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, quote_output
18 class IOpHandleTable(Interface):
22 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
24 def boolean_of_arg(arg):
26 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
27 return arg.lower() in ("true", "t", "1", "on")
29 def parse_replace_arg(replace):
30 if replace.lower() == "only-files":
33 return boolean_of_arg(replace)
35 def get_root(ctx_or_req):
36 req = IRequest(ctx_or_req)
37 # the addSlash=True gives us one extra (empty) segment
38 depth = len(req.prepath) + len(req.postpath) - 1
39 link = "/".join([".."] * depth)
42 def get_arg(ctx_or_req, argname, default=None, multiple=False):
43 """Extract an argument from either the query args (req.args) or the form
44 body fields (req.fields). If multiple=False, this returns a single value
45 (or the default, which defaults to None), and the query args take
46 precedence. If multiple=True, this returns a tuple of arguments (possibly
47 empty), starting with all those in the query args.
49 req = IRequest(ctx_or_req)
51 if argname in req.args:
52 results.extend(req.args[argname])
53 if req.fields and argname in req.fields:
54 results.append(req.fields[argname].value)
61 def convert_children_json(nodemaker, children_json):
62 """I convert the JSON output of GET?t=json into the dict-of-nodes input
63 to both dirnode.create_subdirectory() and
64 client.create_directory(initial_children=). This is used by
65 t=mkdir-with-children and t=mkdir-immutable"""
68 data = simplejson.loads(children_json)
69 for (namex, (ctype, propdict)) in data.iteritems():
70 namex = unicode(namex)
71 writecap = to_str(propdict.get("rw_uri"))
72 readcap = to_str(propdict.get("ro_uri"))
73 metadata = propdict.get("metadata", {})
74 # name= argument is just for error reporting
75 childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
76 children[namex] = (childnode, metadata)
79 def abbreviate_time(data):
85 return abbreviate.abbreviate_time(data)
89 return "%.0fms" % (1000*s)
91 return "%.1fms" % (1000*s)
92 return "%.0fus" % (1000000*s)
94 def compute_rate(bytes, seconds):
98 if seconds is None or seconds == 0:
101 # negative values don't make sense here
105 return 1.0 * bytes / seconds
107 def abbreviate_rate(data):
108 # 21.8kBps, 554.4kBps 4.37MBps
113 return "%1.2fMBps" % (r/1000000)
115 return "%.1fkBps" % (r/1000)
118 def abbreviate_size(data):
119 # 21.8kB, 554.4kB 4.37MB
124 return "%1.2fGB" % (r/1000000000)
126 return "%1.2fMB" % (r/1000000)
128 return "%.1fkB" % (r/1000)
131 def plural(sequence_or_length):
132 if isinstance(sequence_or_length, int):
133 length = sequence_or_length
135 length = len(sequence_or_length)
140 def text_plain(text, ctx):
142 req.setHeader("content-type", "text/plain")
143 req.setHeader("content-length", len(text))
146 class WebError(Exception):
147 def __init__(self, text, code=http.BAD_REQUEST):
151 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
152 # Internal Server Error, we either need to do that ICanHandleException trick,
153 # or make sure that childFactory returns a WebErrorResource (and never an
154 # actual exception). The latter is growing increasingly annoying.
156 def should_create_intermediate_directories(req):
157 t = get_arg(req, "t", "").strip()
158 return bool(req.method in ("PUT", "POST") and
159 t not in ("delete", "rename", "rename-form", "check"))
161 def humanize_failure(f):
162 # return text, responsecode
163 if f.check(EmptyPathnameComponentError):
164 return ("The webapi does not allow empty pathname components, "
165 "i.e. a double slash", http.BAD_REQUEST)
166 if f.check(ExistingChildError):
167 return ("There was already a child by that name, and you asked me "
168 "to not replace it.", http.CONFLICT)
169 if f.check(NoSuchChildError):
170 quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
171 return ("No such child: %s" % quoted_name, http.NOT_FOUND)
172 if f.check(NotEnoughSharesError):
173 t = ("NotEnoughSharesError: This indicates that some "
174 "servers were unavailable, or that shares have been "
175 "lost to server departure, hard drive failure, or disk "
176 "corruption. You should perform a filecheck on "
177 "this object to learn more.\n\nThe full error message is:\n"
179 return (t, http.GONE)
180 if f.check(NoSharesError):
181 t = ("NoSharesError: no shares could be found. "
182 "Zero shares usually indicates a corrupt URI, or that "
183 "no servers were connected, but it might also indicate "
184 "severe corruption. You should perform a filecheck on "
185 "this object to learn more.\n\nThe full error message is:\n"
187 return (t, http.GONE)
188 if f.check(UnrecoverableFileError):
189 t = ("UnrecoverableFileError: the directory (or mutable file) could "
190 "not be retrieved, because there were insufficient good shares. "
191 "This might indicate that no servers were connected, "
192 "insufficient servers were connected, the URI was corrupt, or "
193 "that shares have been lost due to server departure, hard drive "
194 "failure, or disk corruption. You should perform a filecheck on "
195 "this object to learn more.")
196 return (t, http.GONE)
197 if f.check(MustNotBeUnknownRWError):
198 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
199 immutable = f.value.args[2]
201 t = ("MustNotBeUnknownRWError: an operation to add a child named "
202 "%s to a directory was given an unknown cap in a write slot.\n"
203 "If the cap is actually an immutable readcap, then using a "
204 "webapi server that supports a later version of Tahoe may help.\n\n"
205 "If you are using the webapi directly, then specifying an immutable "
206 "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
207 "omitting the write slot (rw_uri), would also work in this "
208 "case.") % quoted_name
210 t = ("MustNotBeUnknownRWError: an operation to add a child named "
211 "%s to a directory was given an unknown cap in a write slot.\n"
212 "Using a webapi server that supports a later version of Tahoe "
214 "If you are using the webapi directly, specifying a readcap in "
215 "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
216 "writecap in the write slot if desired, would also work in this "
217 "case.") % quoted_name
218 return (t, http.BAD_REQUEST)
219 if f.check(MustBeDeepImmutableError):
220 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
221 t = ("MustBeDeepImmutableError: a cap passed to this operation for "
222 "the child named %s, needed to be immutable but was not. Either "
223 "the cap is being added to an immutable directory, or it was "
224 "originally retrieved from an immutable directory as an unknown "
225 "cap.") % quoted_name
226 return (t, http.BAD_REQUEST)
227 if f.check(MustBeReadonlyError):
228 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
229 t = ("MustBeReadonlyError: a cap passed to this operation for "
230 "the child named '%s', needed to be read-only but was not. "
231 "The cap is being passed in a read slot (ro_uri), or was retrieved "
232 "from a read slot as an unknown cap.") % quoted_name
233 return (t, http.BAD_REQUEST)
234 if f.check(WebError):
235 return (f.value.text, f.value.code)
236 if f.check(FileTooLargeError):
237 return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
238 return (str(f), None)
240 class MyExceptionHandler(appserver.DefaultExceptionHandler):
241 def simple(self, ctx, text, code=http.BAD_REQUEST):
243 req.setResponseCode(code)
244 #req.responseHeaders.setRawHeaders("content-encoding", [])
245 #req.responseHeaders.setRawHeaders("content-disposition", [])
246 req.setHeader("content-type", "text/plain;charset=utf-8")
247 if isinstance(text, unicode):
248 text = text.encode("utf-8")
249 req.setHeader("content-length", str(len(text)))
251 # TODO: consider putting the requested URL here
252 req.finishRequest(False)
254 def renderHTTP_exception(self, ctx, f):
256 text, code = humanize_failure(f)
258 log.msg("exception in humanize_failure")
259 log.msg("argument was %s" % (f,))
261 text, code = str(f), None
263 return self.simple(ctx, text, code)
264 if f.check(server.UnsupportedMethod):
265 # twisted.web.server.Request.render() has support for transforming
266 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
267 # return code, but nevow does not.
270 return self.simple(ctx,
271 "I don't know how to treat a %s request." % method,
272 http.NOT_IMPLEMENTED)
274 accept = req.getHeader("accept")
277 if "*/*" in accept or "text/*" in accept or "text/html" in accept:
278 super = appserver.DefaultExceptionHandler
279 return super.renderHTTP_exception(self, ctx, f)
281 traceback = f.getTraceback()
282 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
284 class NeedOperationHandleError(WebError):
289 def renderHTTP(self, ctx):
290 request = IRequest(ctx)
292 # if we were using regular twisted.web Resources (and the regular
293 # twisted.web.server.Request object) then we could implement
294 # render_PUT and render_GET. But Nevow's request handler
295 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
296 # some code from the Resource.render method that Nevow bypasses, to
298 m = getattr(self, 'render_' + request.method, None)
300 from twisted.web.server import UnsupportedMethod
301 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))