bad98a98f96f092aa45750787096d20580a22eaf
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
1 import ConfigurationData, { StationTemplateURL, StorageConfiguration } from '../types/ConfigurationData';
2
3 import Constants from './Constants';
4 import { StorageType } from '../types/Storage';
5 import type { WorkerChoiceStrategy } from 'poolifier';
6 import { WorkerProcessType } from '../types/Worker';
7 import fs from 'fs';
8 import path from 'path';
9
10 export default class Configuration {
11 private static configurationFilePath = path.join(path.resolve(__dirname, '../'), 'assets', 'config.json');
12 private static configurationFileWatcher: fs.FSWatcher;
13 private static configuration: ConfigurationData | null = null;
14 private static configurationChangeCallback: () => Promise<void>;
15
16 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
17 Configuration.configurationChangeCallback = cb;
18 }
19
20 static getLogStatisticsInterval(): number {
21 Configuration.warnDeprecatedConfigurationKey('statisticsDisplayInterval', 'Use \'logStatisticsInterval\' instead');
22 // Read conf
23 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval') ? Configuration.getConfig().logStatisticsInterval : 60;
24 }
25
26 static getPerformanceStorage(): StorageConfiguration {
27 let storageConfiguration: StorageConfiguration;
28 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
29 storageConfiguration =
30 {
31 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'enabled') ? { enabled: Configuration.getConfig().performanceStorage.enabled } : { enabled: false },
32 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'type') ? { type: Configuration.getConfig().performanceStorage.type } : { type: StorageType.JSON_FILE },
33 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'URI') ? { URI: Configuration.getConfig().performanceStorage.URI } : { URI: 'file:///performanceMeasurements.json' }
34 };
35 } else {
36 storageConfiguration =
37 {
38 enabled: false,
39 type: StorageType.JSON_FILE,
40 URI: 'file:///performanceMeasurements.json'
41 };
42 }
43 return storageConfiguration;
44 }
45
46 static getAutoReconnectMaxRetries(): number {
47 Configuration.warnDeprecatedConfigurationKey('autoReconnectTimeout', 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
48 Configuration.warnDeprecatedConfigurationKey('connectionTimeout', 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
49 Configuration.warnDeprecatedConfigurationKey('autoReconnectMaxRetries', 'Use it in charging station template instead');
50 // Read conf
51 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
52 return Configuration.getConfig().autoReconnectMaxRetries;
53 }
54 }
55
56 static getStationTemplateURLs(): StationTemplateURL[] {
57 Configuration.getConfig().stationTemplateURLs.forEach((stationURL: StationTemplateURL) => {
58 if (!Configuration.isUndefined(stationURL['numberOfStation'])) {
59 console.error(`${Configuration.logPrefix()} Deprecated configuration key 'numberOfStation' usage for template file '${stationURL.file}' in 'stationTemplateURLs'. Use 'numberOfStations' instead`);
60 }
61 });
62 // Read conf
63 return Configuration.getConfig().stationTemplateURLs;
64 }
65
66 static getWorkerProcess(): WorkerProcessType {
67 Configuration.warnDeprecatedConfigurationKey('useWorkerPool;', 'Use \'workerProcess\' to define the type of worker process to use instead');
68 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess') ? Configuration.getConfig().workerProcess : WorkerProcessType.WORKER_SET;
69 }
70
71 static getWorkerStartDelay(): number {
72 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay') ? Configuration.getConfig().workerStartDelay : Constants.WORKER_START_DELAY;
73 }
74
75 static getWorkerPoolMinSize(): number {
76 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize') ? Configuration.getConfig().workerPoolMinSize : Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
77 }
78
79 static getWorkerPoolMaxSize(): number {
80 Configuration.warnDeprecatedConfigurationKey('workerPoolSize;', 'Use \'workerPoolMaxSize\' instead');
81 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize') ? Configuration.getConfig().workerPoolMaxSize : Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
82 }
83
84 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
85 return Configuration.getConfig().workerPoolStrategy;
86 }
87
88 static getChargingStationsPerWorker(): number {
89 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'chargingStationsPerWorker') ? Configuration.getConfig().chargingStationsPerWorker : Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
90 }
91
92 static getLogConsole(): boolean {
93 Configuration.warnDeprecatedConfigurationKey('consoleLog', 'Use \'logConsole\' instead');
94 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') ? Configuration.getConfig().logConsole : false;
95 }
96
97 static getLogFormat(): string {
98 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') ? Configuration.getConfig().logFormat : 'simple';
99 }
100
101 static getLogRotate(): boolean {
102 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') ? Configuration.getConfig().logRotate : true;
103 }
104
105 static getLogMaxFiles(): number {
106 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') ? Configuration.getConfig().logMaxFiles : 7;
107 }
108
109 static getLogLevel(): string {
110 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') ? Configuration.getConfig().logLevel : 'info';
111 }
112
113 static getLogFile(): string {
114 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') ? Configuration.getConfig().logFile : 'combined.log';
115 }
116
117 static getLogErrorFile(): string {
118 Configuration.warnDeprecatedConfigurationKey('errorFile', 'Use \'logErrorFile\' instead');
119 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') ? Configuration.getConfig().logErrorFile : 'error.log';
120 }
121
122 static getSupervisionURLs(): string[] {
123 // Read conf
124 return Configuration.getConfig().supervisionURLs;
125 }
126
127 static getDistributeStationsToTenantsEqually(): boolean {
128 Configuration.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', 'Use \'distributeStationsToTenantsEqually\' instead');
129 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'distributeStationsToTenantsEqually') ? Configuration.getConfig().distributeStationsToTenantsEqually : true;
130 }
131
132 private static logPrefix(): string {
133 return new Date().toLocaleString() + ' Simulator configuration |';
134 }
135
136 private static warnDeprecatedConfigurationKey(key: string, sectionName?: string, logMsgToAppend = '') {
137 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
138 if (sectionName && !Configuration.isUndefined(Configuration.getConfig()[sectionName]) && !Configuration.isUndefined(Configuration.getConfig()[sectionName][key])) {
139 console.error(`${Configuration.logPrefix()} Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}`);
140 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
141 console.error(`${Configuration.logPrefix()} Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}`);
142 }
143 }
144
145 // Read the config file
146 private static getConfig(): ConfigurationData {
147 if (!Configuration.configuration) {
148 try {
149 Configuration.configuration = JSON.parse(fs.readFileSync(Configuration.configurationFilePath, 'utf8')) as ConfigurationData;
150 } catch (error) {
151 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error);
152 }
153 if (!Configuration.configurationFileWatcher) {
154 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
155 }
156 }
157 return Configuration.configuration;
158 }
159
160 private static getConfigurationFileWatcher(): fs.FSWatcher {
161 try {
162 // eslint-disable-next-line @typescript-eslint/no-misused-promises
163 return fs.watch(Configuration.configurationFilePath).on('change', async (): Promise<void> => {
164 // Nullify to force configuration file reading
165 Configuration.configuration = null;
166 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
167 await Configuration.configurationChangeCallback();
168 }
169 });
170 } catch (error) {
171 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error);
172 }
173 }
174
175 private static objectHasOwnProperty(object: any, property: string): boolean {
176 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
177 }
178
179 private static isUndefined(obj: any): boolean {
180 return typeof obj === 'undefined';
181 }
182
183 private static handleFileException(logPrefix: string, fileType: string, filePath: string, error: NodeJS.ErrnoException): void {
184 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
185 if (error.code === 'ENOENT') {
186 console.error(prefix + fileType + ' file ' + filePath + ' not found: ', error);
187 } else if (error.code === 'EEXIST') {
188 console.error(prefix + fileType + ' file ' + filePath + ' already exists: ', error);
189 } else if (error.code === 'EACCES') {
190 console.error(prefix + fileType + ' file ' + filePath + ' access denied: ', error);
191 } else {
192 console.error(prefix + fileType + ' file ' + filePath + ' error: ', error);
193 }
194 throw error;
195 }
196 }