def default(self, data): def sanitizer(obj): if isinstance(obj, datetime.datetime): _dtime = obj - datetime.timedelta(microseconds=obj.microsecond) return _dtime.isoformat() return obj return jsonutils.dumps(data, default=sanitizer)
def serialize_remote_exception(failure_info): """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] 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 __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 authenticate(self): if self.auth_strategy != 'keystone': raise exception.Unauthorized(message='unknown auth strategy') body = {'auth': {'passwordCredentials': {'username': self.username, 'password': self.password, }, 'tenantName': self.tenant_name, }, } token_url = self.auth_url + "/tokens" # Make sure we follow redirects when trying to reach Keystone tmp_follow_all_redirects = self.follow_all_redirects self.follow_all_redirects = True try: resp, body = self._cs_request(token_url, "POST", body=jsonutils.dumps(body), content_type="application/json") finally: self.follow_all_redirects = tmp_follow_all_redirects status_code = self.get_status_code(resp) if status_code != 200: raise exception.Unauthorized(message=body) if body: try: body = jsonutils.loads(body) except ValueError: pass else: body = None self._extract_service_catalog(body)
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 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 wait(self): LOG.info('nozzle worker starting...') while True: socks = dict(self.poller.poll()) if socks.get(self.broadcast) == zmq.POLLIN: msg_type, msg_id, msg_body = self.broadcast.recv_multipart() message = jsonutils.loads(msg_body) LOG.info('Received request: %s', message) response_msg = {'code': 200, 'message': 'OK'} # check input message if 'cmd' not in message or 'args' not in message: LOG.warn("Error. 'cmd' or 'args' not in message") response_msg['code'] = 500 response_msg['message'] = "missing 'cmd' or 'args' field" self.feedback.send_multipart([msg_type, msg_id, jsonutils.dumps( response_msg)]) break if message['args']['protocol'] == 'http': try: self.ngx_configurer.do_config(message) except exception.NginxConfigureError, e: response_msg['code'] = 500 response_msg['message'] = str(e) elif message['args']['protocol'] == 'tcp': try: self.ha_configurer.do_config(message) except exception.HaproxyConfigureError, e: response_msg['code'] = 500 response_msg['message'] = str(e) else: LOG.exception('Error. Unsupported protocol') response_msg['code'] = 500 response_msg['message'] = "Error: unsupported protocol" # Send results to feedback response_msg['cmd'] = message['cmd'] response_msg['uuid'] = message['args']['uuid'] self.feedback.send_multipart([msg_type, msg_id, jsonutils.dumps(response_msg)])
def client_routine(*args, **kwargs): LOG.info('nozzle client starting...') handler = kwargs['handler'] broadcast = kwargs['broadcast'] poller = zmq.Poller() poller.register(handler, zmq.POLLIN) while True: eventlet.sleep(0) socks = dict(poller.poll(100)) if socks.get(handler) == zmq.POLLIN: msg_type, msg_uuid, msg_json = handler.recv_multipart() response = dict() cli_msg = {'code': 200, 'message': 'OK'} try: msg_body = jsonutils.loads(msg_json) LOG.debug("<<<<<<< client: %s" % msg_body) method = msg_body['method'] args = msg_body['args'] ctxt = context.get_context(**args) method_func = getattr(api, method) result = method_func(ctxt, **args) if result is not None: response.update(result) # send request to worker try: msg = api.get_msg_to_worker(ctxt, method, **args) if msg is not None: request_msg = jsonutils.dumps(msg) LOG.debug(">>>>>>> worker: %s" % request_msg) broadcast.send_multipart([msg_type, msg_uuid, request_msg]) except Exception: pass except Exception as e: cli_msg['code'] = 500 cli_msg['message'] = str(e) LOG.exception(cli_msg['message']) response.update(cli_msg) response_msg = jsonutils.dumps(response) LOG.debug(">>>>>>> client: %s" % response_msg) handler.send_multipart([msg_type, msg_uuid, response_msg])
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 str(jsonutils.dumps(data, ensure_ascii=True)) except TypeError: LOG.error(_("JSON serialization failed.")) raise
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( 'nozzle.openstack.common.notification.%s' % message['event_type']) getattr(logger, priority)(jsonutils.dumps(message))
def checker_routine(*args, **kwargs): LOG.info('nozzle checker starting...') broadcast = kwargs['broadcast'] states = [state.CREATING, state.UPDATING, state.DELETING] while True: eventlet.sleep(6) msg_type = 'lb' msg_uuid = utils.str_uuid() try: ctxt = context.get_admin_context() all_load_balancers = db.load_balancer_get_all(ctxt) transient_load_balancers = filter(lambda x: x.state in states, all_load_balancers) for load_balancer_ref in transient_load_balancers: try: result = dict() message = dict() if load_balancer_ref.state == state.CREATING: message['cmd'] = 'create_lb' result = api.format_msg_to_worker(load_balancer_ref) elif load_balancer_ref.state == state.UPDATING: message['cmd'] = 'update_lb' result = api.format_msg_to_worker(load_balancer_ref) elif load_balancer_ref.state == state.DELETING: message['cmd'] = 'delete_lb' result['user_id'] = load_balancer_ref['user_id'] result['tenant_id'] = load_balancer_ref['project_id'] result['uuid'] = load_balancer_ref['uuid'] result['protocol'] = load_balancer_ref['protocol'] message['args'] = result request_msg = jsonutils.dumps(message) LOG.debug(">>>>>>> worker: %s" % request_msg) broadcast.send_multipart([msg_type, msg_uuid, request_msg]) except Exception as exp: LOG.exception(str(exp)) continue except Exception as exp: LOG.exception(str(exp)) continue
def get_data(self, parsed_args): nozzle_client = self.get_client() obj_shower = getattr(nozzle_client, "show_%s" % self.resource) data = obj_shower(parsed_args.id) if data['code'] != 200: raise Exception("error: %s" % data['message']) info = data['data'] for k, v in info.iteritems(): if v is None: info[k] = "" elif isinstance(v, list): value = "" for item in v: if value: value += "\n" if isinstance(item, dict): value += jsonutils.dumps(item) else: value += str(item) info[k] = value return zip(*sorted(info.iteritems()))
def __call__(self, req): """Return all nozzle API versions.""" version_objs = [ { "id": "v1.0", "status": "DEPRECATED", }, { "id": "v2.0", "status": "CURRENT", }, ] if req.path != '/': return webob.exc.HTTPNotFound() reponse = dict(versions=version_objs) body = jsonutils.dumps(reponse) reponse = webob.Response() reponse.body = body return reponse
def get_data(self, parsed_args): nozzle_client = self.get_client() body = self.make_request_body(parsed_args) obj_creator = getattr(nozzle_client, "create_%s" % self.resource) data = obj_creator(body) ## deal with result if data['code'] != 200: raise Exception("error: %s" % data['message']) info = data['data'] for k, v in info.iteritems(): if isinstance(v, list): value = "" for item in v: if value: value += "\n" if isinstance(item, dict): value += jsonutils.dumps(item) else: value += str(item) info[k] = value elif v is None: info[k] = "" return zip(*sorted(info.iteritems()))
def _to_json(self, data): return jsonutils.dumps(data)
def check_serialize(msg): """Make sure a message intended for rpc can be serialized.""" jsonutils.dumps(msg)