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