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"]).
19 io_db["path_in"] = io_dir + "in"
20 io_db["path_out"] = io_dir + "out"
21 io_db["path_worldstate"] = io_dir + "worldstate"
22 io_db["path_record"] = "record"
23 io_db["path_save"] = "save"
24 io_db["path_worldconf"] = "confserver/world"
25 io_db["tmp_suffix"] = "_tmp"
26 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
27 os.makedirs(io_dir, exist_ok=True)
28 io_db["file_out"] = open(io_db["path_out"], "w")
29 io_db["file_out"].write(io_db["teststring"] + "\n")
30 if os.access(io_db["path_in"], os.F_OK):
31 os.remove(io_db["path_in"])
32 io_db["file_in"] = open(io_db["path_in"], "w")
33 io_db["file_in"].close()
34 io_db["file_in"] = open(io_db["path_in"], "r")
37 def cleanup_server_io(io_db):
38 """Close and remove all files open in IO files DB."""
39 def helper(file_key, path_key):
41 io_db[file_key].close()
42 os.remove(io_db[path_key])
43 helper("file_out", "path_out")
44 helper("file_in", "path_in")
45 helper("file_worldstate", "path_worldstate")
48 def detect_atomic_leftover(path, tmp_suffix):
49 """Raise explained SystemExit if file is found at path + tmp_suffix."""
50 path_tmp = path + tmp_suffix
51 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
52 "aborted previous attempt to write '" + path + "'. Aborting until " \
53 "the matter is resolved by removing it from its current path."
54 if os.access(path_tmp, os.F_OK):
58 def obey(cmd, io_db, prefix):
60 print("input " + prefix + ": " + cmd)
62 tokens = shlex.split(cmd, comments=True)
63 except ValueError as err:
64 print("Can't tokenize command string: " + str(err) + ".")
68 elif "PING" == tokens[0] and 1 == len(tokens):
69 io_db["file_out"].write("PONG\n")
70 elif "QUIT" == tokens[0] and 1 == len(tokens):
71 record("# " + cmd, path_recordfile)
72 raise SystemExit("received QUIT command")
73 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
74 print("I would generate a new world now, if only I knew how.")
77 print("Invalid command/argument, or bad number of tokens.")
80 def record(cmd, io_db):
81 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
82 # This misses some optimizations from the original record(), namely only
83 # finishing the atomic write with flush() and fsync() every 15 seconds
84 # unless explicitely forced. Implement as needed.
85 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
86 if os.access(io_db["path_record"], os.F_OK):
87 shutil.copyfile(io_db["path_record"], path_tmp)
88 file = open(path_tmp, "a")
89 file.write(cmd + "\n")
91 os.fsync(file.fileno())
93 if os.access(io_db["path_record"], os.F_OK):
94 os.remove(io_db["path_record"])
95 os.rename(path_tmp, io_db["path_record"])
98 def obey_lines_in_file(path, name):
99 """Call obey() on each line of path's file, use name in input prefix."""
100 file = open(io_db["path_worldconf"], "r")
102 for line in file.readlines():
103 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
110 parser = argparse.ArgumentParser()
111 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
113 setup_server_io(io_db)
114 # print("DUMMY: Run game.")
115 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
116 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
117 opts, unknown = parser.parse_known_args()
118 if None != opts.replay:
121 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
122 " (if so late a turn is to be found).")
123 if not os.access(io_db["path_record"], os.F_OK):
124 raise SystemExit("No record file found to replay.")
126 if os.access(io_db["path_save"], os.F_OK):
127 obey_lines_in_file(io_db["path_save"], "save")
129 if not os.access(io_db["path_worldconf"], os.F_OK):
130 msg = "No world config file from which to start a new world."
131 raise SystemExit(msg)
132 obey_lines_in_file(io_db["path_worldconf"], "world config ")
133 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
134 # print("DUMMY: Run io_loop().")
135 except SystemExit as exit:
136 print("ABORTING: " + exit.args[0])
138 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
141 cleanup_server_io(io_db)
142 # print("DUMMY: (Clean up C heap.)")