-
Notifications
You must be signed in to change notification settings - Fork 2
/
ovs-dpctl-top.in
executable file
·1722 lines (1401 loc) · 59.9 KB
/
ovs-dpctl-top.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! @PYTHON@
#
# Copyright (c) 2013 Nicira, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# The approximate_size code was copied from
# http://getpython3.com/diveintopython3/your-first-python-program.html#divingin
# which is licensed under # "Dive Into Python 3," Copyright 2011 Mark Pilgrim,
# used under a Creative Commons Attribution-Share-Alike license:
# http://creativecommons.org/licenses/by-sa/3.0/
#
#
"""Top like behavior for ovs-dpctl dump-flows output.
This program summarizes ovs-dpctl flow content by aggregating the number
of packets, total bytes and occurrence of the following fields:
- Datapath in_port
- Ethernet type
- Source and destination MAC addresses
- IP protocol
- Source and destination IPv4 addresses
- Source and destination IPv6 addresses
- UDP and TCP destination port
- Tunnel source and destination addresses
Output shows four values:
- FIELDS: the flow fields for example in_port(1).
- PACKETS: the total number of packets containing the flow field.
- BYTES: the total number of bytes containing the flow field. If units are
not present then values are in bytes.
- AVERAGE: the average packets size (BYTES/PACKET).
- COUNT: the number of lines in the dump-flow output contain the flow field.
Top Behavior
While in top mode, the default behavior, the following single character
commands are supported:
a - toggles top in accumulate and live mode. Accumulate mode is described
below.
s - toggles which column is used to sort content in decreasing order. A
DESC title is placed over the column.
_ - a space indicating to collect dump-flow content again
h - halt output. Any character will restart sampling
f - cycle through flow fields. The initial field is in_port
q - q for quit.
Accumulate Mode
There are two supported modes: live and accumulate. The default is live.
The parameter --accumulate or the 'a' character in top mode enables the
latter. In live mode, recent dump-flow content is presented.
Where as accumulate mode keeps track of the prior historical
information until the flow is reset not when the flow is purged. Reset
flows are determined when the packet count for a flow has decreased from
its previous sample. There is one caveat, eventually the system will
run out of memory if, after the accumulate-decay period any flows that
have not been refreshed are purged. The goal here is to free memory
of flows that are not active. Statistics are not decremented. Their purpose
is to reflect the overall history of the flow fields.
Debugging Errors
Parsing errors are counted and displayed in the status line at the beginning
of the output. Use the --verbose option with --script to see what output
was not parsed, like this:
$ ovs-dpctl dump-flows | ovs-dpctl-top --script --verbose
Error messages will identify content that failed to parse.
Access Remote Hosts
The --host must follow the format user@hostname. This script simply calls
'ssh user@Hostname' without checking for login credentials therefore public
keys should be installed on the system identified by hostname, such as:
$ ssh-copy-id user@hostname
Consult ssh-copy-id man pages for more details.
Expected usage
$ ovs-dpctl-top
or to run as a script:
$ ovs-dpctl dump-flows > dump-flows.log
$ ovs-dpctl-top --script --flow-file dump-flows.log
"""
# pylint: disable-msg=C0103
# pylint: disable-msg=C0302
# pylint: disable-msg=R0902
# pylint: disable-msg=R0903
# pylint: disable-msg=R0904
# pylint: disable-msg=R0912
# pylint: disable-msg=R0913
# pylint: disable-msg=R0914
import sys
import os
try:
##
# Arg parse is not installed on older Python distributions.
# ovs ships with a version in the directory mentioned below.
import argparse
except ImportError:
sys.path.append(os.path.join("@pkgdatadir@", "python"))
import argparse
import logging
import re
import unittest
import copy
import curses
import operator
import subprocess
import fcntl
import struct
import termios
import datetime
import threading
import time
import socket
##
# The following two definitions provide the necessary netaddr functionality.
# Python netaddr module is not part of the core installation. Packaging
# netaddr was involved and seems inappropriate given that only two
# methods where used.
def ipv4_to_network(ip_str):
""" Calculate the network given a ipv4/mask value.
If a mask is not present simply return ip_str.
"""
pack_length = '!HH'
try:
(ip, mask) = ip_str.split("/")
except ValueError:
# just an ip address no mask.
return ip_str
ip_p = socket.inet_pton(socket.AF_INET, ip)
ip_t = struct.unpack(pack_length, ip_p)
mask_t = struct.unpack(pack_length, socket.inet_pton(socket.AF_INET, mask))
network_n = [ii & jj for (ii, jj) in zip(ip_t, mask_t)]
return socket.inet_ntop(socket.AF_INET,
struct.pack('!HH', network_n[0], network_n[1]))
def ipv6_to_network(ip_str):
""" Calculate the network given a ipv6/mask value.
If a mask is not present simply return ip_str.
"""
pack_length = '!HHHHHHHH'
try:
(ip, mask) = ip_str.split("/")
except ValueError:
# just an ip address no mask.
return ip_str
ip_p = socket.inet_pton(socket.AF_INET6, ip)
ip_t = struct.unpack(pack_length, ip_p)
mask_t = struct.unpack(pack_length,
socket.inet_pton(socket.AF_INET6, mask))
network_n = [ii & jj for (ii, jj) in zip(ip_t, mask_t)]
return socket.inet_ntop(socket.AF_INET6,
struct.pack(pack_length,
network_n[0], network_n[1],
network_n[2], network_n[3],
network_n[4], network_n[5],
network_n[6], network_n[7]))
##
# columns displayed
##
class Columns:
""" Holds column specific content.
Titles needs to be less than 8 characters.
"""
VALUE_WIDTH = 9
FIELDS = "fields"
PACKETS = "packets"
COUNT = "count"
BYTES = "bytes"
AVERAGE = "average"
def __init__(self):
pass
@staticmethod
def assoc_list(obj):
""" Return a associated list. """
return [(Columns.FIELDS, repr(obj)),
(Columns.PACKETS, obj.packets),
(Columns.BYTES, obj.bytes),
(Columns.COUNT, obj.count),
(Columns.AVERAGE, obj.average),
]
def element_eth_get(field_type, element, stats_dict):
""" Extract eth frame src and dst from a dump-flow element."""
fmt = "%s(src=%s,dst=%s)"
element = fmt % (field_type, element["src"], element["dst"])
return SumData(field_type, element, stats_dict["packets"],
stats_dict["bytes"], element)
def element_ipv4_get(field_type, element, stats_dict):
""" Extract src and dst from a dump-flow element."""
fmt = "%s(src=%s,dst=%s)"
element_show = fmt % (field_type, element["src"], element["dst"])
element_key = fmt % (field_type, ipv4_to_network(element["src"]),
ipv4_to_network(element["dst"]))
return SumData(field_type, element_show, stats_dict["packets"],
stats_dict["bytes"], element_key)
def element_tunnel_get(field_type, element, stats_dict):
""" Extract src and dst from a tunnel."""
return element_ipv4_get(field_type, element, stats_dict)
def element_ipv6_get(field_type, element, stats_dict):
""" Extract src and dst from a dump-flow element."""
fmt = "%s(src=%s,dst=%s)"
element_show = fmt % (field_type, element["src"], element["dst"])
element_key = fmt % (field_type, ipv6_to_network(element["src"]),
ipv6_to_network(element["dst"]))
return SumData(field_type, element_show, stats_dict["packets"],
stats_dict["bytes"], element_key)
def element_dst_port_get(field_type, element, stats_dict):
""" Extract src and dst from a dump-flow element."""
element_key = "%s(dst=%s)" % (field_type, element["dst"])
return SumData(field_type, element_key, stats_dict["packets"],
stats_dict["bytes"], element_key)
def element_passthrough_get(field_type, element, stats_dict):
""" Extract src and dst from a dump-flow element."""
element_key = "%s(%s)" % (field_type, element)
return SumData(field_type, element_key,
stats_dict["packets"], stats_dict["bytes"], element_key)
# pylint: disable-msg=R0903
class OutputFormat:
""" Holds field_type and function to extract element value. """
def __init__(self, field_type, generator):
self.field_type = field_type
self.generator = generator
##
# The order below is important. The initial flow field depends on whether
# --script or top mode is used. In top mode, the expected behavior, in_port
# flow fields are shown first. A future feature will allow users to
# filter output by selecting a row. Filtering by in_port is a natural
# filtering starting point.
#
# In script mode, all fields are shown. The expectation is that users could
# filter output by piping through grep.
#
# In top mode, the default flow field is in_port. In --script mode,
# the default flow field is all.
#
# All is added to the end of the OUTPUT_FORMAT list.
##
OUTPUT_FORMAT = [
OutputFormat("in_port", element_passthrough_get),
OutputFormat("eth", element_eth_get),
OutputFormat("eth_type", element_passthrough_get),
OutputFormat("ipv4", element_ipv4_get),
OutputFormat("ipv6", element_ipv6_get),
OutputFormat("udp", element_dst_port_get),
OutputFormat("tcp", element_dst_port_get),
OutputFormat("tunnel", element_tunnel_get),
]
##
ELEMENT_KEY = {
"udp": "udp.dst",
"tcp": "tcp.dst"
}
def top_input_get(args):
""" Return subprocess stdout."""
cmd = []
if (args.host):
cmd += ["ssh", args.host]
cmd += ["ovs-dpctl", "dump-flows"]
return subprocess.Popen(cmd, stderr=subprocess.STDOUT,
stdout=subprocess.PIPE).stdout
def args_get():
""" read program parameters handle any necessary validation of input. """
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
##
# None is a special value indicating to read flows from stdin.
# This handles the case
# ovs-dpctl dump-flows | ovs-dpctl-flows.py
parser.add_argument("-v", "--version", version="@VERSION@",
action="version", help="show version")
parser.add_argument("-f", "--flow-file", dest="flowFiles", default=None,
action="append",
help="file containing flows from ovs-dpctl dump-flow")
parser.add_argument("-V", "--verbose", dest="verbose",
default=logging.CRITICAL,
action="store_const", const=logging.DEBUG,
help="enable debug level verbosity")
parser.add_argument("-s", "--script", dest="top", action="store_false",
help="Run from a script (no user interface)")
parser.add_argument("--host", dest="host",
help="Specify a user@host for retrieving flows see"
"Accessing Remote Hosts for more information")
parser.add_argument("-a", "--accumulate", dest="accumulate",
action="store_true", default=False,
help="Accumulate dump-flow content")
parser.add_argument("--accumulate-decay", dest="accumulateDecay",
default=5.0 * 60, type=float,
help="Decay old accumulated flows. "
"The default is 5 minutes. "
"A value of 0 disables decay.")
parser.add_argument("-d", "--delay", dest="delay", type=int,
default=1000,
help="Delay in milliseconds to collect dump-flow "
"content (sample rate).")
args = parser.parse_args()
logging.basicConfig(level=args.verbose)
return args
###
# Code to parse a single line in dump-flow
###
# key(values)
FIELDS_CMPND = re.compile("([\w]+)\((.+)\)")
# key:value
FIELDS_CMPND_ELEMENT = re.compile("([\w:]+)=([/\.\w:]+)")
FIELDS_ELEMENT = re.compile("([\w]+):([-\.\w]+)")
def flow_line_iter(line):
""" iterate over flow dump elements.
return tuples of (true, element) or (false, remaining element)
"""
# splits by , except for when in a (). Actions element was not
# split properly but we don't need it.
rc = []
element = ""
paren_count = 0
for ch in line:
if (ch == '('):
paren_count += 1
elif (ch == ')'):
paren_count -= 1
if (ch == ' '):
# ignore white space.
continue
elif ((ch == ',') and (paren_count == 0)):
rc.append(element)
element = ""
else:
element += ch
if (paren_count):
raise ValueError(line)
else:
if (len(element) > 0):
rc.append(element)
return rc
def flow_line_compound_parse(compound):
""" Parse compound element
for example
src=00:50:56:b4:4e:f8,dst=33:33:00:01:00:03
which is in
eth(src=00:50:56:b4:4e:f8,dst=33:33:00:01:00:03)
"""
result = {}
for element in flow_line_iter(compound):
match = FIELDS_CMPND_ELEMENT.search(element)
if (match):
key = match.group(1)
value = match.group(2)
result[key] = value
match = FIELDS_CMPND.search(element)
if (match):
key = match.group(1)
value = match.group(2)
result[key] = flow_line_compound_parse(value)
continue
if (len(result.keys()) == 0):
return compound
return result
def flow_line_split(line):
""" Convert a flow dump line into ([fields], [stats], actions) tuple.
Where fields and stats are lists.
This function relies on a the following ovs-dpctl dump-flow
output characteristics:
1. The dumpe flow line consists of a list of frame fields, list of stats
and action.
2. list of frame fields, each stat and action field are delimited by ', '.
3. That all other non stat field are not delimited by ', '.
"""
results = re.split(', ', line)
(field, stats, action) = (results[0], results[1:-1], results[-1])
fields = flow_line_iter(field)
return (fields, stats, action)
def elements_to_dict(elements):
""" Convert line to a hierarchy of dictionaries. """
result = {}
for element in elements:
match = FIELDS_CMPND.search(element)
if (match):
key = match.group(1)
value = match.group(2)
result[key] = flow_line_compound_parse(value)
continue
match = FIELDS_ELEMENT.search(element)
if (match):
key = match.group(1)
value = match.group(2)
result[key] = value
else:
raise ValueError("can't parse >%s<" % element)
return result
# pylint: disable-msg=R0903
class SumData(object):
""" Interface that all data going into SumDb must implement.
Holds the flow field and its corresponding count, total packets,
total bytes and calculates average.
__repr__ is used as key into SumData singleton.
__str__ is used as human readable output.
"""
def __init__(self, field_type, field, packets, flow_bytes, key):
# Count is the number of lines in the dump-flow log.
self.field_type = field_type
self.field = field
self.count = 1
self.packets = int(packets)
self.bytes = int(flow_bytes)
self.key = key
def decrement(self, decr_packets, decr_bytes, decr_count):
""" Decrement content to calculate delta from previous flow sample."""
self.packets -= decr_packets
self.bytes -= decr_bytes
self.count -= decr_count
def __iadd__(self, other):
""" Add two objects. """
if (self.key != other.key):
raise ValueError("adding two unrelated types")
self.count += other.count
self.packets += other.packets
self.bytes += other.bytes
return self
def __isub__(self, other):
""" Decrement two objects. """
if (self.key != other.key):
raise ValueError("adding two unrelated types")
self.count -= other.count
self.packets -= other.packets
self.bytes -= other.bytes
return self
def __getattr__(self, name):
""" Handle average. """
if (name == "average"):
if (self.packets == 0):
return float(0.0)
else:
return float(self.bytes) / float(self.packets)
raise AttributeError(name)
def __str__(self):
""" Used for debugging. """
return "%s %s %s %s" % (self.field, self.count,
self.packets, self.bytes)
def __repr__(self):
""" Used as key in the FlowDB table. """
return self.key
def flow_aggregate(fields_dict, stats_dict):
""" Search for content in a line.
Passed the flow port of the dump-flows plus the current stats consisting
of packets, bytes, etc
"""
result = []
for output_format in OUTPUT_FORMAT:
field = fields_dict.get(output_format.field_type, None)
if (field):
obj = output_format.generator(output_format.field_type,
field, stats_dict)
result.append(obj)
return result
def flows_read(ihdl, flow_db):
""" read flow content from ihdl and insert into flow_db. """
done = False
while (not done):
line = ihdl.readline()
if (len(line) == 0):
# end of input
break
try:
flow_db.flow_line_add(line)
except ValueError, arg:
logging.error(arg)
return flow_db
def get_terminal_size():
"""
return column width and height of the terminal
"""
for fd_io in [0, 1, 2]:
try:
result = struct.unpack('hh',
fcntl.ioctl(fd_io, termios.TIOCGWINSZ,
'1234'))
except IOError:
result = None
continue
if (result is None or result == (0, 0)):
# Maybe we can't get the width. In that case assume (25, 80)
result = (25, 80)
return result
##
# Content derived from:
# http://getpython3.com/diveintopython3/your-first-python-program.html#divingin
##
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
"""Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
"""
size = float(size)
if size < 0:
raise ValueError('number must be non-negative')
if (a_kilobyte_is_1024_bytes):
multiple = 1024
else:
multiple = 1000
for suffix in SUFFIXES[multiple]:
size /= multiple
if size < multiple:
return "%.1f %s" % (size, suffix)
raise ValueError('number too large')
##
# End copied content
##
class ColMeta:
""" Concepts about columns. """
def __init__(self, sortable, width):
self.sortable = sortable
self.width = width
class RowMeta:
""" How to render rows. """
def __init__(self, label, fmt):
self.label = label
self.fmt = fmt
def fmt_packet(obj, width):
""" Provide a string for packets that is appropriate for output."""
return str(obj.packets).rjust(width)
def fmt_count(obj, width):
""" Provide a string for average that is appropriate for output."""
return str(obj.count).rjust(width)
def fmt_avg(obj, width):
""" Provide a string for average that is appropriate for output."""
return str(int(obj.average)).rjust(width)
def fmt_field(obj, width):
""" truncate really long flow and insert ellipses to help make it
clear.
"""
ellipses = " ... "
value = obj.field
if (len(obj.field) > width):
value = value[:(width - len(ellipses))] + ellipses
return value.ljust(width)
def fmt_bytes(obj, width):
""" Provide a string for average that is appropriate for output."""
if (len(str(obj.bytes)) <= width):
value = str(obj.bytes)
else:
value = approximate_size(obj.bytes)
return value.rjust(width)
def title_center(value, width):
""" Center a column title."""
return value.upper().center(width)
def title_rjust(value, width):
""" Right justify a column title. """
return value.upper().rjust(width)
def column_picker(order, obj):
""" return the column as specified by order. """
if (order == 1):
return obj.count
elif (order == 2):
return obj.packets
elif (order == 3):
return obj.bytes
elif (order == 4):
return obj.average
else:
raise ValueError("order outside of range %s" % order)
class Render:
""" Renders flow data.
The two FIELD_SELECT variables should be set to the actual field minus
1. During construction, an internal method increments and initializes
this object.
"""
FLOW_FIELDS = [_field.field_type for _field in OUTPUT_FORMAT] + ["all"]
FIELD_SELECT_SCRIPT = 7
FIELD_SELECT_TOP = -1
def __init__(self, console_width, field_select):
""" Calculate column widths taking into account changes in format."""
self._start_time = datetime.datetime.now()
self._cols = [ColMeta(False, 0),
ColMeta(True, Columns.VALUE_WIDTH),
ColMeta(True, Columns.VALUE_WIDTH),
ColMeta(True, Columns.VALUE_WIDTH),
ColMeta(True, Columns.VALUE_WIDTH)]
self._console_width = console_width
self.console_width_set(console_width)
# Order in this array dictate the order of the columns.
# The 0 width for the first entry is a place holder. This is
# dynamically calculated. The first column is special. We need a
# way to indicate which field are presented.
self._descs = [RowMeta("", title_rjust),
RowMeta("", title_rjust),
RowMeta("", title_rjust),
RowMeta("", title_rjust),
RowMeta("", title_rjust)]
self._column_sort_select = 0
self.column_select_event()
self._titles = [
RowMeta(Columns.FIELDS, title_center),
RowMeta(Columns.COUNT, title_rjust),
RowMeta(Columns.PACKETS, title_rjust),
RowMeta(Columns.BYTES, title_rjust),
RowMeta(Columns.AVERAGE, title_rjust)
]
self._datas = [
RowMeta(None, fmt_field),
RowMeta(None, fmt_count),
RowMeta(None, fmt_packet),
RowMeta(None, fmt_bytes),
RowMeta(None, fmt_avg)
]
##
# _field_types hold which fields are displayed in the field
# column, with the keyword all implying all fields.
##
self._field_types = Render.FLOW_FIELDS
##
# The default is to show all field types.
##
self._field_type_select = field_select
self.field_type_toggle()
def _field_type_select_get(self):
""" Return which field type to display. """
return self._field_types[self._field_type_select]
def field_type_toggle(self):
""" toggle which field types to show. """
self._field_type_select += 1
if (self._field_type_select >= len(self._field_types)):
self._field_type_select = 0
value = Columns.FIELDS + " (%s)" % self._field_type_select_get()
self._titles[0].label = value
def column_select_event(self):
""" Handles column select toggle. """
self._descs[self._column_sort_select].label = ""
for _ in range(len(self._cols)):
self._column_sort_select += 1
if (self._column_sort_select >= len(self._cols)):
self._column_sort_select = 0
# Now look for the next sortable column
if (self._cols[self._column_sort_select].sortable):
break
self._descs[self._column_sort_select].label = "DESC"
def console_width_set(self, console_width):
""" Adjust the output given the new console_width. """
self._console_width = console_width
spaces = len(self._cols) - 1
##
# Calculating column width can be tedious but important. The
# flow field value can be long. The goal here is to dedicate
# fixed column space for packets, bytes, average and counts. Give the
# remaining space to the flow column. When numbers get large
# transition output to output generated by approximate_size which
# limits output to ###.# XiB in other words 9 characters.
##
# At this point, we know the maximum length values. We may
# truncate the flow column to get everything to fit.
self._cols[0].width = 0
values_max_length = sum([ii.width for ii in self._cols]) + spaces
flow_max_length = console_width - values_max_length
self._cols[0].width = flow_max_length
def format(self, flow_db):
""" shows flows based on --script parameter."""
rc = []
##
# Top output consists of
# Title
# Column title (2 rows)
# data
# statistics and status
##
# Title
##
rc.append("Flow Summary".center(self._console_width))
stats = " Total: %(flow_total)s errors: %(flow_errors)s " % \
flow_db.flow_stats_get()
accumulate = flow_db.accumulate_get()
if (accumulate):
stats += "Accumulate: on "
else:
stats += "Accumulate: off "
duration = datetime.datetime.now() - self._start_time
stats += "Duration: %s " % str(duration)
rc.append(stats.ljust(self._console_width))
##
# 2 rows for columns.
##
# Indicate which column is in descending order.
rc.append(" ".join([ii.fmt(ii.label, col.width)
for (ii, col) in zip(self._descs, self._cols)]))
rc.append(" ".join([ii.fmt(ii.label, col.width)
for (ii, col) in zip(self._titles, self._cols)]))
##
# Data.
##
for dd in flow_db.field_values_in_order(self._field_type_select_get(),
self._column_sort_select):
rc.append(" ".join([ii.fmt(dd, col.width)
for (ii, col) in zip(self._datas,
self._cols)]))
return rc
def curses_screen_begin():
""" begin curses screen control. """
stdscr = curses.initscr()
curses.cbreak()
curses.noecho()
stdscr.keypad(1)
return stdscr
def curses_screen_end(stdscr):
""" end curses screen control. """
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
class FlowDB:
""" Implements live vs accumulate mode.
Flows are stored as key value pairs. The key consists of the content
prior to stat fields. The value portion consists of stats in a dictionary
form.
@ \todo future add filtering here.
"""
def __init__(self, accumulate):
self._accumulate = accumulate
self._error_count = 0
# Values are (stats, last update time.)
# The last update time is used for aging.
self._flow_lock = threading.Lock()
# This dictionary holds individual flows.
self._flows = {}
# This dictionary holds aggregate of flow fields.
self._fields = {}
def accumulate_get(self):
""" Return the current accumulate state. """
return self._accumulate
def accumulate_toggle(self):
""" toggle accumulate flow behavior. """
self._accumulate = not self._accumulate
def begin(self):
""" Indicate the beginning of processing flow content.
if accumulate is false clear current set of flows. """
if (not self._accumulate):
self._flow_lock.acquire()
try:
self._flows.clear()
finally:
self._flow_lock.release()
self._fields.clear()
def flow_line_add(self, line):
""" Split a line from a ovs-dpctl dump-flow into key and stats.
The order of the content in the flow should be:
- flow content
- stats for the flow
- actions
This method also assumes that the dump flow output does not
change order of fields of the same flow.
"""
line = line.rstrip("\n")
(fields, stats, _) = flow_line_split(line)
try:
fields_dict = elements_to_dict(fields)
if (len(fields_dict) == 0):
raise ValueError("flow fields are missing %s", line)
stats_dict = elements_to_dict(stats)
if (len(stats_dict) == 0):
raise ValueError("statistics are missing %s.", line)
##
# In accumulate mode, the Flow database can reach 10,000's of
# persistent flows. The interaction of the script with this many
# flows is too slow. Instead, delta are sent to the flow_db
# database allow incremental changes to be done in O(m) time
# where m is the current flow list, instead of iterating over
# all flows in O(n) time where n is the entire history of flows.
key = ",".join(fields)
self._flow_lock.acquire()
try:
(stats_old_dict, _) = self._flows.get(key, (None, None))
finally:
self._flow_lock.release()
self.flow_event(fields_dict, stats_old_dict, stats_dict)
except ValueError, arg:
logging.error(arg)
self._error_count += 1
raise
self._flow_lock.acquire()
try:
self._flows[key] = (stats_dict, datetime.datetime.now())
finally:
self._flow_lock.release()