core/src/plugin/manager.ts

298 lines
8.6 KiB
TypeScript
Raw Normal View History

2020-11-21 15:41:08 +00:00
import * as path from 'path';
2020-11-28 13:34:34 +00:00
import { IEnvironment, Service } from '../types';
2020-11-21 15:41:08 +00:00
import { IPlugin, IPluginManifest, Plugin } from './plugin';
2020-11-28 13:34:34 +00:00
import { PluginConfiguration } from '../types';
2020-11-21 15:41:08 +00:00
import { PluginConfigurator } from './config';
import { ScopedEventEmitter } from '../util/events';
import { NPMExecutor } from '../npm/executor';
import { logger } from '../core/logger';
export function requireNoCache(file: string): object | null {
const fullPath = path.resolve(file);
const mod = require(fullPath);
if (require.cache && require.cache[fullPath]) {
delete require.cache[fullPath];
}
return mod;
}
export class PluginManager {
private plugins: Map<string, IPlugin> = new Map();
private configs: PluginConfigurator = new PluginConfigurator(this.environment);
constructor(
2020-11-28 19:08:23 +00:00
public availablePlugins: IPluginManifest[],
2020-11-21 15:41:08 +00:00
private stream: ScopedEventEmitter,
private environment: IEnvironment,
private npm: NPMExecutor) {
this.addEvents();
}
public getAvailableByName(name: string): IPluginManifest | null {
for (const pl of this.availablePlugins) {
if (pl.name === name) {
return pl;
}
}
return null;
}
public getLoadedByName(name: string): IPlugin | null {
if (this.plugins.has(name)) {
return this.plugins.get(name) as IPlugin;
}
return null;
}
2020-11-28 19:08:23 +00:00
public getLoaded(): IPlugin[] {
const list = []
for (const pl of this.plugins.values()) {
list.push(pl);
}
return list;
}
2020-11-21 15:41:08 +00:00
public addAvailable(manifest: IPluginManifest | IPluginManifest[]): boolean {
// Automatically add arrays of manifests
if (Array.isArray(manifest)) {
let returnValue = true;
for (const mf of manifest) {
if (!this.addAvailable(mf)) {
returnValue = false;
}
}
return returnValue;
}
if (this.getAvailableByName(manifest.name)) {
return false;
}
this.availablePlugins.push(manifest);
return true;
}
public removeAvailable(plugin: IPluginManifest | IPluginManifest[] | string | string[]): boolean {
let returnValue = false;
if (Array.isArray(plugin)) {
returnValue = true;
for (const mf of plugin) {
if (!this.removeAvailable(mf)) {
returnValue = false;
}
}
return returnValue;
}
// By name
if (typeof plugin === 'string') {
const p = this.getAvailableByName(plugin);
if (!p) {
return false;
}
plugin = p;
}
const result: IPluginManifest[] = [];
for (const mf of this.availablePlugins) {
if (mf === plugin) {
returnValue = true;
this.stream.emit('pluginUnload', mf);
continue;
}
result.push(mf);
}
this.availablePlugins = result;
return returnValue;
}
public async load(plugin: IPluginManifest): Promise<IPlugin> {
2020-11-28 13:34:34 +00:00
// Don't load plugins twice
const ready = this.getLoadedByName(plugin.name);
if (ready) {
return ready;
}
2020-11-21 15:41:08 +00:00
// Check dependencies
const requires = [];
logger.debug('Loading plugin', plugin.name);
for (const dep of plugin.dependencies) {
if (dep === plugin.name) {
throw new Error(`Plugin "${plugin.name}" cannot depend on itself.`);
}
const existing = this.getLoadedByName(dep);
if (!existing) {
const available = this.getAvailableByName(dep);
if (!available) {
throw new Error(`Plugin dependency "${dep}" resolution failed for "${plugin.name}"`);
}
requires.push(available);
}
}
// Load dependencies
logger.debug('Loading plugin %s dependencies', plugin.name);
for (const manifest of requires) {
try {
await this.load(manifest);
} catch (e) {
2020-11-28 13:34:34 +00:00
logger.error(e.stack);
throw new Error(`Plugin dependency "${manifest.name}" loading failed for "${plugin.name}"`);
2020-11-21 15:41:08 +00:00
}
}
// Load npm modules
logger.debug('Loading plugin %s npm modules', plugin.name);
for (const depm of plugin.npmDependencies) {
try {
await this.npm.installPackage(depm);
} catch (e) {
2020-11-28 13:34:34 +00:00
logger.error(e.stack);
throw new Error(`Plugin dependency "${depm}" installation failed for "${plugin.name}"`);
2020-11-21 15:41:08 +00:00
}
}
// Load the configuration
const config: PluginConfiguration = await this.configs.loadConfig(plugin);
2020-11-28 19:08:23 +00:00
// Ensure plugin has a full path
if (!plugin.fullPath) {
plugin.fullPath = path.join(this.environment.pluginsPath, plugin.name);
}
2020-11-21 15:41:08 +00:00
// Load the module
logger.debug('Loading plugin %s module', plugin.name);
const PluginModule = requireNoCache(path.resolve(plugin.fullPath, plugin.main)) as any;
if (!PluginModule) {
throw new Error(`Plugin "${plugin.name}" loading failed.`);
}
2020-11-28 13:34:34 +00:00
// Find default configuration, if it's configured, load the configuration
if (PluginModule.prototype.__defconf && config) {
config.setDefaults(PluginModule.prototype.__defconf);
await config.load();
}
2020-11-21 15:41:08 +00:00
// Construct an instance of the module
logger.debug('Instancing plugin %s', plugin.name);
const loaded = new PluginModule(plugin, this.stream, config);
try {
2020-11-28 13:34:34 +00:00
// Give the plugin a service
if (PluginModule.prototype.__service) {
loaded.service = new Service(PluginModule.prototype.__service);
}
2020-11-21 15:41:08 +00:00
// Call the initializer
if (loaded.initialize) {
loaded.initialize.call(loaded);
}
// Call methods that are supposed to be executed automatically on load.
// This is really nasty and probably shouldn't be done, but I don't care!
for (const name of Object.getOwnPropertyNames(PluginModule.prototype)) {
// Prevent double initialization
if (name === 'initialize') {
continue;
}
if (PluginModule.prototype[name] &&
PluginModule.prototype[name].prototype &&
PluginModule.prototype[name].prototype.__autoexec) {
loaded[name].call(loaded);
}
}
} catch (e) {
2020-11-28 13:34:34 +00:00
logger.error(e.stack);
throw new Error(`Plugin "${plugin.name}" initialization failed.`);
2020-11-21 15:41:08 +00:00
}
this.plugins.set(plugin.name, loaded);
this.stream.emit('pluginLoaded', loaded);
// Inform the new plugin that it's dependencies are available
for (const depn of plugin.dependencies) {
this.stream.emitTo(plugin.name, 'pluginLoaded', this.plugins.get(depn));
}
return loaded;
}
private addEvents(): void {
this.stream.on('core', 'pluginLoad', (mf: IPluginManifest | string) => {
if (typeof mf === 'string') {
const manifest = this.getAvailableByName(mf);
if (manifest) {
return this.load(manifest).catch((e) => logger.error(e.stack));
}
}
});
this.stream.on('core', 'pluginUnloaded', (mf: IPlugin | string) => {
if (typeof mf !== 'string') {
2020-11-28 13:34:34 +00:00
if (mf.manifest && mf.service != null) {
mf.service.die();
}
2020-11-21 15:41:08 +00:00
mf = mf.manifest.name;
2020-11-28 13:34:34 +00:00
} else {
const st = this.getLoadedByName(mf);
if (st && st.manifest && st.service != null) {
st.service.die();
}
2020-11-21 15:41:08 +00:00
}
2020-11-28 19:08:23 +00:00
logger.debug('%s has unloaded.', mf);
2020-11-21 15:41:08 +00:00
// Delete plugin from the list of loaded plugins
this.plugins.delete(mf);
// Remove all listeners created by the plugin
this.stream.removeName(mf);
});
this.stream.on('core', 'pluginKill', (mf: IPlugin | string) => {
const pluginName = (typeof mf === 'string' ? mf : mf.manifest.name);
logger.debug('Killing plugin %s', pluginName);
this.stream.emitTo(pluginName, 'pluginUnload', pluginName);
this.stream.emit('pluginUnloaded', mf);
});
this.stream.on('core', 'shutdown', (state: number) => {
// When the shutdown is initiated, this state will be zero.
// We will be re-emitting this event with a higher state when
// all the plugins have finished shutting down.
if (state !== 0) {
return;
}
logger.debug('Shutdown has been received by plugin manager');
// Shutting down all the plugins
for (const [name, plugin] of this.plugins) {
this.stream.emitTo(name, 'pluginUnload', name);
}
// Every second check for plugins
let testCount = 0;
const testInterval = setInterval(() => {
// There's still plugins loaded..
if (this.plugins.size > 0 && testCount < 5) {
testCount++;
return;
}
// Shut down when there are no more plugins active or
// after 5 seconds we just force shutdown
clearInterval(testInterval);
this.stream.emitTo('core', 'shutdown', 1);
}, 1000);
});
}
}