]> arthur.barton.de Git - bup.git/blob - cmd/on-cmd.py
on: only wait for a process if it might exist
[bup.git] / cmd / on-cmd.py
1 #!/usr/bin/env python
2 import sys, os, struct, getopt, subprocess, signal
3 from bup import options, ssh, path
4 from bup.helpers import *
5
6 optspec = """
7 bup on <hostname> index ...
8 bup on <hostname> save ...
9 bup on <hostname> split ...
10 """
11 o = options.Options(optspec, optfunc=getopt.getopt)
12 (opt, flags, extra) = o.parse(sys.argv[1:])
13 if len(extra) < 2:
14     o.fatal('arguments expected')
15
16 class SigException(Exception):
17     def __init__(self, signum):
18         self.signum = signum
19         Exception.__init__(self, 'signal %d received' % signum)
20 def handler(signum, frame):
21     raise SigException(signum)
22
23 signal.signal(signal.SIGTERM, handler)
24 signal.signal(signal.SIGINT, handler)
25
26 sp = None
27 p = None
28 ret = 99
29
30 hp = extra[0].split(':')
31 if len(hp) == 1:
32     (hostname, port) = (hp[0], None)
33 else:
34     (hostname, port) = hp
35
36 argv = extra[1:]
37 p = ssh.connect(hostname, port, 'on--server')
38
39 try:
40     argvs = '\0'.join(['bup'] + argv)
41     p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
42     p.stdin.flush()
43     sp = subprocess.Popen([path.exe(), 'server'],
44                           stdin=p.stdout, stdout=p.stdin)
45     p.stdin.close()
46     p.stdout.close()
47 finally:
48     while 1:
49         # if we get a signal while waiting, we have to keep waiting, just
50         # in case our child doesn't die.
51         try:
52             ret = p.wait()
53             if sp:
54                 sp.wait()
55             break
56         except SigException, e:
57             log('\nbup on: %s\n' % e)
58             os.kill(p.pid, e.signum)
59             ret = 84
60 sys.exit(ret)