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["tmp_suffix"] = "_tmp"
25 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
26 os.makedirs(io_dir, exist_ok=True)
27 io_db["file_out"] = open(io_db["path_out"], "w")
28 io_db["file_out"].write(io_db["teststring"] + "\n")
29 if os.access(io_db["path_in"], os.F_OK):
30 os.remove(io_db["path_in"])
31 io_db["file_in"] = open(io_db["path_in"], "w")
32 io_db["file_in"].close()
33 io_db["file_in"] = open(io_db["path_in"], "r")
36 def cleanup_server_io(io_db):
37 """Close and remove all files open in IO files DB."""
38 def helper(file_key, path_key):
40 io_db[file_key].close()
41 os.remove(io_db[path_key])
42 helper("file_out", "path_out")
43 helper("file_in", "path_in")
44 helper("file_worldstate", "path_worldstate")
47 def detect_atomic_leftover(path, tmp_suffix):
48 """Raise explained SystemExit if file is found at path + tmp_suffix."""
49 path_tmp = path + tmp_suffix
50 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
51 "aborted previous attempt to write '" + path + "'. Aborting until " \
52 "the matter is resolved by removing it from its current path."
53 if os.access(path_tmp, os.F_OK):
57 def obey(cmd, io_db, prefix):
59 print("input " + prefix + ": " + cmd)
61 tokens = shlex.split(cmd, comments=True)
62 except ValueError as err:
63 print("Can't tokenize command string: " + str(err) + ".")
67 elif "PING" == tokens[0] and 1 == len(tokens):
68 io_db["file_out"].write("PONG\n")
69 elif "QUIT" == tokens[0] and 1 == len(tokens):
70 record("# " + cmd, path_recordfile)
71 raise SystemExit("received QUIT command")
72 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
73 print("I would generate a new world now, if only I knew how.")
74 record(cmd, io_db["path_record"])
76 print("Invalid command/argument, or bad number of tokens.")
79 def record(cmd, path_recordfile):
80 """Append cmd string plus newline to file at path_recordfile."""
81 # Doesn't yet replace old record() fully.
82 file = open(path_recordfile, "a")
83 file.write(cmd + "\n")
87 def obey_lines_in_file(path, name):
88 """Call obey() on each line of path's file, use name in input prefix."""
89 file = open(io_db["path_worldconf"], "r")
91 for line in file.readlines():
92 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
99 parser = argparse.ArgumentParser()
100 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
102 setup_server_io(io_db)
103 # print("DUMMY: Run game.")
104 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
105 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
106 opts, unknown = parser.parse_known_args()
107 if None != opts.replay:
110 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
111 " (if so late a turn is to be found).")
112 if not os.access(io_db["path_record"], os.F_OK):
113 raise SystemExit("No record file found to replay.")
115 if os.access(io_db["path_save"], os.F_OK):
116 obey_lines_in_file(io_db["path_save"], "save")
118 if not os.access(io_db["path_worldconf"], os.F_OK):
119 msg = "No world config file from which to start a new world."
120 raise SystemExit(msg)
121 obey_lines_in_file(io_db["path_worldconf"], "world config ")
122 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
123 # print("DUMMY: Run io_loop().")
124 except SystemExit as exit:
125 print("ABORTING: " + exit.args[0])
127 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
130 cleanup_server_io(io_db)
131 # print("DUMMY: (Clean up C heap.)")