]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/common.py
storage: add a lease-checker-and-expirer crawler, plus web status page.
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / common.py
1
2 from twisted.web import http, server
3 from zope.interface import Interface
4 from nevow import loaders, appserver
5 from nevow.inevow import IRequest
6 from nevow.util import resource_filename
7 from allmydata.interfaces import ExistingChildError, NoSuchChildError, \
8      FileTooLargeError, NotEnoughSharesError
9 from allmydata.util import abbreviate # TODO: consolidate
10
11 class IOpHandleTable(Interface):
12     pass
13
14 def getxmlfile(name):
15     return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
16
17 def boolean_of_arg(arg):
18     # TODO: ""
19     assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
20     return arg.lower() in ("true", "t", "1", "on")
21
22 def get_root(ctx_or_req):
23     req = IRequest(ctx_or_req)
24     # the addSlash=True gives us one extra (empty) segment
25     depth = len(req.prepath) + len(req.postpath) - 1
26     link = "/".join([".."] * depth)
27     return link
28
29 def get_arg(ctx_or_req, argname, default=None, multiple=False):
30     """Extract an argument from either the query args (req.args) or the form
31     body fields (req.fields). If multiple=False, this returns a single value
32     (or the default, which defaults to None), and the query args take
33     precedence. If multiple=True, this returns a tuple of arguments (possibly
34     empty), starting with all those in the query args.
35     """
36     req = IRequest(ctx_or_req)
37     results = []
38     if argname in req.args:
39         results.extend(req.args[argname])
40     if req.fields and argname in req.fields:
41         results.append(req.fields[argname].value)
42     if multiple:
43         return tuple(results)
44     if results:
45         return results[0]
46     return default
47
48 def abbreviate_time(data):
49     # 1.23s, 790ms, 132us
50     if data is None:
51         return ""
52     s = float(data)
53     if s >= 10:
54         return abbreviate.abbreviate_time(data)
55     if s >= 1.0:
56         return "%.2fs" % s
57     if s >= 0.01:
58         return "%dms" % (1000*s)
59     if s >= 0.001:
60         return "%.1fms" % (1000*s)
61     return "%dus" % (1000000*s)
62
63 def abbreviate_rate(data):
64     # 21.8kBps, 554.4kBps 4.37MBps
65     if data is None:
66         return ""
67     r = float(data)
68     if r > 1000000:
69         return "%1.2fMBps" % (r/1000000)
70     if r > 1000:
71         return "%.1fkBps" % (r/1000)
72     return "%dBps" % r
73
74 def abbreviate_size(data):
75     # 21.8kB, 554.4kB 4.37MB
76     if data is None:
77         return ""
78     r = float(data)
79     if r > 1000000000:
80         return "%1.2fGB" % (r/1000000000)
81     if r > 1000000:
82         return "%1.2fMB" % (r/1000000)
83     if r > 1000:
84         return "%.1fkB" % (r/1000)
85     return "%dB" % r
86
87 def plural(sequence_or_length):
88     if isinstance(sequence_or_length, int):
89         length = sequence_or_length
90     else:
91         length = len(sequence_or_length)
92     if length == 1:
93         return ""
94     return "s"
95
96 def text_plain(text, ctx):
97     req = IRequest(ctx)
98     req.setHeader("content-type", "text/plain")
99     req.setHeader("content-length", len(text))
100     return text
101
102 class WebError(Exception):
103     def __init__(self, text, code=http.BAD_REQUEST):
104         self.text = text
105         self.code = code
106
107 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
108 # Internal Server Error, we either need to do that ICanHandleException trick,
109 # or make sure that childFactory returns a WebErrorResource (and never an
110 # actual exception). The latter is growing increasingly annoying.
111
112 def should_create_intermediate_directories(req):
113     t = get_arg(req, "t", "").strip()
114     return bool(req.method in ("PUT", "POST") and
115                 t not in ("delete", "rename", "rename-form", "check"))
116
117
118 class MyExceptionHandler(appserver.DefaultExceptionHandler):
119     def simple(self, ctx, text, code=http.BAD_REQUEST):
120         req = IRequest(ctx)
121         req.setResponseCode(code)
122         #req.responseHeaders.setRawHeaders("content-encoding", [])
123         #req.responseHeaders.setRawHeaders("content-disposition", [])
124         req.setHeader("content-type", "text/plain;charset=utf-8")
125         if isinstance(text, unicode):
126             text = text.encode("utf-8")
127         req.setHeader("content-length", str(len(text)))
128         req.write(text)
129         # TODO: consider putting the requested URL here
130         req.finishRequest(False)
131
132     def renderHTTP_exception(self, ctx, f):
133         traceback = f.getTraceback()
134         if f.check(ExistingChildError):
135             return self.simple(ctx,
136                                "There was already a child by that "
137                                "name, and you asked me to not "
138                                "replace it.",
139                                http.CONFLICT)
140         elif f.check(NoSuchChildError):
141             name = f.value.args[0]
142             return self.simple(ctx,
143                                "No such child: %s" % name.encode("utf-8"),
144                                http.NOT_FOUND)
145         elif f.check(NotEnoughSharesError):
146             got = f.value.got
147             needed = f.value.needed
148             if got == 0:
149                 t = ("NotEnoughSharesError: no shares could be found. "
150                      "Zero shares usually indicates a corrupt URI, or that "
151                      "no servers were connected, but it might also indicate "
152                      "severe corruption. You should perform a filecheck on "
153                      "this object to learn more.")
154             else:
155                 t = ("NotEnoughSharesError: %d share%s found, but we need "
156                      "%d to recover the file. This indicates that some "
157                      "servers were unavailable, or that shares have been "
158                      "lost to server departure, hard drive failure, or disk "
159                      "corruption. You should perform a filecheck on "
160                      "this object to learn more.") % (got, plural(got), needed)
161             return self.simple(ctx, t, http.GONE)
162         elif f.check(WebError):
163             return self.simple(ctx, f.value.text, f.value.code)
164         elif f.check(FileTooLargeError):
165             return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
166         elif f.check(server.UnsupportedMethod):
167             # twisted.web.server.Request.render() has support for transforming
168             # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
169             # return code, but nevow does not.
170             req = IRequest(ctx)
171             method = req.method
172             return self.simple(ctx,
173                                "I don't know how to treat a %s request." % method,
174                                http.NOT_IMPLEMENTED)
175         req = IRequest(ctx)
176         accept = req.getHeader("accept")
177         if not accept:
178             accept = "*/*"
179         if "*/*" in accept or "text/*" in accept or "text/html" in accept:
180             super = appserver.DefaultExceptionHandler
181             return super.renderHTTP_exception(self, ctx, f)
182         # use plain text
183         return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
184
185 class NeedOperationHandleError(WebError):
186     pass
187
188 class RenderMixin:
189
190     def renderHTTP(self, ctx):
191         request = IRequest(ctx)
192
193         # if we were using regular twisted.web Resources (and the regular
194         # twisted.web.server.Request object) then we could implement
195         # render_PUT and render_GET. But Nevow's request handler
196         # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
197         # some code from the Resource.render method that Nevow bypasses, to
198         # do the same thing.
199         m = getattr(self, 'render_' + request.method, None)
200         if not m:
201             from twisted.web.server import UnsupportedMethod
202             raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
203         return m(ctx)