diff --git a/ryu/lib/bfdlib.py b/ryu/lib/bfdlib.py index 388618a7..6818b3e7 100644 --- a/ryu/lib/bfdlib.py +++ b/ryu/lib/bfdlib.py @@ -34,10 +34,11 @@ Please note that: import logging -import six import time import random +import six + from ryu.base import app_manager from ryu.controller import event from ryu.controller import ofp_event @@ -47,7 +48,6 @@ from ryu.exception import RyuException from ryu.ofproto.ether import ETH_TYPE_IP, ETH_TYPE_ARP from ryu.ofproto import ofproto_v1_3 from ryu.ofproto import inet -from ryu.lib import ofctl_v1_3 from ryu.lib import hub from ryu.lib.packet import packet from ryu.lib.packet import ethernet @@ -462,7 +462,6 @@ class BFDSession(object): self._remote_session_state == bfd.BFD_STATE_UP: flags |= bfd.BFD_FLAG_DEMAND - ver = 1 diag = self._local_diag state = self._session_state detect_mult = self._detect_mult @@ -570,13 +569,13 @@ class BFDPacket(object): i = iter(pkt) eth_pkt = next(i) - assert type(eth_pkt) == ethernet.ethernet + assert isinstance(eth_pkt, ethernet.ethernet) ipv4_pkt = next(i) - assert type(ipv4_pkt) == ipv4.ipv4 + assert isinstance(ipv4_pkt, ipv4.ipv4) - udp_pkt = i.next() - assert type(udp_pkt) == udp.udp + udp_pkt = next(i) + assert isinstance(udp_pkt, udp.udp) udp_payload = next(i) @@ -619,10 +618,10 @@ class ARPPacket(object): i = iter(pkt) eth_pkt = next(i) # Ensure it's an ethernet frame. - assert type(eth_pkt) == ethernet.ethernet + assert isinstance(eth_pkt, ethernet.ethernet) arp_pkt = next(i) - if type(arp_pkt) != arp.arp: + if not isinstance(arp_pkt, arp.arp): raise ARPPacket.ARPUnknownFormat() if arp_pkt.opcode not in (ARP_REQUEST, ARP_REPLY): diff --git a/ryu/lib/dpid.py b/ryu/lib/dpid.py index 1224ae0e..87208859 100644 --- a/ryu/lib/dpid.py +++ b/ryu/lib/dpid.py @@ -18,8 +18,7 @@ # string representation is in hex without '0x' _DPID_LEN = 16 -_DPID_LEN_STR = str(_DPID_LEN) -_DPID_FMT = '%0' + _DPID_LEN_STR + 'x' +_DPID_FMT = '%0{0}x'.format(_DPID_LEN) DPID_PATTERN = r'[0-9a-f]{%d}' % _DPID_LEN diff --git a/ryu/lib/hub.py b/ryu/lib/hub.py index 2ec8d691..a5ac50a6 100644 --- a/ryu/lib/hub.py +++ b/ryu/lib/hub.py @@ -54,9 +54,9 @@ if HUB_TYPE == 'eventlet': return func(*args, **kwargs) except TaskExit: pass - except: + except BaseException as e: if raise_error: - raise + raise e # Log uncaught exception. # Note: this is an intentional divergence from gevent # behaviour; gevent silently ignores such exceptions. @@ -75,9 +75,9 @@ if HUB_TYPE == 'eventlet': return func(*args, **kwargs) except TaskExit: pass - except: + except BaseException as e: if raise_error: - raise + raise e # Log uncaught exception. # Note: this is an intentional divergence from gevent # behaviour; gevent silently ignores such exceptions. diff --git a/ryu/lib/igmplib.py b/ryu/lib/igmplib.py index a2822323..719626f3 100644 --- a/ryu/lib/igmplib.py +++ b/ryu/lib/igmplib.py @@ -573,7 +573,7 @@ class IgmpSnooper(IgmpBase): timeout = query.maxresp / 10 self._to_hosts.setdefault(dpid, {}) - if '0.0.0.0' == query.address: + if query.address == '0.0.0.0': # general query. reset all reply status. for group in self._to_hosts[dpid].values(): group['replied'] = False diff --git a/ryu/lib/lacplib.py b/ryu/lib/lacplib.py index 84d4777c..36682a6f 100644 --- a/ryu/lib/lacplib.py +++ b/ryu/lib/lacplib.py @@ -84,12 +84,11 @@ class LacpLib(app_manager.RyuApp): if you want to use multi LAG, call 'add' method more than once. """ assert isinstance(ports, list) - assert 2 <= len(ports) + assert len(ports) >= 2 ifs = {} for port in ports: ifs[port] = {'enabled': False, 'timeout': 0} - bond = {} - bond[dpid] = ifs + bond = {dpid: ifs} self._bonds.append(bond) # ------------------------------------------------------------------- diff --git a/ryu/lib/ofctl_utils.py b/ryu/lib/ofctl_utils.py index 89cd5c83..a09517a2 100644 --- a/ryu/lib/ofctl_utils.py +++ b/ryu/lib/ofctl_utils.py @@ -195,7 +195,7 @@ def to_match_vid(value, ofpvid_present): def to_match_masked_int(value): if isinstance(value, str) and '/' in value: value = value.split('/') - return (str_to_int(value[0]), str_to_int(value[1])) + return str_to_int(value[0]), str_to_int(value[1]) return str_to_int(value) diff --git a/ryu/lib/ofctl_v1_0.py b/ryu/lib/ofctl_v1_0.py index b38cc12b..be7d3913 100644 --- a/ryu/lib/ofctl_v1_0.py +++ b/ryu/lib/ofctl_v1_0.py @@ -290,8 +290,8 @@ def get_desc_stats(dp, waiters): 'sw_desc': stats.sw_desc, 'serial_num': stats.serial_num, 'dp_desc': stats.dp_desc} - desc = {str(dp.id): s} - return desc + + return {str(dp.id): s} def get_queue_stats(dp, waiters, port=None, queue_id=None): @@ -319,8 +319,8 @@ def get_queue_stats(dp, waiters, port=None, queue_id=None): 'tx_bytes': stat.tx_bytes, 'tx_errors': stat.tx_errors, 'tx_packets': stat.tx_packets}) - desc = {str(dp.id): s} - return desc + + return {str(dp.id): s} def get_flow_stats(dp, waiters, flow=None): @@ -355,8 +355,8 @@ def get_flow_stats(dp, waiters, flow=None): 'packet_count': stats.packet_count, 'table_id': UTIL.ofp_table_to_user(stats.table_id)} flows.append(s) - flows = {str(dp.id): flows} - return flows + + return {str(dp.id): flows} def get_aggregate_flow_stats(dp, waiters, flow=None): @@ -381,9 +381,8 @@ def get_aggregate_flow_stats(dp, waiters, flow=None): 'byte_count': st.byte_count, 'flow_count': st.flow_count} flows.append(s) - flows = {str(dp.id): flows} - return flows + return {str(dp.id): flows} def get_table_stats(dp, waiters): @@ -432,9 +431,8 @@ def get_table_stats(dp, waiters): 'lookup_count': stat.lookup_count, 'matched_count': stat.matched_count} tables.append(s) - desc = {str(dp.id): tables} - return desc + return {str(dp.id): tables} def get_port_stats(dp, waiters, port=None): @@ -465,8 +463,8 @@ def get_port_stats(dp, waiters, port=None): 'rx_crc_err': stats.rx_crc_err, 'collisions': stats.collisions} ports.append(s) - ports = {str(dp.id): ports} - return ports + + return {str(dp.id): ports} def get_port_desc(dp, waiters): @@ -476,7 +474,6 @@ def get_port_desc(dp, waiters): ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG) descs = [] - for msg in msgs: stats = msg.ports for stat in stats.values(): @@ -490,8 +487,8 @@ def get_port_desc(dp, waiters): 'supported': stat.supported, 'peer': stat.peer} descs.append(d) - descs = {str(dp.id): descs} - return descs + + return {str(dp.id): descs} def mod_flow_entry(dp, flow, cmd): diff --git a/ryu/lib/ofctl_v1_2.py b/ryu/lib/ofctl_v1_2.py index 3015b305..f51b0fd2 100644 --- a/ryu/lib/ofctl_v1_2.py +++ b/ryu/lib/ofctl_v1_2.py @@ -95,8 +95,8 @@ def to_actions(dp, acts): if action_type == 'WRITE_ACTIONS': write_actions = [] write_acts = a.get('actions') - for a in write_acts: - action = to_action(dp, a) + for act in write_acts: + action = to_action(dp, act) if action is not None: write_actions.append(action) else: @@ -106,8 +106,8 @@ def to_actions(dp, acts): parser.OFPInstructionActions(ofp.OFPIT_WRITE_ACTIONS, write_actions)) elif action_type == 'CLEAR_ACTIONS': - inst.append(parser.OFPInstructionActions( - ofp.OFPIT_CLEAR_ACTIONS, [])) + inst.append( + parser.OFPInstructionActions(ofp.OFPIT_CLEAR_ACTIONS, [])) elif action_type == 'GOTO_TABLE': table_id = UTIL.ofp_table_from_user(a.get('table_id')) inst.append(parser.OFPInstructionGotoTable(table_id)) @@ -358,8 +358,7 @@ def match_to_str(ofmatch): 'tcp_src': 'tp_src', 'tcp_dst': 'tp_dst', 'udp_src': 'tp_src', - 'udp_dst': 'tp_dst' - } + 'udp_dst': 'tp_dst'} match = {} @@ -407,8 +406,8 @@ def get_desc_stats(dp, waiters): 'sw_desc': stats.sw_desc, 'serial_num': stats.serial_num, 'dp_desc': stats.dp_desc} - desc = {str(dp.id): s} - return desc + + return {str(dp.id): s} def get_queue_stats(dp, waiters, port=None, queue_id=None): @@ -438,8 +437,8 @@ def get_queue_stats(dp, waiters, port=None, queue_id=None): 'tx_bytes': stat.tx_bytes, 'tx_errors': stat.tx_errors, 'tx_packets': stat.tx_packets}) - desc = {str(dp.id): s} - return desc + + return {str(dp.id): s} def get_queue_config(dp, waiters, port=None): @@ -452,10 +451,11 @@ def get_queue_config(dp, waiters, port=None): msgs = [] ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG) - prop_type = {dp.ofproto.OFPQT_MIN_RATE: 'MIN_RATE', - dp.ofproto.OFPQT_MAX_RATE: 'MAX_RATE', - dp.ofproto.OFPQT_EXPERIMENTER: 'EXPERIMENTER', - } + prop_type = { + dp.ofproto.OFPQT_MIN_RATE: 'MIN_RATE', + dp.ofproto.OFPQT_MAX_RATE: 'MAX_RATE', + dp.ofproto.OFPQT_EXPERIMENTER: 'EXPERIMENTER', + } configs = [] for config in msgs: @@ -478,9 +478,8 @@ def get_queue_config(dp, waiters, port=None): c = {'port': UTIL.ofp_port_to_user(config.port), 'queues': queue_list} configs.append(c) - configs = {str(dp.id): configs} - return configs + return {str(dp.id): configs} def get_flow_stats(dp, waiters, flow=None): @@ -519,9 +518,8 @@ def get_flow_stats(dp, waiters, flow=None): 'table_id': UTIL.ofp_table_to_user(stats.table_id), 'length': stats.length} flows.append(s) - flows = {str(dp.id): flows} - return flows + return {str(dp.id): flows} def get_aggregate_flow_stats(dp, waiters, flow=None): @@ -549,9 +547,8 @@ def get_aggregate_flow_stats(dp, waiters, flow=None): 'byte_count': stats.byte_count, 'flow_count': stats.flow_count} flows.append(s) - flows = {str(dp.id): flows} - return flows + return {str(dp.id): flows} def get_table_stats(dp, waiters): @@ -674,9 +671,8 @@ def get_table_stats(dp, waiters): 'lookup_count': stat.lookup_count, 'matched_count': stat.matched_count} tables.append(s) - desc = {str(dp.id): tables} - return desc + return {str(dp.id): tables} def get_port_stats(dp, waiters, port=None): @@ -707,8 +703,8 @@ def get_port_stats(dp, waiters, port=None): 'rx_crc_err': stats.rx_crc_err, 'collisions': stats.collisions} ports.append(s) - ports = {str(dp.id): ports} - return ports + + return {str(dp.id): ports} def get_group_stats(dp, waiters, group_id=None): @@ -737,8 +733,8 @@ def get_group_stats(dp, waiters, group_id=None): 'byte_count': stats.byte_count, 'bucket_stats': bucket_counters} groups.append(g) - groups = {str(dp.id): groups} - return groups + + return {str(dp.id): groups} def get_group_features(dp, waiters): @@ -797,8 +793,8 @@ def get_group_features(dp, waiters): 'max_groups': max_groups, 'actions': actions} features.append(f) - features = {str(dp.id): features} - return features + + return {str(dp.id): features} def get_group_desc(dp, waiters): @@ -829,8 +825,8 @@ def get_group_desc(dp, waiters): 'group_id': UTIL.ofp_group_to_user(stats.group_id), 'buckets': buckets} descs.append(d) - descs = {str(dp.id): descs} - return descs + + return {str(dp.id): descs} def get_port_desc(dp, waiters): @@ -856,8 +852,8 @@ def get_port_desc(dp, waiters): 'curr_speed': stat.curr_speed, 'max_speed': stat.max_speed} descs.append(d) - descs = {str(dp.id): descs} - return descs + + return {str(dp.id): descs} def mod_flow_entry(dp, flow, cmd): diff --git a/ryu/lib/ofctl_v1_3.py b/ryu/lib/ofctl_v1_3.py index 3d768ce2..f407e5ad 100644 --- a/ryu/lib/ofctl_v1_3.py +++ b/ryu/lib/ofctl_v1_3.py @@ -55,8 +55,8 @@ def to_actions(dp, acts): if action_type == 'WRITE_ACTIONS': write_actions = [] write_acts = a.get('actions') - for a in write_acts: - action = to_action(dp, a) + for act in write_acts: + action = to_action(dp, act) if action is not None: write_actions.append(action) else: @@ -66,8 +66,8 @@ def to_actions(dp, acts): parser.OFPInstructionActions(ofp.OFPIT_WRITE_ACTIONS, write_actions)) elif action_type == 'CLEAR_ACTIONS': - inst.append(parser.OFPInstructionActions( - ofp.OFPIT_CLEAR_ACTIONS, [])) + inst.append( + parser.OFPInstructionActions(ofp.OFPIT_CLEAR_ACTIONS, [])) elif action_type == 'GOTO_TABLE': table_id = UTIL.ofp_table_from_user(a.get('table_id')) inst.append(parser.OFPInstructionGotoTable(table_id)) @@ -133,7 +133,7 @@ def action_to_str(act): if act.experimenter == ofproto_common.NX_EXPERIMENTER_ID: try: return ofctl_nicira_ext.action_to_str(act, action_to_str) - except: + except Exception: LOG.debug('Error parsing NX_ACTION(%s)', act.__class__.__name__, exc_info=True) @@ -299,8 +299,7 @@ def match_to_str(ofmatch): 'tcp_src': 'tp_src', 'tcp_dst': 'tp_dst', 'udp_src': 'tp_src', - 'udp_dst': 'tp_dst' - } + 'udp_dst': 'tp_dst'} match = {} @@ -395,8 +394,7 @@ def get_queue_config(dp, waiters, port=None, to_user=True): prop_type = {dp.ofproto.OFPQT_MIN_RATE: 'MIN_RATE', dp.ofproto.OFPQT_MAX_RATE: 'MAX_RATE', - dp.ofproto.OFPQT_EXPERIMENTER: 'EXPERIMENTER', - } + dp.ofproto.OFPQT_EXPERIMENTER: 'EXPERIMENTER'} configs = [] for config in msgs: @@ -564,8 +562,7 @@ def get_table_features(dp, waiters, to_user=True): ofproto.OFPTFPT_APPLY_SETFIELD: 'APPLY_SETFIELD', ofproto.OFPTFPT_APPLY_SETFIELD_MISS: 'APPLY_SETFIELD_MISS', ofproto.OFPTFPT_EXPERIMENTER: 'EXPERIMENTER', - ofproto.OFPTFPT_EXPERIMENTER_MISS: 'EXPERIMENTER_MISS' - } + ofproto.OFPTFPT_EXPERIMENTER_MISS: 'EXPERIMENTER_MISS'} if not to_user: prop_type = dict((k, k) for k in prop_type.keys()) @@ -600,41 +597,42 @@ def get_table_features(dp, waiters, to_user=True): p = {'type': prop_type.get(prop.type, 'UNKNOWN')} if prop.type in p_type_instructions: instruction_ids = [] - for id in prop.instruction_ids: - i = {'len': id.len, - 'type': id.type} - instruction_ids.append(i) + for i in prop.instruction_ids: + inst = {'len': i.len, + 'type': i.type} + instruction_ids.append(inst) p['instruction_ids'] = instruction_ids elif prop.type in p_type_next_tables: table_ids = [] - for id in prop.table_ids: - table_ids.append(id) + for i in prop.table_ids: + table_ids.append(i) p['table_ids'] = table_ids elif prop.type in p_type_actions: action_ids = [] - for id in prop.action_ids: - i = {'len': id.len, - 'type': id.type} - action_ids.append(i) + for i in prop.action_ids: + act = {'len': i.len, + 'type': i.type} + action_ids.append(act) p['action_ids'] = action_ids elif prop.type in p_type_oxms: oxm_ids = [] - for id in prop.oxm_ids: - i = {'hasmask': id.hasmask, - 'length': id.length, - 'type': id.type} - oxm_ids.append(i) + for i in prop.oxm_ids: + oxm = {'hasmask': i.hasmask, + 'length': i.length, + 'type': i.type} + oxm_ids.append(oxm) p['oxm_ids'] = oxm_ids elif prop.type in p_type_experimenter: pass properties.append(p) - s = {'name': stat.name.decode('utf-8'), - 'metadata_match': stat.metadata_match, - 'metadata_write': stat.metadata_write, - 'config': stat.config, - 'max_entries': stat.max_entries, - 'properties': properties, - } + s = { + 'name': stat.name.decode('utf-8'), + 'metadata_match': stat.metadata_match, + 'metadata_write': stat.metadata_write, + 'config': stat.config, + 'max_entries': stat.max_entries, + 'properties': properties, + } if to_user: s['table_id'] = UTIL.ofp_table_to_user(stat.table_id) diff --git a/ryu/lib/ofctl_v1_4.py b/ryu/lib/ofctl_v1_4.py index 98ac94d8..71e33fd7 100644 --- a/ryu/lib/ofctl_v1_4.py +++ b/ryu/lib/ofctl_v1_4.py @@ -166,8 +166,7 @@ def to_match(dp, attrs): 'pbb_isid': ofctl_utils.to_match_masked_int, 'tunnel_id': ofctl_utils.to_match_masked_int, 'ipv6_exthdr': ofctl_utils.to_match_masked_int, - 'pbb_uca': int, - } + 'pbb_uca': int} keys = {'dl_dst': 'eth_dst', 'dl_src': 'eth_src', @@ -430,27 +429,27 @@ def get_table_features(dp, waiters, to_user=True): p['type'] = t if t != prop.type else 'UNKNOWN' if prop.type in p_type_instructions: instruction_ids = [] - for id in prop.instruction_ids: - i = {'len': id.len, - 'type': id.type} - instruction_ids.append(i) + for i in prop.instruction_ids: + inst = {'len': i.len, + 'type': i.type} + instruction_ids.append(inst) p['instruction_ids'] = instruction_ids elif prop.type in p_type_next_tables: table_ids = [] - for id in prop.table_ids: - table_ids.append(id) + for i in prop.table_ids: + table_ids.append(i) p['table_ids'] = table_ids elif prop.type in p_type_actions: action_ids = [] - for id in prop.action_ids: - i = id.to_jsondict()[id.__class__.__name__] - action_ids.append(i) + for i in prop.action_ids: + act = i.to_jsondict()[i.__class__.__name__] + action_ids.append(act) p['action_ids'] = action_ids elif prop.type in p_type_oxms: oxm_ids = [] - for id in prop.oxm_ids: - i = id.to_jsondict()[id.__class__.__name__] - oxm_ids.append(i) + for i in prop.oxm_ids: + oxm = i.to_jsondict()[i.__class__.__name__] + oxm_ids.append(oxm) p['oxm_ids'] = oxm_ids elif prop.type in p_type_experimenter: pass @@ -677,8 +676,7 @@ def get_group_features(dp, waiters, to_user=True): ofp.OFPAT_SET_FIELD: 'SET_FIELD', ofp.OFPAT_PUSH_PBB: 'PUSH_PBB', ofp.OFPAT_POP_PBB: 'POP_PBB', - ofp.OFPAT_EXPERIMENTER: 'EXPERIMENTER', - } + ofp.OFPAT_EXPERIMENTER: 'EXPERIMENTER'} stats = dp.ofproto_parser.OFPGroupFeaturesStatsRequest(dp, 0) msgs = [] diff --git a/ryu/lib/ofctl_v1_5.py b/ryu/lib/ofctl_v1_5.py index 52c2de88..43ee0fcb 100644 --- a/ryu/lib/ofctl_v1_5.py +++ b/ryu/lib/ofctl_v1_5.py @@ -171,8 +171,7 @@ def to_match(dp, attrs): 'pbb_uca': int, 'tcp_flags': int, 'actset_output': int, - 'packet_type': ofctl_utils.to_match_packet_type, - } + 'packet_type': ofctl_utils.to_match_packet_type} keys = {'dl_dst': 'eth_dst', 'dl_src': 'eth_src', @@ -501,27 +500,27 @@ def get_table_features(dp, waiters, to_user=True): p['type'] = t if t != prop.type else 'UNKNOWN' if prop.type in p_type_instructions: instruction_ids = [] - for id in prop.instruction_ids: - i = {'len': id.len, - 'type': id.type} - instruction_ids.append(i) + for i in prop.instruction_ids: + inst = {'len': i.len, + 'type': i.type} + instruction_ids.append(inst) p['instruction_ids'] = instruction_ids elif prop.type in p_type_next_tables: table_ids = [] - for id in prop.table_ids: - table_ids.append(id) + for i in prop.table_ids: + table_ids.append(i) p['table_ids'] = table_ids elif prop.type in p_type_actions: action_ids = [] - for id in prop.action_ids: - i = id.to_jsondict()[id.__class__.__name__] - action_ids.append(i) + for i in prop.action_ids: + act = i.to_jsondict()[i.__class__.__name__] + action_ids.append(act) p['action_ids'] = action_ids elif prop.type in p_type_oxms: oxm_ids = [] - for id in prop.oxm_ids: - i = id.to_jsondict()[id.__class__.__name__] - oxm_ids.append(i) + for i in prop.oxm_ids: + oxm = i.to_jsondict()[i.__class__.__name__] + oxm_ids.append(oxm) p['oxm_ids'] = oxm_ids elif prop.type == p_type_packet: oxm_values = [] @@ -756,8 +755,7 @@ def get_group_features(dp, waiters, to_user=True): ofp.OFPAT_POP_PBB: 'POP_PBB', ofp.OFPAT_COPY_FIELD: 'COPY_FIELD', ofp.OFPAT_METER: 'METER', - ofp.OFPAT_EXPERIMENTER: 'EXPERIMENTER', - } + ofp.OFPAT_EXPERIMENTER: 'EXPERIMENTER'} stats = dp.ofproto_parser.OFPGroupFeaturesStatsRequest(dp, 0) msgs = [] diff --git a/ryu/lib/pack_utils.py b/ryu/lib/pack_utils.py index a84d14a7..e2afa7b4 100644 --- a/ryu/lib/pack_utils.py +++ b/ryu/lib/pack_utils.py @@ -18,13 +18,6 @@ import struct def msg_pack_into(fmt, buf, offset, *args): - if len(buf) < offset: - buf += bytearray(offset - len(buf)) - - if len(buf) == offset: - buf += struct.pack(fmt, *args) - return - needed_len = offset + struct.calcsize(fmt) if len(buf) < needed_len: buf += bytearray(needed_len - len(buf)) diff --git a/ryu/lib/port_no.py b/ryu/lib/port_no.py index 33720f3c..0eb65635 100644 --- a/ryu/lib/port_no.py +++ b/ryu/lib/port_no.py @@ -17,8 +17,7 @@ # string representation is in hex without '0x' _PORT_NO_LEN = 8 -_PORT_NO_LEN_STR = str(_PORT_NO_LEN) -_PORT_NO_FMT = '%0' + _PORT_NO_LEN_STR + 'x' +_PORT_NO_FMT = '%0{0}x'.format(_PORT_NO_LEN) PORT_NO_PATTERN = r'[0-9a-f]{%d}' % _PORT_NO_LEN diff --git a/ryu/lib/rpc.py b/ryu/lib/rpc.py index 57ba00c9..ed38f976 100644 --- a/ryu/lib/rpc.py +++ b/ryu/lib/rpc.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi # @@ -19,6 +17,9 @@ # msgpack-rpc # http://wiki.msgpack.org/display/MSGPACK/RPC+specification +from collections import deque +import select + import msgpack import six @@ -53,12 +54,12 @@ class MessageEncoder(object): assert isinstance(method, six.binary_type) assert isinstance(params, list) msgid = self._create_msgid() - return (self._packer.pack([MessageType.REQUEST, msgid, method, - params]), msgid) + return (self._packer.pack( + [MessageType.REQUEST, msgid, method, params]), msgid) def create_response(self, msgid, error=None, result=None): assert isinstance(msgid, int) - assert 0 <= msgid and msgid <= 0xffffffff + assert 0 <= msgid <= 0xffffffff assert error is None or result is None return self._packer.pack([MessageType.RESPONSE, msgid, error, result]) @@ -76,21 +77,18 @@ class MessageEncoder(object): for m in self._unpacker: self._dispatch_message(m, disp_table) - def _dispatch_message(self, m, disp_table): + @staticmethod + def _dispatch_message(m, disp_table): # XXX validation - type = m[0] + t = m[0] try: - f = disp_table[type] + f = disp_table[t] except KeyError: # ignore messages with unknown type return f(m[1:]) -from collections import deque -import select - - class EndPoint(object): """An endpoint *sock* is a socket-like. it can be either blocking or non-blocking. @@ -231,7 +229,7 @@ class EndPoint(object): except KeyError: return None error, result = m - return (result, error) + return result, error def get_notification(self): return self._get_message(self._notifications) @@ -241,6 +239,7 @@ class RPCError(Exception): """an error from server """ def __init__(self, error): + super(RPCError, self).__init__() self._error = error def get_value(self): diff --git a/ryu/lib/snortlib.py b/ryu/lib/snortlib.py index 803eb452..a8c1363e 100644 --- a/ryu/lib/snortlib.py +++ b/ryu/lib/snortlib.py @@ -40,6 +40,8 @@ class SnortLib(app_manager.RyuApp): self.name = 'snortlib' self.config = {'unixsock': True} self._set_logger() + self.sock = None + self.nwsock = None def set_config(self, config): assert isinstance(config, dict) diff --git a/ryu/lib/sockopt.py b/ryu/lib/sockopt.py index 6e533586..c3e9d1ad 100644 --- a/ryu/lib/sockopt.py +++ b/ryu/lib/sockopt.py @@ -21,6 +21,10 @@ import struct from ryu.lib import sockaddr +TCP_MD5SIG_LINUX = 0x0e +TCP_MD5SIG_BSD = 0x10 + + def _set_tcp_md5sig_linux(s, addr, key): # struct tcp_md5sig { # struct sockaddr_storage addr; @@ -29,7 +33,6 @@ def _set_tcp_md5sig_linux(s, addr, key): # u32 pad2; # u8 key[80]; # } - TCP_MD5SIG = 14 af = s.family if af == socket.AF_INET: sa = sockaddr.sa_in4(addr) @@ -39,14 +42,13 @@ def _set_tcp_md5sig_linux(s, addr, key): raise ValueError("unsupported af %s" % (af,)) ss = sockaddr.sa_to_ss(sa) tcp_md5sig = ss + struct.pack("2xH4x80s", len(key), key) - s.setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG, tcp_md5sig) + s.setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG_LINUX, tcp_md5sig) def _set_tcp_md5sig_bsd(s, _addr, _key): # NOTE: On this platform, address and key need to be set using setkey(8). - TCP_MD5SIG = 0x10 tcp_md5sig = struct.pack("I", 1) - s.setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG, tcp_md5sig) + s.setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG_BSD, tcp_md5sig) def set_tcp_md5sig(s, addr, key): diff --git a/ryu/lib/stplib.py b/ryu/lib/stplib.py index beb68e14..bb5bd6f0 100644 --- a/ryu/lib/stplib.py +++ b/ryu/lib/stplib.py @@ -191,7 +191,7 @@ class Stp(app_manager.RyuApp): self.bridge_list = {} def close(self): - for dpid in self.bridge_list.keys(): + for dpid in self.bridge_list: self._unregister_bridge(dpid) def _set_logger(self): @@ -480,12 +480,12 @@ class Bridge(object): pkt = packet.Packet(msg.data) if bpdu.ConfigurationBPDUs in pkt: - """ Receive Configuration BPDU. - - If receive superior BPDU: - re-caluculation of spanning tree. - - If receive Topology Change BPDU: - throw EventTopologyChange. - forward Topology Change BPDU. """ + # Received Configuration BPDU. + # - If received superior BPDU: + # Re-calculates spanning tree. + # - If received Topology Change BPDU: + # Throws EventTopologyChange. + # Forwards Topology Change BPDU. (bpdu_pkt, ) = pkt.get_protocols(bpdu.ConfigurationBPDUs) if bpdu_pkt.message_age > bpdu_pkt.max_age: log_msg = 'Drop BPDU packet which message_age exceeded.' @@ -506,24 +506,23 @@ class Bridge(object): self._forward_tc_bpdu(rcv_tc) elif bpdu.TopologyChangeNotificationBPDUs in pkt: - """ Receive Topology Change Notification BPDU. - send Topology Change Ack BPDU. - throw EventTopologyChange. - - Root bridge: - send Topology Change BPDU from all port. - - Non root bridge: - send Topology Change Notification BPDU to root bridge. """ + # Received Topology Change Notification BPDU. + # Send Topology Change Ack BPDU and throws EventTopologyChange. + # - Root bridge: + # Sends Topology Change BPDU from all port. + # - Non root bridge: + # Sends Topology Change Notification BPDU to root bridge. in_port.transmit_ack_bpdu() self.topology_change_notify(None) elif bpdu.RstBPDUs in pkt: - """ Receive Rst BPDU. """ + # Received Rst BPDU. # TODO: RSTP pass else: - """ Receive non BPDU packet. - throw EventPacketIn. """ + # Received non BPDU packet. + # Throws EventPacketIn. self.send_event(EventPacketIn(msg)) def recalculate_spanning_tree(self, init=True): @@ -544,7 +543,7 @@ class Bridge(object): if init: self.logger.info('Root bridge.', extra=self.dpid_str) - for port_no in self.ports.keys(): + for port_no in self.ports: port_roles[port_no] = DESIGNATED_PORT else: (port_roles, @@ -574,7 +573,7 @@ class Bridge(object): root_priority = self.root_priority root_times = self.root_times - for port_no in self.ports.keys(): + for port_no in self.ports: if self.ports[port_no].state is not PORT_STATE_DISABLE: port_roles[port_no] = DESIGNATED_PORT else: @@ -726,7 +725,7 @@ class Port(object): dp.ofproto.OFPPF_1GB_HD: bpdu.PORT_PATH_COST_1GB, dp.ofproto.OFPPF_1GB_FD: bpdu.PORT_PATH_COST_1GB, dp.ofproto.OFPPF_10GB_FD: bpdu.PORT_PATH_COST_10GB} - for rate in sorted(path_costs.keys(), reverse=True): + for rate in sorted(path_costs, reverse=True): if ofport.curr & rate: values['path_cost'] = path_costs[rate] break @@ -859,10 +858,10 @@ class Port(object): if new_state is not PORT_STATE_DISABLE: self.ofctl.set_port_status(self.ofport, new_state) - if(new_state is PORT_STATE_FORWARD or - (self.state is PORT_STATE_FORWARD and - (new_state is PORT_STATE_DISABLE or - new_state is PORT_STATE_BLOCK))): + if(new_state is PORT_STATE_FORWARD + or (self.state is PORT_STATE_FORWARD + and (new_state is PORT_STATE_DISABLE + or new_state is PORT_STATE_BLOCK))): self.topology_change_notify(new_state) if (new_state is PORT_STATE_DISABLE @@ -927,7 +926,7 @@ class Port(object): or self.role is NON_DESIGNATED_PORT)): self._update_wait_bpdu_timer() chk_flg = True - elif(rcv_info is INFERIOR and self.role is DESIGNATED_PORT): + elif rcv_info is INFERIOR and self.role is DESIGNATED_PORT: chk_flg = True # Check TopologyChange flag. diff --git a/ryu/lib/stringify.py b/ryu/lib/stringify.py index 21b0d9de..81eb6178 100644 --- a/ryu/lib/stringify.py +++ b/ryu/lib/stringify.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi # @@ -19,7 +17,6 @@ from __future__ import print_function import base64 -import collections import inspect import six @@ -104,7 +101,7 @@ class NXFlowSpecFieldType(TypeDescr): if not isinstance(v, list): return v field, ofs = v - return (field, ofs) + return field, ofs _types = { @@ -126,7 +123,7 @@ class StringifyMixin(object): Currently the following types are implemented. ========= ============= - Type Descrption + Type Description ========= ============= ascii US-ASCII utf-8 UTF-8 @@ -162,7 +159,7 @@ class StringifyMixin(object): def _is_class(cls, dict_): # we distinguish a dict like OFPSwitchFeatures.ports # from OFPxxx classes using heuristics. - # exmples of OFP classes: + # Examples of OFP classes: # {"OFPMatch": { ... }} # {"MTIPv6SRC": { ... }} assert isinstance(dict_, dict) @@ -208,7 +205,7 @@ class StringifyMixin(object): if six.PY3: json_value = json_value.decode('ascii') elif isinstance(v, list): - json_value = list(map(_encode, v)) + json_value = [_encode(ve) for ve in v] elif isinstance(v, dict): json_value = _mapdict(_encode, v) # while a python dict key can be any hashable object, @@ -218,7 +215,7 @@ class StringifyMixin(object): else: try: json_value = v.to_jsondict() - except: + except Exception: json_value = v return json_value return _encode @@ -253,7 +250,7 @@ class StringifyMixin(object): ============= ===================================================== """ dict_ = {} - encode = lambda k, x: self._encode_value(k, x, encode_string) + encode = lambda key, val: self._encode_value(key, val, encode_string) for k, v in obj_attrs(self): dict_[k] = encode(k, v) return {self.__class__.__name__: dict_} @@ -282,6 +279,8 @@ class StringifyMixin(object): @classmethod def _decode_value(cls, k, json_value, decode_string=base64.b64decode, **additional_args): + # Note: To avoid passing redundant arguments (e.g. 'datapath' for + # non OFP classes), we omit '**additional_args' here. return cls._get_decoder(k, decode_string)(json_value) @classmethod @@ -290,13 +289,13 @@ class StringifyMixin(object): if isinstance(json_value, (bytes, six.text_type)): v = decode_string(json_value) elif isinstance(json_value, list): - v = list(map(_decode, json_value)) + v = [_decode(jv) for jv in json_value] elif isinstance(json_value, dict): if cls._is_class(json_value): v = cls.obj_from_jsondict(json_value, **additional_args) else: v = _mapdict(_decode, json_value) - # XXXhack + # XXX: Hack # try to restore integer keys used by # OFPSwitchFeatures.ports. try: @@ -386,11 +385,11 @@ def obj_attrs(msg_): """ if isinstance(msg_, StringifyMixin): - iter = msg_.stringify_attrs() + itr = msg_.stringify_attrs() else: # probably called by msg_str_attr - iter = obj_python_attrs(msg_) - for k, v in iter: + itr = obj_python_attrs(msg_) + for k, v in itr: if k.endswith('_') and k[:-1] in _RESERVED_KEYWORD: # XXX currently only StringifyMixin has restoring logic assert isinstance(msg_, StringifyMixin) diff --git a/ryu/lib/type_desc.py b/ryu/lib/type_desc.py index 3f158fc2..eca80137 100644 --- a/ryu/lib/type_desc.py +++ b/ryu/lib/type_desc.py @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import base64 import six @@ -28,20 +29,20 @@ class IntDescr(TypeDescr): def __init__(self, size): self.size = size - def to_user(self, bin): + def to_user(self, binary): i = 0 - for x in range(self.size): - c = bin[:1] + for _ in range(self.size): + c = binary[:1] i = i * 256 + ord(c) - bin = bin[1:] + binary = binary[1:] return i def from_user(self, i): - bin = b'' - for x in range(self.size): - bin = six.int2byte(i & 255) + bin + binary = b'' + for _ in range(self.size): + binary = six.int2byte(i & 255) + binary i //= 256 - return bin + return binary Int1 = IntDescr(1) Int2 = IntDescr(2) @@ -65,13 +66,13 @@ class IntDescrMlt(TypeDescr): self.num = num self.size = length * num - def to_user(self, bin): - assert len(bin) == self.size - lb = _split_str(bin, self.length) + def to_user(self, binary): + assert len(binary) == self.size + lb = _split_str(binary, self.length) li = [] for b in lb: i = 0 - for x in range(self.length): + for _ in range(self.length): c = b[:1] i = i * 256 + ord(c) b = b[1:] @@ -80,14 +81,14 @@ class IntDescrMlt(TypeDescr): def from_user(self, li): assert len(li) == self.num - bin = b'' + binary = b'' for i in li: b = b'' - for x in range(self.length): + for _ in range(self.length): b = six.int2byte(i & 255) + b i //= 256 - bin += b - return bin + binary += b + return binary Int4Double = IntDescrMlt(4, 2) @@ -111,13 +112,12 @@ class IPv6Addr(TypeDescr): class UnknownType(TypeDescr): - import base64 - b64encode = base64.b64encode - if six.PY3: - @classmethod - def to_user(cls, data): - return cls.b64encode(data).decode('ascii') - else: - to_user = staticmethod(base64.b64encode) + @staticmethod + def to_user(data): + if six.PY3: + return base64.b64encode(data).decode('ascii') + else: + return base64.b64encode(data) + from_user = staticmethod(base64.b64decode)