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 while not self._stop:
204 data = self.read_data()
205 self.send_to_server(data)
206 data = self.recv_from_server()
207 self.write_data(data)
211 return sys.stdin.readline()
213 def write_data(self, data):
214 sys.stdout.write(data)
215 # sys.stdout.write is buffered, this is why we need to do a flush()
218 def send_to_server(self, data):
220 self._ctrl_sock.send(data)
222 if e.errno == errno.EPIPE:
224 self._ctrl_sock.send(data)
227 encoded = data.rstrip()
228 msg = base64.b64decode(encoded)
232 def recv_from_server(self):
236 chunk = self._ctrl_sock.recv(1024)
238 if e.errno != errno.EINTR:
243 if chunk[-1] == "\n":
249 self._ctrl_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
250 sock_addr = os.path.join(self._root_dir, CTRL_SOCK)
251 self._ctrl_sock.connect(sock_addr)
253 def disconnect(self):
255 self._ctrl_sock.close()
259 class Client(object):
260 def __init__(self, root_dir = ".", host = None, port = None, user = None,
262 self.root_dir = root_dir
263 self.addr = (host, port)
266 self._stopped = False
270 if self._process.poll() is None:
271 os.kill(self._process.pid, signal.SIGTERM)
275 root_dir = self.root_dir
276 (host, port) = self.addr
280 python_code = "from nepi.util import server;c=server.Forwarder(%r);\
281 c.forward()" % (root_dir,)
283 self._process = popen_ssh_subprocess(python_code, host, port,
286 self._process = subprocess.Popen(
287 ["python", "-c", python_code],
288 stdin = subprocess.PIPE,
289 stdout = subprocess.PIPE,
290 stderr = subprocess.PIPE
292 if self._process.poll():
293 err = self._process.stderr.read()
294 raise RuntimeError("Client could not be executed: %s" % \
297 def send_msg(self, msg):
298 encoded = base64.b64encode(msg)
299 data = "%s\n" % encoded
302 self._process.stdin.write(data)
303 except (IOError, ValueError):
304 # dead process, poll it to un-zombify
307 # try again after reconnect
308 # If it fails again, though, give up
310 self._process.stdin.write(data)
313 self.send_msg(STOP_MSG)
316 def read_reply(self):
317 data = self._process.stdout.readline()
318 encoded = data.rstrip()
319 return base64.b64decode(encoded)
321 def popen_ssh_subprocess(python_code, host, port, user, agent,
324 python_path.replace("'", r"'\''")
325 cmd = """PYTHONPATH="$PYTHONPATH":'%s' """ % python_path
328 # Uncomment for debug (to run everything under strace)
329 # We had to verify if strace works (cannot nest them)
330 #cmd += "if strace echo >/dev/null 2>&1; then CMD='strace -ff -tt -s 200 -o strace.out'; else CMD=''; fi\n"
332 #if self.mode == MODE_SSH:
333 # cmd += "strace -f -tt -s 200 -o strace$$.out "
335 cmd += "import base64, os\n"
336 cmd += "cmd = \"\"\n"
337 cmd += "while True:\n"
338 cmd += " cmd += os.read(0, 1)\n" # one byte from stdin
339 cmd += " if cmd[-1] == \"\\n\": break\n"
340 cmd += "cmd = base64.b64decode(cmd)\n"
341 # Uncomment for debug
342 #cmd += "os.write(2, \"Executing python code: %s\\n\" % cmd)\n"
343 cmd += "os.write(1, \"OK\\n\")\n" # send a sync message
344 cmd += "exec(cmd)\n'"
347 # Don't bother with localhost. Makes test easier
348 '-o', 'NoHostAuthenticationForLocalhost=yes',
353 args.append('-p%d' % port)
356 # connects to the remote host and starts a remote rpyc connection
357 proc = subprocess.Popen(args,
358 stdout = subprocess.PIPE,
359 stdin = subprocess.PIPE,
360 stderr = subprocess.PIPE)
361 # send the command to execute
362 os.write(proc.stdin.fileno(),
363 base64.b64encode(python_code) + "\n")
364 msg = os.read(proc.stdout.fileno(), 3)
366 raise RuntimeError("Failed to start remote python interpreter")