]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/root.py
web: factor out identical renderHTTP methods
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / root.py
1
2 import time
3
4 from twisted.internet import address
5 from twisted.web import http
6 from nevow import rend, url, tags as T
7 from nevow.inevow import IRequest
8 from nevow.static import File as nevow_File # TODO: merge with static.File?
9 from nevow.util import resource_filename
10 from formless import webform
11
12 import allmydata # to display import path
13 from allmydata import get_package_versions_string
14 from allmydata import provisioning
15 from allmydata.util import idlib
16 from allmydata.interfaces import IFileNode
17 from allmydata.web import filenode, directory, unlinked, status
18 from allmydata.web.common import abbreviate_size, IClient, getxmlfile, \
19      WebError, get_arg, RenderMixin
20
21
22
23 class URIHandler(RenderMixin, rend.Page):
24     # I live at /uri . There are several operations defined on /uri itself,
25     # mostly involed with creation of unlinked files and directories.
26
27     def render_GET(self, ctx):
28         req = IRequest(ctx)
29         uri = get_arg(req, "uri", None)
30         if uri is None:
31             raise WebError("GET /uri requires uri=")
32         there = url.URL.fromContext(ctx)
33         there = there.clear("uri")
34         # I thought about escaping the childcap that we attach to the URL
35         # here, but it seems that nevow does that for us.
36         there = there.child(uri)
37         return there
38
39     def render_PUT(self, ctx):
40         req = IRequest(ctx)
41         # either "PUT /uri" to create an unlinked file, or
42         # "PUT /uri?t=mkdir" to create an unlinked directory
43         t = get_arg(req, "t", "").strip()
44         if t == "":
45             mutable = bool(get_arg(req, "mutable", "").strip())
46             if mutable:
47                 return unlinked.PUTUnlinkedSSK(ctx)
48             else:
49                 return unlinked.PUTUnlinkedCHK(ctx)
50         if t == "mkdir":
51             return unlinked.PUTUnlinkedCreateDirectory(ctx)
52         errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
53                   "and POST?t=mkdir")
54         raise WebError(errmsg, http.BAD_REQUEST)
55
56     def render_POST(self, ctx):
57         # "POST /uri?t=upload&file=newfile" to upload an
58         # unlinked file or "POST /uri?t=mkdir" to create a
59         # new directory
60         req = IRequest(ctx)
61         t = get_arg(req, "t", "").strip()
62         if t in ("", "upload"):
63             mutable = bool(get_arg(req, "mutable", "").strip())
64             if mutable:
65                 return unlinked.POSTUnlinkedSSK(ctx)
66             else:
67                 return unlinked.POSTUnlinkedCHK(ctx)
68         if t == "mkdir":
69             return unlinked.POSTUnlinkedCreateDirectory(ctx)
70         errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
71                   "and POST?t=mkdir")
72         raise WebError(errmsg, http.BAD_REQUEST)
73
74     def childFactory(self, ctx, name):
75         # 'name' is expected to be a URI
76         client = IClient(ctx)
77         try:
78             node = client.create_node_from_uri(name)
79             return directory.make_handler_for(node)
80         except (TypeError, AssertionError):
81             raise WebError("'%s' is not a valid file- or directory- cap"
82                            % name)
83
84 class FileHandler(rend.Page):
85     # I handle /file/$FILECAP[/IGNORED] , which provides a URL from which a
86     # file can be downloaded correctly by tools like "wget".
87
88     def childFactory(self, ctx, name):
89         req = IRequest(ctx)
90         if req.method not in ("GET", "HEAD"):
91             raise WebError("/file can only be used with GET or HEAD")
92         # 'name' must be a file URI
93         client = IClient(ctx)
94         try:
95             node = client.create_node_from_uri(name)
96         except (TypeError, AssertionError):
97             raise WebError("'%s' is not a valid file- or directory- cap"
98                            % name)
99         if not IFileNode.providedBy(node):
100             raise WebError("'%s' is not a file-cap" % name)
101         return filenode.FileNodeDownloadHandler(node)
102
103     def renderHTTP(self, ctx):
104         raise WebError("/file must be followed by a file-cap and a name",
105                        http.NOT_FOUND)
106
107 class Root(rend.Page):
108
109     addSlash = True
110     docFactory = getxmlfile("welcome.xhtml")
111
112     child_uri = URIHandler()
113     child_file = FileHandler()
114     child_named = FileHandler()
115
116     child_webform_css = webform.defaultCSS
117     child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
118
119     child_provisioning = provisioning.ProvisioningTool()
120     child_status = status.Status()
121     child_helper_status = status.HelperStatus()
122     child_statistics = status.Statistics()
123
124     def data_version(self, ctx, data):
125         return get_package_versions_string()
126     def data_import_path(self, ctx, data):
127         return str(allmydata)
128     def data_my_nodeid(self, ctx, data):
129         return idlib.nodeid_b2a(IClient(ctx).nodeid)
130
131     def render_services(self, ctx, data):
132         ul = T.ul()
133         client = IClient(ctx)
134         try:
135             ss = client.getServiceNamed("storage")
136             allocated_s = abbreviate_size(ss.allocated_size())
137             allocated = "about %s allocated" % allocated_s
138             sizelimit = "no size limit"
139             if ss.sizelimit is not None:
140                 sizelimit = "size limit is %s" % abbreviate_size(ss.sizelimit)
141             ul[T.li["Storage Server: %s, %s" % (allocated, sizelimit)]]
142         except KeyError:
143             ul[T.li["Not running storage server"]]
144
145         try:
146             h = client.getServiceNamed("helper")
147             stats = h.get_stats()
148             active_uploads = stats["chk_upload_helper.active_uploads"]
149             ul[T.li["Helper: %d active uploads" % (active_uploads,)]]
150         except KeyError:
151             ul[T.li["Not running helper"]]
152
153         return ctx.tag[ul]
154
155     def data_introducer_furl(self, ctx, data):
156         return IClient(ctx).introducer_furl
157     def data_connected_to_introducer(self, ctx, data):
158         if IClient(ctx).connected_to_introducer():
159             return "yes"
160         return "no"
161
162     def data_helper_furl(self, ctx, data):
163         try:
164             uploader = IClient(ctx).getServiceNamed("uploader")
165         except KeyError:
166             return None
167         furl, connected = uploader.get_helper_info()
168         return furl
169     def data_connected_to_helper(self, ctx, data):
170         try:
171             uploader = IClient(ctx).getServiceNamed("uploader")
172         except KeyError:
173             return "no" # we don't even have an Uploader
174         furl, connected = uploader.get_helper_info()
175         if connected:
176             return "yes"
177         return "no"
178
179     def data_known_storage_servers(self, ctx, data):
180         ic = IClient(ctx).introducer_client
181         servers = [c
182                    for c in ic.get_all_connectors().values()
183                    if c.service_name == "storage"]
184         return len(servers)
185
186     def data_connected_storage_servers(self, ctx, data):
187         ic = IClient(ctx).introducer_client
188         return len(ic.get_all_connections_for("storage"))
189
190     def data_services(self, ctx, data):
191         ic = IClient(ctx).introducer_client
192         c = [ (service_name, nodeid, rsc)
193               for (nodeid, service_name), rsc
194               in ic.get_all_connectors().items() ]
195         c.sort()
196         return c
197
198     def render_service_row(self, ctx, data):
199         (service_name, nodeid, rsc) = data
200         ctx.fillSlots("peerid", "%s %s" % (idlib.nodeid_b2a(nodeid),
201                                            rsc.nickname))
202         if rsc.rref:
203             rhost = rsc.remote_host
204             if nodeid == IClient(ctx).nodeid:
205                 rhost_s = "(loopback)"
206             elif isinstance(rhost, address.IPv4Address):
207                 rhost_s = "%s:%d" % (rhost.host, rhost.port)
208             else:
209                 rhost_s = str(rhost)
210             connected = "Yes: to " + rhost_s
211             since = rsc.last_connect_time
212         else:
213             connected = "No"
214             since = rsc.last_loss_time
215
216         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
217         ctx.fillSlots("connected", connected)
218         ctx.fillSlots("since", time.strftime(TIME_FORMAT, time.localtime(since)))
219         ctx.fillSlots("announced", time.strftime(TIME_FORMAT,
220                                                  time.localtime(rsc.announcement_time)))
221         ctx.fillSlots("version", rsc.version)
222         ctx.fillSlots("service_name", rsc.service_name)
223
224         return ctx.tag
225
226     def render_download_form(self, ctx, data):
227         # this is a form where users can download files by URI
228         form = T.form(action="uri", method="get",
229                       enctype="multipart/form-data")[
230             T.fieldset[
231             T.legend(class_="freeform-form-label")["Download a file"],
232             "URI to download: ",
233             T.input(type="text", name="uri"), " ",
234             "Filename to download as: ",
235             T.input(type="text", name="filename"), " ",
236             T.input(type="submit", value="Download!"),
237             ]]
238         return T.div[form]
239
240     def render_view_form(self, ctx, data):
241         # this is a form where users can download files by URI, or jump to a
242         # named directory
243         form = T.form(action="uri", method="get",
244                       enctype="multipart/form-data")[
245             T.fieldset[
246             T.legend(class_="freeform-form-label")["View a file or directory"],
247             "URI to view: ",
248             T.input(type="text", name="uri"), " ",
249             T.input(type="submit", value="View!"),
250             ]]
251         return T.div[form]
252
253     def render_upload_form(self, ctx, data):
254         # this is a form where users can upload unlinked files
255         form = T.form(action="uri", method="post",
256                       enctype="multipart/form-data")[
257             T.fieldset[
258             T.legend(class_="freeform-form-label")["Upload a file"],
259             "Choose a file: ",
260             T.input(type="file", name="file", class_="freeform-input-file"),
261             T.input(type="hidden", name="t", value="upload"),
262             " Mutable?:", T.input(type="checkbox", name="mutable"),
263             T.input(type="submit", value="Upload!"),
264             ]]
265         return T.div[form]
266
267     def render_mkdir_form(self, ctx, data):
268         # this is a form where users can create new directories
269         form = T.form(action="uri", method="post",
270                       enctype="multipart/form-data")[
271             T.fieldset[
272             T.legend(class_="freeform-form-label")["Create a directory"],
273             T.input(type="hidden", name="t", value="mkdir"),
274             T.input(type="hidden", name="redirect_to_result", value="true"),
275             T.input(type="submit", value="Create Directory!"),
276             ]]
277         return T.div[form]
278