8 def setup_server_io(io_db):
9 """Fill IO files DB with proper file( path)s. Write process IO test string.
11 Decide file paths. Ensure IO files directory at server/. Remove any old in
12 file if found. Set up new in file (io_db["file_in"]) for reading at
13 io_db["path_in"], and new out file (io_db["file_out"]) for writing at
14 io_db["path_out"]. Start out file with process hash line of format PID +
15 " " + floated UNIX time (io_db["teststring"]).
18 io_db["path_in"] = io_dir + "in"
19 io_db["path_out"] = io_dir + "out"
20 io_db["path_worldstate"] = io_dir + "worldstate"
21 io_db["path_record"] = "record"
22 io_db["path_save"] = "save"
23 io_db["path_worldconf"] = "confserver/world"
24 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
25 os.makedirs(io_dir, exist_ok=True)
26 io_db["file_out"] = open(io_db["path_out"], "w")
27 io_db["file_out"].write(io_db["teststring"] + "\n")
28 if os.access(io_db["path_in"], os.F_OK):
29 os.remove(io_db["path_in"])
30 io_db["file_in"] = open(io_db["path_in"], "w")
31 io_db["file_in"].close()
32 io_db["file_in"] = open(io_db["path_in"], "r")
35 def cleanup_server_io(io_db):
36 """Close and remove all files open in IO files DB."""
37 def helper(file_key, path_key):
39 io_db[file_key].close()
40 os.remove(io_db[path_key])
41 helper("file_out", "path_out")
42 helper("file_in", "path_in")
43 helper("file_worldstate", "path_worldstate")
46 def detect_atomic_leftover(path):
47 """Raise explained SystemExit if file is found at path + "_tmp"."""
48 path_tmp = path + "_tmp"
49 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
50 "aborted previous attempt to write '" + path + "'. Aborting until " \
51 "the matter is resolved by removing it from its current path."
52 if os.access(path_tmp, os.F_OK):
56 def obey(cmd, io_db, prefix):
58 print("input " + prefix + ": " + cmd)
60 tokens = shlex.split(cmd, comments=True)
61 except ValueError as err:
62 print("Can't tokenize command string: " + str(err) + ".")
66 elif "PING" == tokens[0] and 1 == len(tokens):
67 io_db["file_out"].write("PONG\n")
68 elif "QUIT" == tokens[0] and 1 == len(tokens):
69 record("# " + cmd, path_recordfile)
70 raise SystemExit("received QUIT command")
71 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
72 print("I would generate a new world now, if only I knew how.")
73 record(cmd, io_db["path_record"])
75 print("Invalid command/argument, or bad number of tokens.")
78 def record(cmd, path_recordfile):
79 """Append cmd string plus newline to file at path_recordfile."""
80 # Doesn't yet replace old record() fully.
81 file = open(path_recordfile, "a")
82 file.write(cmd + "\n")
86 def obey_lines_in_file(path, name):
87 """Call obey() on each line of path's file, use name in input prefix."""
88 file = open(io_db["path_worldconf"], "r")
90 for line in file.readlines():
91 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
97 parser = argparse.ArgumentParser()
98 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
100 setup_server_io(io_db)
101 # print("DUMMY: Run game.")
102 detect_atomic_leftover(io_db["path_save"])
103 detect_atomic_leftover(io_db["path_record"])
104 opts, unknown = parser.parse_known_args()
105 if None != opts.replay:
108 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
109 " (if so late a turn is to be found).")
110 if not os.access(io_db["path_record"], os.F_OK):
111 raise SystemExit("No record file found to replay.")
113 if os.access(io_db["path_save"], os.F_OK):
114 obey_lines_in_file(io_db["path_save"], "save")
116 if not os.access(io_db["path_worldconf"], os.F_OK):
117 msg = "No world config file from which to start a new world."
118 raise SystemExit(msg)
119 obey_lines_in_file(io_db["path_worldconf"], "world config ")
120 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
121 # print("DUMMY: Run io_loop().")
122 except SystemExit as exit:
123 print("ABORTING: " + exit.args[0])
125 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
128 cleanup_server_io(io_db)
129 # print("DUMMY: (Clean up C heap.)")