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