702fa582c46e26934d22e1151b761f9c66fa9467
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
1 import ConfigurationData, {
2 StationTemplateUrl,
3 StorageConfiguration,
4 SupervisionUrlDistribution,
5 UIWebSocketServerConfiguration,
6 } from '../types/ConfigurationData';
7
8 import Constants from './Constants';
9 import { EmptyObject } from '../types/EmptyObject';
10 import { HandleErrorParams } from '../types/Error';
11 import { ServerOptions } from 'ws';
12 import { StorageType } from '../types/Storage';
13 import type { WorkerChoiceStrategy } from 'poolifier';
14 import WorkerConstants from '../worker/WorkerConstants';
15 import { WorkerProcessType } from '../types/Worker';
16 import chalk from 'chalk';
17 import fs from 'fs';
18 import path from 'path';
19
20 export default class Configuration {
21 private static configurationFilePath = path.join(
22 path.resolve(__dirname, '../'),
23 'assets',
24 'config.json'
25 );
26
27 private static configurationFileWatcher: fs.FSWatcher;
28 private static configuration: ConfigurationData | null = null;
29 private static configurationChangeCallback: () => Promise<void>;
30
31 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
32 Configuration.configurationChangeCallback = cb;
33 }
34
35 static getLogStatisticsInterval(): number {
36 Configuration.warnDeprecatedConfigurationKey(
37 'statisticsDisplayInterval',
38 null,
39 "Use 'logStatisticsInterval' instead"
40 );
41 // Read conf
42 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval')
43 ? Configuration.getConfig().logStatisticsInterval
44 : 60;
45 }
46
47 static getUIWebSocketServer(): UIWebSocketServerConfiguration {
48 let options: ServerOptions = {
49 host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
50 port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT,
51 };
52 let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
53 enabled: true,
54 options,
55 };
56 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
57 if (
58 Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')
59 ) {
60 options = {
61 ...options,
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 }),
70 };
71 }
72 uiWebSocketServerConfiguration = {
73 ...uiWebSocketServerConfiguration,
74 ...(Configuration.objectHasOwnProperty(
75 Configuration.getConfig().uiWebSocketServer,
76 'enabled'
77 ) && { enabled: Configuration.getConfig().uiWebSocketServer.enabled }),
78 options,
79 };
80 }
81 return uiWebSocketServerConfiguration;
82 }
83
84 static getPerformanceStorage(): StorageConfiguration {
85 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', "Use 'uri' instead");
86 let storageConfiguration: StorageConfiguration = {
87 enabled: false,
88 type: StorageType.JSON_FILE,
89 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE),
90 };
91 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
92 storageConfiguration = {
93 ...storageConfiguration,
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 }),
110 };
111 }
112 return storageConfiguration;
113 }
114
115 static getAutoReconnectMaxRetries(): number {
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 );
131 // Read conf
132 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
133 return Configuration.getConfig().autoReconnectMaxRetries;
134 }
135 }
136
137 static getStationTemplateUrls(): StationTemplateUrl[] {
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[]);
147 Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => {
148 if (!Configuration.isUndefined(stationUrl['numberOfStation'])) {
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 );
154 }
155 });
156 // Read conf
157 return Configuration.getConfig().stationTemplateUrls;
158 }
159
160 static getWorkerProcess(): WorkerProcessType {
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;
169 }
170
171 static getWorkerStartDelay(): number {
172 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay')
173 ? Configuration.getConfig().workerStartDelay
174 : WorkerConstants.DEFAULT_WORKER_START_DELAY;
175 }
176
177 static getElementStartDelay(): number {
178 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'elementStartDelay')
179 ? Configuration.getConfig().elementStartDelay
180 : WorkerConstants.DEFAULT_ELEMENT_START_DELAY;
181 }
182
183 static getWorkerPoolMinSize(): number {
184 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize')
185 ? Configuration.getConfig().workerPoolMinSize
186 : WorkerConstants.DEFAULT_POOL_MIN_SIZE;
187 }
188
189 static getWorkerPoolMaxSize(): number {
190 Configuration.warnDeprecatedConfigurationKey(
191 'workerPoolSize;',
192 null,
193 "Use 'workerPoolMaxSize' instead"
194 );
195 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize')
196 ? Configuration.getConfig().workerPoolMaxSize
197 : WorkerConstants.DEFAULT_POOL_MAX_SIZE;
198 }
199
200 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
201 return Configuration.getConfig().workerPoolStrategy;
202 }
203
204 static getChargingStationsPerWorker(): number {
205 return Configuration.objectHasOwnProperty(
206 Configuration.getConfig(),
207 'chargingStationsPerWorker'
208 )
209 ? Configuration.getConfig().chargingStationsPerWorker
210 : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER;
211 }
212
213 static getLogConsole(): boolean {
214 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, "Use 'logConsole' instead");
215 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole')
216 ? Configuration.getConfig().logConsole
217 : false;
218 }
219
220 static getLogFormat(): string {
221 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat')
222 ? Configuration.getConfig().logFormat
223 : 'simple';
224 }
225
226 static getLogRotate(): boolean {
227 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate')
228 ? Configuration.getConfig().logRotate
229 : true;
230 }
231
232 static getLogMaxFiles(): number {
233 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles')
234 ? Configuration.getConfig().logMaxFiles
235 : 7;
236 }
237
238 static getLogLevel(): string {
239 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel')
240 ? Configuration.getConfig().logLevel.toLowerCase()
241 : 'info';
242 }
243
244 static getLogFile(): string {
245 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile')
246 ? Configuration.getConfig().logFile
247 : 'combined.log';
248 }
249
250 static getLogErrorFile(): string {
251 Configuration.warnDeprecatedConfigurationKey('errorFile', null, "Use 'logErrorFile' instead");
252 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile')
253 ? Configuration.getConfig().logErrorFile
254 : 'error.log';
255 }
256
257 static getSupervisionUrls(): string | string[] {
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[]);
267 // Read conf
268 return Configuration.getConfig().supervisionUrls;
269 }
270
271 static getSupervisionUrlDistribution(): SupervisionUrlDistribution {
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;
288 }
289
290 private static logPrefix(): string {
291 return new Date().toLocaleString() + ' Simulator configuration |';
292 }
293
294 private static warnDeprecatedConfigurationKey(
295 key: string,
296 sectionName?: string,
297 logMsgToAppend = ''
298 ) {
299 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
300 if (
301 sectionName &&
302 !Configuration.isUndefined(Configuration.getConfig()[sectionName]) &&
303 !Configuration.isUndefined(Configuration.getConfig()[sectionName] as Record<string, unknown>)[
304 key
305 ]
306 ) {
307 console.error(
308 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${
309 logMsgToAppend && '. ' + logMsgToAppend
310 }}`
311 );
312 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
313 console.error(
314 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${
315 logMsgToAppend && '. ' + logMsgToAppend
316 }}`
317 );
318 }
319 }
320
321 // Read the config file
322 private static getConfig(): ConfigurationData {
323 if (!Configuration.configuration) {
324 try {
325 Configuration.configuration = JSON.parse(
326 fs.readFileSync(Configuration.configurationFilePath, 'utf8')
327 ) as ConfigurationData;
328 } catch (error) {
329 Configuration.handleFileException(
330 Configuration.logPrefix(),
331 'Configuration',
332 Configuration.configurationFilePath,
333 error as NodeJS.ErrnoException
334 );
335 }
336 if (!Configuration.configurationFileWatcher) {
337 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
338 }
339 }
340 return Configuration.configuration;
341 }
342
343 private static getConfigurationFileWatcher(): fs.FSWatcher {
344 try {
345 return fs.watch(Configuration.configurationFilePath, (event, filename): void => {
346 if (filename && event === 'change') {
347 // Nullify to force configuration file reading
348 Configuration.configuration = null;
349 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
350 Configuration.configurationChangeCallback().catch((error) => {
351 throw typeof error === 'string' ? new Error(error) : error;
352 });
353 }
354 }
355 });
356 } catch (error) {
357 Configuration.handleFileException(
358 Configuration.logPrefix(),
359 'Configuration',
360 Configuration.configurationFilePath,
361 error as Error
362 );
363 }
364 }
365
366 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
367 const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
368 switch (storageType) {
369 case StorageType.JSON_FILE:
370 return `file://${path.join(
371 path.resolve(__dirname, '../../'),
372 Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME
373 )}`;
374 case StorageType.SQLITE:
375 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
376 default:
377 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
378 }
379 }
380
381 private static objectHasOwnProperty(object: unknown, property: string): boolean {
382 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
383 }
384
385 private static isUndefined(obj: unknown): boolean {
386 return typeof obj === 'undefined';
387 }
388
389 private static handleFileException(
390 logPrefix: string,
391 fileType: string,
392 filePath: string,
393 error: NodeJS.ErrnoException,
394 params: HandleErrorParams<EmptyObject> = { throwError: true }
395 ): void {
396 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
397 if (error.code === 'ENOENT') {
398 console.error(
399 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '),
400 error
401 );
402 } else if (error.code === 'EEXIST') {
403 console.error(
404 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '),
405 error
406 );
407 } else if (error.code === 'EACCES') {
408 console.error(
409 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '),
410 error
411 );
412 } else {
413 console.error(
414 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '),
415 error
416 );
417 }
418 if (params?.throwError) {
419 throw error;
420 }
421 }
422 }