Properly default also the performance storage enablement
[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 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', 'Use \'uri\' instead');
55 let storageConfiguration: StorageConfiguration = {
56 enabled: false,
57 type: StorageType.JSON_FILE,
58 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE)
59 };
60 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
61 storageConfiguration =
62 {
63 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'enabled')
64 ? { enabled: Configuration.getConfig().performanceStorage.enabled }
65 : { enabled: false },
66 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'type')
67 ? { type: Configuration.getConfig().performanceStorage.type }
68 : { type: StorageType.JSON_FILE },
69 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'uri')
70 ? { uri: Configuration.getConfig().performanceStorage.uri }
71 : { uri: this.getDefaultPerformanceStorageUri(Configuration.getConfig()?.performanceStorage?.type ?? StorageType.JSON_FILE) }
72 };
73 }
74 return storageConfiguration;
75 }
76
77 static getAutoReconnectMaxRetries(): number {
78 Configuration.warnDeprecatedConfigurationKey('autoReconnectTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
79 Configuration.warnDeprecatedConfigurationKey('connectionTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
80 Configuration.warnDeprecatedConfigurationKey('autoReconnectMaxRetries', null, 'Use it in charging station template instead');
81 // Read conf
82 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
83 return Configuration.getConfig().autoReconnectMaxRetries;
84 }
85 }
86
87 static getStationTemplateUrls(): StationTemplateUrl[] {
88 Configuration.warnDeprecatedConfigurationKey('stationTemplateURLs', null, 'Use \'stationTemplateUrls\' instead');
89 !Configuration.isUndefined(Configuration.getConfig()['stationTemplateURLs']) && (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()['stationTemplateURLs'] as StationTemplateUrl[]);
90 Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => {
91 if (!Configuration.isUndefined(stationUrl['numberOfStation'])) {
92 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${stationUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`);
93 }
94 });
95 // Read conf
96 return Configuration.getConfig().stationTemplateUrls;
97 }
98
99 static getWorkerProcess(): WorkerProcessType {
100 Configuration.warnDeprecatedConfigurationKey('useWorkerPool;', null, 'Use \'workerProcess\' to define the type of worker process to use instead');
101 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess') ? Configuration.getConfig().workerProcess : WorkerProcessType.WORKER_SET;
102 }
103
104 static getWorkerStartDelay(): number {
105 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay') ? Configuration.getConfig().workerStartDelay : Constants.WORKER_START_DELAY;
106 }
107
108 static getWorkerPoolMinSize(): number {
109 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize') ? Configuration.getConfig().workerPoolMinSize : Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
110 }
111
112 static getWorkerPoolMaxSize(): number {
113 Configuration.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead');
114 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize') ? Configuration.getConfig().workerPoolMaxSize : Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
115 }
116
117 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
118 return Configuration.getConfig().workerPoolStrategy;
119 }
120
121 static getChargingStationsPerWorker(): number {
122 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'chargingStationsPerWorker') ? Configuration.getConfig().chargingStationsPerWorker : Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
123 }
124
125 static getLogConsole(): boolean {
126 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead');
127 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') ? Configuration.getConfig().logConsole : false;
128 }
129
130 static getLogFormat(): string {
131 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') ? Configuration.getConfig().logFormat : 'simple';
132 }
133
134 static getLogRotate(): boolean {
135 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') ? Configuration.getConfig().logRotate : true;
136 }
137
138 static getLogMaxFiles(): number {
139 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') ? Configuration.getConfig().logMaxFiles : 7;
140 }
141
142 static getLogLevel(): string {
143 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') ? Configuration.getConfig().logLevel : 'info';
144 }
145
146 static getLogFile(): string {
147 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') ? Configuration.getConfig().logFile : 'combined.log';
148 }
149
150 static getLogErrorFile(): string {
151 Configuration.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead');
152 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') ? Configuration.getConfig().logErrorFile : 'error.log';
153 }
154
155 static getSupervisionUrls(): string[] {
156 Configuration.warnDeprecatedConfigurationKey('supervisionURLs', null, 'Use \'supervisionUrls\' instead');
157 !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) && (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as string[]);
158 // Read conf
159 return Configuration.getConfig().supervisionUrls;
160 }
161
162 static getDistributeStationsToTenantsEqually(): boolean {
163 Configuration.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', null, 'Use \'distributeStationsToTenantsEqually\' instead');
164 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'distributeStationsToTenantsEqually') ? Configuration.getConfig().distributeStationsToTenantsEqually : true;
165 }
166
167 private static logPrefix(): string {
168 return new Date().toLocaleString() + ' Simulator configuration |';
169 }
170
171 private static warnDeprecatedConfigurationKey(key: string, sectionName?: string, logMsgToAppend = '') {
172 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
173 if (sectionName && !Configuration.isUndefined(Configuration.getConfig()[sectionName]) && !Configuration.isUndefined(Configuration.getConfig()[sectionName][key])) {
174 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}}`);
175 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
176 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}}`);
177 }
178 }
179
180 // Read the config file
181 private static getConfig(): ConfigurationData {
182 if (!Configuration.configuration) {
183 try {
184 Configuration.configuration = JSON.parse(fs.readFileSync(Configuration.configurationFilePath, 'utf8')) as ConfigurationData;
185 } catch (error) {
186 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error);
187 }
188 if (!Configuration.configurationFileWatcher) {
189 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
190 }
191 }
192 return Configuration.configuration;
193 }
194
195 private static getConfigurationFileWatcher(): fs.FSWatcher {
196 try {
197 return fs.watch(Configuration.configurationFilePath, (event, filename): void => {
198 if (filename && event === 'change') {
199 // Nullify to force configuration file reading
200 Configuration.configuration = null;
201 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
202 Configuration.configurationChangeCallback().catch(() => { /* This is intentional */ });
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 }