]> arthur.barton.de Git - bup.git/blob - cmd/web-cmd.py
web: attempt orderly shut down on SIGTERM
[bup.git] / cmd / web-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 import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
9
10 from bup import options, git, vfs
11 from bup.helpers import (debug1, handle_ctrl_c, log, resource_path,
12                          saved_errors)
13
14 try:
15     from tornado.ioloop import IOLoop
16     import tornado.httpserver
17     import tornado.web
18 except ImportError:
19     log('error: cannot find the python "tornado" module; please install it\n')
20     sys.exit(1)
21
22
23 handle_ctrl_c()
24
25
26 def _compute_breadcrumbs(path, show_hidden=False):
27     """Returns a list of breadcrumb objects for a path."""
28     breadcrumbs = []
29     breadcrumbs.append(('[root]', '/'))
30     path_parts = path.split('/')[1:-1]
31     full_path = '/'
32     for part in path_parts:
33         full_path += part + "/"
34         url_append = ""
35         if show_hidden:
36             url_append = '?hidden=1'
37         breadcrumbs.append((part, full_path+url_append))
38     return breadcrumbs
39
40
41 def _contains_hidden_files(n):
42     """Return True if n contains files starting with a '.', False otherwise."""
43     for sub in n:
44         name = sub.name
45         if len(name)>1 and name.startswith('.'):
46             return True
47
48     return False
49
50
51 def _compute_dir_contents(n, path, show_hidden=False):
52     """Given a vfs node, returns an iterator for display info of all subs."""
53     url_append = ""
54     if show_hidden:
55         url_append = "?hidden=1"
56
57     if path != "/":
58         yield('..', '../' + url_append, '')
59     for sub in n:
60         display = sub.name
61         link = urllib.quote(sub.name)
62
63         # link should be based on fully resolved type to avoid extra
64         # HTTP redirect.
65         if stat.S_ISDIR(sub.try_resolve().mode):
66             link += "/"
67
68         if not show_hidden and len(display)>1 and display.startswith('.'):
69             continue
70
71         size = None
72         if stat.S_ISDIR(sub.mode):
73             display += '/'
74         elif stat.S_ISLNK(sub.mode):
75             display += '@'
76         else:
77             size = sub.size()
78             size = (opt.human_readable and format_filesize(size)) or size
79
80         yield (display, link + url_append, size)
81
82
83 class BupRequestHandler(tornado.web.RequestHandler):
84     def get(self, path):
85         return self._process_request(path)
86
87     def head(self, path):
88         return self._process_request(path)
89     
90     @tornado.web.asynchronous
91     def _process_request(self, path):
92         path = urllib.unquote(path)
93         print 'Handling request for %s' % path
94         try:
95             n = top.resolve(path)
96         except vfs.NoSuchFile:
97             self.send_error(404)
98             return
99         f = None
100         if stat.S_ISDIR(n.mode):
101             self._list_directory(path, n)
102         else:
103             self._get_file(path, n)
104
105     def _list_directory(self, path, n):
106         """Helper to produce a directory listing.
107
108         Return value is either a file object, or None (indicating an
109         error).  In either case, the headers are sent.
110         """
111         if not path.endswith('/') and len(path) > 0:
112             print 'Redirecting from %s to %s' % (path, path + '/')
113             return self.redirect(path + '/', permanent=True)
114
115         try:
116             show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
117         except ValueError as e:
118             show_hidden = False
119
120         self.render(
121             'list-directory.html',
122             path=path,
123             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
124             files_hidden=_contains_hidden_files(n),
125             hidden_shown=show_hidden,
126             dir_contents=_compute_dir_contents(n, path, show_hidden))
127
128     def _get_file(self, path, n):
129         """Process a request on a file.
130
131         Return value is either a file object, or None (indicating an error).
132         In either case, the headers are sent.
133         """
134         ctype = self._guess_type(path)
135
136         self.set_header("Last-Modified", self.date_time_string(n.mtime))
137         self.set_header("Content-Type", ctype)
138         size = n.size()
139         self.set_header("Content-Length", str(size))
140         assert(len(n.hash) == 20)
141         self.set_header("Etag", n.hash.encode('hex'))
142
143         if self.request.method != 'HEAD':
144             self.flush()
145             f = n.open()
146             it = chunkyreader(f)
147             def write_more(me):
148                 try:
149                     blob = it.next()
150                 except StopIteration:
151                     f.close()
152                     self.finish()
153                     return
154                 self.request.connection.stream.write(blob,
155                                                      callback=lambda: me(me))
156             write_more(write_more)
157         else:
158             self.finish()
159
160     def _guess_type(self, path):
161         """Guess the type of a file.
162
163         Argument is a PATH (a filename).
164
165         Return value is a string of the form type/subtype,
166         usable for a MIME Content-type header.
167
168         The default implementation looks the file's extension
169         up in the table self.extensions_map, using application/octet-stream
170         as a default; however it would be permissible (if
171         slow) to look inside the data to make a better guess.
172         """
173         base, ext = posixpath.splitext(path)
174         if ext in self.extensions_map:
175             return self.extensions_map[ext]
176         ext = ext.lower()
177         if ext in self.extensions_map:
178             return self.extensions_map[ext]
179         else:
180             return self.extensions_map['']
181
182     if not mimetypes.inited:
183         mimetypes.init() # try to read system mime.types
184     extensions_map = mimetypes.types_map.copy()
185     extensions_map.update({
186         '': 'text/plain', # Default
187         '.py': 'text/plain',
188         '.c': 'text/plain',
189         '.h': 'text/plain',
190         })
191
192     def date_time_string(self, t):
193         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
194
195
196 io_loop = None
197
198 def handle_sigterm(signum, frame):
199     global io_loop
200     debug1('\nbup-web: signal %d received\n' % signum)
201     log('Shutdown requested\n')
202     if not io_loop:
203         sys.exit(0)
204     io_loop.stop()
205
206
207 signal.signal(signal.SIGTERM, handle_sigterm)
208
209 optspec = """
210 bup web [[hostname]:port]
211 --
212 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
213 browser           open the site in the default browser
214 """
215 o = options.Options(optspec)
216 (opt, flags, extra) = o.parse(sys.argv[1:])
217
218 if len(extra) > 1:
219     o.fatal("at most one argument expected")
220
221 address = ('127.0.0.1', 8080)
222 if len(extra) > 0:
223     addressl = extra[0].split(':', 1)
224     addressl[1] = int(addressl[1])
225     address = tuple(addressl)
226
227 git.check_repo_or_die()
228 top = vfs.RefList(None)
229
230 settings = dict(
231     debug = 1,
232     template_path = resource_path('web'),
233     static_path = resource_path('web/static')
234 )
235
236 # Disable buffering on stdout, for debug messages
237 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
238
239 application = tornado.web.Application([
240     (r"(/.*)", BupRequestHandler),
241 ], **settings)
242
243 http_server = tornado.httpserver.HTTPServer(application)
244 http_server.listen(address[1], address=address[0])
245
246 try:
247     sock = http_server._socket # tornado < 2.0
248 except AttributeError as e:
249     sock = http_server._sockets.values()[0]
250
251 print "Serving HTTP on %s:%d..." % sock.getsockname()
252
253 io_loop_pending = IOLoop.instance()
254 if opt.browser:
255     browser_addr = 'http://' + address[0] + ':' + str(address[1])
256     io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
257
258 io_loop = io_loop_pending
259 io_loop.start()
260
261 if saved_errors:
262     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
263     sys.exit(1)