home · contact · privacy
Server/py: Move atomic leftovers detection into setup_server_io().
[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"]). Run detect_atomic_leftover
17     on io_db["path_record"] and io_db["path_save"].
18     """
19     io_dir = "server/"
20     io_db["path_in"] = io_dir + "in"
21     io_db["path_out"] = io_dir + "out"
22     io_db["path_worldstate"] = io_dir + "worldstate"
23     io_db["path_record"] = "record"
24     io_db["path_save"] = "save"
25     io_db["path_worldconf"] = "confserver/world"
26     io_db["tmp_suffix"] = "_tmp"
27     io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
28     os.makedirs(io_dir, exist_ok=True)
29     io_db["file_out"] = open(io_db["path_out"], "w")
30     io_db["file_out"].write(io_db["teststring"] + "\n")
31     if os.access(io_db["path_in"], os.F_OK):
32         os.remove(io_db["path_in"])
33     io_db["file_in"] = open(io_db["path_in"], "w")
34     io_db["file_in"].close()
35     io_db["file_in"] = open(io_db["path_in"], "r")
36     detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
37     detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
38
39
40 def cleanup_server_io(io_db):
41     """Close and remove all files open in IO files DB."""
42     def helper(file_key, path_key):
43         if file_key in io_db:
44             io_db[file_key].close()
45             os.remove(io_db[path_key])
46     helper("file_out", "path_out")
47     helper("file_in", "path_in")
48     helper("file_worldstate", "path_worldstate")
49
50
51 def detect_atomic_leftover(path, tmp_suffix):
52     """Raise explained SystemExit if file is found at path + tmp_suffix."""
53     path_tmp = path + tmp_suffix
54     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
55           "aborted previous attempt to write '" + path + "'. Aborting until " \
56           "the matter is resolved by removing it from its current path."
57     if os.access(path_tmp, os.F_OK):
58         raise SystemExit(msg)
59
60
61 def obey(cmd, io_db, prefix):
62     """"""
63     print("input " + prefix + ": " + cmd)
64     try:
65         tokens = shlex.split(cmd, comments=True)
66     except ValueError as err:
67         print("Can't tokenize command string: " + str(err) + ".")
68         return
69     if 0 == len(tokens):
70         pass
71     elif "PING" == tokens[0] and 1 == len(tokens):
72         io_db["file_out"].write("PONG\n")
73     elif "QUIT" == tokens[0] and 1 == len(tokens):
74         record("# " + cmd, path_recordfile)
75         raise SystemExit("received QUIT command")
76     elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
77         print("I would generate a new world now, if only I knew how.")
78         record(cmd, io_db)
79     else:
80         print("Invalid command/argument, or bad number of tokens.")
81
82
83 def record(cmd, io_db):
84     """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
85     # This misses some optimizations from the original record(), namely only
86     # finishing the atomic write with expensive flush() and fsync() every 15
87     # seconds unless explicitely forced. Implement as needed.
88     path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
89     if os.access(io_db["path_record"], os.F_OK):
90         shutil.copyfile(io_db["path_record"], path_tmp)
91     file = open(path_tmp, "a")
92     file.write(cmd + "\n")
93     file.flush()
94     os.fsync(file.fileno())
95     file.close()
96     if os.access(io_db["path_record"], os.F_OK):
97         os.remove(io_db["path_record"])
98     os.rename(path_tmp, io_db["path_record"])
99
100
101 def obey_lines_in_file(path, name, break_test = None):
102     """Call obey() on each line of path's file, use name in input prefix.
103
104     If break_test function is set, only read the file until it returns True.
105     """
106     file = open(path, "r")
107     line_n = 1
108     for line in file.readlines():
109         if None != break_test and break_test():
110             break
111         obey(line.rstrip(), io_db, name + "file line " + str(line_n))
112         line_n = line_n + 1
113     file.close()
114
115
116 def make_turn_tester(turn_to_compare, world_db):
117     """Return tester whether world_db["turn"] greater/equal turn_to_compare."""
118     def turn_tester():
119         return world_db["turn"] >= turn_to_compare
120     return turn_tester
121
122
123 io_db = {}
124 world_db = {}
125 try:
126     parser = argparse.ArgumentParser()
127     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
128                         action='store')
129     setup_server_io(io_db)
130     # print("DUMMY: Run game.")
131     opts, unknown = parser.parse_known_args()
132     if None != opts.replay:
133         if opts.replay < 1:
134             opts.replay = 1
135         print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
136               " (if so late a turn is to be found).")
137         if not os.access(io_db["path_record"], os.F_OK):
138             raise SystemExit("No record file found to replay.")
139         world_db["turn"] = 0
140         break_tester = make_turn_tester(opts.replay, world_db)
141         obey_lines_in_file(io_db["path_record"], "record ", break_tester)
142     else:
143         if os.access(io_db["path_save"], os.F_OK):
144             obey_lines_in_file(io_db["path_save"], "save")
145         else:
146             if not os.access(io_db["path_worldconf"], os.F_OK):
147                 msg = "No world config file from which to start a new world."
148                 raise SystemExit(msg)
149             obey_lines_in_file(io_db["path_worldconf"], "world config ")
150             obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
151         # print("DUMMY: Run io_loop().")
152 except SystemExit as exit:
153     print("ABORTING: " + exit.args[0])
154 except:
155     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
156     raise
157 finally:
158     cleanup_server_io(io_db)
159     # print("DUMMY: (Clean up C heap.)")