Example #1
0
    def test_plugin_prefix_with_parent_resource(self):
        controller = self.DummySvcPlugin()
        parent = dict(member_name="tenant",
                      collection_name="tenants")
        member = {'custom_member_action': "GET"}
        collections = {'collection_action': "GET"}
        res_ext = extensions.ResourceExtension('tweedles', controller, parent,
                                               path_prefix="/dummy_svc",
                                               member_actions=member,
                                               collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        index_response = test_app.get("/dummy_svc/tenants/1/tweedles")
        self.assertEqual(200, index_response.status_int)

        response = test_app.get("/dummy_svc/tenants/1/"
                                "tweedles/1/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['member_action'],
                         "value")

        response = test_app.get("/dummy_svc/tenants/2/"
                                "tweedles/collection_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'],
                         "value")
Example #2
0
 def test_plug_l2_gw_port_attachment(self):
     tenant_id = 'pippo'
     node_uuid = _uuid()
     lswitch = nvplib.create_lswitch(self.fake_cluster, tenant_id,
                                     'fake-switch')
     gw_id = self._create_gw_service(node_uuid, 'fake-gw')['uuid']
     lport = nvplib.create_lport(self.fake_cluster,
                                 lswitch['uuid'],
                                 tenant_id,
                                 _uuid(),
                                 'fake-gw-port',
                                 gw_id,
                                 True)
     json.loads(nvplib.plug_l2_gw_service(self.fake_cluster,
                                          lswitch['uuid'],
                                          lport['uuid'],
                                          gw_id))
     uri = nvplib._build_uri_path(nvplib.LSWITCHPORT_RESOURCE,
                                  lport['uuid'],
                                  lswitch['uuid'],
                                  is_attachment=True)
     resp_obj = json.loads(
         nvplib.do_single_request("GET", uri,
                                  cluster=self.fake_cluster))
     self.assertIn('LogicalPortAttachment', resp_obj)
     self.assertEqual(resp_obj['LogicalPortAttachment']['type'],
                      'L2GatewayAttachment')
Example #3
0
    def test_plugin_prefix_with_parent_resource(self):
        controller = self.DummySvcPlugin()
        parent = dict(member_name="tenant",
                      collection_name="tenants")
        member = {'custom_member_action': "GET"}
        collections = {'collection_action': "GET"}
        res_ext = extensions.ResourceExtension('tweedles', controller, parent,
                                               path_prefix="/dummy_svc",
                                               member_actions=member,
                                               collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        index_response = test_app.get("/dummy_svc/tenants/1/tweedles")
        self.assertEqual(200, index_response.status_int)

        response = test_app.get("/dummy_svc/tenants/1/"
                                "tweedles/1/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['member_action'],
                         "value")

        response = test_app.get("/dummy_svc/tenants/2/"
                                "tweedles/collection_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'],
                         "value")
Example #4
0
    def test_resource_extension_for_get_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {"custom_collection_action": "GET"}
        res_ext = extensions.ResourceExtension("tweedles", controller, collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/tweedles/custom_collection_action")
        self.assertEqual(200, response.status_int)
        LOG.debug(jsonutils.loads(response.body))
        self.assertEqual(jsonutils.loads(response.body)["collection"], "value")
Example #5
0
    def test_resource_extension_for_get_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {'custom_collection_action': "GET"}
        res_ext = extensions.ResourceExtension('tweedles', controller,
                                               collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/tweedles/custom_collection_action")
        self.assertEqual(200, response.status_int)
        LOG.debug(jsonutils.loads(response.body))
        self.assertEqual(jsonutils.loads(response.body)['collection'], "value")
Example #6
0
    def test_resource_ext_with_custom_member_action_gets_plugin_prefix(self):
        controller = self.DummySvcPlugin()
        member = {"custom_member_action": "GET"}
        collections = {"collection_action": "GET"}
        res_ext = extensions.ResourceExtension(
            "tweedles", controller, path_prefix="/dummy_svc", member_actions=member, collection_actions=collections
        )
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/dummy_svc/tweedles/1/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)["member_action"], "value")

        response = test_app.get("/dummy_svc/tweedles/collection_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)["collection"], "value")
Example #7
0
    def test_resource_extension_with_custom_member_action_and_attr_map(self):
        controller = self.ResourceExtensionController()
        member = {'custom_member_action': "GET"}
        params = {
            'tweedles': {
                'id': {
                    'allow_post': False,
                    'allow_put': False,
                    'validate': {
                        'type:uuid': None
                    },
                    'is_visible': True
                },
                'name': {
                    'allow_post': True,
                    'allow_put': True,
                    'validate': {
                        'type:string': None
                    },
                    'default': '',
                    'is_visible': True
                },
            }
        }
        res_ext = extensions.ResourceExtension('tweedles',
                                               controller,
                                               member_actions=member,
                                               attr_map=params)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/tweedles/some_id/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(
            jsonutils.loads(response.body)['member_action'], "value")
Example #8
0
    def _handler(self, client_sock, client_addr):
        """Handle incoming lease relay stream connection.

        This method will only read the first 1024 bytes and then close the
        connection.  The limit exists to limit the impact of misbehaving
        clients.
        """
        try:
            msg = client_sock.recv(1024)
            data = jsonutils.loads(msg)
            client_sock.close()

            network_id = data['network_id']
            if not uuidutils.is_uuid_like(network_id):
                raise ValueError(
                    _("Network ID %s is not a valid UUID") % network_id)
            ip_address = str(netaddr.IPAddress(data['ip_address']))
            lease_remaining = int(data['lease_remaining'])
            self.callback(network_id, ip_address, lease_remaining)
        except ValueError as e:
            LOG.warn(_('Unable to parse lease relay msg to dict.'))
            LOG.warn(_('Exception value: %s'), e)
            LOG.warn(_('Message representation: %s'), repr(msg))
        except Exception as e:
            LOG.exception(_('Unable update lease. Exception'))
Example #9
0
 def _goose_handler(req, res):
     #NOTE: This only handles JSON responses.
     # You can use content type header to test for XML.
     data = jsonutils.loads(res.body)
     data['FOXNSOX:googoose'] = req.GET.get('chewing')
     res.body = jsonutils.dumps(data)
     return res
Example #10
0
def update_port(network, port_id, **params):
    controller = params["controller"]
    lport_obj = {}

    if "state" in params:
        state = params["state"]
        check_port_state(state)
        admin_status = True
        if state == "DOWN":
            admin_status = False
        lport_obj["admin_status_enabled"] = admin_status

    uri = "/ws.v1/lswitch/" + network + "/lport/" + port_id
    try:
        resp_obj = do_single_request("PUT",
                                     uri,
                                     jsonutils.dumps(lport_obj),
                                     controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port or Network not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port_id, net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()

    obj = jsonutils.loads(resp_obj)
    obj["port-op-status"] = get_port_status(controller, network, obj["uuid"])
    return obj
Example #11
0
    def _handler(self, client_sock, client_addr):
        """Handle incoming lease relay stream connection.

        This method will only read the first 1024 bytes and then close the
        connection.  The limit exists to limit the impact of misbehaving
        clients.
        """
        try:
            msg = client_sock.recv(1024)
            data = jsonutils.loads(msg)
            client_sock.close()

            network_id = data['network_id']
            if not uuidutils.is_uuid_like(network_id):
                raise ValueError(_("Network ID %s is not a valid UUID") %
                                 network_id)
            ip_address = str(netaddr.IPAddress(data['ip_address']))
            lease_remaining = int(data['lease_remaining'])
            self.callback(network_id, ip_address, lease_remaining)
        except ValueError as e:
            LOG.warn(_('Unable to parse lease relay msg to dict.'))
            LOG.warn(_('Exception value: %s'), e)
            LOG.warn(_('Message representation: %s'), repr(msg))
        except Exception as e:
            LOG.exception(_('Unable update lease. Exception'))
Example #12
0
def get_port_status(controller, lswitch_id, port_id):
    """Retrieve the operational status of the port"""
    # Make sure the network exists first
    try:
        do_single_request("GET", "/ws.v1/lswitch/%s" % (lswitch_id),
                          controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Network not found, Error: %s" % str(e))
        raise exception.NetworkNotFound(net_id=lswitch_id)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    try:
        r = do_single_request(
            "GET",
            "/ws.v1/lswitch/%s/lport/%s/status" % (lswitch_id, port_id),
            controller=controller)
        r = jsonutils.loads(r)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port_id, net_id=lswitch_id)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    if r['link_status_up'] is True:
        return "UP"
    else:
        return "DOWN"
Example #13
0
def create_port(tenant, network, port_init_state, **params):
    # Check initial state -- this throws an exception if the port state is
    # invalid
    check_port_state(port_init_state)

    controller = params["controller"]

    ls_uuid = network

    admin_status = True
    if port_init_state == "DOWN":
        admin_status = False
    lport_obj = {"admin_status_enabled": admin_status}

    path = "/ws.v1/lswitch/" + ls_uuid + "/lport"
    try:
        resp_obj = do_single_request("POST",
                                     path,
                                     jsonutils.dumps(lport_obj),
                                     controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Network not found, Error: %s" % str(e))
        raise exception.NetworkNotFound(net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()

    result = jsonutils.loads(resp_obj)
    result['port-op-status'] = get_port_status(controller, ls_uuid,
                                               result['uuid'])
    return result
Example #14
0
def update_port(network, port_id, **params):
    controller = params["controller"]
    lport_obj = {}

    if "state" in params:
        state = params["state"]
        check_port_state(state)
        admin_status = True
        if state == "DOWN":
            admin_status = False
        lport_obj["admin_status_enabled"] = admin_status

    uri = "/ws.v1/lswitch/" + network + "/lport/" + port_id
    try:
        resp_obj = do_single_request("PUT",
                                     uri,
                                     jsonutils.dumps(lport_obj),
                                     controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port or Network not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port_id, net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()

    obj = jsonutils.loads(resp_obj)
    obj["port-op-status"] = get_port_status(controller, network, obj["uuid"])
    return obj
Example #15
0
 def _bands_handler(req, res):
     #NOTE: This only handles JSON responses.
     # You can use content type header to test for XML.
     data = jsonutils.loads(res.body)
     data['FOXNSOX:big_bands'] = 'Pig Bands!'
     res.body = jsonutils.dumps(data)
     return res
Example #16
0
def get_port_status(controller, lswitch_id, port_id):
    """Retrieve the operational status of the port"""
    # Make sure the network exists first
    try:
        do_single_request("GET",
                          "/ws.v1/lswitch/%s" % (lswitch_id),
                          controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Network not found, Error: %s" % str(e))
        raise exception.NetworkNotFound(net_id=lswitch_id)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    try:
        r = do_single_request("GET",
                              "/ws.v1/lswitch/%s/lport/%s/status" %
                              (lswitch_id, port_id),
                              controller=controller)
        r = jsonutils.loads(r)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port_id, net_id=lswitch_id)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    if r['link_status_up'] is True:
        return "UP"
    else:
        return "DOWN"
Example #17
0
def create_port(tenant, network, port_init_state, **params):
    # Check initial state -- this throws an exception if the port state is
    # invalid
    check_port_state(port_init_state)

    controller = params["controller"]

    ls_uuid = network

    admin_status = True
    if port_init_state == "DOWN":
        admin_status = False
    lport_obj = {"admin_status_enabled": admin_status}

    path = "/ws.v1/lswitch/" + ls_uuid + "/lport"
    try:
        resp_obj = do_single_request("POST",
                                     path,
                                     jsonutils.dumps(lport_obj),
                                     controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Network not found, Error: %s" % str(e))
        raise exception.NetworkNotFound(net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()

    result = jsonutils.loads(resp_obj)
    result['port-op-status'] = get_port_status(controller, ls_uuid,
                                               result['uuid'])
    return result
 def _check_is_create_user(self,request,re,info):
     '''Withdraw tenant_id from re ,read body from write in database'''
     if 'resource' in info and info['resource']=='users' \
     and 'method' in info and info['method']=='POST':
         print '[auth] create user'
         re_json=json.loads(re[0])
         print '[auth] re_json = ',re_json
         userid=re_json['user']['id']
         body=json.loads(request.body)
         username=body['user']['name']
         userpasswd=body['user']['passwd']
         usercompany=body['user']['company']
         session=Session()
         session.add(User(name=username,passwd=userpasswd,id=userid,company=usercompany))
         session.commit()
         return True
     return False
Example #19
0
    def test_get_resources(self):
        app = _setup_extensions_test_app()

        response = app.get("/dummy_resources/1?chewing=newblue")

        response_data = jsonutils.loads(response.body)
        self.assertEqual('newblue', response_data['FOXNSOX:googoose'])
        self.assertEqual("Pig Bands!", response_data['FOXNSOX:big_bands'])
Example #20
0
    def test_get_resources(self):
        app = _setup_extensions_test_app()

        response = app.get("/dummy_resources/1?chewing=newblue")

        response_data = jsonutils.loads(response.body)
        self.assertEqual('newblue', response_data['FOXNSOX:googoose'])
        self.assertEqual("Pig Bands!", response_data['FOXNSOX:big_bands'])
Example #21
0
    def test_resource_extension_with_custom_member_action(self):
        controller = self.ResourceExtensionController()
        member = {"custom_member_action": "GET"}
        res_ext = extensions.ResourceExtension("tweedles", controller, member_actions=member)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/tweedles/some_id/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)["member_action"], "value")
Example #22
0
    def load_json(cls, data, default_rule=None):
        """
        Allow loading of JSON rule data.
        """

        # Suck in the JSON data and parse the rules
        rules = dict((k, parse_rule(v)) for k, v in jsonutils.loads(data).items())

        return cls(rules, default_rule)
Example #23
0
def delete_all_ports(controller, ls_uuid):
    res = do_single_request("GET",
                            "/ws.v1/lswitch/%s/lport?fields=uuid" % ls_uuid,
                            controller=controller)
    res = jsonutils.loads(res)
    for r in res["results"]:
        do_single_request("DELETE",
                          "/ws.v1/lswitch/%s/lport/%s" % (ls_uuid, r["uuid"]),
                          controller=controller)
Example #24
0
def delete_all_ports(controller, ls_uuid):
    res = do_single_request("GET", "/ws.v1/lswitch/%s/lport?fields=uuid" %
                            ls_uuid, controller=controller)
    res = jsonutils.loads(res)
    for r in res["results"]:
        do_single_request(
            "DELETE",
            "/ws.v1/lswitch/%s/lport/%s" % (ls_uuid, r["uuid"]),
            controller=controller)
Example #25
0
    def test_resource_ext_with_custom_member_action_gets_plugin_prefix(self):
        controller = self.DummySvcPlugin()
        member = {'custom_member_action': "GET"}
        collections = {'collection_action': "GET"}
        res_ext = extensions.ResourceExtension('tweedles', controller,
                                               path_prefix="/dummy_svc",
                                               member_actions=member,
                                               collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/dummy_svc/tweedles/1/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['member_action'],
                         "value")

        response = test_app.get("/dummy_svc/tweedles/collection_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'],
                         "value")
Example #26
0
 def get_configuration_dict(self, agent_db):
     try:
         conf = jsonutils.loads(agent_db.configurations)
     except Exception:
         msg = _('Configuration for agent %(agent_type)s on host %(host)s'
                 ' is invalid.')
         LOG.warn(msg, {'agent_type': agent_db.agent_type,
                        'host': agent_db.host})
         conf = {}
     return conf
Example #27
0
 def _create_tz(self, name):
     post_uri = "/ws.v1/transport-zone"
     body = {"display_name": name, "tags": [{"tag": "plugin-test"}]}
     try:
         resp_obj = self.quantum.api_client.request("POST", post_uri,
                                                    jsonutils.dumps(body))
     except NvpApiClient.NvpApiException as e:
         print("Unknown API Error: %s" % str(e))
         raise exception.QuantumException()
     return jsonutils.loads(resp_obj)["uuid"]
Example #28
0
    def load_json(cls, data, default_rule=None):
        """
        Allow loading of JSON rule data.
        """

        # Suck in the JSON data and parse the rules
        rules = dict(
            (k, parse_rule(v)) for k, v in jsonutils.loads(data).items())

        return cls(rules, default_rule)
Example #29
0
    def test_resource_extension_with_custom_member_action(self):
        controller = self.ResourceExtensionController()
        member = {'custom_member_action': "GET"}
        res_ext = extensions.ResourceExtension('tweedles', controller,
                                               member_actions=member)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/tweedles/some_id/custom_member_action")
        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['member_action'],
                         "value")
Example #30
0
def get_network(controller, net_id):
    path = "/ws.v1/lswitch/%s" % net_id
    try:
        resp_obj = do_single_request("GET", path, controller=controller)
        network = jsonutils.loads(resp_obj)
    except NvpApiClient.ResourceNotFound as e:
        raise exception.NetworkNotFound(net_id=net_id)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    LOG.debug("Got network \"%s\": %s" % (net_id, network))
    return network
Example #31
0
 def _create_tz(self, name):
     post_uri = "/ws.v1/transport-zone"
     body = {"display_name": name, "tags": [{"tag": "plugin-test"}]}
     try:
         resp_obj = self.quantum.api_client.request("POST",
                                                    post_uri,
                                                    jsonutils.dumps(body))
     except NvpApiClient.NvpApiException as e:
         LOG.error("Unknown API Error: %s" % str(e))
         raise exception.QuantumException()
     return jsonutils.loads(resp_obj)["uuid"]
Example #32
0
def get_network(controller, net_id):
    path = "/ws.v1/lswitch/%s" % net_id
    try:
        resp_obj = do_single_request("GET", path, controller=controller)
        network = jsonutils.loads(resp_obj)
    except NvpApiClient.ResourceNotFound as e:
        raise exception.NetworkNotFound(net_id=net_id)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    LOG.debug("Got network \"%s\": %s" % (net_id, network))
    return network
Example #33
0
    def test_resource_extension_for_delete_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {'custom_collection_action': "DELETE"}
        res_ext = extensions.ResourceExtension('tweedles', controller,
                                               collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.delete("/tweedles/custom_collection_action")

        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'], 'value')
Example #34
0
    def test_resource_ext_for_formatted_req_on_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {'custom_collection_action': "GET"}
        res_ext = extensions.ResourceExtension('tweedles', controller,
                                               collection_actions=collections)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/tweedles/custom_collection_action.json")

        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'], "value")
Example #35
0
    def test_resource_ext_for_nested_resource_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {"custom_collection_action": "GET"}
        parent = dict(collection_name="beetles", member_name="beetle")
        res_ext = extensions.ResourceExtension("tweedles", controller, collection_actions=collections, parent=parent)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/beetles/beetle_id" "/tweedles/custom_collection_action")

        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)["collection"], "value")
Example #36
0
 def test_plug_l2_gw_port_attachment(self):
     tenant_id = 'pippo'
     node_uuid = _uuid()
     lswitch = nvplib.create_lswitch(self.fake_cluster, tenant_id,
                                     'fake-switch')
     gw_id = self._create_gw_service(node_uuid, 'fake-gw')['uuid']
     lport = nvplib.create_lport(self.fake_cluster, lswitch['uuid'],
                                 tenant_id, _uuid(), 'fake-gw-port', gw_id,
                                 True)
     json.loads(
         nvplib.plug_l2_gw_service(self.fake_cluster, lswitch['uuid'],
                                   lport['uuid'], gw_id))
     uri = nvplib._build_uri_path(nvplib.LSWITCHPORT_RESOURCE,
                                  lport['uuid'],
                                  lswitch['uuid'],
                                  is_attachment=True)
     resp_obj = json.loads(
         nvplib.do_single_request("GET", uri, cluster=self.fake_cluster))
     self.assertIn('LogicalPortAttachment', resp_obj)
     self.assertEqual(resp_obj['LogicalPortAttachment']['type'],
                      'L2GatewayAttachment')
Example #37
0
    def test_resource_extension_for_delete_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {'custom_collection_action': "DELETE"}
        res_ext = extensions.ResourceExtension('tweedles',
                                               controller,
                                               collection_actions=collections)
        test_app = setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.delete("/tweedles/custom_collection_action")

        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'], 'value')
Example #38
0
    def nos_rest_conn(self, nos_url, action, data, headers):
        self.nos_url = nos_url
        body_data = json.dumps(data)
        if not headers:
            headers = {}
        headers['Content-type'] = 'application/json'
        headers['Accept'] = 'application/json'

        LOG.debug(_("PLUMgrid_NOS_Server: %(server)s %(port)s %(action)s"),
                  dict(server=self.server, port=self.port, action=action))

        conn = httplib.HTTPConnection(self.server, self.port,
                                      timeout=self.timeout)
        if conn is None:
            LOG.error(_('PLUMgrid_NOS_Server: Could not establish HTTP '
                        'connection'))
            return

        try:
            LOG.debug(_("PLUMgrid_NOS_Server Sending Data: %(nos_url)s "
                        "%(body_data)s %(headers)s"),
                      dict(
                          nos_url=nos_url,
                          body_data=body_data,
                          headers=headers,
                      ))
            conn.request(action, nos_url, body_data, headers)
            resp = conn.getresponse()
            resp_str = resp.read()

            LOG.debug(_("PLUMgrid_NOS_Server Connection Data: %(resp)s, "
                        "%(resp_str)s"), dict(resp=resp, resp_str=resp_str))

            if resp.status is httplib.OK:
                try:
                    respdata = json.loads(resp_str)
                    LOG.debug(_("PLUMgrid_NOS_Server Connection RESP: %s"),
                              respdata)
                    pass
                except ValueError:
                    err_message = _("PLUMgrid HTTP Connection Failed: ")
                    LOG.Exception(err_message)
                    raise plum_excep.PLUMgridException(err_message)

            ret = (resp.status, resp.reason, resp_str)
        except urllib2.HTTPError:
            LOG.error(_('PLUMgrid_NOS_Server: %(action)s failure, %(e)r'))
            ret = 0, None, None, None
        conn.close()
        LOG.debug(_("PLUMgrid_NOS_Server: status=%(status)d, "
                  "reason=%(reason)r, ret=%(ret)s"),
                  {'status': ret[0], 'reason': ret[1], 'ret': ret[2]})
        return ret
Example #39
0
 def get_configuration_dict(self, agent_db):
     try:
         conf = jsonutils.loads(agent_db.configurations)
     except Exception:
         msg = _('Configuration for agent %(agent_type)s on host %(host)s'
                 ' is invalid.')
         LOG.warn(msg, {
             'agent_type': agent_db.agent_type,
             'host': agent_db.host
         })
         conf = {}
     return conf
Example #40
0
 def _test_create_lrouter_dnat_rule(self, func):
     tenant_id = 'pippo'
     lrouter = nvplib.create_lrouter(self.fake_cluster, tenant_id,
                                     'fake_router', '192.168.0.1')
     nat_rule = func(
         self.fake_cluster,
         lrouter['uuid'],
         '10.0.0.99',
         match_criteria={'destination_ip_addresses': '192.168.0.5'})
     uri = nvplib._build_uri_path(nvplib.LROUTERNAT_RESOURCE,
                                  nat_rule['uuid'], lrouter['uuid'])
     return json.loads(
         nvplib.do_single_request("GET", uri, cluster=self.fake_cluster))
Example #41
0
 def parse_response_msg(self, recv_msg):
     msg = jsonutils.loads(recv_msg)
     if msg['status'] == 'OK':
         if 'response' in msg:
             return msg.get('response')
         return
     elif msg['status'] == 'FAIL':
         msg_dict = dict(action=msg['action'], reason=msg['reason'])
         error_msg = _("Action %(action)s failed: %(reason)s") % msg_dict
     else:
         error_msg = _("Unknown operation status %s") % msg['status']
     LOG.error(error_msg)
     raise exceptions.MlnxException(error_msg)
Example #42
0
def get_port(controller, network, port, relations=None):
    uri = "/ws.v1/lswitch/" + network + "/lport/" + port + "?"
    if relations:
        uri += "relations=%s" % relations
    try:
        resp_obj = do_single_request("GET", uri, controller=controller)
        port = jsonutils.loads(resp_obj)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port or Network not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port, net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    return port
Example #43
0
def get_port(controller, network, port, relations=None):
    uri = "/ws.v1/lswitch/" + network + "/lport/" + port + "?"
    if relations:
        uri += "relations=%s" % relations
    try:
        resp_obj = do_single_request("GET", uri, controller=controller)
        port = jsonutils.loads(resp_obj)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port or Network not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port, net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    return port
Example #44
0
    def test_resource_ext_for_nested_resource_custom_collection_action(self):
        controller = self.ResourceExtensionController()
        collections = {'custom_collection_action': "GET"}
        parent = dict(collection_name='beetles', member_name='beetle')
        res_ext = extensions.ResourceExtension('tweedles', controller,
                                               collection_actions=collections,
                                               parent=parent)
        test_app = _setup_extensions_test_app(SimpleExtensionManager(res_ext))

        response = test_app.get("/beetles/beetle_id"
                                "/tweedles/custom_collection_action")

        self.assertEqual(200, response.status_int)
        self.assertEqual(jsonutils.loads(response.body)['collection'], "value")
Example #45
0
    def test_extend_get_resource_response(self):
        def extend_response_data(req, res):
            data = jsonutils.loads(res.body)
            data["FOXNSOX:extended_key"] = req.GET.get("extended_key")
            res.body = jsonutils.dumps(data)
            return res

        app = self._setup_app_with_request_handler(extend_response_data, "GET")
        response = app.get("/dummy_resources/1?extended_key=extended_data")

        self.assertEqual(200, response.status_int)
        response_data = jsonutils.loads(response.body)
        self.assertEqual("extended_data", response_data["FOXNSOX:extended_key"])
        self.assertEqual("knox", response_data["fort"])
Example #46
0
def unplug_interface(controller, network, port):
    uri = "/ws.v1/lswitch/" + network + "/lport/" + port + "/attachment"
    lport_obj = {"type": "NoAttachment"}
    try:
        resp_obj = do_single_request("PUT",
                                     uri,
                                     jsonutils.dumps(lport_obj),
                                     controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port or Network not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port, net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    return jsonutils.loads(resp_obj)
Example #47
0
 def _test_create_lrouter_dnat_rule(self, func):
     tenant_id = 'pippo'
     lrouter = nvplib.create_lrouter(self.fake_cluster,
                                     tenant_id,
                                     'fake_router',
                                     '192.168.0.1')
     nat_rule = func(self.fake_cluster, lrouter['uuid'], '10.0.0.99',
                     match_criteria={'destination_ip_addresses':
                                     '192.168.0.5'})
     uri = nvplib._build_uri_path(nvplib.LROUTERNAT_RESOURCE,
                                  nat_rule['uuid'],
                                  lrouter['uuid'])
     return json.loads(nvplib.do_single_request("GET", uri,
                                                cluster=self.fake_cluster))
Example #48
0
def unplug_interface(controller, network, port):
    uri = "/ws.v1/lswitch/" + network + "/lport/" + port + "/attachment"
    lport_obj = {"type": "NoAttachment"}
    try:
        resp_obj = do_single_request("PUT",
                                     uri,
                                     jsonutils.dumps(lport_obj),
                                     controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Port or Network not found, Error: %s" % str(e))
        raise exception.PortNotFound(port_id=port, net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    return jsonutils.loads(resp_obj)
 def _check_is_authorize_user(self,request,info):
     if 'resource' in info and info['resource']=='users' and 'method' in info  \
     and info['method']=='PUT' and 'userid' in info and info['userid'] \
     and 'action' in info and info['action']=='authorize_user':
         print '[auth] authorize user'
         userid=info['userid']
         body=json.loads(request.body)
         session=Session()
         try:
             session.query(User).filter_by(id=userid).one()
         except:
             raise webob.exc.HTTPBadRequest(detail="User doesn't exist.")
         #body : 'vnspolciy' , 'vcspolicy' , 'vnsitespolicy' , 'vnlinkspolicy' , 'sitespolicy'
         if 'vnspolicy' in body['user']:
             vnspolicy=body['user']['vnspolicy']
             for vnpolicy_key,vnpolicy_value in vnspolicy.iteritems():
                 if vnpolicy_key in ['create_vn',]:
                     session=Session()
                     query=session.query(VnsPolicy).filter_by(userid=userid)
                     if query.count():
                         userpolicy=query.one()
                         userpolicy.update({vnpolicy_key:attributes.convert_to_boolean(vnpolicy_value)})
                         session.commit()
                     else:
                         vnkwargs={vnpolicy_key:attributes.convert_to_boolean(vnpolicy_value)}
                         session.add(VnsPolicy(id=uuid4().get_hex(),userid=userid,**vnkwargs))
                         session.commit()
         if 'vcspolicy' in body['user']:
             vcspolicy=body['user']['vcspolicy']
             for vcpolicy_key,vcpolicy_value in vcspolicy.iteritems():
                 if vcpolicy_key in ['create_vc',]:
                     session=Session()
                     query=session.query(VcsPolicy).filter_by(userid=userid)
                     if query.count():
                         userpolicy=query.one()
                         userpolicy.update({vcpolicy_key:attributes.convert_to_boolean(vcpolicy_value)})
                         session.commit()
                     else:
                         vckwargs={vcpolicy_key:attributes.convert_to_boolean(vcpolicy_value)}
                         session.add(VcsPolicy(id=uuid4().get_hex(),userid=userid,**vckwargs))
                         session.commit()
         if 'vnsitespolicy' in body['user']:
             pass
         if 'vnlinkspolicy' in body['user']:
             pass
         if 'sitespolicy' in body['user']:
             pass
         return True
     return False
Example #50
0
 def _make_agent_dict(self, agent, fields=None):
     attr = ext_agent.RESOURCE_ATTRIBUTE_MAP.get(
         ext_agent.RESOURCE_NAME + 's')
     res = dict((k, agent[k]) for k in attr
                if k not in ['alive', 'configurations'])
     res['alive'] = not self._is_agent_down(res['heartbeat_timestamp'])
     try:
         res['configurations'] = jsonutils.loads(agent['configurations'])
     except Exception:
         msg = _('Configurations for agent %(agent_type)s on host %(host)s'
                 ' are invalid.')
         LOG.warn(msg, {'agent_type': res['agent_type'],
                        'host': res['host']})
         res['configurations'] = {}
     return self._fields(res, fields)
Example #51
0
def query_ports(controller, network, relations=None, fields="*", filters=None):
    uri = "/ws.v1/lswitch/" + network + "/lport?"
    if relations:
        uri += "relations=%s" % relations
    uri += "&fields=%s" % fields
    if filters and "attachment" in filters:
        uri += "&attachment_vif_uuid=%s" % filters["attachment"]
    try:
        resp_obj = do_single_request("GET", uri, controller=controller)
    except NvpApiClient.ResourceNotFound as e:
        LOG.error("Network not found, Error: %s" % str(e))
        raise exception.NetworkNotFound(net_id=network)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    return jsonutils.loads(resp_obj)["results"]
Example #52
0
    def _unpack_json_msg(self, msg):
        """Load the JSON data in msg if msg.content_type indicates that it
           is necessary.  Put the loaded data back into msg.content and
           update msg.content_type appropriately.

        A Qpid Message containing a dict will have a content_type of
        'amqp/map', whereas one containing a string that needs to be converted
        back from JSON will have a content_type of JSON_CONTENT_TYPE.

        :param msg: a Qpid Message object
        :returns: None
        """
        if msg.content_type == JSON_CONTENT_TYPE:
            msg.content = jsonutils.loads(msg.content)
            msg.content_type = 'amqp/map'
Example #53
0
    def test_extend_get_resource_response(self):
        def extend_response_data(req, res):
            data = jsonutils.loads(res.body)
            data['FOXNSOX:extended_key'] = req.GET.get('extended_key')
            res.body = jsonutils.dumps(data)
            return res

        app = self._setup_app_with_request_handler(extend_response_data, 'GET')
        response = app.get("/dummy_resources/1?extended_key=extended_data")

        self.assertEqual(200, response.status_int)
        response_data = jsonutils.loads(response.body)
        self.assertEqual('extended_data',
                         response_data['FOXNSOX:extended_key'])
        self.assertEqual('knox', response_data['fort'])
Example #54
0
def check_default_transport_zone(c):
    """Make sure the default transport zone specified in the config exists"""
    msg = []
    # This will throw an exception on failure and that's ok since it will
    # just propogate to the cli.
    resp = do_single_request("GET",
                             "/ws.v1/transport-zone?uuid=%s" %
                             c.default_tz_uuid,
                             controller=c)
    result = jsonutils.loads(resp)
    if int(result["result_count"]) == 0:
        msg.append("Unable to find zone \"%s\" for controller \"%s\"" %
                   (c.default_tz_uuid, c.name))
    if len(msg) > 0:
        raise Exception(' '.join(msg))
Example #55
0
    def _unpack_json_msg(self, msg):
        """Load the JSON data in msg if msg.content_type indicates that it
           is necessary.  Put the loaded data back into msg.content and
           update msg.content_type appropriately.

        A Qpid Message containing a dict will have a content_type of
        'amqp/map', whereas one containing a string that needs to be converted
        back from JSON will have a content_type of JSON_CONTENT_TYPE.

        :param msg: a Qpid Message object
        :returns: None
        """
        if msg.content_type == JSON_CONTENT_TYPE:
            msg.content = jsonutils.loads(msg.content)
            msg.content_type = 'amqp/map'
Example #56
0
def query_networks(controller, tenant_id, fields="*", tags=None):
    uri = "/ws.v1/lswitch?fields=%s" % fields
    if tags:
        for t in tags:
            uri += "&tag=%s&tag_scope=%s" % (t[0], t[1])
    try:
        resp_obj = do_single_request("GET", uri, controller=controller)
    except NvpApiClient.NvpApiException as e:
        raise exception.QuantumException()
    if not resp_obj:
        return []
    lswitches = jsonutils.loads(resp_obj)["results"]
    nets = [{
        'net-id': lswitch["uuid"],
        'net-name': lswitch["display_name"]
    } for lswitch in lswitches]
    return nets