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