示例#1
0
    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)
示例#2
0
    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)])
示例#3
0
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])
示例#4
0
def worker_routine(*args, **kwargs):
    LOG.info('nozzle worker starting...')

    feedback = kwargs['feedback']
    poller = zmq.Poller()
    poller.register(feedback, zmq.POLLIN)

    while True:
        eventlet.sleep(0)
        socks = dict(poller.poll(100))
        if socks.get(feedback) == zmq.POLLIN:
            msg_type, msg_uuid, msg_json = feedback.recv_multipart()
            msg_body = jsonutils.loads(msg_json)
            LOG.debug("<<<<<<< worker: %s" % msg_body)
            # update load balancer's state
            try:
                args = msg_body
                ctxt = context.get_admin_context()
                api.update_load_balancer_state(ctxt, **args)
            except Exception as exp:
                LOG.exception(str(exp))
                continue
示例#5
0
def deserialize_remote_exception(conf, data):
    failure = jsonutils.loads(str(data))

    trace = failure.get('tb', [])
    message = failure.get('message', "") + "\n" + "\n".join(trace)
    name = failure.get('class')
    module = failure.get('module')

    # NOTE(ameade): We DO NOT want to allow just any module to be imported, in
    # order to prevent arbitrary code execution.
    if not module in conf.allowed_rpc_exception_modules:
        return RemoteError(name, failure.get('message'), trace)

    try:
        mod = importutils.import_module(module)
        klass = getattr(mod, name)
        if not issubclass(klass, Exception):
            raise TypeError("Can only deserialize Exceptions")

        failure = klass(**failure.get('kwargs', {}))
    except (AttributeError, TypeError, ImportError):
        return RemoteError(name, failure.get('message'), trace)

    ex_type = type(failure)
    str_override = lambda self: message
    new_ex_type = type(ex_type.__name__ + "_Remote", (ex_type,),
                       {'__str__': str_override, '__unicode__': str_override})
    try:
        # NOTE(ameade): Dynamically create a new exception type and swap it in
        # as the new type for the exception. This only works on user defined
        # Exceptions and not core python exceptions. This is important because
        # we cannot necessarily change an exception message so we must override
        # the __str__ method.
        failure.__class__ = new_ex_type
    except TypeError as e:
        # NOTE(ameade): If a core exception then just add the traceback to the
        # first exception argument.
        failure.args = (message,) + failure.args[1:]
    return failure
示例#6
0
 def _from_json(self, datastring):
     return jsonutils.loads(datastring)
示例#7
0
文件: wsgi.py 项目: ljjjustin/nozzle
 def _from_json(self, datastring):
     try:
         return jsonutils.loads(datastring)
     except ValueError:
         msg = _("cannot understand JSON")
         raise exception.MalformedRequestBody(reason=msg)
示例#8
0
def _deserialize(data):
    """
    Deserialization wrapper
    """
    LOG.debug(_("Deserializing: %s"), data)
    return jsonutils.loads(data)