Fix not initialized variables at startup
[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 { isMainThread } from 'worker_threads';
24 import path from 'path';
25 import { version } from '../../package.json';
26
27 export default class Bootstrap {
28 private static instance: Bootstrap | null = null;
29 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
30 private readonly uiServer!: AbstractUIServer;
31 private readonly storage!: Storage;
32 private numberOfChargingStations: number;
33 private readonly version: string = version;
34 private started: boolean;
35 private readonly workerScript: string;
36
37 private constructor() {
38 this.started = false;
39 this.workerScript = path.join(
40 path.resolve(__dirname, '../'),
41 'charging-station',
42 'ChargingStationWorker.js'
43 );
44 this.initWorkerImplementation();
45 Configuration.getUIServer().enabled &&
46 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
47 ...Configuration.getUIServer().options,
48 handleProtocols: UIServiceUtils.handleProtocols,
49 }));
50 Configuration.getPerformanceStorage().enabled &&
51 (this.storage = StorageFactory.getStorage(
52 Configuration.getPerformanceStorage().type,
53 Configuration.getPerformanceStorage().uri,
54 this.logPrefix()
55 ));
56 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
57 }
58
59 public static getInstance(): Bootstrap {
60 if (!Bootstrap.instance) {
61 Bootstrap.instance = new Bootstrap();
62 }
63 return Bootstrap.instance;
64 }
65
66 public async start(): Promise<void> {
67 if (isMainThread && !this.started) {
68 try {
69 this.numberOfChargingStations = 0;
70 await this.storage?.open();
71 await this.workerImplementation.start();
72 this.uiServer?.start();
73 const stationTemplateUrls = Configuration.getStationTemplateUrls();
74 // Start ChargingStation object in worker thread
75 if (stationTemplateUrls) {
76 for (const stationTemplateUrl of stationTemplateUrls) {
77 try {
78 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
79 for (let index = 1; index <= nbStations; index++) {
80 await this.startChargingStation(index, stationTemplateUrl);
81 }
82 } catch (error) {
83 console.error(
84 chalk.red(
85 'Error at starting charging station with template file ' +
86 stationTemplateUrl.file +
87 ': '
88 ),
89 error
90 );
91 }
92 }
93 } else {
94 console.warn(chalk.yellow("No 'stationTemplateUrls' defined in configuration, exiting"));
95 }
96 if (this.numberOfChargingStations === 0) {
97 console.warn(
98 chalk.yellow('No charging station template enabled in configuration, exiting')
99 );
100 } else {
101 console.log(
102 chalk.green(
103 `Charging stations simulator ${
104 this.version
105 } started with ${this.numberOfChargingStations.toString()} charging station(s) and ${
106 ChargingStationUtils.workerDynamicPoolInUse()
107 ? `${Configuration.getWorkerPoolMinSize().toString()}/`
108 : ''
109 }${this.workerImplementation.size}${
110 ChargingStationUtils.workerPoolInUse()
111 ? `/${Configuration.getWorkerPoolMaxSize().toString()}`
112 : ''
113 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
114 this.workerImplementation.maxElementsPerWorker
115 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
116 : ''
117 }`
118 )
119 );
120 }
121 this.started = true;
122 } catch (error) {
123 console.error(chalk.red('Bootstrap start error '), error);
124 }
125 } else {
126 console.error(chalk.red('Cannot start an already started charging stations simulator'));
127 }
128 }
129
130 public async stop(): Promise<void> {
131 if (isMainThread && this.started) {
132 await this.workerImplementation.stop();
133 this.uiServer?.stop();
134 await this.storage?.close();
135 } else {
136 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
137 }
138 this.started = false;
139 }
140
141 public async restart(): Promise<void> {
142 await this.stop();
143 this.initWorkerImplementation();
144 await this.start();
145 }
146
147 private initWorkerImplementation(): void {
148 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
149 this.workerScript,
150 Configuration.getWorkerProcess(),
151 {
152 workerStartDelay: Configuration.getWorkerStartDelay(),
153 elementStartDelay: Configuration.getElementStartDelay(),
154 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
155 poolMinSize: Configuration.getWorkerPoolMinSize(),
156 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
157 poolOptions: {
158 workerChoiceStrategy: Configuration.getWorkerPoolStrategy(),
159 },
160 messageHandler: async (msg: ChargingStationWorkerMessage) => {
161 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
162 this.uiServer.chargingStations.add(msg.data.id as string);
163 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
164 this.uiServer.chargingStations.delete(msg.data.id as string);
165 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
166 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
167 }
168 },
169 }
170 );
171 }
172
173 private async startChargingStation(
174 index: number,
175 stationTemplateUrl: StationTemplateUrl
176 ): Promise<void> {
177 const workerData: ChargingStationWorkerData = {
178 index,
179 templateFile: path.join(
180 path.resolve(__dirname, '../'),
181 'assets',
182 'station-templates',
183 path.basename(stationTemplateUrl.file)
184 ),
185 };
186 await this.workerImplementation.addElement(workerData);
187 this.numberOfChargingStations++;
188 }
189
190 private logPrefix(): string {
191 return Utils.logPrefix(' Bootstrap |');
192 }
193 }