Example #1
0
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from jinja2 import Environment, FileSystemLoader
from pweby.wsgi import Response
from pweby.log import getLogger

LOG = getLogger(__name__)


template_path = 'templates'
env = Environment(loader=FileSystemLoader(template_path))


def render(template_name=None, **kwargs):
    if not template_name:
        LOG.error('template_name has to not be None.')
        raise Exception()
    template = env.get_template(template_name)
    source = template.render(**kwargs)
    return Response(body=source)

Example #2
0
try:
    # Importing just the symbol here because the io module does not
    # exist in Python 2.6.
    from io import UnsupportedOperation  # noqa
except ImportError:
    # Python 2.6
    UnsupportedOperation = None

import eventlet
from eventlet import event

from pweby import log as logging
from pweby.utils import get_worker_count, initialize_if_enabled, notify_once, ThreadGroup

LOG = logging.getLogger(__name__)


def _sighup_supported():
    return hasattr(signal, "SIGHUP")


def _is_daemon():
    # The process group for a foreground process will match the
    # process group of the controlling terminal. If those values do
    # not match, or ioctl() fails on the stdout file handle, we assume
    # the process is running in the background as a daemon.
    # http://www.gnu.org/software/bash/manual/bashref.html#Job-Control-Basics
    try:
        is_daemon = os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno())
    except OSError as err:
Example #3
0
File: wsgi.py Project: syfun/pweby
    def __init__(self, app, name='pweby server', host=None, port=None, pool_size=None,
                 protocol=eventlet.wsgi.HttpProtocol, backlog=128):
        """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.
        :returns: None

        """
        # Allow operators to customize http requests max header line size.
        eventlet.wsgi.MAX_HEADER_LINE = CONF.max_header_line
        self.client_socket_timeout = CONF.client_socket_timeout or None
        self.app = self._set_app(app)
        self.name = name
        self._host = host or "0.0.0.0"
        self._port = port or 8090
        self._server = None
        self._socket = None
        self._protocol = protocol
        self.pool_size = pool_size or self.default_pool_size
        self._pool = eventlet.GreenPool(self.pool_size)
        self._logger = logging.getLogger("eventlet.wsgi.server")
        self._wsgi_logger = logging.WritableLogger(self._logger)

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

        bind_addr = (self._host, self._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

        cert_file = CONF.ssl_cert_file
        key_file = CONF.ssl_key_file
        ca_file = CONF.ssl_ca_file
        self._use_ssl = cert_file or 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.")

        retry_until = time.time() + 30
        while not self._socket and time.time() < retry_until:
            try:
                self._socket = eventlet.listen(bind_addr, backlog=backlog,
                                               family=family)
            except socket.error as err:
                if err.args[0] != errno.EADDRINUSE:
                    raise
                eventlet.sleep(0.1)

        if not self._socket:
            raise RuntimeError("Could not bind to %(host)s:%(port)s "
                               "after trying for 30 seconds" %
                               {'host': host, 'port': port})

        (self._host, self._port) = self._socket.getsockname()[0:2]
        LOG.info("%(name)s listening on %(_host)s:%(_port)s" %
                 {'name': self.name, '_host': self._host, '_port': self._port})