]>
Commit | Line | Data |
---|---|---|
1 | import fs from 'fs'; | |
2 | import path from 'path'; | |
3 | import { fileURLToPath } from 'url'; | |
4 | ||
5 | import chalk from 'chalk'; | |
6 | import merge from 'just-merge'; | |
7 | import { WorkerChoiceStrategies } from 'poolifier'; | |
8 | ||
9 | import Constants from './Constants'; | |
10 | import { | |
11 | type ConfigurationData, | |
12 | type StationTemplateUrl, | |
13 | type StorageConfiguration, | |
14 | SupervisionUrlDistribution, | |
15 | type UIServerConfiguration, | |
16 | type WorkerConfiguration, | |
17 | } from '../types/ConfigurationData'; | |
18 | import type { EmptyObject } from '../types/EmptyObject'; | |
19 | import type { HandleErrorParams } from '../types/Error'; | |
20 | import { FileType } from '../types/FileType'; | |
21 | import { StorageType } from '../types/Storage'; | |
22 | import { ApplicationProtocol } from '../types/UIProtocol'; | |
23 | import { WorkerProcessType } from '../types/Worker'; | |
24 | import WorkerConstants from '../worker/WorkerConstants'; | |
25 | ||
26 | export default class Configuration { | |
27 | private static configurationFile = path.join( | |
28 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'), | |
29 | 'assets', | |
30 | 'config.json' | |
31 | ); | |
32 | ||
33 | private static configurationFileWatcher: fs.FSWatcher; | |
34 | private static configuration: ConfigurationData | null = null; | |
35 | private static configurationChangeCallback: () => Promise<void>; | |
36 | ||
37 | private constructor() { | |
38 | // This is intentional | |
39 | } | |
40 | ||
41 | static setConfigurationChangeCallback(cb: () => Promise<void>): void { | |
42 | Configuration.configurationChangeCallback = cb; | |
43 | } | |
44 | ||
45 | static getLogStatisticsInterval(): number { | |
46 | Configuration.warnDeprecatedConfigurationKey( | |
47 | 'statisticsDisplayInterval', | |
48 | null, | |
49 | "Use 'logStatisticsInterval' instead" | |
50 | ); | |
51 | // Read conf | |
52 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval') | |
53 | ? Configuration.getConfig().logStatisticsInterval | |
54 | : Constants.DEFAULT_LOG_STATISTICS_INTERVAL; | |
55 | } | |
56 | ||
57 | static getUIServer(): UIServerConfiguration { | |
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 | } | |
63 | let uiServerConfiguration: UIServerConfiguration = { | |
64 | enabled: false, | |
65 | type: ApplicationProtocol.WS, | |
66 | options: { | |
67 | host: Constants.DEFAULT_UI_SERVER_HOST, | |
68 | port: Constants.DEFAULT_UI_SERVER_PORT, | |
69 | }, | |
70 | }; | |
71 | if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiServer')) { | |
72 | uiServerConfiguration = merge(uiServerConfiguration, Configuration.getConfig().uiServer); | |
73 | } | |
74 | if (Configuration.isCFEnvironment() === true) { | |
75 | delete uiServerConfiguration.options.host; | |
76 | uiServerConfiguration.options.port = parseInt(process.env.PORT); | |
77 | } | |
78 | return uiServerConfiguration; | |
79 | } | |
80 | ||
81 | static getPerformanceStorage(): StorageConfiguration { | |
82 | Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', "Use 'uri' instead"); | |
83 | let storageConfiguration: StorageConfiguration = { | |
84 | enabled: false, | |
85 | type: StorageType.JSON_FILE, | |
86 | uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE), | |
87 | }; | |
88 | if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) { | |
89 | storageConfiguration = { | |
90 | ...storageConfiguration, | |
91 | ...Configuration.getConfig().performanceStorage, | |
92 | }; | |
93 | } | |
94 | return storageConfiguration; | |
95 | } | |
96 | ||
97 | static getAutoReconnectMaxRetries(): number { | |
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 | ); | |
113 | // Read conf | |
114 | if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) { | |
115 | return Configuration.getConfig().autoReconnectMaxRetries; | |
116 | } | |
117 | } | |
118 | ||
119 | static getStationTemplateUrls(): StationTemplateUrl[] { | |
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[]); | |
129 | Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => { | |
130 | if (!Configuration.isUndefined(stationUrl['numberOfStation'])) { | |
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 | ); | |
136 | } | |
137 | }); | |
138 | // Read conf | |
139 | return Configuration.getConfig().stationTemplateUrls; | |
140 | } | |
141 | ||
142 | static getWorker(): WorkerConfiguration { | |
143 | Configuration.warnDeprecatedConfigurationKey( | |
144 | 'useWorkerPool', | |
145 | null, | |
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" | |
172 | ); | |
173 | Configuration.warnDeprecatedConfigurationKey( | |
174 | 'workerPoolSize;', | |
175 | null, | |
176 | "Use 'worker' section to define the worker pool maximum size instead" | |
177 | ); | |
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 | ); | |
188 | let workerConfiguration: WorkerConfiguration = { | |
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, | |
219 | poolStrategy: | |
220 | Configuration.getConfig().workerPoolStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN, | |
221 | }; | |
222 | if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'worker')) { | |
223 | workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig().worker }; | |
224 | } | |
225 | return workerConfiguration; | |
226 | } | |
227 | ||
228 | static getLogConsole(): boolean { | |
229 | Configuration.warnDeprecatedConfigurationKey('consoleLog', null, "Use 'logConsole' instead"); | |
230 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') | |
231 | ? Configuration.getConfig().logConsole | |
232 | : false; | |
233 | } | |
234 | ||
235 | static getLogFormat(): string { | |
236 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') | |
237 | ? Configuration.getConfig().logFormat | |
238 | : 'simple'; | |
239 | } | |
240 | ||
241 | static getLogRotate(): boolean { | |
242 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') | |
243 | ? Configuration.getConfig().logRotate | |
244 | : true; | |
245 | } | |
246 | ||
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 | ); | |
259 | } | |
260 | ||
261 | static getLogLevel(): string { | |
262 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') | |
263 | ? Configuration.getConfig().logLevel.toLowerCase() | |
264 | : 'info'; | |
265 | } | |
266 | ||
267 | static getLogFile(): string { | |
268 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') | |
269 | ? Configuration.getConfig().logFile | |
270 | : 'combined.log'; | |
271 | } | |
272 | ||
273 | static getLogErrorFile(): string { | |
274 | Configuration.warnDeprecatedConfigurationKey('errorFile', null, "Use 'logErrorFile' instead"); | |
275 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') | |
276 | ? Configuration.getConfig().logErrorFile | |
277 | : 'error.log'; | |
278 | } | |
279 | ||
280 | static getSupervisionUrls(): string | string[] { | |
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[]); | |
290 | // Read conf | |
291 | return Configuration.getConfig().supervisionUrls; | |
292 | } | |
293 | ||
294 | static getSupervisionUrlDistribution(): SupervisionUrlDistribution { | |
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; | |
311 | } | |
312 | ||
313 | private static logPrefix(): string { | |
314 | return `${new Date().toLocaleString()} Simulator configuration |`; | |
315 | } | |
316 | ||
317 | private static warnDeprecatedConfigurationKey( | |
318 | key: string, | |
319 | sectionName?: string, | |
320 | logMsgToAppend = '' | |
321 | ) { | |
322 | if ( | |
323 | sectionName && | |
324 | !Configuration.isUndefined(Configuration.getConfig()[sectionName]) && | |
325 | !Configuration.isUndefined( | |
326 | (Configuration.getConfig()[sectionName] as Record<string, unknown>)[key] | |
327 | ) | |
328 | ) { | |
329 | console.error( | |
330 | chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${ | |
331 | logMsgToAppend && `. ${logMsgToAppend}` | |
332 | }}` | |
333 | ); | |
334 | } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) { | |
335 | console.error( | |
336 | chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${ | |
337 | logMsgToAppend && `. ${logMsgToAppend}` | |
338 | }}` | |
339 | ); | |
340 | } | |
341 | } | |
342 | ||
343 | // Read the config file | |
344 | private static getConfig(): ConfigurationData { | |
345 | if (!Configuration.configuration) { | |
346 | try { | |
347 | Configuration.configuration = JSON.parse( | |
348 | fs.readFileSync(Configuration.configurationFile, 'utf8') | |
349 | ) as ConfigurationData; | |
350 | } catch (error) { | |
351 | Configuration.handleFileException( | |
352 | Configuration.logPrefix(), | |
353 | FileType.Configuration, | |
354 | Configuration.configurationFile, | |
355 | error as NodeJS.ErrnoException | |
356 | ); | |
357 | } | |
358 | if (!Configuration.configurationFileWatcher) { | |
359 | Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher(); | |
360 | } | |
361 | } | |
362 | return Configuration.configuration; | |
363 | } | |
364 | ||
365 | private static getConfigurationFileWatcher(): fs.FSWatcher { | |
366 | try { | |
367 | return fs.watch(Configuration.configurationFile, (event, filename): void => { | |
368 | if (filename && event === 'change') { | |
369 | // Nullify to force configuration file reading | |
370 | Configuration.configuration = null; | |
371 | if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) { | |
372 | Configuration.configurationChangeCallback().catch((error) => { | |
373 | throw typeof error === 'string' ? new Error(error) : error; | |
374 | }); | |
375 | } | |
376 | } | |
377 | }); | |
378 | } catch (error) { | |
379 | Configuration.handleFileException( | |
380 | Configuration.logPrefix(), | |
381 | FileType.Configuration, | |
382 | Configuration.configurationFile, | |
383 | error as NodeJS.ErrnoException | |
384 | ); | |
385 | } | |
386 | } | |
387 | ||
388 | private static isCFEnvironment(): boolean { | |
389 | return process.env.VCAP_APPLICATION !== undefined; | |
390 | } | |
391 | ||
392 | private static getDefaultPerformanceStorageUri(storageType: StorageType) { | |
393 | switch (storageType) { | |
394 | case StorageType.JSON_FILE: | |
395 | return `file://${path.join( | |
396 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'), | |
397 | Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME | |
398 | )}`; | |
399 | case StorageType.SQLITE: | |
400 | return `file://${path.join( | |
401 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'), | |
402 | `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db` | |
403 | )}`; | |
404 | default: | |
405 | throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`); | |
406 | } | |
407 | } | |
408 | ||
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 | ||
417 | private static handleFileException( | |
418 | logPrefix: string, | |
419 | fileType: FileType, | |
420 | filePath: string, | |
421 | error: NodeJS.ErrnoException, | |
422 | params: HandleErrorParams<EmptyObject> = { throwError: true } | |
423 | ): void { | |
424 | const prefix = logPrefix.trim().length !== 0 ? `${logPrefix} ` : ''; | |
425 | let logMsg: string; | |
426 | switch (error.code) { | |
427 | case 'ENOENT': | |
428 | logMsg = `${fileType} file ${filePath} not found: `; | |
429 | break; | |
430 | case 'EEXIST': | |
431 | logMsg = `${fileType} file ${filePath} already exists: `; | |
432 | break; | |
433 | case 'EACCES': | |
434 | logMsg = `${fileType} file ${filePath} access denied: `; | |
435 | break; | |
436 | default: | |
437 | logMsg = `${fileType} file ${filePath} error: `; | |
438 | } | |
439 | console.error(`${chalk.green(prefix)}${chalk.red(logMsg)}`, error); | |
440 | if (params?.throwError) { | |
441 | throw error; | |
442 | } | |
443 | } | |
444 | } |