home · contact · privacy
Server/py: Replace HandledException with SystemExit (erlehmann advice).
[plomrogue] / plomrogue-server.py
1 import argparse
2 import errno
3 import os
4 import time
5
6
7 def setup_server_io(io_db):
8     """Fill IO files DB with proper file( path)s. Write process IO test string.
9
10     Ensure IO files directory at server/. Remove any old in file if found. Set
11     up new in file (io_db["file_in"]) for reading at io_db["path_in"], and new
12     out file (io_db["file_out"]) for writing at io_db["path_out"]. Start out
13     file with process hash line of format PID + " " + floated UNIX time
14     (io_db["teststring"]). Set worldstate file path io_db["path_worldstate"].
15     """
16     io_dir = "server/"
17     io_db["path_in"] = io_dir + "in"
18     io_db["path_out"] = io_dir + "out"
19     io_db["path_worldstate"] = io_dir + "worldstate"
20     io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
21     os.makedirs(io_dir, exist_ok=True)
22     io_db["file_out"] = open(io_db["path_out"], "w")
23     io_db["file_out"].write(io_db["teststring"] + "\n")
24     if os.access(io_db["path_in"], os.F_OK):
25         os.remove(io_db["path_in"])
26     io_db["file_in"] = open(io_db["path_in"], "w")
27     io_db["file_in"].close()
28     io_db["file_in"] = open(io_db["path_in"], "r")
29
30
31 def cleanup_server_io(io_db):
32     """Close and remove all files open in IO files DB."""
33     def helper(file_key, path_key):
34         if file_key in io_db:
35             io_db[file_key].close()
36             os.remove(io_db[path_key])
37     helper("file_out", "path_out")
38     helper("file_in", "path_in")
39     helper("file_worldstate", "path_worldstate")
40
41
42 def detect_atomic_leftover(path):
43     """Raise explained HandledException if file is found at path + "_tmp"."""
44     path_tmp = path + "_tmp"
45     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
46           "aborted previous attempt to write '" + path + "'. Aborting until " \
47           "the matter is resolved by removing it from its current path."
48     if os.access(path_tmp, os.F_OK):
49         raise SystemExit(msg)
50
51
52 def obey(msg):
53     """"""
54     print("Input: " + msg)
55
56
57 def tokenize(string):
58     """Divide string by ' ', \t & " quotes (that also group). Escape with \."""
59     charlist_A = list(string)
60     i = 0
61     for c in charlist_A:
62         if "\\" == c and i < len(charlist_A) - 1:
63             charlist_A[i] = "remove"
64             charlist_A[i + 1] = charlist_A[i + 1] + "_escaped"
65         i = i + 1
66     charlist_B = []
67     for c in charlist_A:
68         if "remove" != c:
69             charlist_B.append(c)
70     in_quotes = 0
71     i = 0
72     for c in charlist_B:
73         if "\"" == c:
74             in_quotes = 0 if in_quotes else 1
75             if i < len(charlist_B) - 1:
76                 charlist_B[i] = "separator"
77         elif (not in_quotes) and (" " == c or "\t" == c):
78             charlist_B[i] = "separator"
79         i = i + 1
80     list_of_charlists = [[]]
81     i = 0
82     for c in charlist_B:
83         if "separator" == c:
84             if [] != list_of_charlists[-1]:
85                 list_of_charlists.append([])
86                 i = i + 1
87         else:
88             list_of_charlists[i].append(c[0])
89     tokens = []
90     for charlist in list_of_charlists:
91         tokens.append("".join(charlist))
92     return tokens
93
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     opts, unknown = parser.parse_known_args()
101     setup_server_io(io_db)
102     # print("DUMMY: Run game.")
103     path_recordfile = "recordfile"
104     path_savefile = "savefile"
105     detect_atomic_leftover(path_savefile)
106     detect_atomic_leftover(path_recordfile)
107     if None != opts.replay:
108         if opts.replay < 1:
109             opts.replay = 1
110         print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
111               " (if so late a turn is to be found).")
112         if not os.access(path_recordfile, os.F_OK):
113             raise SystemExit("No record file found to replay.")
114     elif os.access(path_savefile, os.F_OK):
115         print(open(path_savefile, "r").read())
116     else:
117         msg = "MAKE_WORLD " + str(int(time.time()))
118         obey(msg)
119 except SystemExit as exit:
120     print("ABORTING: " + exit.args[0])
121 except:
122     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
123     raise
124 finally:
125     cleanup_server_io(io_db)
126     # print("DUMMY: (Clean up C heap.)")