9 def setup_server_io(io_db):
10 """Fill IO files DB with proper file( path)s. Write process IO test string.
12 Decide file paths. Ensure IO files directory at server/. Remove any old in
13 file if found. Set up new in file (io_db["file_in"]) for reading at
14 io_db["path_in"], and new out file (io_db["file_out"]) for writing at
15 io_db["path_out"]. Start out file with process hash line of format PID +
16 " " + floated UNIX time (io_db["teststring"]). Run detect_atomic_leftover
17 on io_db["path_record"] and io_db["path_save"].
20 io_db["path_in"] = io_dir + "in"
21 io_db["path_out"] = io_dir + "out"
22 io_db["path_worldstate"] = io_dir + "worldstate"
23 io_db["path_record"] = "record"
24 io_db["path_save"] = "save"
25 io_db["path_worldconf"] = "confserver/world"
26 io_db["tmp_suffix"] = "_tmp"
27 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
28 os.makedirs(io_dir, exist_ok=True)
29 io_db["file_out"] = open(io_db["path_out"], "w")
30 io_db["file_out"].write(io_db["teststring"] + "\n")
31 if os.access(io_db["path_in"], os.F_OK):
32 os.remove(io_db["path_in"])
33 io_db["file_in"] = open(io_db["path_in"], "w")
34 io_db["file_in"].close()
35 io_db["file_in"] = open(io_db["path_in"], "r")
36 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
37 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
40 def cleanup_server_io(io_db):
41 """Close and remove all files open in IO files DB."""
42 def helper(file_key, path_key):
44 io_db[file_key].close()
45 os.remove(io_db[path_key])
46 helper("file_out", "path_out")
47 helper("file_in", "path_in")
48 helper("file_worldstate", "path_worldstate")
51 def detect_atomic_leftover(path, tmp_suffix):
52 """Raise explained SystemExit if file is found at path + tmp_suffix."""
53 path_tmp = path + tmp_suffix
54 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
55 "aborted previous attempt to write '" + path + "'. Aborting until " \
56 "the matter is resolved by removing it from its current path."
57 if os.access(path_tmp, os.F_OK):
61 def obey(cmd, io_db, prefix):
63 print("input " + prefix + ": " + cmd)
65 tokens = shlex.split(cmd, comments=True)
66 except ValueError as err:
67 print("Can't tokenize command string: " + str(err) + ".")
71 elif "PING" == tokens[0] and 1 == len(tokens):
72 io_db["file_out"].write("PONG\n")
73 elif "QUIT" == tokens[0] and 1 == len(tokens):
74 record("# " + cmd, path_recordfile)
75 raise SystemExit("received QUIT command")
76 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
77 print("I would generate a new world now, if only I knew how.")
80 print("Invalid command/argument, or bad number of tokens.")
83 def record(cmd, io_db):
84 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
85 # This misses some optimizations from the original record(), namely only
86 # finishing the atomic write with expensive flush() and fsync() every 15
87 # seconds unless explicitely forced. Implement as needed.
88 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
89 if os.access(io_db["path_record"], os.F_OK):
90 shutil.copyfile(io_db["path_record"], path_tmp)
91 file = open(path_tmp, "a")
92 file.write(cmd + "\n")
94 os.fsync(file.fileno())
96 if os.access(io_db["path_record"], os.F_OK):
97 os.remove(io_db["path_record"])
98 os.rename(path_tmp, io_db["path_record"])
101 def obey_lines_in_file(path, name, break_test=None):
102 """Call obey() on each line of path's file, use name in input prefix.
104 If break_test function is set, only read the file until it returns True.
106 file = open(path, "r")
108 for line in file.readlines():
109 if None != break_test and break_test():
111 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
116 def make_turn_tester(turn_to_compare, world_db):
117 """Return tester whether world_db["turn"] greater/equal turn_to_compare."""
119 return world_db["turn"] >= turn_to_compare
123 def parse_command_line_arguments():
124 """Return settings values read from command line arguments."""
125 parser = argparse.ArgumentParser()
126 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
128 opts, unknown = parser.parse_known_args()
135 opts = parse_command_line_arguments()
136 setup_server_io(io_db)
137 # print("DUMMY: Run game.")
138 if None != opts.replay:
141 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
142 " (if so late a turn is to be found).")
143 if not os.access(io_db["path_record"], os.F_OK):
144 raise SystemExit("No record file found to replay.")
146 break_tester = make_turn_tester(opts.replay, world_db)
147 obey_lines_in_file(io_db["path_record"], "record ", break_tester)
150 if os.access(io_db["path_save"], os.F_OK):
151 obey_lines_in_file(io_db["path_save"], "save")
153 if not os.access(io_db["path_worldconf"], os.F_OK):
154 msg = "No world config file from which to start a new world."
155 raise SystemExit(msg)
156 obey_lines_in_file(io_db["path_worldconf"], "world config ")
157 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
158 # print("DUMMY: Run io_loop().")
159 except SystemExit as exit:
160 print("ABORTING: " + exit.args[0])
162 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
165 cleanup_server_io(io_db)
166 # print("DUMMY: (Clean up C heap.)")