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