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