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, \
12 from allmydata.mutable.common import UnrecoverableFileError
13 from allmydata.util import abbreviate # TODO: consolidate
15 class IOpHandleTable(Interface):
19 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
21 def boolean_of_arg(arg):
23 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
24 return arg.lower() in ("true", "t", "1", "on")
26 def parse_replace_arg(replace):
27 if replace.lower() == "only-files":
30 return boolean_of_arg(replace)
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)
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.
46 req = IRequest(ctx_or_req)
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)
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"""
65 data = simplejson.loads(children_json)
66 for (name, (ctype, propdict)) in data.iteritems():
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)
79 def abbreviate_time(data):
85 return abbreviate.abbreviate_time(data)
89 return "%dms" % (1000*s)
91 return "%.1fms" % (1000*s)
92 return "%dus" % (1000000*s)
94 def abbreviate_rate(data):
95 # 21.8kBps, 554.4kBps 4.37MBps
100 return "%1.2fMBps" % (r/1000000)
102 return "%.1fkBps" % (r/1000)
105 def abbreviate_size(data):
106 # 21.8kB, 554.4kB 4.37MB
111 return "%1.2fGB" % (r/1000000000)
113 return "%1.2fMB" % (r/1000000)
115 return "%.1fkB" % (r/1000)
118 def plural(sequence_or_length):
119 if isinstance(sequence_or_length, int):
120 length = sequence_or_length
122 length = len(sequence_or_length)
127 def text_plain(text, ctx):
129 req.setHeader("content-type", "text/plain")
130 req.setHeader("content-length", len(text))
133 class WebError(Exception):
134 def __init__(self, text, code=http.BAD_REQUEST):
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.
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"))
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"
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"
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)
191 class MyExceptionHandler(appserver.DefaultExceptionHandler):
192 def simple(self, ctx, text, code=http.BAD_REQUEST):
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)))
202 # TODO: consider putting the requested URL here
203 req.finishRequest(False)
205 def renderHTTP_exception(self, ctx, f):
207 text, code = humanize_failure(f)
209 log.msg("exception in humanize_failure")
210 log.msg("argument was %s" % (f,))
212 text, code = str(f), 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.
221 return self.simple(ctx,
222 "I don't know how to treat a %s request." % method,
223 http.NOT_IMPLEMENTED)
225 accept = req.getHeader("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)
232 traceback = f.getTraceback()
233 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
235 class NeedOperationHandleError(WebError):
240 def renderHTTP(self, ctx):
241 request = IRequest(ctx)
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
249 m = getattr(self, 'render_' + request.method, None)
251 from twisted.web.server import UnsupportedMethod
252 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))