Example #1
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        print "OVS addres is " + str(ovsdb_addr)
        _proto, _host, _port = ovsdb_addr.split(':')

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        if ovsdb_addr is None:
            if self.ovs_bridge:
                self.ovs_bridge.del_controller()
                self.ovs_bridge = None
            return
        self.ovsdb_addr = ovsdb_addr
        if self.ovs_bridge is None:
            print "OVS bridge DPID is " + str(dpid)
            print "OVS address is " + ovsdb_addr
            ovs_bridge = bridge.OVSBridge(self.CONF, dpid, ovsdb_addr)
            self.ovs_bridge = ovs_bridge
            print "OVS bridge is " + str(ovs_bridge)
            try:
                ovs_bridge.init()
            except:
                raise ValueError('ovsdb addr is not available. DPID: ' +
                                 str(dpid))
Example #2
0
    def apply_qos(self, dpid):
      
        self.logger.info("function called with: dpid %s port speed %s", dpid, self.PORT_SPEED)
        ovs_bridge = bridge.OVSBridge(CONF=self.CONF, datapath_id=dpid,
                                      ovsdb_addr=OVSDB_ADDR)
        try:
            ovs_bridge.init()
        except:
            raise ValueError('address not availble')
 
        names = ovs_bridge.get_port_name_list()
        for name in names:
            port_id = ovs_bridge.get_ofport(name)

            if dpid in left_ports:
                if port_id in left_ports[dpid]:
                    continue

            self.logger.info("queue lists formed at a port %s", self.queue_list)
            result = ovs_bridge.set_qos(name, type='linux-htb',
                                        max_rate=str(self.PORT_SPEED),
                                        queue_list=self.queue_list)
            self.logger.info("ouput obtained %s ", result)
            self.logger.info("values applied to switch %s,  port %s queue %s ", dpid, name, self.queue_list)
        return
Example #3
0
 def init_bridge(self, remote_addr):
     print('init_bridge')
     host_ovsdb = HostOvsdb(remote_addr)
     br = bridge.OVSBridge(CONF=conf,
                           datapath_id=None,
                           ovsdb_addr=host_ovsdb.ovsdb_addr)
     br.br_name = host_ovsdb.br_name
     # TODO:判断是否设置 ovs-vsctl set-manager "ptcp:6640"
     command1 = vsctl.VSCtlCommand(command='br-exists',
                                   args=[host_ovsdb.br_name])
     br.run_command([command1])
     if not command1.result:
         command2 = vsctl.VSCtlCommand(command='add-br',
                                       args=[host_ovsdb.br_name])
         command3 = vsctl.VSCtlCommand(
             command='set',
             args=['Bridge', host_ovsdb.br_name, 'protocols=OpenFlow13'])
         br.run_command([command2])
         br.run_command([command3])
     host_ovsdb.dpid = int(br.get_datapath_id()[0], 16)
     # host_ovsdb.dpid = br.get_datapath_id()[0]
     br.set_controller(["tcp:%s:6633" % server_addr])
     if host_ovsdb.tunnel_port_name not in br.get_port_name_list():
         br.add_vxlan_port(conf.tunnel_port,
                           remote_ip='flow',
                           local_ip='flow',
                           key='flow')
     host_ovsdb.tunnel_port_id = br.get_ofport(conf.tunnel_port)
     self.db.update_ovsdb(host_ovsdb)
     while not dpid_datapath_dict.setdefault(host_ovsdb.dpid, None):
         print('conneting controller')
         time.sleep(1)
     return host_ovsdb.br_name
Example #4
0
    def _port_setup(self, dp, port_no, tunnel_key):
        if _is_reserved_port(dp, port_no):
            return

        dpid = dp.id
        try:
            port = self.dpset.get_port(dpid, port_no)
        except ryu_exc.PortNotFound:
            self.logger.debug('port not found')
            return

        try:
            ovsdb_addr = self.conf_sw.get_key(dpid, conf_switch_key.OVSDB_ADDR)
        except KeyError:
            self.logger.debug('ovsdb_addr not found')
            return

        self._port_flow_add(dp, port_no)

        self.logger.debug('ovs_port_update dpid %s port_no %s', dpid, port_no)
        # ovs-vsctl --db=ovsdb_addr --timeout=2
        # set Port port.name tag=tunnel_key
        ovs_br = bridge.OVSBridge(dpid, ovsdb_addr, 2)
        # ofp_phy_port::name is zero-padded
        port_name = port.name.rstrip('\x00')
        try:
            ovs_br.set_db_attribute("Port", port_name, "tag", tunnel_key)
        except hub.Timeout:
            self.logger.error('timeout')
            return

        return True
Example #5
0
    def _get_ovs_bridge(self, dpid):
        datapath = self._get_datapath(dpid)
        if datapath is None:
            self.logger.debug('No such datapath: %s', dpid)
            return None

        ovs = self.ovs.get(dpid, None)
        ovsdb_addr = 'tcp:%s:%d' % (datapath.address[0], OVSDB_PORT)

        if (ovs is not None and ovs.datapath_id == dpid
                and ovs.vsctl.remote == ovsdb_addr):
            return ovs

        self.logger.info("Connecting to %s", ovsdb_addr)

        try:
            ovs = ovs_bridge.OVSBridge(CONF=self.CONF,
                                       datapath_id=datapath.id,
                                       ovsdb_addr=ovsdb_addr)
            ovs.init()
            self.ovs[dpid] = ovs
            return ovs
        except Exception as e:
            self.logger.exception('Cannot initiate OVSDB connection: %s', e)
            return None
Example #6
0
    def delete_port(self, req, **kwargs):
        port = kwargs['port']
        remote_addr = req.environ['REMOTE_ADDR']
        server_name = req.environ['SERVER_NAME']
        host_ovsdb = ip_host_ovsdb_dict.setdefault(remote_addr, None)
        if host_ovsdb is None:
            return ResponseErrorNoPort()
        else:
            br = bridge.OVSBridge(CONF=conf,
                                  datapath_id=host_ovsdb.dpid,
                                  ovsdb_addr=host_ovsdb.ovsdb_addr)
            br.init()
        t_mes = tunnel_message_dict.setdefault(port)
        if t_mes is None:
            return ResponseErrorNoPort()
        datapath = self.simple_switch_app.switches.get(host_ovsdb.dpid)
        if datapath is not None:
            parser = datapath.ofproto_parser
            actions = []
            match1 = parser.OFPMatch(in_port=t_mes.port_id)
            del_flow(datapath, 3, match1, actions)

            match2 = parser.OFPMatch(tunnel_id=t_mes.tunnel_id)
            del_flow(datapath, 3, match2, actions)
        return ResponseSuccess()
Example #7
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        self.logger.debug('set_ovsdb_addr dpid %s ovsdb_addr %s',
                          dpid_lib.dpid_to_str(dpid), ovsdb_addr)
        _proto, _host, _port = ovsdb_addr.split(':')

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        if ovsdb_addr is None:
            # TODO: clean up this ovs switch
            if self.ovs_bridge:
                self.ovs_bridge.del_controller()
                self.ovs_bridge = None
            return
        self.ovsdb_addr = ovsdb_addr
        if self.ovs_bridge is None:
            self.logger.debug('ovsdb: adding ports %s', self.ports)
            ovs_bridge = bridge.OVSBridge(dpid, ovsdb_addr)
            self.ovs_bridge = ovs_bridge
            ovs_bridge.init()
            # TODO: for multi-controller
            #       not overwrite controllers, but append this controller
            ovs_bridge.set_controller([self.ctrl_addr])
            for port in self.ports.values():
                self.logger.debug('adding port %s', port)
                self.update_port(port.ofport, port.name, True)
Example #8
0
    def tunnel_create(self, dpid, params):
        ovsdb = params['tnrm']['ovsdb']
        remote_ip = params['tnrm']['remote_ip']
        local_ip = params['tnrm']['local_ip']
        tunnel_type = params['tnrm']['type']
        tunnel_name = params['tnrm']['name']

        id = int(dpid, 16)
        ovs_bridge = bridge.OVSBridge(bridge.CONF, id, ovsdb)

        try:
            ovs_bridge.init()
            ovs_bridge.add_tunnel_port(tunnel_name, tunnel_type, local_ip,
                                       remote_ip)
            tp = ovs_bridge.get_tunnel_port(tunnel_name, tunnel_type)
        except:
            raise

        output = {
            'id': '%d' % id,
            'tnrm': {
                'tunnel': {
                    'name': '%s' % tp.port_name,
                    'ofport': '%s' % tp.ofport,
                    'type': '%s' % tp.tunnel_type,
                    'local_ip': '%s' % tp.local_ip,
                    'remote_ip': '%s' % tp.remote_ip
                }
            }
        }
        return output
Example #9
0
    def apply_qos(self, dpid):
        '''
        Logic:
        1. Establish the communication with ovsdb using RYU ovsbridge library
        2. Apply the Queuing in all the ports
        '''
        self.logger.info("apply_qos called with: dpid %s portspeed %s", dpid, self.PORT_SPEED)
        ovs_bridge = bridge.OVSBridge(CONF=self.CONF, datapath_id=dpid,
                                      ovsdb_addr=OVSDB_ADDR)
        try:
            ovs_bridge.init()
        except:
            raise ValueError('ovsdb addr is not available.')

        # find port name 
        names = ovs_bridge.get_port_name_list()
        for name in names:
            port_id = ovs_bridge.get_ofport(name)

            if dpid in QUEUE_IGNORE_LIST:
                if port_id in QUEUE_IGNORE_LIST[dpid]:
                    continue

            self.logger.info("queues %s", self.queues)
            result = ovs_bridge.set_qos(name, type='linux-htb',
                                        max_rate=str(self.PORT_SPEED),
                                        queues=self.queues)
            self.logger.info("ouput %s ", result)
            self.logger.info("Applied the Qos switch %s,  port %s queue %s ", dpid, name, self.queues)
        return
Example #10
0
 def __init__(self, datapath_id, CONF=RyuConfMock):
     ovsdb_addr = "tcp:%s:%d" % ("127.0.0.1", OVSDB_PORT)
     self.datapath_id = datapath_id
     self.ovs = ovs_bridge.OVSBridge(CONF=CONF,
                                     datapath_id=datapath_id,
                                     ovsdb_addr=ovsdb_addr)
     self._lock = threading.Lock()
     self._bridge_mac = None
Example #11
0
    def set_queue(self, rest, switch_id, vlan_id):
        if self.ovs_bridge is None:
            ovs_bridge = bridge.OVSBridge(self.CONF, switch_id, OVSDB_ADDR)
            #ovs_vsctl = vsctl.VSCtl(OVSDB_ADDR) #set OVSDB_ADDR
            self.ovs_bridge = ovs_bridge
            try:
                ovs_bridge.init()
            except:
                raise ValueError(
                    'Unable to set ovs_bridge in set_queue method')
            #msg = {'result': 'fail',
            #       'msg' : self.ovs_bridge,
            #       'details': 'ovs_bridge not created'}
            #return REST_COMMAND_RESULT, msg

        self.queue_list.clear()
        queue_type = rest.get(REST_QUEUE_TYPE, 'linux-htb')
        parent_max_rate = rest.get(REST_QUEUE_MAX_RATE, None)
        queues = rest.get(REST_QUEUES, [])
        queue_id = 0
        queue_config = []
        for queue in queues:
            max_rate = queue.get(REST_QUEUE_MAX_RATE, None)
            min_rate = queue.get(REST_QUEUE_MIN_RATE, None)
            if max_rate is None and min_rate is None:
                raise ValueError('Required to specify max_rate or min_rate')
            config = {}
            if max_rate is not None:
                config['max-rate'] = max_rate
            if min_rate is not None:
                config['min-rate'] = min_rate
            if len(config):
                queue_config.append(config)
            self.queue_list[queue_id] = {'config': config}
            queue_id += 1

        port_name = rest.get(REST_PORT_NAME, None)
        vif_ports = self.ovs_bridge.get_port_name_list()

        if port_name is not None:
            if port_name not in vif_ports:
                raise ValueError('%s port does not exist' % port_name)
            vif_ports = [port_name]

        for port_name in vif_ports:
            try:
                self.ovs_bridge.set_qos(port_name,
                                        type=queue_type,
                                        max_rate=parent_max_rate,
                                        queues=queue_config)
            except Exception as msg:
                raise ValueError(msg)

        msg = {'result': 'success', 'details': self.queue_list}

        return REST_COMMAND_RESULT, msg
Example #12
0
    def put_port(self, req, **kwargs):
        simple_switch = self.simple_switch_app
        port = kwargs['port']
        try:
            new_entry = req.json if req.body else {}
            t_mes_old = tunnel_message_dict.setdefault(port)
            if t_mes_old is None:
                return ResponseErrorNoPort()
            t_mes = TunnelMessage(new_entry)
            remote_addr = req.environ['REMOTE_ADDR']
            host_ovsdb = self.db.get_ovsdb(remote_addr)
            if host_ovsdb is None:
                return ResponseErrorNoInit()
            else:
                br = bridge.OVSBridge(CONF=conf,
                                      datapath_id=host_ovsdb.dpid,
                                      ovsdb_addr=host_ovsdb.ovsdb_addr)
                br.init()
            if port not in br.get_port_name_list():
                return ResponseErrorNoPort()
            t_mes.port_id = br.get_ofport(t_mes.port_name)
            tunnel_message_dict[t_mes.port_name] = t_mes
            datapath = simple_switch.switches_datapath.get(host_ovsdb.dpid)

            if datapath is not None:
                parser = datapath.ofproto_parser
                # ofproto = datapath.ofproto
                action1 = [
                    parser.NXActionSetTunnel(tun_id=t_mes.tunnel_id),
                    # OFPAT_SET_FIELD
                    parser.OFPActionSetField(tun_ipv4_dst=t_mes.remote_ip),
                ]
                if t_mes.local_ip:
                    action1.append(
                        parser.OFPActionSetField(tun_ipv4_src=t_mes.local_ip))
                action1.append(
                    parser.OFPActionOutput(host_ovsdb.tunnel_port_id))
                match = parser.OFPMatch(in_port=t_mes.port_id)
                mod_flow(datapath, 3, match, action1)

                match2 = parser.OFPMatch(tunnel_id=t_mes_old.tunnel_id)
                del_flow(datapath, 3, match2, [])

                actions2 = [parser.OFPActionOutput(t_mes.port_id)]
                match2 = parser.OFPMatch(in_port=host_ovsdb.tunnel_port_id,
                                         tunnel_id=t_mes.tunnel_id)
                add_flow(datapath, 3, match2, actions2)

            else:
                raise Exception("no depapath")
        except Exception as e:
            return ResponseErrorPortBase(msg=str(e))
        else:
            return ResponseSuccess()
Example #13
0
    def post_port(self, req, **kwargs):
        port = kwargs['port']
        remote_addr = req.environ['REMOTE_ADDR']
        try:
            host_ovsdb = self.db.get_ovsdb(remote_addr)
            if host_ovsdb is None:
                return ResponseErrorNoInit()
            else:
                br = bridge.OVSBridge(CONF=conf,
                                      datapath_id=host_ovsdb.dpid,
                                      ovsdb_addr=host_ovsdb.ovsdb_addr)
                br.init()
            if port not in br.get_port_name_list():
                return ResponseErrorNoPort()
            new_entry = req.json if req.body else {}
            new_entry['IP'] = remote_addr
            t_mes = TunnelPort(new_entry)
            t_mes.port_id = br.get_ofport(t_mes.port_name)
            if t_mes.port_id == -1:
                return ResponseErrorNoPort()
            self.db.update_tunnel_port(t_mes)
            datapath = dpid_datapath_dict[br.datapath_id]
            if datapath is not None:
                parser = datapath.ofproto_parser
                # ofproto = datapath.ofproto
                actions = [
                    parser.NXActionSetTunnel(tun_id=t_mes.tunnel_id),
                    # OFPAT_SET_FIELD
                    parser.OFPActionSetField(tun_ipv4_dst=t_mes.remote_ip),
                ]
                if t_mes.local_ip:
                    actions.append(
                        parser.OFPActionSetField(tun_ipv4_src=t_mes.local_ip))
                actions.append(
                    parser.OFPActionOutput(host_ovsdb.tunnel_port_id))
                match = parser.OFPMatch(in_port=t_mes.port_id)
                add_flow(datapath, 3, match, actions)

                actions2 = [parser.OFPActionOutput(t_mes.port_id)]
                match2 = parser.OFPMatch(in_port=host_ovsdb.tunnel_port_id,
                                         tunnel_id=t_mes.tunnel_id)
                add_flow(datapath, 3, match2, actions2)
            else:
                return ResponseErrorPortBase(msg='no datapath %s ' %
                                             host_ovsdb.dpid)
        except Exception as e:
            traceback.print_exc(limit=10, file=sys.stdout)
            return ResponseErrorPortBase(msg=str(e))
        else:
            return ResponseSuccess()
Example #14
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        elif ovsdb_addr is None:
            # Determine deleting OVSDB address was requested.
            if self.ovs_bridge:
                self.ovs_bridge = None
            return

        ovs_bridge = bridge.OVSBridge(self.CONF, dpid, ovsdb_addr)
        try:
            ovs_bridge.init()
        except:
            raise ValueError('ovsdb addr is not available.')
        self.ovsdb_addr = ovsdb_addr
        self.ovs_bridge = ovs_bridge
Example #15
0
    def get_ovs_bridge(cls, datapath):
        dpid = datapath.id
        ovsdb_addr = 'tcp:%s:%d' % (datapath.address[0], cls.OVSDB_PORT)

        if (cls.ovs is not None and cls.ovs.datapath_id == dpid
                and cls.ovs.vsctl.remote == ovsdb_addr):
            return cls.ovs

        try:
            cls.ovs = bridge.OVSBridge(CONF=cls.CONF,
                                       datapath_id=dpid,
                                       ovsdb_addr=ovsdb_addr)
            cls.ovs.init()
        except (ValueError, KeyError) as e:
            logging.warning('Cannot initiate OVSDB connection: %s', e)
            return None
        return cls.ovs
Example #16
0
    def list_ports(self, dpid, params):
        ovsdb = params['tnrm']['ovsdb']

        id = int(dpid, 16)
        print "id=%d" % id
        ovs_bridge = bridge.OVSBridge(bridge.CONF, id, ovsdb)

        ovs_bridge.init()
        ports = ovs_bridge.get_port_name_list()
        # results = []
        results = {}
        for p in ports:
            ofport = ovs_bridge.get_ofport(p)
            # print "ports=%s ofport=%d" % (p, ofport)
            result = {'port': '%s' % p, 'ofport': '%d' % ofport}
            # results.append(result)
            results[p] = str(ofport)

        return ({'id': '%s' % id, 'tnrm': {'ports': results}})
Example #17
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        _proto, _host, _port = ovsdb_addr.split(':')

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        elif ovsdb_addr is None:
            # Determine deleting OVSDB address was requested.
            if self.ovs_bridge:
                self.ovs_bridge = None
            return
        ovs_bridge = bridge.OVSBridge(self.CONF, dpid, ovsdb_addr)
        try:
            ovs_bridge.init()
        except:
            raise ValueError('ovsdb addr is not available.')
        self.ovsdb_addr = ovsdb_addr
        self.ovs_bridge = ovs_bridge
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        _proto, _host, _port = ovsdb_addr.split(':')

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        if ovsdb_addr is None:
            if self.ovs_bridge:
                self.ovs_bridge.del_controller()
                self.ovs_bridge = None
            return
        self.ovsdb_addr = ovsdb_addr
        if self.ovs_bridge is None:
            ovs_bridge = bridge.OVSBridge(self.CONF, dpid, ovsdb_addr)
            self.ovs_bridge = ovs_bridge
            try:
                ovs_bridge.init()
            except:
                raise ValueError('ovsdb addr is not available.')
Example #19
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        _proto, _host, _port = ovsdb_addr.split(':')

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        if ovsdb_addr is None:
            if self.ovs_bridge:
                self.ovs_bridge.del_controller()
                self.ovs_bridge = None
            return
        self.ovsdb_addr = ovsdb_addr
        if self.ovs_bridge is None:
            ovs_bridge = bridge.OVSBridge(self.CONF, dpid, ovsdb_addr)
            self.ovs_bridge = ovs_bridge
            try:
                ovs_bridge.init()
            except Exception as e:
                logging.exception("ovs_bridge init failed: %s")
Example #20
0
    def __init__(self, CONF, dpid, ovsdb_addr, tunnel_ip, tunnel_type,
                 conf_switch_, network_api, tunnel_api, logger):
        super(TunnelDP, self).__init__()
        self.dpid = dpid
        self.network_api = network_api
        self.tunnel_api = tunnel_api
        self.logger = logger

        self.ovs_bridge = ovs_bridge.OVSBridge(CONF, dpid, ovsdb_addr)

        self.tunnel_ip = tunnel_ip
        self.tunnel_type = tunnel_type
        self.tunnel_nw_id = _TUNNEL_TYPE_TO_NW_ID[tunnel_type]
        self.tunnels = {}  # port number -> TunnelPort

        self.conf_switch = conf_switch_
        self.inited = False

        self.req_q = hub.Queue()
        self.thr = hub.spawn(self._serve_loop)
Example #21
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        LOG.info("OVSDB_ADDR %r ", ovsdb_addr)
        _proto, _host, _port = ovsdb_addr.split(':')

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        if ovsdb_addr is None:
            if self.ovs_bridge:
                self.ovs_bridge.del_controller()
                self.ovs_bridge = None
            return
        self.ovsdb_addr = OVSDB_ADDR
        if self.ovs_bridge is None:
            ovs_bridge = bridge.OVSBridge(self.CONF, dpid, OVSDB_ADDR)
            #ovs_vsctl = vsctl.VSCtl(OVSDB_ADDR) #set OVSDB_ADDR
            self.ovs_bridge = ovs_bridge
            try:
                ovs_bridge.init()
            except:
                raise ValueError('ovsdb addr is not available.')
Example #22
0
    def _get_ovs_bridge(self):
        datapath = self._get_datapath()
        if datapath['err']:
            self.logger.debug(datapath['err'])
            return None
        dpid = to_int(datapath['out'], 16)

        ovsdb_addr = 'tcp:%s:%d' % (DATAPATH_ADDR, OVSDB_PORT)
        if (self.ovs is not None and self.ovs.datapath_id == dpid
                and self.ovs.vsctl.remote == ovsdb_addr):
            return self.ovs

        try:
            self.ovs = ovs_bridge.OVSBridge(CONF=self.CONF,
                                            datapath_id=dpid,
                                            ovsdb_addr=ovsdb_addr)
            self.ovs.init()
        except Exception as e:
            self.logger.exception('Cannot initiate OVSDB connection: %s', e)
            return None

        return self.ovs
Example #23
0
from my_tunnelflow.orm_data import HostOvsdb
from my_tunnelflow.orm_data import TunnelMessage
from my_tunnelflow.global_data import ip_host_ovsdb_dict
from my_tunnelflow.global_data import tunnel_message_dict

opts = [
    cfg.StrOpt('tunnel_bridge', default='ovs', help='tunnel_bridge'),
    cfg.StrOpt('tunnel_port',
               default='tunnel_port',
               help='"protocols" option for ovs-vsctl (e.g. OpenFlow13)'),
    cfg.IntOpt('ovsdb_timeout', default=5, help='timeout ')
]
conf = cfg.ConfigOpts()
conf.register_cli_opts(opts)

host_ovsdb = HostOvsdb('192.168.125.149')
br = bridge.OVSBridge(CONF=conf,
                      datapath_id=None,
                      ovsdb_addr=host_ovsdb.ovsdb_addr)
br.br_name = host_ovsdb.br_name
# TODO:判断是否设置 ovs-vsctl set-manager "ptcp:6640"
command1 = vsctl.VSCtlCommand(command='br-exists', args=[host_ovsdb.br_name])
br.run_command([command1])
if not command1.result:
    command2 = vsctl.VSCtlCommand(command='add-br', args=[host_ovsdb.br_name])
    command3 = vsctl.VSCtlCommand(
        command='set',
        args=['Bridge', host_ovsdb.br_name, 'protocols=OpenFlow13'])
    br.run_command([command2])
    br.run_command([command3])
Example #24
0
 def del_port(self, ovsdb, dpid, name):
     id = int(dpid, 16)
     ovs_bridge = bridge.OVSBridge(bridge.CONF, id, ovsdb)
     ovs_bridge.init()
     ovs_bridge.del_port(name)
Example #25
0
    def reset(self):
        self.L4=[]
        self.L5=[]
        self.Content=[]
        datapath = self.ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser


        empty_match = parser.OFPMatch()
        instructions = []
        flow_mod = self.remove_table_flows(datapath, 0,empty_match, instructions)
        self.logger.info("deleting all flow entries in table")
        datapath.send_msg(flow_mod)
        
        #command = vsctl.VSCtlCommand("set",("port"))
        #self.ovs_vsctl.run_command([command])
        #print(command)
        self.ovs_bridge = bridge.OVSBridge(self.CONF,datapath.id,self.ovsdb_addr)
        try:
            self.ovs_bridge.init()
            self.logger.info("OVSBridge success")
        except:
            self.logger.info("OVSBridge fail")
            return
        
        vif_ports = self.ovs_bridge.get_port_name_list()
        
        f = open("config.ini","r")

        line = f.readline()
        self.mode = int(line)    #mode: 1-Layer4; 2-Layer5; 3-Content
        #self.logger.info(line)
        if self.mode == 1:
            self.logger.info("Layer 4 mode")
            '''
            line = f.readline()
            parameters = line.split(' ')
            self.L4.append(int(parameters[0]))
            maxRate = int(parameters[1])
            minRate = int(parameters[2])
            
            queue_config=[]
            config={}
            config['max-rate']=str(maxRate)
            config['min-rate']=str(minRate)
            queue_config.append(config)

            line = f.readline()
            parameters = line.split(' ')
            '''
            queue_config=[]
            while True:
                line = f.readline()
                parameters = line.split(' ')
                if len(parameters) != 3:
                    #print(parameters)
                    break
                self.L4.append(int(parameters[0]))
                maxRate = int(parameters[1])
                minRate = int(parameters[2])

                config={}
                config['max-rate']=str(maxRate)
                config['min-rate']=str(minRate)
                queue_config.append(config)

            maxRate = int(parameters[0])
            minRate = int(parameters[1])


            config={}
            config['max-rate']=str(maxRate)
            config['min-rate']=str(minRate)
            queue_config.append(config)

            for port_name in vif_ports:
                self.logger.info("Set QoS to port %s",port_name)
                try:
                    self.ovs_bridge.set_qos(port_name,type='linux-htb',queues=queue_config)
                    self.logger.info("QoS success")
                except:
                    self.logger.info("QoS fail")
        


        
        elif self.mode == 2:
            self.logger.info("Layer 5 mode")
            queue_config=[]
            while True:
                line = f.readline()
                parameters = line.split(' ')
                #print(parameters)
                if len(parameters) != 4:
                    #print(parameters)
                    break
                self.L5.append((int(parameters[0]),int(parameters[1])))
                maxRate = int(parameters[2])
                minRate = int(parameters[3])

                config={}
                config['max-rate']=str(maxRate)
                config['min-rate']=str(minRate)
                queue_config.append(config)
                        
            maxRate = int(parameters[0])
            minRate = int(parameters[1])
    
            config={}
            config['max-rate']=str(maxRate)
            config['min-rate']=str(minRate)
            queue_config.append(config)           


            for port_name in vif_ports:
                self.logger.info("Set QoS to port %s",port_name)
                try:
                    self.ovs_bridge.set_qos(port_name,type='linux-htb',queues=queue_config)
                    self.logger.info("QoS success")
                except:
                    self.logger.info("QoS fail")
        elif self.mode == 3:
            self.logger.info("Content mode")
            queue_config=[]
            while True:
                line = f.readline()
                parameters = line.split(' ')
                #print(parameters)
                if len(parameters) != 3:
                    #print(parameters)
                    break
                self.Content.append(int(parameters[0]))
                maxRate = int(parameters[1])
                minRate = int(parameters[2])

                config={}
                config['max-rate']=str(maxRate)
                config['min-rate']=str(minRate)
                queue_config.append(config)
                        
            maxRate = int(parameters[0])
            minRate = int(parameters[1])
    
            config={}
            config['max-rate']=str(maxRate)
            config['min-rate']=str(minRate)
            queue_config.append(config)           
            

            for port_name in vif_ports:
                self.logger.info("Set QoS to port %s",port_name)
                try:
                    self.ovs_bridge.set_qos(port_name,type='linux-htb',queues=queue_config)
                    self.logger.info("QoS success")
                except:
                    self.logger.info("QoS fail")

               
        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)
Example #26
0
conf = cfg.ConfigOpts()
conf.register_cli_opts(opts)

OVSDB_ADDR = 'tcp:192.168.83.132:6640'
ret = vsctl.valid_ovsdb_addr(OVSDB_ADDR)
ovs_vsctl = vsctl.VSCtl(OVSDB_ADDR)
# command1 = vsctl.VSCtlCommand(command='br-exists', args=['br0'])
# command2 = vsctl.VSCtlCommand(command='add-br', args=['br0'], options='--may-exist')
#
# ovs_vsctl.run_command([command2])
# print(command2.result)

#ovs_vsctl.run_command([command2])
#print(command2.result)
# print(command3.result)

br = bridge.OVSBridge(CONF=conf, datapath_id=None, ovsdb_addr=OVSDB_ADDR)
br.br_name = 's1'
ret = br.get_datapath_id()
print(ret)
br.add_tunnel_port(name="p1",
                   tunnel_type="vxlan",
                   remote_ip="1.1.1.1",
                   key='flow',
                   ofport=1)

br.add_tunnel_port(name="p2",
                   tunnel_type="vxlan",
                   remote_ip="1.1.1.2",
                   key='flow',
                   ofport=10)