forked from avocado-framework/avocado-vt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_net.py
More file actions
4906 lines (4218 loc) · 157 KB
/
utils_net.py
File metadata and controls
4906 lines (4218 loc) · 157 KB
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
import errno
import fcntl
import hashlib
import ipaddress as pyipaddr
import json
import logging
import math
import os
import platform
import random
import re
import shelve
import shutil
import signal
import socket
import struct
import sys
import time
import uuid
import aexpect
import netifaces
import six
from aexpect import remote
from avocado.core import exceptions
from avocado.utils import path as utils_path
from avocado.utils import process, stacktrace
from six.moves import xrange
from virttest import (
arch,
data_dir,
openvswitch,
propcan,
utils_misc,
utils_package,
utils_selinux,
)
from virttest.remote import RemoteRunner
from virttest.staging import service, utils_memory
from virttest.utils_windows import system, virtio_win
from virttest.versionable_class import factory
try:
unicode
except NameError:
unicode = str
CTYPES_SUPPORT = True
try:
import ctypes
except ImportError:
CTYPES_SUPPORT = False
SYSFS_NET_PATH = "/sys/class/net"
PROCFS_NET_PATH = "/proc/net/dev"
# globals
sock = None
sockfd = None
LOG = logging.getLogger("avocado." + __name__)
class NetError(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
class TAPModuleError(NetError):
def __init__(self, devname, action="open", details=None):
NetError.__init__(self, devname)
self.devname = devname
self.action = action
self.details = details
def __str__(self):
e_msg = "Can't %s %s" % (self.action, self.devname)
if self.details is not None:
e_msg += " : %s" % self.details
return e_msg
class TAPNotExistError(NetError):
def __init__(self, ifname):
NetError.__init__(self, ifname)
self.ifname = ifname
def __str__(self):
return "Interface %s does not exist" % self.ifname
class TAPCreationError(NetError):
def __init__(self, ifname, details=None):
NetError.__init__(self, ifname, details)
self.ifname = ifname
self.details = details
def __str__(self):
e_msg = "Cannot create TAP device %s" % self.ifname
if self.details is not None:
e_msg += ": %s" % self.details
return e_msg
class MacvtapCreationError(NetError):
def __init__(self, ifname, base_interface, details=None):
NetError.__init__(self, ifname, details)
self.ifname = ifname
self.interface = base_interface
self.details = details
def __str__(self):
e_msg = "Cannot create macvtap device %s " % self.ifname
e_msg += "base physical interface %s." % self.interface
if self.details is not None:
e_msg += ": %s" % self.details
return e_msg
class MacvtapGetBaseInterfaceError(NetError):
def __init__(self, ifname=None, details=None):
NetError.__init__(self, ifname, details)
self.ifname = ifname
self.details = details
def __str__(self):
e_msg = "Cannot get a valid physical interface to create macvtap."
if self.ifname:
e_msg += "physical interface is : %s " % self.ifname
if self.details is not None:
e_msg += "error info: %s" % self.details
return e_msg
class TAPBringUpError(NetError):
def __init__(self, ifname):
NetError.__init__(self, ifname)
self.ifname = ifname
def __str__(self):
return "Cannot bring up TAP %s" % self.ifname
class TAPBringDownError(NetError):
def __init__(self, ifname):
NetError.__init__(self, ifname)
self.ifname = ifname
def __str__(self):
return "Cannot bring down TAP %s" % self.ifname
class BRAddIfError(NetError):
def __init__(self, ifname, brname, details):
NetError.__init__(self, ifname, brname, details)
self.ifname = ifname
self.brname = brname
self.details = details
def __str__(self):
return "Can't add interface %s to bridge %s: %s" % (
self.ifname,
self.brname,
self.details,
)
class BRDelIfError(NetError):
def __init__(self, ifname, brname, details):
NetError.__init__(self, ifname, brname, details)
self.ifname = ifname
self.brname = brname
self.details = details
def __str__(self):
return "Can't remove interface %s from bridge %s: %s" % (
self.ifname,
self.brname,
self.details,
)
class IfNotInBridgeError(NetError):
def __init__(self, ifname, details):
NetError.__init__(self, ifname, details)
self.ifname = ifname
self.details = details
def __str__(self):
return "Interface %s is not present on any bridge: %s" % (
self.ifname,
self.details,
)
class OpenflowSwitchError(NetError):
def __init__(self, brname):
NetError.__init__(self, brname)
self.brname = brname
def __str__(self):
return (
"Only support openvswitch, make sure your env support ovs, "
"and your bridge %s is an openvswitch" % self.brname
)
class BRNotExistError(NetError):
def __init__(self, brname, details):
NetError.__init__(self, brname, details)
self.brname = brname
self.details = details
def __str__(self):
return "Bridge %s does not exist: %s" % (self.brname, self.details)
class IfChangeBrError(NetError):
def __init__(self, ifname, old_brname, new_brname, details):
NetError.__init__(self, ifname, old_brname, new_brname, details)
self.ifname = ifname
self.new_brname = new_brname
self.old_brname = old_brname
self.details = details
def __str__(self):
return "Can't move interface %s from bridge %s to bridge %s: %s" % (
self.ifname,
self.new_brname,
self.oldbrname,
self.details,
)
class IfChangeAddrError(NetError):
def __init__(self, ifname, ipaddr, details):
NetError.__init__(self, ifname, ipaddr, details)
self.ifname = ifname
self.ipaddr = ipaddr
self.details = details
def __str__(self):
return "Can't change interface IP address %s from interface %s: %s" % (
self.ifname,
self.ipaddr,
self.details,
)
class BRIpError(NetError):
def __init__(self, brname):
NetError.__init__(self, brname)
self.brname = brname
def __str__(self):
return (
"Bridge %s doesn't have an IP address assigned. It's"
" impossible to start dnsmasq for this bridge." % (self.brname)
)
class VMIPV6NeighNotFoundError(NetError):
def __init__(self, ipv6_address):
NetError.__init__(self, ipv6_address)
self.ipv6_address = ipv6_address
def __str__(self):
return "No IPV6 neighbours with address %s" % self.ipv6_address
class VMIPV6AdressError(NetError):
def __init__(self, error_info):
NetError.__init__(self, error_info)
self.error_info = error_info
def __str__(self):
return "%s, check your test env supports IPV6" % self.error_info
class HwAddrSetError(NetError):
def __init__(self, ifname, mac):
NetError.__init__(self, ifname, mac)
self.ifname = ifname
self.mac = mac
def __str__(self):
return "Can not set mac %s to interface %s" % (self.mac, self.ifname)
class HwAddrGetError(NetError):
def __init__(self, ifname):
NetError.__init__(self, ifname)
self.ifname = ifname
def __str__(self):
return "Can not get mac of interface %s" % self.ifname
class IPAddrGetError(NetError):
def __init__(self, mac_addr, details=None):
NetError.__init__(self, mac_addr)
self.mac_addr = mac_addr
self.details = details
def __str__(self):
details_msg = "Get guest nic ['%s'] IP address error" % self.mac_addr
details_msg += "error info: %s" % self.details
return details_msg
class IPAddrSetError(NetError):
def __init__(self, mac_addr, ip_addr, details=None):
NetError.__init__(self, mac_addr, ip_addr)
self.mac_addr = mac_addr
self.ip_addr = ip_addr
self.details = details
def __str__(self):
details_msg = "Cannot set IP %s to guest mac ['%s']." % (
self.ip_addr,
self.mac_addr,
)
details_msg += " Error info: %s" % self.details
return details_msg
class HwOperstarteGetError(NetError):
def __init__(self, ifname, details=None):
NetError.__init__(self, ifname)
self.ifname = ifname
self.details = details
def __str__(self):
return "Get nic %s operstate error, %s" % (self.ifname, self.details)
class VlanError(NetError):
def __init__(self, ifname, details):
NetError.__init__(self, ifname, details)
self.ifname = ifname
self.details = details
def __str__(self):
return "Vlan error on interface %s: %s" % (self.ifname, self.details)
class VMNetError(NetError):
def __str__(self):
return (
"VMNet instance items must be dict-like and contain " "a 'nic_name' mapping"
)
class DbNoLockError(NetError):
def __str__(self):
return "Attempt made to access database with improper locking"
class DelLinkError(NetError):
def __init__(self, ifname, details=None):
NetError.__init__(self, ifname, details)
self.ifname = ifname
self.details = details
def __str__(self):
e_msg = "Cannot delete interface %s" % self.ifname
if self.details is not None:
e_msg += ": %s" % self.details
return e_msg
def warp_init_del(func):
def new_func(*args, **argkw):
globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
globals()["sockfd"] = globals()["sock"].fileno()
try:
return func(*args, **argkw)
finally:
globals()["sock"].close()
globals()["sock"] = None
globals()["sockfd"] = None
return new_func
class Interface(object):
"""Class representing a Linux network device."""
def __init__(self, name):
self.name = name
def __repr__(self):
return "<%s %s at 0x%x>" % (self.__class__.__name__, self.name, id(self))
@warp_init_del
def set_iface_flag(self, flag, active=True):
# Get existing device flags
ifreq = struct.pack("16sh", self.name.encode(), 0)
flags = struct.unpack("16sh", fcntl.ioctl(sockfd, arch.SIOCGIFFLAGS, ifreq))[1]
# Set new flags
if active:
flags = flags | flag
else:
flags = flags & ~flag
ifreq = struct.pack("16sh", self.name.encode(), flags)
fcntl.ioctl(sockfd, arch.SIOCSIFFLAGS, ifreq)
@warp_init_del
def is_iface_flag_on(self, flag):
ifreq = struct.pack("16sh", self.name.encode(), 0)
flags = struct.unpack("16sh", fcntl.ioctl(sockfd, arch.SIOCGIFFLAGS, ifreq))[1]
if flags & flag:
return True
else:
return False
def up(self):
"""
Bring up the bridge interface. Equivalent to ifconfig [iface] up.
"""
self.set_iface_flag(arch.IFF_UP)
def down(self):
"""
Bring down the bridge interface. Equivalent to ifconfig [iface] down.
"""
self.set_iface_flag(arch.IFF_UP, active=False)
def is_up(self):
"""
Return True if the interface is up, False otherwise.
"""
return self.is_iface_flag_on(arch.IFF_UP)
def promisc_on(self):
"""
Enable promiscuous mode on the interface.
Equivalent to ip link set [iface] promisc on.
"""
self.set_iface_flag(arch.IFF_PROMISC)
def promisc_off(self):
"""
Disable promiscuous mode on the interface.
Equivalent to ip link set [iface] promisc off.
"""
self.set_iface_flag(arch.IFF_PROMISC, active=False)
def is_promisc(self):
"""
Return True if the interface promiscuous mode is on, False otherwise.
"""
return self.is_iface_flag_on(arch.IFF_PROMISC)
@warp_init_del
def get_mac(self):
"""
Obtain the device's mac address.
"""
ifreq = struct.pack("16sH14s", self.name.encode(), socket.AF_UNIX, b"\x00" * 14)
res = fcntl.ioctl(sockfd, arch.SIOCGIFHWADDR, ifreq)
address = struct.unpack("16sH14s", res)[2]
mac = struct.unpack("6B8x", address)
return ":".join(["%02X" % i for i in mac])
@warp_init_del
def set_mac(self, newmac):
"""
Set the device's mac address. Device must be down for this to
succeed.
"""
macbytes = [int(i, 16) for i in newmac.split(":")]
ifreq = struct.pack("16sH6B8x", self.name.encode(), socket.AF_UNIX, *macbytes)
fcntl.ioctl(sockfd, arch.SIOCSIFHWADDR, ifreq)
@warp_init_del
def get_ip(self):
"""
Get ip address of this interface
"""
ifreq = struct.pack("16sH14s", self.name.encode(), socket.AF_INET, b"\x00" * 14)
try:
res = fcntl.ioctl(sockfd, arch.SIOCGIFADDR, ifreq)
except IOError:
return None
ip = struct.unpack("16sH2x4s8x", res)[2]
return socket.inet_ntoa(ip)
@warp_init_del
def set_ip(self, newip):
"""
Set the ip address of the interface
"""
ipbytes = socket.inet_aton(newip)
ifreq = struct.pack(
"16sH2s4s8s",
self.name.encode(),
socket.AF_INET,
b"\x00" * 2,
ipbytes,
b"\x00" * 8,
)
fcntl.ioctl(sockfd, arch.SIOCSIFADDR, ifreq)
@warp_init_del
def get_netmask(self):
"""
Get ip network netmask
"""
if not CTYPES_SUPPORT:
raise exceptions.TestSkipError(
"Getting the netmask requires " "python > 2.4"
)
ifreq = struct.pack("16sH14s", self.name.encode(), socket.AF_INET, b"\x00" * 14)
try:
res = fcntl.ioctl(sockfd, arch.SIOCGIFNETMASK, ifreq)
except IOError:
return 0
netmask = socket.ntohl(struct.unpack("16sH2xI8x", res)[2])
return 32 - int(math.log(ctypes.c_uint32(~netmask).value + 1, 2))
@warp_init_del
def set_netmask(self, netmask):
"""
Set netmask
"""
if not CTYPES_SUPPORT:
raise exceptions.TestSkipError(
"Setting the netmask requires " "python > 2.4"
)
netmask = ctypes.c_uint32(~((2 ** (32 - netmask)) - 1)).value
nmbytes = socket.htonl(netmask)
ifreq = struct.pack(
"16sH2si8s",
self.name.encode(),
socket.AF_INET,
b"\x00" * 2,
nmbytes,
b"\x00" * 8,
)
fcntl.ioctl(sockfd, arch.SIOCSIFNETMASK, ifreq)
@warp_init_del
def get_mtu(self):
"""
Get MTU size of the interface
"""
ifreq = struct.pack("16sH14s", self.name.encode(), socket.AF_INET, b"\x00" * 14)
res = fcntl.ioctl(sockfd, arch.SIOCGIFMTU, ifreq)
return struct.unpack("16sH14s", res)[1]
@warp_init_del
def set_mtu(self, newmtu):
"""
Set MTU size of the interface
"""
ifreq = struct.pack("16sH14s", self.name.encode(), newmtu, b"\x00" * 14)
fcntl.ioctl(sockfd, arch.SIOCSIFMTU, ifreq)
@warp_init_del
def get_index(self):
"""
Convert an interface name to an index value.
"""
ifreq = struct.pack("16si", self.name.encode(), 0)
res = fcntl.ioctl(sockfd, arch.SIOCGIFINDEX, ifreq)
return struct.unpack("16si", res)[1]
@warp_init_del
def get_stats(self):
"""
Get the status information of the Interface
"""
spl_re = re.compile(r"\s+")
fp = open(PROCFS_NET_PATH)
# Skip headers
fp.readline()
fp.readline()
while True:
data = fp.readline()
if not data:
return None
name, stats_str = data.split(":")
if name.strip() != self.name:
continue
stats = [int(a) for a in spl_re.split(stats_str.strip())]
break
titles = [
"rx_bytes",
"rx_packets",
"rx_errs",
"rx_drop",
"rx_fifo",
"rx_frame",
"rx_compressed",
"rx_multicast",
"tx_bytes",
"tx_packets",
"tx_errs",
"tx_drop",
"tx_fifo",
"tx_colls",
"tx_carrier",
"tx_compressed",
]
return dict(zip(titles, stats))
def is_brport(self):
"""
Check Whether this Interface is a bridge port_to_br
"""
path = os.path.join(SYSFS_NET_PATH, self.name)
return os.path.exists(os.path.join(path, "brport"))
def __netlink_pack(self, msgtype, flags, seq, pid, data):
"""
Pack with Netlink message header and data
into Netlink package
:msgtype: Message types: e.g. RTM_DELLINK
:flags: Flag bits
:seq: The sequence number of the message
:pid: Process ID
:data: data
:return: return the package
"""
return struct.pack("IHHII", 16 + len(data), msgtype, flags, seq, pid) + data
def __netlink_unpack(self, data):
"""
Unpack the data from kernel
"""
out = []
while data:
length, msgtype, flags, seq, pid = struct.unpack("IHHII", data[:16])
if len(data) < length:
raise RuntimeError("Buffer overrun!")
out.append((msgtype, flags, seq, pid, data[16:length]))
data = data[length:]
return out
def dellink(self):
"""
Delete the interface. Equivalent to 'ip link delete NAME'.
"""
# create socket
sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, arch.NETLINK_ROUTE)
# Get the interface index
interface_index = self.get_index()
# send data to socket
sock.send(
self.__netlink_pack(
msgtype=arch.RTM_DELLINK,
flags=arch.NLM_F_REQUEST | arch.NLM_F_ACK,
seq=1,
pid=0,
data=struct.pack("BxHiII", arch.AF_PACKET, 0, interface_index, 0, 0),
)
)
# receive data from socket
try:
while True:
data_recv = sock.recv(1024)
for msgtype, flags, mseq, pid, data in self.__netlink_unpack(data_recv):
if msgtype == arch.NLMSG_ERROR:
(err_no,) = struct.unpack("i", data[:4])
if err_no == 0:
return 0
else:
raise DelLinkError(self.name, os.strerror(-err_no))
else:
raise DelLinkError(self.name, "unexpected error")
finally:
sock.close()
class Macvtap(Interface):
"""
class of macvtap, base Interface
"""
def __init__(self, tapname=None):
if tapname is None:
self.tapname = "macvtap" + utils_misc.generate_random_id()
else:
self.tapname = tapname
Interface.__init__(self, self.tapname)
def get_tapname(self):
return self.tapname
def get_device(self):
return "/dev/tap%s" % self.get_index()
def ip_link_ctl(self, params, ignore_status=False):
return process.run(
"%s %s" % (utils_path.find_command("ip"), " ".join(params)),
ignore_status=ignore_status,
verbose=False,
)
def create(self, device, mode="vepa"):
"""
Create a macvtap device, only when the device does not exist.
:param device: Macvtap device to be created.
:param mode: Creation mode.
"""
path = os.path.join(SYSFS_NET_PATH, self.tapname)
if not os.path.exists(path):
self.ip_link_ctl(
[
"link",
"add",
"link",
device,
"name",
self.tapname,
"type",
"macvtap",
"mode",
mode,
]
)
def delete(self):
path = os.path.join(SYSFS_NET_PATH, self.tapname)
if os.path.exists(path):
self.ip_link_ctl(["link", "delete", self.tapname])
def open(self):
device = self.get_device()
try:
return os.open(device, os.O_RDWR)
except OSError as e:
raise TAPModuleError(device, "open", e)
class IPAddress(object):
"""
Class to manipulate IPv4 or IPv6 address.
"""
def __init__(self, ip_str="", info=""):
self.addr = ""
self.iface = ""
self.scope = 0
self.packed_addr = None
if info:
try:
self.iface = info["iface"]
self.addr = info["addr"]
self.version = info["version"]
self.scope = info["scope"]
except KeyError:
pass
if ip_str:
self.canonicalize(ip_str)
def __str__(self):
if self.version == "ipv6":
return "%s%%%s" % (self.addr, self.scope)
else:
return self.addr
def canonicalize(self, ip_str):
"""
Parse an IP string for listen to IPAddress content.
"""
try:
if ":" in ip_str:
self.version = "ipv6"
if "%" in ip_str:
ip_str, scope = ip_str.split("%")
self.scope = int(scope)
self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str)
self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr)
else:
self.version = "ipv4"
self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str)
self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr)
except socket.error as detail:
if "illegal IP address" in str(detail):
self.addr = ip_str
self.version = "hostname"
def listening_on(self, port, max_retry=30):
"""
Check whether a port is used for listening.
"""
def test_connection(self, port):
"""
Try connect to a port and return the connect result as error no.
"""
port = int(port)
if self.version == "ipv6":
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.settimeout(1.0)
result = sock.connect_ex((self.addr, port, 0, self.scope))
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.0)
result = sock.connect_ex((self.addr, port))
return result
retry = 0
while True:
if retry == max_retry:
return False
result = test_connection(self, port)
if result == 0:
return True
elif result == 11: # Resource temporarily unavailable.
time.sleep(0.1)
retry += 1
else:
return False
def __eq__(self, other_ip):
if self.version != other_ip.version:
return False
if self.addr != other_ip.addr:
return False
if self.iface and other_ip.iface and self.iface != other_ip.iface:
return False
return True
def raw_ping(command, timeout, session, output_func):
"""
Low-level ping command execution.
:param command: Ping command.
:param timeout: Timeout of the ping command.
:param session: Local executon hint or session to execute the ping command.
"""
if session is None:
LOG.info("The command of Ping is: %s", command)
process = aexpect.run_bg(command, output_func=output_func, timeout=timeout)
# Send SIGINT signal to notify the timeout of running ping process,
# Because ping have the ability to catch the SIGINT signal so we can
# always get the packet loss ratio even if timeout.
if process.is_alive():
utils_misc.kill_process_tree(process.get_pid(), signal.SIGINT)
status = process.get_status()
output = process.get_output()
process.close()
return status, output
else:
output = ""
try:
output = session.cmd_output(
command, timeout=timeout, print_func=output_func
)
except aexpect.ShellTimeoutError:
# Send ctrl+c (SIGINT) through ssh session
session.send("\003")
try:
output2 = session.read_up_to_prompt(print_func=output_func)
output += output2
except aexpect.ExpectTimeoutError as e:
output += e.output
# We also need to use this session to query the return value
session.send("\003")
session.sendline(session.status_test_command)
try:
o2 = session.read_up_to_prompt()
except aexpect.ExpectError:
status = -1
else:
try:
status = int(re.findall("\d+", o2)[0])
except Exception:
status = -1
return status, output
def ping(
dest=None,
count=None,
interval=None,
interface=None,
packetsize=None,
ttl=None,
hint=None,
adaptive=False,
broadcast=False,
flood=False,
timeout=0,
output_func=LOG.debug,
session=None,
force_ipv4=False,
):
"""
Wrapper of ping.
:param dest: Destination address.
:param count: Count of icmp packet.
:param interval: Interval of two icmp echo request.
:param interface: Specified interface of the source address.
:param packetsize: Packet size of icmp.
:param ttl: IP time to live.
:param hint: Path mtu discovery hint.
:param adaptive: Adaptive ping flag.
:param broadcast: Broadcast ping flag.
:param flood: Flood ping flag.
:param timeout: Timeout for the ping command.
:param output_func: Function used to log the result of ping.
:param session: Local executon hint or session to execute the ping command.
:param force_ipv4: Whether or not force using IPV4 to ping.
"""
command = "ping"
if session and "Windows" in session.cmd_output_safe("echo %OS%"):
if dest:
command += " %s " % dest
else:
command += " localhost "
if count:
command += " -n %s" % count
if packetsize:
command += " -l %s" % packetsize
if ttl:
command += " -i %s" % ttl
if interface:
command += " -S %s" % interface
if flood:
command += " -t"
else:
if ":" in dest:
command = "ping6"
if dest:
command += " %s " % dest
else:
command += " localhost "
if count:
command += " -c %s" % count
if interval:
command += " -i %s" % interval
if interface:
command += " -I %s" % interface
else:
if dest.upper().startswith("FE80"):
err_msg = "Using ipv6 linklocal must assigne interface"
raise exceptions.TestSkipError(err_msg)
if packetsize:
command += " -s %s" % packetsize
if ttl:
command += " -t %s" % ttl
if hint:
command += " -M %s" % hint
if adaptive:
command += " -A"
if broadcast:
command += " -b"
if flood:
command += " -f -q"
command = "sleep %s && kill -2 `pidof ping` & %s" % (timeout, command)
output_func = None
timeout += 1
if force_ipv4:
command += " -4"
return raw_ping(command, timeout, session, output_func)
def get_macvtap_base_iface(base_interface=None):
"""
Get physical interface to create macvtap, if you assigned base interface
is valid(not belong to any bridge and is up), will use it; else use the
first physical interface, which is not a brport and up.
"""
tap_base_device = None
(dev_int, _) = get_sorted_net_if()