]> arthur.barton.de Git - bup.git/commitdiff
Merge web GET fix and SIGTERM and unix:// support
authorRob Browning <rlb@defaultvalue.org>
Sat, 12 Mar 2016 17:55:05 +0000 (11:55 -0600)
committerRob Browning <rlb@defaultvalue.org>
Sat, 12 Mar 2016 17:55:05 +0000 (11:55 -0600)
Tested-by: Rob Browning <rlb@defaultvalue.org>
Signed-off-by: Rob Browning <rlb@defaultvalue.org>
Documentation/bup-web.md
Makefile
cmd/web-cmd.py
t/test-web.sh [new file with mode: 0755]

index 08fd84dc75f190e48ea38048ad1cc984652f6448..2f7750f66f49b0022711b00c63a0c95fbb1b0fe9 100644 (file)
@@ -10,6 +10,8 @@ bup-web - Start web server to browse bup repositiory
 
 bup web [[hostname]:port]
 
+bup web unix://path
+
 # DESCRIPTION
 
 `bup web` starts a web server that can browse bup repositories. The file
@@ -21,6 +23,12 @@ hierarchy is the same as that shown by `bup-fuse`(1), `bup-ls`(1) and
 you'd like to expose the web server to anyone on your network (dangerous!) you
 can omit the bind address to bind to all available interfaces: `:8080`.
 
+When `unix://path` is specified, the server will listen on the
+filesystem socket at `path` rather than a network socket.
+
+A `SIGTERM` signal may be sent to the server to request an orderly
+shutdown.
+
 # OPTIONS
 
 --human-readable
@@ -34,15 +42,33 @@ can omit the bind address to bind to all available interfaces: `:8080`.
     $ bup web
     Serving HTTP on 127.0.0.1:8080...
     ^C
+    Interrupted.
 
     $ bup web :8080
     Serving HTTP on 0.0.0.0:8080...
     ^C
+    Interrupted.
 
+    $ bup web unix://socket &
+    Serving HTTP on filesystem socket 'socket'
+    $ curl --unix-socket ./socket http://localhost/
+    $ fg
+    bup web unix://socket
+    ^C
+    Interrupted.
+
+    $ bup web &
+    [1] 30980
+    Serving HTTP on 127.0.0.1:8080...
+    $ kill -s TERM 30980
+    Shutdown requested
+    $ wait 30980
+    $ echo $?
+    0
 
 # SEE ALSO
 
-`bup-fuse`(1), `bup-ls`(1), `bup-ftp`(1), `bup-restore`(1)
+`bup-fuse`(1), `bup-ls`(1), `bup-ftp`(1), `bup-restore`(1), `kill`(1)
 
 
 # BUP
index 79fbcb36e9e04e41efc03f36e06c5aea67653ac5..1fdac2611147205817c20295f3e7a6c7edd7aa28 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -145,6 +145,7 @@ runtests-python: all t/tmp
            | tee -a t/tmp/test-log/$$$$.log
 
 cmdline_tests := \
+  t/test-web.sh \
   t/test-rm.sh \
   t/test-gc.sh \
   t/test-main.sh \
index 9d5d8a1445b0d0454da06c636e7e27e785006899..47817f0e3cdf82182630303e59034cef071a2f30 100755 (executable)
@@ -5,14 +5,18 @@ exec "$bup_python" "$0" ${1+"$@"}
 """
 # end of bup preamble
 
-import mimetypes, os, posixpath, stat, sys, time, urllib, webbrowser
+from collections import namedtuple
+import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
 
 from bup import options, git, vfs
-from bup.helpers import debug1, handle_ctrl_c, log, resource_path
+from bup.helpers import (chunkyreader, debug1, handle_ctrl_c, log,
+                         resource_path, saved_errors)
 
 try:
-    import tornado.httpserver
-    import tornado.ioloop
+    from tornado import gen
+    from tornado.httpserver import HTTPServer
+    from tornado.ioloop import IOLoop
+    from tornado.netutil import bind_unix_socket
     import tornado.web
 except ImportError:
     log('error: cannot find the python "tornado" module; please install it\n')
@@ -86,7 +90,6 @@ class BupRequestHandler(tornado.web.RequestHandler):
     def head(self, path):
         return self._process_request(path)
     
-    @tornado.web.asynchronous
     def _process_request(self, path):
         path = urllib.unquote(path)
         print 'Handling request for %s' % path
@@ -124,6 +127,7 @@ class BupRequestHandler(tornado.web.RequestHandler):
             hidden_shown=show_hidden,
             dir_contents=_compute_dir_contents(n, path, show_hidden))
 
+    @gen.coroutine
     def _get_file(self, path, n):
         """Process a request on a file.
 
@@ -131,30 +135,21 @@ class BupRequestHandler(tornado.web.RequestHandler):
         In either case, the headers are sent.
         """
         ctype = self._guess_type(path)
-
         self.set_header("Last-Modified", self.date_time_string(n.mtime))
         self.set_header("Content-Type", ctype)
         size = n.size()
         self.set_header("Content-Length", str(size))
         assert(len(n.hash) == 20)
         self.set_header("Etag", n.hash.encode('hex'))
-
         if self.request.method != 'HEAD':
-            self.flush()
             f = n.open()
-            it = chunkyreader(f)
-            def write_more(me):
-                try:
-                    blob = it.next()
-                except StopIteration:
-                    f.close()
-                    self.finish()
-                    return
-                self.request.connection.stream.write(blob,
-                                                     callback=lambda: me(me))
-            write_more(write_more)
-        else:
-            self.finish()
+            try:
+                it = chunkyreader(f)
+                for blob in chunkyreader(f):
+                    self.write(blob)
+            finally:
+                f.close()
+        raise gen.Return()
 
     def _guess_type(self, path):
         """Guess the type of a file.
@@ -192,11 +187,28 @@ class BupRequestHandler(tornado.web.RequestHandler):
         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
 
 
+io_loop = None
+
+def handle_sigterm(signum, frame):
+    global io_loop
+    debug1('\nbup-web: signal %d received\n' % signum)
+    log('Shutdown requested\n')
+    if not io_loop:
+        sys.exit(0)
+    io_loop.stop()
+
+
+signal.signal(signal.SIGTERM, handle_sigterm)
+
+UnixAddress = namedtuple('UnixAddress', ['path'])
+InetAddress = namedtuple('InetAddress', ['host', 'port'])
+
 optspec = """
 bup web [[hostname]:port]
+bup web unix://path
 --
 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
-browser           open the site in the default browser
+browser           show repository in default browser (incompatible with unix://)
 """
 o = options.Options(optspec)
 (opt, flags, extra) = o.parse(sys.argv[1:])
@@ -204,11 +216,24 @@ o = options.Options(optspec)
 if len(extra) > 1:
     o.fatal("at most one argument expected")
 
-address = ('127.0.0.1', 8080)
-if len(extra) > 0:
-    addressl = extra[0].split(':', 1)
-    addressl[1] = int(addressl[1])
-    address = tuple(addressl)
+if len(extra) == 0:
+    address = InetAddress(host='127.0.0.1', port=8080)
+else:
+    bind_url = extra[0]
+    if bind_url.startswith('unix://'):
+        address = UnixAddress(path=bind_url[len('unix://'):])
+    else:
+        addr_parts = extra[0].split(':', 1)
+        if len(addr_parts) == 1:
+            host = '127.0.0.1'
+            port = addr_parts[0]
+        else:
+            host, port = addr_parts
+        try:
+            port = int(port)
+        except (TypeError, ValueError) as ex:
+            o.fatal('port must be an integer, not %r', port)
+        address = InetAddress(host=host, port=port)
 
 git.check_repo_or_die()
 top = vfs.RefList(None)
@@ -226,19 +251,30 @@ application = tornado.web.Application([
     (r"(/.*)", BupRequestHandler),
 ], **settings)
 
-if __name__ == "__main__":
-    http_server = tornado.httpserver.HTTPServer(application)
-    http_server.listen(address[1], address=address[0])
+http_server = HTTPServer(application)
+io_loop_pending = IOLoop.instance()
 
+if isinstance(address, InetAddress):
+    http_server.listen(address.port, address.host)
     try:
         sock = http_server._socket # tornado < 2.0
     except AttributeError as e:
         sock = http_server._sockets.values()[0]
-
     print "Serving HTTP on %s:%d..." % sock.getsockname()
-
-    loop = tornado.ioloop.IOLoop.instance()
     if opt.browser:
         browser_addr = 'http://' + address[0] + ':' + str(address[1])
-        loop.add_callback(lambda : webbrowser.open(browser_addr))
-    loop.start()
+        io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
+elif isinstance(address, UnixAddress):
+    unix_socket = bind_unix_socket(address.path)
+    http_server.add_socket(unix_socket)
+    print "Serving HTTP on filesystem socket %r" % address.path
+else:
+    log('error: unexpected address %r', address)
+    sys.exit(1)
+
+io_loop = io_loop_pending
+io_loop.start()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
diff --git a/t/test-web.sh b/t/test-web.sh
new file mode 100755 (executable)
index 0000000..842b6e9
--- /dev/null
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+. wvtest-bup.sh || exit $?
+. t/lib.sh || exit $?
+
+set -o pipefail
+
+TOP="$(WVPASS pwd)" || exit $?
+tmpdir="$(WVPASS wvmktempdir)" || exit $?
+export BUP_DIR="$tmpdir/bup"
+
+bup()
+{
+    "$TOP/bup" "$@"
+}
+
+wait-for-server-start()
+{
+    curl --unix-socket ./socket http://localhost/
+    curl_status=$?
+    while test $curl_status -eq 7; do
+        sleep 0.2
+        curl --unix-socket ./socket http://localhost/
+        curl_status=$?
+    done
+    WVPASSEQ $curl_status 0
+}
+
+WVPASS cd "$tmpdir"
+
+# FIXME: add WVSKIP
+run_test=true
+
+if test -z "$(type -p curl)"; then
+    WVSTART 'curl does not appear to be installed; skipping  test'
+    run_test=''
+fi
+    
+WVPASS bup-python -c "import socket as s; s.socket(s.AF_UNIX).bind('socket')"
+curl --unix-socket ./socket http://localhost/foo
+if test $? -ne 7; then
+    WVSTART 'curl does not appear to support --unix-socket; skipping test'
+    run_test=''
+fi
+    
+if test -n "$run_test"; then
+    WVSTART 'web'
+    WVPASS bup init
+    WVPASS mkdir src
+    WVPASS echo excitement > src/data
+    WVPASS bup index src
+    WVPASS bup save -n src --strip src
+
+    "$TOP/bup" web unix://socket &
+    web_pid=$!
+    wait-for-server-start
+
+    WVPASS curl --unix-socket ./socket http://localhost/src/latest/data > result
+
+    WVPASSEQ excitement "$(cat result)"
+    WVPASS kill -s TERM "$web_pid"
+    WVPASS wait "$web_pid"
+fi
+
+WVPASS rm -r "$tmpdir"