Add tunable for charging station start delay for linear ramp up
[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 { HandleErrorParams } from '../types/Error';
5 import { ServerOptions } from 'ws';
6 import { StorageType } from '../types/Storage';
7 import type { WorkerChoiceStrategy } from 'poolifier';
8 import { WorkerProcessType } from '../types/Worker';
9 import chalk from 'chalk';
10 import fs from 'fs';
11 import path from 'path';
12
13 export default class Configuration {
14 private static configurationFilePath = path.join(path.resolve(__dirname, '../'), 'assets', 'config.json');
15 private static configurationFileWatcher: fs.FSWatcher;
16 private static configuration: ConfigurationData | null = null;
17 private static configurationChangeCallback: () => Promise<void>;
18
19 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
20 Configuration.configurationChangeCallback = cb;
21 }
22
23 static getLogStatisticsInterval(): number {
24 Configuration.warnDeprecatedConfigurationKey('statisticsDisplayInterval', null, 'Use \'logStatisticsInterval\' instead');
25 // Read conf
26 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval') ? Configuration.getConfig().logStatisticsInterval : 60;
27 }
28
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 = {
41 ...options,
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 {
48 ...uiWebSocketServerConfiguration,
49 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'enabled') && { enabled: Configuration.getConfig().uiWebSocketServer.enabled },
50 options
51 };
52 }
53 return uiWebSocketServerConfiguration;
54 }
55
56 static getPerformanceStorage(): StorageConfiguration {
57 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', 'Use \'uri\' instead');
58 let storageConfiguration: StorageConfiguration = {
59 enabled: false,
60 type: StorageType.JSON_FILE,
61 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE)
62 };
63 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
64 storageConfiguration =
65 {
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) }
70 };
71 }
72 return storageConfiguration;
73 }
74
75 static getAutoReconnectMaxRetries(): number {
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');
79 // Read conf
80 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
81 return Configuration.getConfig().autoReconnectMaxRetries;
82 }
83 }
84
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}`);
91 }
92 });
93 // Read conf
94 return Configuration.getConfig().stationTemplateUrls;
95 }
96
97 static getWorkerProcess(): WorkerProcessType {
98 Configuration.warnDeprecatedConfigurationKey('useWorkerPool;', null, 'Use \'workerProcess\' to define the type of worker process to use instead');
99 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess') ? Configuration.getConfig().workerProcess : WorkerProcessType.WORKER_SET;
100 }
101
102 static getWorkerStartDelay(): number {
103 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay') ? Configuration.getConfig().workerStartDelay : Constants.WORKER_START_DELAY;
104 }
105
106 static getElementStartDelay(): number {
107 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'elementStartDelay') ? Configuration.getConfig().elementStartDelay : Constants.ELEMENT_START_DELAY;
108 }
109
110 static getWorkerPoolMinSize(): number {
111 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize') ? Configuration.getConfig().workerPoolMinSize : Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
112 }
113
114 static getWorkerPoolMaxSize(): number {
115 Configuration.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead');
116 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize') ? Configuration.getConfig().workerPoolMaxSize : Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
117 }
118
119 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
120 return Configuration.getConfig().workerPoolStrategy;
121 }
122
123 static getChargingStationsPerWorker(): number {
124 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'chargingStationsPerWorker') ? Configuration.getConfig().chargingStationsPerWorker : Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
125 }
126
127 static getLogConsole(): boolean {
128 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead');
129 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') ? Configuration.getConfig().logConsole : false;
130 }
131
132 static getLogFormat(): string {
133 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') ? Configuration.getConfig().logFormat : 'simple';
134 }
135
136 static getLogRotate(): boolean {
137 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') ? Configuration.getConfig().logRotate : true;
138 }
139
140 static getLogMaxFiles(): number {
141 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') ? Configuration.getConfig().logMaxFiles : 7;
142 }
143
144 static getLogLevel(): string {
145 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') ? Configuration.getConfig().logLevel.toLowerCase() : 'info';
146 }
147
148 static getLogFile(): string {
149 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') ? Configuration.getConfig().logFile : 'combined.log';
150 }
151
152 static getLogErrorFile(): string {
153 Configuration.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead');
154 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') ? Configuration.getConfig().logErrorFile : 'error.log';
155 }
156
157 static getSupervisionUrls(): string | string[] {
158 Configuration.warnDeprecatedConfigurationKey('supervisionURLs', null, 'Use \'supervisionUrls\' instead');
159 !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) && (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as string[]);
160 // Read conf
161 return Configuration.getConfig().supervisionUrls;
162 }
163
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;
168 }
169
170 private static logPrefix(): string {
171 return new Date().toLocaleString() + ' Simulator configuration |';
172 }
173
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])) {
177 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}}`);
178 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
179 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}}`);
180 }
181 }
182
183 // Read the config file
184 private static getConfig(): ConfigurationData {
185 if (!Configuration.configuration) {
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 }
191 if (!Configuration.configurationFileWatcher) {
192 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
193 }
194 }
195 return Configuration.configuration;
196 }
197
198 private static getConfigurationFileWatcher(): fs.FSWatcher {
199 try {
200 return fs.watch(Configuration.configurationFilePath, (event, filename): void => {
201 if (filename && event === 'change') {
202 // Nullify to force configuration file reading
203 Configuration.configuration = null;
204 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
205 Configuration.configurationChangeCallback().catch((error) => {
206 throw typeof error === 'string' ? new Error(error) : error;
207 });
208 }
209 }
210 });
211 } catch (error) {
212 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error as Error);
213 }
214 }
215
216 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
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
228 private static objectHasOwnProperty(object: unknown, property: string): boolean {
229 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
230 }
231
232 private static isUndefined(obj: unknown): boolean {
233 return typeof obj === 'undefined';
234 }
235
236 private static handleFileException(logPrefix: string, fileType: string, filePath: string, error: NodeJS.ErrnoException, params: HandleErrorParams = { throwError: true }): void {
237 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
238 if (error.code === 'ENOENT') {
239 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '), error);
240 } else if (error.code === 'EEXIST') {
241 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '), error);
242 } else if (error.code === 'EACCES') {
243 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '), error);
244 } else {
245 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '), error);
246 }
247 if (params?.throwError) {
248 throw error;
249 }
250 }
251 }