-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathserver.py
More file actions
180 lines (152 loc) · 4.47 KB
/
Copy pathserver.py
File metadata and controls
180 lines (152 loc) · 4.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
__author__ = "Kurt Schwehr"
__version__ = ["$Revision:", "4799", "$"][1]
__revision__ = __version__ # For pylint
__date__ = [
"$Date:",
"2006-09-25",
"11:09:02",
"-0400",
"(Mon,",
"25",
"Sep",
"2006)",
"$",
][1]
__copyright__ = "2008"
__license__ = "Apache 2.0"
__contact__ = "kurt at ccom.unh.edu"
__doc__ = """
Tools to support writing python server programs. Pulled from serial-logger.
@undocumented: __doc__
@since: 2008-Oct-16
@status: under development
@organization: U{CCOM<http://ccom.unh.edu/>}
"""
import contextlib
import datetime
import os
import time
SERIAL_SPEEDS = [
# 0, 50, 75, 110,
# 134, 150, 200,
300,
600,
1200,
1800,
2400,
4800,
9600,
19200,
38400,
57600,
115200,
230400,
]
def create_daemon():
"""nohup like function to detach from the terminal
if options.daemonMode:
create_daemon()
if options.pidFile != None:
open(options.pidFile, 'w').write(str(os.getpid())+'\n')
"""
try:
pid = os.fork()
except OSError as except_params:
raise Exception("%s [%d]" % (except_params.strerror, except_params.errno))
if pid == 0:
# The first child.
os.setsid()
try:
pid = os.fork() # Fork a second child.
except OSError as except_params:
raise Exception("%s [%d]" % (except_params.strerror, except_params.errno))
if pid != 0:
os._exit(0) # Exit parent (the first child) of the second child.
else:
os._exit(0) # Exit parent of the first child.
import resource # Resource usage information.
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY:
maxfd = 1024
# Iterate through and close all file descriptors.
if True:
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # ERROR, fd wasn't open to begin with (ignored)
pass
# Send all output to /dev/null - FIX: send it to a log file
os.open("/dev/null", os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2)
# Did I want to subclass file?
class LogFileWithRotate:
__slots__ = (
"current_date",
"log_file",
"log_filename",
"prefix",
"station",
"uscg_format",
"v",
)
def __init__(
self, prefix="log-", station="runknown", uscg_format=True, verbose=False
):
self.v = verbose
self.prefix = prefix
self.log_filename = None
self.log_file = None
self.station = station
self.uscg_format = uscg_format
self.open()
def open(self):
"""Open a log file. Close old one if it exists"""
if self.log_file is not None:
if self.v:
print("closing logfile")
self.write_tail()
self.log_file.close()
now = self.current_date = datetime.datetime.utcnow()
self.log_filename = self.prefix + now.strftime("%Y-%m-%d")
if self.v:
print(f"opening log file: {self.log_filename}")
self.log_file = open(self.log_filename, "a")
self.write_header()
def write_header(self):
self.write("# START LOGGING", rotate=False)
def write_tail(self):
self.write("# STOP LOGGING", rotate=False)
def needs_rotate(self):
"Check if the log needs to be rotated"
old = self.current_date
now = datetime.datetime.utcnow()
return old.strftime("%j") != now.strftime("%j")
def rotate(self, force=False):
if not force and not self.needs_rotate():
return
if self.v:
print("rotate log file")
self.open()
def write(self, data, verbose=False, rotate=True):
if rotate:
self.rotate()
log_str = ""
if self.uscg_format:
log_str = data
if data[-1] in ("\n", "\r"):
log_str = data[:-1]
log_str += f",{self.station},{time.time()}\n"
else:
log_str = data
if data != "\n":
log_str += "\n"
if verbose:
print(log_str, end=" ")
self.log_file.write(log_str)
def __del__(self):
if getattr(self, "log_file", None) is not None and not self.log_file.closed:
with contextlib.suppress(Exception):
self.write_tail()
with contextlib.suppress(Exception):
self.log_file.close()