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