Esempio n. 1
0
def main(args):
    try:
        options = parseargs(args)
    except ValueError:
        print "Command not understood %s" % (" ".join(args))
        sys.exit(2)

    config = SafeConfigParser()
    try:
        config.readfp(open('gameroom.cfg', 'rU'))
    except IOError:
        print "Could not open 'gameroom.cfg' this file must be readable and contain the configuration for connecting to the gameroom."
        sys.exit(1)

    aeilog = logging.getLogger("gameroom.aei")
    if config.has_section("Logging"):
        logdir = config.get("Logging", "directory")
        if not os.path.exists(logdir):
            print "Log directory '%s' not found, attempting to create it." % (logdir)
            os.makedirs(logdir)
        logfilename = "%s-%s.log" % (time.strftime("%Y%m%d-%H%M"),
                    str(os.getpid()),
                    )
        logfilename = os.path.join(logdir, logfilename)
        if config.has_option("Logging", "level"):
            loglevel = str_loglevel(config.get("Logging", "level"))
        else:
            loglevel = logging.WARN

        logging.basicConfig(level = loglevel,
                filename = logfilename,
                datefmt="%Y-%m-%d %H:%M:%S",
                format="%(asctime)s %(levelname)s:%(name)s:%(message)s",
                )

        if (config.has_option("Logging", "console")
            and config.getboolean("Logging", "console")):
            global console
            console = logging.StreamHandler()
            if config.has_option("Logging", "console_level"):
                conlevel = str_loglevel(config.get("Logging", "console_level"))
            else:
                conlevel = logging.INFO
            console.setLevel(conlevel)
            logging.getLogger('').addHandler(console)

        if config.has_option("Logging", "net_level"):
            netlevel = str_loglevel(config.get("Logging", "net_level"))
            netlog.setLevel(netlevel)

        if config.has_option("Logging", "engine_level"):
            enginelevel = str_loglevel(config.get("Logging", "engine_level"))
            enginelog.setLevel(enginelevel)

        if config.has_option("Logging", "aei_level"):
            aeilog.setLevel(str_loglevel(config.get("Logging", "aei_level")))

        positionlog.setLevel(logging.ERROR)
        if (config.has_option("Logging", "log_position")
            and config.getboolean("Logging", "log_position")):
            positionlog.setLevel(logging.INFO)


    run_dir = config.get("global", "run_dir")
    if not os.path.exists(run_dir):
        log.warn("Run file directory '%s' not found, attempting to create it." % (run_dir))
        os.makedirs(run_dir)
    bot_count = how_many_bots(run_dir)
    if bot_count >= config.getint("global", "max_bots"):
        log.info("Max number of bot limit %d reached, need to wait until some bots finish."
            % (config.getint("global", "max_bots")))
        return

    bot_section = config.get("global", "default_engine")
    com_method = config.get(bot_section, "communication_method").lower()
    enginecmd = config.get(bot_section, "cmdline")

    games_num = config.getint(bot_section, "games_num")
    games_played = 0

    while games_num == 0 or games_played < games_num:
        unknowns_caught = 0
        gameid_or_opponent = options['against']
    #while True:
        try:
            if com_method == "2008cc":
                engine_ctl = EngineController(SocketEngine(enginecmd, legacy_mode=True))
            elif com_method == "socket":
                engine_ctl = EngineController(SocketEngine(enginecmd, log=aeilog))
            elif com_method == "stdio":
                engine_ctl = EngineController(StdioEngine(enginecmd, log=aeilog))
            else:
                raise ValueError("Unrecognized communication method, %s" % (com_method))
        except OSError, exc:
            log.error("Could not start the engine; exception thrown: %s", exc)
            sys.exit(1)

        for option in config.options(bot_section):
            if option.startswith("bot_"):
                value = config.get(bot_section, option)
                engine_ctl.setoption(option[4:], value)
                log.info("Setting bot option %s = %s", option[4:], value)
        engine_ctl.isready()

        bot_username = config.get(bot_section, "username")
        bot_password = config.get(bot_section, "password")
        bot_greeting = config.get(bot_section, "greeting")

        gameroom = GameRoom(config.get("global", "gameroom_url"))
        gameroom.login(bot_username, bot_password)
        side = options['side']
        table = None
        if gameid_or_opponent == "":
            log.info("Starting a new game")
            if side == "":
                side = 'b'
            tc = config.get(bot_section, "timecontrol")
            rated = config.getboolean(bot_section, "rated")
            log.info("Will play on side %s, using timecontrol %s" % (side, tc))
            table = gameroom.newgame(side, tc, rated)
        else:
            # look through my games for correct opponent and side
            games = gameroom.mygames()
            for game in games:
                if (gameid_or_opponent == game['player'].lower()
                        or gameid_or_opponent == game['gid']):
                    if (side == "" or side == game['side']
                        and not already_playing(run_dir, game['gid'], game['side'])):
                        table = Table(gameroom, game)
                        log.info("Found in progress game")
                        break
            if table == None:
                games = gameroom.opengames()
                for game in games:
                    if (gameid_or_opponent == game['player'].lower()
                            or gameid_or_opponent == game['gid']):
                        if (side == "" or side == game['side']
                            and not already_playing(run_dir, game['gid'], game['side'])):
                            table = Table(gameroom, game)
                            log.info("Found game to join")
                            break
            if table == None:
                log.error("Could not find game against %s with side '%s'", gameid_or_opponent, side)
                break
        # Set the game to play in to current game id in case of a restart
        gameid_or_opponent = table.gid

        if options['against'] != "":
            joinmsg = "Joined game gid=%s side=%s; against %s" % (table.gid, table.side, options['against'])
        else:
            joinmsg = "Created game gid=%s side=%s; waiting for opponent" % (table.gid, table.side)
        log.info(joinmsg)
        if console is None:
            print joinmsg

        if config.has_option(bot_section, "ponder"):
            table.ponder = config.getboolean(bot_section, "ponder")
            if table.ponder:
                log.info("Set pondering on.")
            else:
                log.info("Set pondering off.")
        else:
            table.ponder = False
        if config.has_option("global", "min_move_time"):
            table.min_move_time = config.getint("global", "min_move_time")
            log.info("Set minimum move time to %d seconds.", table.min_move_time)
        else:
            table.min_move_time = 5
        if config.has_option("global", "min_time_left"):
            table.min_timeleft = config.getint("global", "min_time_left")
            log.info("Setting emergency stop time to %d seconds" % table.min_timeleft)
        else:
            table.min_timeleft = 5

        try:
            try:
                log.info("Joining game on %s side", table.side)
                table.reserveseat()
                table.sitdown()
                table.updatestate()
                try:
                    touch_run_file(run_dir, "%s%s.bot" % (table.gid, table.side))
                    time.sleep(1) # Give the server a small break.
                    log.info("Starting play")
                    table.playgame(engine_ctl, bot_greeting, options['onemove'])
                finally:
                    log.info("Leaving game")
                    remove_run_files(run_dir, "%s%s.bot" % (table.gid, table.side))
                    table.leave()
                #break
                games_played += 1
                continue  #Tomas changed from break
            finally:
                try:
                    engine_ctl.quit()
                except (socket.error, IOError):
                    pass
                for i in range(30):
                    if engine_ctl.engine.proc.poll() is not None:
                        break
                    time.sleep(1)
                else:
                    log.warn("Engine did not exit in 30 seconds, terminating process")
                    try:
                        if sys.platform == 'win32':
                            import ctypes
                            handle = int(engine_ctl.engine.proc._handle)
                            ctypes.windll.kernel32.TerminateProcess(handle, 0)
                        else:
                            os.kill(engine_ctl.engine.proc.pid, signal.SIGTERM)
                    except os.error:
                        # don't worry about errors when trying to kill the engine
                        pass
                engine_ctl.cleanup()
                time.sleep(1)
        except (KeyboardInterrupt, SystemExit):
            raise
        except EngineCrashException, exc:
            log.error("Bot engine crashed (%s), restarting.", exc.args[0])
            time.sleep(1)
Esempio n. 2
0
            print "No move received from %s" % (eng.ident["name"])
            break
        ply += 1

    if resp and hasattr(resp, "move"):
        print resp.move
    print position.to_long_str()

    return (position.is_end_state(), position)

engines = []

permove = 2
max_reserve = 30

eng = EngineController(StdioEngine("akimot/akimot", bot_id="1", log = logging))
print "Bot 1: %s Author: %s" % (eng.ident['name'], eng.ident['author'])
if max_reserve:
    eng.setoption("tcmove", permove)
    eng.setoption("tcmax", max_reserve)
else:
    eng.setoption("depth", 8)
eng.setoption("hash", 100)
eng.setoption("opening_book", 1)
eng.ident['name'] += " cur"
engines.append(eng)

eng = EngineController(StdioEngine("akimot/akimot", bot_id="2", log = logging))
print "Bot 2: %s Author: %s" % (eng.ident['name'], eng.ident['author'])
if max_reserve:
    eng.setoption("tcmove", permove)
Esempio n. 3
0
            break
        except socket.error, exc:
            if (hasattr(exc, 'args')
                    and (exc.args[0] == 10048
                        or exc.args[0] == 98)):
                address = (address[0], address[1]+1)
            else:
                raise

    botargs = [botcmd]
    botargs += [str(x) for x in address]
    log.info("Starting engine with command '%s'", " ".join(botargs))
    bot_proc = Popen(botargs, cwd=working_dir)
    con = listensock.accept()
    log.debug("Engine connected.")
    engine = EngineController(SocketEngine(con))
    listensock.close()
    del listensock
    log.info("Engine initialized")
    engine.process = bot_proc

    return (engine, bot_proc)

def touch_run_file(run_dir, rfile):
    filename = os.path.join(run_dir, rfile)
    rf = open(filename, 'w')
    rf.write("%d\n" % os.getpid())
    rf.close()
    log.info("Created run file at %s" % filename)

def remove_run_files(run_dir, rfile):
Esempio n. 4
0
def main(args):
    try:
        options = parseargs(args)
    except ValueError:
        print "Command not understood %s" % (" ".join(args))
        sys.exit(2)

    config = SafeConfigParser()
    try:
        config.readfp(open('gameroom.cfg', 'rU'))
    except IOError:
        print "Could not open 'gameroom.cfg' this file must be readable and contain the configuration for connecting to the gameroom."
        sys.exit(1)

    aeilog = logging.getLogger("gameroom.aei")
    if config.has_section("Logging"):
        logdir = config.get("Logging", "directory")
        if not os.path.exists(logdir):
            print "Log directory '%s' not found, attempting to create it." % (
                logdir)
            os.makedirs(logdir)
        logfilename = "%s-%s.log" % (
            time.strftime("%Y%m%d-%H%M"),
            str(os.getpid()),
        )
        logfilename = os.path.join(logdir, logfilename)
        if config.has_option("Logging", "level"):
            loglevel = str_loglevel(config.get("Logging", "level"))
        else:
            loglevel = logging.WARN

        logging.basicConfig(
            level=loglevel,
            filename=logfilename,
            datefmt="%Y-%m-%d %H:%M:%S",
            format="%(asctime)s %(levelname)s:%(name)s:%(message)s",
        )

        if (config.has_option("Logging", "console")
                and config.getboolean("Logging", "console")):
            global console
            console = logging.StreamHandler()
            if config.has_option("Logging", "console_level"):
                conlevel = str_loglevel(config.get("Logging", "console_level"))
            else:
                conlevel = logging.INFO
            console.setLevel(conlevel)
            logging.getLogger('').addHandler(console)

        if config.has_option("Logging", "net_level"):
            netlevel = str_loglevel(config.get("Logging", "net_level"))
            netlog.setLevel(netlevel)

        if config.has_option("Logging", "engine_level"):
            enginelevel = str_loglevel(config.get("Logging", "engine_level"))
            enginelog.setLevel(enginelevel)

        if config.has_option("Logging", "aei_level"):
            aeilog.setLevel(str_loglevel(config.get("Logging", "aei_level")))

        positionlog.setLevel(logging.ERROR)
        if (config.has_option("Logging", "log_position")
                and config.getboolean("Logging", "log_position")):
            positionlog.setLevel(logging.INFO)

    run_dir = config.get("global", "run_dir")
    if not os.path.exists(run_dir):
        log.warn(
            "Run file directory '%s' not found, attempting to create it." %
            (run_dir))
        os.makedirs(run_dir)
    bot_count = how_many_bots(run_dir)
    if bot_count >= config.getint("global", "max_bots"):
        log.info(
            "Max number of bot limit %d reached, need to wait until some bots finish."
            % (config.getint("global", "max_bots")))
        return

    bot_section = config.get("global", "default_engine")
    com_method = config.get(bot_section, "communication_method").lower()
    enginecmd = config.get(bot_section, "cmdline")

    games_num = config.getint(bot_section, "games_num")
    games_played = 0

    while games_num == 0 or games_played < games_num:
        unknowns_caught = 0
        gameid_or_opponent = options['against']
        #while True:
        try:
            if com_method == "2008cc":
                engine_ctl = EngineController(
                    SocketEngine(enginecmd, legacy_mode=True))
            elif com_method == "socket":
                engine_ctl = EngineController(
                    SocketEngine(enginecmd, log=aeilog))
            elif com_method == "stdio":
                engine_ctl = EngineController(
                    StdioEngine(enginecmd, log=aeilog))
            else:
                raise ValueError("Unrecognized communication method, %s" %
                                 (com_method))
        except OSError, exc:
            log.error("Could not start the engine; exception thrown: %s", exc)
            sys.exit(1)

        for option in config.options(bot_section):
            if option.startswith("bot_"):
                value = config.get(bot_section, option)
                engine_ctl.setoption(option[4:], value)
                log.info("Setting bot option %s = %s", option[4:], value)
        engine_ctl.isready()

        bot_username = config.get(bot_section, "username")
        bot_password = config.get(bot_section, "password")
        bot_greeting = config.get(bot_section, "greeting")

        gameroom = GameRoom(config.get("global", "gameroom_url"))
        gameroom.login(bot_username, bot_password)
        side = options['side']
        table = None
        if gameid_or_opponent == "":
            log.info("Starting a new game")
            if side == "":
                side = 'b'
            tc = config.get(bot_section, "timecontrol")
            rated = config.getboolean(bot_section, "rated")
            log.info("Will play on side %s, using timecontrol %s" % (side, tc))
            table = gameroom.newgame(side, tc, rated)
        else:
            # look through my games for correct opponent and side
            games = gameroom.mygames()
            for game in games:
                if (gameid_or_opponent == game['player'].lower()
                        or gameid_or_opponent == game['gid']):
                    if (side == ""
                            or side == game['side'] and not already_playing(
                                run_dir, game['gid'], game['side'])):
                        table = Table(gameroom, game)
                        log.info("Found in progress game")
                        break
            if table == None:
                games = gameroom.opengames()
                for game in games:
                    if (gameid_or_opponent == game['player'].lower()
                            or gameid_or_opponent == game['gid']):
                        if (side == "" or side == game['side']
                                and not already_playing(
                                    run_dir, game['gid'], game['side'])):
                            table = Table(gameroom, game)
                            log.info("Found game to join")
                            break
            if table == None:
                log.error("Could not find game against %s with side '%s'",
                          gameid_or_opponent, side)
                break
        # Set the game to play in to current game id in case of a restart
        gameid_or_opponent = table.gid

        if options['against'] != "":
            joinmsg = "Joined game gid=%s side=%s; against %s" % (
                table.gid, table.side, options['against'])
        else:
            joinmsg = "Created game gid=%s side=%s; waiting for opponent" % (
                table.gid, table.side)
        log.info(joinmsg)
        if console is None:
            print joinmsg

        if config.has_option(bot_section, "ponder"):
            table.ponder = config.getboolean(bot_section, "ponder")
            if table.ponder:
                log.info("Set pondering on.")
            else:
                log.info("Set pondering off.")
        else:
            table.ponder = False
        if config.has_option("global", "min_move_time"):
            table.min_move_time = config.getint("global", "min_move_time")
            log.info("Set minimum move time to %d seconds.",
                     table.min_move_time)
        else:
            table.min_move_time = 5
        if config.has_option("global", "min_time_left"):
            table.min_timeleft = config.getint("global", "min_time_left")
            log.info("Setting emergency stop time to %d seconds" %
                     table.min_timeleft)
        else:
            table.min_timeleft = 5

        try:
            try:
                log.info("Joining game on %s side", table.side)
                table.reserveseat()
                table.sitdown()
                table.updatestate()
                try:
                    touch_run_file(run_dir,
                                   "%s%s.bot" % (table.gid, table.side))
                    time.sleep(1)  # Give the server a small break.
                    log.info("Starting play")
                    table.playgame(engine_ctl, bot_greeting,
                                   options['onemove'])
                finally:
                    log.info("Leaving game")
                    remove_run_files(run_dir,
                                     "%s%s.bot" % (table.gid, table.side))
                    table.leave()
                #break
                games_played += 1
                continue  #Tomas changed from break
            finally:
                try:
                    engine_ctl.quit()
                except (socket.error, IOError):
                    pass
                for i in range(30):
                    if engine_ctl.engine.proc.poll() is not None:
                        break
                    time.sleep(1)
                else:
                    log.warn(
                        "Engine did not exit in 30 seconds, terminating process"
                    )
                    try:
                        if sys.platform == 'win32':
                            import ctypes
                            handle = int(engine_ctl.engine.proc._handle)
                            ctypes.windll.kernel32.TerminateProcess(handle, 0)
                        else:
                            os.kill(engine_ctl.engine.proc.pid, signal.SIGTERM)
                    except os.error:
                        # don't worry about errors when trying to kill the engine
                        pass
                engine_ctl.cleanup()
                time.sleep(1)
        except (KeyboardInterrupt, SystemExit):
            raise
        except EngineCrashException, exc:
            log.error("Bot engine crashed (%s), restarting.", exc.args[0])
            time.sleep(1)
Esempio n. 5
0
            log.debug("Listening for engine on %s:%d" % address)
            break
        except socket.error, exc:
            if (hasattr(exc, 'args')
                    and (exc.args[0] == 10048 or exc.args[0] == 98)):
                address = (address[0], address[1] + 1)
            else:
                raise

    botargs = [botcmd]
    botargs += [str(x) for x in address]
    log.info("Starting engine with command '%s'", " ".join(botargs))
    bot_proc = Popen(botargs, cwd=working_dir)
    con = listensock.accept()
    log.debug("Engine connected.")
    engine = EngineController(SocketEngine(con))
    listensock.close()
    del listensock
    log.info("Engine initialized")
    engine.process = bot_proc

    return (engine, bot_proc)


def touch_run_file(run_dir, rfile):
    filename = os.path.join(run_dir, rfile)
    rf = open(filename, 'w')
    rf.write("%d\n" % os.getpid())
    rf.close()
    log.info("Created run file at %s" % filename)
Esempio n. 6
0
from subprocess import Popen

import board

from aei import SocketEngine, StdioEngine, EngineController, EngineException

if len(sys.argv) < 2:
    print "usage: analyse boardfile"
    sys.exit()

pfile = open(sys.argv[1], 'r')
plines = pfile.readlines()
movenum, pos = board.parse_long_pos(plines)
pfile.close()

eng = EngineController(StdioEngine("akimot/akimot", logging))

#eng.setoption("tcmove", 120)
#eng.setoption("tcmax", 600)
#eng.setoption("tcmoveused", 0)
#eng.setoption("wreserve", 300)
#eng.setoption("breserve", 300)
#eng.setoption("root_lmr", 0)
#eng.setoption("use_lmr", 0)

#eng.setoption("log_console", 1)
#eng.setoption("depth", "12")
#eng.setoption("hash", 500)
print pos.to_long_str()
eng.setposition(pos)
eng.go()
Esempio n. 7
0
from subprocess import Popen

import board

from aei import SocketEngine, StdioEngine, EngineController, EngineException

if len(sys.argv) < 2:
    print "usage: analyse boardfile"
    sys.exit()

pfile = open(sys.argv[1], 'r')
plines = pfile.readlines()
movenum, pos = board.parse_long_pos(plines)
pfile.close()

eng = EngineController(StdioEngine("akimot/akimot", logging))

#eng.setoption("tcmove", 120)
#eng.setoption("tcmax", 600)
#eng.setoption("tcmoveused", 0)
#eng.setoption("wreserve", 300)
#eng.setoption("breserve", 300)
#eng.setoption("root_lmr", 0)
#eng.setoption("use_lmr", 0)

#eng.setoption("log_console", 1)
#eng.setoption("depth", "12")
#eng.setoption("hash", 500)
print pos.to_long_str()
eng.setposition(pos)
eng.go()
Esempio n. 8
0
            break
        ply += 1

    if resp and hasattr(resp, "move"):
        print resp.move
    print position.to_long_str()

    return (position.is_end_state(), position)


engines = []

permove = 2
max_reserve = 30

eng = EngineController(StdioEngine("akimot/akimot", bot_id="1", log=logging))
print "Bot 1: %s Author: %s" % (eng.ident['name'], eng.ident['author'])
if max_reserve:
    eng.setoption("tcmove", permove)
    eng.setoption("tcmax", max_reserve)
else:
    eng.setoption("depth", 8)
eng.setoption("hash", 100)
eng.setoption("opening_book", 1)
eng.ident['name'] += " cur"
engines.append(eng)

eng = EngineController(StdioEngine("akimot/akimot", bot_id="2", log=logging))
print "Bot 2: %s Author: %s" % (eng.ident['name'], eng.ident['author'])
if max_reserve:
    eng.setoption("tcmove", permove)