This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathplugin-loader.ts
193 lines (181 loc) · 5.49 KB
/
plugin-loader.ts
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
/**
* Copyright 2018, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
Logger,
Plugin,
PluginConfig,
PluginNames,
Stats,
TracerBase,
} from '@opencensus/core';
import * as fs from 'fs';
import * as path from 'path';
import * as hook from 'require-in-the-middle';
import { Constants } from '../constants';
enum HookState {
UNINITIALIZED,
ENABLED,
DISABLED,
}
/**
* The PluginLoader class can load instrumentation plugins that
* use a patch mechanism to enable automatic tracing for
* specific target modules.
*/
export class PluginLoader {
/** The tracer */
private tracer: TracerBase;
/** logger */
private logger: Logger;
/** The stats */
private stats?: Stats;
/** A list of loaded plugins. */
plugins: Plugin[] = [];
/**
* A field that tracks whether the r-i-t-m hook has been loaded for the
* first time, as well as whether the hook body is enabled or not.
*/
private hookState = HookState.UNINITIALIZED;
/**
* Constructs a new PluginLoader instance.
* @param tracer The tracer.
*/
constructor(logger: Logger, tracer: TracerBase, stats?: Stats) {
this.tracer = tracer;
this.logger = logger;
this.stats = stats;
}
/**
* Gets the default package name for a target module. The default package
* name uses the default scope and a default prefix.
* @param moduleName The module name.
* @returns The default name for that package.
*/
private static defaultPackageName(moduleName: string): string {
return `${Constants.OPENCENSUS_SCOPE}/${
Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX
}-${moduleName}`;
}
/**
* Returns a PluginNames object, build from a string array of target modules
* names, using the defaultPackageName.
* @param modulesToPatch A list of modules to patch.
* @returns Plugin names.
*/
static defaultPluginsFromArray(modulesToPatch: string[]): PluginNames {
const plugins = modulesToPatch.reduce(
(plugins: PluginNames, moduleName: string) => {
plugins[moduleName] = PluginLoader.defaultPackageName(moduleName);
return plugins;
},
{} as PluginNames
);
return plugins;
}
/**
* Gets the package version.
* @param name Name.
* @param basedir The base directory.
*/
private getPackageVersion(name: string, basedir: string) {
let version = null;
if (basedir) {
const pkgJson = path.join(basedir, 'package.json');
try {
version = JSON.parse(fs.readFileSync(pkgJson).toString()).version;
} catch (e) {
this.logger.error(
'could not get version of %s module: %s',
name,
e.message
);
}
} else {
version = process.versions.node;
}
return version;
}
/**
* Loads a list of plugins (using a map of the target module name
* and its instrumentation plugin package name). Each plugin module
* should implement the core Plugin interface and export an instance
* named as "plugin". This function will attach a hook to be called
* the first time the module is loaded.
* @param pluginList A list of plugins.
*/
loadPlugins(pluginList: PluginNames) {
if (this.hookState === HookState.UNINITIALIZED) {
hook(Object.keys(pluginList), (exports, name, basedir) => {
if (this.hookState !== HookState.ENABLED) {
return exports;
}
const plugin = pluginList[name];
const version = this.getPackageVersion(name, basedir as string);
this.logger.info('trying loading %s.%s', name, version);
if (!version) {
return exports;
}
this.logger.debug('applying patch to %s@%s module', name, version);
let moduleName;
let moduleConfig: PluginConfig = {};
if (typeof plugin === 'string') {
moduleName = plugin;
} else {
moduleConfig = plugin.config;
moduleName = plugin.module;
}
this.logger.debug('using package %s to patch %s', moduleName, name);
// Expecting a plugin from module;
try {
const plugin: Plugin = require(moduleName as string).plugin;
this.plugins.push(plugin);
return plugin.enable(
exports,
this.tracer,
version,
moduleConfig,
basedir,
this.stats
);
} catch (e) {
this.logger.error(
'could not load plugin %s of module %s. Error: %s',
moduleName,
name,
e.message
);
return exports;
}
});
}
this.hookState = HookState.ENABLED;
}
/** Unloads plugins. */
unloadPlugins() {
for (const plugin of this.plugins) {
plugin.disable();
}
this.plugins = [];
this.hookState = HookState.DISABLED;
}
/**
* Adds a search path for plugin modules. Intended for testing purposes only.
* @param searchPath The path to add.
*/
static set searchPathForTest(searchPath: string) {
module.paths.push(searchPath);
}
}