ATG: add support for idTag distribution algorithms
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
8114d10e
JB
3import path from 'path';
4import { fileURLToPath } from 'url';
c72f6634 5import { type Worker, isMainThread } from 'worker_threads';
8114d10e
JB
6
7import chalk from 'chalk';
8
9import { version } from '../../package.json';
32de5a57 10import BaseError from '../exception/BaseError';
6c1761d4 11import type { Storage } from '../performance/storage/Storage';
8114d10e 12import { StorageFactory } from '../performance/storage/StorageFactory';
e7aeea18 13import {
32de5a57 14 ChargingStationData,
e7aeea18
JB
15 ChargingStationWorkerData,
16 ChargingStationWorkerMessage,
53e5fd67 17 ChargingStationWorkerMessageData,
e7aeea18
JB
18 ChargingStationWorkerMessageEvents,
19} from '../types/ChargingStationWorker';
6c1761d4 20import type { StationTemplateUrl } from '../types/ConfigurationData';
8a36b1eb 21import type { Statistics } from '../types/Statistics';
8114d10e 22import Configuration from '../utils/Configuration';
32de5a57 23import logger from '../utils/Logger';
ded13d97 24import Utils from '../utils/Utils';
6c1761d4 25import type WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 26import WorkerFactory from '../worker/WorkerFactory';
8114d10e 27import { ChargingStationUtils } from './ChargingStationUtils';
6c1761d4 28import type { AbstractUIServer } from './ui-server/AbstractUIServer';
8114d10e 29import UIServerFactory from './ui-server/UIServerFactory';
ded13d97 30
32de5a57
LM
31const moduleName = 'Bootstrap';
32
e4cb2c14
JB
33const missingChargingStationsConfigurationExitCode = 1;
34const noChargingStationTemplatesExitCode = 2;
35
5a010bf0 36export class Bootstrap {
535aaa27 37 private static instance: Bootstrap | null = null;
aa428a31 38 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
fe94fce0 39 private readonly uiServer!: AbstractUIServer;
6a49ad23 40 private readonly storage!: Storage;
7c72977b
JB
41 private numberOfChargingStationTemplates!: number;
42 private numberOfChargingStations!: number;
89b7a234 43 private numberOfStartedChargingStations!: number;
9e23580d 44 private readonly version: string = version;
eb87fe87 45 private started: boolean;
9e23580d 46 private readonly workerScript: string;
ded13d97
JB
47
48 private constructor() {
eb87fe87 49 this.started = false;
aa428a31 50 this.workerImplementation = null;
e7aeea18 51 this.workerScript = path.join(
0d8140bd 52 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 53 'charging-station',
44a95b7f 54 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
e7aeea18 55 );
7c72977b 56 this.initialize();
5af9aa8a 57 Configuration.getUIServer().enabled === true &&
976d11ec 58 (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer()));
eb3abc4f 59 Configuration.getPerformanceStorage().enabled === true &&
e7aeea18
JB
60 (this.storage = StorageFactory.getStorage(
61 Configuration.getPerformanceStorage().type,
62 Configuration.getPerformanceStorage().uri,
63 this.logPrefix()
64 ));
7874b0b1 65 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
66 }
67
68 public static getInstance(): Bootstrap {
1ca780f9 69 if (Bootstrap.instance === null) {
ded13d97
JB
70 Bootstrap.instance = new Bootstrap();
71 }
72 return Bootstrap.instance;
73 }
74
75 public async start(): Promise<void> {
452a82ca 76 if (isMainThread && this.started === false) {
ded13d97 77 try {
48d17ce2
JB
78 // Enable unconditionally for now
79 this.logUnhandledRejection();
80 this.logUncaughtException();
7c72977b 81 this.initialize();
6a49ad23 82 await this.storage?.open();
a4bc2942 83 await this.workerImplementation.start();
675fa8e3 84 this.uiServer?.start();
1f5df42a 85 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 86 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 87 // Start ChargingStation object in worker thread
45bd0627 88 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 89 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 90 try {
1f5df42a 91 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 92 for (let index = 1; index <= nbStations; index++) {
717c1e56 93 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
94 }
95 } catch (error) {
e7aeea18
JB
96 console.error(
97 chalk.red(
3d25cc86
JB
98 'Error at starting charging station with template file ' +
99 stationTemplateUrl.file +
100 ': '
e7aeea18
JB
101 ),
102 error
103 );
ded13d97
JB
104 }
105 }
106 } else {
45bd0627
JB
107 console.warn(
108 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
109 );
e4cb2c14 110 process.exit(missingChargingStationsConfigurationExitCode);
ded13d97 111 }
a4bc2942 112 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
113 console.warn(
114 chalk.yellow('No charging station template enabled in configuration, exiting')
115 );
e4cb2c14 116 process.exit(noChargingStationTemplatesExitCode);
ded13d97 117 } else {
32de5a57 118 console.info(
e7aeea18
JB
119 chalk.green(
120 `Charging stations simulator ${
121 this.version
7c72977b 122 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 123 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 124 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
125 : ''
126 }${this.workerImplementation.size}${
17ac262c 127 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 128 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 129 : ''
cf2a5d9b 130 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
131 this.workerImplementation.maxElementsPerWorker
132 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
133 : ''
134 }`
135 )
136 );
ded13d97 137 }
eb87fe87 138 this.started = true;
ded13d97 139 } catch (error) {
10d244c0 140 console.error(chalk.red('Bootstrap start error: '), error);
ded13d97 141 }
b322b8b4
JB
142 } else {
143 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
144 }
145 }
146
147 public async stop(): Promise<void> {
452a82ca 148 if (isMainThread && this.started === true) {
a4bc2942 149 await this.workerImplementation.stop();
b19021e2 150 this.workerImplementation = null;
675fa8e3 151 this.uiServer?.stop();
6a49ad23 152 await this.storage?.close();
ba7965c4 153 this.started = false;
b322b8b4 154 } else {
ba7965c4 155 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
ded13d97 156 }
ded13d97
JB
157 }
158
159 public async restart(): Promise<void> {
160 await this.stop();
7c72977b 161 this.initialize();
ded13d97
JB
162 await this.start();
163 }
164
ec7f4dce 165 private initializeWorkerImplementation(): void {
e2c77f10 166 this.workerImplementation === null &&
ec7f4dce
JB
167 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
168 this.workerScript,
cf2a5d9b 169 Configuration.getWorker().processType,
ec7f4dce 170 {
cf2a5d9b
JB
171 workerStartDelay: Configuration.getWorker().startDelay,
172 elementStartDelay: Configuration.getWorker().elementStartDelay,
173 poolMaxSize: Configuration.getWorker().poolMaxSize,
174 poolMinSize: Configuration.getWorker().poolMinSize,
175 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
ec7f4dce 176 poolOptions: {
cf2a5d9b 177 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 178 },
32de5a57 179 messageHandler: this.messageHandler.bind(this) as (
c72f6634 180 this: Worker,
53e5fd67 181 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57 182 ) => void,
ec7f4dce
JB
183 }
184 ));
ded13d97 185 }
81797102 186
32de5a57 187 private messageHandler(
53e5fd67 188 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
189 ): void {
190 // logger.debug(
191 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
192 // msg,
193 // null,
194 // 2
195 // )}`
196 // );
197 try {
198 switch (msg.id) {
199 case ChargingStationWorkerMessageEvents.STARTED:
200 this.workerEventStarted(msg.data as ChargingStationData);
201 break;
202 case ChargingStationWorkerMessageEvents.STOPPED:
203 this.workerEventStopped(msg.data as ChargingStationData);
204 break;
205 case ChargingStationWorkerMessageEvents.UPDATED:
206 this.workerEventUpdated(msg.data as ChargingStationData);
207 break;
208 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
209 this.workerEventPerformanceStatistics(msg.data as Statistics);
210 break;
211 default:
212 throw new BaseError(
213 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
214 );
215 }
216 } catch (error) {
217 logger.error(
218 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
219 msg.id
220 }' event:`,
221 error
222 );
223 }
224 }
225
e2c77f10 226 private workerEventStarted = (data: ChargingStationData) => {
51c83d6f 227 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 228 ++this.numberOfStartedChargingStations;
e2c77f10 229 };
32de5a57 230
e2c77f10 231 private workerEventStopped = (data: ChargingStationData) => {
51c83d6f 232 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 233 --this.numberOfStartedChargingStations;
e2c77f10 234 };
32de5a57 235
e2c77f10 236 private workerEventUpdated = (data: ChargingStationData) => {
51c83d6f 237 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
e2c77f10 238 };
32de5a57
LM
239
240 private workerEventPerformanceStatistics = (data: Statistics) => {
241 this.storage.storePerformanceStatistics(data) as void;
242 };
243
7c72977b 244 private initialize() {
7c72977b 245 this.numberOfChargingStationTemplates = 0;
89b7a234
JB
246 this.numberOfChargingStations = 0;
247 this.numberOfStartedChargingStations = 0;
ec7f4dce 248 this.initializeWorkerImplementation();
7c72977b
JB
249 }
250
48d17ce2
JB
251 private logUncaughtException(): void {
252 process.on('uncaughtException', (error: Error) => {
253 console.error(chalk.red('Uncaught exception: '), error);
254 });
255 }
256
257 private logUnhandledRejection(): void {
258 process.on('unhandledRejection', (reason: unknown) => {
259 console.error(chalk.red('Unhandled rejection: '), reason);
260 });
261 }
262
e7aeea18
JB
263 private async startChargingStation(
264 index: number,
265 stationTemplateUrl: StationTemplateUrl
266 ): Promise<void> {
717c1e56
JB
267 const workerData: ChargingStationWorkerData = {
268 index,
e7aeea18 269 templateFile: path.join(
0d8140bd 270 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
271 'assets',
272 'station-templates',
ee5f26a2 273 stationTemplateUrl.file
e7aeea18 274 ),
717c1e56
JB
275 };
276 await this.workerImplementation.addElement(workerData);
89b7a234 277 ++this.numberOfChargingStations;
717c1e56
JB
278 }
279
81797102 280 private logPrefix(): string {
689dca78 281 return Utils.logPrefix(' Bootstrap |');
81797102 282 }
ded13d97 283}