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
17 class IOpHandleTable(Interface):
21 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
23 def boolean_of_arg(arg):
25 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
26 return arg.lower() in ("true", "t", "1", "on")
28 def parse_replace_arg(replace):
29 if replace.lower() == "only-files":
32 return boolean_of_arg(replace)
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)
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.
48 req = IRequest(ctx_or_req)
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)
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"""
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)
78 def abbreviate_time(data):
84 return abbreviate.abbreviate_time(data)
88 return "%.0fms" % (1000*s)
90 return "%.1fms" % (1000*s)
91 return "%.0fus" % (1000000*s)
93 def compute_rate(bytes, seconds):
97 if seconds is None or seconds == 0:
100 # negative values don't make sense here
104 return 1.0 * bytes / seconds
106 def abbreviate_rate(data):
107 # 21.8kBps, 554.4kBps 4.37MBps
112 return "%1.2fMBps" % (r/1000000)
114 return "%.1fkBps" % (r/1000)
117 def abbreviate_size(data):
118 # 21.8kB, 554.4kB 4.37MB
123 return "%1.2fGB" % (r/1000000000)
125 return "%1.2fMB" % (r/1000000)
127 return "%.1fkB" % (r/1000)
130 def plural(sequence_or_length):
131 if isinstance(sequence_or_length, int):
132 length = sequence_or_length
134 length = len(sequence_or_length)
139 def text_plain(text, ctx):
141 req.setHeader("content-type", "text/plain")
142 req.setHeader("content-length", len(text))
145 class WebError(Exception):
146 def __init__(self, text, code=http.BAD_REQUEST):
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.
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"))
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"
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"
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]
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")
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 "
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)
239 class MyExceptionHandler(appserver.DefaultExceptionHandler):
240 def simple(self, ctx, text, code=http.BAD_REQUEST):
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)))
250 # TODO: consider putting the requested URL here
251 req.finishRequest(False)
253 def renderHTTP_exception(self, ctx, f):
255 text, code = humanize_failure(f)
257 log.msg("exception in humanize_failure")
258 log.msg("argument was %s" % (f,))
260 text, code = str(f), 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.
269 return self.simple(ctx,
270 "I don't know how to treat a %s request." % method,
271 http.NOT_IMPLEMENTED)
273 accept = req.getHeader("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)
280 traceback = f.getTraceback()
281 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
283 class NeedOperationHandleError(WebError):
288 def renderHTTP(self, ctx):
289 request = IRequest(ctx)
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
297 m = getattr(self, 'render_' + request.method, None)
299 from twisted.web.server import UnsupportedMethod
300 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))