Beispiel #1
0
    def __initialize(self, config):
        try:
            host, port = split_host_port(config['listen'], None)
        except Exception:
            raise ValueError(
                'Invalid "restapi" config: expected <HOST>:<PORT> for "listen", but got "{0}"'
                .format(config['listen']))

        if self.__listen is not None:  # changing config in runtime
            self.shutdown()

        self.__listen = config['listen']
        self.__ssl_options = self.__get_ssl_options(config)

        HTTPServer.__init__(self, (host, port), RestApiHandler)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        self.__protocol = 'http'

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        if self.__ssl_options.get('certfile'):
            import ssl
            ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ctx.load_cert_chain(**self.__ssl_options)
            self.socket = ctx.wrap_socket(self.socket, server_side=True)
            self.__protocol = 'https'
        return True
Beispiel #2
0
    def __init__(self, port, session):
        self._logger = logging.getLogger(self.__class__.__name__)

        self.port = port
        self.session = session
        self.vod_fileindex = None
        self.vod_download = None
        self.vod_info = defaultdict(
            dict
        )  # A dictionary containing info about the requested VOD streams.

        for _ in xrange(10000):
            try:
                HTTPServer.__init__(self, ("127.0.0.1", self.port),
                                    VideoRequestHandler)
                self._logger.debug("Listening at %d", self.port)
                break
            except socket.error:
                self._logger.debug("Listening failed at %d", self.port)
                self.port += 1
                continue

        self.server_thread = None

        self.daemon_threads = True
        self.allow_reuse_address = True
Beispiel #3
0
    def __init__(self,
                 boat,
                 behaviour_manager,
                 waypoint_manager,
                 server_address,
                 RequestHandlerClass,
                 bind_and_activate=True):

        HTTPServer.__init__(self, server_address, RequestHandlerClass,
                            bind_and_activate)
        log.info('boatd api listening on %s:%s', *server_address)

        self.boat = boat
        self.behaviour_manager = behaviour_manager
        self.waypoint_manager = waypoint_manager
        self.running = True

        # set API endpoints for GETs
        self.handles = {
            '/': self.boatd_info,
            '/boat': self.boat_attr,
            '/relative_wind': self.relative_wind,
            '/active': self.boat_active,
            '/behaviours': self.behaviours,
            '/waypoints': self.waypoints,
        }

        # set API endpoints for POSTs
        self.post_handles = {
            '/': self.boatd_post,
            '/behaviours': self.behaviours_post,
            '/waypoints': self.waypoints_post,
        }
Beispiel #4
0
 def __init__(self, server_address, RequestHandlerClass,
              ssl_context=None, request_queue_size=None):
     # This overrides the implementation of __init__ in python's
     # SocketServer.TCPServer (which BaseHTTPServer.HTTPServer
     # does not override, thankfully).
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self.socket = socket.socket(self.address_family,
                                 self.socket_type)
     self.ssl_context = ssl_context
     if ssl_context:
         class TSafeConnection(tsafe.Connection):
             def settimeout(self, *args):
                 self._lock.acquire()
                 try:
                     return self._ssl_conn.settimeout(*args)
                 finally:
                     self._lock.release()
             def gettimeout(self):
                 self._lock.acquire()
                 try:
                     return self._ssl_conn.gettimeout()
                 finally:
                     self._lock.release()
         self.socket = TSafeConnection(ssl_context, self.socket)
     self.server_bind()
     if request_queue_size:
         self.socket.listen(request_queue_size)
     self.server_activate()
Beispiel #5
0
    def __init__(self, boat, behaviour_manager,
                 server_address, RequestHandlerClass, bind_and_activate=True):

        HTTPServer.__init__(self, server_address, RequestHandlerClass,
                            bind_and_activate)
        log.info('boatd api listening on %s:%s', *server_address)

        self.boat = boat
        self.behaviour_manager = behaviour_manager
        self.running = True

        # set API endpoints for GETs
        self.handles = {
            '/': self.boatd_info,
            '/boat': self.boat_attr,
            '/wind': self.wind,
            '/active': self.boat_active,
            '/behaviours': self.behaviours,
        }

        # set API endpoints for POSTs
        self.post_handles = {
            '/': self.boatd_post,
            '/behaviours': self.behaviours_post,
        }
Beispiel #6
0
    def __init__(self, patroni, config):
        self._auth_key = base64.b64encode(config['auth'].encode(
            'utf-8')).decode('utf-8') if 'auth' in config else None
        host, port = config['listen'].split(':')
        HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        protocol = 'http'

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        options = {
            option: config[option]
            for option in ['certfile', 'keyfile'] if option in config
        }
        if options.get('certfile'):
            import ssl
            self.socket = ssl.wrap_socket(self.socket,
                                          server_side=True,
                                          **options)
            protocol = 'https'

        self.connection_string = '{0}://{1}/patroni'.format(
            protocol, config.get('connect_address', config['listen']))

        self.patroni = patroni
        self.daemon = True
Beispiel #7
0
    def __init__(self, RequestHandlerClass):
        HTTPServer.__init__(self, None, RequestHandlerClass, False)

        self.requestHandler = RequestHandlerClass

        # TODO provide proper limit for this queue
        self.queue = TaskQueue("http-server", sys.maxint)
Beispiel #8
0
 def __init__(self, patroni, config):
     self.connection_string = 'http://{}/patroni'.format(config.get('connect_address', None) or config['listen'])
     host, port = config['listen'].split(':')
     HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
     Thread.__init__(self, target=self.serve_forever)
     self._set_fd_cloexec(self.socket)
     self.patroni = patroni
     self.daemon = True
Beispiel #9
0
 def __init__(self, addr, handler, root, userpwd):
     HTTPServer.__init__(self, addr, handler)
     self.root = root
     self.userpwd = userpwd  # WebDav Auth user:passwd
     if len(userpwd) > 0:
         self.auth_enable = True
     else:
         self.auth_enable = False
Beispiel #10
0
 def __init__(self, addr, handler, root, userpwd):
     HTTPServer.__init__(self, addr, handler)
     self.root = root
     self.userpwd = userpwd      # WebDAV Auth user:passwd 
     if len(userpwd)>0:
         self.auth_enable = True
     else:
         self.auth_enable = False
    def __init__(self):
        """Create the stub and start listening on a local port"""

        # Choose a local open port
        address = ('', 0)

        # Start the server
        HTTPServer.__init__(self, address, GradingRequestHandler)
        self.start()
Beispiel #12
0
 def __init__(self, server_address, handler, impl, meta):
     '''
     :param server_address: address of the server
     :param handler: handler for requests
     :param impl: reference to the implementation object
     '''
     HTTPServer.__init__(self, server_address, handler)
     self.impl = impl
     self.meta = meta
Beispiel #13
0
 def __init__(self, server_address, handler, impl, meta):
     '''
     :param server_address: address of the server
     :param handler: handler for requests
     :param impl: reference to the implementation object
     '''
     HTTPServer.__init__(self, server_address, handler)
     self.impl = impl
     self.meta = meta
Beispiel #14
0
    def __init__(self, store, *args, **kwargs):
        HTTPServer.__init__(self, *args, **kwargs)
        self.sessions = {}
        self.store = store

        if self.server_port != 80:
            self.base_url = ('http://%s:%s/' %
                             (self.server_name, self.server_port))
        else:
            self.base_url = 'http://%s/' % (self.server_name, )
Beispiel #15
0
    def __init__(self, store, *args, **kwargs):
        HTTPServer.__init__(self, *args, **kwargs)
        self.sessions = {}
        self.store = store

        if self.server_port != 80:
            self.base_url = ('http://%s:%s/' %
                             (self.server_name, self.server_port))
        else:
            self.base_url = 'http://%s/' % (self.server_name,)
Beispiel #16
0
    def __httpserver_init(self, host, port):
        dual_stack = self.__has_dual_stack()
        if host in ('', '*'):
            host = None

        info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
        # in case dual stack is not supported we want IPv4 to be preferred over IPv6
        info.sort(key=lambda x: x[0] == socket.AF_INET, reverse=not dual_stack)

        self.address_family = info[0][0]
        HTTPServer.__init__(self, info[0][-1][:2], RestApiHandler)
    def __init__(self):
        """Start listening on a local port for responses from the xqueue"""
        # Create an empty list in which to store request records
        self._request_list = []

        # Choose an open local port
        address = ('', 0)

        # Create and start the server
        HTTPServer.__init__(self, address, LoggingRequestHandler)
        self.start()
Beispiel #18
0
    def __init__(self, *args, **kwargs):
        HTTPServer.__init__(self, *args, **kwargs)

        if self.server_port != 80:
            self.base_url = ('http://%s:%s/' %
                             (self.server_name, self.server_port))
        else:
            self.base_url = 'http://%s/' % (self.server_name,)

        self.openid = None
        self.approved = {}
        self.lastCheckIDRequest = {}
Beispiel #19
0
    def __init__(self, *args, **kwargs):
        HTTPServer.__init__(self, *args, **kwargs)

        if self.server_port != 80:
            self.base_url = ('http://%s:%s/' %
                             (self.server_name, self.server_port))
        else:
            self.base_url = 'http://%s/' % (self.server_name, )

        self.openid = None
        self.approved = {}
        self.lastCheckIDRequest = {}
Beispiel #20
0
 def __init__(
     self,
     crl_url_path,
     crl_directory,
     server_address,
     RequestHandlerClass,
 ):
     if not crl_url_path.endswith('/'):
         raise ValueError("crl_url_path %r must end with a slash" %
                          crl_url_path)
     self.crl_url_path = crl_url_path
     self.crl_directory = crl_directory
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
Beispiel #21
0
    def __init__(self, port_num,
                 response={'username': '******', 'external_id': 1}):
        '''
        Initialize the mock Comment Service server instance.
        *port_num* is the localhost port to listen to
        *response* is a dictionary that will be JSON-serialized
            and sent in response to comment service requests.
        '''
        self._response_str = json.dumps(response)

        handler = MockCommentServiceRequestHandler
        address = ('', port_num)
        HTTPServer.__init__(self, address, handler)
Beispiel #22
0
 def __init__(self,
              server_address,
              RequestHandlerClass,
              client_id,
              client_secret,
              bind_and_activate=True):
     HTTPServer.__init__(self,
                         server_address,
                         RequestHandlerClass,
                         bind_and_activate=bind_and_activate)
     self.logger = logging.getLogger('auth_server.http')
     self.client_id = client_id
     self.client_secret = client_secret
     self.listening_event = threading.Event()
Beispiel #23
0
 def __init__(self, response='', address=None):
     self.received = None
     self.response = response
     if address!=None:
         HTTPServer.__init__(self, address, handler)
     else:
         for port in range(1024,65536):
             try:
                 HTTPServer.__init__(self, ('localhost', port), handler)
             except socket.error as e:
                 if e.errno!=98: # Address already in use
                     raise
             else:
                 break
         else:
             raise Exception('No open ports')
Beispiel #24
0
    def __httpserver_init(self, host, port):
        dual_stack = self.__has_dual_stack()
        if host in ('', '*'):
            host = None

        info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
        # in case dual stack is not supported we want IPv4 to be preferred over IPv6
        info.sort(key=lambda x: x[0] == socket.AF_INET, reverse=not dual_stack)

        self.address_family = info[0][0]
        try:
            HTTPServer.__init__(self, info[0][-1][:2], RestApiHandler)
        except socket.error:
            logger.error(
                    "Couldn't start a service on '%s:%s', please check your `restapi.listen` configuration", host, port)
            raise
Beispiel #25
0
    def __initialize(self, config):
        self.__ssl_options = self.__get_ssl_options(config)
        self.__listen = config['listen']
        host, port = config['listen'].rsplit(':', 1)
        HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        self.__protocol = 'http'

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        if self.__ssl_options.get('certfile'):
            import ssl
            self.socket = ssl.wrap_socket(self.socket, server_side=True, **self.__ssl_options)
            self.__protocol = 'https'
        self.__set_connection_string(config.get('connect_address'))
Beispiel #26
0
    def __initialize(self, config):
        self.__ssl_options = self.__get_ssl_options(config)
        self.__listen = config['listen']
        host, port = config['listen'].split(':')
        HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        self.__protocol = 'http'

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        if self.__ssl_options.get('certfile'):
            import ssl
            self.socket = ssl.wrap_socket(self.socket, server_side=True, **self.__ssl_options)
            self.__protocol = 'https'
        self.__set_connection_string(config.get('connect_address'))
Beispiel #27
0
    def __init__(self, port_num=0):
        """
        Configure the server to listen on localhost.
        Default is to choose an arbitrary open port.
        """
        address = ('0.0.0.0', port_num)
        HTTPServer.__init__(self, address, self.HANDLER_CLASS)

        # Create a dict to store configuration values set by the client
        self.config = dict()

        # Start the server in a separate thread
        server_thread = threading.Thread(target=self.serve_forever)
        server_thread.daemon = True
        server_thread.start()

        # Log the port we're using to help identify port conflict errors
        LOGGER.debug('Starting service on port {0}'.format(self.port))
    def __init__(self, patroni, config):
        self._auth_key = base64.b64encode(config['auth'].encode('utf-8')).decode('utf-8') if 'auth' in config else None
        host, port = config['listen'].split(':')
        HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        protocol = 'http'

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        options = {option: config[option] for option in ['certfile', 'keyfile'] if option in config}
        if options.get('certfile'):
            import ssl
            self.socket = ssl.wrap_socket(self.socket, server_side=True, **options)
            protocol = 'https'

        self.connection_string = '{0}://{1}/patroni'.format(protocol, config.get('connect_address', config['listen']))

        self.patroni = patroni
        self.daemon = True
Beispiel #29
0
    def __init__(self, patroni, config):
        self._auth_key = base64.b64encode(config["auth"].encode("utf-8")).decode("utf-8") if "auth" in config else None
        host, port = config["listen"].split(":")
        HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
        Thread.__init__(self, target=self.serve_forever)
        self._set_fd_cloexec(self.socket)

        protocol = "http"

        # wrap socket with ssl if 'certfile' is defined in a config.yaml
        # Sometime it's also needed to pass reference to a 'keyfile'.
        options = {option: config[option] for option in ["certfile", "keyfile"] if option in config}
        if options.get("certfile", None):
            import ssl

            self.socket = ssl.wrap_socket(self.socket, server_side=True, **options)
            protocol = "https"

        self.connection_string = "{}://{}/patroni".format(protocol, config.get("connect_address", config["listen"]))

        self.patroni = patroni
        self.daemon = True
Beispiel #30
0
    def __init__(self, port, session):
        self._logger = logging.getLogger(self.__class__.__name__)

        self.port = port
        self.session = session
        self.vod_fileindex = None
        self.vod_download = None
        self.vod_info = defaultdict(dict)  # A dictionary containing info about the requested VOD streams.

        for _ in xrange(10000):
            try:
                HTTPServer.__init__(self, ("127.0.0.1", self.port), VideoRequestHandler)
                self._logger.debug("Listening at %d", self.port)
                break
            except socket.error:
                self._logger.debug("Listening failed at %d", self.port)
                self.port += 1
                continue

        self.server_thread = None

        self.daemon_threads = True
        self.allow_reuse_address = True
Beispiel #31
0
 def __init__(self, RequestHandlerClass):
     HTTPServer.__init__(self, None, RequestHandlerClass, False)
     self.requestHandler = RequestHandlerClass
     self.queue = TaskQueue("http-server", _MAX_QUEUE_TASKS)
Beispiel #32
0
 def __init__(self, server, routes=(), static_dirs=(), *args, **kwargs):
     self._server = server
     self._routes.extend(routes)
     self._static_dirs.extend(static_dirs)
     HTTPServer.__init__(self, *args, **kwargs)
Beispiel #33
0
    def do_bind(self):
        """Perform HTTP server binding and activation."""

        HTTPServer.__init__(self, (self.host, self.port), HTTPRequestHandler)
Beispiel #34
0
 def __init__(self, address, handler):
     HTTPServer.__init__(self, address, handler)
     self.response_queue = queue.Queue()
Beispiel #35
0
 def __init__(self, server_address, RequestHandlerClass, client_id, client_secret, bind_and_activate=True):
     HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate)
     self.logger = logging.getLogger('auth_server.http')
     self.client_id = client_id
     self.client_secret = client_secret
     self.listening_event = threading.Event()
Beispiel #36
0
 def __init__(self, timeout=-1):
     self.timeout = None if timeout < 0 else timeout
     self.__methods__ = {}
     self.__methods__.update(self._setup(self))
     HTTPServer.__init__(self, self._localhost(), RequestHandler)
     log("httpd: server started on: {}".format(self.server_address))
 def __init__(self, client, subscription_manager, *args, **kwargs):
     self.client = client
     self.subscription_manager = subscription_manager
     HTTPServer.__init__(self, *args, **kwargs)
Beispiel #38
0
 def __init__(self, RequestHandlerClass):
     HTTPServer.__init__(self, None, RequestHandlerClass, False)
     self.requestHandler = RequestHandlerClass
     self.queue = TaskQueue("http-server", _MAX_QUEUE_TASKS)
Beispiel #39
0
 def __init__(self, address, handler):
     HTTPServer.__init__(self, address, handler)
     self.response_queue = queue.Queue()
Beispiel #40
0
 def __init__(self, server_address, request_handler, path):
     self.path = path
     HTTPServer.__init__(self, server_address, request_handler)
Beispiel #41
0
 def __init__(self, base_path, *args, **kwargs):
     HTTPServer.__init__(self, *args, **kwargs)
     self.RequestHandlerClass.base_path = base_path
Beispiel #42
0
 def __init__(self, server_address, request_handler, path):
     self.path = path
     HTTPServer.__init__(self, server_address, request_handler)
Beispiel #43
0
    def do_bind(self):
        """Perform HTTP server binding and activation."""

        HTTPServer.__init__(self, (self.host, self.port), HTTPRequestHandler)
Beispiel #44
0
 def __init__(self, server_address, RequestHandlerClass,
              ssl_context=None, request_queue_size=None):
     assert not ssl_context, "pyOpenSSL not installed"
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     if request_queue_size:
         self.socket.listen(request_queue_size)