Exemple #1
0
 def shutdown(self):
     print("Shutdown server")
     TCPServer.shutdown(self)
     #try:
     #    os.remove(self.pid_path)
     #except OSError as exc:
     #    logger.critical("Could not remove pid_path: %s", exc)
     print("Shutdown done")
Exemple #2
0
 def shutdown(self):
     print("Shutdown server")
     TCPServer.shutdown(self)
     #try:
     #    os.remove(self.pid_path)
     #except OSError as exc:
     #    logger.critical("Could not remove pid_path: %s", exc)
     print("Shutdown done")
Exemple #3
0
def preview_main(gen_script, default_port):
    """Main entrypoint for previewing documentation.

    Args:
        gen_script: Generation script, required to generate docs.
        default_port: Default port for local HTTP server.
    """
    assert isfile(_SPHINX_BUILD), "Please execute via 'bazel run'"
    parser = argparse.ArgumentParser()
    parser.register('type', 'bool', _str2bool)
    parser.add_argument(
        "--browser", type='bool', default=True, metavar='BOOL',
        help="Open browser. Disable this if you are frequently recompiling.")
    parser.add_argument(
        "--port", type=int, default=default_port, metavar='PORT',
        help="Port for serving doc pages with a HTTP server.")
    args = parser.parse_args()
    # Choose an arbitrary location for generating documentation.
    out_dir = abspath("sphinx-tmp")
    if isdir(out_dir):
        rmtree(out_dir)
    # Generate.
    check_call([sys.executable, gen_script, "--out_dir", out_dir])
    print("Sphinx preview docs are available at:")
    file_url = "file://{}".format(join(out_dir, "index.html"))
    browser_url = file_url
    print()
    print("  {}".format(file_url))
    # Serve the current directory for local browsing. Required for MacOS.
    # N.B. We serve the preview via a HTTP server because it is necessary for
    # certain browsers (Safari on MacOS, possibly Chrome) due to local file
    # restrictions.
    os.chdir(out_dir)
    sockaddr = ("127.0.0.1", args.port)
    TCPServer.allow_reuse_address = True
    httpd = TCPServer(sockaddr, _Handler)
    http_url = "http://{}:{}/index.html".format(*sockaddr)
    print()
    print("  {}".format(http_url))
    # Default to using HTTP serving only on MacOS; on Ubuntu, it can spit
    # out errors and exceptions about broken pipes, 404 files, etc.
    if sys.platform == "darwin":
        browser_url = http_url
    # Try the default browser.
    if args.browser:
        webbrowser.open(browser_url)
    # Wait for server.
    print()
    print("Serving and waiting ... use Ctrl-C to exit.")
    httpd.serve_forever()
Exemple #4
0
def get_auth_code(hostname='localhost', port=8080, listen_path='/'):
    """Listens for an incoming auth code redirect

    This will probably need to be called in a thread so that an initial request
    can be sent while the redirect listener is listening.

    Args:
        hostname (str, optional): The hostname to listen on.
        port (int, optional): What port to listen on
        listen_path (str, optional): What path to listen on"""

    httpd = TCPServer((hostname, port), AuthCodeListener)
    while httpd.RequestHandlerClass.keep_listening:
        httpd.handle_request()

    return httpd.RequestHandlerClass.code
Exemple #5
0
def get_server(port):
    """
    Call proxyd.shutdown() to stop the server
    """

    proxyd = TCPServer(("", port), Proxy)
    return proxyd
Exemple #6
0
    def get_server(cls, port):
        """
        Call httpd.shutdown() to stop the server
        """

        httpd = TCPServer(("", port), TestWebServerHandler)
        return httpd
Exemple #7
0
    def start(self, bind_ip='0.0.0.0', bind_port=3240):
        """ Start the server """
        LOGGER.info('Starting USBIP server on {}:{}'.format(
            bind_ip, bind_port))

        # Configure the socket server
        TCPServer.allow_reuse_address = True
        TCPServer.timeout = RECV_TIMEOUT_SEC
        self.server = TCPServer((bind_ip, bind_port), UsbIpHandler)
        self.server.controller = self.controller
        self.server.keep_alive = threading.Event()
        self.server.keep_alive.set()

        # Start the server in it's own thread
        signal.signal(signal.SIGINT, self._interrupt_handler)
        self.should_stop.clear()
        self.thread = threading.Thread(target=self._serve)
        self.thread.start()
 def server_bind(self):
     """Override of TCPServer.server_bind() that tracks bind-time assigned random ports."""
     TCPServer.server_bind(self)
     _, self.server_port = self.socket.getsockname()[:2]
Exemple #9
0
    def __init__(self, host="localhost", port=9998, **kwargs):
        self.host, self.port = host, port

        TCPServer.__init__(self, (self.host, self.port), MyTCPHandler)

        self.poll_interval = kwargs.pop("poll_interval", 0.5)
Exemple #10
0
 def serve_forever(self):
     """
     Handle requests until an explicit shutdown() request. 
     Poll for shutdown every poll_interval seconds. Ignores self.timeout. 
     """
     TCPServer.serve_forever(self, poll_interval=self.poll_interval)
Exemple #11
0
with zipfile.ZipFile("bindings/pydrake/doc/sphinx.zip", "r") as archive:
    archive.extractall("sphinx-tmp")
os.chdir("sphinx-tmp")
file_url = "file://%s/index.html " % os.path.abspath(os.getcwd())


# An HTTP handler without logging.
class Handler(SimpleHTTPRequestHandler):
    def log_request(*_):
        pass


# Serve the current directory for local browsing.
sockaddr = ("127.0.0.1", args.port)
TCPServer.allow_reuse_address = True
httpd = TCPServer(sockaddr, Handler)
http_url = "http://%s:%s/index.html" % sockaddr

# Users can click these as a backup, if the auto-open below doesn't work.
print("Sphinx preview docs are available at:", file=sys.stderr)
print("", file=sys.stderr)
print("  " + http_url, file=sys.stderr)
print("", file=sys.stderr)
print("  " + file_url, file=sys.stderr)
print("", file=sys.stderr)

# Try the default browser, then wait.
if args.browser:
    print("Opening webbrowser", file=sys.stderr)
    if sys.platform == "darwin":
        # macOS
Exemple #12
0
 def __init__(self, server_address=None,
              requestHandlerClass=TelnetRequestHandler):
     if not server_address:
         server_address = ('', 23)
     TCPServer.__init__(self, server_address, requestHandlerClass)
Exemple #13
0
with zipfile.ZipFile("bindings/pydrake/doc/sphinx.zip", "r") as archive:
    archive.extractall("sphinx-tmp")
os.chdir("sphinx-tmp")
file_url = "file://%s/index.html " % os.path.abspath(os.getcwd())


# An HTTP handler without logging.
class Handler(SimpleHTTPRequestHandler):
    def log_request(*_):
        pass


# Serve the current directory for local browsing.
sockaddr = ("127.0.0.1", args.port)
TCPServer.allow_reuse_address = True
httpd = TCPServer(sockaddr, Handler)
http_url = "http://%s:%s/index.html" % sockaddr

# Users can click these as a backup, if the auto-open below doesn't work.
print("Sphinx preview docs are available at:", file=sys.stderr)
print("", file=sys.stderr)
print("  " + http_url, file=sys.stderr)
print("", file=sys.stderr)
print("  " + file_url, file=sys.stderr)
print("", file=sys.stderr)

# Try the default browser, then wait.
if args.browser:
    print("Opening webbrowser", file=sys.stderr)
    if sys.platform == "darwin":
        # macOS
Exemple #14
0
    def __init__(self, host="localhost", port=9998, **kwargs):
        self.host, self.port = host, port

        TCPServer.__init__(self, (self.host, self.port), MyTCPHandler)

        self.poll_interval = kwargs.pop("poll_interval", 0.5)
Exemple #15
0
 def serve_forever(self):
     """
     Handle requests until an explicit shutdown() request.
     Poll for shutdown every poll_interval seconds. Ignores self.timeout.
     """
     TCPServer.serve_forever(self, poll_interval=self.poll_interval)
Exemple #16
0
class UsbIpServer(object):
    """ USBIP TCP Server """
    def __init__(self, controller):
        self.controller = controller
        self.should_stop = threading.Event()
        self.server = None
        self.thread = None
        self.ports = {}

    def _interrupt_handler(self, *args):  #pylint: disable=unused-argument
        """ Handle interrupt signals """
        LOGGER.warning('Interrupt signal received (Ctrl+C)')
        self.stop()

    def _serve(self):
        """ Serve forever, but doesn't ignore timeouts """
        while not self.should_stop.is_set():
            self.server.handle_request()

    def start(self, bind_ip='0.0.0.0', bind_port=3240):
        """ Start the server """
        LOGGER.info('Starting USBIP server on {}:{}'.format(
            bind_ip, bind_port))

        # Configure the socket server
        TCPServer.allow_reuse_address = True
        TCPServer.timeout = RECV_TIMEOUT_SEC
        self.server = TCPServer((bind_ip, bind_port), UsbIpHandler)
        self.server.controller = self.controller
        self.server.keep_alive = threading.Event()
        self.server.keep_alive.set()

        # Start the server in it's own thread
        signal.signal(signal.SIGINT, self._interrupt_handler)
        self.should_stop.clear()
        self.thread = threading.Thread(target=self._serve)
        self.thread.start()

    def stop(self):
        """ Stop the server """
        LOGGER.info('Stopping the USBIP server')

        # Detach all devices
        self.detach_all()
        LOGGER.debug('All devices detached')

        # Shutdown the server
        self.should_stop.set()
        self.server.keep_alive.clear()
        self.server.server_close()
        LOGGER.debug('TCP Socket closed')

        # Wait for the thread to finish
        self.thread.join()
        self.thread = None
        LOGGER.debug('Server thread joined')

    def attach(self, device_id):
        """ Attach a single device with USBIP by device id """
        LOGGER.debug('Attaching device {}'.format(device_id))

        # Validate the device id
        split = device_id.split('-')
        assert len(split) == 2
        assert int(split[0]) == self.controller.bus_no
        assert int(split[1]) <= len(self.controller.devices)

        # Attach the device. Failing to attach a valid device should be treated
        #  as a fatal error since the end user may have to manually configure
        #  their environment back to a clean state
        args = ['sudo', 'usbip', 'attach', '-r', '127.0.0.1', '-b', device_id]
        process = Popen(args, stdout=PIPE, stderr=PIPE)
        out, err = process.communicate()
        code = process.returncode
        if code != 0:
            msg = 'Error while attaching device {} ({})'.format(
                device_id, code)
            msg += '\n{}\n{}'.format(out, err)
            LOGGER.fatal(msg)
            raise RuntimeError(msg)
        new_port = len(self.ports)
        self.ports[new_port] = device_id

    def detach(self, port):  #pylint: disable=no-self-use
        """ Detach a single device with USBIP by port number """
        LOGGER.debug('Detaching port {}'.format(port))

        # Detach the port. There are normal reasons why a device may fail to
        #  detach, but for safety, warn the user when it occurs.
        args = ['sudo', 'usbip', 'detach', '-p', str(port)]
        process = Popen(args, stdout=PIPE, stderr=PIPE)
        out, err = process.communicate()
        code = process.returncode
        if code != 0:
            msg = 'Error while detaching port {} ({})'.format(port, code)
            msg += '\n{}\n{}'.format(out, err)
            LOGGER.warning(msg)
        else:
            parts = self.ports[port].split('-')
            bus_no = int(parts[0])
            dev_no = int(parts[1])
            device_id = (bus_no << 16) | dev_no
            device = self.controller.get_device(device_id)
            device.stop()
            del self.ports[port]

    def attach_all(self):
        """ Attach all devices with USBIP """
        for idx in range(len(self.controller.devices)):
            device_no = idx + 1
            device_id = '{}-{}'.format(self.controller.bus_no, device_no)
            self.attach(device_id)

    def detach_all(self):
        """ Detach all devices with USBIP """
        # Copy ports so that the sub-function can delete while enumerating
        ports = copy.deepcopy(list(self.ports.keys()))
        for port in ports:
            self.detach(port)
Exemple #17
0
 def server_bind(self):
   """Override of TCPServer.server_bind() that tracks bind-time assigned random ports."""
   TCPServer.server_bind(self)
   _, self.server_port = self.socket.getsockname()[:2]
Exemple #18
0
def serve():
    httpd = TCPServer((_host, _port), MockHTTPHandler)
    httpd.serve_forever()