home · contact · privacy
Server/py: Flush PONG! message.
[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     Set io_db["kicked_by_rival"] to False. Decide file paths. Ensure IO files
13     directory at server/. Remove any old in file if found. Set up new in file
14     (io_db["file_in"]) for reading at io_db["path_in"], and new out file
15     (io_db["file_out"]) for writing at io_db["path_out"]. Start out file with
16     process hash line of format PID + " " + floated UNIX time
17     (io_db["teststring"]). Run detect_atomic_leftover on io_db["path_record"]
18     and io_db["path_save"].
19     """
20     io_dir = "server/"
21     io_db["kicked_by_rival"] = False
22     io_db["path_in"] = io_dir + "in"
23     io_db["path_out"] = io_dir + "out"
24     io_db["path_worldstate"] = io_dir + "worldstate"
25     io_db["path_record"] = "record"
26     io_db["path_save"] = "save"
27     io_db["path_worldconf"] = "confserver/world"
28     io_db["tmp_suffix"] = "_tmp"
29     io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
30     os.makedirs(io_dir, exist_ok=True)
31     io_db["file_out"] = open(io_db["path_out"], "w")
32     io_db["file_out"].write(io_db["teststring"] + "\n")
33     io_db["file_out"].flush()
34     if os.access(io_db["path_in"], os.F_OK):
35         os.remove(io_db["path_in"])
36     io_db["file_in"] = open(io_db["path_in"], "w")
37     io_db["file_in"].close()
38     io_db["file_in"] = open(io_db["path_in"], "r")
39     detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
40     detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
41
42
43 def cleanup_server_io(io_db):
44     """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
45     def helper(file_key, path_key):
46         if file_key in io_db:
47             io_db[file_key].close()
48             if not io_db["kicked_by_rival"] \
49                and os.access(io_db[path_key], os.F_OK):
50                 os.remove(io_db[path_key])
51     helper("file_out", "path_out")
52     helper("file_in", "path_in")
53     helper("file_worldstate", "path_worldstate")
54
55
56 def detect_atomic_leftover(path, tmp_suffix):
57     """Raise explained SystemExit if file is found at path + tmp_suffix."""
58     path_tmp = path + tmp_suffix
59     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
60           "aborted previous attempt to write '" + path + "'. Aborting until " \
61           "the matter is resolved by removing it from its current path."
62     if os.access(path_tmp, os.F_OK):
63         raise SystemExit(msg)
64
65
66 def obey(cmd, io_db, prefix, replay_file=None, do_record=False):
67     """"""
68     server_test(io_db)
69     print("input " + prefix + ": " + cmd)
70     try:
71         tokens = shlex.split(cmd, comments=True)
72     except ValueError as err:
73         print("Can't tokenize command string: " + str(err) + ".")
74         return
75     if 0 == len(tokens):
76         pass
77     elif "PING" == tokens[0] and 1 == len(tokens):
78         io_db["file_out"].write("PONG\n")
79         io_db["file_out"].flush()
80     elif "QUIT" == tokens[0] and 1 == len(tokens):
81         if do_record:
82             record("# " + cmd, io_db)
83         raise SystemExit("received QUIT command")
84     elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
85         if replay_file:
86             print("Due to replay mode, reading command as 'go on in record'.")
87             line = replay_file.readline()
88             if len(line) > 0:
89                 obey(line.rstrip(), io_db,
90                      replay_file.prefix + str(file.line_n))
91                 file.line_n = file.line_n + 1
92             else:
93                 print("Reached end of record file.")
94         else:
95             print("I would generate a new world now, if only I knew how.")
96             if do_record:
97                 record(cmd, io_db)
98     else:
99         print("Invalid command/argument, or bad number of tokens.")
100
101
102 def record(cmd, io_db):
103     """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
104     # This misses some optimizations from the original record(), namely only
105     # finishing the atomic write with expensive flush() and fsync() every 15
106     # seconds unless explicitely forced. Implement as needed.
107     path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
108     if os.access(io_db["path_record"], os.F_OK):
109         shutil.copyfile(io_db["path_record"], path_tmp)
110     file = open(path_tmp, "a")
111     file.write(cmd + "\n")
112     file.flush()
113     os.fsync(file.fileno())
114     file.close()
115     if os.access(io_db["path_record"], os.F_OK):
116         os.remove(io_db["path_record"])
117     os.rename(path_tmp, io_db["path_record"])
118
119
120 def obey_lines_in_file(path, name, do_record=False):
121     """Call obey() on each line of path's file, use name in input prefix."""
122     file = open(path, "r")
123     line_n = 1
124     for line in file.readlines():
125         obey(line.rstrip(), io_db, name + "file line " + str(line_n),
126              do_record=do_record)
127         line_n = line_n + 1
128     file.close()
129
130
131 def parse_command_line_arguments():
132     """Return settings values read from command line arguments."""
133     parser = argparse.ArgumentParser()
134     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
135                         action='store')
136     opts, unknown = parser.parse_known_args()
137     return opts
138
139
140 def server_test(io_db):
141     """Ensure valid server out file belonging to current process.
142
143     On failure, set io_db["kicked_by_rival"] and raise SystemExit.
144     """
145     if not os.access(io_db["path_out"], os.F_OK):
146         raise SystemExit("Server output file has disappeared.")
147     file = open(io_db["path_out"], "r")
148     test = file.readline().rstrip("\n")
149     file.close()
150     if test != io_db["teststring"]:
151         io_db["kicked_by_rival"] = True
152         msg = "Server test string in server output file does not match. This" \
153               " indicates that the current server process has been " \
154               "superseded by another one."
155         raise SystemExit(msg)
156
157
158 def read_command(io_db):
159     """Return next newline-delimited command from server in file.
160
161     Keep building return string until a newline is encountered. Pause between
162     unsuccessful reads, and after too much waiting, run server_test().
163     """
164     wait_on_fail = 1
165     max_wait = 5
166     now = time.time()
167     command = ""
168     while 1:
169         add = io_db["file_in"].readline()
170         if len(add) > 0:
171             command = command + add
172             if len(command) > 0 and "\n" == command[-1]:
173                 command = command[:-1]
174                 break
175         else:
176             time.sleep(wait_on_fail)
177             if now + max_wait < time.time():
178                 server_test(io_db)
179                 now = time.time()
180     return command
181
182
183 io_db = {}
184 world_db = {}
185 try:
186     opts = parse_command_line_arguments()
187     setup_server_io(io_db)
188     # print("DUMMY: Run game.")
189     if None != opts.replay:
190         if opts.replay < 1:
191             opts.replay = 1
192         print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
193               " (if so late a turn is to be found).")
194         if not os.access(io_db["path_record"], os.F_OK):
195             raise SystemExit("No record file found to replay.")
196         world_db["turn"] = 0
197         file = open(io_db["path_record"], "r")
198         file.prefix = "recod file line "
199         file.line_n = 1
200         while world_db["turn"] < opts.replay:
201             obey(file.readline().rstrip(), io_db,
202                  file.prefix + str(file.line_n))
203             file.line_n = file.line_n + 1
204         try:
205             while 1:
206                 obey(read_command(io_db), io_db, "in file", replay_file=file)
207         except SystemExit:
208             file.close()
209             raise
210     else:
211         if os.access(io_db["path_save"], os.F_OK):
212             obey_lines_in_file(io_db["path_save"], "save")
213         else:
214             if not os.access(io_db["path_worldconf"], os.F_OK):
215                 msg = "No world config file from which to start a new world."
216                 raise SystemExit(msg)
217             obey_lines_in_file(io_db["path_worldconf"], "world config ",
218                                do_record=True)
219             obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file",
220                  do_record=True)
221         while 1:
222             obey(read_command(io_db), io_db, "in file", do_record=True)
223 except SystemExit as exit:
224     print("ABORTING: " + exit.args[0])
225 except:
226     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
227     raise
228 finally:
229     cleanup_server_io(io_db)
230     # print("DUMMY: (Clean up C heap.)")