Simplify ATG logPrefix() method
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
e7aeea18
JB
3import {
4 ChargingStationWorkerData,
5 ChargingStationWorkerMessage,
6 ChargingStationWorkerMessageEvents,
7} from '../types/ChargingStationWorker';
81797102 8
fe94fce0
JB
9import { AbstractUIServer } from './ui-server/AbstractUIServer';
10import { ApplicationProtocol } from '../types/UIProtocol';
17ac262c 11import { ChargingStationUtils } from './ChargingStationUtils';
ded13d97 12import Configuration from '../utils/Configuration';
717c1e56 13import { StationTemplateUrl } from '../types/ConfigurationData';
c3ee95af 14import Statistics from '../types/Statistics';
a6b3c6c3
JB
15import { Storage } from '../performance/storage/Storage';
16import { StorageFactory } from '../performance/storage/StorageFactory';
fe94fce0 17import UIServerFactory from './ui-server/UIServerFactory';
675fa8e3 18import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
ded13d97 19import Utils from '../utils/Utils';
fd1fdf1b 20import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 21import WorkerFactory from '../worker/WorkerFactory';
8eac9a09 22import chalk from 'chalk';
ded13d97 23import { isMainThread } from 'worker_threads';
bf1866b2 24import path from 'path';
84e52c2c 25import { version } from '../../package.json';
ded13d97
JB
26
27export default class Bootstrap {
535aaa27 28 private static instance: Bootstrap | null = null;
c3ee95af 29 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
fe94fce0 30 private readonly uiServer!: AbstractUIServer;
6a49ad23 31 private readonly storage!: Storage;
7c72977b
JB
32 private numberOfChargingStationTemplates!: number;
33 private numberOfChargingStations!: number;
9e23580d 34 private readonly version: string = version;
eb87fe87 35 private started: boolean;
9e23580d 36 private readonly workerScript: string;
ded13d97
JB
37
38 private constructor() {
eb87fe87 39 this.started = false;
e7aeea18
JB
40 this.workerScript = path.join(
41 path.resolve(__dirname, '../'),
42 'charging-station',
43 'ChargingStationWorker.js'
44 );
7c72977b 45 this.initialize();
8df3f0a9 46 this.initWorkerImplementation();
675fa8e3 47 Configuration.getUIServer().enabled &&
fe94fce0 48 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
675fa8e3 49 ...Configuration.getUIServer().options,
e7aeea18
JB
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 ));
7874b0b1 58 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
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> {
eb87fe87 69 if (isMainThread && !this.started) {
ded13d97 70 try {
7c72977b 71 this.initialize();
6a49ad23 72 await this.storage?.open();
a4bc2942 73 await this.workerImplementation.start();
675fa8e3 74 this.uiServer?.start();
1f5df42a 75 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 76 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 77 // Start ChargingStation object in worker thread
1f5df42a
JB
78 if (stationTemplateUrls) {
79 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 80 try {
1f5df42a 81 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 82 for (let index = 1; index <= nbStations; index++) {
717c1e56 83 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
84 }
85 } catch (error) {
e7aeea18
JB
86 console.error(
87 chalk.red(
3d25cc86
JB
88 'Error at starting charging station with template file ' +
89 stationTemplateUrl.file +
90 ': '
e7aeea18
JB
91 ),
92 error
93 );
ded13d97
JB
94 }
95 }
96 } else {
3d25cc86 97 console.warn(chalk.yellow("No 'stationTemplateUrls' defined in configuration, exiting"));
ded13d97 98 }
a4bc2942 99 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
100 console.warn(
101 chalk.yellow('No charging station template enabled in configuration, exiting')
102 );
ded13d97 103 } else {
e7aeea18
JB
104 console.log(
105 chalk.green(
106 `Charging stations simulator ${
107 this.version
7c72977b 108 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 109 ChargingStationUtils.workerDynamicPoolInUse()
e7aeea18
JB
110 ? `${Configuration.getWorkerPoolMinSize().toString()}/`
111 : ''
112 }${this.workerImplementation.size}${
17ac262c
JB
113 ChargingStationUtils.workerPoolInUse()
114 ? `/${Configuration.getWorkerPoolMaxSize().toString()}`
115 : ''
e7aeea18
JB
116 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
117 this.workerImplementation.maxElementsPerWorker
118 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
119 : ''
120 }`
121 )
122 );
ded13d97 123 }
eb87fe87 124 this.started = true;
ded13d97 125 } catch (error) {
8eac9a09 126 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 127 }
b322b8b4
JB
128 } else {
129 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
130 }
131 }
132
133 public async stop(): Promise<void> {
eb87fe87 134 if (isMainThread && this.started) {
a4bc2942 135 await this.workerImplementation.stop();
675fa8e3 136 this.uiServer?.stop();
6a49ad23 137 await this.storage?.close();
b322b8b4
JB
138 } else {
139 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 140 }
eb87fe87 141 this.started = false;
ded13d97
JB
142 }
143
144 public async restart(): Promise<void> {
145 await this.stop();
7c72977b 146 this.initialize();
535aaa27 147 this.initWorkerImplementation();
ded13d97
JB
148 await this.start();
149 }
150
2a370053 151 private initWorkerImplementation(): void {
e7aeea18
JB
152 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
153 this.workerScript,
154 Configuration.getWorkerProcess(),
8df3f0a9 155 {
4bfd80fa
JB
156 workerStartDelay: Configuration.getWorkerStartDelay(),
157 elementStartDelay: Configuration.getElementStartDelay(),
8df3f0a9
JB
158 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
159 poolMinSize: Configuration.getWorkerPoolMinSize(),
160 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
161 poolOptions: {
e7aeea18 162 workerChoiceStrategy: Configuration.getWorkerPoolStrategy(),
ffd71f2c 163 },
98dc07fa 164 messageHandler: async (msg: ChargingStationWorkerMessage) => {
ee0f106b 165 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
675fa8e3 166 this.uiServer.chargingStations.add(msg.data.id as string);
ee0f106b 167 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
675fa8e3 168 this.uiServer.chargingStations.delete(msg.data.id as string);
ee0f106b 169 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
c3ee95af 170 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
ffd71f2c 171 }
e7aeea18
JB
172 },
173 }
174 );
ded13d97 175 }
81797102 176
7c72977b
JB
177 private initialize() {
178 this.numberOfChargingStations = 0;
179 this.numberOfChargingStationTemplates = 0;
180 }
181
e7aeea18
JB
182 private async startChargingStation(
183 index: number,
184 stationTemplateUrl: StationTemplateUrl
185 ): Promise<void> {
717c1e56
JB
186 const workerData: ChargingStationWorkerData = {
187 index,
e7aeea18
JB
188 templateFile: path.join(
189 path.resolve(__dirname, '../'),
190 'assets',
191 'station-templates',
192 path.basename(stationTemplateUrl.file)
193 ),
717c1e56
JB
194 };
195 await this.workerImplementation.addElement(workerData);
196 this.numberOfChargingStations++;
197 }
198
81797102 199 private logPrefix(): string {
689dca78 200 return Utils.logPrefix(' Bootstrap |');
81797102 201 }
ded13d97 202}