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