Optimize ATG run duration handling
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
2a370053 3import { ChargingStationWorkerData, WorkerMessage, WorkerMessageEvents } from '../types/Worker';
81797102 4
ded13d97 5import Configuration from '../utils/Configuration';
a6b3c6c3
JB
6import { Storage } from '../performance/storage/Storage';
7import { StorageFactory } from '../performance/storage/StorageFactory';
ded13d97 8import Utils from '../utils/Utils';
fd1fdf1b 9import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 10import WorkerFactory from '../worker/WorkerFactory';
8eac9a09 11import chalk from 'chalk';
ded13d97 12import { isMainThread } from 'worker_threads';
bf1866b2 13import path from 'path';
84e52c2c 14import { version } from '../../package.json';
ded13d97
JB
15
16export default class Bootstrap {
535aaa27
JB
17 private static instance: Bootstrap | null = null;
18 private static workerImplementation: WorkerAbstract | null = null;
81797102 19 private static storage: Storage;
c63c21bc 20 private static numberOfChargingStations: number;
aef1b33a 21 private version: string = version;
eb87fe87 22 private started: boolean;
ded13d97 23 private workerScript: string;
ded13d97
JB
24
25 private constructor() {
eb87fe87 26 this.started = false;
07f35004 27 this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'ChargingStationWorker.js');
8df3f0a9 28 this.initWorkerImplementation();
81797102 29 Bootstrap.storage = StorageFactory.getStorage(Configuration.getPerformanceStorage().type, Configuration.getPerformanceStorage().URI, this.logPrefix());
7874b0b1 30 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
31 }
32
33 public static getInstance(): Bootstrap {
34 if (!Bootstrap.instance) {
35 Bootstrap.instance = new Bootstrap();
36 }
37 return Bootstrap.instance;
38 }
39
40 public async start(): Promise<void> {
eb87fe87 41 if (isMainThread && !this.started) {
ded13d97 42 try {
c63c21bc 43 Bootstrap.numberOfChargingStations = 0;
2a370053 44 await Bootstrap.storage.open();
535aaa27 45 await Bootstrap.workerImplementation.start();
ded13d97
JB
46 // Start ChargingStation object in worker thread
47 if (Configuration.getStationTemplateURLs()) {
48 for (const stationURL of Configuration.getStationTemplateURLs()) {
49 try {
c63c21bc 50 const nbStations = stationURL.numberOfStations ?? 0;
ded13d97 51 for (let index = 1; index <= nbStations; index++) {
07f35004 52 const workerData: ChargingStationWorkerData = {
ded13d97 53 index,
bf1866b2 54 templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationURL.file))
ded13d97 55 };
535aaa27 56 await Bootstrap.workerImplementation.addElement(workerData);
c63c21bc 57 Bootstrap.numberOfChargingStations++;
ded13d97
JB
58 }
59 } catch (error) {
8eac9a09 60 console.error(chalk.red('Charging station start with template file ' + stationURL.file + ' error '), error);
ded13d97
JB
61 }
62 }
63 } else {
8eac9a09 64 console.warn(chalk.yellow('No stationTemplateURLs defined in configuration, exiting'));
ded13d97 65 }
c63c21bc 66 if (Bootstrap.numberOfChargingStations === 0) {
8eac9a09 67 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
ded13d97 68 } else {
c63c21bc 69 console.log(chalk.green(`Charging stations simulator ${this.version} started with ${Bootstrap.numberOfChargingStations.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${Bootstrap.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${Bootstrap.workerImplementation.maxElementsPerWorker ? ` (${Bootstrap.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`));
ded13d97 70 }
eb87fe87 71 this.started = true;
ded13d97 72 } catch (error) {
8eac9a09 73 console.error(chalk.red('Bootstrap start error '), error);
ded13d97
JB
74 }
75 }
76 }
77
78 public async stop(): Promise<void> {
eb87fe87 79 if (isMainThread && this.started) {
535aaa27 80 await Bootstrap.workerImplementation.stop();
2a370053 81 await Bootstrap.storage.close();
ded13d97 82 }
eb87fe87 83 this.started = false;
ded13d97
JB
84 }
85
86 public async restart(): Promise<void> {
87 await this.stop();
535aaa27 88 this.initWorkerImplementation();
ded13d97
JB
89 await this.start();
90 }
91
2a370053 92 private initWorkerImplementation(): void {
07f35004 93 Bootstrap.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
8df3f0a9
JB
94 {
95 startDelay: Configuration.getWorkerStartDelay(),
96 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
97 poolMinSize: Configuration.getWorkerPoolMinSize(),
98 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
99 poolOptions: {
100 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
ffd71f2c
JB
101 },
102 messageHandler: async (msg: WorkerMessage) => {
103 if (msg.id === WorkerMessageEvents.PERFORMANCE_STATISTICS) {
104 await Bootstrap.storage.storePerformanceStatistics(msg.data);
105 }
81797102 106 }
535aaa27 107 });
ded13d97 108 }
81797102
JB
109
110 private logPrefix(): string {
689dca78 111 return Utils.logPrefix(' Bootstrap |');
81797102 112 }
ded13d97 113}