yqlrun.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #include <yql/tools/yqlrun/lib/yqlrun_lib.h>
  2. #include <yql/tools/yqlrun/http/yql_server.h>
  3. #include <yql/essentials/providers/common/udf_resolve/yql_outproc_udf_resolver.h>
  4. #include <yql/essentials/providers/common/udf_resolve/yql_simple_udf_resolver.h>
  5. #include <yql/essentials/providers/common/udf_resolve/yql_udf_resolver_with_index.h>
  6. #include <yql/essentials/providers/common/provider/yql_provider_names.h>
  7. #include <yql/essentials/minikql/mkql_function_registry.h>
  8. #include <yql/essentials/minikql/invoke_builtins/mkql_builtins.h>
  9. #include <yql/essentials/utils/backtrace/backtrace.h>
  10. #include <yql/essentials/utils/log/tls_backend.h>
  11. #include <yql/essentials/utils/log/log.h>
  12. #include <yql/essentials/parser/pg_wrapper/interface/parser.h>
  13. #include <yql/essentials/parser/pg_catalog/catalog.h>
  14. #include <yql/essentials/protos/pg_ext.pb.h>
  15. #include <yql/essentials/core/file_storage/file_storage.h>
  16. #include <yql/essentials/core/file_storage/proto/file_storage.pb.h>
  17. #include <yql/essentials/core/services/mounts/yql_mounts.h>
  18. #include <yql/essentials/core/facade/yql_facade.h>
  19. #include <yql/essentials/core/pg_ext/yql_pg_ext.h>
  20. #include <yql/essentials/core/yql_udf_resolver.h>
  21. #include <yql/essentials/core/yql_udf_index.h>
  22. #include <yql/essentials/core/yql_library_compiler.h>
  23. #include <yql/essentials/ast/yql_expr.h>
  24. #include <library/cpp/getopt/last_getopt.h>
  25. #include <library/cpp/logger/stream.h>
  26. #include <google/protobuf/text_format.h>
  27. #include <util/generic/string.h>
  28. #include <util/generic/vector.h>
  29. #include <util/generic/hash.h>
  30. #include <util/datetime/base.h>
  31. using namespace NYql;
  32. using namespace NKikimr::NMiniKQL;
  33. using namespace NYql::NHttp;
  34. namespace NMiniKQL = NKikimr::NMiniKQL;
  35. class TStoreMappingFunctor: public NLastGetopt::IOptHandler {
  36. public:
  37. TStoreMappingFunctor(THashMap<TString, TString>* target, char delim = '@')
  38. : Target(target)
  39. , Delim(delim)
  40. {
  41. }
  42. void HandleOpt(const NLastGetopt::TOptsParser* parser) final {
  43. const TStringBuf val(parser->CurValOrDef());
  44. const auto service = TString(val.After(Delim));
  45. auto res = Target->emplace(TString(val.Before(Delim)), service);
  46. if (!res.second) {
  47. /// force replace already exist parametr
  48. res.first->second = service;
  49. }
  50. }
  51. private:
  52. THashMap<TString, TString>* Target;
  53. char Delim;
  54. };
  55. void CommonInit(const NLastGetopt::TOptsParseResult& res, const TString& udfResolverPath, bool filterSysCalls,
  56. const TVector<TString>& udfsPaths, TFileStoragePtr fileStorage,
  57. IUdfResolver::TPtr& udfResolver, IFunctionRegistry::TPtr funcRegistry, TUdfIndex::TPtr& udfIndex) {
  58. if (fileStorage && res.Has("scan-udfs")) {
  59. if (!udfResolverPath) {
  60. ythrow yexception() << "udf-resolver path must be specified when use 'scan-udfs'";
  61. }
  62. udfResolver = NCommon::CreateOutProcUdfResolver(funcRegistry.Get(), fileStorage, udfResolverPath, {}, {}, filterSysCalls, {});
  63. Cerr << TInstant::Now().ToStringLocalUpToSeconds() << " Udf scanning started for " << udfsPaths.size() << " udfs ..." << Endl;
  64. udfIndex = new TUdfIndex();
  65. LoadRichMetadataToUdfIndex(*udfResolver, udfsPaths, false, TUdfIndex::EOverrideMode::RaiseError, *udfIndex);
  66. Cerr << TInstant::Now().ToStringLocalUpToSeconds() << " UdfIndex done." << Endl;
  67. udfResolver = NCommon::CreateUdfResolverWithIndex(udfIndex, udfResolver, fileStorage);
  68. Cerr << TInstant::Now().ToStringLocalUpToSeconds() << " Udfs scanned" << Endl;
  69. return;
  70. }
  71. udfResolver = fileStorage && udfResolverPath
  72. ? NCommon::CreateOutProcUdfResolver(funcRegistry.Get(), fileStorage, udfResolverPath, {}, {}, false, {})
  73. : NCommon::CreateSimpleUdfResolver(funcRegistry.Get(), fileStorage, true);
  74. }
  75. template <typename TMessage>
  76. THolder<TMessage> ParseProtoConfig(const TString& cfgFile) {
  77. auto config = MakeHolder<TMessage>();
  78. TString configData = TFileInput(cfgFile).ReadAll();;
  79. using ::google::protobuf::TextFormat;
  80. if (!TextFormat::ParseFromString(configData, config.Get())) {
  81. Cerr << "Bad format of gateways configuration";
  82. return {};
  83. }
  84. return config;
  85. }
  86. int RunUI(int argc, const char* argv[])
  87. {
  88. Cerr << "yqlrun ABI version: " << NKikimr::NUdf::CurrentAbiVersionStr() << Endl;
  89. NYql::NBacktrace::RegisterKikimrFatalActions();
  90. NYql::NBacktrace::EnableKikimrSymbolize();
  91. TVector<TString> udfsPaths;
  92. TString udfsDir;
  93. TString mountConfig;
  94. TVector<TString> filesMappingList;
  95. TString udfResolverPath;
  96. bool udfResolverFilterSyscalls = false;
  97. TString gatewaysCfgFile;
  98. TString fsCfgFile;
  99. TString pgExtConfig;
  100. THashMap<TString, TString> clusterMapping;
  101. clusterMapping["plato"] = YtProviderName;
  102. THashSet<TString> sqlFlags;
  103. NLastGetopt::TOpts opts = NLastGetopt::TOpts::Default();
  104. opts.AddLongOption('u', "udf", "Load shared library with UDF by given path").AppendTo(&udfsPaths);
  105. opts.AddLongOption("udfs-dir", "Load all shared libraries with UDFs found in given directory").StoreResult(&udfsDir);
  106. opts.AddLongOption('m', "mounts", "Mount points config file.").StoreResult(&mountConfig);
  107. opts.AddLongOption('f', "file", "name@path").AppendTo(&filesMappingList);
  108. opts.AddLongOption("udf-resolver", "Path to udf-resolver").Optional().RequiredArgument("PATH").StoreResult(&udfResolverPath);
  109. opts.AddLongOption("udf-resolver-filter-syscalls", "Filter syscalls in udf resolver")
  110. .Optional()
  111. .NoArgument()
  112. .SetFlag(&udfResolverFilterSyscalls);
  113. opts.AddLongOption("scan-udfs", "Scan specified udfs with external udf resolver to use static function registry").NoArgument();
  114. opts.AddLongOption('C', "cluster", "set cluster to service mapping").RequiredArgument("name@service").Handler(new TStoreMappingFunctor(&clusterMapping));
  115. opts.AddLongOption("gateways-cfg", "gateways configuration file").Optional().RequiredArgument("FILE").StoreResult(&gatewaysCfgFile);
  116. opts.AddLongOption("fs-cfg", "fs configuration file").Optional().RequiredArgument("FILE").StoreResult(&fsCfgFile);
  117. opts.AddLongOption("pg-ext", "pg extensions config file").StoreResult(&pgExtConfig);
  118. opts.AddLongOption("sql-flags", "SQL translator pragma flags").SplitHandler(&sqlFlags, ',');
  119. TServerConfig config;
  120. config.SetAssetsPath("http/www");
  121. config.InitCliOptions(opts);
  122. NLastGetopt::TOptsParseResult res(&opts, argc, argv);
  123. config.ParseFromCli(res);
  124. TUserDataTable userData;
  125. for (auto& s : filesMappingList) {
  126. TStringBuf fileName, filePath;
  127. TStringBuf(s).Split('@', fileName, filePath);
  128. if (fileName.empty() || filePath.empty()) {
  129. Cerr << "Incorrect file mapping, expected form name@path, e.g. MyFile@file.txt" << Endl;
  130. return 1;
  131. }
  132. auto& file = userData[TUserDataKey::File(GetDefaultFilePrefix() + fileName)];
  133. file.Type = EUserDataType::PATH;
  134. file.Data = filePath;
  135. }
  136. NMiniKQL::FindUdfsInDir(udfsDir, &udfsPaths);
  137. NPg::SetSqlLanguageParser(NSQLTranslationPG::CreateSqlLanguageParser());
  138. NPg::LoadSystemFunctions(*NSQLTranslationPG::CreateSystemFunctionsParser());
  139. if (!pgExtConfig.empty()) {
  140. auto config = ParseProtoConfig<NProto::TPgExtensions>(pgExtConfig);
  141. Y_ABORT_UNLESS(config);
  142. TVector<NPg::TExtensionDesc> extensions;
  143. PgExtensionsFromProto(*config, extensions);
  144. NPg::RegisterExtensions(extensions, false,
  145. *NSQLTranslationPG::CreateExtensionSqlParser(),
  146. NKikimr::NMiniKQL::CreateExtensionLoader().get());
  147. }
  148. NPg::GetSqlLanguageParser()->Freeze();
  149. THolder<TGatewaysConfig> gatewaysConfig;
  150. if (!gatewaysCfgFile.empty()) {
  151. gatewaysConfig = ParseProtoConfig<TGatewaysConfig>(gatewaysCfgFile);
  152. if (!gatewaysConfig) {
  153. return -1;
  154. }
  155. if (gatewaysConfig->HasSqlCore()) {
  156. sqlFlags.insert(gatewaysConfig->GetSqlCore().GetTranslationFlags().begin(), gatewaysConfig->GetSqlCore().GetTranslationFlags().end());
  157. }
  158. }
  159. THolder<TFileStorageConfig> fsConfig;
  160. if (!fsCfgFile.empty()) {
  161. fsConfig = ParseProtoConfig<TFileStorageConfig>(fsCfgFile);
  162. if (!fsConfig) {
  163. return 1;
  164. }
  165. } else {
  166. fsConfig = MakeHolder<TFileStorageConfig>();
  167. }
  168. auto fileStorage = WithAsync(CreateFileStorage(*fsConfig));
  169. IUdfResolver::TPtr udfResolver;
  170. auto funcRegistry = CreateFunctionRegistry(&NYql::NBacktrace::KikimrBackTrace, CreateBuiltinRegistry(), false, udfsPaths);
  171. TUdfIndex::TPtr udfIndex;
  172. CommonInit(res, udfResolverPath, udfResolverFilterSyscalls, udfsPaths, fileStorage, udfResolver, funcRegistry, udfIndex);
  173. TExprContext ctx;
  174. ctx.NextUniqueId = NPg::GetSqlLanguageParser()->GetContext().NextUniqueId;
  175. IModuleResolver::TPtr moduleResolver;
  176. if (!mountConfig.empty()) {
  177. TModulesTable modules;
  178. auto mount = ParseProtoConfig<NYqlMountConfig::TMountConfig>(mountConfig);
  179. Y_ABORT_UNLESS(mount);
  180. FillUserDataTableFromFileSystem(*mount, userData);
  181. if (!CompileLibraries(userData, ctx, modules)) {
  182. Cerr << "Errors on compile libraries:" << Endl;
  183. ctx.IssueManager.GetIssues().PrintTo(Cerr);
  184. return -1;
  185. }
  186. moduleResolver = std::make_shared<TModuleResolver>(std::move(modules), ctx.NextUniqueId, clusterMapping, sqlFlags);
  187. } else {
  188. if (!GetYqlDefaultModuleResolver(ctx, moduleResolver, clusterMapping)) {
  189. Cerr << "Errors loading default YQL libraries:" << Endl;
  190. ctx.IssueManager.GetIssues().PrintTo(Cerr);
  191. return -1;
  192. }
  193. }
  194. TString fn = "pkg/a/b/c.sql";
  195. TString content0 = "$sqr = ($x) -> { return 2 * $x * $x; }; export $sqr;";
  196. TString content1 = "$sqr = ($x) -> { return 3 * $x * $x; }; export $sqr;";
  197. moduleResolver->RegisterPackage("a.b");
  198. if (!moduleResolver->AddFromMemory(fn, content0, ctx, 1, 0) || !moduleResolver->AddFromMemory(fn, content1, ctx, 1, 1)) {
  199. Cerr << "Unable to compile SQL library" << Endl;
  200. ctx.IssueManager.GetIssues().PrintTo(Cerr);
  201. return -1;
  202. }
  203. TExprContext::TFreezeGuard freezeGuard(ctx);
  204. NLog::YqlLoggerScope logger(new NLog::TTlsLogBackend(new TStreamLogBackend(&Cerr)));
  205. NLog::YqlLogger().SetComponentLevel(NLog::EComponent::Core, NLog::ELevel::DEBUG);
  206. NLog::YqlLogger().SetComponentLevel(NLog::EComponent::CoreEval, NLog::ELevel::DEBUG);
  207. NLog::YqlLogger().SetComponentLevel(NLog::EComponent::CorePeepHole, NLog::ELevel::DEBUG);
  208. auto server = CreateYqlServer(config,
  209. funcRegistry.Get(), udfIndex, ctx.NextUniqueId,
  210. userData,
  211. std::move(gatewaysConfig),
  212. sqlFlags,
  213. moduleResolver, udfResolver, fileStorage);
  214. server->Start();
  215. server->Wait();
  216. return 0;
  217. }
  218. int main(int argc, const char *argv[]) {
  219. try {
  220. if (argc > 1 && TString(argv[1]) == TStringBuf("ui")) {
  221. return RunUI(argc, argv);
  222. } else {
  223. return NYql::TYqlRunTool().Main(argc, argv);
  224. }
  225. }
  226. catch (...) {
  227. Cerr << CurrentExceptionMessage() << Endl;
  228. return 1;
  229. }
  230. }