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