Debian Codegraph @

scripts/ipg.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2024 Intel Corporation
4 # Author Walfred Tedeschi <[email protected]>
5 #
6 # SPDX-License-Identifier: BSD-2-Clause
7 #
8 # Parse PcapNG files produced by Profishark and plot interpacket gap, etc.
9 #
10
11 import argparse
12 import binascii
13 import pathlib
14
15 import matplotlib.pyplot as plt
16 import pandas as pd
17 import seaborn as sns
18 from beautifultable import BeautifulTable
19 from scapy.layers.l2 import Dot1Q
20 from scapy.utils import PcapReader
21
22 preambleLength = 7 + 1
23 crcLength = 4
24 headerLength = 18 # With Vlan
25 fullOverhead = preambleLength + crcLength + headerLength
26
27 tclass_cycle_time = 0.001
28
29
30 class Stats:
31 def __init__(self):
32 self.IPG = {
33 "count": 0,
34 "mean": 0,
35 "std" "min": 0,
36 "Q25": 0,
37 "Q50": 0,
38 "Q75": 0,
39 "max": 0,
40 }
41 self.BatchStart = {
42 "count": 0,
43 "mean": 0,
44 "std" "min": 0,
45 "Q25": 0,
46 "Q50": 0,
47 "Q75": 0,
48 "max": 0,
49 }
50 self.BatchEnd = {
51 "count": 0,
52 "mean": 0,
53 "std" "min": 0,
54 "Q25": 0,
55 "Q50": 0,
56 "Q75": 0,
57 "max": 0,
58 }
59 self.BatchCount = {
60 "count": 0,
61 "mean": 0,
62 "std" "min": 0,
63 "Q25": 0,
64 "Q50": 0,
65 "Q75": 0,
66 "max": 0,
67 }
68 self.cycles = 0
69 self.packetLenght = 0
70
71
72 def create_main_table():
73 global tclass_start_cycle
74 ipgTable = BeautifulTable(precision=4)
75 ipgTable.rows.append(["count", "min", "mean", "std", "Q25", "Q50", "Q75", "max"])
76 ipgTable.columns.width = [14, 14, 14, 14, 14, 14, 14, 14]
77 ipgTable.border.left = ""
78 ipgTable.border.right = ""
79 ipgTable.border.top = ""
80 ipgTable.border.bottom = ""
81
82 # Batch Count
83 bcTable = BeautifulTable(precision=4)
84 bcTable.rows.append(["min", "mean", "max"])
85 bcTable.columns.width = [5, 6, 5]
86 bcTable.border.left = ""
87 bcTable.border.right = ""
88 bcTable.border.top = ""
89 bcTable.border.bottom = ""
90 # Batch Start
91 bsTable = BeautifulTable(precision=4)
92 bsTable.rows.append(["min", "mean", "max"])
93 bsTable.columns.width = [14, 14, 14]
94 bsTable.border.left = ""
95 bsTable.border.right = ""
96 bsTable.border.top = ""
97 bsTable.border.bottom = ""
98 # Batch End
99 beTable = BeautifulTable(precision=4)
100 beTable.rows.append(["min", "mean", "max"])
101 beTable.columns.width = [14, 14, 14]
102 beTable.border.left = ""
103 beTable.border.right = ""
104 beTable.border.top = ""
105 beTable.border.bottom = ""
106
107 # Main table
108 mainTable = BeautifulTable(maxwidth=500)
109 mainTable.columns.header = [
110 "Traffic Class",
111 "Cycles",
112 "Pkt Len",
113 "Batch Count",
114 "IPG",
115 "Batch Start",
116 "Batch End",
117 ]
118
119 # mainTable.columns.header = [ "Traffic Class",
120 # "Cycles",
121 # "Pkt Len",
122 # "Batch Count",
123 # "IPG" ]
124 mainTable.rows.append(
125 ["Cycle Time (s)", tclass_cycle_time, "", bcTable, ipgTable, bsTable, beTable]
126 )
127
128 # mainTable.rows.append(["Cycle Time (s)", tclass_cycle_time, "", bcTable, ipgTable])
129
130 return mainTable
131
132
133 def populate_stats(stats, className, table):
134 global tclass_start_cycle
135 resultIPGTable = BeautifulTable(precision=4)
136 try:
137 resultIPGTable.rows.append(
138 [
139 stats.IPG["count"],
140 stats.IPG["min"],
141 stats.IPG["mean"],
142 stats.IPG["std"],
143 stats.IPG["Q25"],
144 stats.IPG["Q50"],
145 stats.IPG["Q75"],
146 stats.IPG["max"],
147 ]
148 )
149 except:
150 print("not enough data to calculate IPG")
151
152 resultIPGTable.columns.width = [14, 14, 14, 14, 14, 14, 14, 14]
153 resultIPGTable.border.left = ""
154 resultIPGTable.border.right = ""
155 resultIPGTable.border.top = ""
156 resultIPGTable.border.bottom = ""
157
158 resultBCTable = BeautifulTable(precision=0)
159
160 try:
161 resultBCTable.rows.append(
162 [stats.BatchCount["min"], stats.BatchCount["mean"], stats.BatchCount["max"]]
163 )
164 except KeyError:
165 print("Missing Batch count values")
166
167 resultBCTable.columns.width = [5, 6, 5]
168 resultBCTable.border.left = ""
169 resultBCTable.border.right = ""
170 resultBCTable.border.top = ""
171 resultBCTable.border.bottom = ""
172
173 resultBSTable = BeautifulTable(precision=6)
174 try:
175 resultBSTable.rows.append(
176 [stats.BatchStart["min"], stats.BatchStart["mean"], stats.BatchStart["max"]]
177 )
178 except KeyError:
179 print("Missing Batch start values")
180
181 resultBSTable.columns.width = [14, 14, 14]
182 resultBSTable.border.left = ""
183 resultBSTable.border.right = ""
184 resultBSTable.border.top = ""
185 resultBSTable.border.bottom = ""
186
187 resultBETable = BeautifulTable(precision=6)
188 try:
189 resultBETable.rows.append(
190 [stats.BatchEnd["min"], stats.BatchEnd["mean"], stats.BatchEnd["max"]]
191 )
192 except KeyError:
193 print("Missing Batch start end")
194
195 resultBETable.columns.width = [14, 14, 14]
196 resultBETable.border.left = ""
197 resultBETable.border.right = ""
198 resultBETable.border.top = ""
199 resultBETable.border.bottom = ""
200 table.rows.append(
201 [
202 className,
203 stats.cycles,
204 stats.packetLenght,
205 resultBCTable,
206 resultIPGTable,
207 resultBSTable,
208 resultBETable,
209 ]
210 )
211 # table.rows.append([className,
212 # stats.cycles,
213 # stats.packetLenght,
214 # resultBCTable,
215 # resultIPGTable])
216
217
218 def cycleOffset(cycleCounter, pkt_time, startTime):
219 global tclass_cycle_time
220 currCycleTime = (cycleCounter - 1) * tclass_cycle_time
221 deltaTime = pkt_time - startTime
222 # if cycleCounter < 4:
223 res = deltaTime - currCycleTime
224 return res
225
226
227 class TrafficClass:
228 global tclass_start_cycle
229
230 def __init__(self, pcp, tcName):
231 self.pcp = pcp
232 self.tcName = tcName
233 self.DeltaTime = []
234 self.DTimeTime = []
235 self.IPG = []
236 self.IPGTime = []
237 self.framesWithinCycle = []
238 self.framesWithinCycleTime = []
239 self.batch_End = []
240 self.batch_Start = []
241 self.burstTime = []
242 self.aveIPGInBurst = []
243 self.countIPG = 0
244 self.lengths = []
245 self.deltaPktTime = 0
246 self.prevPktTime = 0
247 self.curpktTime = 0
248 self.bytesStransmitedPerBurst = 0
249 self.framesInBurst = 0
250 self.prevPktLength = 0
251 self.firstCycle = -1
252 self.cycleCounter = -1
253 self.currentCycle = -1
254 self.curCycleTime = 0
255 self.transmitTime = 0
256 self.burstTimeStart = 0
257 self.burstTimeEnd = 0
258 self.missingWithinACycle = 0
259 self.cur_batch_end = 0
260 self.cur_batch_start = 0
261 self.dataframeIPG = None
262 self.dataframeAveIPG = None
263 self.sequenceErrors = 0
264 self.prevSequenceCounter = 0
265 self.stats = Stats()
266
267 def processPkt(self, pkt, cycleCounter, sequenceCounter):
268 global fullOverhead
269
270 if self.firstCycle == -1:
271 self.firstCycle = cycleCounter
272 self.cycleCounter = cycleCounter
273 self.currentCycle = cycleCounter
274
275 self.prevPktTime = self.curpktTime
276
277 if self.firstCycle == cycleCounter:
278 return
279
280 self.curpktTime = pkt.time
281 self.deltaPktTime = self.curpktTime - self.prevPktTime
282
283 pktLen = headerLength + len(pkt.load)
284 if pktLen not in self.lengths:
285 self.lengths.append(pktLen)
286
287 # Middle of the burst
288 if self.currentCycle == cycleCounter:
289 self.framesInBurst = self.framesInBurst + 1
290 if self.currentCycle > self.firstCycle + 1:
291 self.IPG.append(float((self.deltaPktTime - self.transmitTime) * 1e6))
292 self.IPGTime.append(float(pkt.time))
293 self.countIPG = self.countIPG + 1
294 self.DeltaTime.append(self.deltaPktTime)
295 self.DTimeTime.append(pkt.time)
296 if self.prevSequenceCounter > sequenceCounter:
297 self.sequenceErrors = self.sequenceErrors + 1
298
299 if self.currentCycle != cycleCounter:
300 if self.cycleCounter > self.firstCycle + 1:
301 self.batch_End.append(self.prevPktTime - self.burstTimeEnd)
302 self.burstTimeEnd = self.prevPktTime
303 if self.cycleCounter > self.firstCycle + 1:
304 self.framesWithinCycle.append(self.framesInBurst)
305 self.framesWithinCycleTime.append(pkt.time)
306 # burstTime = self.burstTimeEnd - self.burstTimeStart
307 # print(self.pcp, self.currentCycle, sequenceCounter, self.framesInBurst, burstTime)
308 if self.cycleCounter > self.firstCycle + 1:
309 self.batch_Start.append(self.curpktTime - self.burstTimeStart)
310 self.burstTimeStart = self.curpktTime
311 self.cycleCounter = self.cycleCounter + 1
312 self.framesInBurst = 1
313 self.currentCycle = cycleCounter
314
315 self.prevPktLength = len(pkt.load) + fullOverhead
316 self.bytesStransmitedPerBurst = (
317 self.bytesStransmitedPerBurst + self.prevPktLength
318 )
319 self.transmitTime = (self.prevPktLength * 8) / 1e9
320 self.prevSequenceCounter = sequenceCounter
321
322 def plotMe(self, fileName):
323 if len(self.DeltaTime) == 0:
324 return
325 print(self.lengths)
326 nofFrames = max(self.framesWithinCycle)
327 fig, axs = plt.subplots(2, 2, sharex=True)
328 fig.suptitle(
329 self.tcName
330 + " "
331 + str(self.prevPktLength)
332 + "bytes x"
333 + str(nofFrames)
334 + " Time trace"
335 )
336 axs[0, 0].plot(self.DTimeTime, self.DeltaTime, "ro")
337 axs[0, 0].set_title("Delta Time between packets")
338 axs[0, 0].set(xlabel="Time(s)", ylabel="Delta in us")
339 axs[0, 1].plot(self.IPGTime, self.IPG, "ro")
340 axs[0, 1].set_title("IPG (us)")
341 axs[0, 1].set(xlabel="Time (s)", ylabel="IPG in us")
342 axs[1, 1].plot(self.framesWithinCycleTime, self.framesWithinCycle, "ro")
343 Title = "Frames per burst " + str(nofFrames)
344 axs[1, 1].set_title(Title)
345 axs[1, 1].set(xlabel="Time (s)", ylabel="Count of frames per burst")
346 plt.show()
347
348 def plotMeSplit(self, fileName):
349 if len(self.DeltaTime) == 0:
350 return
351 print(self.lengths)
352 nofFrames = max(self.framesWithinCycle)
353
354 plt.plot(self.DTimeTime, self.DeltaTime, "ro")
355 plt.title(self.tcName + " " + "Delta Time between packets")
356 plt.xlabel(xlabel="Time(s)")
357 plt.ylabel(ylabel="Delta in us")
358 plt.show()
359 plt.plot(self.IPGTime, self.IPG, "ro")
360 plt.title(self.tcName + " " + "IPG (us)")
361 plt.xlabel("Time (s)")
362 plt.ylabel("IPG in us")
363 plt.show()
364 plt.plot(self.framesWithinCycleTime, self.framesWithinCycle, "ro")
365 plt.title(self.tcName + " " + "Frames per burst " + str(nofFrames))
366 plt.xlabel("Time (s)")
367 plt.ylabel("Count of frames per burst")
368 plt.show()
369
370 def getDataFrameIPG(self):
371 nofFrames = max(self.framesWithinCycle)
372 title = (
373 self.tcName + ": " + str(self.prevPktLength) + "bytes x" + str(nofFrames)
374 )
375 print(title)
376 self.dataframeIPG = pd.DataFrame(self.IPG[:])
377 # self.dataframeIPG.set_axis({title}, axis=1, inplace=True)
378 self.dataframeIPG.set_axis({title}, axis=1)
379 return self.dataframeIPG
380
381 def getLengths(self):
382 print(self.lengths)
383 return " - ".join(str(le) for le in self.lengths)
384
385 def getDataFrameIPGwithinBurst(self):
386 nofFrames = max(self.framesWithinCycle)
387 title = self.tcName + ": " + str(nofFrames) + " within the burst"
388 print(title)
389 self.dataframeAveIPG = pd.DataFrame(self.aveIPGInBurst[:])
390 # self.dataframeAveIPG.set_axis({title}, axis=1, inplace=True)
391 self.dataframeAveIPG.set_axis({title}, axis=1)
392 return self.dataframeAveIPG
393
394 def describe(self):
395 self.dataframeIPG = self.getDataFrameIPG()
396 print(self.dataframeIPG.describe())
397 print(self.getDataFrameIPGwithinBurst().describe())
398
399 def getStats(self):
400 df = pd.DataFrame(self.batch_End[:])
401 try:
402 self.stats.BatchEnd["count"] = float(df.count())
403 self.stats.BatchEnd["min"] = float(df.min())
404 self.stats.BatchEnd["max"] = float(df.max())
405 self.stats.BatchEnd["mean"] = float(df.mean())
406 self.stats.BatchEnd["std"] = float(df.std())
407 self.stats.BatchEnd["Q25"] = df.quantile(0.25)
408 self.stats.BatchEnd["Q50"] = df.quantile(0.50)
409 self.stats.BatchEnd["Q75"] = df.quantile(0.75)
410 except TypeError:
411 print("Not Possible to process Batch end")
412
413 df = pd.DataFrame(self.batch_Start[:])
414 try:
415 self.stats.BatchStart["min"] = float(df.min())
416 self.stats.BatchStart["max"] = float(df.max())
417 self.stats.BatchStart["mean"] = float(df.mean())
418 except TypeError:
419 print("Not Possible to process Batch start")
420
421 df = pd.DataFrame(self.IPG[:])
422 try:
423 self.stats.IPG["count"] = float(df.count().iloc[0])
424 self.stats.IPG["min"] = float(df.min().iloc[0])
425 self.stats.IPG["max"] = float(df.max().iloc[0])
426 self.stats.IPG["mean"] = float(df.mean().iloc[0])
427 self.stats.IPG["std"] = float(df.std().iloc[0])
428 self.stats.IPG["Q25"] = float(df.quantile(0.25).iloc[0])
429 self.stats.IPG["Q50"] = float(df.quantile(0.50).iloc[0])
430 self.stats.IPG["Q75"] = float(df.quantile(0.75).iloc[0])
431 except TypeError:
432 print("Not Possible to process IPG")
433
434 df = pd.DataFrame(self.framesWithinCycle[1:])
435 try:
436 self.stats.BatchCount["min"] = int(df.min().iloc[0])
437 self.stats.BatchCount["max"] = int(df.max().iloc[0])
438 self.stats.BatchCount["mean"] = int(df.mean().iloc[0])
439 self.stats.cycles = self.cycleCounter
440 self.stats.packetLenght = self.getLengths()
441 except TypeError:
442 print("Not Possible to process Batch Count")
443 print(
444 "for the pcp ", self.pcp, ",", self.sequenceErrors, " sequence errors found"
445 )
446 return self.stats
447
448 def hasDataAvailable(self):
449 return 1 if len(self.DeltaTime) != 0 else 0
450
451
452 pktCounter = []
453 pktTime = []
454 pcp = []
455
456
457 def print_payload(pkt):
458 message = pkt.payload.payload.decode()
459 message_len = len(message)
460 left = 0
461 right = 8
462 loop = int(message_len / 16) + 1
463 for i in range(loop):
464 print(
465 " " * 8,
466 i,
467 " :",
468 binascii.hexlify(message[left:right]),
469 binascii.hexlify(message[left + 8 : right + 8]),
470 )
471 left += 16
472 right += 16
473
474
475 def process_pcap(file_name, end, noend):
476
477 TrafficClasses = dict()
478
479 print("Opening {}...".format(file_name))
480
481 firstObservedCycle = -1
482 interesting_packet_count = 0
483 count = 0
484 local_file = open(file_name, "rb")
485 r = PcapReader(local_file)
486 while count < end or noend:
487 try:
488 pkt = r.next()
489 except StopIteration:
490 print("No more samples")
491 break
492
493 count += 1
494
495 if pkt.type == 0x8100:
496 vlan_pkt = pkt[Dot1Q]
497
498 pktCounter.append(count)
499 pktTime.append(float(pkt.time))
500 prio = vlan_pkt.fields["prio"]
501 pcp.append(vlan_pkt.fields["prio"])
502
503 if prio not in TrafficClasses:
504 TrafficClasses[prio] = TrafficClass(prio, "PCP " + str(prio))
505
506 sequenceCounter = int.from_bytes(pkt.load[2:6], "big")
507 cycleCounter = int.from_bytes(pkt.load[6:10], "big")
508 # frameId = int.from_bytes(pkt.load[0:2], "big")
509 # payloadStr = pkt.load[10:34].decode("utf-8")
510 # print (prio, cycleCounter, sequenceCounter, frameId, payloadStr)
511
512 if firstObservedCycle == -1:
513 firstObservedCycle = cycleCounter
514
515 if cycleCounter == firstObservedCycle:
516 continue
517
518 TrafficClasses[prio].processPkt(pkt, cycleCounter, sequenceCounter)
519
520 continue
521
522 interesting_packet_count += 1
523 # return
524 plt.plot(pktCounter, pcp, "ro")
525 plt.title("Packet order")
526 plt.ylabel("PCP value")
527 plt.xlabel("Count units")
528 plt.show()
529
530 plt.plot(pktTime, pcp, "ro")
531 plt.title("Packet order in time")
532 plt.ylabel("PCP value")
533 plt.xlabel("Time")
534 plt.show()
535
536 for key in TrafficClasses:
537 TrafficClasses[key].plotMe(file_name)
538 # TrafficClasses[key].plotMeSplit(file_name)
539 # TrafficClasses[key].describe()
540
541 mainTable = create_main_table()
542 for key in TrafficClasses:
543 if TrafficClasses[key].hasDataAvailable():
544 stats = TrafficClasses[key].getStats()
545 populate_stats(stats, key, mainTable)
546 print(mainTable)
547
548 names = [key for key in TrafficClasses if TrafficClasses[key].hasDataAvailable()]
549 for name in names:
550 allDF = TrafficClasses[name].getDataFrameIPG()
551 allDF = allDF.fillna(allDF.mean())
552 ax = sns.boxplot(data=allDF)
553 title = "IPG Boxplot: " + " ".join(str(names))
554 ax.set_title(title)
555 ax.set_ylabel("IPG (us)")
556 plt.show()
557
558 print(
559 "{} contains {} packets ({} interesting)".format(
560 file_name, count, interesting_packet_count
561 )
562 )
563
564
565 def main():
566 global tclass_cycle_time
567 parser = argparse.ArgumentParser(
568 description="Process long term data recorded with TSN dashboard \
569 generating graphics and statistics summary for the key performance indicators."
570 )
571
572 parser.add_argument(
573 "--file",
574 metavar="file",
575 type=pathlib.Path,
576 help="Name of the file generated by the profishark (pcapng)",
577 required=True,
578 )
579
580 parser.add_argument(
581 "--end",
582 metavar="end",
583 type=int,
584 default=2000,
585 help="Number of of points to use",
586 required=False,
587 )
588
589 parser.add_argument(
590 "-a",
591 "--all",
592 default=False,
593 action="store_true",
594 help="Use all available data points",
595 required=False,
596 )
597
598 parser.add_argument(
599 "-c",
600 "--cycle-time",
601 help="Cycle time (second). Default 0.0005s (500us)",
602 type=float,
603 required=False,
604 default=0.0005,
605 )
606
607 args = parser.parse_args()
608
609 tclass_cycle_time = args.cycle_time
610
611 process_pcap(args.file, args.end, args.all)
612
613
614 if __name__ == "__main__":
615 main()