8 def setup_server_io(io_db):
9 """Fill IO files DB with proper file( path)s. Write process IO test string.
11 Ensure IO files directory at server/. Remove any old in file if found. Set
12 up new in file (io_db["file_in"]) for reading at io_db["path_in"], and new
13 out file (io_db["file_out"]) for writing at io_db["path_out"]. Start out
14 file with process hash line of format PID + " " + floated UNIX time
15 (io_db["teststring"]). Set worldstate file path io_db["path_worldstate"].
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["teststring"] = str(os.getpid()) + " " + str(time.time())
22 os.makedirs(io_dir, exist_ok=True)
23 io_db["file_out"] = open(io_db["path_out"], "w")
24 io_db["file_out"].write(io_db["teststring"] + "\n")
25 if os.access(io_db["path_in"], os.F_OK):
26 os.remove(io_db["path_in"])
27 io_db["file_in"] = open(io_db["path_in"], "w")
28 io_db["file_in"].close()
29 io_db["file_in"] = open(io_db["path_in"], "r")
32 def cleanup_server_io(io_db):
33 """Close and remove all files open in IO files DB."""
34 def helper(file_key, path_key):
36 io_db[file_key].close()
37 os.remove(io_db[path_key])
38 helper("file_out", "path_out")
39 helper("file_in", "path_in")
40 helper("file_worldstate", "path_worldstate")
43 def detect_atomic_leftover(path):
44 """Raise explained SystemExit if file is found at path + "_tmp"."""
45 path_tmp = path + "_tmp"
46 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
47 "aborted previous attempt to write '" + path + "'. Aborting until " \
48 "the matter is resolved by removing it from its current path."
49 if os.access(path_tmp, os.F_OK):
53 def obey(cmd, io_db, path_recordfile):
55 print("Input: " + cmd)
57 tokens = shlex.split(cmd, comments=True)
58 except ValueError as err:
59 print("Can't tokenize command string: " + str(err) + ".")
63 elif "PING" == tokens[0] and 1 == len(tokens):
64 io_db["file_out"].write("PONG\n")
65 elif "QUIT" == tokens[0] and 1 == len(tokens):
66 record("# " + cmd, path_recordfile)
67 raise SystemExit("received QUIT command")
68 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
69 print("I would generate a new world now, if only I knew how.")
70 record(cmd, path_recordfile)
72 print("Invalid command/argument, or bad number of tokens.")
75 def record(cmd, path_recordfile):
76 """Append cmd string plus newline to file at path_recordfile."""
77 file = open(path_recordfile, "a")
78 file.write(cmd + "\n")
85 parser = argparse.ArgumentParser()
86 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
88 opts, unknown = parser.parse_known_args()
89 setup_server_io(io_db)
90 # print("DUMMY: Run game.")
91 path_recordfile = "recordfile"
92 path_savefile = "savefile"
93 detect_atomic_leftover(path_savefile)
94 detect_atomic_leftover(path_recordfile)
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(path_recordfile, os.F_OK):
101 raise SystemExit("No record file found to replay.")
102 elif os.access(path_savefile, os.F_OK):
103 print(open(path_savefile, "r").read())
105 path_worldconfig = "confserver/world"
106 if not os.access(path_worldconfig, os.F_OK):
107 msg = "No world config file from which to start a new world."
108 raise SystemExit(msg)
109 file = open(path_worldconfig)
110 for line in file.readlines():
111 obey(line.rstrip(), io_db, path_recordfile)
113 obey("MAKE_WORLD " + str(int(time.time())), io_db, path_recordfile)
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.)")