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'; |
aef1b33a | 6 | import Statistics, { StatisticsData } 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 { |
418106c8 | 17 | private objId: string; |
aef1b33a JB |
18 | private performanceObserver: PerformanceObserver; |
19 | private statistics: Statistics; | |
20 | private displayInterval: NodeJS.Timeout; | |
560bcf5b | 21 | |
2a370053 | 22 | public constructor(objId: string, URI: URL) { |
c0560973 | 23 | this.objId = objId; |
aef1b33a | 24 | this.initializePerformanceObserver(); |
2a370053 | 25 | this.statistics = { id: this.objId ?? 'Object id not specified', URI: URI.toString(), createdAt: new Date(), 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: |
aef1b33a JB |
42 | if (this.statistics.statisticsData[command] && this.statistics.statisticsData[command].countRequest) { |
43 | this.statistics.statisticsData[command].countRequest++; | |
7dde0b73 | 44 | } else { |
aef1b33a JB |
45 | this.statistics.statisticsData[command] = {} as StatisticsData; |
46 | this.statistics.statisticsData[command].countRequest = 1; | |
7f134aca JB |
47 | } |
48 | break; | |
d2a64eb5 | 49 | case MessageType.CALL_RESULT_MESSAGE: |
aef1b33a JB |
50 | if (this.statistics.statisticsData[command]) { |
51 | if (this.statistics.statisticsData[command].countResponse) { | |
52 | this.statistics.statisticsData[command].countResponse++; | |
7f134aca | 53 | } else { |
aef1b33a | 54 | this.statistics.statisticsData[command].countResponse = 1; |
7f134aca JB |
55 | } |
56 | } else { | |
aef1b33a JB |
57 | this.statistics.statisticsData[command] = {} as StatisticsData; |
58 | this.statistics.statisticsData[command].countResponse = 1; | |
7dde0b73 | 59 | } |
7f134aca | 60 | break; |
d2a64eb5 | 61 | case MessageType.CALL_ERROR_MESSAGE: |
aef1b33a JB |
62 | if (this.statistics.statisticsData[command]) { |
63 | if (this.statistics.statisticsData[command].countError) { | |
64 | this.statistics.statisticsData[command].countError++; | |
7f134aca | 65 | } else { |
aef1b33a | 66 | this.statistics.statisticsData[command].countError = 1; |
7f134aca JB |
67 | } |
68 | } else { | |
aef1b33a JB |
69 | this.statistics.statisticsData[command] = {} as StatisticsData; |
70 | this.statistics.statisticsData[command].countError = 1; | |
7f134aca JB |
71 | } |
72 | break; | |
73 | default: | |
54b1efe0 | 74 | logger.error(`${this.logPrefix()} wrong message type ${messageType}`); |
7f134aca | 75 | break; |
7dde0b73 JB |
76 | } |
77 | } | |
78 | ||
aef1b33a | 79 | public start(): void { |
72f041bd JB |
80 | this.startLogStatisticsInterval(); |
81 | if (Configuration.getPerformanceStorage().enabled) { | |
82 | logger.info(`${this.logPrefix()} storage enabled: type ${Configuration.getPerformanceStorage().type}, URI: ${Configuration.getPerformanceStorage().URI}`); | |
83 | } | |
7dde0b73 JB |
84 | } |
85 | ||
aef1b33a | 86 | public stop(): void { |
7874b0b1 JB |
87 | if (this.displayInterval) { |
88 | clearInterval(this.displayInterval); | |
89 | } | |
aef1b33a | 90 | performance.clearMarks(); |
087a502d JB |
91 | this.performanceObserver?.disconnect(); |
92 | } | |
93 | ||
94 | public restart(): void { | |
95 | this.stop(); | |
96 | this.start(); | |
136c90ba JB |
97 | } |
98 | ||
aef1b33a JB |
99 | private initializePerformanceObserver(): void { |
100 | this.performanceObserver = new PerformanceObserver((list) => { | |
eb835fa8 JB |
101 | const lastPerformanceEntry = list.getEntries()[0]; |
102 | this.addPerformanceEntryToStatistics(lastPerformanceEntry); | |
103 | logger.debug(`${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`, lastPerformanceEntry); | |
a0ba4ced | 104 | }); |
aef1b33a JB |
105 | this.performanceObserver.observe({ entryTypes: ['measure'] }); |
106 | } | |
107 | ||
aef1b33a JB |
108 | private logStatistics(): void { |
109 | logger.info(this.logPrefix() + ' %j', this.statistics); | |
7dde0b73 JB |
110 | } |
111 | ||
72f041bd JB |
112 | private startLogStatisticsInterval(): void { |
113 | if (Configuration.getLogStatisticsInterval() > 0) { | |
aef1b33a JB |
114 | this.displayInterval = setInterval(() => { |
115 | this.logStatistics(); | |
72f041bd | 116 | }, Configuration.getLogStatisticsInterval() * 1000); |
d7d1db72 | 117 | logger.info(this.logPrefix() + ' logged every ' + Utils.formatDurationSeconds(Configuration.getLogStatisticsInterval())); |
aef1b33a | 118 | } else { |
72f041bd | 119 | logger.info(this.logPrefix() + ' log interval is set to ' + Configuration.getLogStatisticsInterval().toString() + '. Not logging statistics'); |
7dde0b73 JB |
120 | } |
121 | } | |
122 | ||
6bf6769e JB |
123 | private median(dataSet: number[]): number { |
124 | if (Array.isArray(dataSet) && dataSet.length === 1) { | |
125 | return dataSet[0]; | |
126 | } | |
2891f761 | 127 | const sortedDataSet = dataSet.slice().sort((a, b) => (a - b)); |
6bf6769e JB |
128 | const middleIndex = Math.floor(sortedDataSet.length / 2); |
129 | if (sortedDataSet.length % 2) { | |
130 | return sortedDataSet[middleIndex / 2]; | |
131 | } | |
132 | return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2; | |
133 | } | |
134 | ||
b49422c6 JB |
135 | // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree |
136 | private percentile(dataSet: number[], percentile: number): number { | |
137 | if (percentile < 0 && percentile > 100) { | |
138 | throw new RangeError('Percentile is not between 0 and 100'); | |
139 | } | |
140 | if (Utils.isEmptyArray(dataSet)) { | |
141 | return 0; | |
142 | } | |
2891f761 | 143 | const sortedDataSet = dataSet.slice().sort((a, b) => (a - b)); |
b49422c6 JB |
144 | if (percentile === 0) { |
145 | return sortedDataSet[0]; | |
146 | } | |
147 | if (percentile === 100) { | |
148 | return sortedDataSet[sortedDataSet.length - 1]; | |
149 | } | |
150 | const percentileIndex = ((percentile / 100) * sortedDataSet.length) - 1; | |
151 | if (Number.isInteger(percentileIndex)) { | |
152 | return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2; | |
153 | } | |
154 | return sortedDataSet[Math.round(percentileIndex)]; | |
155 | } | |
156 | ||
aeada1fa JB |
157 | private stdDeviation(dataSet: number[]): number { |
158 | let totalDataSet = 0; | |
159 | for (const data of dataSet) { | |
160 | totalDataSet += data; | |
161 | } | |
162 | const dataSetMean = totalDataSet / dataSet.length; | |
163 | let totalGeometricDeviation = 0; | |
164 | for (const data of dataSet) { | |
165 | const deviation = data - dataSetMean; | |
166 | totalGeometricDeviation += deviation * deviation; | |
167 | } | |
168 | return Math.sqrt(totalGeometricDeviation / dataSet.length); | |
169 | } | |
170 | ||
b49422c6 JB |
171 | private addPerformanceEntryToStatistics(entry: PerformanceEntry): void { |
172 | let entryName = entry.name; | |
e9017bfc | 173 | // Rename entry name |
b49422c6 JB |
174 | const MAP_NAME: Record<string, string> = {}; |
175 | if (MAP_NAME[entryName]) { | |
176 | entryName = MAP_NAME[entryName]; | |
7ec46a9a JB |
177 | } |
178 | // Initialize command statistics | |
b49422c6 JB |
179 | if (!this.statistics.statisticsData[entryName]) { |
180 | this.statistics.statisticsData[entryName] = {} as StatisticsData; | |
7ec46a9a | 181 | } |
b49422c6 | 182 | // Update current statistics |
a6b3c6c3 | 183 | this.statistics.updatedAt = new Date(); |
b49422c6 JB |
184 | this.statistics.statisticsData[entryName].countTimeMeasurement = this.statistics.statisticsData[entryName].countTimeMeasurement ? this.statistics.statisticsData[entryName].countTimeMeasurement + 1 : 1; |
185 | this.statistics.statisticsData[entryName].currentTimeMeasurement = entry.duration; | |
186 | this.statistics.statisticsData[entryName].minTimeMeasurement = this.statistics.statisticsData[entryName].minTimeMeasurement ? (this.statistics.statisticsData[entryName].minTimeMeasurement > entry.duration ? entry.duration : this.statistics.statisticsData[entryName].minTimeMeasurement) : entry.duration; | |
187 | this.statistics.statisticsData[entryName].maxTimeMeasurement = this.statistics.statisticsData[entryName].maxTimeMeasurement ? (this.statistics.statisticsData[entryName].maxTimeMeasurement < entry.duration ? entry.duration : this.statistics.statisticsData[entryName].maxTimeMeasurement) : entry.duration; | |
188 | this.statistics.statisticsData[entryName].totalTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement ? this.statistics.statisticsData[entryName].totalTimeMeasurement + entry.duration : entry.duration; | |
189 | this.statistics.statisticsData[entryName].avgTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement / this.statistics.statisticsData[entryName].countTimeMeasurement; | |
190 | Array.isArray(this.statistics.statisticsData[entryName].timeMeasurementSeries) ? this.statistics.statisticsData[entryName].timeMeasurementSeries.push(entry.duration) : this.statistics.statisticsData[entryName].timeMeasurementSeries = new CircularArray<number>(DEFAULT_CIRCULAR_ARRAY_SIZE, entry.duration); | |
191 | this.statistics.statisticsData[entryName].medTimeMeasurement = this.median(this.statistics.statisticsData[entryName].timeMeasurementSeries); | |
192 | this.statistics.statisticsData[entryName].ninetyFiveThPercentileTimeMeasurement = this.percentile(this.statistics.statisticsData[entryName].timeMeasurementSeries, 95); | |
193 | this.statistics.statisticsData[entryName].stdDevTimeMeasurement = this.stdDeviation(this.statistics.statisticsData[entryName].timeMeasurementSeries); | |
72f041bd | 194 | if (Configuration.getPerformanceStorage().enabled) { |
98dc07fa | 195 | parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS, data: this.statistics }); |
72f041bd | 196 | } |
7ec46a9a JB |
197 | } |
198 | ||
c0560973 | 199 | private logPrefix(): string { |
54b1efe0 | 200 | return Utils.logPrefix(` ${this.objId} | Performance statistics`); |
6af9012e | 201 | } |
7dde0b73 | 202 | } |