rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
raise CmpetitionError(
raise CompetitionError(
def scale_parameters(self, optimiser_parameters): l = [] for pspec, v in zip(self.parameter_specs, optimiser_parameters): try: l.append(pspec.scale_fn(v)) except Exception: raise CmpetitionError( "error from scale_fn for %s\n%s" % (pspec.code, compact_tracebacks.format_traceback(skip=1))) return tuple(l)
desribes what 0 values mean). time_settings None means the information isn't available.
describes what 0 values mean). time_settings None means the information isn't available.
def is_pass(self): return (self.coords is None)
fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job()
job = fx.get_job()
def test_get_job(tc): vals = { 'cmdline1' : "", 'cmdline2' : "sing song", } fx = Ringmaster_fixture(tc, simple_ctl.substitute(vals)) fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job() tc.assertEqual(job.game_id, "0_000") tc.assertEqual(job.game_data, ("0", 0)) tc.assertEqual(job.board_size, 9) tc.assertEqual(job.komi, 7.5) tc.assertEqual(job.move_limit, 400) tc.assertEqual(job.handicap, None) tc.assertIs(job.handicap_is_free, False) tc.assertIs(job.use_internal_scorer, True) tc.assertEqual(job.sgf_event, 'test') tc.assertIsNone(job.gtp_log_pathname) tc.assertIsNone(job.sgf_filename) tc.assertIsNone(job.sgf_dirname) tc.assertIsNone(job.void_sgf_dirname) tc.assertEqual(job.player_b.code, 'p1') tc.assertEqual(job.player_w.code, 'p2') tc.assertEqual(job.player_b.cmd_args, ['test']) tc.assertEqual(job.player_w.cmd_args, ['test', 'sing', 'song']) tc.assertDictEqual(job.player_b.gtp_translations, {}) tc.assertListEqual(job.player_b.startup_gtp_commands, []) tc.assertEqual(job.player_b.stderr_pathname, os.devnull) tc.assertIsNone(job.player_b.cwd) tc.assertIsNone(job.player_b.environ)
fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job()
job = fx.get_job()
def test_settings(tc): vals = { 'cmdline1' : "", 'cmdline2' : "", } extra = "\n".join([ "handicap = 9", "handicap_style = 'free'", "record_games = True", "scorer = 'players'" ]) fx = Ringmaster_fixture(tc, simple_ctl.substitute(vals) + extra) fx.ringmaster.enable_gtp_logging() fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job() tc.assertEqual(job.game_id, "0_000") tc.assertEqual(job.handicap, 9) tc.assertIs(job.handicap_is_free, True) tc.assertIs(job.use_internal_scorer, False) tc.assertEqual(job.player_b.stderr_pathname, os.devnull) tc.assertEqual(job.gtp_log_pathname, '/nonexistent/ctl/test.gtplogs/0_000.log') tc.assertEqual(job.sgf_filename, '0_000.sgf') tc.assertEqual(job.sgf_dirname, '/nonexistent/ctl/test.games') tc.assertEqual(job.void_sgf_dirname, '/nonexistent/ctl/test.void') tc.assertEqual(fx.ringmaster.get_sgf_filename("0_000"), "0_000.sgf") tc.assertEqual(fx.ringmaster.get_sgf_pathname("0_000"), "/nonexistent/ctl/test.games/0_000.sgf")
fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job()
job = fx.get_job()
def test_stderr_settings(tc): vals = { 'cmdline1' : "", 'cmdline2' : "", } extra = "\n".join([ "players['p1'] = Player('test')\n" ]) fx = Ringmaster_fixture(tc, simple_ctl.substitute(vals) + extra) fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job() tc.assertEqual(job.player_b.stderr_pathname, "/nonexistent/ctl/test.log") tc.assertEqual(job.player_w.stderr_pathname, os.devnull)
fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job()
job = fx.get_job()
def test_stderr_settings_nolog(tc): vals = { 'cmdline1' : "", 'cmdline2' : "", } extra = "\n".join([ "players['p1'] = Player('test')\n" "stderr_to_log = False\n" ]) fx = Ringmaster_fixture(tc, simple_ctl.substitute(vals) + extra) fx.ringmaster.set_clean_status() fx.ringmaster._open_files() fx.ringmaster._initialise_presenter() fx.ringmaster._initialise_terminal_reader() job = fx.ringmaster.get_job() tc.assertIsNone(job.player_b.stderr_pathname, None) tc.assertEqual(job.player_w.stderr_pathname, os.devnull)
engine_names -- map colour -> string engine_descriptions -- map colour -> string
engine_names -- map player code -> string engine_descriptions -- map player code -> string
def __init__(self): self.gtp_translations = {}
self.write_status()
def process_response(self, response): """Job response function for the job manager.""" self.log("response from game %s" % response.game_id) self.competition.process_game_result(response) del self.games_in_progress[response.game_id] if not self.stopping_quietly: self.write_status() self.update_display() if self.chatty: print print "game %s completed: %s" % ( response.game_id, response.game_result.describe())
stderr_b = open(self.player_b.stderr_pathname, "wa")
stderr_b = open(self.player_b.stderr_pathname, "a")
def run(self): game = gtp_games.Game( {'b' : self.player_b.code, 'w' : self.player_w.code}, {'b' : self.player_b.cmd_args, 'w' : self.player_w.cmd_args}, self.board_size, self.komi, self.move_limit) if self.use_internal_scorer: game.use_internal_scorer() else: if self.player_b.is_reliable_scorer: game.allow_scorer('b') if self.player_w.is_reliable_scorer: game.allow_scorer('w') game.set_gtp_translations({'b' : self.player_b.gtp_translations, 'w' : self.player_w.gtp_translations}) if self.gtp_log_pathname is not None: # the controller will flush() this after each write, so I think we # can get away without closing it. game.set_gtp_log(open(self.gtp_log_pathname, "w")) # we never write to these files in this process, so I think we can get # away without closing them. if self.player_b.stderr_pathname is not None: stderr_b = open(self.player_b.stderr_pathname, "wa") game.set_stderr('b', stderr_b) if self.player_w.stderr_pathname is not None: stderr_w = open(self.player_w.stderr_pathname, "wa") game.set_stderr('w', stderr_w) try: game.start_players() for command, arguments in self.player_b.startup_gtp_commands: game.send_command('b', command, *arguments) for command, arguments in self.player_w.startup_gtp_commands: game.send_command('w', command, *arguments) game.request_engine_descriptions() if self.handicap: try: game.set_handicap(self.handicap, self.handicap_is_free) except ValueError: raise job_manager.JobFailed( "aborting game: invalid handicap") game.run() except (GtpProtocolError, GtpTransportError, GtpEngineError), e: raise job_manager.JobFailed("aborting game due to error:\n%s\n" % e) try: game.close_players() except StandardError, e: raise job_manager.JobFailed( "error shutting down players:\n%s\n" % e) if self.sgf_pathname is not None: self.record_game(game) response = Game_job_result() response.game_id = self.game_id response.game_result = game.result response.engine_names = game.engine_names response.engine_descriptions = game.engine_descriptions response.game_data = self.game_data return response
stderr_w = open(self.player_w.stderr_pathname, "wa")
stderr_w = open(self.player_w.stderr_pathname, "a")
def run(self): game = gtp_games.Game( {'b' : self.player_b.code, 'w' : self.player_w.code}, {'b' : self.player_b.cmd_args, 'w' : self.player_w.cmd_args}, self.board_size, self.komi, self.move_limit) if self.use_internal_scorer: game.use_internal_scorer() else: if self.player_b.is_reliable_scorer: game.allow_scorer('b') if self.player_w.is_reliable_scorer: game.allow_scorer('w') game.set_gtp_translations({'b' : self.player_b.gtp_translations, 'w' : self.player_w.gtp_translations}) if self.gtp_log_pathname is not None: # the controller will flush() this after each write, so I think we # can get away without closing it. game.set_gtp_log(open(self.gtp_log_pathname, "w")) # we never write to these files in this process, so I think we can get # away without closing them. if self.player_b.stderr_pathname is not None: stderr_b = open(self.player_b.stderr_pathname, "wa") game.set_stderr('b', stderr_b) if self.player_w.stderr_pathname is not None: stderr_w = open(self.player_w.stderr_pathname, "wa") game.set_stderr('w', stderr_w) try: game.start_players() for command, arguments in self.player_b.startup_gtp_commands: game.send_command('b', command, *arguments) for command, arguments in self.player_w.startup_gtp_commands: game.send_command('w', command, *arguments) game.request_engine_descriptions() if self.handicap: try: game.set_handicap(self.handicap, self.handicap_is_free) except ValueError: raise job_manager.JobFailed( "aborting game: invalid handicap") game.run() except (GtpProtocolError, GtpTransportError, GtpEngineError), e: raise job_manager.JobFailed("aborting game due to error:\n%s\n" % e) try: game.close_players() except StandardError, e: raise job_manager.JobFailed( "error shutting down players:\n%s\n" % e) if self.sgf_pathname is not None: self.record_game(game) response = Game_job_result() response.game_id = self.game_id response.game_result = game.result response.engine_names = game.engine_names response.engine_descriptions = game.engine_descriptions response.game_data = self.game_data return response
"""Interpret Python code from a string. source -- string
"""Interpret Python code from a unicode string. source -- unicode object
def interpret_python(source, provided_globals): """Interpret Python code from a string. source -- string provided_globals -- dict The string is executed with a copy of provided_globals as the global and local namespace. Returns that namespace. """ result = provided_globals.copy() exec source in result return result
exec source in result
code = compile(source, "<control file>", 'exec', division.compiler_flag, True) exec code in result
def interpret_python(source, provided_globals): """Interpret Python code from a string. source -- string provided_globals -- dict The string is executed with a copy of provided_globals as the global and local namespace. Returns that namespace. """ result = provided_globals.copy() exec source in result return result
control_s, self.competition.control_file_globals())
control_u, self.competition.control_file_globals())
def _load_control_file(self): """Main implementation for __init__."""
return ValueError
raise ValueError
def opponent_of(colour): """Return the opponent colour. colour -- 'b' or 'w' Returns 'b' or 'w'. """ try: return _opponents[colour] except KeyError: return ValueError
commands -- map colour -> command used to launch the program
def __repr__(self): return "<Game_result: %s>" % self.describe()
expanded node in this tree has dimension*branching_factor children.
expanded node in this tree has branching_factor**dimension children.
def __repr__(self): return "<Node:%.2f{%s}>" % (self.value, repr(self.children))
In particular, this rejects unicode objects and strings contaning spaces.
In particular, this rejects unicode objects and strings containing spaces.
def is_well_formed_gtp_word(s): """Check whether 's' is well-formed as a single GTP word. In particular, this rejects unicode objects and strings contaning spaces. """ if not isinstance(s, str): return False if not _gtp_word_characters_re.search(s): return False return True
player = game_jobs.Player() player.code = 'test' player.cmd_args = ['test'] check = game_jobs.Player_check() check.player = player check.board_size = 9 check.komi = 7.0 game_jobs.check_player(check)
ck = Player_check_fixture(tc) game_jobs.check_player(ck.check)
def test_check_player(tc): fx = gtp_engine_fixtures.Mock_subprocess_fixture(tc) player = game_jobs.Player() player.code = 'test' player.cmd_args = ['test'] check = game_jobs.Player_check() check.player = player check.board_size = 9 check.komi = 7.0 game_jobs.check_player(check)
player = game_jobs.Player() player.code = 'test' player.cmd_args = ['no_boardsize'] check = game_jobs.Player_check() check.player = player check.board_size = 9 check.komi = 7.0
ck = Player_check_fixture(tc) ck.player.cmd_args = ['no_boardsize']
def test_check_player_boardsize_fails(tc): fx = gtp_engine_fixtures.Mock_subprocess_fixture(tc) engine = gtp_engine_fixtures.get_test_engine() fx.register_engine('no_boardsize', engine) player = game_jobs.Player() player.code = 'test' player.cmd_args = ['no_boardsize'] check = game_jobs.Player_check() check.player = player check.board_size = 9 check.komi = 7.0 with tc.assertRaises(game_jobs.CheckFailed) as ar: game_jobs.check_player(check) tc.assertEqual(str(ar.exception), "failure response from 'boardsize 9' to test:\n" "unknown command")
game_jobs.check_player(check)
game_jobs.check_player(ck.check)
def test_check_player_boardsize_fails(tc): fx = gtp_engine_fixtures.Mock_subprocess_fixture(tc) engine = gtp_engine_fixtures.get_test_engine() fx.register_engine('no_boardsize', engine) player = game_jobs.Player() player.code = 'test' player.cmd_args = ['no_boardsize'] check = game_jobs.Player_check() check.player = player check.board_size = 9 check.komi = 7.0 with tc.assertRaises(game_jobs.CheckFailed) as ar: game_jobs.check_player(check) tc.assertEqual(str(ar.exception), "failure response from 'boardsize 9' to test:\n" "unknown command")
def do_run(ringmaster, worker_count=None, max_games=None):
def do_run(ringmaster, options): if options.log_gtp: ringmaster.enable_gtp_logging() if options.quiet: ringmaster.set_quiet_mode()
def do_run(ringmaster, worker_count=None, max_games=None): if ringmaster.status_file_exists(): ringmaster.load_status() else: ringmaster.set_clean_status() if worker_count is not None: ringmaster.set_parallel_worker_count(worker_count) ringmaster.run(max_games) ringmaster.report()
if worker_count is not None: ringmaster.set_parallel_worker_count(worker_count) ringmaster.run(max_games)
if options.parallel is not None: ringmaster.set_parallel_worker_count(options.parallel) ringmaster.run(options.max_games)
def do_run(ringmaster, worker_count=None, max_games=None): if ringmaster.status_file_exists(): ringmaster.load_status() else: ringmaster.set_clean_status() if worker_count is not None: ringmaster.set_parallel_worker_count(worker_count) ringmaster.run(max_games) ringmaster.report()
def do_show(ringmaster): if not ringmaster.status_file_exists(): raise RingmasterError("no status file") ringmaster.load_status() ringmaster.print_status_report() def do_report(ringmaster): if not ringmaster.status_file_exists(): raise RingmasterError("no status file") ringmaster.load_status() ringmaster.report() def do_stop(ringmaster):
def do_stop(ringmaster, options):
def do_show(ringmaster): if not ringmaster.status_file_exists(): raise RingmasterError("no status file") ringmaster.load_status() ringmaster.print_status_report()
def do_reset(ringmaster):
def do_show(ringmaster, options): if not ringmaster.status_file_exists(): raise RingmasterError("no status file") ringmaster.load_status() ringmaster.print_status_report() def do_report(ringmaster, options): if not ringmaster.status_file_exists(): raise RingmasterError("no status file") ringmaster.load_status() ringmaster.report() def do_reset(ringmaster, options):
def do_reset(ringmaster): ringmaster.delete_state_and_output()
if command not in ("run", "stop", "show", "report", "reset", "check", "debugstatus"): parser.error("no such command: %s" % command)
try: action = _actions[command] except KeyError: parser.error("no such command: %s" % command)
def run(argv, ringmaster_class): usage = ("%prog [options] <control file> [command]\n\n" "commands: run (default), stop, show, report, reset, check") parser = OptionParser(usage=usage, prog="ringmaster") parser.add_option("--max-games", "-g", type="int", help="maximum number of games to play in this run") parser.add_option("--parallel", "-j", type="int", help="number of worker processes") parser.add_option("--quiet", "-q", action="store_true", help="silent except for warnings and errors") parser.add_option("--log-gtp", action="store_true", help="write GTP logs") (options, args) = parser.parse_args() if len(args) == 0: parser.error("no control file specified") if len(args) > 2: parser.error("too many arguments") if len(args) == 1: command = "run" else: command = args[1] if command not in ("run", "stop", "show", "report", "reset", "check", "debugstatus"): parser.error("no such command: %s" % command) tourn_pathname = args[0] if not tourn_pathname.endswith(".tourn"): parser.error("not a .tourn file") exit_status = 0 try: if not os.path.exists(tourn_pathname): raise RingmasterError("control file %s not found" % tourn_pathname) ringmaster = ringmaster_class(tourn_pathname) if command == "run": if options.log_gtp: ringmaster.enable_gtp_logging() if options.quiet: ringmaster.set_quiet_mode() do_run(ringmaster, options.parallel, options.max_games) elif command == "show": do_show(ringmaster) elif command == "stop": do_stop(ringmaster) elif command == "report": do_report(ringmaster) elif command == "reset": do_reset(ringmaster) elif command == "check": if not ringmaster.check_players(): exit_status = 1 elif command == "debugstatus": ringmaster.print_status() else: raise AssertionError except RingmasterError, e: print >>sys.stderr, "ringmaster:", e exit_status = 1 except KeyboardInterrupt: exit_status = 3 except job_manager.JobSourceError, e: print >>sys.stderr, "ringmaster: internal error" print >>sys.stderr, e exit_status = 4 except: print >>sys.stderr, "ringmaster: internal error" compact_tracebacks.log_traceback() exit_status = 4 sys.exit(exit_status)
exit_status = 0
def run(argv, ringmaster_class): usage = ("%prog [options] <control file> [command]\n\n" "commands: run (default), stop, show, report, reset, check") parser = OptionParser(usage=usage, prog="ringmaster") parser.add_option("--max-games", "-g", type="int", help="maximum number of games to play in this run") parser.add_option("--parallel", "-j", type="int", help="number of worker processes") parser.add_option("--quiet", "-q", action="store_true", help="silent except for warnings and errors") parser.add_option("--log-gtp", action="store_true", help="write GTP logs") (options, args) = parser.parse_args() if len(args) == 0: parser.error("no control file specified") if len(args) > 2: parser.error("too many arguments") if len(args) == 1: command = "run" else: command = args[1] if command not in ("run", "stop", "show", "report", "reset", "check", "debugstatus"): parser.error("no such command: %s" % command) tourn_pathname = args[0] if not tourn_pathname.endswith(".tourn"): parser.error("not a .tourn file") exit_status = 0 try: if not os.path.exists(tourn_pathname): raise RingmasterError("control file %s not found" % tourn_pathname) ringmaster = ringmaster_class(tourn_pathname) if command == "run": if options.log_gtp: ringmaster.enable_gtp_logging() if options.quiet: ringmaster.set_quiet_mode() do_run(ringmaster, options.parallel, options.max_games) elif command == "show": do_show(ringmaster) elif command == "stop": do_stop(ringmaster) elif command == "report": do_report(ringmaster) elif command == "reset": do_reset(ringmaster) elif command == "check": if not ringmaster.check_players(): exit_status = 1 elif command == "debugstatus": ringmaster.print_status() else: raise AssertionError except RingmasterError, e: print >>sys.stderr, "ringmaster:", e exit_status = 1 except KeyboardInterrupt: exit_status = 3 except job_manager.JobSourceError, e: print >>sys.stderr, "ringmaster: internal error" print >>sys.stderr, e exit_status = 4 except: print >>sys.stderr, "ringmaster: internal error" compact_tracebacks.log_traceback() exit_status = 4 sys.exit(exit_status)
if command == "run": if options.log_gtp: ringmaster.enable_gtp_logging() if options.quiet: ringmaster.set_quiet_mode() do_run(ringmaster, options.parallel, options.max_games) elif command == "show": do_show(ringmaster) elif command == "stop": do_stop(ringmaster) elif command == "report": do_report(ringmaster) elif command == "reset": do_reset(ringmaster) elif command == "check": if not ringmaster.check_players(): exit_status = 1 elif command == "debugstatus": ringmaster.print_status() else: raise AssertionError
exit_status = action(ringmaster, options)
def run(argv, ringmaster_class): usage = ("%prog [options] <control file> [command]\n\n" "commands: run (default), stop, show, report, reset, check") parser = OptionParser(usage=usage, prog="ringmaster") parser.add_option("--max-games", "-g", type="int", help="maximum number of games to play in this run") parser.add_option("--parallel", "-j", type="int", help="number of worker processes") parser.add_option("--quiet", "-q", action="store_true", help="silent except for warnings and errors") parser.add_option("--log-gtp", action="store_true", help="write GTP logs") (options, args) = parser.parse_args() if len(args) == 0: parser.error("no control file specified") if len(args) > 2: parser.error("too many arguments") if len(args) == 1: command = "run" else: command = args[1] if command not in ("run", "stop", "show", "report", "reset", "check", "debugstatus"): parser.error("no such command: %s" % command) tourn_pathname = args[0] if not tourn_pathname.endswith(".tourn"): parser.error("not a .tourn file") exit_status = 0 try: if not os.path.exists(tourn_pathname): raise RingmasterError("control file %s not found" % tourn_pathname) ringmaster = ringmaster_class(tourn_pathname) if command == "run": if options.log_gtp: ringmaster.enable_gtp_logging() if options.quiet: ringmaster.set_quiet_mode() do_run(ringmaster, options.parallel, options.max_games) elif command == "show": do_show(ringmaster) elif command == "stop": do_stop(ringmaster) elif command == "report": do_report(ringmaster) elif command == "reset": do_reset(ringmaster) elif command == "check": if not ringmaster.check_players(): exit_status = 1 elif command == "debugstatus": ringmaster.print_status() else: raise AssertionError except RingmasterError, e: print >>sys.stderr, "ringmaster:", e exit_status = 1 except KeyboardInterrupt: exit_status = 3 except job_manager.JobSourceError, e: print >>sys.stderr, "ringmaster: internal error" print >>sys.stderr, e exit_status = 4 except: print >>sys.stderr, "ringmaster: internal error" compact_tracebacks.log_traceback() exit_status = 4 sys.exit(exit_status)
game_id -- int
game_id -- short string
def __init__(self): self.gtp_translations = {}
self.issued -= len(self.to_reissue)
def rollback(self): """Make issued-but-not-fixed tokens available again.""" self.to_reissue.update(self.outstanding) self.outstanding = set() self.issued -= len(self.to_reissue)
A copy of tournament_globals is used as the global namespace. Returns this
A copy of control_file_globals is used as the global namespace. Returns this
def read_tourn_file(pathname): """Read the specified file as a .tourn file. A copy of tournament_globals is used as the global namespace. Returns this namespace as a dict. """ result = control_file_globals.copy() f = open(pathname) exec f in result f.close() return result
files_to_remove.append()
files_to_remove.append(pathname)
def run(self): files_to_remove = [] dirs_to_remove = []
Returns the result text from the engine as a string with no leading or trailing whitespace. (This doesn't include the leading =[id] bit.)
Returns the result text from the engine as a string with no trailing whitespace. It may contain newlines, but there are no empty lines except perhaps the first. There is no leading whitespace on the first line. (It doesn't include the leading =[id] bit.)
def do_command(self, channel_id, command, *arguments): """Send a command over a channel and return the response.
def test_basic_config(tc): comp = playoffs.Playoff('test') config = {
def check_screen_report(tc, comp, expected): """Check that a competition's screen report is as expected.""" out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual(out.getvalue(), expected) class Playoff_fixture(test_framework.Fixture): """Fixture setting up a Playoff. attributes: comp -- Playoff """ def __init__(self, tc, config=None): if config is None: config = default_config() self.tc = tc self.comp = playoffs.Playoff('testcomp') self.comp.initialise_from_control_file(config) self.comp.set_clean_status() def check_screen_report(self, expected): """Check that the screen report is as expected.""" check_screen_report(self.tc, self.comp, expected) def default_config(): return {
def test_basic_config(tc): comp = playoffs.Playoff('test') config = { 'players' : { 't1' : Player_config("test"), 't2' : Player_config("test"), }, 'board_size' : 13, 'komi' : 7.5, 'matchups' : [ Matchup_config( 't1', 't2', board_size=9, komi=0.5, alternating=True, handicap=6, handicap_style='free', move_limit=50, scorer="internal", number_of_games=20), Matchup_config('t2', 't1', id='m1'), Matchup_config('t1', 't2'), ], } comp.initialise_from_control_file(config) m0 = comp.get_matchup('0') m1 = comp.get_matchup('m1') m2 = comp.get_matchup('2') tc.assertListEqual(comp.get_matchup_ids(), ['0', 'm1', '2']) tc.assertDictEqual(comp.get_matchups(), {'0' : m0, 'm1' : m1, '2' : m2}) tc.assertEqual(m0.p1, 't1') tc.assertEqual(m0.p2, 't2') tc.assertEqual(m0.board_size, 9) tc.assertEqual(m0.komi, 0.5) tc.assertIs(m0.alternating, True) tc.assertEqual(m0.handicap, 6) tc.assertEqual(m0.handicap_style, 'free') tc.assertEqual(m0.move_limit, 50) tc.assertEqual(m0.scorer, 'internal') tc.assertEqual(m0.number_of_games, 20) tc.assertEqual(m1.p1, 't2') tc.assertEqual(m1.p2, 't1') tc.assertEqual(m1.board_size, 13) tc.assertEqual(m1.komi, 7.5) tc.assertIs(m1.alternating, False) tc.assertEqual(m1.handicap, None) tc.assertEqual(m1.handicap_style, 'fixed') tc.assertEqual(m1.move_limit, 1000) tc.assertEqual(m1.scorer, 'players') tc.assertEqual(m1.number_of_games, None)
't1' : Player_config("test"), 't2' : Player_config("test"),
't1' : Player_config("test1"), 't2' : Player_config("test2"),
def test_basic_config(tc): comp = playoffs.Playoff('test') config = { 'players' : { 't1' : Player_config("test"), 't2' : Player_config("test"), }, 'board_size' : 13, 'komi' : 7.5, 'matchups' : [ Matchup_config( 't1', 't2', board_size=9, komi=0.5, alternating=True, handicap=6, handicap_style='free', move_limit=50, scorer="internal", number_of_games=20), Matchup_config('t2', 't1', id='m1'), Matchup_config('t1', 't2'), ], } comp.initialise_from_control_file(config) m0 = comp.get_matchup('0') m1 = comp.get_matchup('m1') m2 = comp.get_matchup('2') tc.assertListEqual(comp.get_matchup_ids(), ['0', 'm1', '2']) tc.assertDictEqual(comp.get_matchups(), {'0' : m0, 'm1' : m1, '2' : m2}) tc.assertEqual(m0.p1, 't1') tc.assertEqual(m0.p2, 't2') tc.assertEqual(m0.board_size, 9) tc.assertEqual(m0.komi, 0.5) tc.assertIs(m0.alternating, True) tc.assertEqual(m0.handicap, 6) tc.assertEqual(m0.handicap_style, 'free') tc.assertEqual(m0.move_limit, 50) tc.assertEqual(m0.scorer, 'internal') tc.assertEqual(m0.number_of_games, 20) tc.assertEqual(m1.p1, 't2') tc.assertEqual(m1.p2, 't1') tc.assertEqual(m1.board_size, 13) tc.assertEqual(m1.komi, 7.5) tc.assertIs(m1.alternating, False) tc.assertEqual(m1.handicap, None) tc.assertEqual(m1.handicap_style, 'fixed') tc.assertEqual(m1.move_limit, 1000) tc.assertEqual(m1.scorer, 'players') tc.assertEqual(m1.number_of_games, None)
], }
]
def test_basic_config(tc): comp = playoffs.Playoff('test') config = { 'players' : { 't1' : Player_config("test"), 't2' : Player_config("test"), }, 'board_size' : 13, 'komi' : 7.5, 'matchups' : [ Matchup_config( 't1', 't2', board_size=9, komi=0.5, alternating=True, handicap=6, handicap_style='free', move_limit=50, scorer="internal", number_of_games=20), Matchup_config('t2', 't1', id='m1'), Matchup_config('t1', 't2'), ], } comp.initialise_from_control_file(config) m0 = comp.get_matchup('0') m1 = comp.get_matchup('m1') m2 = comp.get_matchup('2') tc.assertListEqual(comp.get_matchup_ids(), ['0', 'm1', '2']) tc.assertDictEqual(comp.get_matchups(), {'0' : m0, 'm1' : m1, '2' : m2}) tc.assertEqual(m0.p1, 't1') tc.assertEqual(m0.p2, 't2') tc.assertEqual(m0.board_size, 9) tc.assertEqual(m0.komi, 0.5) tc.assertIs(m0.alternating, True) tc.assertEqual(m0.handicap, 6) tc.assertEqual(m0.handicap_style, 'free') tc.assertEqual(m0.move_limit, 50) tc.assertEqual(m0.scorer, 'internal') tc.assertEqual(m0.number_of_games, 20) tc.assertEqual(m1.p1, 't2') tc.assertEqual(m1.p2, 't1') tc.assertEqual(m1.board_size, 13) tc.assertEqual(m1.komi, 7.5) tc.assertIs(m1.alternating, False) tc.assertEqual(m1.handicap, None) tc.assertEqual(m1.handicap_style, 'fixed') tc.assertEqual(m1.move_limit, 1000) tc.assertEqual(m1.scorer, 'players') tc.assertEqual(m1.number_of_games, None)
comp = playoffs.Playoff('test') config = { 'players' : { 't1' : Player_config("test"), 't2' : Player_config("test"), }, 'board_size' : 12, 'handicap' : 6, 'komi' : 7.5, 'matchups' : [ Matchup_config('t1', 't2'), ], }
comp = playoffs.Playoff('testcomp') config = default_config() config['board_size'] = 12 config['handicap'] = 6
def test_global_handicap_validation(tc): comp = playoffs.Playoff('test') config = { 'players' : { 't1' : Player_config("test"), 't2' : Player_config("test"), }, 'board_size' : 12, 'handicap' : 6, 'komi' : 7.5, 'matchups' : [ Matchup_config('t1', 't2'), ], } with tc.assertRaises(ControlFileError) as ar: comp.initialise_from_control_file(config) tc.assertEqual(str(ar.exception), "default fixed handicap out of range for board size 12")
comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't1', number_of_games=1000), ], } comp.initialise_from_control_file(config) comp.set_clean_status() tc.assertEqual(comp.get_game().game_id, '0_000')
config = default_config() config['matchups'][0] = Matchup_config('t1', 't2', number_of_games=1000) fx = Playoff_fixture(tc, config) tc.assertEqual(fx.comp.get_game().game_id, '0_000')
def test_game_id_format(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't1', number_of_games=1000), ], } comp.initialise_from_control_file(config) comp.set_clean_status() tc.assertEqual(comp.get_game().game_id, '0_000')
comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game()
fx = Playoff_fixture(tc) job1 = fx.comp.get_game()
def test_play(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game() tc.assertIsInstance(job1, Game_job) tc.assertEqual(job1.game_id, '0_0') tc.assertEqual(job1.player_b.code, 't1') tc.assertEqual(job1.player_w.code, 't2') tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5) tc.assertEqual(job1.move_limit, 1000) tc.assertEqual(job1.game_data, ('0', 0)) tc.assertIsNone(job1.sgf_filename) tc.assertIsNone(job1.sgf_dirname) tc.assertIsNone(job1.void_sgf_dirname) tc.assertEqual(job1.sgf_event, 'testcomp') tc.assertIsNone(job1.gtp_log_pathname) job2 = comp.get_game() tc.assertIsInstance(job2, Game_job) tc.assertEqual(job2.game_id, '0_1') tc.assertEqual(job2.player_b.code, 't2') tc.assertEqual(job2.player_w.code, 't1') result1 = Game_result({'b' : 't1', 'w' : 't2'}, 'b') result1.sgf_result = "B+8.5" response1 = Game_job_result() response1.game_id = job1.game_id response1.game_result = result1 response1.engine_names = {} response1.engine_descriptions = {} response1.game_data = job1.game_data comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (1 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 1 100.00% (black)\n" "t2 0 0.00% (white)\n") tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5)
tc.assertEqual(job1.board_size, 13) tc.assertEqual(job1.komi, 7.5)
def test_play(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game() tc.assertIsInstance(job1, Game_job) tc.assertEqual(job1.game_id, '0_0') tc.assertEqual(job1.player_b.code, 't1') tc.assertEqual(job1.player_w.code, 't2') tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5) tc.assertEqual(job1.move_limit, 1000) tc.assertEqual(job1.game_data, ('0', 0)) tc.assertIsNone(job1.sgf_filename) tc.assertIsNone(job1.sgf_dirname) tc.assertIsNone(job1.void_sgf_dirname) tc.assertEqual(job1.sgf_event, 'testcomp') tc.assertIsNone(job1.gtp_log_pathname) job2 = comp.get_game() tc.assertIsInstance(job2, Game_job) tc.assertEqual(job2.game_id, '0_1') tc.assertEqual(job2.player_b.code, 't2') tc.assertEqual(job2.player_w.code, 't1') result1 = Game_result({'b' : 't1', 'w' : 't2'}, 'b') result1.sgf_result = "B+8.5" response1 = Game_job_result() response1.game_id = job1.game_id response1.game_result = result1 response1.engine_names = {} response1.engine_descriptions = {} response1.game_data = job1.game_data comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (1 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 1 100.00% (black)\n" "t2 0 0.00% (white)\n") tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
job2 = comp.get_game()
job2 = fx.comp.get_game()
def test_play(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game() tc.assertIsInstance(job1, Game_job) tc.assertEqual(job1.game_id, '0_0') tc.assertEqual(job1.player_b.code, 't1') tc.assertEqual(job1.player_w.code, 't2') tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5) tc.assertEqual(job1.move_limit, 1000) tc.assertEqual(job1.game_data, ('0', 0)) tc.assertIsNone(job1.sgf_filename) tc.assertIsNone(job1.sgf_dirname) tc.assertIsNone(job1.void_sgf_dirname) tc.assertEqual(job1.sgf_event, 'testcomp') tc.assertIsNone(job1.gtp_log_pathname) job2 = comp.get_game() tc.assertIsInstance(job2, Game_job) tc.assertEqual(job2.game_id, '0_1') tc.assertEqual(job2.player_b.code, 't2') tc.assertEqual(job2.player_w.code, 't1') result1 = Game_result({'b' : 't1', 'w' : 't2'}, 'b') result1.sgf_result = "B+8.5" response1 = Game_job_result() response1.game_id = job1.game_id response1.game_result = result1 response1.engine_names = {} response1.engine_descriptions = {} response1.game_data = job1.game_data comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (1 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 1 100.00% (black)\n" "t2 0 0.00% (white)\n") tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(),
fx.comp.process_game_result(response1) fx.check_screen_report(
def test_play(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game() tc.assertIsInstance(job1, Game_job) tc.assertEqual(job1.game_id, '0_0') tc.assertEqual(job1.player_b.code, 't1') tc.assertEqual(job1.player_w.code, 't2') tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5) tc.assertEqual(job1.move_limit, 1000) tc.assertEqual(job1.game_data, ('0', 0)) tc.assertIsNone(job1.sgf_filename) tc.assertIsNone(job1.sgf_dirname) tc.assertIsNone(job1.void_sgf_dirname) tc.assertEqual(job1.sgf_event, 'testcomp') tc.assertIsNone(job1.gtp_log_pathname) job2 = comp.get_game() tc.assertIsInstance(job2, Game_job) tc.assertEqual(job2.game_id, '0_1') tc.assertEqual(job2.player_b.code, 't2') tc.assertEqual(job2.player_w.code, 't1') result1 = Game_result({'b' : 't1', 'w' : 't2'}, 'b') result1.sgf_result = "B+8.5" response1 = Game_job_result() response1.game_id = job1.game_id response1.game_result = result1 response1.engine_names = {} response1.engine_descriptions = {} response1.game_data = job1.game_data comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (1 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 1 100.00% (black)\n" "t2 0 0.00% (white)\n") tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
"board size: 12 komi: 3.5\n"
"board size: 13 komi: 7.5\n"
def test_play(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game() tc.assertIsInstance(job1, Game_job) tc.assertEqual(job1.game_id, '0_0') tc.assertEqual(job1.player_b.code, 't1') tc.assertEqual(job1.player_w.code, 't2') tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5) tc.assertEqual(job1.move_limit, 1000) tc.assertEqual(job1.game_data, ('0', 0)) tc.assertIsNone(job1.sgf_filename) tc.assertIsNone(job1.sgf_dirname) tc.assertIsNone(job1.void_sgf_dirname) tc.assertEqual(job1.sgf_event, 'testcomp') tc.assertIsNone(job1.gtp_log_pathname) job2 = comp.get_game() tc.assertIsInstance(job2, Game_job) tc.assertEqual(job2.game_id, '0_1') tc.assertEqual(job2.player_b.code, 't2') tc.assertEqual(job2.player_w.code, 't1') result1 = Game_result({'b' : 't1', 'w' : 't2'}, 'b') result1.sgf_result = "B+8.5" response1 = Game_job_result() response1.game_id = job1.game_id response1.game_result = result1 response1.engine_names = {} response1.engine_descriptions = {} response1.game_data = job1.game_data comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (1 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 1 100.00% (black)\n" "t2 0 0.00% (white)\n") tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
tc.assertListEqual(fx.comp.get_matchup_results('0'), [('0_0', result1)])
def test_play(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() job1 = comp.get_game() tc.assertIsInstance(job1, Game_job) tc.assertEqual(job1.game_id, '0_0') tc.assertEqual(job1.player_b.code, 't1') tc.assertEqual(job1.player_w.code, 't2') tc.assertEqual(job1.board_size, 12) tc.assertEqual(job1.komi, 3.5) tc.assertEqual(job1.move_limit, 1000) tc.assertEqual(job1.game_data, ('0', 0)) tc.assertIsNone(job1.sgf_filename) tc.assertIsNone(job1.sgf_dirname) tc.assertIsNone(job1.void_sgf_dirname) tc.assertEqual(job1.sgf_event, 'testcomp') tc.assertIsNone(job1.gtp_log_pathname) job2 = comp.get_game() tc.assertIsInstance(job2, Game_job) tc.assertEqual(job2.game_id, '0_1') tc.assertEqual(job2.player_b.code, 't2') tc.assertEqual(job2.player_w.code, 't1') result1 = Game_result({'b' : 't1', 'w' : 't2'}, 'b') result1.sgf_result = "B+8.5" response1 = Game_job_result() response1.game_id = job1.game_id response1.game_result = result1 response1.engine_names = {} response1.engine_descriptions = {} response1.game_data = job1.game_data comp.process_game_result(response1) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (1 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 1 100.00% (black)\n" "t2 0 0.00% (white)\n") tc.assertListEqual(comp.get_matchup_results('0'), [('0_0', result1)])
comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() jobs = [comp.get_game() for _ in range(8)]
fx = Playoff_fixture(tc) jobs = [fx.comp.get_game() for _ in range(8)]
def test_play_many(tc): comp = playoffs.Playoff('testcomp') config = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp.initialise_from_control_file(config) comp.set_clean_status() jobs = [comp.get_game() for _ in range(8)] def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response for i in [0, 3]: response = fake_response(jobs[i], 'b') comp.process_game_result(response) jobs += [comp.get_game() for _ in range(3)] for i in [4, 2, 6, 7]: response = fake_response(jobs[i], 'w') comp.process_game_result(response) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(), "t1 v t2 (6 games)\n" "board size: 12 komi: 3.5\n" " wins\n" "t1 2 33.33% (black)\n" "t2 4 66.67% (white)\n") tc.assertEqual(len(comp.get_matchup_results('0')), 6) #tc.assertEqual(comp.scheduler.allocators['0'].issued, 11) #tc.assertEqual(comp.scheduler.allocators['0'].fixed, 6) config2 = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], } comp2 = playoffs.Playoff('testcomp') comp2.initialise_from_control_file(config2) comp2.set_status(comp.get_status()) #tc.assertEqual(comp2.scheduler.allocators['0'].issued, 6) #tc.assertEqual(comp2.scheduler.allocators['0'].fixed, 6) jobs2 = [comp.get_game() for _ in range(4)] tc.assertListEqual([job.game_id for job in jobs2], ['0_1', '0_5', '0_8', '0_9'])
comp.process_game_result(response) jobs += [comp.get_game() for _ in range(3)]
fx.comp.process_game_result(response) jobs += [fx.comp.get_game() for _ in range(3)]
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
comp.process_game_result(response) out = StringIO() comp.write_screen_report(out) tc.assertMultiLineEqual( out.getvalue(),
fx.comp.process_game_result(response) fx.check_screen_report(
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
"board size: 12 komi: 3.5\n"
"board size: 13 komi: 7.5\n"
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
tc.assertEqual(len(comp.get_matchup_results('0')), 6) config2 = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't2', alternating=True), ], }
tc.assertEqual(len(fx.comp.get_matchup_results('0')), 6)
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
comp2.initialise_from_control_file(config2) comp2.set_status(comp.get_status())
comp2.initialise_from_control_file(default_config()) status = pickle.loads(pickle.dumps(fx.comp.get_status())) comp2.set_status(status)
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
jobs2 = [comp.get_game() for _ in range(4)]
jobs2 = [comp2.get_game() for _ in range(4)]
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
config2 = { 'players' : { 't1' : Player_config("test1"), 't2' : Player_config("test2"), 't3' : Player_config("test3"), }, 'board_size' : 12, 'komi' : 3.5, 'matchups' : [ Matchup_config('t1', 't3', alternating=True), ], }
config2 = default_config() config2['players']['t3'] = Player_config("test3") config2['matchups'][0] = Matchup_config('t1', 't3', alternating=True)
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
comp2.set_status(comp.get_status())
comp2.set_status(status)
def fake_response(job, winner): result = Game_result({'b' : 't1', 'w' : 't2'}, winner) response = Game_job_result() response.game_id = job.game_id response.game_result = result response.engine_names = {} response.engine_descriptions = {} response.game_data = job.game_data return response
def _make_proxy(): channel = gtp_engine_fixtures.get_test_channel() controller = gtp_controller.Gtp_controller(channel, 'testbackend') proxy = gtp_proxy.Gtp_proxy() proxy.set_back_end_controller(controller) proxy._commands_handled = controller.channel.engine.commands_handled return proxy
class Proxy_fixture(test_framework.Fixture): """Fixture managing a Gtp_proxy with the test engine as its back-end. attributes: proxy -- Gtp_proxy controller -- Gtp_controller channel -- Testing_gtp_channel (like get_test_channel()) engine -- the proxy engine underlying_engine -- the underlying test engine (like get_test_engine()) commands_handled -- from the underlying Recording_gtp_engine_protocol """ def __init__(self, tc): self.tc = tc self.channel = gtp_engine_fixtures.get_test_channel() self.underlying_engine = self.channel.engine self.controller = gtp_controller.Gtp_controller( self.channel, 'testbackend') self.proxy = gtp_proxy.Gtp_proxy() self.proxy.set_back_end_controller(self.controller) self.engine = self.proxy.engine self.commands_handled = self.underlying_engine.commands_handled def check_command(self, *args, **kwargs): """Send a command to the proxy engine and check its response. (This is testing the proxy engine, not the underlying engine.) parameters as for gtp_engine_test_support.check_engine() """ gtp_engine_test_support.check_engine( self.tc, self.engine, *args, **kwargs)
def _make_proxy(): channel = gtp_engine_fixtures.get_test_channel() controller = gtp_controller.Gtp_controller(channel, 'testbackend') proxy = gtp_proxy.Gtp_proxy() proxy.set_back_end_controller(controller) # Make the commands from the underlying Recording_gtp_engine_protocol # available to tests proxy._commands_handled = controller.channel.engine.commands_handled return proxy
proxy = _make_proxy() check_engine(tc, proxy.engine, 'test', ['ab', 'cd'], "args: ab cd") proxy.close()
fx = Proxy_fixture(tc) fx.check_command('test', ['ab', 'cd'], "args: ab cd") fx.proxy.close()
def test_proxy(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'test', ['ab', 'cd'], "args: ab cd") proxy.close() tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('test', ['ab', 'cd']), ('quit', [])]) tc.assertTrue(proxy.controller.channel.is_closed)
proxy._commands_handled,
fx.commands_handled,
def test_proxy(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'test', ['ab', 'cd'], "args: ab cd") proxy.close() tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('test', ['ab', 'cd']), ('quit', [])]) tc.assertTrue(proxy.controller.channel.is_closed)
tc.assertTrue(proxy.controller.channel.is_closed)
tc.assertTrue(fx.controller.channel.is_closed)
def test_proxy(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'test', ['ab', 'cd'], "args: ab cd") proxy.close() tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('test', ['ab', 'cd']), ('quit', [])]) tc.assertTrue(proxy.controller.channel.is_closed)
proxy = _make_proxy() check_engine(tc, proxy.engine, 'quit', [], "", expect_end=True) proxy.close()
fx = Proxy_fixture(tc) fx.check_command('quit', [], "", expect_end=True) fx.proxy.close()
def test_close_after_quit(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'quit', [], "", expect_end=True) proxy.close() tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('quit', [])]) tc.assertTrue(proxy.controller.channel.is_closed)
proxy._commands_handled,
fx.commands_handled,
def test_close_after_quit(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'quit', [], "", expect_end=True) proxy.close() tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('quit', [])]) tc.assertTrue(proxy.controller.channel.is_closed)
tc.assertTrue(proxy.controller.channel.is_closed)
tc.assertTrue(fx.channel.is_closed)
def test_close_after_quit(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'quit', [], "", expect_end=True) proxy.close() tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('quit', [])]) tc.assertTrue(proxy.controller.channel.is_closed)
proxy = _make_proxy()
fx = Proxy_fixture(tc)
def test_list_commands(tc): proxy = _make_proxy() tc.assertListEqual( proxy.engine.list_commands(), ['error', 'fatal', 'gomill-passthrough', 'known_command', 'list_commands', 'multiline', 'protocol_version', 'quit', 'test']) proxy.close()
proxy.engine.list_commands(),
fx.engine.list_commands(),
def test_list_commands(tc): proxy = _make_proxy() tc.assertListEqual( proxy.engine.list_commands(), ['error', 'fatal', 'gomill-passthrough', 'known_command', 'list_commands', 'multiline', 'protocol_version', 'quit', 'test']) proxy.close()
proxy.close()
fx.proxy.close()
def test_list_commands(tc): proxy = _make_proxy() tc.assertListEqual( proxy.engine.list_commands(), ['error', 'fatal', 'gomill-passthrough', 'known_command', 'list_commands', 'multiline', 'protocol_version', 'quit', 'test']) proxy.close()
proxy = _make_proxy() tc.assertTrue(proxy.back_end_has_command('test')) tc.assertFalse(proxy.back_end_has_command('xyzzy')) tc.assertFalse(proxy.back_end_has_command('gomill-passthrough'))
fx = Proxy_fixture(tc) tc.assertTrue(fx.proxy.back_end_has_command('test')) tc.assertFalse(fx.proxy.back_end_has_command('xyzzy')) tc.assertFalse(fx.proxy.back_end_has_command('gomill-passthrough'))
def test_back_end_has_command(tc): proxy = _make_proxy() tc.assertTrue(proxy.back_end_has_command('test')) tc.assertFalse(proxy.back_end_has_command('xyzzy')) tc.assertFalse(proxy.back_end_has_command('gomill-passthrough'))
proxy = _make_proxy() check_engine(tc, proxy.engine, 'known_command', ['gomill-passthrough'], "true") check_engine(tc, proxy.engine, 'gomill-passthrough', ['test', 'ab', 'cd'], "args: ab cd") check_engine(tc, proxy.engine, 'gomill-passthrough', ['known_command', 'gomill-passthrough'], "false") check_engine(tc, proxy.engine, 'gomill-passthrough', [], "invalid arguments", expect_failure=True)
fx = Proxy_fixture(tc) fx.check_command('known_command', ['gomill-passthrough'], "true") fx.check_command('gomill-passthrough', ['test', 'ab', 'cd'], "args: ab cd") fx.check_command( 'gomill-passthrough', ['known_command', 'gomill-passthrough'], "false") fx.check_command('gomill-passthrough', [], "invalid arguments", expect_failure=True)
def test_passthrough(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'known_command', ['gomill-passthrough'], "true") check_engine(tc, proxy.engine, 'gomill-passthrough', ['test', 'ab', 'cd'], "args: ab cd") check_engine(tc, proxy.engine, 'gomill-passthrough', ['known_command', 'gomill-passthrough'], "false") check_engine(tc, proxy.engine, 'gomill-passthrough', [], "invalid arguments", expect_failure=True) tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('test', ['ab', 'cd']), ('known_command', ['gomill-passthrough'])])
proxy._commands_handled,
fx.commands_handled,
def test_passthrough(tc): proxy = _make_proxy() check_engine(tc, proxy.engine, 'known_command', ['gomill-passthrough'], "true") check_engine(tc, proxy.engine, 'gomill-passthrough', ['test', 'ab', 'cd'], "args: ab cd") check_engine(tc, proxy.engine, 'gomill-passthrough', ['known_command', 'gomill-passthrough'], "false") check_engine(tc, proxy.engine, 'gomill-passthrough', [], "invalid arguments", expect_failure=True) tc.assertEqual( proxy._commands_handled, [('list_commands', []), ('test', ['ab', 'cd']), ('known_command', ['gomill-passthrough'])])
proxy = _make_proxy() tc.assertEqual(proxy.pass_command("test", ["ab", "cd"]), "args: ab cd")
fx = Proxy_fixture(tc) tc.assertEqual(fx.proxy.pass_command("test", ["ab", "cd"]), "args: ab cd")
def test_pass_command(tc): proxy = _make_proxy() tc.assertEqual(proxy.pass_command("test", ["ab", "cd"]), "args: ab cd") with tc.assertRaises(BadGtpResponse) as ar: proxy.pass_command("error", []) tc.assertEqual(ar.exception.gtp_error_message, "normal error") tc.assertEqual(str(ar.exception), "failure response from 'error' to testbackend:\n" "normal error")
proxy.pass_command("error", [])
fx.proxy.pass_command("error", [])
def test_pass_command(tc): proxy = _make_proxy() tc.assertEqual(proxy.pass_command("test", ["ab", "cd"]), "args: ab cd") with tc.assertRaises(BadGtpResponse) as ar: proxy.pass_command("error", []) tc.assertEqual(ar.exception.gtp_error_message, "normal error") tc.assertEqual(str(ar.exception), "failure response from 'error' to testbackend:\n" "normal error")
proxy = _make_proxy() proxy.controller.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: proxy.pass_command("test", [])
fx = Proxy_fixture(tc) fx.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: fx.proxy.pass_command("test", [])
def test_pass_command_with_channel_error(tc): proxy = _make_proxy() proxy.controller.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: proxy.pass_command("test", []) tc.assertEqual(str(ar.exception), "transport error sending 'test' to testbackend:\n" "forced failure for send_command_line") tc.assertIsInstance(ar.exception.cause, GtpTransportError) proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', [])])
proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', [])])
fx.proxy.close() tc.assertEqual(fx.commands_handled, [('list_commands', [])])
def test_pass_command_with_channel_error(tc): proxy = _make_proxy() proxy.controller.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: proxy.pass_command("test", []) tc.assertEqual(str(ar.exception), "transport error sending 'test' to testbackend:\n" "forced failure for send_command_line") tc.assertIsInstance(ar.exception.cause, GtpTransportError) proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', [])])
return proxy.handle_command("error", [])
return fx.proxy.handle_command("error", [])
def handle_xyzzy(args): if args and args[0] == "error": return proxy.handle_command("error", []) else: return proxy.handle_command("test", ["nothing", "happens"])
return proxy.handle_command("test", ["nothing", "happens"]) proxy = _make_proxy() proxy.engine.add_command("xyzzy", handle_xyzzy) check_engine(tc, proxy.engine, 'xyzzy', [], "args: nothing happens") check_engine(tc, proxy.engine, 'xyzzy', ['error'], "normal error", expect_failure=True)
return fx.proxy.handle_command("test", ["nothing", "happens"]) fx = Proxy_fixture(tc) fx.engine.add_command("xyzzy", handle_xyzzy) fx.check_command('xyzzy', [], "args: nothing happens") fx.check_command('xyzzy', ['error'], "normal error", expect_failure=True)
def handle_xyzzy(args): if args and args[0] == "error": return proxy.handle_command("error", []) else: return proxy.handle_command("test", ["nothing", "happens"])
return proxy.handle_command("test", []) proxy = _make_proxy() proxy.engine.add_command("xyzzy", handle_xyzzy) proxy.controller.channel.fail_next_command = True check_engine(tc, proxy.engine, 'xyzzy', [], "transport error sending 'test' to testbackend:\n" "forced failure for send_command_line", expect_failure=True, expect_end=True) proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', [])])
return fx.proxy.handle_command("test", []) fx = Proxy_fixture(tc) fx.engine.add_command("xyzzy", handle_xyzzy) fx.channel.fail_next_command = True fx.check_command('xyzzy', [], "transport error sending 'test' to testbackend:\n" "forced failure for send_command_line", expect_failure=True, expect_end=True) fx.proxy.close() tc.assertEqual(fx.commands_handled, [('list_commands', [])])
def handle_xyzzy(args): return proxy.handle_command("test", [])
proxy = _make_proxy() tc.assertEqual(proxy.pass_command("quit", []), "") check_engine(tc, proxy.engine, 'test', ['ab', 'cd'], "error sending 'test ab cd' to testbackend:\n" "engine has closed the command channel", expect_failure=True, expect_end=True)
fx = Proxy_fixture(tc) tc.assertEqual(fx.proxy.pass_command("quit", []), "") fx.check_command('test', ['ab', 'cd'], "error sending 'test ab cd' to testbackend:\n" "engine has closed the command channel", expect_failure=True, expect_end=True)
def test_back_end_goes_away(tc): proxy = _make_proxy() tc.assertEqual(proxy.pass_command("quit", []), "") check_engine(tc, proxy.engine, 'test', ['ab', 'cd'], "error sending 'test ab cd' to testbackend:\n" "engine has closed the command channel", expect_failure=True, expect_end=True)
proxy = _make_proxy() proxy.controller.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: proxy.close()
fx = Proxy_fixture(tc) fx.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: fx.proxy.close()
def test_close_with_errors(tc): proxy = _make_proxy() proxy.controller.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: proxy.close() tc.assertEqual(str(ar.exception), "transport error sending 'quit' to testbackend:\n" "forced failure for send_command_line") tc.assertTrue(proxy.controller.channel.is_closed)
tc.assertTrue(proxy.controller.channel.is_closed)
tc.assertTrue(fx.channel.is_closed)
def test_close_with_errors(tc): proxy = _make_proxy() proxy.controller.channel.fail_next_command = True with tc.assertRaises(BackEndError) as ar: proxy.close() tc.assertEqual(str(ar.exception), "transport error sending 'quit' to testbackend:\n" "forced failure for send_command_line") tc.assertTrue(proxy.controller.channel.is_closed)
proxy = _make_proxy() tc.assertEqual(proxy.pass_command("quit", []), "") check_engine(tc, proxy.engine, 'quit', [], "", expect_end=True) proxy.close() tc.assertEqual(proxy._commands_handled,
fx = Proxy_fixture(tc) tc.assertEqual(fx.proxy.pass_command("quit", []), "") fx.check_command('quit', [], "", expect_end=True) fx.proxy.close() tc.assertEqual(fx.commands_handled,
def test_quit_ignores_already_closed(tc): proxy = _make_proxy() tc.assertEqual(proxy.pass_command("quit", []), "") check_engine(tc, proxy.engine, 'quit', [], "", expect_end=True) proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', []), ('quit', [])])
proxy = _make_proxy() proxy.controller.channel.engine.add_command("quit", force_error) check_engine(tc, proxy.engine, 'quit', [], None,
fx = Proxy_fixture(tc) fx.underlying_engine.add_command("quit", force_error) fx.check_command('quit', [], None,
def force_error(args): 1 / 0
proxy.close() tc.assertEqual(proxy._commands_handled,
fx.proxy.close() tc.assertEqual(fx.commands_handled,
def force_error(args): 1 / 0
proxy = _make_proxy() proxy.controller.channel.fail_next_command = True check_engine(tc, proxy.engine, 'quit', [], "transport error sending 'quit' to testbackend:\n" "forced failure for send_command_line", expect_failure=True, expect_end=True) proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', [])])
fx = Proxy_fixture(tc) fx.channel.fail_next_command = True fx.check_command('quit', [], "transport error sending 'quit' to testbackend:\n" "forced failure for send_command_line", expect_failure=True, expect_end=True) fx.proxy.close() tc.assertEqual(fx.commands_handled, [('list_commands', [])])
def test_quit_with_channel_error(tc): proxy = _make_proxy() proxy.controller.channel.fail_next_command = True check_engine(tc, proxy.engine, 'quit', [], "transport error sending 'quit' to testbackend:\n" "forced failure for send_command_line", expect_failure=True, expect_end=True) proxy.close() tc.assertEqual(proxy._commands_handled, [('list_commands', [])])
Raises ValueError with an appropriate message if 'arg' isn't a valid GTP
Raises ValueError with an appropriate message if 'vertex' isn't a valid GTP
def coords_from_vertex(vertex, board_size): """Interpret a string representing a vertex, as specified by GTP. Returns a pair of coordinates (row, col) in range(0, board_size) Raises ValueError with an appropriate message if 'arg' isn't a valid GTP vertex specification for a board of size 'board_size'. """ if not 0 < board_size <= 25: raise ValueError("board_size out of range") s = vertex.lower() if s == "pass": return None try: col_c = s[0] if (not "a" <= col_c <= "z") or col_c == "i": raise ValueError if col_c > "i": col = ord(col_c) - ord("b") else: col = ord(col_c) - ord("a") row = int(s[1:]) - 1 if row < 0: raise ValueError except (IndexError, ValueError): raise ValueError("invalid vertex: '%s'" % s) if not (col < board_size and row < board_size): raise ValueError("vertex is off board: '%s'" % s) return row, col
if isinstance(b_score, Exception):
if b_score is Exception:
def handle_final_score_b(args): if isinstance(b_score, Exception): raise b_score return b_score
if isinstance(w_score, Exception):
if w_score is Exception:
def handle_final_score_w(args): if isinstance(w_score, Exception): raise w_score return w_score
fx.run_score_test("black wins", "W+4") tc.assertEqual(fx.game.result.sgf_result, "W+4") tc.assertIsNone(fx.game.result.detail) tc.assertEqual(fx.game.result.winning_colour, 'w')
fx.run_score_test("black wins", "W+4.5") tc.assertEqual(fx.game.result.sgf_result, "W+4.5") tc.assertIsNone(fx.game.result.detail) tc.assertEqual(fx.game.result.winning_colour, 'w') tc.assertEqual(fx.game.describe_scoring(), "two beat one W+4.5\n" "one final_score: black wins\n" "two final_score: W+4.5")
def test_players_score_one_illformed(tc): fx = Game_fixture(tc) fx.run_score_test("black wins", "W+4") tc.assertEqual(fx.game.result.sgf_result, "W+4") tc.assertIsNone(fx.game.result.detail) tc.assertEqual(fx.game.result.winning_colour, 'w')
fx.run_score_test("b+3", "B+4")
fx.run_score_test("b+3", "B+4.0")
def test_players_score_agree_except_margin(tc): fx = Game_fixture(tc) fx.run_score_test("b+3", "B+4") tc.assertEqual(fx.game.result.sgf_result, "B+") tc.assertEqual(fx.game.result.detail, "unknown margin") tc.assertEqual(fx.game.result.winning_colour, 'b')
unittest2.TestCase.__init__(self)
FrameworkTestCase.__init__(self)
def __init__(self, fn): unittest2.TestCase.__init__(self) self.fn = fn try: self.name = fn.__module__.split(".", 1)[-1] + "." + fn.__name__ except AttributeError: self.name = str(fn)
"""Render tablular output.
"""Render tabular output.
def render(self, s, width): if self.align == 'left': s = s.ljust(width) elif self.align == 'right': s = s.rjust(width) return s + " " * self.right_padding
s = controller.safe_do_command(colour, 'gomill-cpu_time')
s = controller.safe_do_command('gomill-cpu_time')
def calculate_cpu_times(self): """Set CPU times in self.result.
import logging LOG_FILENAME = '/tmp/openid.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) logging.debug("%s %s" % (identity_url, openid.openid))
def openid_is_authorized(req, identity_url, trust_root): """ Check that they own the given identity URL, and that the trust_root is in their whitelist of trusted sites. """ if not req.user.is_authenticated(): return None openid = openid_get_identity(req, identity_url) if openid is None: return None import logging LOG_FILENAME = '/tmp/openid.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) logging.debug("%s %s" % (identity_url, openid.openid)) if openid.trustedroot_set.filter(trust_root=trust_root).count() < 1: return None return openid
url = '%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, path)
url = '%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, urlquote(path))
def landing_page(request, orequest): """ The page shown when the user attempts to sign in somewhere using OpenID but is not authenticated with the site. For idproxy.net, a message telling them to log in manually is displayed. """ request.session['OPENID_REQUEST'] = orequest login_url = settings.LOGIN_URL path = request.get_full_path() url = '%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, path) return HttpResponseRedirect(url)
from megrok.layout import Page
from megrok.layout.components import UtilityView
def nextURL(self): url = self.url(self.context) return url
class Index(PageDisplayForm, Page, ContextualMenuEntry):
class Index(PageDisplayForm, ContextualMenuEntry):
def nextURL(self): url = self.url(self.context) return url
class Edit(PageEditForm, grok.View):
class Edit(PageEditForm, ContextualMenuEntry): grok.implements(IDisplayView)
def nextURL(self): url = self.url(self.context) return url
return item.geburtsdatum.strftime('%d.%m.%Y')
if item.geburtsdatum != None: return item.geburtsdatum.strftime('%d.%m.%Y')
def renderCell(self, item): return item.geburtsdatum.strftime('%d.%m.%Y')
for base, dirs, files in os.walk(STARTDIR):
for base, dirs, files in os.walk(STARTDIR, topdown=True):
def findOn(self,path):
skipDir = False
def findOn(self,path):
pprint(l) skipDir = True if skipDir: dirs.remove(dir_)
pprint(('DG',l)) culls.add(dir_)
def findOn(self,path):
pprint(l)
pprint(('DO',l)) for cull in culls: dirs.remove(cull)
def findOn(self,path):
pprint(l)
pprint(('FG', base, path, f, l))
def findOn(self,path):
class ReplicatedDiskException(Exception): pass
def commit(self): 'called when backup has acknowledged checkpoint reception' pass
class BufferedNICException(Exception): pass
_rth = None def getrth(): global _rth if not _rth: _rth = netlink.rtnl() return _rth class Netbuf(object): "Proxy for netdev with a queueing discipline" @staticmethod def devclass(): "returns the name of this device class" return 'unknown' @classmethod def available(cls): "returns True if this module can proxy the device" return cls._hasdev(cls.devclass()) def __init__(self, devname): self.devname = devname self.vif = None def install(self, vif): "set up proxy on device" raise BufferedNICException('unimplemented') def uninstall(self): "remove proxy on device" raise BufferedNICException('unimplemented') @staticmethod def _hasdev(devclass): """check for existence of device, attempting to load kernel module if not present""" devname = '%s0' % devclass rth = getrth() if rth.getlink(devname): return True if util.modprobe(devclass) and rth.getlink(devname): return True return False class IFBBuffer(Netbuf): """Capture packets arriving on a VIF using an ingress filter and tc mirred action to forward them to an IFB device. """ @staticmethod def devclass(): return 'ifb' def install(self, vif): self.vif = vif util.runcmd('ip link set %s up' % self.devname) util.runcmd('tc qdisc add dev %s ingress' % vif.dev) util.runcmd('tc filter add dev %s parent ffff: proto ip pref 10 ' 'u32 match u32 0 0 action mirred egress redirect ' 'dev %s' % (vif.dev, self.devname)) def uninstall(self): util.runcmd('tc filter del dev %s parent ffff: proto ip pref 10 u32' \ % self.vif.dev) util.runcmd('tc qdisc del dev %s ingress' % self.vif.dev) util.runcmd('ip link set %s down' % self.devname) class IMQBuffer(Netbuf): """Redirect packets coming in on vif to an IMQ device.""" imqebt = '/usr/lib/xen/bin/imqebt' @staticmethod def devclass(): return 'imq' def install(self, vif): self.vif = vif for mod in ['imq', 'ebt_imq']: util.runcmd(['modprobe', mod]) util.runcmd("ip link set %s up" % self.devname) util.runcmd("%s -F FORWARD" % self.imqebt) util.runcmd("%s -A FORWARD -i %s -j imq --todev %s" % (self.imqebt, vif.dev, self.devname)) def uninstall(self): util.runcmd("%s -F FORWARD" % self.imqebt) util.runcmd('ip link set %s down' % self.devname) netbuftypes = [IFBBuffer, IMQBuffer] def selectnetbuf(): "Find the best available buffer type" for driver in netbuftypes: if driver.available(): return driver raise BufferedNICException('no net buffer available') class Netbufpool(object): """Allocates/releases proxy netdevs (IMQ/IFB) A file contains a list of entries of the form <pid>:<device>\n To allocate a device, lock the file, then claim a new device if one is free. If there are no free devices, check each PID for liveness and take a device if the PID is dead, otherwise return failure. Add an entry to the file before releasing the lock. """ def __init__(self, netbufclass): "Create a pool of Device" self.netbufclass = netbufclass self.path = '/var/run/remus/' + self.netbufclass.devclass() self.devices = self.getdevs() pooldir = os.path.dirname(self.path) if not os.path.exists(pooldir): os.makedirs(pooldir, 0755) def get(self): "allocate a free device" def getfreedev(table): for dev in self.devices: if dev not in table or not util.checkpid(table[dev]): return dev return None lock = util.Lock(self.path) table = self.load() dev = getfreedev(table) if not dev: lock.unlock() raise BufferedNICException('no free devices') dev = self.netbufclass(dev) table[dev.devname] = os.getpid() self.save(table) lock.unlock() return dev def put(self, dev): "release claim on device" lock = util.Lock(self.path) table = self.load() del table[dev.devname] self.save(table) lock.unlock() def load(self): """load and parse allocation table""" table = {} if not os.path.exists(self.path): return table fd = open(self.path) for line in fd.readlines(): iface, pid = line.strip().split() table[iface] = int(pid) fd.close() return table def save(self, table): """write table to disk""" lines = ['%s %d\n' % (iface, table[iface]) for iface in sorted(table)] fd = open(self.path, 'w') fd.writelines(lines) fd.close() def getdevs(self): """find all available devices of our device type""" ifaces = [] for line in util.runcmd('ifconfig -a -s').splitlines(): iface = line.split()[0] if iface.startswith(self.netbufclass.devclass()): ifaces.append(iface) return ifaces
def commit(self): msg = os.read(self.msgfd.fileno(), 4) if msg != 'done': print 'Unknown message: %s' % msg