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