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