2bc650cc32ec9116f638b33da3eb1d4e4a361d21
[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 export default class Bootstrap {
36 private static instance: Bootstrap | null = null;
37 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
38 private readonly uiServer!: AbstractUIServer;
39 private readonly storage!: Storage;
40 private numberOfChargingStationTemplates!: number;
41 private numberOfChargingStations!: number;
42 private numberOfStartedChargingStations!: number;
43 private readonly version: string = version;
44 private started: boolean;
45 private readonly workerScript: string;
46
47 private constructor() {
48 this.started = false;
49 this.workerScript = path.join(
50 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
51 'charging-station',
52 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
53 );
54 this.initialize();
55 Configuration.getUIServer().enabled &&
56 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
57 ...Configuration.getUIServer().options,
58 handleProtocols: UIServiceUtils.handleProtocols,
59 }));
60 Configuration.getPerformanceStorage().enabled &&
61 (this.storage = StorageFactory.getStorage(
62 Configuration.getPerformanceStorage().type,
63 Configuration.getPerformanceStorage().uri,
64 this.logPrefix()
65 ));
66 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
67 }
68
69 public static getInstance(): Bootstrap {
70 if (Bootstrap.instance === null) {
71 Bootstrap.instance = new Bootstrap();
72 }
73 return Bootstrap.instance;
74 }
75
76 public async start(): Promise<void> {
77 if (isMainThread && !this.started) {
78 try {
79 this.initialize();
80 await this.storage?.open();
81 await this.workerImplementation.start();
82 this.uiServer?.start();
83 const stationTemplateUrls = Configuration.getStationTemplateUrls();
84 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
85 // Start ChargingStation object in worker thread
86 if (!Utils.isEmptyArray(stationTemplateUrls)) {
87 for (const stationTemplateUrl of stationTemplateUrls) {
88 try {
89 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
90 for (let index = 1; index <= nbStations; index++) {
91 await this.startChargingStation(index, stationTemplateUrl);
92 }
93 } catch (error) {
94 console.error(
95 chalk.red(
96 'Error at starting charging station with template file ' +
97 stationTemplateUrl.file +
98 ': '
99 ),
100 error
101 );
102 }
103 }
104 } else {
105 console.warn(
106 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
107 );
108 }
109 if (this.numberOfChargingStations === 0) {
110 console.warn(
111 chalk.yellow('No charging station template enabled in configuration, exiting')
112 );
113 process.exit();
114 } else {
115 console.info(
116 chalk.green(
117 `Charging stations simulator ${
118 this.version
119 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
120 ChargingStationUtils.workerDynamicPoolInUse()
121 ? `${Configuration.getWorker().poolMinSize.toString()}/`
122 : ''
123 }${this.workerImplementation.size}${
124 ChargingStationUtils.workerPoolInUse()
125 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
126 : ''
127 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
128 this.workerImplementation.maxElementsPerWorker
129 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
130 : ''
131 }`
132 )
133 );
134 }
135 this.started = true;
136 } catch (error) {
137 console.error(chalk.red('Bootstrap start error '), error);
138 }
139 } else {
140 console.error(chalk.red('Cannot start an already started charging stations simulator'));
141 }
142 }
143
144 public async stop(): Promise<void> {
145 if (isMainThread && this.started) {
146 await this.workerImplementation.stop();
147 this.workerImplementation = null;
148 this.uiServer?.stop();
149 await this.storage?.close();
150 } else {
151 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
152 }
153 this.started = false;
154 }
155
156 public async restart(): Promise<void> {
157 await this.stop();
158 this.initialize();
159 await this.start();
160 }
161
162 private initializeWorkerImplementation(): void {
163 !this.workerImplementation &&
164 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
165 this.workerScript,
166 Configuration.getWorker().processType,
167 {
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,
173 poolOptions: {
174 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
175 },
176 messageHandler: this.messageHandler.bind(this) as (
177 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
178 ) => void,
179 }
180 ));
181 }
182
183 private messageHandler(
184 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
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
222 private workerEventStarted(data: ChargingStationData) {
223 this.uiServer?.chargingStations.set(data.hashId, data);
224 ++this.numberOfStartedChargingStations;
225 }
226
227 private workerEventStopped(data: ChargingStationData) {
228 this.uiServer?.chargingStations.set(data.hashId, data);
229 --this.numberOfStartedChargingStations;
230 }
231
232 private workerEventUpdated(data: ChargingStationData) {
233 this.uiServer?.chargingStations.set(data.hashId, data);
234 }
235
236 private workerEventPerformanceStatistics = (data: Statistics) => {
237 this.storage.storePerformanceStatistics(data) as void;
238 };
239
240 private initialize() {
241 this.numberOfChargingStationTemplates = 0;
242 this.numberOfChargingStations = 0;
243 this.numberOfStartedChargingStations = 0;
244 this.initializeWorkerImplementation();
245 }
246
247 private async startChargingStation(
248 index: number,
249 stationTemplateUrl: StationTemplateUrl
250 ): Promise<void> {
251 const workerData: ChargingStationWorkerData = {
252 index,
253 templateFile: path.join(
254 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
255 'assets',
256 'station-templates',
257 stationTemplateUrl.file
258 ),
259 };
260 await this.workerImplementation.addElement(workerData);
261 ++this.numberOfChargingStations;
262 }
263
264 private logPrefix(): string {
265 return Utils.logPrefix(' Bootstrap |');
266 }
267 }