예제 #1
0
    def commit(self, tid=None, transaction=None, rollback=False):
        self._load_event.clear()
        error = None

        if tid:
            transaction = self._transactions[tid]
        else:
            transaction = transaction or self.last()

        # create a new route
        if not self._exists:
            try:
                self.nl.route('add', **IPRouteRequest(self))
            except Exception:
                self.nl = None
                self.ipdb.routes.remove(self)
                raise

        # work on existing route
        snapshot = self.pick()
        try:
            # route set
            request = IPRouteRequest(transaction - snapshot)
            if any([request[x] not in (None, {'attrs': []}) for x in request]):
                self.nl.route('set', **IPRouteRequest(transaction))

            if transaction.get('removal'):
                self.nl.route('delete', **IPRouteRequest(snapshot))

        except Exception as e:
            if not rollback:
                ret = self.commit(transaction=snapshot, rollback=True)
                if isinstance(ret, Exception):
                    error = ret
                else:
                    error = e
            else:
                self.drop()
                x = RuntimeError()
                x.cause = e
                raise x

        if not rollback:
            self.drop()
            self.reload()

        if error is not None:
            error.transaction = transaction
            raise error

        return self
예제 #2
0
파일: routes.py 프로젝트: smurfix/pyroute2
 def __init__(self, route):
     dict.__init__(self, [x for x in IPRouteRequest(route).items()
                          if x[0] in ('dst',
                                      'dst_len',
                                      'src',
                                      'src_len',
                                      'tos',
                                      'priority',
                                      'gateway',
                                      'table') and x[1]])
예제 #3
0
 def test_route_multipath_helper(self):
     require_user('root')
     req = IPRouteRequest({'dst': '172.16.242.0/24',
                           'multipath': [{'hops': 20,
                                          'ifindex': 1,
                                          'gateway': '127.0.0.2'},
                                         {'hops': 30,
                                          'ifindex': 1,
                                          'gateway': '127.0.0.3'}]})
     self.ip.route('add', **req)
     assert grep('ip route show', pattern='172.16.242.0/24')
     assert grep('ip route show', pattern='nexthop.*127.0.0.2.*weight 21')
     assert grep('ip route show', pattern='nexthop.*127.0.0.3.*weight 31')
     self.ip.route('del', dst='172.16.242.0', mask=24)
예제 #4
0
 def test_route_multipath_helper(self):
     require_user('root')
     naddr = str(self.ipnets[1].network)
     req = IPRouteRequest({'dst': '%s/24' % naddr,
                           'multipath': [{'hops': 20,
                                          'oif': 1,
                                          'gateway': '127.0.0.2'},
                                         {'hops': 30,
                                          'oif': 1,
                                          'gateway': '127.0.0.3'}]})
     self.ip.route('add', **req)
     assert grep('ip route show', pattern='%s/24' % naddr)
     assert grep('ip route show', pattern='nexthop.*127.0.0.2.*weight 21')
     assert grep('ip route show', pattern='nexthop.*127.0.0.3.*weight 31')
     self.ip.route('del', dst=naddr, mask=24)
예제 #5
0
 def create(self):
     iface = self.containerName + 'veth0'
     ifacePeer = self.containerName + 'veth1'
     ip_main = IPDB()
     ip_sub = IPDB(nl=NetNS(self.containerName))
     ip_main.create(ifname=iface, kind='veth', peer=ifacePeer).commit()
     with ip_main.interfaces[ifacePeer] as veth:
         veth.net_ns_fd = self.containerName
     with ip_main.interfaces[iface] as veth:
         veth.up()
     ip_main.release()
     with ip_sub.interfaces[ifacePeer] as veth:
         #if not self.containerDhcp:
         if not hasattr(self, 'containerDhcp'):
             veth.add_ip(self.containerIp)
         if hasattr(self, 'containerMac'):
             veth.address = self.containerMac
     ip_sub.release()
     ns = NetNS(self.containerName)
     idx = ns.link_lookup(ifname=ifacePeer)[0]
     ns.link('set', index=idx, net_ns_fs=self.containerName, ifname='eth0')
     ns.link('set', index=idx, net_ns_fs=self.containerName, state='up')
     if hasattr(self, 'containerGateway'):
         request = {"dst": "0.0.0.0/0", "gateway": self.containerGateway}
         ns.route("add", **IPRouteRequest(request))
     ns.close()
     subprocess.call(["ovs-vsctl", "add-port", "br0", iface])
     dockerControl = DockerControl(self.containerObject)
     if hasattr(self, 'containerDhcp'):
         dhcpCmd = 'dhclient eth0'
         dockerControl.runCmd(dhcpCmd)
     addressCmd = 'ip address show dev eth0'
     addressInfo = dockerControl.runCmd(addressCmd)
     addressInfoList = addressInfo.splitlines()
     macAddressInfo = addressInfoList[1].split()[1]
     ipAddressInfo = addressInfoList[2].split()[1]
     ipAddressInfoDict = dict({
         'containerName': self.containerName,
         'macAddress': macAddressInfo,
         'ipAddress': ipAddressInfo
     })
     return json.dumps(ipAddressInfoDict)
예제 #6
0
파일: route.py 프로젝트: abn/pyroute2
 def __init__(self, route):
     dict.__init__(self, [
         x for x in IPRouteRequest(route).items()
         if x[0] in ('dst', 'dst_len', 'oif', 'iif', 'table')
     ])
예제 #7
0
파일: route.py 프로젝트: abn/pyroute2
    def commit(self, tid=None, transaction=None, rollback=False):
        self._load_event.clear()
        error = None
        drop = True

        if tid:
            transaction = self._transactions[tid]
        else:
            if transaction:
                drop = False
            else:
                transaction = self.last()

        # create a new route
        if self['ipdb_scope'] != 'system':
            try:
                self.ipdb.update_routes(
                    self.nl.route('add', **IPRouteRequest(transaction)))
            except Exception:
                self.nl = None
                self.ipdb.routes.remove(self)
                raise

        # work on existing route
        snapshot = self.pick()
        try:
            # route set
            request = IPRouteRequest(transaction - snapshot)
            if any([request[x] not in (None, {'attrs': []}) for x in request]):
                self.ipdb.update_routes(
                    self.nl.route('set', **IPRouteRequest(transaction)))

            # route removal
            if (transaction['ipdb_scope'] in ('shadow', 'remove')) or\
                    ((transaction['ipdb_scope'] == 'create') and rollback):
                if transaction['ipdb_scope'] == 'shadow':
                    self.set_item('ipdb_scope', 'locked')
                self.ipdb.update_routes(
                    self.nl.route('delete', **IPRouteRequest(snapshot)))
                if transaction['ipdb_scope'] == 'shadow':
                    self.set_item('ipdb_scope', 'shadow')

        except Exception as e:
            if not rollback:
                ret = self.commit(transaction=snapshot, rollback=True)
                if isinstance(ret, Exception):
                    error = ret
                else:
                    error = e
            else:
                if drop:
                    self.drop()
                x = RuntimeError()
                x.cause = e
                raise x

        if drop and not rollback:
            self.drop()

        if error is not None:
            error.transaction = transaction
            raise error

        if not rollback:
            with self._direct_state:
                self['multipath'] = transaction['multipath']
            self.reload()

        return self