| 1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
| 2 | |
| 3 | import { ChargingStationWorkerData, ChargingStationWorkerMessage, ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker'; |
| 4 | |
| 5 | import Configuration from '../utils/Configuration'; |
| 6 | import { Storage } from '../performance/storage/Storage'; |
| 7 | import { StorageFactory } from '../performance/storage/StorageFactory'; |
| 8 | import { UIServiceUtils } from './ui-websocket-services/UIServiceUtils'; |
| 9 | import UIWebSocketServer from './UIWebSocketServer'; |
| 10 | import Utils from '../utils/Utils'; |
| 11 | import WorkerAbstract from '../worker/WorkerAbstract'; |
| 12 | import WorkerFactory from '../worker/WorkerFactory'; |
| 13 | import chalk from 'chalk'; |
| 14 | import { isMainThread } from 'worker_threads'; |
| 15 | import path from 'path'; |
| 16 | import { version } from '../../package.json'; |
| 17 | |
| 18 | export default class Bootstrap { |
| 19 | private static instance: Bootstrap | null = null; |
| 20 | private workerImplementation: WorkerAbstract | null = null; |
| 21 | private readonly uiWebSocketServer!: UIWebSocketServer; |
| 22 | private readonly storage!: Storage; |
| 23 | private numberOfChargingStations: number; |
| 24 | private readonly version: string = version; |
| 25 | private started: boolean; |
| 26 | private readonly workerScript: string; |
| 27 | |
| 28 | private constructor() { |
| 29 | this.started = false; |
| 30 | this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'ChargingStationWorker.js'); |
| 31 | this.initWorkerImplementation(); |
| 32 | Configuration.getUIWebSocketServer().enabled && (this.uiWebSocketServer = new UIWebSocketServer({ |
| 33 | ...Configuration.getUIWebSocketServer().options, handleProtocols: UIServiceUtils.handleProtocols |
| 34 | })); |
| 35 | Configuration.getPerformanceStorage().enabled && (this.storage = StorageFactory.getStorage( |
| 36 | Configuration.getPerformanceStorage().type, |
| 37 | Configuration.getPerformanceStorage().uri, |
| 38 | this.logPrefix() |
| 39 | )); |
| 40 | Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart()); |
| 41 | } |
| 42 | |
| 43 | public static getInstance(): Bootstrap { |
| 44 | if (!Bootstrap.instance) { |
| 45 | Bootstrap.instance = new Bootstrap(); |
| 46 | } |
| 47 | return Bootstrap.instance; |
| 48 | } |
| 49 | |
| 50 | public async start(): Promise<void> { |
| 51 | if (isMainThread && !this.started) { |
| 52 | try { |
| 53 | this.numberOfChargingStations = 0; |
| 54 | await this.storage?.open(); |
| 55 | await this.workerImplementation.start(); |
| 56 | this.uiWebSocketServer?.start(); |
| 57 | const stationTemplateUrls = Configuration.getStationTemplateUrls(); |
| 58 | // Start ChargingStation object in worker thread |
| 59 | if (stationTemplateUrls) { |
| 60 | for (const stationTemplateUrl of stationTemplateUrls) { |
| 61 | try { |
| 62 | const nbStations = stationTemplateUrl.numberOfStations ?? 0; |
| 63 | for (let index = 1; index <= nbStations; index++) { |
| 64 | const workerData: ChargingStationWorkerData = { |
| 65 | index, |
| 66 | templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationTemplateUrl.file)) |
| 67 | }; |
| 68 | await this.workerImplementation.addElement(workerData); |
| 69 | this.numberOfChargingStations++; |
| 70 | } |
| 71 | } catch (error) { |
| 72 | console.error(chalk.red('Charging station start with template file ' + stationTemplateUrl.file + ' error '), error); |
| 73 | } |
| 74 | } |
| 75 | } else { |
| 76 | console.warn(chalk.yellow('No stationTemplateUrls defined in configuration, exiting')); |
| 77 | } |
| 78 | if (this.numberOfChargingStations === 0) { |
| 79 | console.warn(chalk.yellow('No charging station template enabled in configuration, exiting')); |
| 80 | } else { |
| 81 | console.log(chalk.green(`Charging stations simulator ${this.version} started with ${this.numberOfChargingStations.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${this.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${this.workerImplementation.maxElementsPerWorker ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`)); |
| 82 | } |
| 83 | this.started = true; |
| 84 | } catch (error) { |
| 85 | console.error(chalk.red('Bootstrap start error '), error); |
| 86 | } |
| 87 | } else { |
| 88 | console.error(chalk.red('Cannot start an already started charging stations simulator')); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | public async stop(): Promise<void> { |
| 93 | if (isMainThread && this.started) { |
| 94 | await this.workerImplementation.stop(); |
| 95 | this.uiWebSocketServer?.stop(); |
| 96 | await this.storage?.close(); |
| 97 | } else { |
| 98 | console.error(chalk.red('Trying to stop the charging stations simulator while not started')); |
| 99 | } |
| 100 | this.started = false; |
| 101 | } |
| 102 | |
| 103 | public async restart(): Promise<void> { |
| 104 | await this.stop(); |
| 105 | this.initWorkerImplementation(); |
| 106 | await this.start(); |
| 107 | } |
| 108 | |
| 109 | private initWorkerImplementation(): void { |
| 110 | this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(), |
| 111 | { |
| 112 | startDelay: Configuration.getWorkerStartDelay(), |
| 113 | poolMaxSize: Configuration.getWorkerPoolMaxSize(), |
| 114 | poolMinSize: Configuration.getWorkerPoolMinSize(), |
| 115 | elementsPerWorker: Configuration.getChargingStationsPerWorker(), |
| 116 | poolOptions: { |
| 117 | workerChoiceStrategy: Configuration.getWorkerPoolStrategy() |
| 118 | }, |
| 119 | messageHandler: async (msg: ChargingStationWorkerMessage) => { |
| 120 | if (msg.id === ChargingStationWorkerMessageEvents.STARTED) { |
| 121 | this.uiWebSocketServer.chargingStations.add(msg.data.id); |
| 122 | } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) { |
| 123 | this.uiWebSocketServer.chargingStations.delete(msg.data.id); |
| 124 | } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) { |
| 125 | await this.storage.storePerformanceStatistics(msg.data); |
| 126 | } |
| 127 | } |
| 128 | }); |
| 129 | } |
| 130 | |
| 131 | private logPrefix(): string { |
| 132 | return Utils.logPrefix(' Bootstrap |'); |
| 133 | } |
| 134 | } |