Version 1.1.50
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
CommitLineData
2dcfe98e 1import ConfigurationData, { StationTemplateUrl, StorageConfiguration, SupervisionUrlDistribution, UIWebSocketServerConfiguration } from '../types/ConfigurationData';
e118beaa 2
322c9192 3import Constants from './Constants';
e0a50bcd 4import { HandleErrorParams } from '../types/Error';
6a49ad23 5import { ServerOptions } from 'ws';
72f041bd 6import { StorageType } from '../types/Storage';
9efbac5b 7import type { WorkerChoiceStrategy } from 'poolifier';
a4624c96 8import { WorkerProcessType } from '../types/Worker';
8eac9a09 9import chalk from 'chalk';
3f40bc9c 10import fs from 'fs';
bf1866b2 11import path from 'path';
7dde0b73 12
3f40bc9c 13export default class Configuration {
bf1866b2 14 private static configurationFilePath = path.join(path.resolve(__dirname, '../'), 'assets', 'config.json');
ded13d97 15 private static configurationFileWatcher: fs.FSWatcher;
6e0964c8 16 private static configuration: ConfigurationData | null = null;
e57acf6a
JB
17 private static configurationChangeCallback: () => Promise<void>;
18
19 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
20 Configuration.configurationChangeCallback = cb;
21 }
7dde0b73 22
72f041bd 23 static getLogStatisticsInterval(): number {
e4362ed7 24 Configuration.warnDeprecatedConfigurationKey('statisticsDisplayInterval', null, 'Use \'logStatisticsInterval\' instead');
7dde0b73 25 // Read conf
72f041bd
JB
26 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval') ? Configuration.getConfig().logStatisticsInterval : 60;
27 }
28
6a49ad23
JB
29 static getUIWebSocketServer(): UIWebSocketServerConfiguration {
30 let options: ServerOptions = {
31 host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
32 port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT
33 };
34 let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
35 enabled: true,
36 options
37 };
38 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
39 if (Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')) {
40 options = {
1ba1e8fb 41 ...options,
6a49ad23
JB
42 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer.options, 'host') && { host: Configuration.getConfig().uiWebSocketServer.options.host },
43 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer.options, 'port') && { port: Configuration.getConfig().uiWebSocketServer.options.port }
44 };
45 }
46 uiWebSocketServerConfiguration =
47 {
1ba1e8fb 48 ...uiWebSocketServerConfiguration,
6a49ad23
JB
49 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'enabled') && { enabled: Configuration.getConfig().uiWebSocketServer.enabled },
50 options
51 };
52 }
53 return uiWebSocketServerConfiguration;
54 }
55
72f041bd 56 static getPerformanceStorage(): StorageConfiguration {
1f5df42a 57 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', 'Use \'uri\' instead');
6a49ad23
JB
58 let storageConfiguration: StorageConfiguration = {
59 enabled: false,
60 type: StorageType.JSON_FILE,
1f5df42a 61 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE)
6a49ad23 62 };
72f041bd
JB
63 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
64 storageConfiguration =
65 {
1ba1e8fb
JB
66 ...storageConfiguration,
67 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'enabled') && { enabled: Configuration.getConfig().performanceStorage.enabled },
68 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'type') && { type: Configuration.getConfig().performanceStorage.type },
69 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'uri') && { uri: this.getDefaultPerformanceStorageUri(Configuration.getConfig()?.performanceStorage?.type ?? StorageType.JSON_FILE) }
72f041bd 70 };
72f041bd
JB
71 }
72 return storageConfiguration;
7dde0b73
JB
73 }
74
9ccca265 75 static getAutoReconnectMaxRetries(): number {
e4362ed7
JB
76 Configuration.warnDeprecatedConfigurationKey('autoReconnectTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
77 Configuration.warnDeprecatedConfigurationKey('connectionTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
78 Configuration.warnDeprecatedConfigurationKey('autoReconnectMaxRetries', null, 'Use it in charging station template instead');
7dde0b73 79 // Read conf
963ee397 80 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
3574dfd3
JB
81 return Configuration.getConfig().autoReconnectMaxRetries;
82 }
7dde0b73
JB
83 }
84
1f5df42a
JB
85 static getStationTemplateUrls(): StationTemplateUrl[] {
86 Configuration.warnDeprecatedConfigurationKey('stationTemplateURLs', null, 'Use \'stationTemplateUrls\' instead');
87 !Configuration.isUndefined(Configuration.getConfig()['stationTemplateURLs']) && (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()['stationTemplateURLs'] as StationTemplateUrl[]);
88 Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => {
89 if (!Configuration.isUndefined(stationUrl['numberOfStation'])) {
90 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${stationUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`);
eb3937cb
JB
91 }
92 });
7dde0b73 93 // Read conf
1f5df42a 94 return Configuration.getConfig().stationTemplateUrls;
7dde0b73
JB
95 }
96
a4624c96 97 static getWorkerProcess(): WorkerProcessType {
e4362ed7 98 Configuration.warnDeprecatedConfigurationKey('useWorkerPool;', null, 'Use \'workerProcess\' to define the type of worker process to use instead');
a4624c96
JB
99 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess') ? Configuration.getConfig().workerProcess : WorkerProcessType.WORKER_SET;
100 }
101
322c9192
JB
102 static getWorkerStartDelay(): number {
103 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay') ? Configuration.getConfig().workerStartDelay : Constants.WORKER_START_DELAY;
104 }
105
4bfd80fa
JB
106 static getElementStartDelay(): number {
107 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'elementStartDelay') ? Configuration.getConfig().elementStartDelay : Constants.ELEMENT_START_DELAY;
108 }
109
a4624c96 110 static getWorkerPoolMinSize(): number {
1f0052b9 111 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize') ? Configuration.getConfig().workerPoolMinSize : Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
7dde0b73
JB
112 }
113
4fa59b8a 114 static getWorkerPoolMaxSize(): number {
e4362ed7 115 Configuration.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead');
1f0052b9 116 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize') ? Configuration.getConfig().workerPoolMaxSize : Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
7dde0b73
JB
117 }
118
9efbac5b
JB
119 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
120 return Configuration.getConfig().workerPoolStrategy;
121 }
122
3d2ff9e4 123 static getChargingStationsPerWorker(): number {
1f0052b9 124 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'chargingStationsPerWorker') ? Configuration.getConfig().chargingStationsPerWorker : Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
3d2ff9e4
J
125 }
126
7ec46a9a 127 static getLogConsole(): boolean {
e4362ed7 128 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead');
963ee397 129 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') ? Configuration.getConfig().logConsole : false;
7dde0b73
JB
130 }
131
a4a21709 132 static getLogFormat(): string {
963ee397 133 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') ? Configuration.getConfig().logFormat : 'simple';
027b409a
JB
134 }
135
6bf6769e 136 static getLogRotate(): boolean {
963ee397 137 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') ? Configuration.getConfig().logRotate : true;
6bf6769e
JB
138 }
139
140 static getLogMaxFiles(): number {
963ee397 141 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') ? Configuration.getConfig().logMaxFiles : 7;
6bf6769e
JB
142 }
143
324fd4ee
JB
144 static getLogLevel(): string {
145 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') ? Configuration.getConfig().logLevel.toLowerCase() : 'info';
2e6f5966
JB
146 }
147
a4a21709 148 static getLogFile(): string {
963ee397 149 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') ? Configuration.getConfig().logFile : 'combined.log';
7dde0b73
JB
150 }
151
7ec46a9a 152 static getLogErrorFile(): string {
e4362ed7 153 Configuration.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead');
963ee397 154 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') ? Configuration.getConfig().logErrorFile : 'error.log';
7dde0b73
JB
155 }
156
2dcfe98e 157 static getSupervisionUrls(): string | string[] {
1f5df42a
JB
158 Configuration.warnDeprecatedConfigurationKey('supervisionURLs', null, 'Use \'supervisionUrls\' instead');
159 !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) && (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as string[]);
7dde0b73 160 // Read conf
1f5df42a 161 return Configuration.getConfig().supervisionUrls;
7dde0b73
JB
162 }
163
2dcfe98e
JB
164 static getSupervisionUrlDistribution(): SupervisionUrlDistribution {
165 Configuration.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', null, 'Use \'supervisionUrlDistribution\' instead');
166 Configuration.warnDeprecatedConfigurationKey('distributeStationsToTenantsEqually', null, 'Use \'supervisionUrlDistribution\' instead');
167 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'supervisionUrlDistribution') ? Configuration.getConfig().supervisionUrlDistribution : SupervisionUrlDistribution.ROUND_ROBIN;
7dde0b73 168 }
eb3937cb 169
23132a44
JB
170 private static logPrefix(): string {
171 return new Date().toLocaleString() + ' Simulator configuration |';
172 }
173
912136b1
JB
174 private static warnDeprecatedConfigurationKey(key: string, sectionName?: string, logMsgToAppend = '') {
175 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
176 if (sectionName && !Configuration.isUndefined(Configuration.getConfig()[sectionName]) && !Configuration.isUndefined(Configuration.getConfig()[sectionName][key])) {
e4362ed7 177 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}}`);
912136b1 178 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
e4362ed7 179 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}}`);
eb3937cb
JB
180 }
181 }
182
183 // Read the config file
184 private static getConfig(): ConfigurationData {
185 if (!Configuration.configuration) {
23132a44
JB
186 try {
187 Configuration.configuration = JSON.parse(fs.readFileSync(Configuration.configurationFilePath, 'utf8')) as ConfigurationData;
188 } catch (error) {
189 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error);
190 }
ded13d97
JB
191 if (!Configuration.configurationFileWatcher) {
192 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
193 }
eb3937cb
JB
194 }
195 return Configuration.configuration;
196 }
963ee397 197
ded13d97 198 private static getConfigurationFileWatcher(): fs.FSWatcher {
23132a44 199 try {
860a9c5a 200 return fs.watch(Configuration.configurationFilePath, (event, filename): void => {
3ec10737
JB
201 if (filename && event === 'change') {
202 // Nullify to force configuration file reading
203 Configuration.configuration = null;
204 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
dcaf96dc
JB
205 Configuration.configurationChangeCallback().catch((error) => {
206 throw typeof error === 'string' ? new Error(error) : error;
207 });
3ec10737 208 }
23132a44
JB
209 }
210 });
211 } catch (error) {
860a9c5a 212 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error as Error);
23132a44 213 }
ded13d97
JB
214 }
215
1f5df42a 216 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
d5603918
JB
217 const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
218 switch (storageType) {
219 case StorageType.JSON_FILE:
220 return `file://${path.join(path.resolve(__dirname, '../../'), Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME)}`;
221 case StorageType.SQLITE:
222 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
223 default:
224 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
225 }
226 }
227
73d09045 228 private static objectHasOwnProperty(object: unknown, property: string): boolean {
23132a44 229 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
963ee397
JB
230 }
231
73d09045 232 private static isUndefined(obj: unknown): boolean {
963ee397
JB
233 return typeof obj === 'undefined';
234 }
23132a44 235
e0a50bcd 236 private static handleFileException(logPrefix: string, fileType: string, filePath: string, error: NodeJS.ErrnoException, params: HandleErrorParams = { throwError: true }): void {
23132a44
JB
237 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
238 if (error.code === 'ENOENT') {
e4362ed7 239 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '), error);
72f041bd 240 } else if (error.code === 'EEXIST') {
e4362ed7 241 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '), error);
72f041bd 242 } else if (error.code === 'EACCES') {
e4362ed7 243 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '), error);
23132a44 244 } else {
e4362ed7 245 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '), error);
23132a44 246 }
e0a50bcd
JB
247 if (params?.throwError) {
248 throw error;
249 }
23132a44 250 }
7dde0b73 251}