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