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