Add persistent OCPP parameters key/value support by CS generated name
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
CommitLineData
e7aeea18
JB
1import ConfigurationData, {
2 StationTemplateUrl,
3 StorageConfiguration,
4 SupervisionUrlDistribution,
5 UIWebSocketServerConfiguration,
6} from '../types/ConfigurationData';
e118beaa 7
322c9192 8import Constants from './Constants';
717c1e56 9import { EmptyObject } from '../types/EmptyObject';
e0a50bcd 10import { HandleErrorParams } from '../types/Error';
6a49ad23 11import { ServerOptions } from 'ws';
72f041bd 12import { StorageType } from '../types/Storage';
9efbac5b 13import type { WorkerChoiceStrategy } from 'poolifier';
3fa0f0ed 14import WorkerConstants from '../worker/WorkerConstants';
a4624c96 15import { WorkerProcessType } from '../types/Worker';
8eac9a09 16import chalk from 'chalk';
3f40bc9c 17import fs from 'fs';
bf1866b2 18import path from 'path';
7dde0b73 19
3f40bc9c 20export default class Configuration {
e7aeea18
JB
21 private static configurationFilePath = path.join(
22 path.resolve(__dirname, '../'),
23 'assets',
24 'config.json'
25 );
10068088 26
ded13d97 27 private static configurationFileWatcher: fs.FSWatcher;
6e0964c8 28 private static configuration: ConfigurationData | null = null;
e57acf6a
JB
29 private static configurationChangeCallback: () => Promise<void>;
30
31 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
32 Configuration.configurationChangeCallback = cb;
33 }
7dde0b73 34
72f041bd 35 static getLogStatisticsInterval(): number {
e7aeea18
JB
36 Configuration.warnDeprecatedConfigurationKey(
37 'statisticsDisplayInterval',
38 null,
39 "Use 'logStatisticsInterval' instead"
40 );
7dde0b73 41 // Read conf
e7aeea18
JB
42 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval')
43 ? Configuration.getConfig().logStatisticsInterval
44 : 60;
72f041bd
JB
45 }
46
6a49ad23
JB
47 static getUIWebSocketServer(): UIWebSocketServerConfiguration {
48 let options: ServerOptions = {
49 host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
e7aeea18 50 port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT,
6a49ad23
JB
51 };
52 let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
53 enabled: true,
e7aeea18 54 options,
6a49ad23
JB
55 };
56 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
e7aeea18
JB
57 if (
58 Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')
59 ) {
6a49ad23 60 options = {
1ba1e8fb 61 ...options,
e7aeea18
JB
62 ...(Configuration.objectHasOwnProperty(
63 Configuration.getConfig().uiWebSocketServer.options,
64 'host'
65 ) && { host: Configuration.getConfig().uiWebSocketServer.options.host }),
66 ...(Configuration.objectHasOwnProperty(
67 Configuration.getConfig().uiWebSocketServer.options,
68 'port'
69 ) && { port: Configuration.getConfig().uiWebSocketServer.options.port }),
6a49ad23
JB
70 };
71 }
e7aeea18 72 uiWebSocketServerConfiguration = {
1ba1e8fb 73 ...uiWebSocketServerConfiguration,
e7aeea18
JB
74 ...(Configuration.objectHasOwnProperty(
75 Configuration.getConfig().uiWebSocketServer,
76 'enabled'
77 ) && { enabled: Configuration.getConfig().uiWebSocketServer.enabled }),
78 options,
6a49ad23
JB
79 };
80 }
81 return uiWebSocketServerConfiguration;
82 }
83
72f041bd 84 static getPerformanceStorage(): StorageConfiguration {
e7aeea18 85 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', "Use 'uri' instead");
6a49ad23
JB
86 let storageConfiguration: StorageConfiguration = {
87 enabled: false,
88 type: StorageType.JSON_FILE,
e7aeea18 89 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE),
6a49ad23 90 };
72f041bd 91 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
e7aeea18 92 storageConfiguration = {
1ba1e8fb 93 ...storageConfiguration,
e7aeea18
JB
94 ...(Configuration.objectHasOwnProperty(
95 Configuration.getConfig().performanceStorage,
96 'enabled'
97 ) && { enabled: Configuration.getConfig().performanceStorage.enabled }),
98 ...(Configuration.objectHasOwnProperty(
99 Configuration.getConfig().performanceStorage,
100 'type'
101 ) && { type: Configuration.getConfig().performanceStorage.type }),
102 ...(Configuration.objectHasOwnProperty(
103 Configuration.getConfig().performanceStorage,
104 'uri'
105 ) && {
106 uri: this.getDefaultPerformanceStorageUri(
107 Configuration.getConfig()?.performanceStorage?.type ?? StorageType.JSON_FILE
108 ),
109 }),
72f041bd 110 };
72f041bd
JB
111 }
112 return storageConfiguration;
7dde0b73
JB
113 }
114
9ccca265 115 static getAutoReconnectMaxRetries(): number {
e7aeea18
JB
116 Configuration.warnDeprecatedConfigurationKey(
117 'autoReconnectTimeout',
118 null,
119 "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead"
120 );
121 Configuration.warnDeprecatedConfigurationKey(
122 'connectionTimeout',
123 null,
124 "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead"
125 );
126 Configuration.warnDeprecatedConfigurationKey(
127 'autoReconnectMaxRetries',
128 null,
129 'Use it in charging station template instead'
130 );
7dde0b73 131 // Read conf
963ee397 132 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
3574dfd3
JB
133 return Configuration.getConfig().autoReconnectMaxRetries;
134 }
7dde0b73
JB
135 }
136
1f5df42a 137 static getStationTemplateUrls(): StationTemplateUrl[] {
e7aeea18
JB
138 Configuration.warnDeprecatedConfigurationKey(
139 'stationTemplateURLs',
140 null,
141 "Use 'stationTemplateUrls' instead"
142 );
143 !Configuration.isUndefined(Configuration.getConfig()['stationTemplateURLs']) &&
144 (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()[
145 'stationTemplateURLs'
146 ] as StationTemplateUrl[]);
1f5df42a
JB
147 Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => {
148 if (!Configuration.isUndefined(stationUrl['numberOfStation'])) {
e7aeea18
JB
149 console.error(
150 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${
151 stationUrl.file
152 }' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`
153 );
eb3937cb
JB
154 }
155 });
7dde0b73 156 // Read conf
1f5df42a 157 return Configuration.getConfig().stationTemplateUrls;
7dde0b73
JB
158 }
159
a4624c96 160 static getWorkerProcess(): WorkerProcessType {
e7aeea18
JB
161 Configuration.warnDeprecatedConfigurationKey(
162 'useWorkerPool;',
163 null,
164 "Use 'workerProcess' to define the type of worker process to use instead"
165 );
166 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess')
167 ? Configuration.getConfig().workerProcess
168 : WorkerProcessType.WORKER_SET;
a4624c96
JB
169 }
170
322c9192 171 static getWorkerStartDelay(): number {
e7aeea18
JB
172 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay')
173 ? Configuration.getConfig().workerStartDelay
3fa0f0ed 174 : WorkerConstants.DEFAULT_WORKER_START_DELAY;
322c9192
JB
175 }
176
4bfd80fa 177 static getElementStartDelay(): number {
e7aeea18
JB
178 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'elementStartDelay')
179 ? Configuration.getConfig().elementStartDelay
3fa0f0ed 180 : WorkerConstants.DEFAULT_ELEMENT_START_DELAY;
4bfd80fa
JB
181 }
182
a4624c96 183 static getWorkerPoolMinSize(): number {
e7aeea18
JB
184 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize')
185 ? Configuration.getConfig().workerPoolMinSize
3fa0f0ed 186 : WorkerConstants.DEFAULT_POOL_MIN_SIZE;
7dde0b73
JB
187 }
188
4fa59b8a 189 static getWorkerPoolMaxSize(): number {
e7aeea18
JB
190 Configuration.warnDeprecatedConfigurationKey(
191 'workerPoolSize;',
192 null,
193 "Use 'workerPoolMaxSize' instead"
194 );
195 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize')
196 ? Configuration.getConfig().workerPoolMaxSize
3fa0f0ed 197 : WorkerConstants.DEFAULT_POOL_MAX_SIZE;
7dde0b73
JB
198 }
199
9efbac5b
JB
200 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
201 return Configuration.getConfig().workerPoolStrategy;
202 }
203
3d2ff9e4 204 static getChargingStationsPerWorker(): number {
e7aeea18
JB
205 return Configuration.objectHasOwnProperty(
206 Configuration.getConfig(),
207 'chargingStationsPerWorker'
208 )
209 ? Configuration.getConfig().chargingStationsPerWorker
3fa0f0ed 210 : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER;
3d2ff9e4
J
211 }
212
7ec46a9a 213 static getLogConsole(): boolean {
e7aeea18
JB
214 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, "Use 'logConsole' instead");
215 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole')
216 ? Configuration.getConfig().logConsole
217 : false;
7dde0b73
JB
218 }
219
a4a21709 220 static getLogFormat(): string {
e7aeea18
JB
221 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat')
222 ? Configuration.getConfig().logFormat
223 : 'simple';
027b409a
JB
224 }
225
6bf6769e 226 static getLogRotate(): boolean {
e7aeea18
JB
227 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate')
228 ? Configuration.getConfig().logRotate
229 : true;
6bf6769e
JB
230 }
231
232 static getLogMaxFiles(): number {
e7aeea18
JB
233 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles')
234 ? Configuration.getConfig().logMaxFiles
235 : 7;
6bf6769e
JB
236 }
237
324fd4ee 238 static getLogLevel(): string {
e7aeea18
JB
239 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel')
240 ? Configuration.getConfig().logLevel.toLowerCase()
241 : 'info';
2e6f5966
JB
242 }
243
a4a21709 244 static getLogFile(): string {
e7aeea18
JB
245 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile')
246 ? Configuration.getConfig().logFile
247 : 'combined.log';
7dde0b73
JB
248 }
249
7ec46a9a 250 static getLogErrorFile(): string {
e7aeea18
JB
251 Configuration.warnDeprecatedConfigurationKey('errorFile', null, "Use 'logErrorFile' instead");
252 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile')
253 ? Configuration.getConfig().logErrorFile
254 : 'error.log';
7dde0b73
JB
255 }
256
2dcfe98e 257 static getSupervisionUrls(): string | string[] {
e7aeea18
JB
258 Configuration.warnDeprecatedConfigurationKey(
259 'supervisionURLs',
260 null,
261 "Use 'supervisionUrls' instead"
262 );
263 !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) &&
264 (Configuration.getConfig().supervisionUrls = Configuration.getConfig()[
265 'supervisionURLs'
266 ] as string[]);
7dde0b73 267 // Read conf
1f5df42a 268 return Configuration.getConfig().supervisionUrls;
7dde0b73
JB
269 }
270
2dcfe98e 271 static getSupervisionUrlDistribution(): SupervisionUrlDistribution {
e7aeea18
JB
272 Configuration.warnDeprecatedConfigurationKey(
273 'distributeStationToTenantEqually',
274 null,
275 "Use 'supervisionUrlDistribution' instead"
276 );
277 Configuration.warnDeprecatedConfigurationKey(
278 'distributeStationsToTenantsEqually',
279 null,
280 "Use 'supervisionUrlDistribution' instead"
281 );
282 return Configuration.objectHasOwnProperty(
283 Configuration.getConfig(),
284 'supervisionUrlDistribution'
285 )
286 ? Configuration.getConfig().supervisionUrlDistribution
287 : SupervisionUrlDistribution.ROUND_ROBIN;
7dde0b73 288 }
eb3937cb 289
23132a44
JB
290 private static logPrefix(): string {
291 return new Date().toLocaleString() + ' Simulator configuration |';
292 }
293
e7aeea18
JB
294 private static warnDeprecatedConfigurationKey(
295 key: string,
296 sectionName?: string,
297 logMsgToAppend = ''
298 ) {
e7aeea18
JB
299 if (
300 sectionName &&
301 !Configuration.isUndefined(Configuration.getConfig()[sectionName]) &&
455ee9cf
JB
302 !Configuration.isUndefined(
303 (Configuration.getConfig()[sectionName] as Record<string, unknown>)[key]
304 )
e7aeea18
JB
305 ) {
306 console.error(
307 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${
308 logMsgToAppend && '. ' + logMsgToAppend
309 }}`
310 );
912136b1 311 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
e7aeea18
JB
312 console.error(
313 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${
314 logMsgToAppend && '. ' + logMsgToAppend
315 }}`
316 );
eb3937cb
JB
317 }
318 }
319
320 // Read the config file
321 private static getConfig(): ConfigurationData {
322 if (!Configuration.configuration) {
23132a44 323 try {
e7aeea18
JB
324 Configuration.configuration = JSON.parse(
325 fs.readFileSync(Configuration.configurationFilePath, 'utf8')
326 ) as ConfigurationData;
23132a44 327 } catch (error) {
e7aeea18
JB
328 Configuration.handleFileException(
329 Configuration.logPrefix(),
330 'Configuration',
331 Configuration.configurationFilePath,
3fa0f0ed 332 error as NodeJS.ErrnoException
e7aeea18 333 );
23132a44 334 }
ded13d97
JB
335 if (!Configuration.configurationFileWatcher) {
336 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
337 }
eb3937cb
JB
338 }
339 return Configuration.configuration;
340 }
963ee397 341
ded13d97 342 private static getConfigurationFileWatcher(): fs.FSWatcher {
23132a44 343 try {
860a9c5a 344 return fs.watch(Configuration.configurationFilePath, (event, filename): void => {
3ec10737
JB
345 if (filename && event === 'change') {
346 // Nullify to force configuration file reading
347 Configuration.configuration = null;
348 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
dcaf96dc
JB
349 Configuration.configurationChangeCallback().catch((error) => {
350 throw typeof error === 'string' ? new Error(error) : error;
351 });
3ec10737 352 }
23132a44
JB
353 }
354 });
355 } catch (error) {
e7aeea18
JB
356 Configuration.handleFileException(
357 Configuration.logPrefix(),
358 'Configuration',
359 Configuration.configurationFilePath,
360 error as Error
361 );
23132a44 362 }
ded13d97
JB
363 }
364
1f5df42a 365 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
d5603918
JB
366 const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
367 switch (storageType) {
368 case StorageType.JSON_FILE:
e7aeea18
JB
369 return `file://${path.join(
370 path.resolve(__dirname, '../../'),
371 Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME
372 )}`;
d5603918
JB
373 case StorageType.SQLITE:
374 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
375 default:
376 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
377 }
378 }
379
73d09045 380 private static objectHasOwnProperty(object: unknown, property: string): boolean {
23132a44 381 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
963ee397
JB
382 }
383
73d09045 384 private static isUndefined(obj: unknown): boolean {
963ee397
JB
385 return typeof obj === 'undefined';
386 }
23132a44 387
e7aeea18
JB
388 private static handleFileException(
389 logPrefix: string,
390 fileType: string,
391 filePath: string,
392 error: NodeJS.ErrnoException,
393 params: HandleErrorParams<EmptyObject> = { throwError: true }
394 ): void {
23132a44
JB
395 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
396 if (error.code === 'ENOENT') {
e7aeea18
JB
397 console.error(
398 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '),
399 error
400 );
72f041bd 401 } else if (error.code === 'EEXIST') {
e7aeea18
JB
402 console.error(
403 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '),
404 error
405 );
72f041bd 406 } else if (error.code === 'EACCES') {
e7aeea18
JB
407 console.error(
408 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '),
409 error
410 );
23132a44 411 } else {
e7aeea18
JB
412 console.error(
413 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '),
414 error
415 );
23132a44 416 }
e0a50bcd
JB
417 if (params?.throwError) {
418 throw error;
419 }
23132a44 420 }
7dde0b73 421}