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 io_db["file_out"].flush()
32 if os.access(io_db["path_in"], os.F_OK):
33 os.remove(io_db["path_in"])
34 io_db["file_in"] = open(io_db["path_in"], "w")
35 io_db["file_in"].close()
36 io_db["file_in"] = open(io_db["path_in"], "r")
37 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
38 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
41 def cleanup_server_io(io_db):
42 """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
43 def helper(file_key, path_key):
45 io_db[file_key].close()
46 if not io_db["kicked_by_rival"]:
47 os.remove(io_db[path_key])
48 helper("file_out", "path_out")
49 helper("file_in", "path_in")
50 helper("file_worldstate", "path_worldstate")
53 def detect_atomic_leftover(path, tmp_suffix):
54 """Raise explained SystemExit if file is found at path + tmp_suffix."""
55 path_tmp = path + tmp_suffix
56 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
57 "aborted previous attempt to write '" + path + "'. Aborting until " \
58 "the matter is resolved by removing it from its current path."
59 if os.access(path_tmp, os.F_OK):
63 def obey(cmd, io_db, prefix):
65 print("input " + prefix + ": " + cmd)
67 tokens = shlex.split(cmd, comments=True)
68 except ValueError as err:
69 print("Can't tokenize command string: " + str(err) + ".")
73 elif "PING" == tokens[0] and 1 == len(tokens):
74 io_db["file_out"].write("PONG\n")
75 elif "QUIT" == tokens[0] and 1 == len(tokens):
76 record("# " + cmd, path_recordfile)
77 raise SystemExit("received QUIT command")
78 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
79 print("I would generate a new world now, if only I knew how.")
82 print("Invalid command/argument, or bad number of tokens.")
85 def record(cmd, io_db):
86 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
87 # This misses some optimizations from the original record(), namely only
88 # finishing the atomic write with expensive flush() and fsync() every 15
89 # seconds unless explicitely forced. Implement as needed.
90 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
91 if os.access(io_db["path_record"], os.F_OK):
92 shutil.copyfile(io_db["path_record"], path_tmp)
93 file = open(path_tmp, "a")
94 file.write(cmd + "\n")
96 os.fsync(file.fileno())
98 if os.access(io_db["path_record"], os.F_OK):
99 os.remove(io_db["path_record"])
100 os.rename(path_tmp, io_db["path_record"])
103 def obey_lines_in_file(path, name):
104 """Call obey() on each line of path's file, use name in input prefix."""
105 file = open(path, "r")
107 for line in file.readlines():
108 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
113 def parse_command_line_arguments():
114 """Return settings values read from command line arguments."""
115 parser = argparse.ArgumentParser()
116 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
118 opts, unknown = parser.parse_known_args()
122 def server_test(io_db):
123 """Ensure valid server out file belonging to current process.
125 On failure, set io_db["kicked_by_rival"] and raise SystemExit.
127 if not os.access(io_db["path_out"], os.F_OK):
128 raise SystemExit("Server output file has disappeared.")
129 file = open(io_db["path_out"], "r")
130 test = file.readline().rstrip("\n")
132 if test != io_db["teststring"]:
133 io_db["kicked_by_rival"] = True
134 msg = "Server test string in server output file does not match. This" \
135 " indicates that the current server process has been " \
136 "superseded by another one."
137 raise SystemExit(msg)
147 opts = parse_command_line_arguments()
148 setup_server_io(io_db)
149 # print("DUMMY: Run game.")
150 if None != opts.replay:
153 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
154 " (if so late a turn is to be found).")
155 if not os.access(io_db["path_record"], os.F_OK):
156 raise SystemExit("No record file found to replay.")
158 file = open(io_db["path_record"], "r")
159 prefix = "record file line "
161 while world_db["turn"] < opts.replay:
163 obey(file.readline().rstrip(), io_db, prefix + str(line_n))
165 world_db["turn"] = world_db["turn"] + 1
168 obey(file.readline().rstrip(), io_db, prefix + str(line_n))
172 if os.access(io_db["path_save"], os.F_OK):
173 obey_lines_in_file(io_db["path_save"], "save")
175 if not os.access(io_db["path_worldconf"], os.F_OK):
176 msg = "No world config file from which to start a new world."
177 raise SystemExit(msg)
178 obey_lines_in_file(io_db["path_worldconf"], "world config ")
179 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
183 except SystemExit as exit:
184 print("ABORTING: " + exit.args[0])
186 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
189 cleanup_server_io(io_db)
190 # print("DUMMY: (Clean up C heap.)")