Ensure that workerSet always properly start a worker at init
[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 numberOfChargingStationTemplates!: number;
33 private numberOfChargingStations!: number;
34 private readonly version: string = version;
35 private started: boolean;
36 private readonly workerScript: string;
37
38 private constructor() {
39 this.started = false;
40 this.workerScript = path.join(
41 path.resolve(__dirname, '../'),
42 'charging-station',
43 'ChargingStationWorker.js'
44 );
45 this.initialize();
46 this.initWorkerImplementation();
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.getWorkerPoolMinSize().toString()}/`
113 : ''
114 }${this.workerImplementation.size}${
115 ChargingStationUtils.workerPoolInUse()
116 ? `/${Configuration.getWorkerPoolMaxSize().toString()}`
117 : ''
118 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' 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.uiServer?.stop();
139 await this.storage?.close();
140 } else {
141 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
142 }
143 this.started = false;
144 }
145
146 public async restart(): Promise<void> {
147 await this.stop();
148 this.initialize();
149 this.initWorkerImplementation();
150 await this.start();
151 }
152
153 private initWorkerImplementation(): void {
154 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
155 this.workerScript,
156 Configuration.getWorkerProcess(),
157 {
158 workerStartDelay: Configuration.getWorkerStartDelay(),
159 elementStartDelay: Configuration.getElementStartDelay(),
160 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
161 poolMinSize: Configuration.getWorkerPoolMinSize(),
162 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
163 poolOptions: {
164 workerChoiceStrategy: Configuration.getWorkerPoolStrategy(),
165 },
166 messageHandler: async (msg: ChargingStationWorkerMessage) => {
167 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
168 this.uiServer.chargingStations.add(msg.data.id as string);
169 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
170 this.uiServer.chargingStations.delete(msg.data.id as string);
171 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
172 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
173 }
174 },
175 }
176 );
177 }
178
179 private initialize() {
180 this.numberOfChargingStations = 0;
181 this.numberOfChargingStationTemplates = 0;
182 }
183
184 private async startChargingStation(
185 index: number,
186 stationTemplateUrl: StationTemplateUrl
187 ): Promise<void> {
188 const workerData: ChargingStationWorkerData = {
189 index,
190 templateFile: path.join(
191 path.resolve(__dirname, '../'),
192 'assets',
193 'station-templates',
194 path.basename(stationTemplateUrl.file)
195 ),
196 };
197 await this.workerImplementation.addElement(workerData);
198 this.numberOfChargingStations++;
199 }
200
201 private logPrefix(): string {
202 return Utils.logPrefix(' Bootstrap |');
203 }
204 }