Example #1
0
 def _from_xml(self, datastring):
     if datastring is None:
         return None
     plurals = set(self.metadata.get('plurals', {}))
     try:
         node = self._parseXML(datastring)
         root_tag = self._get_key(node.tag)
         # Deserialize link node was needed by unit test for verifying
         # the request's response
         links = self._get_links(root_tag, node)
         result = self._from_xml_node(node, plurals)
         # root_tag = constants.VIRTUAL_ROOT_KEY and links is not None
         # is not possible because of the way data are serialized.
         if root_tag == constants.VIRTUAL_ROOT_KEY:
             return result
         return dict({root_tag: result}, **links)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             parseError = False
             # Python2.7
             if (hasattr(etree, 'ParseError') and
                 isinstance(e, getattr(etree, 'ParseError'))):
                 parseError = True
             # Python2.6
             elif isinstance(e, expat.ExpatError):
                 parseError = True
             if parseError:
                 msg = _("Cannot understand XML")
                 raise exception.MalformedRequestBody(reason=msg)
Example #2
0
 def _from_xml(self, datastring):
     if datastring is None:
         return None
     plurals = set(self.metadata.get('plurals', {}))
     try:
         node = self._parseXML(datastring)
         root_tag = self._get_key(node.tag)
         # Deserialize link node was needed by unit test for verifying
         # the request's response
         links = self._get_links(root_tag, node)
         result = self._from_xml_node(node, plurals)
         # root_tag = constants.VIRTUAL_ROOT_KEY and links is not None
         # is not possible because of the way data are serialized.
         if root_tag == constants.VIRTUAL_ROOT_KEY:
             return result
         return dict({root_tag: result}, **links)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             parseError = False
             # Python2.7
             if (hasattr(etree, 'ParseError')
                     and isinstance(e, getattr(etree, 'ParseError'))):
                 parseError = True
             # Python2.6
             elif isinstance(e, expat.ExpatError):
                 parseError = True
             if parseError:
                 msg = _("Cannot understand XML")
                 raise exception.MalformedRequestBody(reason=msg)
Example #3
0
 def run_vsctl(self, args, check_error=False):
     full_args = ["sudo", "ovs-vsctl", "--timeout=%d" % self.vsctl_timeout] + args
     try:
         return ovs_utils.execute(full_args, root_helper=None)
     except Exception as e:
         with excutils.save_and_reraise_exception() as ctxt:
             if not check_error:
                 ctxt.reraise = False
Example #4
0
 def run_vsctl(self, args, check_error=False):
     full_args = ["sudo", "ovs-vsctl",
                  "--timeout=%d" % self.vsctl_timeout] + args
     try:
         return ovs_utils.execute(full_args, root_helper=None)
     except Exception as e:
         with excutils.save_and_reraise_exception() as ctxt:
             if not check_error:
                 ctxt.reraise = False
Example #5
0
 def __init__(self, **kwargs):
     try:
         super(VNFSvcException, self).__init__(self.message % kwargs)
         self.msg = self.message % kwargs
     except Exception:
         with excutils.save_and_reraise_exception() as ctxt:
             if not self.use_fatal_exceptions():
                 ctxt.reraise = False
                 # at least get the core message out if something happened
                 super(VNFSvcException, self).__init__(self.message)
Example #6
0
 def __init__(self, **kwargs):
     try:
         super(VNFSvcException, self).__init__(self.message % kwargs)
         self.msg = self.message % kwargs
     except Exception:
         with excutils.save_and_reraise_exception() as ctxt:
             if not self.use_fatal_exceptions():
                 ctxt.reraise = False
                 # at least get the core message out if something happened
                 super(VNFSvcException, self).__init__(self.message)
Example #7
0
def serve_wsgi(cls):

    try:
        service = cls.create()
        service.start()
    except Exception:
        with excutils.save_and_reraise_exception():
            LOG.exception(_('Unrecoverable error: please check log '
                            'for details.'))

    return service
Example #8
0
def serve_wsgi(cls):

    try:
        service = cls.create()
        service.start()
    except Exception:
        with excutils.save_and_reraise_exception():
            LOG.exception(
                _('Unrecoverable error: please check log '
                  'for details.'))

    return service
Example #9
0
def remove_path_on_error(path, remove=delete_if_exists):
    """Protect code that wants to operate on PATH atomically.
    Any exception will cause PATH to be removed.

    :param path: File to work with
    :param remove: Optional function to remove passed path
    """

    try:
        yield
    except Exception:
        with excutils.save_and_reraise_exception():
            remove(path)
Example #10
0
    def deserialize_body(self, request, action):
        try:
            content_type = request.best_match_content_type()
        except exception.InvalidContentType:
            LOG.debug(_("Unrecognized Content-Type provided in request"))
            return {}

        if content_type is None:
            LOG.debug(_("No Content-Type provided in request"))
            return {}

        if not len(request.body) > 0:
            LOG.debug(_("Empty body provided in request"))
            return {}

        try:
            deserializer = self.get_body_deserializer(content_type)
        except exception.InvalidContentType:
            with excutils.save_and_reraise_exception():
                LOG.debug(_("Unable to deserialize body as provided "
                            "Content-Type"))

        return deserializer.deserialize(request.body, action)
Example #11
0
    def deserialize_body(self, request, action):
        try:
            content_type = request.best_match_content_type()
        except exception.InvalidContentType:
            LOG.debug(_("Unrecognized Content-Type provided in request"))
            return {}

        if content_type is None:
            LOG.debug(_("No Content-Type provided in request"))
            return {}

        if not len(request.body) > 0:
            LOG.debug(_("Empty body provided in request"))
            return {}

        try:
            deserializer = self.get_body_deserializer(content_type)
        except exception.InvalidContentType:
            with excutils.save_and_reraise_exception():
                LOG.debug(
                    _("Unable to deserialize body as provided "
                      "Content-Type"))

        return deserializer.deserialize(request.body, action)
Example #12
0
 def call(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             self.logger(e)
Example #13
0
    def _get_socket(self, host, port, backlog):
        bind_addr = (host, port)
        try:
            info = socket.getaddrinfo(bind_addr[0],
                                      bind_addr[1],
                                      socket.AF_UNSPEC,
                                      socket.SOCK_STREAM)[0]
            family = info[0]
            bind_addr = info[-1]
        except Exception:
            LOG.exception(_("Unable to listen on %(host)s:%(port)s"),
                          {'host': host, 'port': port})
            sys.exit(1)

        if CONF.use_ssl:
            if not os.path.exists(CONF.ssl_cert_file):
                raise RuntimeError(_("Unable to find ssl_cert_file "
                                     ": %s") % CONF.ssl_cert_file)

            # ssl_key_file is optional because the key may be embedded in the
            # certificate file
            if CONF.ssl_key_file and not os.path.exists(CONF.ssl_key_file):
                raise RuntimeError(_("Unable to find "
                                     "ssl_key_file : %s") % CONF.ssl_key_file)

            # ssl_ca_file is optional
            if CONF.ssl_ca_file and not os.path.exists(CONF.ssl_ca_file):
                raise RuntimeError(_("Unable to find ssl_ca_file "
                                     ": %s") % CONF.ssl_ca_file)

        def wrap_ssl(sock):
            ssl_kwargs = {
                'server_side': True,
                'certfile': CONF.ssl_cert_file,
                'keyfile': CONF.ssl_key_file,
                'cert_reqs': ssl.CERT_NONE,
            }

            if CONF.ssl_ca_file:
                ssl_kwargs['ca_certs'] = CONF.ssl_ca_file
                ssl_kwargs['cert_reqs'] = ssl.CERT_REQUIRED

            return ssl.wrap_socket(sock, **ssl_kwargs)

        sock = None
        retry_until = time.time() + CONF.retry_until_window
        while not sock and time.time() < retry_until:
            try:
                sock = eventlet.listen(bind_addr,
                                       backlog=backlog,
                                       family=family)
                if CONF.use_ssl:
                    sock = wrap_ssl(sock)

            except socket.error as err:
                with excutils.save_and_reraise_exception() as ctxt:
                    if err.errno == errno.EADDRINUSE:
                        ctxt.reraise = False
                        eventlet.sleep(0.1)
        if not sock:
            raise RuntimeError(_("Could not bind to %(host)s:%(port)s "
                               "after trying for %(time)d seconds") %
                               {'host': host,
                                'port': port,
                                'time': CONF.retry_until_window})
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # sockets can hang around forever without keepalive
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        # This option isn't available in the OS X version of eventlet
        if hasattr(socket, 'TCP_KEEPIDLE'):
            sock.setsockopt(socket.IPPROTO_TCP,
                            socket.TCP_KEEPIDLE,
                            CONF.tcp_keepidle)

        return sock
Example #14
0
 def call(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             self.logger(e)
Example #15
0
    def _get_socket(self, host, port, backlog):
        bind_addr = (host, port)
        try:
            info = socket.getaddrinfo(bind_addr[0], bind_addr[1],
                                      socket.AF_UNSPEC, socket.SOCK_STREAM)[0]
            family = info[0]
            bind_addr = info[-1]
        except Exception:
            LOG.exception(_("Unable to listen on %(host)s:%(port)s"), {
                'host': host,
                'port': port
            })
            sys.exit(1)

        if CONF.use_ssl:
            if not os.path.exists(CONF.ssl_cert_file):
                raise RuntimeError(
                    _("Unable to find ssl_cert_file "
                      ": %s") % CONF.ssl_cert_file)

            # ssl_key_file is optional because the key may be embedded in the
            # certificate file
            if CONF.ssl_key_file and not os.path.exists(CONF.ssl_key_file):
                raise RuntimeError(
                    _("Unable to find "
                      "ssl_key_file : %s") % CONF.ssl_key_file)

            # ssl_ca_file is optional
            if CONF.ssl_ca_file and not os.path.exists(CONF.ssl_ca_file):
                raise RuntimeError(
                    _("Unable to find ssl_ca_file "
                      ": %s") % CONF.ssl_ca_file)

        def wrap_ssl(sock):
            ssl_kwargs = {
                'server_side': True,
                'certfile': CONF.ssl_cert_file,
                'keyfile': CONF.ssl_key_file,
                'cert_reqs': ssl.CERT_NONE,
            }

            if CONF.ssl_ca_file:
                ssl_kwargs['ca_certs'] = CONF.ssl_ca_file
                ssl_kwargs['cert_reqs'] = ssl.CERT_REQUIRED

            return ssl.wrap_socket(sock, **ssl_kwargs)

        sock = None
        retry_until = time.time() + CONF.retry_until_window
        while not sock and time.time() < retry_until:
            try:
                sock = eventlet.listen(bind_addr,
                                       backlog=backlog,
                                       family=family)
                if CONF.use_ssl:
                    sock = wrap_ssl(sock)

            except socket.error as err:
                with excutils.save_and_reraise_exception() as ctxt:
                    if err.errno == errno.EADDRINUSE:
                        ctxt.reraise = False
                        eventlet.sleep(0.1)
        if not sock:
            raise RuntimeError(
                _("Could not bind to %(host)s:%(port)s "
                  "after trying for %(time)d seconds") % {
                      'host': host,
                      'port': port,
                      'time': CONF.retry_until_window
                  })
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # sockets can hang around forever without keepalive
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        # This option isn't available in the OS X version of eventlet
        if hasattr(socket, 'TCP_KEEPIDLE'):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
                            CONF.tcp_keepidle)

        return sock