Пример #1
0
 def _create_network_with_exception(self, network_name, ex):
     self.mox.StubOutWithMock(app.neutron, "create_network")
     fake_request = {
         "network": {
             "name": utils.make_net_name(network_name),
             "admin_state_up": True
         }
     }
     app.neutron.create_network(fake_request).AndRaise(ex)
     self.mox.ReplayAll()
Пример #2
0
 def _create_network_with_exception(self, network_name, ex):
     self.mox.StubOutWithMock(app.neutron, "create_network")
     fake_request = {
         "network": {
             "name": utils.make_net_name(network_name),
             "admin_state_up": True
         }
     }
     app.neutron.create_network(fake_request).AndRaise(ex)
     self.mox.ReplayAll()
Пример #3
0
def network_driver_create_network():
    """Creates a new Neutron Network which name is the given NetworkID.

    This function takes the following JSON data and delegates the actual
    network creation to the Neutron client. libnetwork's NetworkID is used as
    the name of Network in Neutron. ::

        {
            "NetworkID": string,
            "IPv4Data" : [{
                "AddressSpace": string,
                "Pool": ipv4-cidr-string,
                "Gateway" : ipv4-address,
                "AuxAddresses": {
                    "<identifier1>" : "<ipv4-address1>",
                    "<identifier2>" : "<ipv4-address2>",
                    ...
                }
            }, ...],
            "IPv6Data" : [{
                "AddressSpace": string,
                "Pool": ipv6-cidr-string,
                "Gateway" : ipv6-address,
                "AuxAddresses": {
                    "<identifier1>" : "<ipv6-address1>",
                    "<identifier2>" : "<ipv6-address2>",
                    ...
                }
            }, ...],
            "Options": {
                ...
            }
        }

    See the following link for more details about the spec:

      https://github.com/docker/libnetwork/blob/master/docs/remote.md#create-network  # noqa
    """
    json_data = flask.request.get_json(force=True)
    app.logger.debug("Received JSON data {0} for"
                     " /NetworkDriver.CreateNetwork".format(json_data))
    jsonschema.validate(json_data, schemata.NETWORK_CREATE_SCHEMA)

    container_net_id = json_data['NetworkID']
    neutron_network_name = utils.make_net_name(container_net_id)
    pool_cidr = json_data['IPv4Data'][0]['Pool']
    gateway_ip = ''
    if 'Gateway' in json_data['IPv4Data'][0]:
        gateway_cidr = json_data['IPv4Data'][0]['Gateway']
        gateway_ip = gateway_cidr.split('/')[0]
        app.logger.debug("gateway_cidr {0}, gateway_ip {1}".format(
            gateway_cidr, gateway_ip))

    neutron_uuid = None
    neutron_name = None
    options = json_data.get('Options')
    if options:
        generic_options = options.get(const.NETWORK_GENERIC_OPTIONS)
        if generic_options:
            neutron_uuid = generic_options.get(const.NEUTRON_UUID_OPTION)
            neutron_name = generic_options.get(const.NEUTRON_NAME_OPTION)

    if not neutron_uuid and not neutron_name:
        network = app.neutron.create_network({
            'network': {
                'name': neutron_network_name,
                "admin_state_up": True
            }
        })
        network_id = network['network']['id']
        _neutron_net_add_tags(network['network']['id'], container_net_id)

        app.logger.info(
            _LI("Created a new network with name {0}"
                " successfully: {1}").format(neutron_network_name, network))
    else:
        try:
            if neutron_uuid:
                networks = _get_networks_by_attrs(id=neutron_uuid)
            else:
                networks = _get_networks_by_attrs(name=neutron_name)
            network_id = networks[0]['id']
        except n_exceptions.NeutronClientException as ex:
            app.logger.error(
                _LE("Error happened during listing "
                    "Neutron networks: {0}").format(ex))
            raise
        _neutron_net_add_tags(network_id, container_net_id)
        _neutron_net_add_tag(network_id, const.KURYR_EXISTING_NEUTRON_NET)
        app.logger.info(
            _LI("Using existing network {0} successfully").format(
                neutron_uuid))

    cidr = netaddr.IPNetwork(pool_cidr)
    subnet_network = str(cidr.network)
    subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)])
    subnets = _get_subnets_by_attrs(network_id=network_id, cidr=subnet_cidr)
    if not subnets:
        new_subnets = [{
            'name': pool_cidr,
            'network_id': network_id,
            'ip_version': cidr.version,
            'cidr': subnet_cidr,
            'enable_dhcp': app.enable_dhcp,
        }]
        if gateway_ip:
            new_subnets[0]['gateway_ip'] = gateway_ip

        app.neutron.create_subnet({'subnets': new_subnets})

    return flask.jsonify(const.SCHEMA['SUCCESS'])
Пример #4
0
    def test_network_driver_create_network(self):
        docker_network_id = utils.get_hash()
        self.mox.StubOutWithMock(app.neutron, "create_network")
        fake_request = {
            "network": {
                "name": utils.make_net_name(docker_network_id),
                "admin_state_up": True
            }
        }
        # The following fake response is retrieved from the Neutron doc:
        #   http://developer.openstack.org/api-ref-networking-v2.html#createNetwork  # noqa
        fake_neutron_net_id = "4e8e5957-649f-477b-9e5b-f1f75b21c03c"
        fake_response = {
            "network": {
                "status": "ACTIVE",
                "subnets": [],
                "name": utils.make_net_name(docker_network_id),
                "admin_state_up": True,
                "tenant_id": "9bacb3c5d39d41a79512987f338cf177",
                "router:external": False,
                "segments": [],
                "shared": False,
                "id": fake_neutron_net_id
            }
        }
        app.neutron.create_network(fake_request).AndReturn(fake_response)

        self.mox.StubOutWithMock(app.neutron, "add_tag")
        tags = utils.create_net_tags(docker_network_id)
        for tag in tags:
            app.neutron.add_tag('networks', fake_neutron_net_id, tag)

        self.mox.StubOutWithMock(app.neutron, 'list_subnets')
        fake_existing_subnets_response = {
            "subnets": []
        }
        fake_cidr_v4 = '192.168.42.0/24'
        app.neutron.list_subnets(
            network_id=fake_neutron_net_id,
            cidr=fake_cidr_v4).AndReturn(fake_existing_subnets_response)

        self.mox.StubOutWithMock(app.neutron, 'create_subnet')
        fake_subnet_request = {
            "subnets": [{
                'name': fake_cidr_v4,
                'network_id': fake_neutron_net_id,
                'ip_version': 4,
                'cidr': fake_cidr_v4,
                'enable_dhcp': app.enable_dhcp,
                'gateway_ip': '192.168.42.1',
            }]
        }
        subnet_v4_id = str(uuid.uuid4())
        fake_v4_subnet = self._get_fake_v4_subnet(
            fake_neutron_net_id, subnet_v4_id,
            name=fake_cidr_v4, cidr=fake_cidr_v4)
        fake_subnet_response = {
            'subnets': [
                fake_v4_subnet['subnet']
            ]
        }
        app.neutron.create_subnet(
            fake_subnet_request).AndReturn(fake_subnet_response)

        self.mox.ReplayAll()

        network_request = {
            'NetworkID': docker_network_id,
            'IPv4Data': [{
                'AddressSpace': 'foo',
                'Pool': '192.168.42.0/24',
                'Gateway': '192.168.42.1/24',
            }],
            'IPv6Data': [{
                'AddressSpace': 'bar',
                'Pool': 'fe80::/64',
                'Gateway': 'fe80::f816:3eff:fe20:57c3/64',
            }],
            'Options': {}
        }
        response = self.app.post('/NetworkDriver.CreateNetwork',
                                 content_type='application/json',
                                 data=jsonutils.dumps(network_request))

        self.assertEqual(200, response.status_code)
        decoded_json = jsonutils.loads(response.data)
        self.assertEqual(constants.SCHEMA['SUCCESS'], decoded_json)
Пример #5
0
    def test_network_driver_create_network(self):
        docker_network_id = hashlib.sha256(utils.getrandbits(256)).hexdigest()
        self.mox.StubOutWithMock(app.neutron, "create_network")
        fake_request = {
            "network": {
                "name": utils.make_net_name(docker_network_id),
                "admin_state_up": True
            }
        }
        # The following fake response is retrieved from the Neutron doc:
        #   http://developer.openstack.org/api-ref-networking-v2.html#createNetwork  # noqa
        fake_neutron_net_id = "4e8e5957-649f-477b-9e5b-f1f75b21c03c"
        fake_response = {
            "network": {
                "status": "ACTIVE",
                "subnets": [],
                "name": utils.make_net_name(docker_network_id),
                "admin_state_up": True,
                "tenant_id": "9bacb3c5d39d41a79512987f338cf177",
                "router:external": False,
                "segments": [],
                "shared": False,
                "id": fake_neutron_net_id
            }
        }
        app.neutron.create_network(fake_request).AndReturn(fake_response)

        self.mox.StubOutWithMock(app.neutron, "add_tag")
        tags = utils.create_net_tags(docker_network_id)
        for tag in tags:
            app.neutron.add_tag('networks', fake_neutron_net_id, tag)

        self.mox.StubOutWithMock(app.neutron, 'list_subnets')
        fake_existing_subnets_response = {"subnets": []}
        fake_cidr_v4 = '192.168.42.0/24'
        app.neutron.list_subnets(
            network_id=fake_neutron_net_id,
            cidr=fake_cidr_v4).AndReturn(fake_existing_subnets_response)

        self.mox.StubOutWithMock(app.neutron, 'create_subnet')
        fake_subnet_request = {
            "subnets": [{
                'name': fake_cidr_v4,
                'network_id': fake_neutron_net_id,
                'ip_version': 4,
                'cidr': fake_cidr_v4,
                'enable_dhcp': app.enable_dhcp,
                'gateway_ip': '192.168.42.1',
            }]
        }
        subnet_v4_id = str(uuid.uuid4())
        fake_v4_subnet = self._get_fake_v4_subnet(fake_neutron_net_id,
                                                  subnet_v4_id,
                                                  name=fake_cidr_v4,
                                                  cidr=fake_cidr_v4)
        fake_subnet_response = {'subnets': [fake_v4_subnet['subnet']]}
        app.neutron.create_subnet(fake_subnet_request).AndReturn(
            fake_subnet_response)

        self.mox.ReplayAll()

        network_request = {
            'NetworkID':
            docker_network_id,
            'IPv4Data': [{
                'AddressSpace': 'foo',
                'Pool': '192.168.42.0/24',
                'Gateway': '192.168.42.1/24',
            }],
            'IPv6Data': [{
                'AddressSpace': 'bar',
                'Pool': 'fe80::/64',
                'Gateway': 'fe80::f816:3eff:fe20:57c3/64',
            }],
            'Options': {}
        }
        response = self.app.post('/NetworkDriver.CreateNetwork',
                                 content_type='application/json',
                                 data=jsonutils.dumps(network_request))

        self.assertEqual(200, response.status_code)
        decoded_json = jsonutils.loads(response.data)
        self.assertEqual(constants.SCHEMA['SUCCESS'], decoded_json)
Пример #6
0
def network_driver_create_network():
    """Creates a new Neutron Network which name is the given NetworkID.

    This function takes the following JSON data and delegates the actual
    network creation to the Neutron client. libnetwork's NetworkID is used as
    the name of Network in Neutron. ::

        {
            "NetworkID": string,
            "IPv4Data" : [{
                "AddressSpace": string,
                "Pool": ipv4-cidr-string,
                "Gateway" : ipv4-address,
                "AuxAddresses": {
                    "<identifier1>" : "<ipv4-address1>",
                    "<identifier2>" : "<ipv4-address2>",
                    ...
                }
            }, ...],
            "IPv6Data" : [{
                "AddressSpace": string,
                "Pool": ipv6-cidr-string,
                "Gateway" : ipv6-address,
                "AuxAddresses": {
                    "<identifier1>" : "<ipv6-address1>",
                    "<identifier2>" : "<ipv6-address2>",
                    ...
                }
            }, ...],
            "Options": {
                ...
            }
        }

    See the following link for more details about the spec:

      https://github.com/docker/libnetwork/blob/master/docs/remote.md#create-network  # noqa
    """
    json_data = flask.request.get_json(force=True)
    app.logger.debug("Received JSON data {0} for"
                     " /NetworkDriver.CreateNetwork".format(json_data))
    jsonschema.validate(json_data, schemata.NETWORK_CREATE_SCHEMA)
    container_net_id = json_data['NetworkID']
    neutron_network_name = utils.make_net_name(container_net_id, tags=app.tag)
    pool_cidr = json_data['IPv4Data'][0]['Pool']
    gateway_ip = ''
    if 'Gateway' in json_data['IPv4Data'][0]:
        gateway_cidr = json_data['IPv4Data'][0]['Gateway']
        gateway_ip = gateway_cidr.split('/')[0]
        app.logger.debug("gateway_cidr {0}, gateway_ip {1}"
            .format(gateway_cidr, gateway_ip))

    neutron_uuid = None
    neutron_name = None
    options = json_data.get('Options')
    if options:
        generic_options = options.get(const.NETWORK_GENERIC_OPTIONS)
        if generic_options:
            neutron_uuid = generic_options.get(const.NEUTRON_UUID_OPTION)
            neutron_name = generic_options.get(const.NEUTRON_NAME_OPTION)

    if not neutron_uuid and not neutron_name:
        network = app.neutron.create_network(
            {'network': {'name': neutron_network_name,
                         "admin_state_up": True}})
        network_id = network['network']['id']
        _neutron_net_add_tags(network['network']['id'], container_net_id,
                              tags=app.tag)

        app.logger.info(_LI("Created a new network with name {0}"
                            " successfully: {1}")
                        .format(neutron_network_name, network))
    else:
        try:
            if neutron_uuid:
                networks = _get_networks_by_attrs(id=neutron_uuid)
            else:
                networks = _get_networks_by_attrs(name=neutron_name)
            network_id = networks[0]['id']
        except n_exceptions.NeutronClientException as ex:
            app.logger.error(_LE("Error happened during listing "
                                 "Neutron networks: {0}").format(ex))
            raise
        if app.tag:
            _neutron_net_add_tags(network_id, container_net_id, tags=app.tag)
            _neutron_net_add_tag(network_id, const.KURYR_EXISTING_NEUTRON_NET)
        else:
            network = app.neutron.update_network(
                neutron_uuid, {'network': {'name': neutron_network_name}})
            app.logger.info(_LI("Updated the network with new name {0}"
                                " successfully: {1}")
                            .format(neutron_network_name, network))
        app.logger.info(_LI("Using existing network {0} successfully")
                        .format(neutron_uuid))

    cidr = netaddr.IPNetwork(pool_cidr)
    subnet_network = str(cidr.network)
    subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)])
    subnets = _get_subnets_by_attrs(
        network_id=network_id, cidr=subnet_cidr)
    if not subnets:
        new_subnets = [{
            'name': pool_cidr,
            'network_id': network_id,
            'ip_version': cidr.version,
            'cidr': subnet_cidr,
            'enable_dhcp': app.enable_dhcp,
        }]
        if gateway_ip:
            new_subnets[0]['gateway_ip'] = gateway_ip

        app.neutron.create_subnet({'subnets': new_subnets})

    return flask.jsonify(const.SCHEMA['SUCCESS'])