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