Esempio n. 1
0
def init():
    from oslo.config import cfg
    CONF = cfg.CONF
    if 'remote_debug' not in CONF:
        return
    if not(CONF.remote_debug.host and CONF.remote_debug.port):
        return 
    
    from mvpn.openstack.common.gettextutils import _
    from mvpn.openstack.common import log as logging
    LOG = logging.getLogger(__name__)
    LOG.debug(_('Listening on %(host)s:%(port)s for debug connection'),
              {'host': CONF.remote_debug.host,
               'port': CONF.remote_debug.port})
               
    from pydev import pydevd
    pydevd.settrace(host=CONF.remote_debug.host,
                    port=CONF.remote_debug.port,
                    stdoutToServer=True,
                    stderrToServer=True)
    
    LOG.warn(_('WARNING: Using the remote debug option changes how '
               'Nova uses the eventlet library to support async IO. This '
               'could result in failures that do not occur under normal '
               'operation. Use at your own risk.'))
Esempio n. 2
0
    def __init__(
        self,
        name,
        app,
        host="0.0.0.0",
        port=9000,
        pool_size=None,
        protocol=eventlet.wsgi.HttpProtocol,
        backlog=128,
        use_ssl=False,
        max_url_len=None,
    ):
        """Initialize, but do not start, a WSGI server.

        :param name: Pretty name for logging.
        :param app: The WSGI application to serve.
        :param host: IP address to serve the application.
        :param port: Port number to server the application.
        :param pool_size: Maximum number of eventlets to spawn concurrently.
        :param backlog: Maximum number of queued connections.
        :param max_url_len: Maximum length of permitted URLs.
        :returns: None
        :raises: nova.exception.InvalidInput     
        """
        # Allow operators to customize http requests max header line size.
        eventlet.wsgi.MAX_HEADER_LINE = CONF.max_header_line
        self.name = name
        self.app = app
        self._server = None
        self._protocol = protocol
        self._pool = eventlet.GreenPool(pool_size or self.default_pool_size)
        self._logger = logging.getLogger("mvpn.%s.wsgi.server" % self.name)
        self._wsgi_logger = logging.WritableLogger(self._logger)
        self._use_ssl = use_ssl
        self._max_url_len = max_url_len

        if backlog < 1:
            raise exception.InvalidInput(reason="The backlog must be more than 1")

        bind_addr = (host, port)
        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix
        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:
            family = socket.AF_INET

        try:
            self._socket = eventlet.listen(bind_addr, family, backlog=backlog)
        except EnvironmentError:
            LOG.error(_("Could not bind to %(host)s:%(port)s"), {"host": host, "port": port})
            raise

        (self.host, self.port) = self._socket.getsockname()[0:2]
        LOG.info(_("%(name)s listening on %(host)s:%(port)s") % self.__dict__)
Esempio n. 3
0
    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if not message:
            try:
                message = self.msg_fmt % kwargs

            except Exception:
                exc_info = sys.exc_info()
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                LOG.exception(_('Exception in string format operation'))
                for name, value in kwargs.iteritems():
                    LOG.error("%s: %s" % (name, value))

                if CONF.fatal_exception_format_errors:
                    raise exc_info[0], exc_info[1], exc_info[2]
                else:
                    # at least get the core message out if something happened
                    message = self.msg_fmt

        super(MvpnException, self).__init__(message)
Esempio n. 4
0
 def deprecated(self, msg, *args, **kwargs):
     stdmsg = _("Deprecated: %s") % msg
     if CONF.fatal_deprecations:
         self.critical(stdmsg, *args, **kwargs)
         raise DeprecatedConfig(msg=stdmsg)
     else:
         self.warn(stdmsg, *args, **kwargs)
Esempio n. 5
0
    def __init__(self, ext_mgr=None, init_only=None):
        if ext_mgr is None:
            if self.ExtensionManager:
                ext_mgr = self.ExtensionManager()
            else:
                raise Exception(_("Must specify an ExtensionManager class"))

          mapper = ProjectMapper()
          self.resources = {}
          self._setup_routes(mapper, ext_mgr, init_only)
          self._setup_ext_routes(mapper, ext_mgr, init_only)
          self._setup_extensions(ext_mgr)
          super(APIRouter, self).__init__(mapper)
Esempio n. 6
0
    def wait(self):
        """Block, until the server has stopped.

        Waits on the server's eventlet to finish, then returns.

        :returns: None

        """
        try:
            if self._server is not None:
                self._server.wait()
        except greenlet.GreenletExit:
            LOG.info(_("WSGI server has stopped."))
Esempio n. 7
0
    def stop(self):
        """Stop this server.

        This is not a very nice action, as currently the method by which a
        server is stopped is by killing its eventlet.

        :returns: None

        """
        LOG.info(_("Stopping WSGI server."))

        if self._server is not None:
            # Resize pool to stop new requests from being processed
            self._pool.resize(0)
            self._server.kill()
Esempio n. 8
0
def _find_facility_from_conf():
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler,
                       CONF.syslog_log_facility,
                       None)

    if facility is None and CONF.syslog_log_facility in facility_names:
        facility = facility_names.get(CONF.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON',
                  'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS',
                  'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP',
                  'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3',
                  'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7']
        valid_facilities.extend(consts)
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return facility
Esempio n. 9
0
 def __call__(self, environ, start_response):
     raise NotImplementedError(_("You must implement __call__"))
Esempio n. 10
0
    def start(self):
        """Start serving a WSGI application.

        :returns: None
        """
        if self._use_ssl:
            try:
                ca_file = CONF.ssl_ca_file
                cert_file = CONF.ssl_cert_file
                key_file = CONF.ssl_key_file

                if cert_file and not os.path.exists(cert_file):
                    raise RuntimeError(_("Unable to find cert_file : %s") % cert_file)

                if ca_file and not os.path.exists(ca_file):
                    raise RuntimeError(_("Unable to find ca_file : %s") % ca_file)

                if key_file and not os.path.exists(key_file):
                    raise RuntimeError(_("Unable to find key_file : %s") % key_file)

                if self._use_ssl and (not cert_file or not key_file):
                    raise RuntimeError(
                        _(
                            "When running server in SSL mode, you must "
                            "specify both a cert_file and key_file "
                            "option value in your configuration file"
                        )
                    )
                ssl_kwargs = {
                    "server_side": True,
                    "certfile": cert_file,
                    "keyfile": key_file,
                    "cert_reqs": ssl.CERT_NONE,
                }

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

                self._socket = eventlet.wrap_ssl(self._socket, **ssl_kwargs)

                self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                # sockets can hang around forever without keepalive
                self._socket.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"):
                    self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, CONF.tcp_keepidle)

            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.error(_("Failed to start %(name)s on %(host)s" ":%(port)s with SSL support") % self.__dict__)

        wsgi_kwargs = {
            "func": eventlet.wsgi.server,
            "sock": self._socket,
            "site": self.app,
            "protocol": self._protocol,
            "custom_pool": self._pool,
            "log": self._wsgi_logger,
            "log_format": CONF.wsgi_log_format,
            "debug": False,
        }

        if self._max_url_len:
            wsgi_kwargs["url_length_limit"] = self._max_url_len

        self._server = eventlet.spawn(**wsgi_kwargs)
Esempio n. 11
0
 def __init__(self):
     LOG.audit(_('Initializing extension manager.'))