Debian Codegraph @

scripts/ppserver

raw
1 #!/usr/bin/env python
2 # Parallel Python Software: http://www.parallelpython.com
3 # Copyright (c) 2005-2012 Vitalii Vanovschi.
4 # Copyright (c) 2015-2016 California Institute of Technology.
5 # Copyright (c) 2016-2026 The Uncertainty Quantification Foundation.
6 # All rights reserved.
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 # * Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 # * Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 # * Neither the name of the author nor the names of its contributors
15 # may be used to endorse or promote products derived from this software
16 # without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28 # THE POSSIBILITY OF SUCH DAMAGE.
29 """
30 ppft server: the parallel python network server
31 """
32 import atexit
33 import logging
34 import errno
35 import getopt
36 import sys
37 import socket
38 import threading
39 import random
40 import string
41 import signal
42 import time
43 import os
44
45 import ppft as pp
46 import ppft.auto as ppauto
47 import ppft.common as ppc
48 import ppft.transport as pptransport
49
50 copyright = ppc.copyright
51 __version__ = version = ppc.__version__
52
53 LISTEN_SOCKET_TIMEOUT = 20
54
55 # compatibility with Jython
56 STAT_SIGNAL = 'SIGUSR1' if 'java' not in sys.platform else 'SIGUSR2'
57
58 import hashlib
59 sha_new = hashlib.sha1
60
61
62 class _NetworkServer(pp.Server):
63 """Network Server Class
64 """
65
66 def __init__(self, ncpus="autodetect", interface="0.0.0.0",
67 broadcast="255.255.255.255", port=None, secret=None,
68 timeout=None, restart=False, proto=2, socket_timeout=3600, pid_file=None):
69 pp.Server.__init__(self, ncpus, (), secret, restart,
70 proto, socket_timeout)
71 if pid_file:
72 with open(pid_file, 'w') as pfile:
73 print(os.getpid(), file=pfile)
74 atexit.register(os.remove, pid_file)
75 self.host = interface
76 self.bcast = broadcast
77 if port is not None:
78 self.port = port
79 else:
80 self.port = ppc.randomport()
81 self.timeout = timeout
82 self.ncon = 0
83 self.last_con_time = time.time()
84 self.ncon_lock = threading.Lock()
85
86 self.logger.debug("Starting network server interface=%s port=%i"
87 % (self.host, self.port))
88 if self.timeout is not None:
89 self.logger.debug("ppserver will exit in %i seconds if no "\
90 "connections with clients exist" % (self.timeout))
91 ppc.start_thread("timeout_check", self.check_timeout)
92
93 def ncon_add(self, val):
94 """Keeps track of the number of connections and time of the last one"""
95 self.ncon_lock.acquire()
96 self.ncon += val
97 self.last_con_time = time.time()
98 self.ncon_lock.release()
99
100 def check_timeout(self):
101 """Checks if timeout happened and shutdowns server if it did"""
102 while True:
103 if self.ncon == 0:
104 idle_time = time.time() - self.last_con_time
105 if idle_time < self.timeout:
106 time.sleep(self.timeout - idle_time)
107 else:
108 self.logger.debug("exiting ppserver due to timeout (no client"\
109 " connections in last %i sec)", self.timeout)
110 os._exit(0)
111 else:
112 time.sleep(self.timeout)
113
114 def listen(self):
115 """Initiates listenting to incoming connections"""
116 try:
117 self.ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
118 # following allows ppserver to restart faster on the same port
119 self.ssocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
120 self.ssocket.settimeout(LISTEN_SOCKET_TIMEOUT)
121 self.ssocket.bind((self.host, self.port))
122 self.ssocket.listen(5)
123 except socket.error:
124 e = sys.exc_info()[1]
125 self.logger.error("Cannot create socket for %s:%s, %s", self.host, self.port, e)
126
127 try:
128 while 1:
129 csocket = None
130 # accept connections from outside
131 try:
132 (csocket, address) = self.ssocket.accept()
133 except socket.timeout:
134 pass
135 # don't exit on an interupt due to a signal
136 except socket.error:
137 e = sys.exc_info()[1]
138 if e.errno == errno.EINTR:
139 pass
140 if self._exiting:
141 return
142 # now do something with the clientsocket
143 # in this case, we'll pretend this is a threaded server
144 if csocket:
145 ppc.start_thread("client_socket", self.crun, (csocket, ))
146 except KeyboardInterrupt:
147 pass
148 except:
149 self.logger.debug("Exception in listen method (possibly expected)", exc_info=True)
150 finally:
151 self.logger.debug("Closing server socket")
152 self.ssocket.close()
153
154 def crun(self, csocket):
155 """Authenticates client and handles its jobs"""
156 mysocket = pptransport.CSocketTransport(csocket, self.socket_timeout)
157 #send PP version
158 mysocket.send(version)
159 #generate a random string
160 srandom = "".join([random.choice(string.ascii_letters)
161 for i in range(16)])
162 mysocket.send(srandom)
163 answer = sha_new(ppc.b_(srandom+self.secret)).hexdigest()
164 clientanswer = ppc.str_(mysocket.receive())
165 if answer != clientanswer:
166 self.logger.warning("Authentication failed, client host=%s, port=%i"
167 % csocket.getpeername())
168 mysocket.send("FAILED")
169 csocket.close()
170 return
171 else:
172 mysocket.send("OK")
173
174 ctype = ppc.str_(mysocket.receive())
175 self.logger.debug("Control message received: " + ctype)
176 self.ncon_add(1)
177 try:
178 if ctype == "STAT":
179 #reset time at each new connection
180 self.get_stats()["local"].time = 0.0
181 #open('/tmp/pp.debug', 'a+').write('STAT: \n')
182 mysocket.send(str(self.get_ncpus()))
183 #open('/tmp/pp.debug', 'a+').write('STAT: get_ncpus\n')
184 while 1:
185 mysocket.receive()
186 #open('/tmp/pp.debug', 'a+').write('STAT: recvd\n')
187 mysocket.send(str(self.get_stats()["local"].time))
188 #open('/tmp/pp.debug', 'a+').write('STAT: _\n')
189 elif ctype=="EXEC":
190 while 1:
191 #open('/tmp/pp.debug', 'a+').write('EXEC: \n')
192 sfunc = mysocket.creceive()
193 #open('/tmp/pp.debug', 'a+').write('EXEC: '+repr((sfunc,))+'\n')
194 sargs = mysocket.receive()
195 #open('/tmp/pp.debug', 'a+').write('EXEC: '+repr((sargs,))+'\n')
196 fun = self.insert(sfunc, sargs)
197 sresult = fun(True)
198 #open('/tmp/pp.debug', 'a+').write('EXEC: '+repr((sresult,))+'\n')
199 mysocket.send(sresult)
200 #open('/tmp/pp.debug', 'a+').write('EXEC: _\n')
201 except:
202 if self._exiting:
203 return
204 if pp.SHOW_EXPECTED_EXCEPTIONS:
205 self.logger.debug("Exception in crun method (possibly expected)", exc_info=True)
206 self.logger.debug("Closing client socket")
207 csocket.close()
208 self.ncon_add(-1)
209
210 def broadcast(self):
211 """Initiaates auto-discovery mechanism"""
212 discover = ppauto.Discover(self)
213 ppc.start_thread("server_broadcast", discover.run,
214 ((self.host, self.port), (self.bcast, self.port)))
215
216
217 def parse_config(file_loc):
218 """
219 Parses a config file in a very forgiving way.
220 """
221 # If we don't have configobj installed then let the user know and exit
222 try:
223 from configobj import ConfigObj
224 except ImportError:
225 ie = sys.exc_info()[1]
226 #sysstderr = getattr(sys.stderr, 'buffer', sys.stderr)
227 print(("ERROR: You must have config obj installed to use"
228 "configuration files. You can still use command line switches."), file=sys.stderr)
229 sys.exit(1)
230
231 if not os.access(file_loc, os.F_OK):
232 print("ERROR: Can not access %s." % arg, file=sys.stderr)
233 sys.exit(1)
234
235 args = {}
236 autodiscovery = False
237 debug = False
238
239 # Load the configuration file
240 config = ConfigObj(file_loc)
241 # try each config item and use the result if it exists. If it doesn't
242 # then simply pass and move along
243 try:
244 args['secret'] = config['general'].get('secret')
245 except:
246 pass
247
248 try:
249 autodiscovery = config['network'].as_bool('autodiscovery')
250 except:
251 pass
252
253 try:
254 args['interface'] = config['network'].get('interface',
255 default="0.0.0.0")
256 except:
257 pass
258
259 try:
260 args['broadcast'] = config['network'].get('broadcast')
261 except:
262 pass
263
264 try:
265 args['port'] = config['network'].as_int('port')
266 except:
267 pass
268
269 try:
270 debug = config['general'].as_bool('debug')
271 except:
272 pass
273
274 try:
275 args['ncpus'] = config['general'].as_int('workers')
276 except:
277 pass
278
279 try:
280 args['proto'] = config['general'].as_int('proto')
281 except:
282 pass
283
284 try:
285 args['restart'] = config['general'].as_bool('restart')
286 except:
287 pass
288
289 try:
290 args['timeout'] = config['network'].as_int('timeout')
291 except:
292 pass
293
294 try:
295 args['socket_timeout'] = config['network'].as_int('socket_timeout')
296 except:
297 pass
298
299 try:
300 args['pid_file'] = config['general'].get('pid_file')
301 except:
302 pass
303 # Return a tuple of the args dict and autodiscovery variable
304 return args, autodiscovery, debug
305
306
307 def print_usage():
308 """Prints help"""
309 print("Parallel Python Network Server (pp-" + version + ")")
310 print("Usage: ppserver [-hdar] [-f format] [-n proto]"\
311 " [-c config_path] [-i interface] [-b broadcast]"\
312 " [-p port] [-w nworkers] [-s secret] [-t seconds]"\
313 " [-k seconds] [-P pid_file]")
314 print("")
315 print("Options: ")
316 print("-h : this help message")
317 print("-d : set log level to debug")
318 print("-f format : log format")
319 print("-a : enable auto-discovery service")
320 print("-r : restart worker process after each"\
321 " task completion")
322 print("-n proto : protocol number for pickle module")
323 print("-c path : path to config file")
324 print("-i interface : interface to listen")
325 print("-b broadcast : broadcast address for auto-discovery service")
326 print("-p port : port to listen")
327 print("-w nworkers : number of workers to start")
328 print("-s secret : secret for authentication")
329 print("-t seconds : timeout to exit if no connections with "\
330 "clients exist")
331 print("-k seconds : socket timeout in seconds")
332 print("-P pid_file : file to write PID to")
333 print("")
334 print("To print server stats send %s to its main process (unix only). " % STAT_SIGNAL)
335 print("")
336 print("Due to the security concerns always use a non-trivial secret key.")
337 print("Secret key set by -s switch will override secret key assigned by")
338 print("pp_secret variable in .pythonrc.py")
339 print("")
340 print("Please visit http://www.parallelpython.com for extended up-to-date")
341 print("documentation, examples and support forums")
342
343
344 def create_network_server(argv):
345 try:
346 opts, args = getopt.getopt(argv, "hdarn:c:b:i:p:w:s:t:f:k:P:", ["help"])
347 except getopt.GetoptError:
348 print_usage()
349 raise
350
351 args = {}
352 autodiscovery = False
353 debug = False
354
355 log_level = logging.WARNING
356 log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
357
358 for opt, arg in opts:
359 if opt in ("-h", "--help"):
360 print_usage()
361 sys.exit()
362 elif opt == "-c":
363 args, autodiscovery, debug = parse_config(arg)
364 elif opt == "-d":
365 debug = True
366 elif opt == "-f":
367 log_format = arg
368 elif opt == "-i":
369 args["interface"] = arg
370 elif opt == "-s":
371 args["secret"] = arg
372 elif opt == "-p":
373 args["port"] = int(arg)
374 elif opt == "-w":
375 args["ncpus"] = int(arg)
376 elif opt == "-a":
377 autodiscovery = True
378 elif opt == "-r":
379 args["restart"] = True
380 elif opt == "-b":
381 args["broadcast"] = arg
382 elif opt == "-n":
383 args["proto"] = int(arg)
384 elif opt == "-t":
385 args["timeout"] = int(arg)
386 elif opt == "-k":
387 args["socket_timeout"] = int(arg)
388 elif opt == "-P":
389 args["pid_file"] = arg
390
391 if debug:
392 log_level = logging.DEBUG
393 pp.SHOW_EXPECTED_EXCEPTIONS = True
394
395 log_handler = logging.StreamHandler()
396 log_handler.setFormatter(logging.Formatter(log_format))
397 logging.getLogger("pp").setLevel(log_level)
398 logging.getLogger("pp").addHandler(log_handler)
399
400 server = _NetworkServer(**args)
401 if autodiscovery:
402 server.broadcast()
403 return server
404
405 def signal_handler(signum, stack):
406 """Prints server stats when %s is received (unix only). """ % STAT_SIGNAL
407 server.print_stats()
408
409
410 if __name__ == "__main__":
411 server = create_network_server(sys.argv[1:])
412 statsignal = getattr(signal, STAT_SIGNAL, None)
413 if statsignal:
414 signal.signal(statsignal, signal_handler)
415 server.listen()
416 #have to destroy it here explicitly otherwise an exception
417 #comes out in Python 2.4
418 del server
419
420
421 # Parallel Python Software: http://www.parallelpython.com