Improve and unify log messages
[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 type { 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 type { StationTemplateUrl } from '../types/ConfigurationData';
21 import type Statistics from '../types/Statistics';
22 import Configuration from '../utils/Configuration';
23 import logger from '../utils/Logger';
24 import Utils from '../utils/Utils';
25 import type WorkerAbstract from '../worker/WorkerAbstract';
26 import WorkerFactory from '../worker/WorkerFactory';
27 import { ChargingStationUtils } from './ChargingStationUtils';
28 import type { AbstractUIServer } from './ui-server/AbstractUIServer';
29 import UIServerFactory from './ui-server/UIServerFactory';
30
31 const moduleName = 'Bootstrap';
32
33 const missingChargingStationsConfigurationExitCode = 1;
34 const noChargingStationTemplatesExitCode = 2;
35
36 export class Bootstrap {
37 private static instance: Bootstrap | null = null;
38 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
39 private readonly uiServer!: AbstractUIServer;
40 private readonly storage!: Storage;
41 private numberOfChargingStationTemplates!: number;
42 private numberOfChargingStations!: number;
43 private numberOfStartedChargingStations!: number;
44 private readonly version: string = version;
45 private started: boolean;
46 private readonly workerScript: string;
47
48 private constructor() {
49 this.started = false;
50 this.workerImplementation = null;
51 this.workerScript = path.join(
52 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
53 'charging-station',
54 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
55 );
56 this.initialize();
57 Configuration.getUIServer().enabled === true &&
58 (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer()));
59 Configuration.getPerformanceStorage().enabled === true &&
60 (this.storage = StorageFactory.getStorage(
61 Configuration.getPerformanceStorage().type,
62 Configuration.getPerformanceStorage().uri,
63 this.logPrefix()
64 ));
65 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
66 }
67
68 public static getInstance(): Bootstrap {
69 if (Bootstrap.instance === null) {
70 Bootstrap.instance = new Bootstrap();
71 }
72 return Bootstrap.instance;
73 }
74
75 public async start(): Promise<void> {
76 if (isMainThread && this.started === false) {
77 try {
78 this.initialize();
79 await this.storage?.open();
80 await this.workerImplementation.start();
81 this.uiServer?.start();
82 const stationTemplateUrls = Configuration.getStationTemplateUrls();
83 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
84 // Start ChargingStation object in worker thread
85 if (!Utils.isEmptyArray(stationTemplateUrls)) {
86 for (const stationTemplateUrl of stationTemplateUrls) {
87 try {
88 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
89 for (let index = 1; index <= nbStations; index++) {
90 await this.startChargingStation(index, stationTemplateUrl);
91 }
92 } catch (error) {
93 console.error(
94 chalk.red(
95 'Error at starting charging station with template file ' +
96 stationTemplateUrl.file +
97 ': '
98 ),
99 error
100 );
101 }
102 }
103 } else {
104 console.warn(
105 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
106 );
107 process.exit(missingChargingStationsConfigurationExitCode);
108 }
109 if (this.numberOfChargingStations === 0) {
110 console.warn(
111 chalk.yellow('No charging station template enabled in configuration, exiting')
112 );
113 process.exit(noChargingStationTemplatesExitCode);
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 === true) {
146 await this.workerImplementation.stop();
147 this.workerImplementation = null;
148 this.uiServer?.stop();
149 await this.storage?.close();
150 this.started = false;
151 } else {
152 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
153 }
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 === null &&
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.stationInfo.hashId, data);
224 ++this.numberOfStartedChargingStations;
225 };
226
227 private workerEventStopped = (data: ChargingStationData) => {
228 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
229 --this.numberOfStartedChargingStations;
230 };
231
232 private workerEventUpdated = (data: ChargingStationData) => {
233 this.uiServer?.chargingStations.set(data.stationInfo.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 }