d1e2efd363f3066cea99c1b6558bf23823052caa
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import path from 'path';
4 import { fileURLToPath } from 'url';
5 import { isMainThread } from 'worker_threads';
6
7 import chalk from 'chalk';
8
9 import { version } from '../../package.json';
10 import BaseError from '../exception/BaseError';
11 import { Storage } from '../performance/storage/Storage';
12 import { StorageFactory } from '../performance/storage/StorageFactory';
13 import {
14 ChargingStationData,
15 ChargingStationWorkerData,
16 ChargingStationWorkerMessage,
17 ChargingStationWorkerMessageData,
18 ChargingStationWorkerMessageEvents,
19 } from '../types/ChargingStationWorker';
20 import { StationTemplateUrl } from '../types/ConfigurationData';
21 import Statistics from '../types/Statistics';
22 import { ApplicationProtocol } from '../types/UIProtocol';
23 import Configuration from '../utils/Configuration';
24 import logger from '../utils/Logger';
25 import Utils from '../utils/Utils';
26 import WorkerAbstract from '../worker/WorkerAbstract';
27 import WorkerFactory from '../worker/WorkerFactory';
28 import { ChargingStationUtils } from './ChargingStationUtils';
29 import { AbstractUIServer } from './ui-server/AbstractUIServer';
30 import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
31 import UIServerFactory from './ui-server/UIServerFactory';
32
33 const moduleName = 'Bootstrap';
34
35 const missingChargingStationsConfigurationExitCode = 1;
36 const noChargingStationTemplatesExitCode = 2;
37
38 export class Bootstrap {
39 private static instance: Bootstrap | null = null;
40 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
41 private readonly uiServer!: AbstractUIServer;
42 private readonly storage!: Storage;
43 private numberOfChargingStationTemplates!: number;
44 private numberOfChargingStations!: number;
45 private numberOfStartedChargingStations!: number;
46 private readonly version: string = version;
47 private started: boolean;
48 private readonly workerScript: string;
49
50 private constructor() {
51 this.started = false;
52 this.workerScript = path.join(
53 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
54 'charging-station',
55 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
56 );
57 this.initialize();
58 Configuration.getUIServer().enabled &&
59 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
60 ...Configuration.getUIServer().options,
61 handleProtocols: UIServiceUtils.handleProtocols,
62 }));
63 Configuration.getPerformanceStorage().enabled &&
64 (this.storage = StorageFactory.getStorage(
65 Configuration.getPerformanceStorage().type,
66 Configuration.getPerformanceStorage().uri,
67 this.logPrefix()
68 ));
69 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
70 }
71
72 public static getInstance(): Bootstrap {
73 if (Bootstrap.instance === null) {
74 Bootstrap.instance = new Bootstrap();
75 }
76 return Bootstrap.instance;
77 }
78
79 public async start(): Promise<void> {
80 if (isMainThread && !this.started) {
81 try {
82 this.initialize();
83 await this.storage?.open();
84 await this.workerImplementation.start();
85 this.uiServer?.start();
86 const stationTemplateUrls = Configuration.getStationTemplateUrls();
87 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
88 // Start ChargingStation object in worker thread
89 if (!Utils.isEmptyArray(stationTemplateUrls)) {
90 for (const stationTemplateUrl of stationTemplateUrls) {
91 try {
92 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
93 for (let index = 1; index <= nbStations; index++) {
94 await this.startChargingStation(index, stationTemplateUrl);
95 }
96 } catch (error) {
97 console.error(
98 chalk.red(
99 'Error at starting charging station with template file ' +
100 stationTemplateUrl.file +
101 ': '
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(missingChargingStationsConfigurationExitCode);
112 }
113 if (this.numberOfChargingStations === 0) {
114 console.warn(
115 chalk.yellow('No charging station template enabled in configuration, exiting')
116 );
117 process.exit(noChargingStationTemplatesExitCode);
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) {
150 await this.workerImplementation.stop();
151 this.workerImplementation = null;
152 this.uiServer?.stop();
153 await this.storage?.close();
154 } else {
155 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
156 }
157 this.started = false;
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 &&
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 (
181 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
182 ) => void,
183 }
184 ));
185 }
186
187 private messageHandler(
188 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
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
226 private workerEventStarted(data: ChargingStationData) {
227 this.uiServer?.chargingStations.set(data.hashId, data);
228 ++this.numberOfStartedChargingStations;
229 }
230
231 private workerEventStopped(data: ChargingStationData) {
232 this.uiServer?.chargingStations.set(data.hashId, data);
233 --this.numberOfStartedChargingStations;
234 }
235
236 private workerEventUpdated(data: ChargingStationData) {
237 this.uiServer?.chargingStations.set(data.hashId, data);
238 }
239
240 private workerEventPerformanceStatistics = (data: Statistics) => {
241 this.storage.storePerformanceStatistics(data) as void;
242 };
243
244 private initialize() {
245 this.numberOfChargingStationTemplates = 0;
246 this.numberOfChargingStations = 0;
247 this.numberOfStartedChargingStations = 0;
248 this.initializeWorkerImplementation();
249 }
250
251 private async startChargingStation(
252 index: number,
253 stationTemplateUrl: StationTemplateUrl
254 ): Promise<void> {
255 const workerData: ChargingStationWorkerData = {
256 index,
257 templateFile: path.join(
258 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
259 'assets',
260 'station-templates',
261 stationTemplateUrl.file
262 ),
263 };
264 await this.workerImplementation.addElement(workerData);
265 ++this.numberOfChargingStations;
266 }
267
268 private logPrefix(): string {
269 return Utils.logPrefix(' Bootstrap |');
270 }
271 }