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