core/src/plugin/manager.ts

353 lines
10 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';
2021-03-23 09:11:41 +00:00
import { IPlugin, IPluginManifest } from './plugin';
2020-11-21 15:41:08 +00:00
2020-11-28 13:34:34 +00:00
import { PluginConfiguration } from '../types';
2020-11-21 15:41:08 +00:00
import { PluginConfigurator } from './config';
2021-03-23 09:11:41 +00:00
import { ScopedEventEmitter, requireNoCache } from '../util';
2020-11-21 15:41:08 +00:00
import { NPMExecutor } from '../npm/executor';
import { logger } from '../core/logger';
export class PluginManager {
private plugins: Map<string, IPlugin> = new Map();
private configs: PluginConfigurator = new PluginConfigurator(this.environment);
private restartQueue: Map<string, IPluginManifest> = new Map();
private stopping = false;
2020-11-21 15:41:08 +00:00
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();
}
2021-02-13 12:24:50 +00:00
public getAvailableByName(name: string): IPluginManifest | undefined {
return this.availablePlugins.find(p => p.name === name);
2020-11-21 15:41:08 +00:00
}
2021-02-13 12:24:50 +00:00
public getLoadedByName(name: string): IPlugin | undefined {
2020-11-21 15:41:08 +00:00
if (this.plugins.has(name)) {
return this.plugins.get(name) as IPlugin;
}
2021-02-13 12:24:50 +00:00
return;
2020-11-21 15:41:08 +00:00
}
2020-11-28 19:08:23 +00:00
public getLoaded(): IPlugin[] {
2021-02-13 12:24:50 +00:00
return Array.from(this.plugins.values());
2020-11-28 19:08:23 +00:00
}
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;
}
2021-03-23 09:11:41 +00:00
// Replace the manifest
2020-11-21 15:41:08 +00:00
if (this.getAvailableByName(manifest.name)) {
2021-03-23 09:11:41 +00:00
this.removeAvailable(manifest, false);
this.availablePlugins.push(manifest);
return true;
2020-11-21 15:41:08 +00:00
}
if (!(/^[a-zA-Z0-9_\-]+$/.test(manifest.name))) {
throw new Error('Illegal name for a plugin!');
}
2020-11-21 15:41:08 +00:00
this.availablePlugins.push(manifest);
return true;
}
2021-03-23 09:11:41 +00:00
public removeAvailable(
plugin: IPluginManifest | IPluginManifest[] | string | string[],
unload = true
): boolean {
2020-11-21 15:41:08 +00:00
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) {
2021-09-18 22:18:33 +00:00
if (mf.name === plugin.name) {
2020-11-21 15:41:08 +00:00
returnValue = true;
2021-03-23 09:11:41 +00:00
if (unload) {
this.stream.emit('pluginUnload', mf);
}
2020-11-21 15:41:08 +00:00
continue;
}
result.push(mf);
}
this.availablePlugins = result;
return returnValue;
}
public async load(plugin: IPluginManifest): Promise<IPlugin> {
// Ignore loading when we're shutting down
if (this.stopping) {
throw new Error('Squeebot is shutting down');
}
2020-11-28 13:34:34 +00:00
// Don't load plugins twice
const ready = this.getLoadedByName(plugin.name);
if (ready) {
return ready;
}
// Dependencies required to load
2020-11-21 15:41:08 +00:00
const requires = [];
// Dependencies available
const available = [];
2020-11-21 15:41:08 +00:00
logger.debug('Loading plugin', plugin.name);
// Check dependencies
for (let dep of plugin.dependencies) {
let optional = false;
if (dep.indexOf('?') !== -1) {
dep = dep.replace('?', '');
optional = true;
}
2020-11-21 15:41:08 +00:00
if (dep === plugin.name) {
throw new Error(`Plugin "${plugin.name}" cannot depend on itself.`);
}
const existing = this.getLoadedByName(dep);
if (existing) {
available.push(existing.manifest);
continue;
}
const isLoaded = this.getAvailableByName(dep);
if (!isLoaded) {
if (optional) {
continue;
2020-11-21 15:41:08 +00:00
}
throw new Error(`Plugin dependency "${dep}" resolution failed for "${plugin.name}"`);
2020-11-21 15:41:08 +00:00
}
requires.push(isLoaded);
2020-11-21 15:41:08 +00:00
}
// Load dependencies
logger.debug('Loading plugin %s dependencies', plugin.name);
for (const manifest of requires) {
try {
await this.load(manifest);
available.push(manifest);
2021-09-03 17:23:22 +00:00
} catch (e: any) {
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);
2021-09-03 17:23:22 +00:00
} catch (e: any) {
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);
}
}
2021-09-03 17:23:22 +00:00
} catch (e: any) {
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 available) {
this.stream.emitTo(plugin.name, 'pluginLoaded', this.plugins.get(depn.name));
2020-11-21 15:41:08 +00:00
}
return loaded;
}
public async restart(mf: IPluginManifest | IPlugin | string): Promise<void> {
let manifest;
if (typeof mf === 'string') {
manifest = this.getAvailableByName(mf);
} else if ('manifest' in mf) {
manifest = mf.manifest;
} else {
manifest = mf;
}
if (!manifest) {
throw new Error('Plugin not found');
}
if (!this.getLoadedByName(manifest.name)) {
this.load(manifest);
return;
}
this.restartQueue.set(manifest.name, manifest);
this.stream.emitTo(manifest.name, 'pluginUnload', manifest.name);
}
2020-11-21 15:41:08 +00:00
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);
// Restart, if applicable
if (this.restartQueue.has(mf) && !this.stopping) {
const manifest = this.restartQueue.get(mf) as IPluginManifest;
this.restartQueue.delete(mf);
this.load(manifest).catch(e => console.error(e));
}
2020-11-21 15:41:08 +00:00
});
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;
}
// Prevent loading of new plugins
this.stopping = true;
2020-11-21 15:41:08 +00:00
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);
});
}
}