Exemple #1
0
def restart(db, db_file, args, config, **kwargs):
    l.debug("Restart server instance ")
    l.debug(args)

    if __is_valid_iser__():
        l.error("User %s does not have permission" % getpass.getuser())
        return 1

    server = sql3.entity.Server(db.getConnection())
    server.fetch(args['id'])

    if 'id' not in server.data:
        l.error("Server Instance not found")
        return 2

    if int(server.get('pid')) <= 0:
        l.error("Server not running.")
        return 3

    import server as s
    s.restart(server, db_file)

    s.stop(server)
    time.sleep(3)

    pid = os.fork()

    if pid == 0:
        s.run(server, db_file, config['storage_folder'])
Exemple #2
0
	def test_maths( self ):
		log_file_name = "integration_logs"

		# Remove possible previous file
		os.remove(log_file_name)

		# Start Graphite Proxy
		server.start( 9999, "true", "false" )

		# Create python request senders to send requests to the graphite proxy
		proxy_host = "127.0.0.1"
		proxy_port = 8090
		senders    = []
		for i in range(6):
			senders.append( request_sender.RequestSender( proxy_host, proxy_port, False ) )

		# Send requests in parallel to test the server threading capabilities (each RequestSender is a different thread)

		# Math category 1
		senders[0].run("test.integration.maths.1 2 0")
		senders[1].run("test.integration.maths.1 3 0")
		senders[2].run("test.integration.maths.1 5 0")

		# Math category 2
		senders[3].run("test.integration.maths.2 2 0")
		senders[4].run("test.integration.maths.2 3 0")
		senders[5].run("test.integration.maths.2 5 0")

		# Wait for the computations
		time.sleep(5)

		# Stop the server thread to be able to quit the programm properly
		server.stop()

		# Get received messages from logs
		logs_file = open(log_file_name, 'r')
		logs = logs_file.read()

		# Check received math message for rule 1 (by number of received messages)
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 10.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 2.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 5.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 3.3"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 3.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 1.5"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 1.2"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.1 100.0"), -1 )

		# Check received math message for rule 2 (by number of spend time)
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 10.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 2.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 5.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 3.3"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 3.0"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 1.5"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 1.2"), -1 )
		self.assertNotEqual( logs.find("Message added: test.integration.maths.2 100.0"), -1 )

		# Remove created logs file
		os.remove(log_file_name)
def run_test(tester, proxy_port, is_udp):
	# Create a python request receiver to receive Normal requests from the graphite proxy (emulate the Graphite Server)
	client_port = 9999
	receiver 	  = request_receiver.RequestReceiver()
	if not receiver.connect("127.0.0.1", client_port):
		print "Impossible to connect, abort."
		receiver.stop()
		sys.exit()

	# Start Graphite Proxy
	server.start( client_port, "false", "false" )

	# Create python request senders to send requests to the graphite proxy
	proxy_host = "127.0.0.1"
	senders    = []
	for i in range(4):
		senders.append( request_sender.RequestSender( proxy_host, proxy_port, is_udp ) )

	# Send requests in parallel to test the server threading capabilities (each RequestSender is a different thread)
	senders[0].run("Integration.test.1 0 0")
	senders[1].run("Integration.test.1 50 0")
	senders[2].run("Integration.test.2 100 0")
	senders[3].run("Integration.test.3 9999 0")

	time.sleep(2)

	server.stop()
	receiver.stop() # Stop the server thread to be able to quit the programm properly

	# Receive normal messages
	tester.assertNotEqual( receiver.getReceivedMEssage().find("Integration.test.1 0.000000 0\nIntegration.test.1 50.000000 0\nIntegration.test.2 100.000000 0\nIntegration.test.3 9999.000000 0\n"), -1 )
Exemple #4
0
def stop():
    try:
        toolkit.verbose("Halting the system.")
        robot.stop()
        server.stop()
    except:
        toolkit.verbose("Uh-oh. An error occured when halting.")
Exemple #5
0
 def load_hhc_viewer(self, filename=None, contents=None, encoding=None, error=None):
     if not error:
         viewer = HHCViewer(filename, contents, encoding)
         viewer.show()
         server.stop() #if there is an error, no need to stop server
         self.exit_screen()
     else:
         if error == server.ERR_INVALID_CHM:
             appuifw.note(ERR_READING, "error")
         elif error == server.ERR_NO_HHC:
             appuifw.note(ERR_NO_HHC, "error")
         self.refresh()
Exemple #6
0
def toggle_measure():
    global measurement
    if measurement == False:  # Start measurement
        measurement = True
        server.measure()
        startStopMeasButton.config(text="Stop Measurement", bg="#f2b4a0")
        mssLabel.config(text="Waiting for {} responses".format(gl.ndevices))
    elif measurement == True:  # Stop measurement
        measurement = False
        server.stop()
        startStopMeasButton.config(text="Start Measurement", bg="#92f0eb")
        mssLabel.config(text="Measurement stopped")
Exemple #7
0
def dir():
    """clean the dirs"""
    banner("STOPPING SERVER")
    server.stop()
    banner("CLEAN DIR")
    local("rm -rf *.egg")
    local('find . -name "*~" -exec rm {} \;  ')
    local('find . -name "*.pyc" -exec rm {} \;  ')
    local("rm -rf build dist *.egg-info *~ #*")
    # local("cd docs; make clean")
    local("rm -rf *.egg-info")
    local("rm -f celeryd@*")
    local("rm -f *.dump")
def authenticate_user():
    url = 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=op8q0n0el0sc3wfoex530h7p4bz43yi&redirect_uri=http://localhost:8081&state=58xox58nj8z9w80mgeorni5vm9i4v1z&scope=user_read'

    # choose the correct Chrome driver for the OS
    if sys.platform == 'win32':
        chrome_driver = os.path.join(
            os.path.dirname(__file__),
            'drivers/chrome/windows_chromedriver.exe')
    elif sys.platform == 'darwin':
        chrome_driver = os.path.join(os.path.dirname(__file__),
                                     'drivers/chrome/macos_chromedriver.exe')
    else:
        chrome_driver = os.path.join(os.path.dirname(__file__),
                                     'drivers/chrome/linux_chromedriver')

    # open up Chrome
    try:
        driver = webdriver.Chrome(executable_path=chrome_driver)
    except Exception:
        print("Chrome didn't work")
        # if Chrome doesn't work, try Firefox (we don't need to use a driver here)
        try:
            driver = webdriver.Firefox()
        except Exception:
            print('No suitable web browsers found')
            sys.exit(1)

    # run the server on separate thread
    Thread(target=server.run).start()

    # navigate to the twitch authorization url
    driver.get(url)

    # set the timeout of the server
    wait = WebDriverWait(driver, 2 * 60)
    try:
        # waits until either 'Authentication successful!' shows in
        # the browser or it times out -- whichever comes first.
        wait.until(
            EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'h2'),
                                             'Authentication successful!'))

        # grab the access token from the url
        access_token = driver.current_url.split('#')[1].split('&')[0].split(
            '=')[1]

        # stop the server because we already got the access token
        server.stop()
        return access_token
    except TimeoutException:
        return None
def test_game(host, num_bots=6, gui=True):
    if not host:
        host = common.HOST

    names = [
        'chipjack',
        'hiprack ',
        'lcp69   ',
        'chipple ',
        'nipple  ',
        'ch8_px__',
        'BillyBo ',
        'bonnyho ',
        'Tman    ',
        'chipdrip',
        'yokie   ',
        'parsnip ',
        'yodeler ',
        'pikachu ',
        'mr_bean ',
        'turdhead',
        'rufus   '
        ]

    names += ['john' for i in range(50)]
    server_thread = threading.Thread(target=server.main, args=(['-s', host],))
    server_thread.start()
    if gui:
        my_client_thread = threading.Thread(target=client.main,
            args=(['-n', names[0], '-m'],))
        my_client_thread.start()
    client_threads = [threading.Thread(target=client.main, args=(['-n', name],))
        for name in names[1:num_bots+1]]
    for thread in client_threads:
        thread.start()

    if gui:
        my_client_thread.join()
    else:
        TEST_DURATION = 5
        print("Running {} sec automated game".format(TEST_DURATION))
        for i in range(TEST_DURATION):
            time.sleep(1)
            print(i+1)
        # cleanup
        server.stop()
        server_thread.join()
        print("Shutdown server")
        for thread in client_threads:
            thread.join(timeout=1)
        print("Shutdown clients")
Exemple #10
0
    def server_cmd(self, world_name, cmd):

        if cmd not in ['start', 'stop', 'reboot']:
            raise cherrypy.HTTPError(404)

        world = server.container(world_name)
        if world and cmd == 'reboot':
            port = server.ports(world)[0]
        else:
            port = server.next_port()

        if cmd == 'stop' or cmd == 'reboot':
            server.stop(world_name)
        if cmd == 'reboot' or cmd == 'start':
            server.start(world_name, port)

        return self.index(world_name)
	def test_statistics( self ):
		# Create a python request receiver to receive Normal requests from the graphite proxy (emulate the Graphite Server)
		client_port = 9999
		receiver 	  = request_receiver.RequestReceiver()
		if not receiver.connect("127.0.0.1", client_port):
			print "Impossible to connect, abort."
			receiver.stop()
			sys.exit()

		# Start Graphite Proxy
		server.start( client_port, "false", "true" )

		time.sleep(4)

		server.stop()
		receiver.stop() # Stop the server thread to be able to quit the programm properly

		# Receive normal messages
		messages = receiver.getReceivedMEssage()

		self.assertNotEqual( messages.find("stats.global_buffer.messages.max"), -1 )
		self.assertNotEqual( messages.find("stats.math_buffer.messages.max"), -1 )
		self.assertNotEqual( messages.find("stats.messages.created.nbr"), -1 )
		self.assertNotEqual( messages.find("stats.statistics.messages.created.nbr"), -1 )
Exemple #12
0
 def handle_sigint(signum, frame):
     print('SIGINT handled!')
     server.stop()
Exemple #13
0
 def tearDown(self):
     logging.info('TestRpc.tearDown')
     server.stop()
Exemple #14
0
grid = create_plane(gridArea)

# delay = pygame.time.get_ticks()

# vectors = [[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1], [-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1]]
# edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)]

while run:
    clock.tick(fps)
    key = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            if option == 2: server.stop()
            if option == 0: engine.stop()
            _exit()

        if event.type == pygame.VIDEORESIZE:
            pass

        if event.type == pygame.MOUSEBUTTONDOWN:
            pass

        if event.type == pygame.KEYDOWN:
            pass

        # if event.type == pygame.MOUSEMOTION:

    if key[pygame.K_ESCAPE]:
Exemple #15
0
def gevent_websocket_workers_pool():
    server = WorkersWebsocketPool()
    yield server
    server.stop()
Exemple #16
0
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.

import webdriver
import server
from ServoProcess import ServoProcess


def handler(self):
    return 200, [('Content-Type', 'text/html')], '<html><body>hi there</body></html>'

with ServoProcess():
    server.serve(handler)
    session = webdriver.Session('127.0.0.1', 7000)
    session.start()
    session.url = "http://localhost:8001"
    try:
        assert session.url == "http://localhost:8001/"
    except AssertionError, e:
        raise Exception("URL don`t match!")
#    session.end()
    server.stop()
Exemple #17
0
        configs = {
            'SCREEN_WIDTH': width,
            'SCREEN_HEIGHT': height,
            'CARLA_HOST': servername,
            'CARLA_PORT': carlaport,
            'AUTO_PILOT': autopilot,
            'ROLENAME': car_name,
            'FILTER': car_type,
            'WORLD_NAME': world,

            'RCNN_MODEL_PATH': rcc_model_path,
            'RCNN_MAP_PATH': rcnn_map_path,
            'RCNN_NET_DIM': rcnn_net_dim,
            'RCNN_MAX_PROPOSALS': rcnn_max_proposals,
            'RCNN_POSITIVE_CLASS': rcc_positive_class,
            'RCNN_THRESHOLD': rcnn_threshold,
            'RCNN_LOOP_COUNTER': rcnn_loop_counter,
        }

        
        create_app(width,height,debug)

        init(configs)
        loop()
        stop()

        print("Service started")
    except Exception as e:
        show_traceback(override=True)
        print("Service failed: " + str(e))
Exemple #18
0
def signal_handler(signal, frame):
    print("Received CTRL+C, stopping...")
    server.stop()
Exemple #19
0
                observation_stats = np.reshape(
                    observation_buffer, (-1, input_normalizer.num_inputs))
                input_normalizer.update(
                    sess,
                    mean=observation_stats.mean(axis=0, keepdims=True),
                    var=observation_stats.var(axis=0, keepdims=True),
                    count=observation_stats.shape[0])
                if not stats_ready:
                    progress.set_postfix_str(
                        "Initial statistics gathered, commencing training session"
                    )
                    sess.run([sync_op, set_stats_ready_op])
                    utility.apply(lambda server: server.reset(), servers)
                else:
                    progress.set_postfix_str("Update %d completed" %
                                             update_idx)

                progress.close()
                rollout_queue, stats_ready, progress = queue.Queue(
                ), True, None
                break

    if step_count > MAX_UPDATE_STEPS:
        print("Completed training process, terminating session")
        utility.apply(lambda server: server.stop(), servers)
        rollout_queue = None

utility.apply(lambda thread: thread.join(), server_threads)
bootstrap_manager.kill()
Exemple #20
0
def start_service_server(port=8080):
    try:
        server.start(app, port=port)
    except KeyboardInterrupt:
        stop_watch()
        server.stop()
Exemple #21
0
def shutdown():
    server.stop()
    return "<h3>Shutting down server...</h3>"
Exemple #22
0
 def handle_sigint(signum, frame):
     print('SIGINT handled!')
     server.stop()
Exemple #23
0
                        any_changes = True

                if any_changes:
                    with open("sessions.json", 'w') as sessions:
                        sessions.write(json.dumps(data))

                priviousOnline = online
                #Sleep for half a minute before the next check
                time.sleep(30)
        except KeyboardInterrupt:
            exit = True
            log("Stopping script...")
            #Save the data
            with open("sessions.json", 'w') as sessions:
                sessions.write(json.dumps(data))
            server.stop()
            log("Done!")
    except Exception as ex:
        log("\033[91mException:", ex, "\033[0m")
        #Write crash report
        with open("crashes.txt", 'a') as crash:
            crash.write(
                datetime.fromtimestamp(
                    get_time()).strftime("[%Y %m.%d %H:%M:%S]: "))
            crash.write(str(ex))
            crash.write("\r\n")
            crash.write(str(traceback.format_exc()))
            crash.write("\r\n")
            crash.write('=' * 40)
            crash.write("\r\n\r\n")
        log("Restarting...")