Esempio n. 1
0
def run(klass):
    server = StandaloneServer(klass)
    server.start()
    port = server.port
    if port == -1:
        print("Couldn't find an available port", file=sys.stderr)
        sys.exit(-1)
Esempio n. 2
0
def check_urls(base_url=None, verbose=False):
    log = lambda *a: verbose and print(*a)

    if not base_url:
        if not os.path.exists(BUILD_DIR):
            process('build')
        base_url = 'localhost:9000'
        args = 'run --port=9000 --no-build'.split(' ')
        server = Thread(target=process, args=args)
        server.daemon = True
        server.start()
        time.sleep(1)

    with open(os.path.join(SRC_DIR, URLS_FILE), 'br') as f:
        urls = json.loads(f.read().decode())

    def get(url, expected_code=200, indent=''):
        comment = ''
        try:
            if base_url.startswith('https://'):
                connection = http.client.HTTPSConnection
            else:
                connection = http.client.HTTPConnection
            host = re.sub('^https?://', '', base_url)
            conn = connection(host)
            conn.request('HEAD', url)
            res = conn.getresponse()
            code = res.status
            if code == 200:
                res_url = url
            else:
                res_url = res.info().get('Location', '')
                res_url = res_url.replace(base_url, '')
        except HTTPError as e:
            code = e.code
            res_url = None

        err = []
        if code != expected_code:
            err = ['%s (%r != %r)' % (url, code, expected_code)]
        else:
            log('%s%s %s %s # %s' % (indent, url, code, res_url, comment))
        return err

    all_aliases = []
    for aliases in urls.values():
        all_aliases += aliases or []

    err = []
    for url in sorted(urls.keys()):
        aliases = urls.get(url)
        err += get(url, expected_code=301 if url in all_aliases else 200)
        for alias in aliases or []:
            err += get(alias, expected_code=301, indent='  ')
    if err:
        print('Errors:')
        print('\n'.join(err))
    else:
        print('OK')
Esempio n. 3
0
def _send_recv_event(event):
    opener = urllib.request.build_opener()
    server = _ShotServer(event["echo_host"], event["echo_port"])
    server.start()
    try:
        # To save events had not numbered sequentially. Check that everything works to increase counter.
        opener.open(_make_event_request({ "_stub": None }))
        opener.open(_make_event_request(event))
        return json.loads(server.wait_for_result().decode())
    finally:
        server.stop()
Esempio n. 4
0
def start_server():
    if not start_server.status:
        # inicia servidor
        server = FixtureHttpServer()
        server.start()
        atexit.register(server.terminate)
        # guarda a porta e cria URL
        global server_port, server_url
        server_port = server.port
        server_url = "http://127.0.0.1:%d" % server.port
        # marca servidor como já inicializado
        start_server.status = 1
Esempio n. 5
0
def start_server(server_class, handler, address, port, *args):
    infos = socket.getaddrinfo(address, port, 0, socket.SOCK_STREAM)
    for family, socktype, proto, canonname, sockaddr in infos:
        logging.debug(
            "creating {5} with {0} {1} {2} {3} {4}".format(
                family, socktype, proto, canonname, sockaddr, server_class.__name__
            )
        )
        server = server_class(family, sockaddr, handler, *args)
        server.start()
        # TODO: remove this temporary hack
        return server
Esempio n. 6
0
def run_tornado():
    app = Application([
        tornado.web.url(r"/xml2var", Xml2VarHandler),
        tornado.web.url(r"/anyxml2var", AnyXml2VarHandler),
        tornado.web.url(r"/var2xml", Var2XmlHandler),
        tornado.web.url(r"/xml2var_attribute_as_key", Xml2VarAttributeAsKeyHandler),
        tornado.web.url(r"/1/", Handler1),
        tornado.web.url(r"/2/", Handler2),
        tornado.web.url(r"/redirect/", RedirectHandler)
    ])
    server = HTTPServer(app)
    server.bind(8888)
    server.start(3)  # 0 - forks one process per cpu
    IOLoop.current().start()
Esempio n. 7
0
def runsimple(func, server_address=("0.0.0.0", 8080)):
    """
    Runs [CherryPy][cp] WSGI server hosting WSGI app `func`. 
    The directory `static/` is hosted statically.

    [cp]: http://www.cherrypy.org
    """
    func = StaticMiddleware(func)
    func = LogMiddleware(func)
    
    server = WSGIServer(server_address, func)

    print("http://%s:%d/" % server_address)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 8
0
  def post_fork_child(self):
    """Post-fork() child callback for ProcessManager.daemonize()."""
    # The server finds run-specific info dirs by looking at the subdirectories of info_dir,
    # which is conveniently and obviously the parent dir of the current run's info dir.
    info_dir = os.path.dirname(self.context.run_tracker.run_info_dir)

    settings = ReportingServer.Settings(info_dir=info_dir,
                                        root=get_buildroot(),
                                        template_dir=self.options.template_dir,
                                        assets_dir=self.options.assets_dir,
                                        allowed_clients=self.options.allowed_clients)

    server = ReportingServer(self.options.port, settings)

    self.write_socket(server.server_port())

    # Block forever.
    server.start()
Esempio n. 9
0
def main():
	PORT = int(os.environ['HTTP_PORT'])
	Handler = http.server.SimpleHTTPRequestHandler
	httpd = socketserver.TCPServer(("", PORT), Handler)
	print("serving at port", PORT)
	server = Thread(target=httpd.serve_forever)
	server.start()
	monitors = {}
	cli = Client(base_url='unix://var/run/docker.sock')
	events = cli.events(since=0,decode=True)
	for e in events:
		if 'id' not in e:
			print('WARNIG: id not in e',e)
			continue
		cid = e['id']
		status = e['status']
		if status in ['start']:
			print('Starting Monitor on',cid)
			if cid in monitors:
				print('WARNIG: Unexpected cid')
				continue
			stop = Event()
			mon = Monitor(cid,stop)
			monitors[cid] = (mon,stop)
			mon.start()
		elif status in ['die']:
			print('Stoping Monitor on',cid)
			if cid not in monitors:
				print('WARNIG: Unexpected cid')
				continue
			(mon,stop) = monitors[cid]
			stop.set()
			mon.join(1)
			print('Stopped')
			del monitors[cid]
		elif status in ['create','destroy','kill','stop','commit','delete']:
			print(status)
			pass
		else:
			print('WARNIG: Unexpected status:',e)
	pass
Esempio n. 10
0
def main(headless):
    port = STATE.get("PREFERRED_PORT")
    if not port:
        port = 8000

    httpd = http.server.HTTPServer(
        ("", port),
        CohortManagerRequestHandler
    )

    if STATE["DEBUG"] or headless:
        print("Server listening on port {}.".format(port))

    # Launch the server thread.
    server = threading.Thread(target=httpd.serve_forever, daemon=False)
    server.start()

    if headless:
        # In headless mode, the only thing that the main thread will do is
        # to wait for interrupt.
        try:
            while server.is_alive():
                pass
        except:
            httpd.shutdown()
            return

    else:
        try:
            client(port)
        except EOFError:
            print("YO")
            httpd.shutdown()
        except KeyboardInterrupt:
            print("Ya")

        httpd.shutdown()
        server.join()
Esempio n. 11
0
    print_ok("handling POST to fake bridge")
    length = int(self.headers['Content-Length'])
    received_metrics = json.loads(self.rfile.read(length).decode('utf-8'))

if __name__ == "__main__":
  ghostunnel = None
  try:
    # Step 1: create certs
    create_root_cert('root')
    create_signed_cert('server', 'root')
    create_signed_cert('new_server', 'root')
    create_signed_cert('client1', 'root')

    httpd = http.server.HTTPServer(('localhost',13080), FakeMetricsBridgeHandler)
    server = threading.Thread(target=httpd.handle_request)
    server.start()

    # Step 2: start ghostunnel
    ghostunnel = Popen(['../ghostunnel', '--listen={0}:13001'.format(LOCALHOST),
      '--target={0}:13100'.format(LOCALHOST), '--keystore=server.p12',
      '--storepass='******'--cacert=root.crt', '--allow-ou=client1',
      '--status={0}:13100'.format(LOCALHOST), '--metrics-url=http://localhost:13080/post'])

    # Step 3: wait for metrics to post
    for i in range(0, 10):
      if received_metrics:
        break
      else:
        # wait a little longer...
        time.sleep(1)
Esempio n. 12
0
                                               bind_and_activate=False)
                httpd.allow_reuse_address = True
                httpd.server_bind()
                httpd.server_activate()
                success("HTTP server started at port", self.PORT)
                try:
                    self.address.put("http://127.0.0.1:" + str(self.PORT) +
                                     "/static/face")
                    self.address.put("http://127.0.0.1:" + str(self.PORT) +
                                     "/static/controller")
                    httpd.serve_forever()
                except KeyboardInterrupt:
                    httpd.server_close()
                    normal("HTTP server shut down.")
            except OSError as exc:
                if exc.args[0] != 48:
                    raise
                error('Port', self.PORT, 'already in use')
                self.PORT += 1
            else:
                break


if __name__ == '__main__':
    server = HTTPServer(8001)
    server.start()
    try:
        server.join()
    except KeyboardInterrupt:
        pass