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