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
14 class IOpHandleTable(Interface):
18 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
20 def boolean_of_arg(arg):
22 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
23 return arg.lower() in ("true", "t", "1", "on")
25 def parse_replace_arg(replace):
26 if replace.lower() == "only-files":
29 return boolean_of_arg(replace)
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)
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.
45 req = IRequest(ctx_or_req)
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)
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=)."""
63 data = simplejson.loads(children_json)
64 for (name, (ctype, propdict)) in data.iteritems():
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
77 def abbreviate_time(data):
83 return abbreviate.abbreviate_time(data)
87 return "%dms" % (1000*s)
89 return "%.1fms" % (1000*s)
90 return "%dus" % (1000000*s)
92 def abbreviate_rate(data):
93 # 21.8kBps, 554.4kBps 4.37MBps
98 return "%1.2fMBps" % (r/1000000)
100 return "%.1fkBps" % (r/1000)
103 def abbreviate_size(data):
104 # 21.8kB, 554.4kB 4.37MB
109 return "%1.2fGB" % (r/1000000000)
111 return "%1.2fMB" % (r/1000000)
113 return "%.1fkB" % (r/1000)
116 def plural(sequence_or_length):
117 if isinstance(sequence_or_length, int):
118 length = sequence_or_length
120 length = len(sequence_or_length)
125 def text_plain(text, ctx):
127 req.setHeader("content-type", "text/plain")
128 req.setHeader("content-length", len(text))
131 class WebError(Exception):
132 def __init__(self, text, code=http.BAD_REQUEST):
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.
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"))
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"
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"
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)
185 class MyExceptionHandler(appserver.DefaultExceptionHandler):
186 def simple(self, ctx, text, code=http.BAD_REQUEST):
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)))
196 # TODO: consider putting the requested URL here
197 req.finishRequest(False)
199 def renderHTTP_exception(self, ctx, f):
201 text, code = humanize_failure(f)
203 log.msg("exception in humanize_failure")
204 log.msg("argument was %s" % (f,))
206 text, code = str(f), 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.
215 return self.simple(ctx,
216 "I don't know how to treat a %s request." % method,
217 http.NOT_IMPLEMENTED)
219 accept = req.getHeader("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)
226 traceback = f.getTraceback()
227 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
229 class NeedOperationHandleError(WebError):
234 def renderHTTP(self, ctx):
235 request = IRequest(ctx)
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
243 m = getattr(self, 'render_' + request.method, None)
245 from twisted.web.server import UnsupportedMethod
246 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))