Memory optimization + worker configuration
[e-mobility-charging-stations-simulator.git] / src / start.ts
1 import Configuration from './utils/Configuration';
2 import { StationTemplateURL } from './types/ConfigurationData';
3 import Utils from './utils/Utils';
4 import Wrk from './charging-station/Worker';
5 import WorkerData from './types/WorkerData';
6 import fs from 'fs';
7
8 class Bootstrap {
9 static async start() {
10 try {
11 let numStationsTotal = 0;
12 let numConcurrentWorkers = 0;
13 let worker: Wrk;
14 let chargingStationsPerWorker = Configuration.getChargingStationsPerWorker();
15 let counter = 0;
16 // Start each ChargingStation object in a worker thread
17 if (Configuration.getStationTemplateURLs()) {
18 for await (const stationURL of Configuration.getStationTemplateURLs()) {
19 try {
20 const nbStations = stationURL.numberOfStations ? stationURL.numberOfStations : 0;
21 numStationsTotal += nbStations;
22 for (let index = 1; index <= nbStations; index++) {
23 const workerData = {
24 index,
25 templateFile: stationURL.file
26 } as WorkerData;
27 if(counter === 0 || counter === chargingStationsPerWorker) {
28 // Start new worker with one charging station
29 worker = await new Wrk('./dist/charging-station/StationWorker.js', workerData, numStationsTotal);
30 worker.start().catch(() => {});
31 counter = 0;
32 // Start workers sequentially to optimize memory at start time
33 await Utils.sleep(500);
34 } else {
35 // Add new charging station to existing Worker
36 worker.startNewChargingStation(workerData, numStationsTotal)
37 }
38 counter++;
39 // Start charging station sequentially to optimize memory at start time
40 numConcurrentWorkers = worker.concurrentWorkers;
41 }
42 } catch (error) {
43 // eslint-disable-next-line no-console
44 console.log('Charging station start with template file ' + stationURL.file + ' error ' + JSON.stringify(error, null, ' '));
45 }
46 }
47 } else {
48 console.log('No stationTemplateURLs defined in configuration, exiting');
49 }
50 if (numStationsTotal === 0) {
51 console.log('No charging station template enabled in configuration, exiting');
52 } else {
53 console.log('Charging station simulator started with ' + numStationsTotal.toString() + ' charging station(s) of ' + numConcurrentWorkers.toString() + ' concurrently running');
54 }
55 } catch (error) {
56 // eslint-disable-next-line no-console
57 console.log('Bootstrap start error ' + JSON.stringify(error, null, ' '));
58 }
59 }
60 }
61
62 Bootstrap.start();