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