1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
|
#include "mkql_function_registry.h"
#include "mkql_utils.h"
#include "mkql_type_builder.h"
#include <yql/essentials/public/udf/udf_static_registry.h>
#include <util/folder/iterator.h>
#include <util/folder/dirut.h>
#include <util/folder/path.h>
#include <util/system/dynlib.h>
#include <util/stream/str.h>
#include <util/string/builder.h>
#include <util/string/split.h>
namespace {
using namespace NKikimr;
using namespace NMiniKQL;
const char MODULE_NAME_DELIMITER = '.';
const char* RegisterFuncName = "Register";
const char* AbiVersionFuncName = "AbiVersion";
#if defined(_win_) || defined(_darwin_)
const char* BindSymbolsFuncName = "BindSymbols";
#endif
const char* SetBackTraceCallbackName = "SetBackTraceCallback";
//////////////////////////////////////////////////////////////////////////////
// TMutableFunctionRegistry
//////////////////////////////////////////////////////////////////////////////
class TMutableFunctionRegistry: public IMutableFunctionRegistry
{
struct TUdfModule {
TString LibraryPath;
std::shared_ptr<NUdf::IUdfModule> Impl;
};
using TUdfModulesMap = THashMap<TString, TUdfModule>;
struct TUdfLibrary: public TThrRefBase {
ui32 AbiVersion = 0;
TDynamicLibrary Lib;
TUdfLibrary()
{
}
};
using TUdfLibraryPtr = TIntrusivePtr<TUdfLibrary>;
class TUdfModuleLoader: public NUdf::IRegistrator {
public:
TUdfModuleLoader(
TUdfModulesMap& modulesMap,
THashSet<TString>* newModules,
const TString& libraryPath,
const TUdfModuleRemappings& remappings,
ui32 abiVersion,
const TString& customUdfPrefix = {})
: ModulesMap(modulesMap)
, NewModules(newModules)
, LibraryPath(libraryPath)
, Remappings(remappings)
, AbiVersion(NUdf::AbiVersionToStr(abiVersion))
, CustomUdfPrefix(customUdfPrefix)
{
}
void AddModule(
const NUdf::TStringRef& name,
NUdf::TUniquePtr<NUdf::IUdfModule> module) override
{
Y_DEBUG_ABORT_UNLESS(module, "Module is empty");
if (!HasError()) {
TUdfModule m;
m.LibraryPath = LibraryPath;
m.Impl.reset(module.Release());
auto it = Remappings.find(name);
const TString& newName = CustomUdfPrefix
+ ((it == Remappings.end())
? TString(name)
: it->second);
auto i = ModulesMap.insert({ newName, std::move(m) });
if (!i.second) {
TUdfModule* oldModule = ModulesMap.FindPtr(newName);
Y_DEBUG_ABORT_UNLESS(oldModule != nullptr);
Error = (TStringBuilder()
<< "UDF module duplication: name " << TStringBuf(name)
<< ", already loaded from " << oldModule->LibraryPath
<< ", trying to load from " << LibraryPath);
} else if (NewModules) {
NewModules->insert(newName);
}
}
}
const TString& GetError() const { return Error; }
bool HasError() const { return !Error.empty(); }
private:
TUdfModulesMap& ModulesMap;
THashSet<TString>* NewModules;
const TString LibraryPath;
const TUdfModuleRemappings& Remappings;
const TString AbiVersion;
TString Error;
const TString CustomUdfPrefix;
};
public:
TMutableFunctionRegistry(IBuiltinFunctionRegistry::TPtr builtins)
: Builtins_(std::move(builtins))
{
}
TMutableFunctionRegistry(const TMutableFunctionRegistry& rhs)
: Builtins_(rhs.Builtins_)
, LoadedLibraries_(rhs.LoadedLibraries_)
, UdfModules_(rhs.UdfModules_)
, SupportsSizedAllocators_(rhs.SupportsSizedAllocators_)
{
}
~TMutableFunctionRegistry() {
}
void AllowUdfPatch() override {
}
void LoadUdfs(
const TString& libraryPath,
const TUdfModuleRemappings& remmapings,
ui32 flags = 0,
const TString& customUdfPrefix = {},
THashSet<TString>* modules = nullptr) override
{
TUdfLibraryPtr lib;
auto libIt = LoadedLibraries_.find(libraryPath);
if (libIt == LoadedLibraries_.end()) {
lib = MakeIntrusive<TUdfLibrary>();
#ifdef _win32_
ui32 loadFlags = 0;
#else
ui32 loadFlags = RTLD_GLOBAL | ((flags & NUdf::IRegistrator::TFlags::TypesOnly) ? RTLD_LAZY : RTLD_NOW);
#endif
TPathSplit absPathSplit(libraryPath);
TString absPath = libraryPath;
if (!absPathSplit.IsAbsolute) {
absPath = JoinPaths(TFsPath::Cwd().PathSplit(), absPathSplit);
}
lib->Lib.Open(absPath.data(), loadFlags);
lib->Lib.SetUnloadable(false);
// (1) check ABI version
auto abiVersionFunc = reinterpret_cast<NUdf::TAbiVersionFunctionPtr>(
lib->Lib.SymOptional(AbiVersionFuncName));
if (!abiVersionFunc) {
return;
}
ui32 version = abiVersionFunc();
Y_ENSURE(NUdf::IsAbiCompatible(version) && version >= NUdf::MakeAbiVersion(2, 8, 0),
"Non compatible ABI version of UDF library " << libraryPath
<< ", expected up to " << NUdf::AbiVersionToStr(NUdf::CurrentCompatibilityAbiVersion() * 100)
<< ", got " << NUdf::AbiVersionToStr(version)
<< "; try to re-compile library using "
<< "YQL_ABI_VERSION(" << UDF_ABI_VERSION_MAJOR
<< " " << UDF_ABI_VERSION_MINOR << " 0) macro in ya.make");
lib->AbiVersion = version;
if (version < NUdf::MakeAbiVersion(2, 8, 0)) {
SupportsSizedAllocators_ = false;
}
#if defined(_win_) || defined(_darwin_)
auto bindSymbolsFunc = reinterpret_cast<NUdf::TBindSymbolsFunctionPtr>(lib->Lib.Sym(BindSymbolsFuncName));
bindSymbolsFunc(NUdf::GetStaticSymbols());
#endif
if (BackTraceCallback_) {
auto setter = reinterpret_cast<NUdf::TSetBackTraceCallbackPtr>(lib->Lib.SymOptional(SetBackTraceCallbackName));
if (setter) {
setter(BackTraceCallback_);
}
}
libIt = LoadedLibraries_.insert({ libraryPath, lib }).first;
} else {
lib = libIt->second;
}
// (2) ensure that Register() func is present
auto registerFunc = reinterpret_cast<NUdf::TRegisterFunctionPtr>(
lib->Lib.Sym(RegisterFuncName));
// (3) do load
THashSet<TString> newModules;
TUdfModuleLoader loader(
UdfModules_,
&newModules,
libraryPath,
remmapings,
lib->AbiVersion, customUdfPrefix);
registerFunc(loader, flags);
Y_ENSURE(!loader.HasError(), loader.GetError());
if (modules) {
*modules = std::move(newModules);
}
}
void AddModule(
const TStringBuf& libraryPath,
const TStringBuf& moduleName,
NUdf::TUniquePtr<NUdf::IUdfModule> module) override
{
TString libraryPathStr(libraryPath);
auto inserted = LoadedLibraries_.insert({ libraryPathStr, nullptr });
if (!inserted.second) {
return;
}
TUdfModuleRemappings remappings;
TUdfModuleLoader loader(
UdfModules_, nullptr, libraryPathStr,
remappings, NUdf::CurrentAbiVersion());
loader.AddModule(moduleName, std::move(module));
Y_ENSURE(!loader.HasError(), loader.GetError());
}
void SetSystemModulePaths(const TUdfModulePathsMap& paths) override {
SystemModulePaths_ = paths;
}
const IBuiltinFunctionRegistry::TPtr& GetBuiltins() const override {
return Builtins_;
}
TStatus FindFunctionTypeInfo(
const TTypeEnvironment& env,
NUdf::ITypeInfoHelper::TPtr typeInfoHelper,
NUdf::ICountersProvider* countersProvider,
const TStringBuf& name,
TType* userType,
const TStringBuf& typeConfig,
ui32 flags,
const NUdf::TSourcePosition& pos,
const NUdf::ISecureParamsProvider* secureParamsProvider,
TFunctionTypeInfo* funcInfo) const override
{
TStringBuf moduleName, funcName;
if (name.TrySplit(MODULE_NAME_DELIMITER, moduleName, funcName)) {
auto it = UdfModules_.find(moduleName);
if (it != UdfModules_.end()) {
TFunctionTypeInfoBuilder typeInfoBuilder(env, typeInfoHelper, moduleName,
(flags & NUdf::IUdfModule::TFlags::TypesOnly) ? nullptr : countersProvider, pos, secureParamsProvider);
const auto& module = *it->second.Impl;
module.BuildFunctionTypeInfo(
funcName, userType, typeConfig, flags, typeInfoBuilder);
if (typeInfoBuilder.HasError()) {
return TStatus::Error()
<< "Module: " << moduleName
<< ", function: " << funcName
<< ", error: " << typeInfoBuilder.GetError();
}
try {
typeInfoBuilder.Build(funcInfo);
}
catch (yexception& e) {
return TStatus::Error()
<< "Module: " << moduleName
<< ", function: " << funcName
<< ", error: " << e.what();
}
if ((flags & NUdf::IRegistrator::TFlags::TypesOnly) &&
!funcInfo->FunctionType)
{
return TStatus::Error()
<< "Module: " << moduleName
<< ", function: " << funcName
<< ", function not found";
}
if (funcInfo->ModuleIRUniqID) {
funcInfo->ModuleIRUniqID.prepend(moduleName);
}
return TStatus::Ok();
}
return TStatus::Error()
<< "Module " << moduleName << " is not registered";
}
return TStatus::Error()
<< "Function name must be in <module>.<func_name> scheme. "
<< "But get " << name;
}
TMaybe<TString> FindUdfPath(const TStringBuf& moduleName) const override {
if (const TUdfModule* udf = UdfModules_.FindPtr(moduleName)) {
return udf->LibraryPath;
}
if (const TString* path = SystemModulePaths_.FindPtr(moduleName)) {
return *path;
}
return Nothing();
}
bool IsLoadedUdfModule(const TStringBuf& moduleName) const override {
return UdfModules_.contains(moduleName);
}
THashSet<TString> GetAllModuleNames() const override {
THashSet<TString> names;
names.reserve(UdfModules_.size());
for (const auto& module: UdfModules_) {
names.insert(module.first);
}
return names;
}
TFunctionsMap GetModuleFunctions(const TStringBuf& moduleName) const override {
struct TFunctionNamesSink: public NUdf::IFunctionNamesSink {
TFunctionsMap Functions;
class TFuncDescriptor : public NUdf::IFunctionDescriptor {
public:
TFuncDescriptor(TFunctionProperties& properties)
: Properties(properties)
{}
private:
void SetTypeAwareness() final {
Properties.IsTypeAwareness = true;
}
TFunctionProperties& Properties;
};
NUdf::IFunctionDescriptor::TPtr Add(const NUdf::TStringRef& name) final {
const auto it = Functions.emplace(name, TFunctionProperties{});
return new TFuncDescriptor(it.first->second);
}
} sink;
const auto it = UdfModules_.find(moduleName);
if (UdfModules_.cend() == it)
return TFunctionsMap();
it->second.Impl->GetAllFunctions(sink);
return sink.Functions;
}
bool SupportsSizedAllocators() const override {
return SupportsSizedAllocators_;
}
void PrintInfoTo(IOutputStream& out) const override {
Builtins_->PrintInfoTo(out);
}
void CleanupModulesOnTerminate() const override {
for (const auto& module : UdfModules_) {
module.second.Impl->CleanupOnTerminate();
}
}
TIntrusivePtr<IMutableFunctionRegistry> Clone() const override {
return new TMutableFunctionRegistry(*this);
}
void SetBackTraceCallback(NUdf::TBackTraceCallback callback) override {
BackTraceCallback_ = callback;
}
private:
const IBuiltinFunctionRegistry::TPtr Builtins_;
THashMap<TString, TUdfLibraryPtr> LoadedLibraries_;
TUdfModulesMap UdfModules_;
THolder<TMemoryUsageInfo> UdfMemoryInfo_;
TUdfModulePathsMap SystemModulePaths_;
NUdf::TBackTraceCallback BackTraceCallback_ = nullptr;
bool SupportsSizedAllocators_ = true;
};
//////////////////////////////////////////////////////////////////////////////
// TBuiltinsWrapper
//////////////////////////////////////////////////////////////////////////////
class TBuiltinsWrapper: public IFunctionRegistry
{
public:
TBuiltinsWrapper(IBuiltinFunctionRegistry::TPtr&& builtins)
: Builtins_(std::move(builtins))
{
}
const IBuiltinFunctionRegistry::TPtr& GetBuiltins() const override {
return Builtins_;
}
void AllowUdfPatch() override {
}
TStatus FindFunctionTypeInfo(
const TTypeEnvironment& env,
NUdf::ITypeInfoHelper::TPtr typeInfoHelper,
NUdf::ICountersProvider* countersProvider,
const TStringBuf& name,
TType* userType,
const TStringBuf& typeConfig,
ui32 flags,
const NUdf::TSourcePosition& pos,
const NUdf::ISecureParamsProvider* secureParamsProvider,
TFunctionTypeInfo* funcInfo) const override
{
Y_UNUSED(env);
Y_UNUSED(typeInfoHelper);
Y_UNUSED(countersProvider);
Y_UNUSED(name);
Y_UNUSED(userType);
Y_UNUSED(typeConfig);
Y_UNUSED(flags);
Y_UNUSED(pos);
Y_UNUSED(secureParamsProvider);
Y_UNUSED(funcInfo);
return TStatus::Error(TStringBuf("Unsupported access to builtins registry"));
}
TMaybe<TString> FindUdfPath(
const TStringBuf& /* moduleName */) const override
{
return{};
}
bool IsLoadedUdfModule(const TStringBuf& /* moduleName */) const override {
return false;
}
THashSet<TString> GetAllModuleNames() const override {
return {};
}
TFunctionsMap GetModuleFunctions(const TStringBuf&) const override {
return TFunctionsMap();
}
bool SupportsSizedAllocators() const override {
return true;
}
void PrintInfoTo(IOutputStream& out) const override {
Builtins_->PrintInfoTo(out);
}
void CleanupModulesOnTerminate() const override {
}
TIntrusivePtr<IMutableFunctionRegistry> Clone() const override {
return new TMutableFunctionRegistry(Builtins_);
}
private:
const IBuiltinFunctionRegistry::TPtr Builtins_;
};
} // namespace
namespace NKikimr {
namespace NMiniKQL {
void FindUdfsInDir(const TString& dirPath, TVector<TString>* paths)
{
static const TStringBuf libPrefix = TStringBuf(MKQL_UDF_LIB_PREFIX);
static const TStringBuf libSuffix = TStringBuf(MKQL_UDF_LIB_SUFFIX);
if (!dirPath.empty()) {
std::vector<TString> dirs;
StringSplitter(dirPath).Split(';').AddTo(&dirs);
for (auto d : dirs) {
TDirIterator dir(d, TDirIterator::TOptions(FTS_LOGICAL).SetMaxLevel(10));
for (auto file = dir.begin(), end = dir.end(); file != end; ++file) {
// skip entries with empty name, and all non-files
// all valid symlinks are already dereferenced, provided by FTS_LOGICAL
if (file->fts_pathlen == file->fts_namelen || file->fts_info != FTS_F) {
continue;
}
TString path(file->fts_path);
TString fileName = GetBaseName(path);
// skip non shared libraries
if (!fileName.StartsWith(libPrefix) ||
!fileName.EndsWith(libSuffix))
{
continue;
}
// skip test udfs when scanning dir
auto udfName = TStringBuf(fileName).Skip(libPrefix.length());
if (udfName.StartsWith(TStringBuf("test_"))) {
continue;
}
paths->push_back(std::move(path));
}
}
}
}
bool SplitModuleAndFuncName(const TStringBuf& name, TStringBuf& module, TStringBuf& func)
{
return name.TrySplit(MODULE_NAME_DELIMITER, module, func);
}
TString FullName(const TStringBuf& module, const TStringBuf& func)
{
TString fullName;
fullName.reserve(module.size() + func.size() + 1);
fullName.append(module);
fullName.append(MODULE_NAME_DELIMITER);
fullName.append(func);
return fullName;
}
TIntrusivePtr<IFunctionRegistry> CreateFunctionRegistry(IBuiltinFunctionRegistry::TPtr&& builtins)
{
return new TBuiltinsWrapper(std::move(builtins));
}
TIntrusivePtr<IFunctionRegistry> CreateFunctionRegistry(
NKikimr::NUdf::TBackTraceCallback backtraceCallback,
IBuiltinFunctionRegistry::TPtr&& builtins,
bool allowUdfPatch,
const TVector<TString>& udfsPaths,
ui32 flags /* = 0 */)
{
auto registry = MakeHolder<TMutableFunctionRegistry>(std::move(builtins));
if (allowUdfPatch) {
registry->AllowUdfPatch();
}
registry->SetBackTraceCallback(backtraceCallback);
// system UDFs loaded with default names
TUdfModuleRemappings remappings;
THashSet<TString> usedUdfPaths;
for (const TString& udfPath: udfsPaths) {
if (usedUdfPaths.insert(udfPath).second) {
registry->LoadUdfs(udfPath, remappings, flags);
}
}
return registry.Release();
}
void FillStaticModules(IMutableFunctionRegistry& registry) {
for (const auto& wrapper : NUdf::GetStaticUdfModuleWrapperList()) {
auto [name, ptr] = wrapper();
registry.AddModule(TString(StaticModulePrefix) + name, name, std::move(ptr));
}
}
} // namespace NMiniKQL
} // namespace NKiki
|