import * as path from 'path'; import { IEnvironment } from '../types/environment'; import { IPlugin, IPluginManifest, Plugin } from './plugin'; import { PluginConfiguration } from '../types/plugin-config'; 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 = new Map(); private configs: PluginConfigurator = new PluginConfigurator(this.environment); constructor( private availablePlugins: IPluginManifest[], 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; } 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 removeRepository(repo: string): boolean { const list: IPluginManifest[] = []; for (const mf of this.availablePlugins) { if (mf.repository && mf.repository === repo) { list.push(mf); } } return this.removeAvailable(list); } public async load(plugin: IPluginManifest): Promise { // 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) { throw new Error(`Plugin dependency "${manifest.name}" loading failed for "${plugin.name}": ${e.stack}`); } } // 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) { throw new Error(`Plugin dependency "${depm}" installation failed for "${plugin.name}": ${e.stack}`); } } // Load the configuration const config: PluginConfiguration = await this.configs.loadConfig(plugin); // 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.`); } // Construct an instance of the module logger.debug('Instancing plugin %s', plugin.name); const loaded = new PluginModule(plugin, this.stream, config); try { // 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) { throw new Error(`Plugin "${plugin.name}" initialization failed: ${e.stack}`); } 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') { mf = mf.manifest.name; } // 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); }); } }