| 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') && { enabled: Configuration.getConfig().performanceStorage.enabled }, |
| 64 | ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'type') |
| 65 | ? { type: Configuration.getConfig().performanceStorage.type } |
| 66 | : { type: StorageType.JSON_FILE }, |
| 67 | ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'uri') |
| 68 | ? { uri: Configuration.getConfig().performanceStorage.uri } |
| 69 | : { 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 getWorkerPoolMinSize(): number { |
| 107 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize') ? Configuration.getConfig().workerPoolMinSize : Constants.DEFAULT_WORKER_POOL_MIN_SIZE; |
| 108 | } |
| 109 | |
| 110 | static getWorkerPoolMaxSize(): number { |
| 111 | Configuration.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead'); |
| 112 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize') ? Configuration.getConfig().workerPoolMaxSize : Constants.DEFAULT_WORKER_POOL_MAX_SIZE; |
| 113 | } |
| 114 | |
| 115 | static getWorkerPoolStrategy(): WorkerChoiceStrategy { |
| 116 | return Configuration.getConfig().workerPoolStrategy; |
| 117 | } |
| 118 | |
| 119 | static getChargingStationsPerWorker(): number { |
| 120 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'chargingStationsPerWorker') ? Configuration.getConfig().chargingStationsPerWorker : Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER; |
| 121 | } |
| 122 | |
| 123 | static getLogConsole(): boolean { |
| 124 | Configuration.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead'); |
| 125 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') ? Configuration.getConfig().logConsole : false; |
| 126 | } |
| 127 | |
| 128 | static getLogFormat(): string { |
| 129 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') ? Configuration.getConfig().logFormat : 'simple'; |
| 130 | } |
| 131 | |
| 132 | static getLogRotate(): boolean { |
| 133 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') ? Configuration.getConfig().logRotate : true; |
| 134 | } |
| 135 | |
| 136 | static getLogMaxFiles(): number { |
| 137 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') ? Configuration.getConfig().logMaxFiles : 7; |
| 138 | } |
| 139 | |
| 140 | static getLogLevel(): string { |
| 141 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') ? Configuration.getConfig().logLevel : 'info'; |
| 142 | } |
| 143 | |
| 144 | static getLogFile(): string { |
| 145 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') ? Configuration.getConfig().logFile : 'combined.log'; |
| 146 | } |
| 147 | |
| 148 | static getLogErrorFile(): string { |
| 149 | Configuration.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead'); |
| 150 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') ? Configuration.getConfig().logErrorFile : 'error.log'; |
| 151 | } |
| 152 | |
| 153 | static getSupervisionUrls(): string[] { |
| 154 | Configuration.warnDeprecatedConfigurationKey('supervisionURLs', null, 'Use \'supervisionUrls\' instead'); |
| 155 | !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) && (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as string[]); |
| 156 | // Read conf |
| 157 | return Configuration.getConfig().supervisionUrls; |
| 158 | } |
| 159 | |
| 160 | static getDistributeStationsToTenantsEqually(): boolean { |
| 161 | Configuration.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', null, 'Use \'distributeStationsToTenantsEqually\' instead'); |
| 162 | return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'distributeStationsToTenantsEqually') ? Configuration.getConfig().distributeStationsToTenantsEqually : true; |
| 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(() => { /* This is intentional */ }); |
| 201 | } |
| 202 | } |
| 203 | }); |
| 204 | } catch (error) { |
| 205 | Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error as Error); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | private static getDefaultPerformanceStorageUri(storageType: StorageType) { |
| 210 | const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`; |
| 211 | switch (storageType) { |
| 212 | case StorageType.JSON_FILE: |
| 213 | return `file://${path.join(path.resolve(__dirname, '../../'), Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME)}`; |
| 214 | case StorageType.SQLITE: |
| 215 | return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`; |
| 216 | default: |
| 217 | throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | private static objectHasOwnProperty(object: unknown, property: string): boolean { |
| 222 | return Object.prototype.hasOwnProperty.call(object, property) as boolean; |
| 223 | } |
| 224 | |
| 225 | private static isUndefined(obj: unknown): boolean { |
| 226 | return typeof obj === 'undefined'; |
| 227 | } |
| 228 | |
| 229 | private static handleFileException(logPrefix: string, fileType: string, filePath: string, error: NodeJS.ErrnoException): void { |
| 230 | const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : ''; |
| 231 | if (error.code === 'ENOENT') { |
| 232 | console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '), error); |
| 233 | } else if (error.code === 'EEXIST') { |
| 234 | console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '), error); |
| 235 | } else if (error.code === 'EACCES') { |
| 236 | console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '), error); |
| 237 | } else { |
| 238 | console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '), error); |
| 239 | } |
| 240 | throw error; |
| 241 | } |
| 242 | } |