ed9f1bef259640df365739f65ab5a4a8913c24d2
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import {
4 ChargingStationWorkerData,
5 ChargingStationWorkerMessage,
6 ChargingStationWorkerMessageEvents,
7 } from '../types/ChargingStationWorker';
8
9 import { AbstractUIServer } from './ui-server/AbstractUIServer';
10 import { ApplicationProtocol } from '../types/UIProtocol';
11 import { ChargingStationUtils } from './ChargingStationUtils';
12 import Configuration from '../utils/Configuration';
13 import { StationTemplateUrl } from '../types/ConfigurationData';
14 import Statistics from '../types/Statistics';
15 import { Storage } from '../performance/storage/Storage';
16 import { StorageFactory } from '../performance/storage/StorageFactory';
17 import UIServerFactory from './ui-server/UIServerFactory';
18 import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
19 import Utils from '../utils/Utils';
20 import WorkerAbstract from '../worker/WorkerAbstract';
21 import WorkerFactory from '../worker/WorkerFactory';
22 import chalk from 'chalk';
23 import { fileURLToPath } from 'url';
24 import { isMainThread } from 'worker_threads';
25 import path from 'path';
26 import { version } from '../../package.json';
27
28 export default class Bootstrap {
29 private static instance: Bootstrap | null = null;
30 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
31 private readonly uiServer!: AbstractUIServer;
32 private readonly storage!: Storage;
33 private numberOfChargingStationTemplates!: number;
34 private numberOfChargingStations!: number;
35 private readonly version: string = version;
36 private started: boolean;
37 private readonly workerScript: string;
38
39 private constructor() {
40 this.started = false;
41 this.workerScript = path.join(
42 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
43 'charging-station',
44 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
45 );
46 this.initialize();
47 Configuration.getUIServer().enabled &&
48 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
49 ...Configuration.getUIServer().options,
50 handleProtocols: UIServiceUtils.handleProtocols,
51 }));
52 Configuration.getPerformanceStorage().enabled &&
53 (this.storage = StorageFactory.getStorage(
54 Configuration.getPerformanceStorage().type,
55 Configuration.getPerformanceStorage().uri,
56 this.logPrefix()
57 ));
58 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
59 }
60
61 public static getInstance(): Bootstrap {
62 if (!Bootstrap.instance) {
63 Bootstrap.instance = new Bootstrap();
64 }
65 return Bootstrap.instance;
66 }
67
68 public async start(): Promise<void> {
69 if (isMainThread && !this.started) {
70 try {
71 this.initialize();
72 await this.storage?.open();
73 await this.workerImplementation.start();
74 this.uiServer?.start();
75 const stationTemplateUrls = Configuration.getStationTemplateUrls();
76 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
77 // Start ChargingStation object in worker thread
78 if (!Utils.isEmptyArray(stationTemplateUrls)) {
79 for (const stationTemplateUrl of stationTemplateUrls) {
80 try {
81 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
82 for (let index = 1; index <= nbStations; index++) {
83 await this.startChargingStation(index, stationTemplateUrl);
84 }
85 } catch (error) {
86 console.error(
87 chalk.red(
88 'Error at starting charging station with template file ' +
89 stationTemplateUrl.file +
90 ': '
91 ),
92 error
93 );
94 }
95 }
96 } else {
97 console.warn(
98 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
99 );
100 }
101 if (this.numberOfChargingStations === 0) {
102 console.warn(
103 chalk.yellow('No charging station template enabled in configuration, exiting')
104 );
105 } else {
106 console.log(
107 chalk.green(
108 `Charging stations simulator ${
109 this.version
110 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
111 ChargingStationUtils.workerDynamicPoolInUse()
112 ? `${Configuration.getWorker().poolMinSize.toString()}/`
113 : ''
114 }${this.workerImplementation.size}${
115 ChargingStationUtils.workerPoolInUse()
116 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
117 : ''
118 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
119 this.workerImplementation.maxElementsPerWorker
120 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
121 : ''
122 }`
123 )
124 );
125 }
126 this.started = true;
127 } catch (error) {
128 console.error(chalk.red('Bootstrap start error '), error);
129 }
130 } else {
131 console.error(chalk.red('Cannot start an already started charging stations simulator'));
132 }
133 }
134
135 public async stop(): Promise<void> {
136 if (isMainThread && this.started) {
137 await this.workerImplementation.stop();
138 this.workerImplementation = null;
139 this.uiServer?.stop();
140 await this.storage?.close();
141 } else {
142 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
143 }
144 this.started = false;
145 }
146
147 public async restart(): Promise<void> {
148 await this.stop();
149 this.initialize();
150 await this.start();
151 }
152
153 private initializeWorkerImplementation(): void {
154 !this.workerImplementation &&
155 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
156 this.workerScript,
157 Configuration.getWorker().processType,
158 {
159 workerStartDelay: Configuration.getWorker().startDelay,
160 elementStartDelay: Configuration.getWorker().elementStartDelay,
161 poolMaxSize: Configuration.getWorker().poolMaxSize,
162 poolMinSize: Configuration.getWorker().poolMinSize,
163 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
164 poolOptions: {
165 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
166 },
167 messageHandler: async (msg: ChargingStationWorkerMessage) => {
168 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
169 this.uiServer.chargingStations.add(msg.data.id as string);
170 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
171 this.uiServer.chargingStations.delete(msg.data.id as string);
172 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
173 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
174 }
175 },
176 }
177 ));
178 }
179
180 private initialize() {
181 this.numberOfChargingStations = 0;
182 this.numberOfChargingStationTemplates = 0;
183 this.initializeWorkerImplementation();
184 }
185
186 private async startChargingStation(
187 index: number,
188 stationTemplateUrl: StationTemplateUrl
189 ): Promise<void> {
190 const workerData: ChargingStationWorkerData = {
191 index,
192 templateFile: path.join(
193 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
194 'assets',
195 'station-templates',
196 path.basename(stationTemplateUrl.file)
197 ),
198 };
199 await this.workerImplementation.addElement(workerData);
200 this.numberOfChargingStations++;
201 }
202
203 private logPrefix(): string {
204 return Utils.logPrefix(' Bootstrap |');
205 }
206 }