home · contact · privacy
Server/py: Replace tokenizer() with shlex.split() (erlehmann advice).
[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     Ensure IO files directory at server/. Remove any old in file if found. Set
12     up new in file (io_db["file_in"]) for reading at io_db["path_in"], and new
13     out file (io_db["file_out"]) for writing at io_db["path_out"]. Start out
14     file with process hash line of format PID + " " + floated UNIX time
15     (io_db["teststring"]). Set worldstate file path io_db["path_worldstate"].
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["teststring"] = str(os.getpid()) + " " + str(time.time())
22     os.makedirs(io_dir, exist_ok=True)
23     io_db["file_out"] = open(io_db["path_out"], "w")
24     io_db["file_out"].write(io_db["teststring"] + "\n")
25     if os.access(io_db["path_in"], os.F_OK):
26         os.remove(io_db["path_in"])
27     io_db["file_in"] = open(io_db["path_in"], "w")
28     io_db["file_in"].close()
29     io_db["file_in"] = open(io_db["path_in"], "r")
30
31
32 def cleanup_server_io(io_db):
33     """Close and remove all files open in IO files DB."""
34     def helper(file_key, path_key):
35         if file_key in io_db:
36             io_db[file_key].close()
37             os.remove(io_db[path_key])
38     helper("file_out", "path_out")
39     helper("file_in", "path_in")
40     helper("file_worldstate", "path_worldstate")
41
42
43 def detect_atomic_leftover(path):
44     """Raise explained HandledException if file is found at path + "_tmp"."""
45     path_tmp = path + "_tmp"
46     msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
47           "aborted previous attempt to write '" + path + "'. Aborting until " \
48           "the matter is resolved by removing it from its current path."
49     if os.access(path_tmp, os.F_OK):
50         raise SystemExit(msg)
51
52
53 def obey(msg):
54     """"""
55     print("Input: " + msg)
56     print(shlex.split(msg))
57
58
59 io_db = {}
60 try:
61     parser = argparse.ArgumentParser()
62     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
63                         action='store')
64     opts, unknown = parser.parse_known_args()
65     setup_server_io(io_db)
66     # print("DUMMY: Run game.")
67     path_recordfile = "recordfile"
68     path_savefile = "savefile"
69     detect_atomic_leftover(path_savefile)
70     detect_atomic_leftover(path_recordfile)
71     if None != opts.replay:
72         if opts.replay < 1:
73             opts.replay = 1
74         print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
75               " (if so late a turn is to be found).")
76         if not os.access(path_recordfile, os.F_OK):
77             raise SystemExit("No record file found to replay.")
78     elif os.access(path_savefile, os.F_OK):
79         print(open(path_savefile, "r").read())
80     else:
81         msg = "MAKE_WORLD " + str(int(time.time()))
82         obey(msg)
83 except SystemExit as exit:
84     print("ABORTING: " + exit.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.)")