Skip to content

Commit 1bd5bba

Browse files
authored
Merge pull request #500 from NetSys/2to3
Python 2/3 Compatibility
2 parents 7b5d7a7 + 3b2bd70 commit 1bd5bba

54 files changed

Lines changed: 284 additions & 251 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.travis.yml

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ before_install:
3131
- sudo apt-get -q update
3232

3333
install:
34-
- sudo apt-get install -y python
35-
- pip install grpcio scapy codecov
34+
- sudo apt-get install -y python2.7 python3 python3-pip
35+
- pip2 install grpcio scapy codecov
36+
- pip3 install grpcio scapy-python3 coverage
3637
- "[[ ${DEBUG:-0} == 0 ]] || sudo apt-get install -y g++-5" # install gcov-5
3738
- "[[ ${SANITIZE:-0} == 0 ]] || sudo apt-get install -y llvm-3.8"
3839
- "[[ $TAG_SUFFIX != _32 ]] || sudo apt-get install -y lib32gcc1"
@@ -50,8 +51,10 @@ script:
5051
- ./container_build.py bess
5152
- ./container_build.py kmod_buildtest
5253
- (cd core && ./all_test) # TcpFlowReconstructTest requires working directory to be `core/`
53-
- coverage run -m unittest discover -v
54-
- bessctl/bessctl -- daemon start -- run testing/run_module_tests
54+
- coverage2 run -m unittest discover -v
55+
- "[[ ${DEBUG:-0} == 0 ]] || coverage3 run -m unittest discover -v"
56+
- python2 bessctl/bessctl -- daemon start -- run testing/run_module_tests
57+
- "[[ ${DEBUG:-0} == 0 ]] || python3 bessctl/bessctl -- daemon start -- run testing/run_module_tests"
5558

5659
after_success:
5760
- bessctl/bessctl daemon stop # flush out the coverage data

bessctl/bessctl

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,25 @@
1-
#!/usr/bin/env python2.7
1+
#!/usr/bin/env python
2+
from __future__ import print_function
3+
from __future__ import absolute_import
24
import sys
35
import os
46
import os.path
5-
import cStringIO
7+
import io
68
import tempfile
79
import time
10+
import cli
11+
import commands
812

913
# Suppress scapy IPv6 warning (must be done before importing scapy module)
1014
import logging
1115
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
1216

13-
import cli
14-
import commands
15-
1617
try:
1718
this_dir = os.path.dirname(os.path.realpath(__file__))
1819
sys.path.insert(1, os.path.join(this_dir, '..'))
1920
from pybess.bess import *
2021
except ImportError:
21-
print >> sys.stderr, 'Cannot import the API module (pybess)'
22+
print('Cannot import the API module (pybess)', file=sys.stderr)
2223
raise
2324

2425

@@ -68,7 +69,7 @@ class BESSCLI(cli.CLI):
6869

6970
except self.bess.RPCError as e:
7071
self.err('RPC failed to {}:{} - {}'.format(
71-
self.bess.peer[0], self.bess.peer[1], e.message))
72+
self.bess.peer[0], self.bess.peer[1], str(e)))
7273

7374
self._handle_broken_connection()
7475
raise self.HandledError()
@@ -120,7 +121,7 @@ def run_cli(instream=sys.stdin):
120121
s.connect()
121122
except BESS.APIError as e:
122123
if cli.interactive:
123-
cli.ferr.write(e.message + '\n')
124+
cli.ferr.write(str(e) + '\n')
124125
cli.ferr.write('Perhaps bessd daemon is not running locally? '
125126
'Try "daemon start".\n')
126127

@@ -147,8 +148,8 @@ def main():
147148
else:
148149
line_buf.append(arg)
149150

150-
cmds.append(' '.join(line_buf))
151-
run_cli(cStringIO.StringIO('\n'.join(cmds)))
151+
cmds.append(u' '.join(line_buf))
152+
run_cli(io.StringIO('\n'.join(cmds)))
152153

153154
if __name__ == '__main__':
154155
main()

bessctl/cli.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ def list_matched(self, line, filters):
198198
if len(matched_list) == 0:
199199
return [], []
200200

201-
max_score = max(map(lambda x: x[1], matched_list))
201+
max_score = max([x[1] for x in matched_list])
202202

203203
ret = []
204204
ret_low = []
@@ -371,7 +371,11 @@ def print_banner(self):
371371
def process_one_line(self):
372372
if self.interactive:
373373
try:
374-
line = raw_input(self.get_prompt())
374+
# Hack for Python 2/3 compatibility
375+
if hasattr(__builtins__, 'raw_input'):
376+
line = raw_input(self.get_prompt())
377+
else:
378+
line = input(self.get_prompt())
375379
except KeyboardInterrupt:
376380
self.fout.write('\n')
377381
return

bessctl/commands.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import print_function
2+
from __future__ import absolute_import
13
import os
24
import os.path
35
import sys
@@ -15,7 +17,6 @@
1517
import tempfile
1618
import signal
1719
import collections
18-
1920
import sugar
2021

2122
try:
@@ -24,7 +25,7 @@
2425
from pybess.module import *
2526
from pybess.port import *
2627
except ImportError:
27-
print >> sys.stderr, 'Cannot import the API module (pybess)'
28+
print('Cannot import the API module (pybess)', file=sys.stderr)
2829
raise
2930

3031

@@ -62,8 +63,8 @@ def __bess_env__(key, default=None):
6263
if default is None:
6364
raise ConfError('Environment variable "%s" must be set.')
6465

65-
print 'Environment variable "%s" is not set. \
66-
Using default value "%s"' % (key, default)
66+
print('Environment variable "%s" is not set. \
67+
Using default value "%s"' % (key, default))
6768
return default
6869

6970

@@ -545,7 +546,12 @@ def warn(cli, msg, func, *args):
545546
cli.rl.set_completer(cli.complete_dummy)
546547

547548
try:
548-
resp = raw_input('WARNING: %s Are you sure? (type "yes") ' % msg)
549+
# Hack for Python 2/3 compatibility
550+
if hasattr(__builtins__, 'raw_input'):
551+
resp = raw_input(
552+
'WARNING: %s Are you sure? (type "yes") ' % msg)
553+
else:
554+
resp = input('WARNING: %s Are you sure? (type "yes") ' % msg)
549555

550556
if resp.strip() == 'yes':
551557
func(cli, *args)
@@ -742,13 +748,13 @@ def _run_file(cli, conf_file, env_map):
742748
try:
743749
original_env = copy.copy(os.environ)
744750

745-
for k, v in env_map.iteritems():
751+
for k, v in env_map.items():
746752
os.environ[k] = str(v)
747753

748754
_do_run_file(cli, conf_file)
749755
finally:
750756
os.environ.clear()
751-
for k, v in original_env.iteritems():
757+
for k, v in original_env.items():
752758
os.environ[k] = v
753759
else:
754760
_do_run_file(cli, conf_file)
@@ -933,7 +939,7 @@ def _limit_to_str(limit):
933939

934940
def _burst_to_str(burst):
935941
# no output if max_burst is not set
936-
if len(burst.values()) == 0 or burst.values()[0] == 0:
942+
if len(burst) == 0 or list(burst.values())[0] == 0:
937943
return ''
938944

939945
if 'count' in burst:
@@ -1044,10 +1050,10 @@ def check_constraints(cli):
10441050

10451051

10461052
def _show_tc_list(cli, tcs):
1047-
wids = sorted(list(set(map(lambda tc: getattr(tc, 'class').wid, tcs))))
1053+
wids = sorted(list(set([getattr(tc, 'class').wid for tc in tcs])))
10481054

10491055
for wid in wids:
1050-
matched = filter(lambda tc: getattr(tc, 'class').wid == wid, tcs)
1056+
matched = [tc for tc in tcs if getattr(tc, 'class').wid == wid]
10511057

10521058
root = _build_tcs_tree(matched)
10531059
if wid == -1:
@@ -1151,7 +1157,7 @@ def _draw_pipeline(cli, field, units, last_stats=None):
11511157
stderr=subprocess.PIPE)
11521158

11531159
for m in modules:
1154-
print >> f.stdin, '[%s]' % node_labels[m.name]
1160+
print('[%s]' % node_labels[m.name], file=f.stdin)
11551161

11561162
for name in names:
11571163
gates = cli.bess.get_module_info(name).ogates
@@ -1178,10 +1184,10 @@ def _draw_pipeline(cli, field, units, last_stats=None):
11781184
edge_attr = '{label::%d %s %s %d:;}' % (
11791185
gate.ogate, label, units, gate.igate)
11801186

1181-
print >> f.stdin, '[%s] ->%s [%s]' % (
1187+
print('[%s] ->%s [%s]' % (
11821188
node_labels[name],
11831189
edge_attr,
1184-
node_labels[gate.name])
1190+
node_labels[gate.name]), file=f.stdin)
11851191
output, error = f.communicate()
11861192
f.wait()
11871193
return output
@@ -1558,8 +1564,8 @@ def get_total(arr):
15581564

15591565
if len(ports) > 1:
15601566
print_delta('Total', get_delta(
1561-
get_total(last.values()),
1562-
get_total(now.values())))
1567+
get_total(list(last.values())),
1568+
get_total(list(now.values()))))
15631569

15641570
for port in ports:
15651571
last[port] = now[port]
@@ -1686,7 +1692,7 @@ def tcpdump_module(cli, module_name, direction, gate, opts):
16861692
direction = 'out'
16871693

16881694
fifo = tempfile.mktemp()
1689-
os.mkfifo(fifo, 0600) # random people should not see packets...
1695+
os.mkfifo(fifo, 0o600) # random people should not see packets...
16901696

16911697
fd = os.open(fifo, os.O_RDWR)
16921698

bessctl/conf/metadata/attr_match.bess

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,5 @@ em:1 -> Sink()
1919
em:2 -> Sink()
2020

2121
# NOTE: metadata attribute values are stored in host order (little endian)!
22-
em.add(fields=['\xcc', '\x22\x11'], gate=1)
23-
em.add(fields=['\x42', '\x33\x44'], gate=2)
22+
em.add(fields=[b'\xcc', b'\x22\x11'], gate=1)
23+
em.add(fields=[b'\x42', b'\x33\x44'], gate=2)

bessctl/conf/perftest/bpf.bess

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ bpf:2 -> Sink() # for matched packets (by the second filter)
1010

1111
def run_testcase(exps, test_pkts):
1212
rewrite.clear()
13-
rewrite.add(templates=map(lambda x: str(x), test_pkts))
13+
rewrite.add(templates=map(lambda x: bytes(x), test_pkts))
1414

1515
# the higher number, the higher priority.
1616
bpf.clear()
@@ -34,10 +34,10 @@ def run_testcase(exps, test_pkts):
3434

3535
pps_total = pps_matched + pps_unmatched
3636

37-
print 'Total: %8.3fMpps Matched: %8.3fMpps Unmatched: %8.3fMpps' % \
38-
(pps_total / 1000000.0,
39-
pps_matched / 1000000.0,
40-
pps_unmatched / 1000000.0)
37+
print('Total: %8.3fMpps Matched: %8.3fMpps Unmatched: %8.3fMpps' %
38+
(pps_total / 1000000.0,
39+
pps_matched / 1000000.0,
40+
pps_unmatched / 1000000.0))
4141

4242
bess.pause_all()
4343

@@ -62,11 +62,11 @@ testcases = [
6262
]
6363

6464
for i, case in enumerate(testcases):
65-
print
66-
print 'Testcase %d: %s' % (i, ', '.join(case[0]))
65+
print()
66+
print('Testcase %d: %s' % (i, ', '.join(case[0])))
6767
pprint.pprint(case[1])
6868

6969
print
7070
for i, case in enumerate(testcases):
71-
print 'Testcase %d:\t\t' % i,
71+
print('Testcase %d:\t\t' % i, end=' ')
7272
run_testcase(*case)

bessctl/conf/perftest/flowgen.bess

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ ip = scapy.IP(src=src_ip, dst=dst_ip)
2323
src_port = int($BESS_SRC_PORT!'10001')
2424
tcp = scapy.TCP(sport=src_port, dport=12345, seq=12345)
2525
payload = "BESS is the Queen of Packet Processing."
26-
pkt_template = str(eth/ip/tcp/payload)
26+
pkt_template = bytes(eth/ip/tcp/payload)
2727

2828
# This script is multi threaded but connects to a single port.
2929
myport = PMDPort(port_id=0, num_inc_q=num_cores, num_out_q=num_cores)
@@ -49,7 +49,7 @@ while True:
4949
portstats = myport.get_port_stats().inc.packets
5050
delta = portstats - prev_portstats
5151
nextround = max(1e6, 1.1 * delta / sleeptime)
52-
print("Received " + str(delta / sleeptime) + " pps. Ramping up to: " + str(nextround))
52+
print("Received " + bytes(delta / sleeptime) + " pps. Ramping up to: " + bytes(nextround))
5353
for wid, pkt_src in flowgens.items():
5454
bess.pause_worker(wid)
5555
pkt_src.update(pps = nextround / num_cores)

bessctl/conf/perftest/loopback_vport.bess

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -39,32 +39,32 @@ def measure():
3939
old_stats[i].inc.packets
4040
inc_mpps.append(pkts_diff / time_diff / 1000000.0)
4141

42-
print '%-15s' % 'CPU',
43-
print '%7s' % '',
42+
print('%-15s' % 'CPU', end=' ')
43+
print('%7s' % '', end=' ')
4444
for i in range(len(ports)):
45-
print '%7d' % cpu_set[i],
45+
print('%7d' % cpu_set[i], end=' ')
4646
print
4747

48-
print '%-15s' % 'Ports',
49-
print '%7s' % '(total)',
48+
print('%-15s' % 'Ports', end=' ')
49+
print('%7s' % '(total)', end=' ')
5050
for i in range(len(ports)):
51-
print '%7s' % ports[i].name,
52-
print
51+
print('%7s' % ports[i].name, end=' ')
52+
print()
5353

54-
print '-' * (8 * (len(ports) + 3))
54+
print('-' * (8 * (len(ports) + 3)))
5555

56-
print '%-15s' % 'Outgoing (Mpps)',
57-
print '%7.3f' % sum(out_mpps),
56+
print('%-15s' % 'Outgoing (Mpps)', end=' ')
57+
print('%7.3f' % sum(out_mpps), end=' ')
5858
for i in range(len(ports)):
59-
print '%7.3f' % out_mpps[i],
60-
print
59+
print('%7.3f' % out_mpps[i], end=' ')
60+
print()
6161

62-
print '%-15s' % 'Incoming (Mpps)',
63-
print '%7.3f' % sum(inc_mpps),
62+
print('%-15s' % 'Incoming (Mpps)', end=' ')
63+
print('%7.3f' % sum(inc_mpps), end=' ')
6464
for i in range(len(ports)):
65-
print '%7.3f' % inc_mpps[i],
66-
print
67-
print
65+
print('%7.3f' % inc_mpps[i], end=' ')
66+
print()
67+
print()
6868

6969
for cpu in range(CORE_START, CORE_END, CORE_STEP):
7070
v = VPort(loopback=1, rxq_cpus=[cpu])

bessctl/conf/perftest/nat.bess

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ eth = scapy.Ether(src='02:1e:67:9f:4d:ac', dst='06:16:3e:1b:72:32')
1010
ip = scapy.IP(src='10.0.0.1', dst='192.168.1.1')
1111
udp = scapy.UDP(sport=10001, dport=10002)
1212
payload = 'helloworld'
13-
pkt_bytes = str(eth/ip/udp/payload)
13+
pkt_bytes = bytes(eth/ip/udp/payload)
1414

1515
Source() \
1616
-> Rewrite(templates=[pkt_bytes]) \

bessctl/conf/perftest/pktgen.bess

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def build_pkt(size):
2121
payload = ('hello' + '0123456789' * 200)[:size-len(eth/ip/udp)]
2222
pkt = eth/ip/udp/payload
2323
pkt.show()
24-
return str(pkt)
24+
return bytes(pkt)
2525

2626
if imix:
2727
# https://en.wikipedia.org/wiki/Internet_Mix
@@ -45,7 +45,7 @@ ports = [PMDPort(port_id=i, num_inc_q=num_cores, num_out_q=num_cores) \
4545
for i in range(num_ports)]
4646

4747
for i in range(num_cores):
48-
print("starting up worker: " + str(i))
48+
print("starting up worker: " + bytes(i))
4949
bess.add_worker(wid=i, core=i)
5050

5151
src = Source()

0 commit comments

Comments
 (0)