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 file = open(path_recordfile, "a")
81 file.write(cmd + "\n")
87 parser = argparse.ArgumentParser()
88 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
90 setup_server_io(io_db)
91 # print("DUMMY: Run game.")
92 detect_atomic_leftover(io_db["path_save"])
93 detect_atomic_leftover(io_db["path_record"])
94 opts, unknown = parser.parse_known_args()
95 if None != opts.replay:
98 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
99 " (if so late a turn is to be found).")
100 if not os.access(io_db["path_record"], os.F_OK):
101 raise SystemExit("No record file found to replay.")
102 elif os.access(io_db["path_save"], os.F_OK):
103 print(open(io_db["path_save"], "r").read())
105 if not os.access(io_db["path_worldconf"], os.F_OK):
106 msg = "No world config file from which to start a new world."
107 raise SystemExit(msg)
108 file = open(io_db["path_worldconf"])
110 for line in file.readlines():
111 obey(line.rstrip(), io_db, "worldconfig file line " + str(line_n))
114 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
115 except SystemExit as exit:
116 print("ABORTING: " + exit.args[0])
118 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
121 cleanup_server_io(io_db)
122 # print("DUMMY: (Clean up C heap.)")