Add a configuration section for the UI WS server
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { ChargingStationWorkerData, ChargingStationWorkerMessage, ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
4
5 import Configuration from '../utils/Configuration';
6 import { Storage } from '../performance/storage/Storage';
7 import { StorageFactory } from '../performance/storage/StorageFactory';
8 import { UIServiceUtils } from './UIWebSocketServices/UIServiceUtils';
9 import UIWebSocketServer from './UIWebSocketServer';
10 import Utils from '../utils/Utils';
11 import WorkerAbstract from '../worker/WorkerAbstract';
12 import WorkerFactory from '../worker/WorkerFactory';
13 import chalk from 'chalk';
14 import { isMainThread } from 'worker_threads';
15 import path from 'path';
16 import { version } from '../../package.json';
17
18 export default class Bootstrap {
19 private static instance: Bootstrap | null = null;
20 private workerImplementation: WorkerAbstract | null = null;
21 private readonly uiWebSocketServer!: UIWebSocketServer;
22 private readonly storage!: Storage;
23 private numberOfChargingStations: number;
24 private readonly version: string = version;
25 private started: boolean;
26 private readonly workerScript: string;
27
28 private constructor() {
29 this.started = false;
30 this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'ChargingStationWorker.js');
31 this.initWorkerImplementation();
32 Configuration.getUIWebSocketServer().enabled && (this.uiWebSocketServer = new UIWebSocketServer({
33 ...Configuration.getUIWebSocketServer().options, handleProtocols: UIServiceUtils.handleProtocols
34 }));
35 Configuration.getPerformanceStorage().enabled && (this.storage = StorageFactory.getStorage(
36 Configuration.getPerformanceStorage().type,
37 Configuration.getPerformanceStorage().URI,
38 this.logPrefix()
39 ));
40 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
41 }
42
43 public static getInstance(): Bootstrap {
44 if (!Bootstrap.instance) {
45 Bootstrap.instance = new Bootstrap();
46 }
47 return Bootstrap.instance;
48 }
49
50 public async start(): Promise<void> {
51 if (isMainThread && !this.started) {
52 try {
53 this.numberOfChargingStations = 0;
54 await this.storage?.open();
55 await this.workerImplementation.start();
56 this.uiWebSocketServer?.start();
57 // Start ChargingStation object in worker thread
58 if (Configuration.getStationTemplateURLs()) {
59 for (const stationURL of Configuration.getStationTemplateURLs()) {
60 try {
61 const nbStations = stationURL.numberOfStations ?? 0;
62 for (let index = 1; index <= nbStations; index++) {
63 const workerData: ChargingStationWorkerData = {
64 index,
65 templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationURL.file))
66 };
67 await this.workerImplementation.addElement(workerData);
68 this.numberOfChargingStations++;
69 }
70 } catch (error) {
71 console.error(chalk.red('Charging station start with template file ' + stationURL.file + ' error '), error);
72 }
73 }
74 } else {
75 console.warn(chalk.yellow('No stationTemplateURLs defined in configuration, exiting'));
76 }
77 if (this.numberOfChargingStations === 0) {
78 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
79 } else {
80 console.log(chalk.green(`Charging stations simulator ${this.version} started with ${this.numberOfChargingStations.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${this.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${this.workerImplementation.maxElementsPerWorker ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`));
81 }
82 this.started = true;
83 } catch (error) {
84 console.error(chalk.red('Bootstrap start error '), error);
85 }
86 } else {
87 console.error(chalk.red('Cannot start an already started charging stations simulator'));
88 }
89 }
90
91 public async stop(): Promise<void> {
92 if (isMainThread && this.started) {
93 await this.workerImplementation.stop();
94 this.uiWebSocketServer?.stop();
95 await this.storage?.close();
96 } else {
97 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
98 }
99 this.started = false;
100 }
101
102 public async restart(): Promise<void> {
103 await this.stop();
104 this.initWorkerImplementation();
105 await this.start();
106 }
107
108 private initWorkerImplementation(): void {
109 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
110 {
111 startDelay: Configuration.getWorkerStartDelay(),
112 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
113 poolMinSize: Configuration.getWorkerPoolMinSize(),
114 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
115 poolOptions: {
116 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
117 },
118 messageHandler: async (msg: ChargingStationWorkerMessage) => {
119 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
120 this.uiWebSocketServer.uiService.chargingStations.add(msg.data.id);
121 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
122 this.uiWebSocketServer.uiService.chargingStations.delete(msg.data.id);
123 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
124 await this.storage.storePerformanceStatistics(msg.data);
125 }
126 }
127 });
128 }
129
130 private logPrefix(): string {
131 return Utils.logPrefix(' Bootstrap |');
132 }
133 }