def plug_interface(controller, network, port, type, attachment=None): uri = "/ws.v1/lswitch/" + network + "/lport/" + port + "/attachment" lport_obj = {} if attachment: lport_obj["vif_uuid"] = attachment lport_obj["type"] = type 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.Conflict as e: LOG.error("Conflict while making attachment to port, " "Error: %s" % str(e)) raise exception.AlreadyAttached(att_id=attachment, port_id=port, net_id=network, att_port_id="UNKNOWN") except NvpApiClient.NvpApiException as e: raise exception.QuantumException() result = jsonutils.dumps(resp_obj) return result
def test_list_credentials(self): """ Test list credentials """ # Create Credential before listing LOG.debug("test_list_credentials - START") req_body1 = jsonutils.dumps(self.test_credential_data) create_response1 = self.test_app.post(self.credential_path, req_body1, content_type=self.contenttype) req_body2 = jsonutils.dumps( {"credential": {"credential_name": "cred9", "user_name": "newUser2", "password": "******"}} ) create_response2 = self.test_app.post(self.credential_path, req_body2, content_type=self.contenttype) index_response = self.test_app.get(self.credential_path) index_resp_body = wsgi.Serializer().deserialize(index_response.body, self.contenttype) self.assertEqual(200, index_response.status_int) # CLean Up - Deletion of the Credentials resp_body1 = wsgi.Serializer().deserialize(create_response1.body, self.contenttype) delete_path1_temp = self.cred_second_path + resp_body1["credentials"]["credential"]["id"] delete_path1 = str(delete_path1_temp) resp_body2 = wsgi.Serializer().deserialize(create_response2.body, self.contenttype) list_all_credential = [resp_body1["credentials"]["credential"], resp_body2["credentials"]["credential"]] self.assertTrue(index_resp_body["credentials"][0] in list_all_credential) self.assertTrue(index_resp_body["credentials"][1] in list_all_credential) delete_path2_temp = self.cred_second_path + resp_body2["credentials"]["credential"]["id"] delete_path2 = str(delete_path2_temp) self.tearDownCredential(delete_path1) self.tearDownCredential(delete_path2) LOG.debug("test_list_credentials - END")
def test_update_credential(self): """ Test update credential """ LOG.debug("test_update_credential - START") req_body = jsonutils.dumps(self.test_credential_data) index_response = self.test_app.post(self.credential_path, req_body, content_type=self.contenttype) resp_body = wsgi.Serializer().deserialize(index_response.body, self.contenttype) rename_req_body = jsonutils.dumps({ 'credential': { 'credential_name': 'cred3', 'user_name': 'RenamedUser', 'password': '******', }, }) rename_path_temp = (self.cred_second_path + resp_body['credentials']['credential']['id']) rename_path = str(rename_path_temp) rename_response = self.test_app.put(rename_path, rename_req_body, content_type=self.contenttype) rename_resp_dict = wsgi.Serializer().deserialize( rename_response.body, self.contenttype) self.assertEqual(rename_resp_dict['credentials']['credential']['name'], 'cred3') self.assertEqual( rename_resp_dict['credentials']['credential']['password'], self.test_credential_data['credential']['password']) self.assertEqual(200, rename_response.status_int) # Clean Up - Delete the Credentials self.tearDownCredential(rename_path) LOG.debug("test_update_credential - END")
def test_update_qos(self): """ Test update qos """ LOG.debug("test_update_qos - START") req_body = jsonutils.dumps(self.test_qos_data) index_response = self.test_app.post(self.qos_path, req_body, content_type=self.contenttype) resp_body = wsgi.Serializer().deserialize(index_response.body, self.contenttype) rename_req_body = jsonutils.dumps({ 'qos': { 'qos_name': 'cisco_rename_qos', 'qos_desc': { 'PPS': 50, 'TTL': 5, }, }, }) rename_path_temp = (self.qos_second_path + resp_body['qoss']['qos']['id']) rename_path = str(rename_path_temp) rename_response = self.test_app.put(rename_path, rename_req_body, content_type=self.contenttype) self.assertEqual(200, rename_response.status_int) rename_resp_dict = wsgi.Serializer().deserialize( rename_response.body, self.contenttype) self.assertEqual(rename_resp_dict['qoss']['qos']['name'], 'cisco_rename_qos') self.tearDownQos(rename_path) LOG.debug("test_update_qos - END")
def test_update_credential(self): """ Test update credential """ LOG.debug("test_update_credential - START") req_body = jsonutils.dumps(self.test_credential_data) index_response = self.test_app.post( self.credential_path, req_body, content_type=self.contenttype) resp_body = wsgi.Serializer().deserialize( index_response.body, self.contenttype) rename_req_body = jsonutils.dumps({ 'credential': { 'credential_name': 'cred3', 'user_name': 'RenamedUser', 'password': '******', }, }) rename_path_temp = (self.cred_second_path + resp_body['credentials']['credential']['id']) rename_path = str(rename_path_temp) rename_response = self.test_app.put(rename_path, rename_req_body, content_type=self.contenttype) rename_resp_dict = wsgi.Serializer().deserialize(rename_response.body, self.contenttype) self.assertEqual(rename_resp_dict['credentials']['credential']['name'], 'cred3') self.assertEqual( rename_resp_dict['credentials']['credential']['password'], self.test_credential_data['credential']['password']) self.assertEqual(200, rename_response.status_int) # Clean Up - Delete the Credentials self.tearDownCredential(rename_path) LOG.debug("test_update_credential - END")
def test_update_qos(self): """ Test update qos """ LOG.debug("test_update_qos - START") req_body = jsonutils.dumps(self.test_qos_data) index_response = self.test_app.post(self.qos_path, req_body, content_type=self.contenttype) resp_body = wsgi.Serializer().deserialize(index_response.body, self.contenttype) rename_req_body = jsonutils.dumps({ 'qos': { 'qos_name': 'cisco_rename_qos', 'qos_desc': { 'PPS': 50, 'TTL': 5, }, }, }) rename_path_temp = (self.qos_second_path + resp_body['qoss']['qos']['id']) rename_path = str(rename_path_temp) rename_response = self.test_app.put(rename_path, rename_req_body, content_type=self.contenttype) self.assertEqual(200, rename_response.status_int) rename_resp_dict = wsgi.Serializer().deserialize(rename_response.body, self.contenttype) self.assertEqual(rename_resp_dict['qoss']['qos']['name'], 'cisco_rename_qos') self.tearDownQos(rename_path) LOG.debug("test_update_qos - END")
def test_list_qoss(self): """ Test list qoss """ LOG.debug("test_list_qoss - START") req_body1 = jsonutils.dumps(self.test_qos_data) create_resp1 = self.test_app.post(self.qos_path, req_body1, content_type=self.contenttype) req_body2 = jsonutils.dumps({"qos": {"qos_name": "cisco_test_qos2", "qos_desc": {"PPS": 50, "TTL": 5}}}) create_resp2 = self.test_app.post(self.qos_path, req_body2, content_type=self.contenttype) index_response = self.test_app.get(self.qos_path) index_resp_body = wsgi.Serializer().deserialize(index_response.body, self.contenttype) self.assertEqual(200, index_response.status_int) # Clean Up - Delete the qos's resp_body1 = wsgi.Serializer().deserialize(create_resp1.body, self.contenttype) qos_path1_temp = self.qos_second_path + resp_body1["qoss"]["qos"]["id"] qos_path1 = str(qos_path1_temp) resp_body2 = wsgi.Serializer().deserialize(create_resp2.body, self.contenttype) list_all_qos = [resp_body1["qoss"]["qos"], resp_body2["qoss"]["qos"]] self.assertTrue(index_resp_body["qoss"][0] in list_all_qos) self.assertTrue(index_resp_body["qoss"][1] in list_all_qos) qos_path2_temp = self.qos_second_path + resp_body2["qoss"]["qos"]["id"] qos_path2 = str(qos_path2_temp) self.tearDownQos(qos_path1) self.tearDownQos(qos_path2) LOG.debug("test_list_qoss - END")
def __call__(self, target, creds): """ Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly 'True'. """ url = ("http:" + self.match) % target data = {"target": jsonutils.dumps(target), "credentials": jsonutils.dumps(creds)} post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return f.read() == "True"
def _check_http(self, match, target_dict, cred_dict): """Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly 'True'. A custom brain using response codes could easily be implemented. """ url = match % target_dict data = {"target": jsonutils.dumps(target_dict), "credentials": jsonutils.dumps(cred_dict)} post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return f.read() == "True"
def _pack_json_msg(self, msg): """Qpid cannot serialize dicts containing strings longer than 65535 characters. This function dumps the message content to a JSON string, which Qpid is able to handle. :param msg: May be either a Qpid Message object or a bare dict. :returns: A Qpid Message with its content field JSON encoded. """ try: msg.content = jsonutils.dumps(msg.content) except AttributeError: # Need to have a Qpid message so we can set the content_type. msg = qpid_messaging.Message(jsonutils.dumps(msg)) msg.content_type = JSON_CONTENT_TYPE return msg
def _check_http(brain, match_kind, match, target_dict, cred_dict): """Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly 'True'. A custom brain using response codes could easily be implemented. """ url = 'http:' + (match % target_dict) data = { 'target': jsonutils.dumps(target_dict), 'credentials': jsonutils.dumps(cred_dict) } post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return f.read() == "True"
def routers_updated(self, context, routers): if routers: LOG.debug(_('Nofity agent routers were updated:\n %s'), jsonutils.dumps(routers, indent=5)) self.cast(context, self.make_msg('routers_updated', routers=routers), topic=self.topic)
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 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
def test_update_qos(self): """ Test update qos """ LOG.debug("test_update_qos - START") req_body = jsonutils.dumps(self.test_qos_data) index_response = self.test_app.post(self.qos_path, req_body, content_type=self.contenttype) resp_body = wsgi.Serializer().deserialize(index_response.body, self.contenttype) rename_req_body = jsonutils.dumps({"qos": {"qos_name": "cisco_rename_qos", "qos_desc": {"PPS": 50, "TTL": 5}}}) rename_path_temp = self.qos_second_path + resp_body["qoss"]["qos"]["id"] rename_path = str(rename_path_temp) rename_response = self.test_app.put(rename_path, rename_req_body, content_type=self.contenttype) self.assertEqual(200, rename_response.status_int) rename_resp_dict = wsgi.Serializer().deserialize(rename_response.body, self.contenttype) self.assertEqual(rename_resp_dict["qoss"]["qos"]["name"], "cisco_rename_qos") self.tearDownQos(rename_path) LOG.debug("test_update_qos - END")
def __init__(self, session, node_name, node_opts=None): """Init the Publisher class with the exchange_name, routing_key, and other options """ self.sender = None self.session = session addr_opts = { "create": "always", "node": { "type": "topic", "x-declare": { "durable": False, # auto-delete isn't implemented for exchanges in qpid, # but put in here anyway "auto-delete": True, }, }, } if node_opts: addr_opts["node"]["x-declare"].update(node_opts) self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts)) self.reconnect(session)
def test_handler_invalid_data(self): network_id = 'cccccccc-cccc-cccc-cccc-cccccccccccc' ip_address = '192.168.x.x' lease_remaining = 120 json_rep = jsonutils.dumps( dict(network_id=network_id, lease_remaining=lease_remaining, ip_address=ip_address)) handler = mock.Mock() mock_sock = mock.Mock() mock_sock.recv.return_value = json_rep relay = dhcp_agent.DhcpLeaseRelay(handler) with mock.patch('quantum.openstack.common.' 'uuidutils.is_uuid_like') as validate: validate.return_value = False with mock.patch.object(dhcp_agent.LOG, 'warn') as log: relay._handler(mock_sock, mock.Mock()) mock_sock.assert_has_calls( [mock.call.recv(1024), mock.call.close()]) self.assertFalse(handler.called) self.assertTrue(log.called)
def format(self, record): message = {'message': record.getMessage(), 'asctime': self.formatTime(record, self.datefmt), 'name': record.name, 'msg': record.msg, 'args': record.args, 'levelname': record.levelname, 'levelno': record.levelno, 'pathname': record.pathname, 'filename': record.filename, 'module': record.module, 'lineno': record.lineno, 'funcname': record.funcName, 'created': record.created, 'msecs': record.msecs, 'relative_created': record.relativeCreated, 'thread': record.thread, 'thread_name': record.threadName, 'process_name': record.processName, 'process': record.process, 'traceback': None} if hasattr(record, 'extra'): message['extra'] = record.extra if record.exc_info: message['traceback'] = self.formatException(record.exc_info) return jsonutils.dumps(message)
def __init__(self, session, callback, node_name, node_opts, link_name, link_opts): """Declare a queue on an amqp session. 'session' is the amqp session to use 'callback' is the callback to call when messages are received 'node_name' is the first part of the Qpid address string, before ';' 'node_opts' will be applied to the "x-declare" section of "node" in the address string. 'link_name' goes into the "name" field of the "link" in the address string 'link_opts' will be applied to the "x-declare" section of "link" in the address string. """ self.callback = callback self.receiver = None self.session = None addr_opts = { "create": "always", "node": {"type": "topic", "x-declare": {"durable": True, "auto-delete": True}}, "link": { "name": link_name, "durable": True, "x-declare": {"durable": False, "auto-delete": True, "exclusive": False}, }, } addr_opts["node"]["x-declare"].update(node_opts) addr_opts["link"]["x-declare"].update(link_opts) self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts)) self.reconnect(session)
def serialize_remote_exception(failure_info, log_failure=True): """Prepares exception data to be sent over rpc. Failure_info should be a sys.exc_info() tuple. """ tb = traceback.format_exception(*failure_info) failure = failure_info[1] if log_failure: LOG.error(_("Returning exception %s to caller"), unicode(failure)) LOG.error(tb) kwargs = {} if hasattr(failure, 'kwargs'): kwargs = failure.kwargs data = { 'class': str(failure.__class__.__name__), 'module': str(failure.__class__.__module__), 'message': unicode(failure), 'tb': tb, 'args': failure.args, 'kwargs': kwargs } json_data = jsonutils.dumps(data) return json_data
def test_returns_404_for_non_existent_resource(self): action_name = "add_tweedle" action_params = dict(name="Beetle") req_body = jsonutils.dumps({action_name: action_params}) response = self.extension_app.post("/asdf/1/action", req_body, content_type="application/json", status="*") self.assertEqual(404, response.status_int)
def test_handler_invalid_data(self): network_id = 'cccccccc-cccc-cccc-cccc-cccccccccccc' ip_address = '192.168.x.x' lease_remaining = 120 json_rep = jsonutils.dumps( dict(network_id=network_id, lease_remaining=lease_remaining, ip_address=ip_address)) handler = mock.Mock() mock_sock = mock.Mock() mock_sock.recv.return_value = json_rep relay = dhcp_agent.DhcpLeaseRelay(handler) with mock.patch.object(relay, '_validate_field') as validate: validate.side_effect = ValueError with mock.patch.object(dhcp_agent.LOG, 'warn') as log: relay._handler(mock_sock, mock.Mock()) mock_sock.assert_has_calls( [mock.call.recv(1024), mock.call.close()]) self.assertFalse(handler.called) self.assertTrue(log.called)
def format(self, record): message = { 'message': record.getMessage(), 'asctime': self.formatTime(record, self.datefmt), 'name': record.name, 'msg': record.msg, 'args': record.args, 'levelname': record.levelname, 'levelno': record.levelno, 'pathname': record.pathname, 'filename': record.filename, 'module': record.module, 'lineno': record.lineno, 'funcname': record.funcName, 'created': record.created, 'msecs': record.msecs, 'relative_created': record.relativeCreated, 'thread': record.thread, 'thread_name': record.threadName, 'process_name': record.processName, 'process': record.process, 'traceback': None } if hasattr(record, 'extra'): message['extra'] = record.extra if record.exc_info: message['traceback'] = self.formatException(record.exc_info) return jsonutils.dumps(message)
def format(self, record): message = { "message": record.getMessage(), "asctime": self.formatTime(record, self.datefmt), "name": record.name, "msg": record.msg, "args": record.args, "levelname": record.levelname, "levelno": record.levelno, "pathname": record.pathname, "filename": record.filename, "module": record.module, "lineno": record.lineno, "funcname": record.funcName, "created": record.created, "msecs": record.msecs, "relative_created": record.relativeCreated, "thread": record.thread, "thread_name": record.threadName, "process_name": record.processName, "process": record.process, "traceback": None, } if hasattr(record, "extra"): message["extra"] = record.extra if record.exc_info: message["traceback"] = self.formatException(record.exc_info) return jsonutils.dumps(message)
def serialize_remote_exception(failure_info, log_failure=True): """Prepares exception data to be sent over rpc. Failure_info should be a sys.exc_info() tuple. """ tb = traceback.format_exception(*failure_info) failure = failure_info[1] if log_failure: LOG.error(_("Returning exception %s to caller"), six.text_type(failure)) LOG.error(tb) kwargs = {} if hasattr(failure, 'kwargs'): kwargs = failure.kwargs data = { 'class': str(failure.__class__.__name__), 'module': str(failure.__class__.__module__), 'message': six.text_type(failure), 'tb': tb, 'args': failure.args, 'kwargs': kwargs } json_data = jsonutils.dumps(data) return json_data
def __call__(self, target, creds): """ Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly 'True'. """ url = ('http:' + self.match) % target data = { 'target': jsonutils.dumps(target), 'credentials': jsonutils.dumps(creds) } post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return f.read() == "True"
def lease_update(cls): network_id = os.environ.get(cls.QUANTUM_NETWORK_ID_KEY) dhcp_relay_socket = os.environ.get(cls.QUANTUM_RELAY_SOCKET_PATH_KEY) action = sys.argv[1] if action not in ('add', 'del', 'old'): sys.exit() mac_address = sys.argv[2] ip_address = sys.argv[3] if action == 'del': lease_remaining = 0 else: lease_remaining = int(os.environ.get('DNSMASQ_TIME_REMAINING', 0)) data = dict(network_id=network_id, mac_address=mac_address, ip_address=ip_address, lease_remaining=lease_remaining) if os.path.exists(dhcp_relay_socket): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(dhcp_relay_socket) sock.send(jsonutils.dumps(data)) sock.close()
def lease_update(cls): network_id = os.environ.get(cls.QUANTUM_NETWORK_ID_KEY) dhcp_relay_socket = os.environ.get(cls.QUANTUM_RELAY_SOCKET_PATH_KEY) action = sys.argv[1] if action not in ("add", "del", "old"): sys.exit() mac_address = sys.argv[2] ip_address = sys.argv[3] if action == "del": lease_remaining = 0 else: lease_remaining = int(os.environ.get("DNSMASQ_TIME_REMAINING", 0)) data = dict( network_id=network_id, mac_address=mac_address, ip_address=ip_address, lease_remaining=lease_remaining ) if os.path.exists(dhcp_relay_socket): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(dhcp_relay_socket) sock.send(jsonutils.dumps(data)) sock.close()
def serialize_msg(raw_msg): # NOTE(russellb) See the docstring for _RPC_ENVELOPE_VERSION for more # information about this format. msg = {_VERSION_KEY: _RPC_ENVELOPE_VERSION, _MESSAGE_KEY: jsonutils.dumps(raw_msg)} return msg
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
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
def port_release(self, fabric, port_mac): LOG.debug(_("Port Release for %(port_mac)s on fabric %(fabric)s"), {'port_mac': port_mac, 'fabric': fabric}) msg = jsonutils.dumps({'action': 'port_release', 'fabric': fabric, 'ref_by': 'mac_address', 'mac': port_mac}) self.send_msg(msg)
def test_extended_action_for_deleting_extra_data(self): action_name = 'FOXNSOX:delete_tweedle' action_params = dict(name='Bailey') req_body = jsonutils.dumps({action_name: action_params}) response = self.extension_app.post("/dummy_resources/1/action", req_body, content_type='application/json') self.assertEqual("Tweedle Bailey Deleted.", response.body)
def test_extended_action_for_adding_extra_data(self): action_name = 'FOXNSOX:add_tweedle' action_params = dict(name='Beetle') req_body = jsonutils.dumps({action_name: action_params}) response = self.extension_app.post('/dummy_resources/1/action', req_body, content_type='application/json') self.assertEqual("Tweedle Beetle Added.", response.body)
def routers_updated(self, context, routers): if routers: LOG.debug(_('Notify agent routers were updated:\n %s'), jsonutils.dumps(routers, indent=5)) self.cast(context, self.make_msg('routers_updated', routers=routers), topic=self.topic)
def test_list_credentials(self): """ Test list credentials """ #Create Credential before listing LOG.debug("test_list_credentials - START") req_body1 = jsonutils.dumps(self.test_credential_data) create_response1 = self.test_app.post(self.credential_path, req_body1, content_type=self.contenttype) req_body2 = jsonutils.dumps({ 'credential': { 'credential_name': 'cred9', 'user_name': 'newUser2', 'password': '******', }, }) create_response2 = self.test_app.post(self.credential_path, req_body2, content_type=self.contenttype) index_response = self.test_app.get(self.credential_path) index_resp_body = wsgi.Serializer().deserialize( index_response.body, self.contenttype) self.assertEqual(200, index_response.status_int) #CLean Up - Deletion of the Credentials resp_body1 = wsgi.Serializer().deserialize(create_response1.body, self.contenttype) delete_path1_temp = (self.cred_second_path + resp_body1['credentials']['credential']['id']) delete_path1 = str(delete_path1_temp) resp_body2 = wsgi.Serializer().deserialize(create_response2.body, self.contenttype) list_all_credential = [ resp_body1['credentials']['credential'], resp_body2['credentials']['credential'] ] self.assertTrue( index_resp_body['credentials'][0] in list_all_credential) self.assertTrue( index_resp_body['credentials'][1] in list_all_credential) delete_path2_temp = (self.cred_second_path + resp_body2['credentials']['credential']['id']) delete_path2 = str(delete_path2_temp) self.tearDownCredential(delete_path1) self.tearDownCredential(delete_path2) LOG.debug("test_list_credentials - END")
def notify(_context, message): """Notifies the recipient of the desired event given the model. Log notifications using openstack's default logging system""" priority = message.get('priority', CONF.default_notification_level) priority = priority.lower() logger = logging.getLogger('quantum.openstack.common.notification.%s' % message['event_type']) getattr(logger, priority)(jsonutils.dumps(message))
def __call__(self, environ, start_response): print "[auth]get through Huawei auth." #self._check_token(environ, start_response) try: return self._parse_request(environ,start_response) except webob.exc.HTTPException,resp: resp.body = json.dumps({'QuantumError': str(resp)}) resp.content_type = 'application/json' return resp(environ,start_response)
def define_fabric_mappings(self, interface_mapping): for fabric, phy_interface in interface_mapping.iteritems(): LOG.debug(_("Define Fabric %(fabric)s on interface %(ifc)s"), {'fabric': fabric, 'ifc': phy_interface}) msg = jsonutils.dumps({'action': 'define_fabric_mapping', 'fabric': fabric, 'interface': phy_interface}) self.send_msg(msg)
def test_returns_404_for_non_existent_resource(self): action_name = 'add_tweedle' action_params = dict(name='Beetle') req_body = jsonutils.dumps({action_name: action_params}) response = self.extension_app.post("/asdf/1/action", req_body, content_type='application/json', status='*') self.assertEqual(404, response.status_int)
def serialize_msg(raw_msg, force_envelope=False): if not _SEND_RPC_ENVELOPE and not force_envelope: return raw_msg # NOTE(russellb) See the docstring for _RPC_ENVELOPE_VERSION for more # information about this format. msg = {_VERSION_KEY: _RPC_ENVELOPE_VERSION, _MESSAGE_KEY: jsonutils.dumps(raw_msg)} return msg
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"]
def _test_lease_relay_script_helper(self, action, lease_remaining, path_exists=True): relay_path = '/dhcp/relay_socket' network_id = 'cccccccc-cccc-cccc-cccc-cccccccccccc' mac_address = 'aa:bb:cc:dd:ee:ff' ip_address = '192.168.1.9' json_rep = jsonutils.dumps( dict(network_id=network_id, lease_remaining=lease_remaining, mac_address=mac_address, ip_address=ip_address)) environ = { 'QUANTUM_NETWORK_ID': network_id, 'QUANTUM_RELAY_SOCKET_PATH': relay_path, 'DNSMASQ_TIME_REMAINING': '120', } def fake_environ(name, default=None): return environ.get(name, default) with mock.patch('os.environ') as mock_environ: mock_environ.get.side_effect = fake_environ with mock.patch.object(dhcp, 'sys') as mock_sys: mock_sys.argv = [ 'lease-update', action, mac_address, ip_address, ] with mock.patch('socket.socket') as mock_socket: mock_conn = mock.Mock() mock_socket.return_value = mock_conn with mock.patch('os.path.exists') as mock_exists: mock_exists.return_value = path_exists dhcp.Dnsmasq.lease_update() mock_exists.assert_called_once_with(relay_path) if path_exists: mock_socket.assert_called_once_with( socket.AF_UNIX, socket.SOCK_STREAM) mock_conn.assert_has_calls([ mock.call.connect(relay_path), mock.call.send(json_rep), mock.call.close() ])
def test_returns_404_for_non_existent_action(self): non_existent_action = 'blah_action' action_params = dict(name="test") req_body = jsonutils.dumps({non_existent_action: action_params}) response = self.extension_app.post("/dummy_resources/1/action", req_body, content_type='application/json', status='*') self.assertEqual(404, response.status_int)
def _serialize(data): """ Serialization wrapper We prefer using JSON, but it cannot encode all types. Error if a developer passes us bad data. """ try: return jsonutils.dumps(data, ensure_ascii=True) except TypeError: with excutils.save_and_reraise_exception(): LOG.error(_("JSON serialization failed."))
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