Guard against duplicate start/stop CS
[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';
5import { isMainThread } from 'worker_threads';
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
JB
20import type { StationTemplateUrl } from '../types/ConfigurationData';
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 {
7c72977b 78 this.initialize();
6a49ad23 79 await this.storage?.open();
a4bc2942 80 await this.workerImplementation.start();
675fa8e3 81 this.uiServer?.start();
1f5df42a 82 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 83 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 84 // Start ChargingStation object in worker thread
45bd0627 85 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 86 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 87 try {
1f5df42a 88 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 89 for (let index = 1; index <= nbStations; index++) {
717c1e56 90 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
91 }
92 } catch (error) {
e7aeea18
JB
93 console.error(
94 chalk.red(
3d25cc86
JB
95 'Error at starting charging station with template file ' +
96 stationTemplateUrl.file +
97 ': '
e7aeea18
JB
98 ),
99 error
100 );
ded13d97
JB
101 }
102 }
103 } else {
45bd0627
JB
104 console.warn(
105 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
106 );
e4cb2c14 107 process.exit(missingChargingStationsConfigurationExitCode);
ded13d97 108 }
a4bc2942 109 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
110 console.warn(
111 chalk.yellow('No charging station template enabled in configuration, exiting')
112 );
e4cb2c14 113 process.exit(noChargingStationTemplatesExitCode);
ded13d97 114 } else {
32de5a57 115 console.info(
e7aeea18
JB
116 chalk.green(
117 `Charging stations simulator ${
118 this.version
7c72977b 119 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 120 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 121 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
122 : ''
123 }${this.workerImplementation.size}${
17ac262c 124 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 125 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 126 : ''
cf2a5d9b 127 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
128 this.workerImplementation.maxElementsPerWorker
129 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
130 : ''
131 }`
132 )
133 );
ded13d97 134 }
eb87fe87 135 this.started = true;
ded13d97 136 } catch (error) {
10d244c0 137 console.error(chalk.red('Bootstrap start error: '), error);
ded13d97 138 }
b322b8b4
JB
139 } else {
140 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
141 }
142 }
143
144 public async stop(): Promise<void> {
452a82ca 145 if (isMainThread && this.started === true) {
a4bc2942 146 await this.workerImplementation.stop();
b19021e2 147 this.workerImplementation = null;
675fa8e3 148 this.uiServer?.stop();
6a49ad23 149 await this.storage?.close();
b322b8b4
JB
150 } else {
151 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 152 }
eb87fe87 153 this.started = false;
ded13d97
JB
154 }
155
156 public async restart(): Promise<void> {
157 await this.stop();
7c72977b 158 this.initialize();
ded13d97
JB
159 await this.start();
160 }
161
ec7f4dce 162 private initializeWorkerImplementation(): void {
e2c77f10 163 this.workerImplementation === null &&
ec7f4dce
JB
164 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
165 this.workerScript,
cf2a5d9b 166 Configuration.getWorker().processType,
ec7f4dce 167 {
cf2a5d9b
JB
168 workerStartDelay: Configuration.getWorker().startDelay,
169 elementStartDelay: Configuration.getWorker().elementStartDelay,
170 poolMaxSize: Configuration.getWorker().poolMaxSize,
171 poolMinSize: Configuration.getWorker().poolMinSize,
172 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
ec7f4dce 173 poolOptions: {
cf2a5d9b 174 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 175 },
32de5a57 176 messageHandler: this.messageHandler.bind(this) as (
53e5fd67 177 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57 178 ) => void,
ec7f4dce
JB
179 }
180 ));
ded13d97 181 }
81797102 182
32de5a57 183 private messageHandler(
53e5fd67 184 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
185 ): void {
186 // logger.debug(
187 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
188 // msg,
189 // null,
190 // 2
191 // )}`
192 // );
193 try {
194 switch (msg.id) {
195 case ChargingStationWorkerMessageEvents.STARTED:
196 this.workerEventStarted(msg.data as ChargingStationData);
197 break;
198 case ChargingStationWorkerMessageEvents.STOPPED:
199 this.workerEventStopped(msg.data as ChargingStationData);
200 break;
201 case ChargingStationWorkerMessageEvents.UPDATED:
202 this.workerEventUpdated(msg.data as ChargingStationData);
203 break;
204 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
205 this.workerEventPerformanceStatistics(msg.data as Statistics);
206 break;
207 default:
208 throw new BaseError(
209 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
210 );
211 }
212 } catch (error) {
213 logger.error(
214 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
215 msg.id
216 }' event:`,
217 error
218 );
219 }
220 }
221
e2c77f10 222 private workerEventStarted = (data: ChargingStationData) => {
51c83d6f 223 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 224 ++this.numberOfStartedChargingStations;
e2c77f10 225 };
32de5a57 226
e2c77f10 227 private workerEventStopped = (data: ChargingStationData) => {
51c83d6f 228 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 229 --this.numberOfStartedChargingStations;
e2c77f10 230 };
32de5a57 231
e2c77f10 232 private workerEventUpdated = (data: ChargingStationData) => {
51c83d6f 233 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
e2c77f10 234 };
32de5a57
LM
235
236 private workerEventPerformanceStatistics = (data: Statistics) => {
237 this.storage.storePerformanceStatistics(data) as void;
238 };
239
7c72977b 240 private initialize() {
7c72977b 241 this.numberOfChargingStationTemplates = 0;
89b7a234
JB
242 this.numberOfChargingStations = 0;
243 this.numberOfStartedChargingStations = 0;
ec7f4dce 244 this.initializeWorkerImplementation();
7c72977b
JB
245 }
246
e7aeea18
JB
247 private async startChargingStation(
248 index: number,
249 stationTemplateUrl: StationTemplateUrl
250 ): Promise<void> {
717c1e56
JB
251 const workerData: ChargingStationWorkerData = {
252 index,
e7aeea18 253 templateFile: path.join(
0d8140bd 254 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
255 'assets',
256 'station-templates',
ee5f26a2 257 stationTemplateUrl.file
e7aeea18 258 ),
717c1e56
JB
259 };
260 await this.workerImplementation.addElement(workerData);
89b7a234 261 ++this.numberOfChargingStations;
717c1e56
JB
262 }
263
81797102 264 private logPrefix(): string {
689dca78 265 return Utils.logPrefix(' Bootstrap |');
81797102 266 }
ded13d97 267}