]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/common.py
web: refactor rate computation, fixes #1166
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / common.py
1
2 import simplejson
3 from twisted.web import http, server
4 from twisted.python import log
5 from zope.interface import Interface
6 from nevow import loaders, appserver
7 from nevow.inevow import IRequest
8 from nevow.util import resource_filename
9 from allmydata.interfaces import ExistingChildError, NoSuchChildError, \
10      FileTooLargeError, NotEnoughSharesError, NoSharesError, \
11      EmptyPathnameComponentError, MustBeDeepImmutableError, \
12      MustBeReadonlyError, MustNotBeUnknownRWError
13 from allmydata.mutable.common import UnrecoverableFileError
14 from allmydata.util import abbreviate
15 from allmydata.util.encodingutil import to_str
16
17 class IOpHandleTable(Interface):
18     pass
19
20 def getxmlfile(name):
21     return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
22
23 def boolean_of_arg(arg):
24     # TODO: ""
25     assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
26     return arg.lower() in ("true", "t", "1", "on")
27
28 def parse_replace_arg(replace):
29     if replace.lower() == "only-files":
30         return replace
31     else:
32         return boolean_of_arg(replace)
33
34 def get_root(ctx_or_req):
35     req = IRequest(ctx_or_req)
36     # the addSlash=True gives us one extra (empty) segment
37     depth = len(req.prepath) + len(req.postpath) - 1
38     link = "/".join([".."] * depth)
39     return link
40
41 def get_arg(ctx_or_req, argname, default=None, multiple=False):
42     """Extract an argument from either the query args (req.args) or the form
43     body fields (req.fields). If multiple=False, this returns a single value
44     (or the default, which defaults to None), and the query args take
45     precedence. If multiple=True, this returns a tuple of arguments (possibly
46     empty), starting with all those in the query args.
47     """
48     req = IRequest(ctx_or_req)
49     results = []
50     if argname in req.args:
51         results.extend(req.args[argname])
52     if req.fields and argname in req.fields:
53         results.append(req.fields[argname].value)
54     if multiple:
55         return tuple(results)
56     if results:
57         return results[0]
58     return default
59
60 def convert_children_json(nodemaker, children_json):
61     """I convert the JSON output of GET?t=json into the dict-of-nodes input
62     to both dirnode.create_subdirectory() and
63     client.create_directory(initial_children=). This is used by
64     t=mkdir-with-children and t=mkdir-immutable"""
65     children = {}
66     if children_json:
67         data = simplejson.loads(children_json)
68         for (namex, (ctype, propdict)) in data.iteritems():
69             namex = unicode(namex)
70             writecap = to_str(propdict.get("rw_uri"))
71             readcap = to_str(propdict.get("ro_uri"))
72             metadata = propdict.get("metadata", {})
73             # name= argument is just for error reporting
74             childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
75             children[namex] = (childnode, metadata)
76     return children
77
78 def abbreviate_time(data):
79     # 1.23s, 790ms, 132us
80     if data is None:
81         return ""
82     s = float(data)
83     if s >= 10:
84         return abbreviate.abbreviate_time(data)
85     if s >= 1.0:
86         return "%.2fs" % s
87     if s >= 0.01:
88         return "%.0fms" % (1000*s)
89     if s >= 0.001:
90         return "%.1fms" % (1000*s)
91     return "%.0fus" % (1000000*s)
92
93 def compute_rate(bytes, seconds):
94     if bytes is None:
95       return None
96
97     if seconds is None or seconds == 0:
98       return None
99
100     # negative values don't make sense here
101     assert bytes > -1
102     assert seconds > 0
103
104     return 1.0 * bytes / seconds
105
106 def abbreviate_rate(data):
107     # 21.8kBps, 554.4kBps 4.37MBps
108     if data is None:
109         return ""
110     r = float(data)
111     if r > 1000000:
112         return "%1.2fMBps" % (r/1000000)
113     if r > 1000:
114         return "%.1fkBps" % (r/1000)
115     return "%.0fBps" % r
116
117 def abbreviate_size(data):
118     # 21.8kB, 554.4kB 4.37MB
119     if data is None:
120         return ""
121     r = float(data)
122     if r > 1000000000:
123         return "%1.2fGB" % (r/1000000000)
124     if r > 1000000:
125         return "%1.2fMB" % (r/1000000)
126     if r > 1000:
127         return "%.1fkB" % (r/1000)
128     return "%.0fB" % r
129
130 def plural(sequence_or_length):
131     if isinstance(sequence_or_length, int):
132         length = sequence_or_length
133     else:
134         length = len(sequence_or_length)
135     if length == 1:
136         return ""
137     return "s"
138
139 def text_plain(text, ctx):
140     req = IRequest(ctx)
141     req.setHeader("content-type", "text/plain")
142     req.setHeader("content-length", len(text))
143     return text
144
145 class WebError(Exception):
146     def __init__(self, text, code=http.BAD_REQUEST):
147         self.text = text
148         self.code = code
149
150 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
151 # Internal Server Error, we either need to do that ICanHandleException trick,
152 # or make sure that childFactory returns a WebErrorResource (and never an
153 # actual exception). The latter is growing increasingly annoying.
154
155 def should_create_intermediate_directories(req):
156     t = get_arg(req, "t", "").strip()
157     return bool(req.method in ("PUT", "POST") and
158                 t not in ("delete", "rename", "rename-form", "check"))
159
160 def humanize_failure(f):
161     # return text, responsecode
162     if f.check(EmptyPathnameComponentError):
163         return ("The webapi does not allow empty pathname components, "
164                 "i.e. a double slash", http.BAD_REQUEST)
165     if f.check(ExistingChildError):
166         return ("There was already a child by that name, and you asked me "
167                 "to not replace it.", http.CONFLICT)
168     if f.check(NoSuchChildError):
169         name = f.value.args[0]
170         return ("No such child: %s" % name.encode("utf-8"), http.NOT_FOUND)
171     if f.check(NotEnoughSharesError):
172         t = ("NotEnoughSharesError: This indicates that some "
173              "servers were unavailable, or that shares have been "
174              "lost to server departure, hard drive failure, or disk "
175              "corruption. You should perform a filecheck on "
176              "this object to learn more.\n\nThe full error message is:\n"
177              "%s") % str(f.value)
178         return (t, http.GONE)
179     if f.check(NoSharesError):
180         t = ("NoSharesError: no shares could be found. "
181              "Zero shares usually indicates a corrupt URI, or that "
182              "no servers were connected, but it might also indicate "
183              "severe corruption. You should perform a filecheck on "
184              "this object to learn more.\n\nThe full error message is:\n"
185              "%s") % str(f.value)
186         return (t, http.GONE)
187     if f.check(UnrecoverableFileError):
188         t = ("UnrecoverableFileError: the directory (or mutable file) could "
189              "not be retrieved, because there were insufficient good shares. "
190              "This might indicate that no servers were connected, "
191              "insufficient servers were connected, the URI was corrupt, or "
192              "that shares have been lost due to server departure, hard drive "
193              "failure, or disk corruption. You should perform a filecheck on "
194              "this object to learn more.")
195         return (t, http.GONE)
196     if f.check(MustNotBeUnknownRWError):
197         name = f.value.args[1]
198         immutable = f.value.args[2]
199         if immutable:
200             t = ("MustNotBeUnknownRWError: an operation to add a child named "
201                  "'%s' to a directory was given an unknown cap in a write slot.\n"
202                  "If the cap is actually an immutable readcap, then using a "
203                  "webapi server that supports a later version of Tahoe may help.\n\n"
204                  "If you are using the webapi directly, then specifying an immutable "
205                  "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
206                  "omitting the write slot (rw_uri), would also work in this "
207                  "case.") % name.encode("utf-8")
208         else:
209             t = ("MustNotBeUnknownRWError: an operation to add a child named "
210                  "'%s' to a directory was given an unknown cap in a write slot.\n"
211                  "Using a webapi server that supports a later version of Tahoe "
212                  "may help.\n\n"
213                  "If you are using the webapi directly, specifying a readcap in "
214                  "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
215                  "writecap in the write slot if desired, would also work in this "
216                  "case.") % name.encode("utf-8")
217         return (t, http.BAD_REQUEST)
218     if f.check(MustBeDeepImmutableError):
219         name = f.value.args[1]
220         t = ("MustBeDeepImmutableError: a cap passed to this operation for "
221              "the child named '%s', needed to be immutable but was not. Either "
222              "the cap is being added to an immutable directory, or it was "
223              "originally retrieved from an immutable directory as an unknown "
224              "cap." % name.encode("utf-8"))
225         return (t, http.BAD_REQUEST)
226     if f.check(MustBeReadonlyError):
227         name = f.value.args[1]
228         t = ("MustBeReadonlyError: a cap passed to this operation for "
229              "the child named '%s', needed to be read-only but was not. "
230              "The cap is being passed in a read slot (ro_uri), or was retrieved "
231              "from a read slot as an unknown cap." % name.encode("utf-8"))
232         return (t, http.BAD_REQUEST)
233     if f.check(WebError):
234         return (f.value.text, f.value.code)
235     if f.check(FileTooLargeError):
236         return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
237     return (str(f), None)
238
239 class MyExceptionHandler(appserver.DefaultExceptionHandler):
240     def simple(self, ctx, text, code=http.BAD_REQUEST):
241         req = IRequest(ctx)
242         req.setResponseCode(code)
243         #req.responseHeaders.setRawHeaders("content-encoding", [])
244         #req.responseHeaders.setRawHeaders("content-disposition", [])
245         req.setHeader("content-type", "text/plain;charset=utf-8")
246         if isinstance(text, unicode):
247             text = text.encode("utf-8")
248         req.setHeader("content-length", str(len(text)))
249         req.write(text)
250         # TODO: consider putting the requested URL here
251         req.finishRequest(False)
252
253     def renderHTTP_exception(self, ctx, f):
254         try:
255             text, code = humanize_failure(f)
256         except:
257             log.msg("exception in humanize_failure")
258             log.msg("argument was %s" % (f,))
259             log.err()
260             text, code = str(f), None
261         if code is not None:
262             return self.simple(ctx, text, code)
263         if f.check(server.UnsupportedMethod):
264             # twisted.web.server.Request.render() has support for transforming
265             # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
266             # return code, but nevow does not.
267             req = IRequest(ctx)
268             method = req.method
269             return self.simple(ctx,
270                                "I don't know how to treat a %s request." % method,
271                                http.NOT_IMPLEMENTED)
272         req = IRequest(ctx)
273         accept = req.getHeader("accept")
274         if not accept:
275             accept = "*/*"
276         if "*/*" in accept or "text/*" in accept or "text/html" in accept:
277             super = appserver.DefaultExceptionHandler
278             return super.renderHTTP_exception(self, ctx, f)
279         # use plain text
280         traceback = f.getTraceback()
281         return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
282
283 class NeedOperationHandleError(WebError):
284     pass
285
286 class RenderMixin:
287
288     def renderHTTP(self, ctx):
289         request = IRequest(ctx)
290
291         # if we were using regular twisted.web Resources (and the regular
292         # twisted.web.server.Request object) then we could implement
293         # render_PUT and render_GET. But Nevow's request handler
294         # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
295         # some code from the Resource.render method that Nevow bypasses, to
296         # do the same thing.
297         m = getattr(self, 'render_' + request.method, None)
298         if not m:
299             from twisted.web.server import UnsupportedMethod
300             raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
301         return m(ctx)