Commit | Line | Data |
---|---|---|
b4d34251 JB |
1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
8114d10e JB |
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'; | |
32de5a57 | 10 | import BaseError from '../exception/BaseError'; |
6c1761d4 | 11 | import type { Storage } from '../performance/storage/Storage'; |
8114d10e | 12 | import { StorageFactory } from '../performance/storage/StorageFactory'; |
e7aeea18 | 13 | import { |
32de5a57 | 14 | ChargingStationData, |
e7aeea18 JB |
15 | ChargingStationWorkerData, |
16 | ChargingStationWorkerMessage, | |
53e5fd67 | 17 | ChargingStationWorkerMessageData, |
e7aeea18 JB |
18 | ChargingStationWorkerMessageEvents, |
19 | } from '../types/ChargingStationWorker'; | |
6c1761d4 JB |
20 | import type { StationTemplateUrl } from '../types/ConfigurationData'; |
21 | import type Statistics from '../types/Statistics'; | |
8114d10e | 22 | import Configuration from '../utils/Configuration'; |
32de5a57 | 23 | import logger from '../utils/Logger'; |
ded13d97 | 24 | import Utils from '../utils/Utils'; |
6c1761d4 | 25 | import type WorkerAbstract from '../worker/WorkerAbstract'; |
ded13d97 | 26 | import WorkerFactory from '../worker/WorkerFactory'; |
8114d10e | 27 | import { ChargingStationUtils } from './ChargingStationUtils'; |
6c1761d4 | 28 | import type { AbstractUIServer } from './ui-server/AbstractUIServer'; |
8114d10e | 29 | import UIServerFactory from './ui-server/UIServerFactory'; |
ded13d97 | 30 | |
32de5a57 LM |
31 | const moduleName = 'Bootstrap'; |
32 | ||
e4cb2c14 JB |
33 | const missingChargingStationsConfigurationExitCode = 1; |
34 | const noChargingStationTemplatesExitCode = 2; | |
35 | ||
5a010bf0 | 36 | export class Bootstrap { |
535aaa27 | 37 | private static instance: Bootstrap | null = null; |
c3ee95af | 38 | private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null; |
fe94fce0 | 39 | private readonly uiServer!: AbstractUIServer; |
6a49ad23 | 40 | private readonly storage!: Storage; |
7c72977b JB |
41 | private numberOfChargingStationTemplates!: number; |
42 | private numberOfChargingStations!: number; | |
89b7a234 | 43 | private numberOfStartedChargingStations!: number; |
9e23580d | 44 | private readonly version: string = version; |
eb87fe87 | 45 | private started: boolean; |
9e23580d | 46 | private readonly workerScript: string; |
ded13d97 JB |
47 | |
48 | private constructor() { | |
eb87fe87 | 49 | this.started = false; |
e7aeea18 | 50 | this.workerScript = path.join( |
0d8140bd | 51 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'), |
e7aeea18 | 52 | 'charging-station', |
44a95b7f | 53 | 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url)) |
e7aeea18 | 54 | ); |
7c72977b | 55 | this.initialize(); |
5af9aa8a JB |
56 | Configuration.getUIServer().enabled === true && |
57 | (this.uiServer = UIServerFactory.getUIServerImplementation( | |
eb3abc4f JB |
58 | Configuration.getUIServer().type, |
59 | Configuration.getUIServer() | |
5af9aa8a | 60 | )); |
eb3abc4f | 61 | Configuration.getPerformanceStorage().enabled === true && |
e7aeea18 JB |
62 | (this.storage = StorageFactory.getStorage( |
63 | Configuration.getPerformanceStorage().type, | |
64 | Configuration.getPerformanceStorage().uri, | |
65 | this.logPrefix() | |
66 | )); | |
7874b0b1 | 67 | Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart()); |
ded13d97 JB |
68 | } |
69 | ||
70 | public static getInstance(): Bootstrap { | |
1ca780f9 | 71 | if (Bootstrap.instance === null) { |
ded13d97 JB |
72 | Bootstrap.instance = new Bootstrap(); |
73 | } | |
74 | return Bootstrap.instance; | |
75 | } | |
76 | ||
77 | public async start(): Promise<void> { | |
452a82ca | 78 | if (isMainThread && this.started === false) { |
ded13d97 | 79 | try { |
7c72977b | 80 | this.initialize(); |
6a49ad23 | 81 | await this.storage?.open(); |
a4bc2942 | 82 | await this.workerImplementation.start(); |
675fa8e3 | 83 | this.uiServer?.start(); |
1f5df42a | 84 | const stationTemplateUrls = Configuration.getStationTemplateUrls(); |
7c72977b | 85 | this.numberOfChargingStationTemplates = stationTemplateUrls.length; |
ded13d97 | 86 | // Start ChargingStation object in worker thread |
45bd0627 | 87 | if (!Utils.isEmptyArray(stationTemplateUrls)) { |
1f5df42a | 88 | for (const stationTemplateUrl of stationTemplateUrls) { |
ded13d97 | 89 | try { |
1f5df42a | 90 | const nbStations = stationTemplateUrl.numberOfStations ?? 0; |
ded13d97 | 91 | for (let index = 1; index <= nbStations; index++) { |
717c1e56 | 92 | await this.startChargingStation(index, stationTemplateUrl); |
ded13d97 JB |
93 | } |
94 | } catch (error) { | |
e7aeea18 JB |
95 | console.error( |
96 | chalk.red( | |
3d25cc86 JB |
97 | 'Error at starting charging station with template file ' + |
98 | stationTemplateUrl.file + | |
99 | ': ' | |
e7aeea18 JB |
100 | ), |
101 | error | |
102 | ); | |
ded13d97 JB |
103 | } |
104 | } | |
105 | } else { | |
45bd0627 JB |
106 | console.warn( |
107 | chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting") | |
108 | ); | |
e4cb2c14 | 109 | process.exit(missingChargingStationsConfigurationExitCode); |
ded13d97 | 110 | } |
a4bc2942 | 111 | if (this.numberOfChargingStations === 0) { |
e7aeea18 JB |
112 | console.warn( |
113 | chalk.yellow('No charging station template enabled in configuration, exiting') | |
114 | ); | |
e4cb2c14 | 115 | process.exit(noChargingStationTemplatesExitCode); |
ded13d97 | 116 | } else { |
32de5a57 | 117 | console.info( |
e7aeea18 JB |
118 | chalk.green( |
119 | `Charging stations simulator ${ | |
120 | this.version | |
7c72977b | 121 | } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${ |
17ac262c | 122 | ChargingStationUtils.workerDynamicPoolInUse() |
cf2a5d9b | 123 | ? `${Configuration.getWorker().poolMinSize.toString()}/` |
e7aeea18 JB |
124 | : '' |
125 | }${this.workerImplementation.size}${ | |
17ac262c | 126 | ChargingStationUtils.workerPoolInUse() |
cf2a5d9b | 127 | ? `/${Configuration.getWorker().poolMaxSize.toString()}` |
17ac262c | 128 | : '' |
cf2a5d9b | 129 | } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${ |
e7aeea18 JB |
130 | this.workerImplementation.maxElementsPerWorker |
131 | ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` | |
132 | : '' | |
133 | }` | |
134 | ) | |
135 | ); | |
ded13d97 | 136 | } |
eb87fe87 | 137 | this.started = true; |
ded13d97 | 138 | } catch (error) { |
10d244c0 | 139 | console.error(chalk.red('Bootstrap start error: '), error); |
ded13d97 | 140 | } |
b322b8b4 JB |
141 | } else { |
142 | console.error(chalk.red('Cannot start an already started charging stations simulator')); | |
ded13d97 JB |
143 | } |
144 | } | |
145 | ||
146 | public async stop(): Promise<void> { | |
452a82ca | 147 | if (isMainThread && this.started === true) { |
a4bc2942 | 148 | await this.workerImplementation.stop(); |
b19021e2 | 149 | this.workerImplementation = null; |
675fa8e3 | 150 | this.uiServer?.stop(); |
6a49ad23 | 151 | await this.storage?.close(); |
b322b8b4 JB |
152 | } else { |
153 | console.error(chalk.red('Trying to stop the charging stations simulator while not started')); | |
ded13d97 | 154 | } |
eb87fe87 | 155 | this.started = false; |
ded13d97 JB |
156 | } |
157 | ||
158 | public async restart(): Promise<void> { | |
159 | await this.stop(); | |
7c72977b | 160 | this.initialize(); |
ded13d97 JB |
161 | await this.start(); |
162 | } | |
163 | ||
ec7f4dce JB |
164 | private initializeWorkerImplementation(): void { |
165 | !this.workerImplementation && | |
166 | (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>( | |
167 | this.workerScript, | |
cf2a5d9b | 168 | Configuration.getWorker().processType, |
ec7f4dce | 169 | { |
cf2a5d9b JB |
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, | |
ec7f4dce | 175 | poolOptions: { |
cf2a5d9b | 176 | workerChoiceStrategy: Configuration.getWorker().poolStrategy, |
ec7f4dce | 177 | }, |
32de5a57 | 178 | messageHandler: this.messageHandler.bind(this) as ( |
53e5fd67 | 179 | msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData> |
32de5a57 | 180 | ) => void, |
ec7f4dce JB |
181 | } |
182 | )); | |
ded13d97 | 183 | } |
81797102 | 184 | |
32de5a57 | 185 | private messageHandler( |
53e5fd67 | 186 | msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData> |
32de5a57 LM |
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) { | |
51c83d6f | 225 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
89b7a234 | 226 | ++this.numberOfStartedChargingStations; |
32de5a57 LM |
227 | } |
228 | ||
229 | private workerEventStopped(data: ChargingStationData) { | |
51c83d6f | 230 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
89b7a234 | 231 | --this.numberOfStartedChargingStations; |
32de5a57 LM |
232 | } |
233 | ||
234 | private workerEventUpdated(data: ChargingStationData) { | |
51c83d6f | 235 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
32de5a57 LM |
236 | } |
237 | ||
238 | private workerEventPerformanceStatistics = (data: Statistics) => { | |
239 | this.storage.storePerformanceStatistics(data) as void; | |
240 | }; | |
241 | ||
7c72977b | 242 | private initialize() { |
7c72977b | 243 | this.numberOfChargingStationTemplates = 0; |
89b7a234 JB |
244 | this.numberOfChargingStations = 0; |
245 | this.numberOfStartedChargingStations = 0; | |
ec7f4dce | 246 | this.initializeWorkerImplementation(); |
7c72977b JB |
247 | } |
248 | ||
e7aeea18 JB |
249 | private async startChargingStation( |
250 | index: number, | |
251 | stationTemplateUrl: StationTemplateUrl | |
252 | ): Promise<void> { | |
717c1e56 JB |
253 | const workerData: ChargingStationWorkerData = { |
254 | index, | |
e7aeea18 | 255 | templateFile: path.join( |
0d8140bd | 256 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'), |
e7aeea18 JB |
257 | 'assets', |
258 | 'station-templates', | |
ee5f26a2 | 259 | stationTemplateUrl.file |
e7aeea18 | 260 | ), |
717c1e56 JB |
261 | }; |
262 | await this.workerImplementation.addElement(workerData); | |
89b7a234 | 263 | ++this.numberOfChargingStations; |
717c1e56 JB |
264 | } |
265 | ||
81797102 | 266 | private logPrefix(): string { |
689dca78 | 267 | return Utils.logPrefix(' Bootstrap |'); |
81797102 | 268 | } |
ded13d97 | 269 | } |