]> arthur.barton.de Git - bup.git/blob - cmd/on-cmd.py
Use absolute_import from the __future__ everywhere
[bup.git] / cmd / on-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
5 """
6 # end of bup preamble
7
8 from __future__ import absolute_import
9 import sys, os, struct, getopt, subprocess, signal
10
11 from subprocess import PIPE
12 from bup import options, ssh, path
13 from bup.helpers import DemuxConn, log
14
15
16 optspec = """
17 bup on <hostname> index ...
18 bup on <hostname> save ...
19 bup on <hostname> split ...
20 """
21 o = options.Options(optspec, optfunc=getopt.getopt)
22 (opt, flags, extra) = o.parse(sys.argv[1:])
23 if len(extra) < 2:
24     o.fatal('arguments expected')
25
26 class SigException(Exception):
27     def __init__(self, signum):
28         self.signum = signum
29         Exception.__init__(self, 'signal %d received' % signum)
30 def handler(signum, frame):
31     raise SigException(signum)
32
33 signal.signal(signal.SIGTERM, handler)
34 signal.signal(signal.SIGINT, handler)
35
36 try:
37     sp = None
38     p = None
39     ret = 99
40
41     hp = extra[0].split(':')
42     if len(hp) == 1:
43         (hostname, port) = (hp[0], None)
44     else:
45         (hostname, port) = hp
46     argv = extra[1:]
47     p = ssh.connect(hostname, port, 'on--server', stderr=PIPE)
48
49     try:
50         argvs = '\0'.join(['bup'] + argv)
51         p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
52         p.stdin.flush()
53         sp = subprocess.Popen([path.exe(), 'server'],
54                               stdin=p.stdout, stdout=p.stdin)
55         p.stdin.close()
56         p.stdout.close()
57         # Demultiplex remote client's stderr (back to stdout/stderr).
58         dmc = DemuxConn(p.stderr.fileno(), open(os.devnull, "w"))
59         for line in iter(dmc.readline, ""):
60             sys.stdout.write(line)
61     finally:
62         while 1:
63             # if we get a signal while waiting, we have to keep waiting, just
64             # in case our child doesn't die.
65             try:
66                 ret = p.wait()
67                 if sp:
68                     sp.wait()
69                 break
70             except SigException as e:
71                 log('\nbup on: %s\n' % e)
72                 os.kill(p.pid, e.signum)
73                 ret = 84
74 except SigException as e:
75     if ret == 0:
76         ret = 99
77     log('\nbup on: %s\n' % e)
78
79 sys.exit(ret)