home · contact · privacy
Server/py: Some refactoring.
[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     io_db["file_out"].flush()
32     if os.access(io_db["path_in"], os.F_OK):
33         os.remove(io_db["path_in"])
34     io_db["file_in"] = open(io_db["path_in"], "w")
35     io_db["file_in"].close()
36     io_db["file_in"] = open(io_db["path_in"], "r")
37     detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
38     detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
39
40
41 def cleanup_server_io(io_db):
42     """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
43     def helper(file_key, path_key):
44         if file_key in io_db:
45             io_db[file_key].close()
46             if not io_db["kicked_by_rival"]:
47                 os.remove(io_db[path_key])
48     helper("file_out", "path_out")
49     helper("file_in", "path_in")
50     helper("file_worldstate", "path_worldstate")
51
52
53 def detect_atomic_leftover(path, tmp_suffix):
54     """Raise explained SystemExit if file is found at path + tmp_suffix."""
55     path_tmp = path + tmp_suffix
56     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
57           "aborted previous attempt to write '" + path + "'. Aborting until " \
58           "the matter is resolved by removing it from its current path."
59     if os.access(path_tmp, os.F_OK):
60         raise SystemExit(msg)
61
62
63 def obey(cmd, io_db, prefix):
64     """"""
65     print("input " + prefix + ": " + cmd)
66     try:
67         tokens = shlex.split(cmd, comments=True)
68     except ValueError as err:
69         print("Can't tokenize command string: " + str(err) + ".")
70         return
71     if 0 == len(tokens):
72         pass
73     elif "PING" == tokens[0] and 1 == len(tokens):
74         io_db["file_out"].write("PONG\n")
75     elif "QUIT" == tokens[0] and 1 == len(tokens):
76         record("# " + cmd, path_recordfile)
77         raise SystemExit("received QUIT command")
78     elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
79         print("I would generate a new world now, if only I knew how.")
80         record(cmd, io_db)
81     else:
82         print("Invalid command/argument, or bad number of tokens.")
83
84
85 def record(cmd, io_db):
86     """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
87     # This misses some optimizations from the original record(), namely only
88     # finishing the atomic write with expensive flush() and fsync() every 15
89     # seconds unless explicitely forced. Implement as needed.
90     path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
91     if os.access(io_db["path_record"], os.F_OK):
92         shutil.copyfile(io_db["path_record"], path_tmp)
93     file = open(path_tmp, "a")
94     file.write(cmd + "\n")
95     file.flush()
96     os.fsync(file.fileno())
97     file.close()
98     if os.access(io_db["path_record"], os.F_OK):
99         os.remove(io_db["path_record"])
100     os.rename(path_tmp, io_db["path_record"])
101
102
103 def obey_lines_in_file(path, name):
104     """Call obey() on each line of path's file, use name in input prefix."""
105     file = open(path, "r")
106     line_n = 1
107     for line in file.readlines():
108         obey(line.rstrip(), io_db, name + "file line " + str(line_n))
109         line_n = line_n + 1
110     file.close()
111
112
113 def parse_command_line_arguments():
114     """Return settings values read from command line arguments."""
115     parser = argparse.ArgumentParser()
116     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
117                         action='store')
118     opts, unknown = parser.parse_known_args()
119     return opts
120
121
122 def server_test(io_db):
123     """Ensure valid server out file belonging to current process.
124
125     On failure, set io_db["kicked_by_rival"] and raise SystemExit.
126     """
127     if not os.access(io_db["path_out"], os.F_OK):
128         raise SystemExit("Server output file has disappeared.")
129     file = open(io_db["path_out"], "r")
130     test = file.readline().rstrip("\n")
131     file.close()
132     if test != io_db["teststring"]:
133         io_db["kicked_by_rival"] = True
134         msg = "Server test string in server output file does not match. This" \
135               " indicates that the current server process has been " \
136               "superseded by another one."
137         raise SystemExit(msg)
138
139
140 io_db = {}
141 world_db = {}
142 try:
143     opts = parse_command_line_arguments()
144     setup_server_io(io_db)
145     # print("DUMMY: Run game.")
146     if None != opts.replay:
147         if opts.replay < 1:
148             opts.replay = 1
149         print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
150               " (if so late a turn is to be found).")
151         if not os.access(io_db["path_record"], os.F_OK):
152             raise SystemExit("No record file found to replay.")
153         world_db["turn"] = 0
154         file = open(io_db["path_record"], "r")
155         line_n = 1
156         for line in file.readlines():
157             if world_db["turn"] >= opts.replay:
158                 break
159             obey(line.rstrip(), io_db, "record file line " + str(line_n))
160             line_n = line_n + 1
161         while 1:
162             server_test(io_db)
163         # what to do next?
164         file.close()
165     else:
166         if os.access(io_db["path_save"], os.F_OK):
167             obey_lines_in_file(io_db["path_save"], "save")
168         else:
169             if not os.access(io_db["path_worldconf"], os.F_OK):
170                 msg = "No world config file from which to start a new world."
171                 raise SystemExit(msg)
172             obey_lines_in_file(io_db["path_worldconf"], "world config ")
173             obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
174         while 1:
175             server_test(io_db)
176         # print("DUMMY: Run io_loop().")
177 except SystemExit as exit:
178     print("ABORTING: " + exit.args[0])
179 except:
180     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
181     raise
182 finally:
183     cleanup_server_io(io_db)
184     # print("DUMMY: (Clean up C heap.)")