Commit | Line | Data |
---|---|---|
edd13439 | 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
b4d34251 | 2 | |
f130b8e6 | 3 | import { EventEmitter } from 'node:events'; |
d972af76 | 4 | import { dirname, extname, join } from 'node:path'; |
36adaf06 | 5 | import process, { exit } from 'node:process'; |
130783a7 | 6 | import { fileURLToPath } from 'node:url'; |
8114d10e JB |
7 | |
8 | import chalk from 'chalk'; | |
8603c1ca | 9 | import { availableParallelism } from 'poolifier'; |
8114d10e | 10 | |
08b58f00 | 11 | import { waitChargingStationEvents } from './Helpers'; |
4c3c0d59 JB |
12 | import type { AbstractUIServer } from './ui-server/AbstractUIServer'; |
13 | import { UIServerFactory } from './ui-server/UIServerFactory'; | |
44ebef4c | 14 | import { version } from '../../package.json'; |
268a74bb | 15 | import { BaseError } from '../exception'; |
17bc43d7 | 16 | import { type Storage, StorageFactory } from '../performance'; |
e7aeea18 | 17 | import { |
bbe10d5f JB |
18 | type ChargingStationData, |
19 | type ChargingStationWorkerData, | |
20 | type ChargingStationWorkerMessage, | |
21 | type ChargingStationWorkerMessageData, | |
e7aeea18 | 22 | ChargingStationWorkerMessageEvents, |
5d049829 | 23 | ConfigurationSection, |
6bd808fd | 24 | ProcedureName, |
268a74bb JB |
25 | type StationTemplateUrl, |
26 | type Statistics, | |
5d049829 JB |
27 | type StorageConfiguration, |
28 | type UIServerConfiguration, | |
29 | type WorkerConfiguration, | |
268a74bb | 30 | } from '../types'; |
fa5995d6 JB |
31 | import { |
32 | Configuration, | |
33 | Constants, | |
9bf0ef23 JB |
34 | formatDurationMilliSeconds, |
35 | generateUUID, | |
fa5995d6 JB |
36 | handleUncaughtException, |
37 | handleUnhandledRejection, | |
9bf0ef23 JB |
38 | isNotEmptyArray, |
39 | isNullOrUndefined, | |
40 | logPrefix, | |
fa5995d6 JB |
41 | logger, |
42 | } from '../utils'; | |
eda9c451 | 43 | import { type WorkerAbstract, WorkerFactory } from '../worker'; |
ded13d97 | 44 | |
32de5a57 LM |
45 | const moduleName = 'Bootstrap'; |
46 | ||
a307349b | 47 | enum exitCodes { |
a51a4ead | 48 | succeeded = 0, |
a307349b JB |
49 | missingChargingStationsConfiguration = 1, |
50 | noChargingStationTemplates = 2, | |
a51a4ead | 51 | gracefulShutdownError = 3, |
a307349b | 52 | } |
e4cb2c14 | 53 | |
f130b8e6 | 54 | export class Bootstrap extends EventEmitter { |
535aaa27 | 55 | private static instance: Bootstrap | null = null; |
d1c99c59 JB |
56 | public numberOfChargingStations!: number; |
57 | public numberOfChargingStationTemplates!: number; | |
aa428a31 | 58 | private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null; |
36adaf06 | 59 | private readonly uiServer: AbstractUIServer | null; |
6a49ad23 | 60 | private readonly storage!: Storage; |
89b7a234 | 61 | private numberOfStartedChargingStations!: number; |
628c30e5 | 62 | private readonly version: string = version; |
a596d200 | 63 | private initializedCounters: boolean; |
eb87fe87 | 64 | private started: boolean; |
82e9c15a JB |
65 | private starting: boolean; |
66 | private stopping: boolean; | |
9e23580d | 67 | private readonly workerScript: string; |
ded13d97 JB |
68 | |
69 | private constructor() { | |
f130b8e6 | 70 | super(); |
6bd808fd | 71 | for (const signal of ['SIGINT', 'SIGQUIT', 'SIGTERM']) { |
36adaf06 | 72 | process.on(signal, this.gracefulShutdown.bind(this)); |
6bd808fd | 73 | } |
4724a293 | 74 | // Enable unconditionally for now |
fa5995d6 JB |
75 | handleUnhandledRejection(); |
76 | handleUncaughtException(); | |
af8e02ca | 77 | this.started = false; |
82e9c15a JB |
78 | this.starting = false; |
79 | this.stopping = false; | |
0f040ac0 | 80 | this.initializedCounters = false; |
a596d200 | 81 | this.initializeCounters(); |
af8e02ca | 82 | this.workerImplementation = null; |
d972af76 JB |
83 | this.workerScript = join( |
84 | dirname(fileURLToPath(import.meta.url)), | |
5edd8ba0 | 85 | `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`, |
e7aeea18 | 86 | ); |
36adaf06 JB |
87 | this.uiServer = UIServerFactory.getUIServerImplementation( |
88 | Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer), | |
864e5f8d | 89 | ); |
864e5f8d JB |
90 | const performanceStorageConfiguration = |
91 | Configuration.getConfigurationSection<StorageConfiguration>( | |
92 | ConfigurationSection.performanceStorage, | |
93 | ); | |
94 | performanceStorageConfiguration.enabled === true && | |
e7aeea18 | 95 | (this.storage = StorageFactory.getStorage( |
864e5f8d JB |
96 | performanceStorageConfiguration.type!, |
97 | performanceStorageConfiguration.uri!, | |
5edd8ba0 | 98 | this.logPrefix(), |
e7aeea18 | 99 | )); |
b3b3f0eb | 100 | Configuration.configurationChangeCallback = async () => Bootstrap.getInstance().restart(false); |
ded13d97 JB |
101 | } |
102 | ||
103 | public static getInstance(): Bootstrap { | |
1ca780f9 | 104 | if (Bootstrap.instance === null) { |
ded13d97 JB |
105 | Bootstrap.instance = new Bootstrap(); |
106 | } | |
107 | return Bootstrap.instance; | |
108 | } | |
109 | ||
110 | public async start(): Promise<void> { | |
ee60150f | 111 | if (this.started === false) { |
82e9c15a JB |
112 | if (this.starting === false) { |
113 | this.starting = true; | |
114 | this.initializeCounters(); | |
864e5f8d JB |
115 | const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>( |
116 | ConfigurationSection.worker, | |
117 | ); | |
118 | this.initializeWorkerImplementation(workerConfiguration); | |
82e9c15a JB |
119 | await this.workerImplementation?.start(); |
120 | await this.storage?.open(); | |
36adaf06 JB |
121 | Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer) |
122 | .enabled === true && this.uiServer?.start(); | |
82e9c15a | 123 | // Start ChargingStation object instance in worker thread |
e1d9a0f4 | 124 | for (const stationTemplateUrl of Configuration.getStationTemplateUrls()!) { |
82e9c15a JB |
125 | try { |
126 | const nbStations = stationTemplateUrl.numberOfStations ?? 0; | |
127 | for (let index = 1; index <= nbStations; index++) { | |
128 | await this.startChargingStation(index, stationTemplateUrl); | |
129 | } | |
130 | } catch (error) { | |
131 | console.error( | |
132 | chalk.red( | |
5edd8ba0 | 133 | `Error at starting charging station with template file ${stationTemplateUrl.file}: `, |
82e9c15a | 134 | ), |
5edd8ba0 | 135 | error, |
82e9c15a | 136 | ); |
ded13d97 | 137 | } |
ded13d97 | 138 | } |
82e9c15a JB |
139 | console.info( |
140 | chalk.green( | |
141 | `Charging stations simulator ${ | |
142 | this.version | |
143 | } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${ | |
144 | Configuration.workerDynamicPoolInUse() | |
864e5f8d | 145 | ? `${workerConfiguration.poolMinSize?.toString()}/` |
82e9c15a JB |
146 | : '' |
147 | }${this.workerImplementation?.size}${ | |
148 | Configuration.workerPoolInUse() | |
864e5f8d | 149 | ? `/${workerConfiguration.poolMaxSize?.toString()}` |
82e9c15a | 150 | : '' |
864e5f8d | 151 | } worker(s) concurrently running in '${workerConfiguration.processType}' mode${ |
9bf0ef23 | 152 | !isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker) |
82e9c15a JB |
153 | ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)` |
154 | : '' | |
5edd8ba0 JB |
155 | }`, |
156 | ), | |
82e9c15a | 157 | ); |
56e2e1ab JB |
158 | Configuration.workerDynamicPoolInUse() && |
159 | console.warn( | |
160 | chalk.yellow( | |
1d8f226b | 161 | 'Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using fixed pool or worker set mode instead', |
5edd8ba0 | 162 | ), |
56e2e1ab | 163 | ); |
0bde1ea1 | 164 | console.info(chalk.green('Worker set/pool information:'), this.workerImplementation?.info); |
82e9c15a JB |
165 | this.started = true; |
166 | this.starting = false; | |
167 | } else { | |
168 | console.error(chalk.red('Cannot start an already starting charging stations simulator')); | |
ded13d97 | 169 | } |
b322b8b4 JB |
170 | } else { |
171 | console.error(chalk.red('Cannot start an already started charging stations simulator')); | |
ded13d97 JB |
172 | } |
173 | } | |
174 | ||
36adaf06 | 175 | public async stop(stopChargingStations = true): Promise<void> { |
ee60150f | 176 | if (this.started === true) { |
82e9c15a JB |
177 | if (this.stopping === false) { |
178 | this.stopping = true; | |
36adaf06 JB |
179 | if (stopChargingStations === true) { |
180 | await this.uiServer?.sendInternalRequest( | |
181 | this.uiServer.buildProtocolRequest( | |
182 | generateUUID(), | |
183 | ProcedureName.STOP_CHARGING_STATION, | |
184 | Constants.EMPTY_FROZEN_OBJECT, | |
ab7a96fa | 185 | ), |
36adaf06 JB |
186 | ); |
187 | await this.waitChargingStationsStopped(); | |
ab7a96fa | 188 | } |
82e9c15a JB |
189 | await this.workerImplementation?.stop(); |
190 | this.workerImplementation = null; | |
191 | this.uiServer?.stop(); | |
192 | await this.storage?.close(); | |
193 | this.resetCounters(); | |
194 | this.initializedCounters = false; | |
195 | this.started = false; | |
196 | this.stopping = false; | |
197 | } else { | |
198 | console.error(chalk.red('Cannot stop an already stopping charging stations simulator')); | |
199 | } | |
b322b8b4 | 200 | } else { |
82e9c15a | 201 | console.error(chalk.red('Cannot stop an already stopped charging stations simulator')); |
ded13d97 | 202 | } |
ded13d97 JB |
203 | } |
204 | ||
36adaf06 JB |
205 | public async restart(stopChargingStations?: boolean): Promise<void> { |
206 | await this.stop(stopChargingStations); | |
ded13d97 JB |
207 | await this.start(); |
208 | } | |
209 | ||
36adaf06 JB |
210 | private async waitChargingStationsStopped(): Promise<void> { |
211 | await Promise.race([ | |
212 | waitChargingStationEvents( | |
213 | this, | |
214 | ChargingStationWorkerMessageEvents.stopped, | |
215 | this.numberOfChargingStations, | |
216 | ), | |
217 | new Promise<string>((resolve) => { | |
218 | setTimeout(() => { | |
219 | const message = `Timeout ${formatDurationMilliSeconds( | |
220 | Constants.STOP_SIMULATOR_TIMEOUT, | |
221 | )} reached at stopping charging stations simulator`; | |
222 | console.warn(chalk.yellow(message)); | |
223 | resolve(message); | |
224 | }, Constants.STOP_SIMULATOR_TIMEOUT); | |
225 | }), | |
226 | ]); | |
227 | } | |
228 | ||
864e5f8d | 229 | private initializeWorkerImplementation(workerConfiguration: WorkerConfiguration): void { |
e1d9a0f4 | 230 | let elementsPerWorker: number | undefined; |
864e5f8d | 231 | if (workerConfiguration?.elementsPerWorker === 'auto') { |
34c200d5 JB |
232 | elementsPerWorker = |
233 | this.numberOfChargingStations > availableParallelism() | |
411f6bb4 | 234 | ? Math.round(this.numberOfChargingStations / (availableParallelism() * 1.5)) |
34c200d5 | 235 | : 1; |
8603c1ca | 236 | } |
e2c77f10 | 237 | this.workerImplementation === null && |
ec7f4dce JB |
238 | (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>( |
239 | this.workerScript, | |
864e5f8d | 240 | workerConfiguration.processType!, |
ec7f4dce | 241 | { |
864e5f8d JB |
242 | workerStartDelay: workerConfiguration.startDelay, |
243 | elementStartDelay: workerConfiguration.elementStartDelay, | |
244 | poolMaxSize: workerConfiguration.poolMaxSize!, | |
245 | poolMinSize: workerConfiguration.poolMinSize!, | |
246 | elementsPerWorker: elementsPerWorker ?? (workerConfiguration.elementsPerWorker as number), | |
ec7f4dce | 247 | poolOptions: { |
be245fda | 248 | messageHandler: this.messageHandler.bind(this) as (message: unknown) => void, |
ec7f4dce | 249 | }, |
5edd8ba0 | 250 | }, |
ec7f4dce | 251 | )); |
ded13d97 | 252 | } |
81797102 | 253 | |
32de5a57 | 254 | private messageHandler( |
5edd8ba0 | 255 | msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>, |
32de5a57 LM |
256 | ): void { |
257 | // logger.debug( | |
258 | // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify( | |
259 | // msg, | |
4ed03b6e | 260 | // undefined, |
e1d9a0f4 JB |
261 | // 2, |
262 | // )}`, | |
32de5a57 LM |
263 | // ); |
264 | try { | |
8cc482a9 | 265 | switch (msg.event) { |
721646e9 | 266 | case ChargingStationWorkerMessageEvents.started: |
32de5a57 | 267 | this.workerEventStarted(msg.data as ChargingStationData); |
f130b8e6 | 268 | this.emit(ChargingStationWorkerMessageEvents.started, msg.data as ChargingStationData); |
32de5a57 | 269 | break; |
721646e9 | 270 | case ChargingStationWorkerMessageEvents.stopped: |
32de5a57 | 271 | this.workerEventStopped(msg.data as ChargingStationData); |
f130b8e6 | 272 | this.emit(ChargingStationWorkerMessageEvents.stopped, msg.data as ChargingStationData); |
32de5a57 | 273 | break; |
721646e9 | 274 | case ChargingStationWorkerMessageEvents.updated: |
32de5a57 | 275 | this.workerEventUpdated(msg.data as ChargingStationData); |
f130b8e6 | 276 | this.emit(ChargingStationWorkerMessageEvents.updated, msg.data as ChargingStationData); |
32de5a57 | 277 | break; |
721646e9 | 278 | case ChargingStationWorkerMessageEvents.performanceStatistics: |
32de5a57 | 279 | this.workerEventPerformanceStatistics(msg.data as Statistics); |
f130b8e6 JB |
280 | this.emit( |
281 | ChargingStationWorkerMessageEvents.performanceStatistics, | |
5edd8ba0 | 282 | msg.data as Statistics, |
f130b8e6 | 283 | ); |
32de5a57 | 284 | break; |
2bb7a73e JB |
285 | case ChargingStationWorkerMessageEvents.startWorkerElementError: |
286 | logger.error( | |
287 | `${this.logPrefix()} ${moduleName}.messageHandler: Error occured while starting worker element:`, | |
288 | msg.data, | |
289 | ); | |
290 | this.emit(ChargingStationWorkerMessageEvents.startWorkerElementError, msg.data); | |
291 | break; | |
292 | case ChargingStationWorkerMessageEvents.startedWorkerElement: | |
293 | break; | |
32de5a57 LM |
294 | default: |
295 | throw new BaseError( | |
f93dda6a JB |
296 | `Unknown charging station worker event: '${ |
297 | msg.event | |
4ed03b6e | 298 | }' received with data: ${JSON.stringify(msg.data, undefined, 2)}`, |
32de5a57 LM |
299 | ); |
300 | } | |
301 | } catch (error) { | |
302 | logger.error( | |
303 | `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${ | |
8cc482a9 | 304 | msg.event |
32de5a57 | 305 | }' event:`, |
5edd8ba0 | 306 | error, |
32de5a57 LM |
307 | ); |
308 | } | |
309 | } | |
310 | ||
e2c77f10 | 311 | private workerEventStarted = (data: ChargingStationData) => { |
51c83d6f | 312 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
89b7a234 | 313 | ++this.numberOfStartedChargingStations; |
56eb297e | 314 | logger.info( |
e6159ce8 | 315 | `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${ |
56eb297e | 316 | data.stationInfo.chargingStationId |
e6159ce8 | 317 | } (hashId: ${data.stationInfo.hashId}) started (${ |
56eb297e | 318 | this.numberOfStartedChargingStations |
5edd8ba0 | 319 | } started from ${this.numberOfChargingStations})`, |
56eb297e | 320 | ); |
e2c77f10 | 321 | }; |
32de5a57 | 322 | |
e2c77f10 | 323 | private workerEventStopped = (data: ChargingStationData) => { |
51c83d6f | 324 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
89b7a234 | 325 | --this.numberOfStartedChargingStations; |
56eb297e | 326 | logger.info( |
e6159ce8 | 327 | `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${ |
56eb297e | 328 | data.stationInfo.chargingStationId |
e6159ce8 | 329 | } (hashId: ${data.stationInfo.hashId}) stopped (${ |
56eb297e | 330 | this.numberOfStartedChargingStations |
5edd8ba0 | 331 | } started from ${this.numberOfChargingStations})`, |
56eb297e | 332 | ); |
e2c77f10 | 333 | }; |
32de5a57 | 334 | |
e2c77f10 | 335 | private workerEventUpdated = (data: ChargingStationData) => { |
51c83d6f | 336 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
e2c77f10 | 337 | }; |
32de5a57 LM |
338 | |
339 | private workerEventPerformanceStatistics = (data: Statistics) => { | |
340 | this.storage.storePerformanceStatistics(data) as void; | |
341 | }; | |
342 | ||
326cec2d | 343 | private initializeCounters() { |
a596d200 | 344 | if (this.initializedCounters === false) { |
0f040ac0 | 345 | this.resetCounters(); |
e1d9a0f4 | 346 | const stationTemplateUrls = Configuration.getStationTemplateUrls()!; |
9bf0ef23 | 347 | if (isNotEmptyArray(stationTemplateUrls)) { |
41bda658 | 348 | this.numberOfChargingStationTemplates = stationTemplateUrls.length; |
7436ee0d | 349 | for (const stationTemplateUrl of stationTemplateUrls) { |
a596d200 | 350 | this.numberOfChargingStations += stationTemplateUrl.numberOfStations ?? 0; |
7436ee0d | 351 | } |
a596d200 JB |
352 | } else { |
353 | console.warn( | |
5edd8ba0 | 354 | chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting"), |
a596d200 | 355 | ); |
10687422 | 356 | exit(exitCodes.missingChargingStationsConfiguration); |
a596d200 JB |
357 | } |
358 | if (this.numberOfChargingStations === 0) { | |
359 | console.warn( | |
5edd8ba0 | 360 | chalk.yellow('No charging station template enabled in configuration, exiting'), |
a596d200 | 361 | ); |
10687422 | 362 | exit(exitCodes.noChargingStationTemplates); |
a596d200 | 363 | } |
a596d200 | 364 | this.initializedCounters = true; |
846d2851 | 365 | } |
7c72977b JB |
366 | } |
367 | ||
0f040ac0 JB |
368 | private resetCounters(): void { |
369 | this.numberOfChargingStationTemplates = 0; | |
370 | this.numberOfChargingStations = 0; | |
371 | this.numberOfStartedChargingStations = 0; | |
372 | } | |
373 | ||
e7aeea18 JB |
374 | private async startChargingStation( |
375 | index: number, | |
5edd8ba0 | 376 | stationTemplateUrl: StationTemplateUrl, |
e7aeea18 | 377 | ): Promise<void> { |
6ed3c845 | 378 | await this.workerImplementation?.addElement({ |
717c1e56 | 379 | index, |
d972af76 JB |
380 | templateFile: join( |
381 | dirname(fileURLToPath(import.meta.url)), | |
e7aeea18 JB |
382 | 'assets', |
383 | 'station-templates', | |
5edd8ba0 | 384 | stationTemplateUrl.file, |
e7aeea18 | 385 | ), |
6ed3c845 | 386 | }); |
717c1e56 JB |
387 | } |
388 | ||
36adaf06 | 389 | private gracefulShutdown(): void { |
f130b8e6 JB |
390 | this.stop() |
391 | .then(() => { | |
83a36f14 | 392 | console.info(`${chalk.green('Graceful shutdown')}`); |
36adaf06 JB |
393 | // stop() asks for charging stations to stop by default |
394 | this.waitChargingStationsStopped() | |
395 | .then(() => { | |
396 | exit(exitCodes.succeeded); | |
397 | }) | |
398 | .catch((error) => { | |
399 | console.error(chalk.red('Error while waiting for charging stations to stop: '), error); | |
400 | exit(exitCodes.gracefulShutdownError); | |
401 | }); | |
f130b8e6 JB |
402 | }) |
403 | .catch((error) => { | |
fca8bc64 | 404 | console.error(chalk.red('Error while shutdowning charging stations simulator: '), error); |
10687422 | 405 | exit(exitCodes.gracefulShutdownError); |
f130b8e6 | 406 | }); |
36adaf06 | 407 | } |
f130b8e6 | 408 | |
8b7072dc | 409 | private logPrefix = (): string => { |
9bf0ef23 | 410 | return logPrefix(' Bootstrap |'); |
8b7072dc | 411 | }; |
ded13d97 | 412 | } |