refactor: rename elementsPerWorkers 'single' -> 'all
[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 );
b3b3f0eb 84 Configuration.configurationChangeCallback = async () => Bootstrap.getInstance().restart(false);
ded13d97
JB
85 }
86
87 public static getInstance(): Bootstrap {
1ca780f9 88 if (Bootstrap.instance === null) {
ded13d97
JB
89 Bootstrap.instance = new Bootstrap();
90 }
91 return Bootstrap.instance;
92 }
93
94 public async start(): Promise<void> {
ee60150f 95 if (this.started === false) {
82e9c15a
JB
96 if (this.starting === false) {
97 this.starting = true;
4354af5a
JB
98 this.on(ChargingStationWorkerMessageEvents.started, this.workerEventStarted);
99 this.on(ChargingStationWorkerMessageEvents.stopped, this.workerEventStopped);
100 this.on(ChargingStationWorkerMessageEvents.updated, this.workerEventUpdated);
101 this.on(
102 ChargingStationWorkerMessageEvents.performanceStatistics,
103 this.workerEventPerformanceStatistics,
104 );
82e9c15a 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(() => {
4354af5a 232 this.removeAllListeners();
5b2721db
JB
233 resolve('Charging stations stopped');
234 })
b7ee97c1 235 .catch(reject)
5b2721db
JB
236 .finally(() => {
237 clearTimeout(waitTimeout);
238 });
239 });
36adaf06
JB
240 }
241
864e5f8d 242 private initializeWorkerImplementation(workerConfiguration: WorkerConfiguration): void {
e1d9a0f4 243 let elementsPerWorker: number | undefined;
487f0dfd
JB
244 switch (workerConfiguration?.elementsPerWorker) {
245 case 'auto':
246 elementsPerWorker =
247 this.numberOfChargingStations > availableParallelism()
248 ? Math.round(this.numberOfChargingStations / (availableParallelism() * 1.5))
249 : 1;
250 break;
c20d5d72 251 case 'all':
487f0dfd
JB
252 elementsPerWorker = this.numberOfChargingStations;
253 break;
8603c1ca 254 }
6d2b7d01
JB
255 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
256 join(
257 dirname(fileURLToPath(import.meta.url)),
258 `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`,
259 ),
260 workerConfiguration.processType!,
261 {
262 workerStartDelay: workerConfiguration.startDelay,
263 elementStartDelay: workerConfiguration.elementStartDelay,
264 poolMaxSize: workerConfiguration.poolMaxSize!,
265 poolMinSize: workerConfiguration.poolMinSize!,
266 elementsPerWorker: elementsPerWorker ?? (workerConfiguration.elementsPerWorker as number),
267 poolOptions: {
268 messageHandler: this.messageHandler.bind(this) as (message: unknown) => void,
487f0dfd 269 workerOptions: { resourceLimits: workerConfiguration.resourceLimits },
5edd8ba0 270 },
6d2b7d01
JB
271 },
272 );
ded13d97 273 }
81797102 274
32de5a57 275 private messageHandler(
5edd8ba0 276 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>,
32de5a57
LM
277 ): void {
278 // logger.debug(
279 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
280 // msg,
4ed03b6e 281 // undefined,
e1d9a0f4
JB
282 // 2,
283 // )}`,
32de5a57
LM
284 // );
285 try {
8cc482a9 286 switch (msg.event) {
721646e9 287 case ChargingStationWorkerMessageEvents.started:
f130b8e6 288 this.emit(ChargingStationWorkerMessageEvents.started, msg.data as ChargingStationData);
32de5a57 289 break;
721646e9 290 case ChargingStationWorkerMessageEvents.stopped:
f130b8e6 291 this.emit(ChargingStationWorkerMessageEvents.stopped, msg.data as ChargingStationData);
32de5a57 292 break;
721646e9 293 case ChargingStationWorkerMessageEvents.updated:
f130b8e6 294 this.emit(ChargingStationWorkerMessageEvents.updated, msg.data as ChargingStationData);
32de5a57 295 break;
721646e9 296 case ChargingStationWorkerMessageEvents.performanceStatistics:
f130b8e6
JB
297 this.emit(
298 ChargingStationWorkerMessageEvents.performanceStatistics,
5edd8ba0 299 msg.data as Statistics,
f130b8e6 300 );
32de5a57 301 break;
2bb7a73e
JB
302 case ChargingStationWorkerMessageEvents.startWorkerElementError:
303 logger.error(
304 `${this.logPrefix()} ${moduleName}.messageHandler: Error occured while starting worker element:`,
305 msg.data,
306 );
307 this.emit(ChargingStationWorkerMessageEvents.startWorkerElementError, msg.data);
308 break;
309 case ChargingStationWorkerMessageEvents.startedWorkerElement:
310 break;
32de5a57
LM
311 default:
312 throw new BaseError(
f93dda6a
JB
313 `Unknown charging station worker event: '${
314 msg.event
4ed03b6e 315 }' received with data: ${JSON.stringify(msg.data, undefined, 2)}`,
32de5a57
LM
316 );
317 }
318 } catch (error) {
319 logger.error(
320 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
8cc482a9 321 msg.event
32de5a57 322 }' event:`,
5edd8ba0 323 error,
32de5a57
LM
324 );
325 }
326 }
327
e2c77f10 328 private workerEventStarted = (data: ChargingStationData) => {
51c83d6f 329 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 330 ++this.numberOfStartedChargingStations;
56eb297e 331 logger.info(
e6159ce8 332 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
56eb297e 333 data.stationInfo.chargingStationId
e6159ce8 334 } (hashId: ${data.stationInfo.hashId}) started (${
56eb297e 335 this.numberOfStartedChargingStations
5edd8ba0 336 } started from ${this.numberOfChargingStations})`,
56eb297e 337 );
e2c77f10 338 };
32de5a57 339
e2c77f10 340 private workerEventStopped = (data: ChargingStationData) => {
51c83d6f 341 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 342 --this.numberOfStartedChargingStations;
56eb297e 343 logger.info(
e6159ce8 344 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
56eb297e 345 data.stationInfo.chargingStationId
e6159ce8 346 } (hashId: ${data.stationInfo.hashId}) stopped (${
56eb297e 347 this.numberOfStartedChargingStations
5edd8ba0 348 } started from ${this.numberOfChargingStations})`,
56eb297e 349 );
e2c77f10 350 };
32de5a57 351
e2c77f10 352 private workerEventUpdated = (data: ChargingStationData) => {
51c83d6f 353 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
e2c77f10 354 };
32de5a57
LM
355
356 private workerEventPerformanceStatistics = (data: Statistics) => {
6d2b7d01 357 this.storage?.storePerformanceStatistics(data) as void;
32de5a57
LM
358 };
359
326cec2d 360 private initializeCounters() {
a596d200 361 if (this.initializedCounters === false) {
0f040ac0 362 this.resetCounters();
e1d9a0f4 363 const stationTemplateUrls = Configuration.getStationTemplateUrls()!;
9bf0ef23 364 if (isNotEmptyArray(stationTemplateUrls)) {
41bda658 365 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
7436ee0d 366 for (const stationTemplateUrl of stationTemplateUrls) {
a596d200 367 this.numberOfChargingStations += stationTemplateUrl.numberOfStations ?? 0;
7436ee0d 368 }
a596d200
JB
369 } else {
370 console.warn(
5edd8ba0 371 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting"),
a596d200 372 );
10687422 373 exit(exitCodes.missingChargingStationsConfiguration);
a596d200
JB
374 }
375 if (this.numberOfChargingStations === 0) {
376 console.warn(
5edd8ba0 377 chalk.yellow('No charging station template enabled in configuration, exiting'),
a596d200 378 );
10687422 379 exit(exitCodes.noChargingStationTemplates);
a596d200 380 }
a596d200 381 this.initializedCounters = true;
846d2851 382 }
7c72977b
JB
383 }
384
0f040ac0
JB
385 private resetCounters(): void {
386 this.numberOfChargingStationTemplates = 0;
387 this.numberOfChargingStations = 0;
388 this.numberOfStartedChargingStations = 0;
389 }
390
e7aeea18
JB
391 private async startChargingStation(
392 index: number,
5edd8ba0 393 stationTemplateUrl: StationTemplateUrl,
e7aeea18 394 ): Promise<void> {
6ed3c845 395 await this.workerImplementation?.addElement({
717c1e56 396 index,
d972af76
JB
397 templateFile: join(
398 dirname(fileURLToPath(import.meta.url)),
e7aeea18
JB
399 'assets',
400 'station-templates',
5edd8ba0 401 stationTemplateUrl.file,
e7aeea18 402 ),
6ed3c845 403 });
717c1e56
JB
404 }
405
36adaf06 406 private gracefulShutdown(): void {
f130b8e6
JB
407 this.stop()
408 .then(() => {
83a36f14 409 console.info(`${chalk.green('Graceful shutdown')}`);
36adaf06
JB
410 // stop() asks for charging stations to stop by default
411 this.waitChargingStationsStopped()
412 .then(() => {
413 exit(exitCodes.succeeded);
414 })
5b2721db 415 .catch(() => {
36adaf06
JB
416 exit(exitCodes.gracefulShutdownError);
417 });
f130b8e6
JB
418 })
419 .catch((error) => {
fca8bc64 420 console.error(chalk.red('Error while shutdowning charging stations simulator: '), error);
10687422 421 exit(exitCodes.gracefulShutdownError);
f130b8e6 422 });
36adaf06 423 }
f130b8e6 424
8b7072dc 425 private logPrefix = (): string => {
9bf0ef23 426 return logPrefix(' Bootstrap |');
8b7072dc 427 };
ded13d97 428}