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