Commit | Line | Data |
---|---|---|
c8eeb62b JB |
1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
a6b3c6c3 | 3 | import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from '../utils/CircularArray'; |
c0560973 | 4 | import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests'; |
57939a9d | 5 | import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks'; |
0c142310 | 6 | import Statistics, { StatisticsData, TimeSeries } from '../types/Statistics'; |
63b48f77 | 7 | |
98dc07fa | 8 | import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker'; |
a6b3c6c3 | 9 | import Configuration from '../utils/Configuration'; |
d2a64eb5 | 10 | import { MessageType } from '../types/ocpp/MessageType'; |
2a370053 | 11 | import { URL } from 'url'; |
a6b3c6c3 | 12 | import Utils from '../utils/Utils'; |
a6b3c6c3 | 13 | import logger from '../utils/Logger'; |
81797102 | 14 | import { parentPort } from 'worker_threads'; |
7dde0b73 | 15 | |
54b1efe0 | 16 | export default class PerformanceStatistics { |
9e23580d | 17 | private readonly objId: string; |
aef1b33a | 18 | private performanceObserver: PerformanceObserver; |
9e23580d | 19 | private readonly statistics: Statistics; |
aef1b33a | 20 | private displayInterval: NodeJS.Timeout; |
560bcf5b | 21 | |
2a370053 | 22 | public constructor(objId: string, URI: URL) { |
c0560973 | 23 | this.objId = objId; |
aef1b33a | 24 | this.initializePerformanceObserver(); |
ff4b895e | 25 | this.statistics = { id: this.objId ?? 'Object id not specified', URI: URI.toString(), createdAt: new Date(), statisticsData: new Map<string, Partial<StatisticsData>>() }; |
560bcf5b JB |
26 | } |
27 | ||
aef1b33a | 28 | public static beginMeasure(id: string): string { |
c63c21bc JB |
29 | const markId = `${id.charAt(0).toUpperCase() + id.slice(1)}~${Utils.generateUUID()}`; |
30 | performance.mark(markId); | |
31 | return markId; | |
57939a9d JB |
32 | } |
33 | ||
c63c21bc JB |
34 | public static endMeasure(name: string, markId: string): void { |
35 | performance.measure(name, markId); | |
36 | performance.clearMarks(markId); | |
aef1b33a JB |
37 | } |
38 | ||
39 | public addRequestStatistic(command: RequestCommand | IncomingRequestCommand, messageType: MessageType): void { | |
7f134aca | 40 | switch (messageType) { |
d2a64eb5 | 41 | case MessageType.CALL_MESSAGE: |
ff4b895e JB |
42 | if (this.statistics.statisticsData.has(command) && this.statistics.statisticsData.get(command)?.countRequest) { |
43 | this.statistics.statisticsData.get(command).countRequest++; | |
7dde0b73 | 44 | } else { |
ff4b895e | 45 | this.statistics.statisticsData.set(command, Object.assign({ countRequest: 1 }, this.statistics.statisticsData.get(command))); |
7f134aca JB |
46 | } |
47 | break; | |
d2a64eb5 | 48 | case MessageType.CALL_RESULT_MESSAGE: |
ff4b895e JB |
49 | if (this.statistics.statisticsData.has(command) && this.statistics.statisticsData.get(command)?.countResponse) { |
50 | this.statistics.statisticsData.get(command).countResponse++; | |
7f134aca | 51 | } else { |
ff4b895e | 52 | this.statistics.statisticsData.set(command, Object.assign({ countResponse: 1 }, this.statistics.statisticsData.get(command))); |
7dde0b73 | 53 | } |
7f134aca | 54 | break; |
d2a64eb5 | 55 | case MessageType.CALL_ERROR_MESSAGE: |
ff4b895e JB |
56 | if (this.statistics.statisticsData.has(command) && this.statistics.statisticsData.get(command)?.countError) { |
57 | this.statistics.statisticsData.get(command).countError++; | |
7f134aca | 58 | } else { |
ff4b895e | 59 | this.statistics.statisticsData.set(command, Object.assign({ countError: 1 }, this.statistics.statisticsData.get(command))); |
7f134aca JB |
60 | } |
61 | break; | |
62 | default: | |
54b1efe0 | 63 | logger.error(`${this.logPrefix()} wrong message type ${messageType}`); |
7f134aca | 64 | break; |
7dde0b73 JB |
65 | } |
66 | } | |
67 | ||
aef1b33a | 68 | public start(): void { |
72f041bd JB |
69 | this.startLogStatisticsInterval(); |
70 | if (Configuration.getPerformanceStorage().enabled) { | |
71 | logger.info(`${this.logPrefix()} storage enabled: type ${Configuration.getPerformanceStorage().type}, URI: ${Configuration.getPerformanceStorage().URI}`); | |
72 | } | |
7dde0b73 JB |
73 | } |
74 | ||
aef1b33a | 75 | public stop(): void { |
7874b0b1 JB |
76 | if (this.displayInterval) { |
77 | clearInterval(this.displayInterval); | |
78 | } | |
aef1b33a | 79 | performance.clearMarks(); |
087a502d JB |
80 | this.performanceObserver?.disconnect(); |
81 | } | |
82 | ||
83 | public restart(): void { | |
84 | this.stop(); | |
85 | this.start(); | |
136c90ba JB |
86 | } |
87 | ||
aef1b33a JB |
88 | private initializePerformanceObserver(): void { |
89 | this.performanceObserver = new PerformanceObserver((list) => { | |
eb835fa8 JB |
90 | const lastPerformanceEntry = list.getEntries()[0]; |
91 | this.addPerformanceEntryToStatistics(lastPerformanceEntry); | |
92 | logger.debug(`${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`, lastPerformanceEntry); | |
a0ba4ced | 93 | }); |
aef1b33a JB |
94 | this.performanceObserver.observe({ entryTypes: ['measure'] }); |
95 | } | |
96 | ||
aef1b33a JB |
97 | private logStatistics(): void { |
98 | logger.info(this.logPrefix() + ' %j', this.statistics); | |
7dde0b73 JB |
99 | } |
100 | ||
72f041bd JB |
101 | private startLogStatisticsInterval(): void { |
102 | if (Configuration.getLogStatisticsInterval() > 0) { | |
aef1b33a JB |
103 | this.displayInterval = setInterval(() => { |
104 | this.logStatistics(); | |
72f041bd | 105 | }, Configuration.getLogStatisticsInterval() * 1000); |
d7d1db72 | 106 | logger.info(this.logPrefix() + ' logged every ' + Utils.formatDurationSeconds(Configuration.getLogStatisticsInterval())); |
aef1b33a | 107 | } else { |
72f041bd | 108 | logger.info(this.logPrefix() + ' log interval is set to ' + Configuration.getLogStatisticsInterval().toString() + '. Not logging statistics'); |
7dde0b73 JB |
109 | } |
110 | } | |
111 | ||
6bf6769e JB |
112 | private median(dataSet: number[]): number { |
113 | if (Array.isArray(dataSet) && dataSet.length === 1) { | |
114 | return dataSet[0]; | |
115 | } | |
2891f761 | 116 | const sortedDataSet = dataSet.slice().sort((a, b) => (a - b)); |
6bf6769e JB |
117 | const middleIndex = Math.floor(sortedDataSet.length / 2); |
118 | if (sortedDataSet.length % 2) { | |
119 | return sortedDataSet[middleIndex / 2]; | |
120 | } | |
121 | return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2; | |
122 | } | |
123 | ||
b49422c6 JB |
124 | // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree |
125 | private percentile(dataSet: number[], percentile: number): number { | |
126 | if (percentile < 0 && percentile > 100) { | |
127 | throw new RangeError('Percentile is not between 0 and 100'); | |
128 | } | |
129 | if (Utils.isEmptyArray(dataSet)) { | |
130 | return 0; | |
131 | } | |
2891f761 | 132 | const sortedDataSet = dataSet.slice().sort((a, b) => (a - b)); |
b49422c6 JB |
133 | if (percentile === 0) { |
134 | return sortedDataSet[0]; | |
135 | } | |
136 | if (percentile === 100) { | |
137 | return sortedDataSet[sortedDataSet.length - 1]; | |
138 | } | |
139 | const percentileIndex = ((percentile / 100) * sortedDataSet.length) - 1; | |
140 | if (Number.isInteger(percentileIndex)) { | |
141 | return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2; | |
142 | } | |
143 | return sortedDataSet[Math.round(percentileIndex)]; | |
144 | } | |
145 | ||
aeada1fa JB |
146 | private stdDeviation(dataSet: number[]): number { |
147 | let totalDataSet = 0; | |
148 | for (const data of dataSet) { | |
149 | totalDataSet += data; | |
150 | } | |
151 | const dataSetMean = totalDataSet / dataSet.length; | |
152 | let totalGeometricDeviation = 0; | |
153 | for (const data of dataSet) { | |
154 | const deviation = data - dataSetMean; | |
155 | totalGeometricDeviation += deviation * deviation; | |
156 | } | |
157 | return Math.sqrt(totalGeometricDeviation / dataSet.length); | |
158 | } | |
159 | ||
b49422c6 JB |
160 | private addPerformanceEntryToStatistics(entry: PerformanceEntry): void { |
161 | let entryName = entry.name; | |
e9017bfc | 162 | // Rename entry name |
b49422c6 JB |
163 | const MAP_NAME: Record<string, string> = {}; |
164 | if (MAP_NAME[entryName]) { | |
165 | entryName = MAP_NAME[entryName]; | |
7ec46a9a JB |
166 | } |
167 | // Initialize command statistics | |
ff4b895e JB |
168 | if (!this.statistics.statisticsData.has(entryName)) { |
169 | this.statistics.statisticsData.set(entryName, {}); | |
7ec46a9a | 170 | } |
b49422c6 | 171 | // Update current statistics |
a6b3c6c3 | 172 | this.statistics.updatedAt = new Date(); |
928e662d JB |
173 | this.statistics.statisticsData.get(entryName).countTimeMeasurement = this.statistics.statisticsData.get(entryName)?.countTimeMeasurement |
174 | ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1 | |
175 | : 1; | |
ff4b895e | 176 | this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration; |
928e662d JB |
177 | this.statistics.statisticsData.get(entryName).minTimeMeasurement = this.statistics.statisticsData.get(entryName)?.minTimeMeasurement |
178 | ? (this.statistics.statisticsData.get(entryName).minTimeMeasurement > entry.duration ? entry.duration : this.statistics.statisticsData.get(entryName).minTimeMeasurement) | |
179 | : entry.duration; | |
180 | this.statistics.statisticsData.get(entryName).maxTimeMeasurement = this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement | |
181 | ? (this.statistics.statisticsData.get(entryName).maxTimeMeasurement < entry.duration ? entry.duration : this.statistics.statisticsData.get(entryName).maxTimeMeasurement) | |
182 | : entry.duration; | |
183 | this.statistics.statisticsData.get(entryName).totalTimeMeasurement = this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement | |
184 | ? this.statistics.statisticsData.get(entryName).totalTimeMeasurement + entry.duration | |
185 | : entry.duration; | |
ff4b895e | 186 | this.statistics.statisticsData.get(entryName).avgTimeMeasurement = this.statistics.statisticsData.get(entryName).totalTimeMeasurement / this.statistics.statisticsData.get(entryName).countTimeMeasurement; |
0c142310 JB |
187 | Array.isArray(this.statistics.statisticsData.get(entryName).timeMeasurementSeries) |
188 | ? this.statistics.statisticsData.get(entryName).timeMeasurementSeries.push({ timestamp: entry.startTime, value: entry.duration }) | |
189 | : this.statistics.statisticsData.get(entryName).timeMeasurementSeries = new CircularArray<TimeSeries>(DEFAULT_CIRCULAR_ARRAY_SIZE, { timestamp: entry.startTime, value: entry.duration }); | |
190 | this.statistics.statisticsData.get(entryName).medTimeMeasurement = this.median(this.extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).timeMeasurementSeries)); | |
191 | this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement = this.percentile(this.extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).timeMeasurementSeries), 95); | |
192 | this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = this.stdDeviation(this.extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).timeMeasurementSeries)); | |
72f041bd | 193 | if (Configuration.getPerformanceStorage().enabled) { |
98dc07fa | 194 | parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS, data: this.statistics }); |
72f041bd | 195 | } |
7ec46a9a JB |
196 | } |
197 | ||
0c142310 JB |
198 | private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] { |
199 | return timeSeries.map((timeSeriesItem) => timeSeriesItem.value); | |
200 | } | |
201 | ||
c0560973 | 202 | private logPrefix(): string { |
54b1efe0 | 203 | return Utils.logPrefix(` ${this.objId} | Performance statistics`); |
6af9012e | 204 | } |
7dde0b73 | 205 | } |