home · contact · privacy
Server/py: Add command line help, handle pre-server-io-setup exits.
[plomrogue] / plomrogue-server.py
1 import argparse
2 import errno
3 import os
4 import time
5
6
7 class HandledException(Exception):
8     """Feature-less Exception child. Use for expected operational errors."""
9
10     pass
11
12
13 def setup_server_io(io_db):
14     """Fill IO files DB with proper file( path)s. Write process IO test string.
15
16     Ensure IO files directory at server/. Remove any old in file if found. Set
17     up new in file (io_db["file_in"]) for reading at io_db["path_in"], and new
18     out file (io_db["file_out"]) for writing at io_db["path_out"]. Start out
19     file with process hash line of format PID + " " + floated UNIX time
20     (io_db["teststring"]). Set worldstate file path io_db["path_worldstate"].
21     """
22     io_dir = "server/"
23     io_db["path_in"] = io_dir + "in"
24     io_db["path_out"] = io_dir + "out"
25     io_db["path_worldstate"] = io_dir + "worldstate"
26     io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
27     os.makedirs(io_dir, exist_ok=True)
28     io_db["file_out"] = open(io_db["path_out"], "w")
29     io_db["file_out"].write(io_db["teststring"] + "\n")
30     if os.access(io_db["path_in"], os.F_OK):
31         os.remove(io_db["path_in"])
32     io_db["file_in"] = open(io_db["path_in"], "w")
33     io_db["file_in"].close()
34     io_db["file_in"] = open(io_db["path_in"], "r")
35
36
37 def cleanup_server_io(io_db):
38     """Close and remove all files open in IO files DB."""
39     if "file_out" in io_db:
40         io_db["file_out"].close()
41         os.remove(io_db["path_out"])
42     if "file_in" in io_db:
43         io_db["file_in"].close()
44         os.remove(io_db["path_in"])
45     if "file_worldstate" in io_db:
46         io_db["file_worldstate"].close()
47         os.remove(io_db["path_worldstate"])
48
49
50 def detect_atomic_leftover(path):
51     """Raise explained HandledException if file is found at path + "_tmp"."""
52     path_tmp = path + "_tmp"
53     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
54           "aborted previous attempt to write '" + path + "'. Aborting until " \
55           "the matter is resolved by removing it from its current path."
56     if os.access(path_tmp, os.F_OK):
57         raise HandledException(msg)
58
59
60 io_db = {}
61 try:
62     parser = argparse.ArgumentParser()
63     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
64                         action='store')
65     args, unknown = parser.parse_known_args()
66     print("Replay: " + str(args.replay))
67     # print("DUMMY: Obey command-line arguments.")
68     # print("DUMMY: Open files.")
69     setup_server_io(io_db)
70     # print("DUMMY: Run game.")
71     path_recordfile = "recordfile"
72     path_savefile = "savefile"
73     detect_atomic_leftover(path_savefile)
74     detect_atomic_leftover(path_recordfile)
75     if os.access(path_savefile, os.F_OK):
76         print(open(path_savefile, "r").read())
77     else:
78         msg = "MAKE_WORLD " + str(int(time.time()))
79         print(msg)
80 except SystemExit:
81     pass
82 except HandledException as exception:
83     print("Error:")
84     print(exception.args[0])
85 except:
86     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
87     raise
88 finally:
89     cleanup_server_io(io_db)
90     # print("DUMMY: (Clean up C heap.)")