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