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