Example #1
0
def run_game(game, dockers, args, sock_file):
    '''
    This contains the logic that needs to be cleaned up at the end of a game
    If there is something that needs to be cleaned up add it in the try catch
    loop surrounding the catch loop surrounding the call of the function
    '''

    # Start the unix stream server
    server.start_server(sock_file, game, dockers)

    if args['use_viewer']:
        viewer_server = server.start_viewer_server(PORT, game)

    # Start the docker instances
    for player_key in dockers:
        docker_inst = dockers[player_key]
        docker_inst.start()
        for player_ in game.players:
            if player_['id'] == player_key:
                player = player_['player']
                break
        if player.planet == bc.Planet.Earth:
            planet = 'earth'
        else:
            planet = 'mars'
        if player.team == bc.Team.Blue:
            team = 'blue'
        else:
            team = 'red'
        name = f'[{planet}:{team}]'
        logger = Logger(name)
        docker_inst.stream_logs(line_action=logger)
        player_['logger'] = logger

    # Wait until all the code is done then clean up
    while not game.game_over:
        time.sleep(1)

    print(game.disconnected)
    print("Dumping matchfile")
    match_ptr = open("/player/" + str(args['replay_filename']), mode='w')
    match_file = {}
    match_file['message'] = game.viewer_messages
    if not game.disconnected:
        if bc.Team.Red == game.manager.winning_team():
            winner = 'player1'
        else:
            winner = 'player2'
    else:
        winner = game.winner


    match_file['metadata'] = {'player1': args['dir_p1'][8:],
            'player2' : args['dir_p2'][8:], 'winner': winner}
    json.dump(match_file, match_ptr)
    match_ptr.close()
    if args['use_viewer']:
        viewer_server.shutdown()

    return winner
Example #2
0
def main(argv):
    argv = gflags.FLAGS(argv)

    if gflags.FLAGS.port == 0: # default value
        port = int(os.environ.get("PORT", 5000))
    else:
        port = gflags.FLAGS.port
    server.start_server(port=port, num_robots_max=gflags.FLAGS.num_robots)
Example #3
0
def main(argv):
    argv = gflags.FLAGS(argv)

    if gflags.FLAGS.port is None:
        port = int(os.environ.get("PORT", 5000))
    else:
        port = gflags.FLAGS.port
    server.start_server(port)
Example #4
0
 def serve(self):
     PatchServerHandler.expected_requests = self.expected_requests
     PatchServerHandler.builds_path = self.builds_path
     for build in os.listdir(self.builds_path):
         PatchServerHandler.expected_results.append(build)
         PatchServerHandler.expected_results.append("install_%s" % build)
     PatchServerHandler.failures_path = self.failures_path
     PatchServerHandler.expected_results = os.listdir(self.builds_path)
     start_server(PatchServer, PatchServerHandler.check, host=self.address, port=self.port)
Example #5
0
 def serve(self):
     PatchServerHandler.expected_requests = self.expected_requests
     PatchServerHandler.builds_path = self.builds_path
     for build in os.listdir(self.builds_path):
         PatchServerHandler.expected_results.append(build)
         PatchServerHandler.expected_results.append("install_%s" % build)
     PatchServerHandler.failures_path = self.failures_path
     PatchServerHandler.expected_results = os.listdir(self.builds_path)
     start_server(PatchServer, PatchServerHandler.check, host=self.address, port=self.port)
Example #6
0
def main():
    parser = ArgumentParser(description="A simple chat application")
    parser.add_argument(
        "--server", help="Run server app or client", action="store_true"
    )
    parser.add_argument("--verboose", action="store_true")
    args = parser.parse_args()
    if args.server:
        start_server(args.verboose)
    else:
        start_client()
Example #7
0
 def __init__(self, quit_callback=None):
     super(TempoStatusBarApp, self).__init__("", quit_button=None)
     self.quit_button = None
     self.quit_callback = quit_callback
     self.menu = []
     self.create_menu()
     self.start = time.time()
     self.menu_is_open = False
     server.start_server()
     utils.Timer(2, self.update).start()
     log.log("Started Tempo")
Example #8
0
def controlarThreejs(cabeza, id, punto, diametro, puntoMedio):
    x = punto[0]
    y = punto[1]
    diametroCara = diametro.value
    posicion = Calculador.calcularPosicionCabeza(puntoCentro, (x, y),
                                                 diametroCara)
    cabeza = Cabeza.Cabeza((x, y), posicion, id)
    server.cabeza = cabeza
    server.diametro = diametro
    server.punto = punto
    server.puntoMedio = puntoMedio
    server.start_server()
Example #9
0
 def activate(self, shell):
     '''Activate the plugin.
     
     Activate the plugin by setting the shell and starting the server. This
     method must be overwritten, as it is indicated by the Rhythmbox
     documentation.
     '''
     print "Activating for shell", shell
     self.shell = shell
     self.player = shell.get_player()
     server.PLUGIN = self
     server.start_server()
Example #10
0
def main():
    """
        The main() function of bord.
        Reads/Sets up parameters and calls the
        generate/render methods
    """
    args = get_cmdline_arguments()
    bord_config = configreader.ConfigReader(args.config)
    count = create_html(bord_config['content_dir'], bord_config['output_dir'])
    print ('Created', count, 'HTML files')
    if (args.server):
        print ('Serving at:', str(args.server))
        server.start_server(bord_config['output_dir'], args.server)
Example #11
0
def run_server_command(*args):
    """
    Run web server for a given directory root location.

        run-server [directory]

    This is default command if none given.
    """
    root_dir = get_root_dir(*args)
    conf_file_name = os.path.join(root_dir, "somememos.conf")
    if os.path.exists(conf_file_name):
        parse_config_file(conf_file_name)

    start_server(root_dir)
Example #12
0
    async def on_ready(self):
        start_server(self)
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')
        await self.change_presence(activity=discord.Game(
            name=
            f'type $help for all commands|Currently in {len(self.guilds)} guilds'
        ))

        for guild in self.guilds:
            print(guild)
            time_trigger_msg = methods.set_interval(database.trigger_time,
                                                    config["day_length"],
                                                    guild, client)
Example #13
0
    def setUp(self):
        '''
        This function sets up up the unix stream server for all the other tests.
        It also logs both players in.
        '''
        num_players = 2
        self.game = server.Game(num_players, "")
        dockers = {}
        try:
            os.unlink(SOCK_FILE)
        except OSError:
            if os.path.exists(SOCK_FILE):
                print("File exists at connection point")
                raise

        self.server = server.start_server(SOCK_FILE, self.game, dockers,
                                          use_docker=False)

        self.conn_p1 = create_socket()
        login(self.conn_p1, self.game.player_ids[0])
        unpacked_data = recv_next_message(self.conn_p1)
        self.assertTrue(unpacked_data["logged_in"])
        self.assertEqual(unpacked_data["error"], "")

        self.conn_p2 = create_socket()
        login(self.conn_p2, self.game.player_ids[1])
        unpacked_data = recv_next_message(self.conn_p2)
        self.assertTrue(unpacked_data["logged_in"])
        self.assertEqual(unpacked_data["error"], "")
def run(server_class=HTTPServer, handle_class=ImageHttpServer, port=8070):
    socket = server.start_server()

    server_address = ('', port)
    httpd = server_class(server_address, handle_class)
    print("Image Http Server Started")
    httpd.serve_forever()
def report():
    rep = open("report.csv", "wb")
    text = [["\t\t\tCustoms Management Database Management System"],
            ["\t\t\t                             Project Amigo"],
            ["\tReports Generated on:"], ["\t%0.19s" % (datetime.now())], [""],
            [
                "MANIFEST#", "PRODUCT", "CARRIED BY", "ISSUED BY", "MODE",
                "BILL#", "DATE", "COUNTRY", "BILL AMOUNT", "FROM PORT",
                "TO PORT", "REMARKS"
            ]]
    writer = csv.writer(rep, delimiter=',')
    for each_line in text:
        writer.writerow(each_line)
    try:
        db = MySQLdb.connect("127.0.0.1", "root", "root", "customs")
    except:
        start_server()
        db = MySQLdb.connect("127.0.0.1", "root", "root", "customs")
    cursor = db.cursor()
    cursor.execute("SELECT manifest_id FROM manifest")
    manifest = cursor.fetchall()
    db.close()
    for man in manifest:
        manifest_id = man[0]
        result = Search(manifest_id)
        [
            manifest_id, description, carrier_name, issuer_name,
            transport_description, bol_id, date, country, bill_amount,
            from_port_name, to_port_name, remarks
        ] = result
        answer = [
            manifest_id, description, carrier_name, issuer_name,
            transport_description, bol_id, date, country,
            "INR %0.2f" % (bill_amount), from_port_name, to_port_name, remarks
        ]
        writer.writerow(answer)

    print "Report Generated @ %.19s" % (datetime.now())
    rep.close()


#report()
class Manager:

    ##Screen
    width, height = 950, 600
    size = width, height

    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("SpaceInvaders")

    #Server
    server = start_server()

    #InputManager
    inputManager = InputManager()

    #Introduction state
    state = StateGameServer(screen, inputManager)

    #Main Loop
    def _run(self):
        self.gameOn = True

        while self.gameOn:
            run()
            dt = fpsClock.tick(30)

            #Inputs
            self.inputManager.update()

            #Updates
            self.update(dt)

            #Renders, put in the screen
            self.render()

    #Update
    def update(self, dt):
        #state updates
        new_state = self.state.update(dt)
        if (new_state == 0):
            return

    def set_state(self, state):
        self.state.destroy()
        self.state = state

    #Render
    def render(self):
        #state renders
        self.state.render()

        #updates the display
        pygame.display.update()
Example #17
0
 def recvMessage(self):
     try:
         client = server.start_server()
         # clientMsg = server.client_thread()
         print("Connected", client)
         # msg = {'msg':clientMsg}
         # rply = {'rply':''}
         # chatData = readChat.insertMessage(self.userName,msg,rply)
         # readChat.updateJson(chatData)
         # self.conversation()
     except BaseException as ex:
         print(ex)
Example #18
0
def main():
    parser = argparse.ArgumentParser()
    for arg in ARGS:
        parser.add_argument(arg, **ARGS[arg])
    options = parser.parse_args()
    os.chdir(options.working)
    check_cache()
    if options.last:
        with open(os.path.join(CACHE_DIR, 'last.txt'), 'w') as lastfile:
            for key, value in json.load(lastfile).iteritems():
                setattr(options, key, value)
        os.chdir(options.working)
    else:
        with open(os.path.join(CACHE_DIR, 'last.txt'), 'w') as lastfile:
            json.dump(vars(options), lastfile)
    if not os.path.exists(options.jar):
        print "Can't find minecraft_server.jar."
        res = raw_input('Download now? [y/N] ')
        if res.startswith('y') or res.startswith('Y'):
            download_server(options.jar)
        else:
            print 'fatal: no minecraft_server.jar.'
            return 1
    options.cachedir = CACHE_DIR
    dataname = os.path.join(options.cachedir, 'data.p')
    data = datafunc.get_data()
    if os.path.exists(dataname):
        with open(dataname) as datafile:
            data.update(pickle.load(datafile))
    datafunc.set_options(options)
    disp = ui.get_disp(options)
    server.start_server(disp)
    disp.wait()
    instances.Instance.stop_all()
    server.stop_server()
    with open(dataname, 'w') as datafile:
        pickle.dump(datafunc.get_data(), datafile)
    print
    sys.exit(0)
Example #19
0
def main():
    parser = argparse.ArgumentParser()
    for arg in ARGS:
        parser.add_argument(arg, **ARGS[arg])
    options = parser.parse_args()
    os.chdir(options.working)
    check_cache()
    if options.last:
        with open(os.path.join(CACHE_DIR, 'last.txt'), 'w') as lastfile:
            for key, value in json.load(lastfile).iteritems():
                setattr(options, key, value)
        os.chdir(options.working)
    else:
        with open(os.path.join(CACHE_DIR, 'last.txt'), 'w') as lastfile:
            json.dump(vars(options), lastfile)
    if not os.path.exists(options.jar):
        print "Can't find minecraft_server.jar."
        res = raw_input('Download now? [y/N] ')
        if res.startswith('y') or res.startswith('Y'):
            download_server(options.jar)
        else:
            print 'fatal: no minecraft_server.jar.'
            return 1
    options.cachedir = CACHE_DIR
    dataname = os.path.join(options.cachedir, 'data.p')
    data = datafunc.get_data()
    if os.path.exists(dataname):
        with open(dataname) as datafile:
            data.update(pickle.load(datafile))
    datafunc.set_options(options)
    disp = ui.get_disp(options)
    server.start_server(disp)
    disp.wait()
    instances.Instance.stop_all()
    server.stop_server()
    with open(dataname, 'w') as datafile:
        pickle.dump(datafunc.get_data(), datafile)
    print
    sys.exit(0)
Example #20
0
def test_durability(repeat):
    server_log_base = server.log_dir + "dur_server_%d.log" % repeat
    client_log_base = server.log_dir + "dur_client_%d.log" % repeat
    server.start_server(extra_args=server_args, log=server_log_base+".1")
    try:
        lsn = 0

        client = Client(server.addr, server.port, log=client_log_base+".1")
        repeat_deposit(client, repeat, 100)
        lsn += repeat + 1
        saved = server.save_db()

        repeat_deposit(client, repeat, 100)
        lsn += repeat
        client.log.close()

        client = Client(server.addr, server.port, log=client_log_base+".1")
        repeat_deposit(client, repeat, 200)
        lsn += repeat + 1
        client.log.close()

        server.stop_server()
        server.restore_db(saved)
        server.start_server(extra_args=server_args, log=server_log_base+".2", remove_old=False)

        client = Client(server.addr, server.port, log=client_log_base+".2", auto_open=False)
        client.id = 1
        _, _, new = client.deposit(0)
        assert new == repeat * 200
        client.id = 2
        _, _, new = client.deposit(0)
        assert new == repeat * 200
        lsn += 2

        client.log.close()
        data.assert_lsn_id(lsn, 2)
    finally:
        server.stop_server()
Example #21
0
 def execute_server_backend(self, platform_name, subid, action, row):
     '''
     后台执行server操作
     '''
     operation_result = False
     name = self.get_select_apikey_name()
     if action == 'start':
         operation_result = server.start_server(platform_name, name, subid)
     elif action == 'stop':
         operation_result = server.stop_server(platform_name, name, subid)
     elif action == 'restart':
         operation_result = server.reboot_server(platform_name, name, subid)
     wx.CallAfter(self.callback_execute_server, action, operation_result,
                  row)
Example #22
0
def connect_to_clients(t):
    """Establish the connections to the clients.

    Modifies table (t) with Player info in-place
    Returns clients (a list of two)
    """
    sockets = start_server()
    clients = [connect_client(s) for s in sockets]
    for i, client in enumerate(clients):
        message_to_client('What is your name?', client)
        name = answer_from_client(client)
        print('{} joined'.format(name))
        t.players += [Player(name, PORTS[i])]
    return clients
Example #23
0
def test_tcp():
    ''' Testing tcp transport between a client and a server '''
    que = queue.Queue()
    t_1 = start_server(que, '127.0.0.1', 65410, 10)
    t_1.start()

    msg = b'EWP 0.2 RPC 0 25\n{"id":1,"method_id":0x00}'
    t_2 = start_client('127.0.0.1', 65410, msg)
    t_2.start()
    t_2.join()
    t_1.join()
    result = que.get()
    if result != msg:
        raise AssertionError()
Example #24
0
def main():
    # print("Configure server parameters :")
    # IPAdr = input("IP : ")
    # port = int(input("Port : "))
    IPAdr = '127.0.0.2'
    port = 5000

    print("Waiting for planner to connect...")
    objectives_coord, static_obj_coord, \
        robots_coord, move_list, conf_list \
        = server.start_server(IPAdr, port)

    simu = Simulator(robots_coord, objectives_coord, static_obj_coord,
                     move_list, conf_list)
    return simu
Example #25
0
    def setUp(self):
        '''
        This function setusp up the unix stream server for all the other tests.
        '''
        num_players = 2
        self.game = server.Game(num_players)
        dockers = {}
        try:
            os.unlink(SOCK_FILE)
        except OSError:
            if os.path.exists(SOCK_FILE):
                print("File exists at connection point")
                raise

        self.server = server.start_server(SOCK_FILE, self.game, dockers,
                                          use_docker=False)
Example #26
0
def serve():
    """
    Start the server (see server.py) and then check every second to see
    if a file changes, if so,  rebuild the site.

    It's not efficient, it just sees if ANY file that isn't hidden changes.
    """
    build_site()
    olds=" ".join([" ".join(["%f"%os.stat(dir+"/"+f).st_mtime for f in files if f[0]!='.']) for (dir,subs,files) in os.walk(config['content'])])
    pid = server.start_server()
    while  True:
        time.sleep(1)
        news=" ".join([" ".join(["%f"%os.stat(dir+"/"+f).st_mtime for f in files if f[0] !='.']) for (dir,subs,files) in os.walk(config['content'])])
        if news!=olds:
            print "REBUILDING"
            build_site()
            olds = news
def connect_method(connection_obj):
    '''
		Establishing a tunnel along to the server,
		generating the payload format and then sending it to the client. 
	'''
    socket_obj, buffer_size, logfile = server.start_server()
    ip_address = server.connect(socket_obj, buffer_size, logfile)
    CRLF, SP = "\r\n", " "
    status_code = "204" + SP
    message = "HTTP/1.1 204 No Content" + CRLF
    server = "Server: " + ip_address + CRLF
    connection = "Connection: Keep-Alive" + CRLF
    date = sub_methods.current_date() + CRLF
    '''
		Forming the actual payload/response message by attaching the header values. 
	'''
    payload = status_code + message + server + connection + date
    try:
        connection_obj.send(payload.encode())
    except socket.error as e:
        print("Error: {}".format(e))
        sys.exit(1)
Example #28
0
async def main(config):
    common_config = config["common"]
    broadcast_config = config["broadcast"]

    # Set up debug printing, defaulting to "ALL"
    log_lvl = log_levels[common_config.get("debug_level", "ALL")]
    log_format = "%(asctime)s %(levelname)s %(message)s"
    logging.basicConfig(format=log_format, level=log_lvl, datefmt="%H:%M:%S")

    # Create a broadcast server and a data container if broadcast is active.
    if broadcast_config["active"]:
        container: Optional[DataContainer] = DataContainer()
        config["broadcast_container"] = container
    else:
        container = None

    # Choose the listener function based on config.
    if common_config["source"] == "network":
        listener = network_listener
    elif common_config["source"] == "serial":
        listener = serial_listener
    else:
        logging.error("Source is neither 'network' nor 'serial'.")
        return

    # Start the necessary tasks. Quit on KeyboardInterrupt.
    try:
        if broadcast_config["active"]:
            assert container is not None  # for type checking, we know this is true here
            await asyncio.gather(uploader(config, listener),
                                 start_server(config, container))
        else:
            await uploader(config, listener)
    except KeyboardInterrupt:
        logging.info("Trying to shut down gracefully.")
        loop = asyncio.get_event_loop()
        loop.stop()
def run_game(game, dockers, args, sock_file):
    '''
    This contains the logic that needs to be cleaned up at the end of a game
    If there is something that needs to be cleaned up add it in the try catch
    loop surrounding the catch loop surrounding the call of the function
    '''

    # Start the unix stream server
    main_server = server.start_server(sock_file, game, dockers)

    viewer_server = server.start_viewer_server(PORT, game) if args['use_viewer'] else None

    # Start the docker instances
    for player_key in dockers:
        docker_inst = dockers[player_key]
        docker_inst.start()
        for player_ in game.players:
            if player_['id'] == player_key:
                player = player_['player']
                break
        if player.planet == bc.Planet.Earth:
            planet = 'earth'
        else:
            planet = 'mars'
        if player.team == bc.Team.Blue:
            team = 'blue'
        else:
            team = 'red'
        name = f'[{planet}:{team}]'
        logger = Logger(name)
        docker_inst.stream_logs(line_action=logger)
        player_['logger'] = logger

    # Wait until all the code is done then clean up
    while not game.game_over:
        time.sleep(0.1)

    print('Killing game server.')
    main_server.shutdown()
    try:
        main_server.server_close()
    except e:
        print(e)

    match_file = {}
    match_file['message'] = game.viewer_messages
    if not game.disconnected:
        if bc.Team.Red == game.manager.winning_team():
            winner = 'player1'
        else:
            winner = 'player2'
    else:
        winner = game.winner

    match_file['metadata'] = {
        'player1': args['dir_p1'][8:],
        'player2': args['dir_p2'][8:],
        'winner': winner
    }

    if args['docker']:
        match_output = abspath(os.path.join('/player', str(args['replay_filename'])))
    else:
        match_output = args['replay_filename']
        if not os.path.isabs(match_output):
            match_output = abspath(os.path.join('..', str(match_output)))

    print("Dumping matchfile to", match_output)
    match_ptr = open(match_output, 'w')
    json.dump(match_file, match_ptr)
    match_ptr.close()
    if viewer_server is not None:
        viewer_server.shutdown()

    return winner
Example #30
0
import sys, os
from server import start_server
from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from app.models.tables import DataBase
from app.settings import DATA_BASE

if __name__ == '__main__':
    PORT = "8080"
    HOST = "0.0.0.0"
    db = DataBase(DATA_BASE)
    db.boot_database()
    try :
        start_server(sys.argv[1])
    except :
        start_server("%s:%s" % (HOST,PORT))
Example #31
0
def main():
    chart.update_chart(PATH_GRAPH)
    start_server(WEB_PORT, TCP_PORT, on_data)
Example #32
0
import server
import amcp
import time
import keyboard

### Small disclaimer, the match has to run, in order for this work.

#Starts the server
try:
    print("Initialize FASE 1")
    server = server.GSIServer(("127.0.0.1", 3000), "S8RL9Z6Y22TYQK45JB4V8PHRJJMD9DS9")
    print("Almost there")
    server.start_server()
    print("Server started")
except:
    print("Oepsie")

# All the Caspar paths.
HTMLTemplate = 'PLAY 1-15 "CASPARJS2/01_INTERVIEW" easenone 1 Linear RIGHT'

TBombPlanted = 'PLAY 1-14 "GUI-ELEMENTS/CSGO-BOMB-GRAPHS/T_BOMB_KABOOM"'
TCleanUpAfterPlant = 'PLAY 1-14 "GUI-ELEMENTS/CSGO-BOMB-GRAPHS/T_CLEAN_UP"'
TClean = 'PLAY 1-14 "GUI-ELEMENTS/CSGO-BOMB-GRAPHS/T_CLEAN"'

CTDefuse = 'PLAY 1-14 "GUI-ELEMENTS/CSGO-BOMB-GRAPHS/CT_DEFUSE"'
CTClean = 'PLAY 1-14 "GUI-ELEMENTS/CSGO-BOMB-GRAPHS/CT_CLEAN"'

# For the UI Elements.
uiSide = "Left"
visible = False
planted = False
Example #33
0
    config['WIFI_IP'] = ifconfig[0]
    config['WIFI_MASK'] = ifconfig[1]
    config['WIFI_DNS'] = ifconfig[2]
    config['WIFI_GATEWAY'] = ifconfig[3]
    config['AUTO_IP_CONFIG'] = "NO"
    print('Saving to file...')
    with open('config.json', 'w') as f:
        json.dump(config, f)
    print('saved')

print('Connection successful')
print(station.ifconfig())
print('Writing config.js...')
with open("www/scripts/config.js", 'w') as f:
    f.write("const device_ip = \"%s\"" % (config['WIFI_IP']))
mac = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode()
print(mac)
#-----------------------------#

# Web server init
try:
    print("Starting web server...")
    server.start_server(relay, dht11, DEBUG_MODE)
except:
    print("Failed to start server")
    print("Attempt to start WebRepl")
    webrepl.start()
print("Starting REPL...")
webrepl.start()
#-----------------------------#
Example #34
0
def start_backend():
    try:
        start_server()
    except Exception as e:
        print("WARNING: Could not start HTTP service: " + str(e))
 def testUnknownServerReq(self):
     with self.assertRaises(ValueError):
         start_server()
Example #36
0
def run_processes(stop_event):

	child = subprocess.Popen('sketch_150125a\\application.windows64\\sketch_150125a')
	server.start_server()
Example #37
0
def runserver():
    run("mkdir -p static/screenshots")
    start_server()
Example #38
0
#!/usr/bin/env python
import server
import warnings
import argparse
from lib.log import log

# Get rid of those f*cking warnings of Flask
warnings.filterwarnings("ignore")

parser = argparse.ArgumentParser()
parser.add_argument("-l", "--log", help="Logs the output to a log file.", action="store_true")

args = parser.parse_args()

if args.log:
    import sys
    import time
    sys.stderr = open("./log/%s.txt" %(time.strftime('%d-%m-%y %H:%M:%S')), "w")
    sys.stdout = sys.stderr

log("Starting server")

server.start_server()
Example #39
0
def server_go(threadName):
   server.start_server(10000,command,pre_room)
Example #40
0
    return home(request, response)


def build_routes():
    server.add_route('get', '/', home)
    server.add_route('get', '/login', login)
    server.add_route('post', '/verify', verify)
    server.add_route('get', '/profile', profile)
    server.add_route('post', '/update_user', update_profile)
    server.add_route('get', '/write', write)
    server.add_route('post', '/new_blog', new_blog)
    server.add_route('get', '/admin', admin)
    server.add_route('post', '/new_user', new_user)


def logger(request, response):
    print 'Got the', request['method'], 'method from client', request[
        'address'], 'for', request['path']
    return request


def put_middleware():
    server.add_middleware(logger)


if __name__ == "__main__":
    port = int(raw_input("PORT>"))
    put_middleware()
    build_routes()
    server.start_server("0.0.0.0", port, 20)
Example #41
0
def run_game(game, dockers, args, sock_file, scrimmage=False):
    '''
    This contains the logic that needs to be cleaned up at the end of a game
    If there is something that needs to be cleaned up add it in the try catch
    loop surrounding the catch loop surrounding the call of the function
    '''

    # Start the unix stream server
    main_server = server.start_server(sock_file, game, dockers)

    viewer_server = server.start_viewer_server(
        PORT, game) if args['use_viewer'] else None

    try:
        # Start the docker instances
        for player_key in dockers:
            docker_inst = dockers[player_key]
            docker_inst.start()
            for player_ in game.players:
                if player_['id'] == player_key:
                    player = player_['player']
                    break
            if player.planet == bc.Planet.Earth:
                planet = 'earth'
            else:
                planet = 'mars'
            if player.team == bc.Team.Blue:
                team = 'blue'
            else:
                team = 'red'

            name = '[{}:{}]'.format(planet, team)
            logger = Logger(name,
                            print=(not args['terminal_viewer']
                                   and not scrimmage))
            docker_inst.stream_logs(line_action=logger)
            player_['logger'] = logger

        # Wait until all the code is done then clean up
        while not game.game_over:
            time.sleep(0.1)

    finally:
        main_server.shutdown()
        try:
            main_server.server_close()
        except e:
            print(e)

        if viewer_server is not None:
            viewer_server.shutdown()

    match_file = {}
    match_file['message'] = game.viewer_messages
    if not game.disconnected:
        if bc.Team.Red == game.manager.winning_team():
            winner = 'player1'
        else:
            winner = 'player2'
    else:
        winner = game.winner

    match_file['metadata'] = {
        'player1': 'player1' if scrimmage else args['dir_p1'][8:],
        'player2': 'player2' if scrimmage else args['dir_p2'][8:],
        'winner': winner
    }

    if args['docker']:
        match_output = abspath(
            os.path.join('/player', str(args['replay_filename'])))
    else:
        match_output = args['replay_filename']
        if not os.path.isabs(match_output):
            match_output = abspath(os.path.join('..', str(match_output)))

    if not scrimmage:
        print("Saving replay to", match_output)

        match_ptr = open(match_output, 'w')
        json.dump(match_file, match_ptr)
        match_ptr.close()

        return winner
    else:
        return winner, match_file
Example #42
0
    def setup(self):
        if G.SINGLEPLAYER:
            try:
                print 'Starting internal server...'
                # TODO: create world menu
                G.SAVE_FILENAME = "world"
                start_server(internal=True)
                sock = socket.socket()
                sock.connect(("localhost", 1486))
            except socket.error as e:
                print "Socket Error:", e
                #Otherwise back to the main menu we go
                return False
            except Exception as e:
                print 'Unable to start internal server'
                import traceback
                traceback.print_exc()
                return False
        else:
            try:
                #Make sure the address they want to connect to works
                ipport = G.IP_ADDRESS.split(":")
                if len(ipport) == 1: ipport.append(1486)
                sock = socket.socket()
                sock.connect((tuple(ipport)))
            except socket.error as e:
                print "Socket Error:", e
                #Otherwise back to the main menu we go
                return False

        self.init_gl()

        sky_rotation = -20.0  # -20.0

        # TERRAIN_CHOICE = self.biome_generator.get_biome_type(sector[0], sector[2])
        default_skybox = 'skydome.jpg'
        #if TERRAIN_CHOICE == G.NETHER:
        #    default_skybox = 'skydome_nether.jpg'
        #else:
        #    default_skybox = 'skybox.jpg'

        print 'loading ' + default_skybox

        self.skydome = Skydome(
            'resources/' + default_skybox,
            #'resources/skydome.jpg',
            0.7,
            100.0,
            sky_rotation,
        )

        self.player_ids = {
        }  # Dict of all players this session, indexes are their ID's [0: first Player on server,]

        self.focus_block = Block(width=1.05, height=1.05)
        self.earth = vec(0.8, 0.8, 0.8, 1.0)
        self.white = vec(1.0, 1.0, 1.0, 1.0)
        self.ambient = vec(1.0, 1.0, 1.0, 1.0)
        self.polished = GLfloat(100.0)
        self.crack_batch = pyglet.graphics.Batch()

        #if G.DISABLE_SAVE and world_exists(G.game_dir, G.SAVE_FILENAME):
        #    open_world(self, G.game_dir, G.SAVE_FILENAME)

        self.world = World()
        self.packetreceiver = PacketReceiver(self.world, self, sock)
        self.world.packetreceiver = self.packetreceiver
        G.CLIENT = self.packetreceiver
        self.packetreceiver.start()

        #Get our position from the server
        self.packetreceiver.request_spawnpos()
        #Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall
        self.update_disabled = self.update
        self.update = lambda dt: None
        #We'll re-enable it when the server tells us where we should be

        self.player = Player(game_mode=G.GAME_MODE)
        print('Game mode: ' + self.player.game_mode)
        self.item_list = ItemSelector(self, self.player, self.world)
        self.inventory_list = InventorySelector(self, self.player, self.world)
        self.item_list.on_resize(self.window.width, self.window.height)
        self.inventory_list.on_resize(self.window.width, self.window.height)
        self.text_input = TextWidget(self.window,
                                     '',
                                     0,
                                     0,
                                     self.window.width,
                                     visible=False,
                                     font_name=G.CHAT_FONT)
        self.text_input.push_handlers(on_toggled=self.on_text_input_toggled,
                                      key_released=self.text_input_callback)
        self.chat_box = TextWidget(self.window,
                                   '',
                                   0,
                                   self.text_input.y + self.text_input.height +
                                   50,
                                   self.window.width / 2,
                                   height=min(300, self.window.height / 3),
                                   visible=False,
                                   multi_line=True,
                                   readonly=True,
                                   font_name=G.CHAT_FONT,
                                   text_color=(255, 255, 255, 255),
                                   background_color=(0, 0, 0, 100),
                                   enable_escape=True)
        self.camera = Camera3D(target=self.player)

        if G.HUD_ENABLED:
            self.label = pyglet.text.Label('',
                                           font_name='Arial',
                                           font_size=8,
                                           x=10,
                                           y=self.window.height - 10,
                                           anchor_x='left',
                                           anchor_y='top',
                                           color=(255, 255, 255, 255))

        #if G.DEBUG_TEXT_ENABLED:
        #    self.debug_text = TextWidget(self.window, '',
        #                           0, self.window.height - 300,
        #                           500, 300,
        #                           visible=True, multi_line=True, readonly=True,
        #                           font_name='Arial', font_size=10,
        #                           text_color=(255, 255, 255, 255),
        #                           background_color=(0, 0, 0, 0))
        pyglet.clock.schedule_interval_soft(self.world.process_queue,
                                            1.0 / G.MAX_FPS)
        pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 10.0,
                                            self.player)
        return True
Example #43
0
# random_forecast.py
__author__ = 'fanbin'


import bindata

import math
import random
import event
import talib
import asyncore
from server import start_server

if __name__ == "__main__":

    # computation engine initialized
    print "Computation engine set up"
    # event loop start
    print "Waiting for backtesting request"
    start_server()
def run_on_server():
    server.start_server()
Example #45
0
# random_forecast.py
__author__ = 'fanbin'

import bindata

import math
import random
import event
import talib
import asyncore
from server import start_server

if __name__ == "__main__":

    # computation engine initialized
    print "Computation engine set up"
    # event loop start
    print "Waiting for backtesting request"
    start_server()
Example #46
0
def main(cfg):
    # Start kraken
    print(pyfiglet.figlet_format("kraken"))
    logging.info("Starting kraken")

    # Parse and read the config
    if os.path.isfile(cfg):
        with open(cfg, "r") as f:
            config = yaml.full_load(f)
        global kubeconfig_path, wait_duration
        distribution = config["kraken"].get("distribution", "openshift")
        kubeconfig_path = config["kraken"].get("kubeconfig_path", "")
        chaos_scenarios = config["kraken"].get("chaos_scenarios", [])
        publish_running_status = config["kraken"].get("publish_kraken_status",
                                                      False)
        port = config["kraken"].get("port", "8081")
        run_signal = config["kraken"].get("signal_state", "RUN")
        litmus_version = config["kraken"].get("litmus_version", "v1.9.1")
        litmus_uninstall = config["kraken"].get("litmus_uninstall", False)
        wait_duration = config["tunings"].get("wait_duration", 60)
        iterations = config["tunings"].get("iterations", 1)
        daemon_mode = config["tunings"].get("daemon_mode", False)
        deploy_performance_dashboards = config["performance_monitoring"].get(
            "deploy_dashboards", False)
        dashboard_repo = config["performance_monitoring"].get(
            "repo",
            "https://github.com/cloud-bulldozer/performance-dashboards.git"
        )  # noqa
        capture_metrics = config["performance_monitoring"].get(
            "capture_metrics", False)
        kube_burner_url = config["performance_monitoring"].get(
            "kube_burner_binary_url",
            "https://github.com/cloud-bulldozer/kube-burner/releases/download/v0.9.1/kube-burner-0.9.1-Linux-x86_64.tar.gz",  # noqa
        )
        config_path = config["performance_monitoring"].get(
            "config_path", "config/kube_burner.yaml")
        metrics_profile = config["performance_monitoring"].get(
            "metrics_profile_path", "config/metrics-aggregated.yaml")
        prometheus_url = config["performance_monitoring"].get(
            "prometheus_url", "")
        prometheus_bearer_token = config["performance_monitoring"].get(
            "prometheus_bearer_token", "")
        run_uuid = config["performance_monitoring"].get("uuid", "")
        enable_alerts = config["performance_monitoring"].get(
            "enable_alerts", False)
        alert_profile = config["performance_monitoring"].get(
            "alert_profile", "")

        # Initialize clients
        if not os.path.isfile(kubeconfig_path):
            logging.error(
                "Cannot read the kubeconfig file at %s, please check" %
                kubeconfig_path)
            sys.exit(1)
        logging.info("Initializing client to talk to the Kubernetes cluster")
        os.environ["KUBECONFIG"] = str(kubeconfig_path)
        kubecli.initialize_clients(kubeconfig_path)

        # find node kraken might be running on
        kubecli.find_kraken_node()

        # Set up kraken url to track signal
        if not 0 <= int(port) <= 65535:
            logging.info("Using port 8081 as %s isn't a valid port number" %
                         (port))
            port = 8081
        address = ("0.0.0.0", port)

        # If publish_running_status is False this should keep us going in our loop below
        if publish_running_status:
            server_address = address[0]
            port = address[1]
            logging.info("Publishing kraken status at http://%s:%s" %
                         (server_address, port))
            server.start_server(address)
            publish_kraken_status(run_signal)

        # Cluster info
        logging.info("Fetching cluster info")
        cluster_version = runcommand.invoke("kubectl get clusterversion", 60)
        cluster_info = runcommand.invoke(
            "kubectl cluster-info | awk 'NR==1' | sed -r "
            "'s/\x1B\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g'", 60)  # noqa
        logging.info("\n%s%s" % (cluster_version, cluster_info))

        # Deploy performance dashboards
        if deploy_performance_dashboards:
            performance_dashboards.setup(dashboard_repo)

        # Generate uuid for the run
        if run_uuid:
            logging.info("Using the uuid defined by the user for the run: %s" %
                         run_uuid)
        else:
            run_uuid = str(uuid.uuid4())
            logging.info("Generated a uuid for the run: %s" % run_uuid)

        # Initialize the start iteration to 0
        iteration = 0

        # Set the number of iterations to loop to infinity if daemon mode is
        # enabled or else set it to the provided iterations count in the config
        if daemon_mode:
            logging.info(
                "Daemon mode enabled, kraken will cause chaos forever\n")
            logging.info("Ignoring the iterations set")
            iterations = float("inf")
        else:
            logging.info(
                "Daemon mode not enabled, will run through %s iterations\n" %
                str(iterations))
            iterations = int(iterations)

        failed_post_scenarios = []
        litmus_installed = False

        # Capture the start time
        start_time = int(time.time())

        # Loop to run the chaos starts here
        while int(iteration) < iterations and run_signal != "STOP":
            # Inject chaos scenarios specified in the config
            logging.info("Executing scenarios for iteration " + str(iteration))
            if chaos_scenarios:
                for scenario in chaos_scenarios:
                    if publish_running_status:
                        run_signal = server.get_status(address)
                    if run_signal == "PAUSE":
                        while publish_running_status and run_signal == "PAUSE":
                            logging.info(
                                "Pausing Kraken run, waiting for %s seconds and will re-poll signal"
                                % str(wait_duration))
                            time.sleep(wait_duration)
                            run_signal = server.get_status(address)
                    if run_signal == "STOP":
                        logging.info("Received STOP signal; ending Kraken run")
                        break
                    scenario_type = list(scenario.keys())[0]
                    scenarios_list = scenario[scenario_type]
                    if scenarios_list:
                        # Inject pod chaos scenarios specified in the config
                        if scenario_type == "pod_scenarios":
                            logging.info("Running pod scenarios")
                            failed_post_scenarios = pod_scenarios.run(
                                kubeconfig_path, scenarios_list, config,
                                failed_post_scenarios, wait_duration)
                        elif scenario_type == "container_scenarios":
                            logging.info("Running container scenarios")
                            failed_post_scenarios = pod_scenarios.container_run(
                                kubeconfig_path, scenarios_list, config,
                                failed_post_scenarios, wait_duration)

                        # Inject node chaos scenarios specified in the config
                        elif scenario_type == "node_scenarios":
                            logging.info("Running node scenarios")
                            nodeaction.run(scenarios_list, config,
                                           wait_duration)

                        # Inject time skew chaos scenarios specified in the config
                        elif scenario_type == "time_scenarios":
                            logging.info("Running time skew scenarios")
                            time_actions.run(scenarios_list, config,
                                             wait_duration)

                        # Inject litmus based chaos scenarios
                        elif scenario_type == "litmus_scenarios":
                            logging.info("Running litmus scenarios")
                            litmus_namespace = "litmus"
                            if not litmus_installed:
                                # Will always uninstall first
                                common_litmus.delete_chaos(litmus_namespace)
                                common_litmus.delete_chaos_experiments(
                                    litmus_namespace)
                                common_litmus.uninstall_litmus(
                                    litmus_version, litmus_namespace)
                                common_litmus.install_litmus(
                                    litmus_version, litmus_namespace)
                                common_litmus.deploy_all_experiments(
                                    litmus_version, litmus_namespace)
                                litmus_installed = True
                                common_litmus.run(
                                    scenarios_list,
                                    config,
                                    litmus_uninstall,
                                    wait_duration,
                                    litmus_namespace,
                                )

                        # Inject cluster shutdown scenarios
                        elif scenario_type == "cluster_shut_down_scenarios":
                            shut_down.run(scenarios_list, config,
                                          wait_duration)

                        # Inject namespace chaos scenarios
                        elif scenario_type == "namespace_scenarios":
                            logging.info("Running namespace scenarios")
                            namespace_actions.run(scenarios_list, config,
                                                  wait_duration,
                                                  failed_post_scenarios,
                                                  kubeconfig_path)

                        # Inject zone failures
                        elif scenario_type == "zone_outages":
                            logging.info("Inject zone outages")
                            zone_outages.run(scenarios_list, config,
                                             wait_duration)

                        # Application outages
                        elif scenario_type == "application_outages":
                            logging.info("Injecting application outage")
                            application_outage.run(scenarios_list, config,
                                                   wait_duration)

                        # PVC scenarios
                        elif scenario_type == "pvc_scenarios":
                            logging.info("Running PVC scenario")
                            pvc_scenario.run(scenarios_list, config)

            iteration += 1
            logging.info("")

        # Capture the end time
        end_time = int(time.time())

        # Capture metrics for the run
        if capture_metrics:
            logging.info("Capturing metrics")
            kube_burner.setup(kube_burner_url)
            kube_burner.scrape_metrics(
                distribution,
                run_uuid,
                prometheus_url,
                prometheus_bearer_token,
                start_time,
                end_time,
                config_path,
                metrics_profile,
            )

        # Check for the alerts specified
        if enable_alerts:
            logging.info("Alerts checking is enabled")
            kube_burner.setup(kube_burner_url)
            if alert_profile:
                kube_burner.alerts(
                    distribution,
                    prometheus_url,
                    prometheus_bearer_token,
                    start_time,
                    end_time,
                    alert_profile,
                )
            else:
                logging.error("Alert profile is not defined")
                sys.exit(1)

        if litmus_uninstall and litmus_installed:
            common_litmus.delete_chaos(litmus_namespace)
            common_litmus.delete_chaos_experiments(litmus_namespace)
            common_litmus.uninstall_litmus(litmus_version, litmus_namespace)

        if failed_post_scenarios:
            logging.error(
                "Post scenarios are still failing at the end of all iterations"
            )
            sys.exit(1)

        run_dir = os.getcwd() + "/kraken.report"
        logging.info(
            "Successfully finished running Kraken. UUID for the run: %s. Report generated at %s. Exiting"
            % (run_uuid, run_dir))
    else:
        logging.error("Cannot find a config at %s, please check" % (cfg))
        sys.exit(1)
Example #47
0
def admin(request, response):
    with open("./views/admin.html", "r") as fd:
        server.send_html_handler(request, response, fd.read())


def new_user(request, response):
    content = request['content']
    session_data = server.get_session(request, response)
    if session_data and 'user' in session_data:
        new_user = content['user'][0]
        redis_server.sadd('all_users', new_user)
    return home(request, response)


def build_routes():
    server.add_route('get', '/', home)
    server.add_route('get', '/login', login)
    server.add_route('post', '/verify', verify)
    server.add_route('get', '/profile', profile)
    server.add_route('post', '/update_user', update_profile)
    server.add_route('get', '/write', write)
    server.add_route('post', '/new_blog', new_blog)
    server.add_route('get', '/admin', admin)
    server.add_route('post', '/new_user', new_user)


if __name__ == "__main__":
    port = int(raw_input("PORT>"))
    build_routes()
    server.start_server("127.0.0.1", port, 20)
Example #48
0
    def setup(self):
        if G.SINGLEPLAYER:
            try:
                print 'Starting internal server...'
                # TODO: create world menu
                G.SAVE_FILENAME = "world"
                start_server(internal=True)
                sock = socket.socket()
                sock.connect(("localhost", 1486))
            except socket.error as e:
                print "Socket Error:", e
                #Otherwise back to the main menu we go
                return False
            except Exception as e:
                print 'Unable to start internal server'
                import traceback
                traceback.print_exc()
                return False
        else:
            try:
                #Make sure the address they want to connect to works
                ipport = G.IP_ADDRESS.split(":")
                if len(ipport) == 1: ipport.append(1486)
                sock = socket.socket()
                sock.connect((tuple(ipport)))
            except socket.error as e:
                print "Socket Error:", e
                #Otherwise back to the main menu we go
                return False

        self.init_gl()

        sky_rotation = -20.0  # -20.0

       # TERRAIN_CHOICE = self.biome_generator.get_biome_type(sector[0], sector[2])
        default_skybox = 'skydome.jpg'
        #if TERRAIN_CHOICE == G.NETHER:
        #    default_skybox = 'skydome_nether.jpg'
        #else:
        #    default_skybox = 'skybox.jpg'

        print 'loading ' + default_skybox

        self.skydome = Skydome(
            'resources/' + default_skybox,
            #'resources/skydome.jpg',
            0.7,
            100.0,
            sky_rotation,
        )

        self.player_ids = {}  # Dict of all players this session, indexes are their ID's [0: first Player on server,]

        self.focus_block = B.Block(width=1.05, height=1.05)
        self.earth = vec(0.8, 0.8, 0.8, 1.0)
        self.white = vec(1.0, 1.0, 1.0, 1.0)
        self.ambient = vec(1.0, 1.0, 1.0, 1.0)
        self.polished = GLfloat(100.0)
        self.crack_batch = pyglet.graphics.Batch()

        #if G.DISABLE_SAVE and world_exists(G.game_dir, G.SAVE_FILENAME):
        #    open_world(self, G.game_dir, G.SAVE_FILENAME)

        self.world = World()
        self.packetreceiver = PacketReceiver(self.world, self, sock)
        self.world.packetreceiver = self.packetreceiver
        G.CLIENT = self.packetreceiver
        self.packetreceiver.start()

        #Get our position from the server
        self.packetreceiver.request_spawnpos()
        #Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall
        self.update_disabled = self.update
        self.update = lambda dt: None
        #We'll re-enable it when the server tells us where we should be

        self.player = Player(game_mode=G.GAME_MODE)
        print('Game mode: ' + self.player.game_mode)
        self.item_list = ItemSelector(self, self.player, self.world)
        self.inventory_list = InventorySelector(self, self.player, self.world)
        self.item_list.on_resize(self.window.width, self.window.height)
        self.inventory_list.on_resize(self.window.width, self.window.height)
        self.text_input = TextWidget(self.window, '',
                                     0, 0,
                                     self.window.width,
                                     visible=False,
                                     font_name=G.CHAT_FONT)
        self.text_input.push_handlers(on_toggled=self.on_text_input_toggled, key_released=self.text_input_callback)
        self.chat_box = TextWidget(self.window, '',
                                   0, self.text_input.y + self.text_input.height + 50,
                                   self.window.width / 2, height=min(300, self.window.height / 3),
                                   visible=False, multi_line=True, readonly=True,
                                   font_name=G.CHAT_FONT,
                                   text_color=(255, 255, 255, 255),
                                   background_color=(0, 0, 0, 100),
                                   enable_escape=True)
        self.camera = Camera3D(target=self.player)
        if G.HUD_ENABLED:
            self.label = pyglet.text.Label(
                '', font_name='Arial', font_size=8, x=10, y=self.window.height - 10,
                anchor_x='left', anchor_y='top', color=(255, 255, 255, 255))
        pyglet.clock.schedule_interval_soft(self.world.process_queue,
                                            1.0 / G.MAX_FPS)
        pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 10.0, self.player)
        return True