2 # -*- coding: utf-8 -*-
17 CTRL_SOCK = "ctrl.sock"
18 STD_ERR = "stderr.log"
26 if hasattr(os, "devnull"):
29 DEV_NULL = "/dev/null"
32 def __init__(self, root_dir = ".", log_level = ERROR_LEVEL):
33 self._root_dir = root_dir
35 self._ctrl_sock = None
36 self._log_level = log_level
45 # can not return normally after fork beacuse no exec was done.
46 # This means that if we don't do a os._exit(0) here the code that
47 # follows the call to "Server.run()" in the "caller code" will be
48 # executed... but by now it has already been executed after the
49 # first process (the one that did the first fork) returned.
57 # pipes for process synchronization
65 # os.waitpid avoids leaving a <defunc> (zombie) process
66 st = os.waitpid(pid1, 0)[1]
68 raise RuntimeError("Daemonization failed")
69 # return 0 to inform the caller method that this is not the
74 # Decouple from parent environment.
75 os.chdir(self._root_dir)
82 # see ref: "os._exit(0)"
85 # close all open file descriptors.
86 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
87 if (max_fd == resource.RLIM_INFINITY):
89 for fd in range(3, max_fd):
96 # Redirect standard file descriptors.
97 stdin = open(DEV_NULL, "r")
98 stderr = stdout = open(STD_ERR, "a", 0)
99 os.dup2(stdin.fileno(), sys.stdin.fileno())
100 # NOTE: sys.stdout.write will still be buffered, even if the file
101 # was opened with 0 buffer
102 os.dup2(stdout.fileno(), sys.stdout.fileno())
103 os.dup2(stderr.fileno(), sys.stderr.fileno())
105 # let the parent process know that the daemonization is finished
110 def post_daemonize(self):
114 self._ctrl_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
115 self._ctrl_sock.bind(CTRL_SOCK)
116 self._ctrl_sock.listen(0)
117 while not self._stop:
118 conn, addr = self._ctrl_sock.accept()
120 while not self._stop:
122 msg = self.recv_msg(conn)
123 except socket.timeout, e:
128 reply = self.stop_action()
130 reply = self.reply_action(msg)
133 self.send_reply(conn, reply)
136 print >>sys.stderr, "NOTICE: Awaiting for reconnection"
144 def recv_msg(self, conn):
148 chunk = conn.recv(1024)
150 if e.errno != errno.EINTR:
156 if chunk[-1] == "\n":
161 decoded = base64.b64decode(data)
162 return decoded.rstrip()
164 def send_reply(self, conn, reply):
165 encoded = base64.b64encode(reply)
166 conn.send("%s\n" % encoded)
170 self._ctrl_sock.close()
175 def stop_action(self):
176 return "Stopping server"
178 def reply_action(self, msg):
179 return "Reply to: %s" % msg
181 def log_error(self, text = None, context = ''):
183 text = traceback.format_exc()
184 date = time.strftime("%Y-%m-%d %H:%M:%S")
186 context = " (%s)" % (context,)
187 sys.stderr.write("ERROR%s: %s\n%s\n" % (context, date, text))
190 def log_debug(self, text):
191 if self._log_level == DEBUG_LEVEL:
192 date = time.strftime("%Y-%m-%d %H:%M:%S")
193 sys.stderr.write("DEBUG: %s\n%s\n" % (date, text))
195 class Forwarder(object):
196 def __init__(self, root_dir = "."):
197 self._ctrl_sock = None
198 self._root_dir = root_dir
203 print >>sys.stderr, "READY."
204 while not self._stop:
205 data = self.read_data()
206 self.send_to_server(data)
207 data = self.recv_from_server()
208 self.write_data(data)
212 return sys.stdin.readline()
214 def write_data(self, data):
215 sys.stdout.write(data)
216 # sys.stdout.write is buffered, this is why we need to do a flush()
219 def send_to_server(self, data):
221 self._ctrl_sock.send(data)
223 if e.errno == errno.EPIPE:
225 self._ctrl_sock.send(data)
228 encoded = data.rstrip()
229 msg = base64.b64decode(encoded)
233 def recv_from_server(self):
237 chunk = self._ctrl_sock.recv(1024)
239 if e.errno != errno.EINTR:
244 if chunk[-1] == "\n":
250 self._ctrl_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
251 sock_addr = os.path.join(self._root_dir, CTRL_SOCK)
252 self._ctrl_sock.connect(sock_addr)
254 def disconnect(self):
256 self._ctrl_sock.close()
260 class Client(object):
261 def __init__(self, root_dir = ".", host = None, port = None, user = None,
263 self.root_dir = root_dir
264 self.addr = (host, port)
267 self._stopped = False
271 if self._process.poll() is None:
272 os.kill(self._process.pid, signal.SIGTERM)
276 root_dir = self.root_dir
277 (host, port) = self.addr
281 python_code = "from nepi.util import server;c=server.Forwarder(%r);\
282 c.forward()" % (root_dir,)
284 self._process = popen_ssh_subprocess(python_code, host, port,
286 # popen_ssh_subprocess already waits for readiness
288 self._process = subprocess.Popen(
289 ["python", "-c", python_code],
290 stdin = subprocess.PIPE,
291 stdout = subprocess.PIPE,
292 stderr = subprocess.PIPE
295 # Wait for the forwarder to be ready, otherwise nobody
296 # will be able to connect to it
297 helo = self._process.stderr.readline()
298 assert helo == 'READY.\n'
300 if self._process.poll():
301 err = self._process.stderr.read()
302 raise RuntimeError("Client could not be executed: %s" % \
305 def send_msg(self, msg):
306 encoded = base64.b64encode(msg)
307 data = "%s\n" % encoded
310 self._process.stdin.write(data)
311 except (IOError, ValueError):
312 # dead process, poll it to un-zombify
315 # try again after reconnect
316 # If it fails again, though, give up
318 self._process.stdin.write(data)
321 self.send_msg(STOP_MSG)
324 def read_reply(self):
325 data = self._process.stdout.readline()
326 encoded = data.rstrip()
327 return base64.b64decode(encoded)
329 def popen_ssh_subprocess(python_code, host, port, user, agent,
332 python_path.replace("'", r"'\''")
333 cmd = """PYTHONPATH="$PYTHONPATH":'%s' """ % python_path
336 # Uncomment for debug (to run everything under strace)
337 # We had to verify if strace works (cannot nest them)
338 #cmd += "if strace echo >/dev/null 2>&1; then CMD='strace -ff -tt -s 200 -o strace.out'; else CMD=''; fi\n"
340 #if self.mode == MODE_SSH:
341 # cmd += "strace -f -tt -s 200 -o strace$$.out "
343 cmd += "import base64, os\n"
344 cmd += "cmd = \"\"\n"
345 cmd += "while True:\n"
346 cmd += " cmd += os.read(0, 1)\n" # one byte from stdin
347 cmd += " if cmd[-1] == \"\\n\": break\n"
348 cmd += "cmd = base64.b64decode(cmd)\n"
349 # Uncomment for debug
350 #cmd += "os.write(2, \"Executing python code: %s\\n\" % cmd)\n"
351 cmd += "os.write(1, \"OK\\n\")\n" # send a sync message
352 cmd += "exec(cmd)\n'"
355 # Don't bother with localhost. Makes test easier
356 '-o', 'NoHostAuthenticationForLocalhost=yes',
361 args.append('-p%d' % port)
364 # connects to the remote host and starts a remote rpyc connection
365 proc = subprocess.Popen(args,
366 stdout = subprocess.PIPE,
367 stdin = subprocess.PIPE,
368 stderr = subprocess.PIPE)
369 # send the command to execute
370 os.write(proc.stdin.fileno(),
371 base64.b64encode(python_code) + "\n")
372 msg = os.read(proc.stdout.fileno(), 3)
374 raise RuntimeError("Failed to start remote python interpreter")