]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/status.py
0da799116b79e4952baf36e188685ff6caa2a067
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / status.py
1
2 import time, pprint, itertools
3 import simplejson
4 from twisted.internet import defer
5 from nevow import rend, inevow, tags as T
6 from allmydata.util import base32, idlib
7 from allmydata.util.time_format import format_time
8 from allmydata.web.common import getxmlfile, get_arg, \
9      abbreviate_time, abbreviate_rate, abbreviate_size, plural, compute_rate
10 from allmydata.interfaces import IUploadStatus, IDownloadStatus, \
11      IPublishStatus, IRetrieveStatus, IServermapUpdaterStatus
12
13 class RateAndTimeMixin:
14
15     def render_time(self, ctx, data):
16         return abbreviate_time(data)
17
18     def render_rate(self, ctx, data):
19         return abbreviate_rate(data)
20
21 class UploadResultsRendererMixin(RateAndTimeMixin):
22     # this requires a method named 'upload_results'
23
24     def render_pushed_shares(self, ctx, data):
25         d = self.upload_results()
26         d.addCallback(lambda res: res.get_pushed_shares())
27         return d
28
29     def render_preexisting_shares(self, ctx, data):
30         d = self.upload_results()
31         d.addCallback(lambda res: res.get_preexisting_shares())
32         return d
33
34     def render_sharemap(self, ctx, data):
35         d = self.upload_results()
36         d.addCallback(lambda res: res.get_sharemap())
37         def _render(sharemap):
38             if sharemap is None:
39                 return "None"
40             l = T.ul()
41             for shnum, servers in sorted(sharemap.items()):
42                 server_names = ', '.join([s.get_name() for s in servers])
43                 l[T.li["%d -> placed on [%s]" % (shnum, server_names)]]
44             return l
45         d.addCallback(_render)
46         return d
47
48     def render_servermap(self, ctx, data):
49         d = self.upload_results()
50         d.addCallback(lambda res: res.get_servermap())
51         def _render(servermap):
52             if servermap is None:
53                 return "None"
54             l = T.ul()
55             for server, shnums in sorted(servermap.items()):
56                 shares_s = ",".join(["#%d" % shnum for shnum in shnums])
57                 l[T.li["[%s] got share%s: %s" % (server.get_name(),
58                                                  plural(shnums), shares_s)]]
59             return l
60         d.addCallback(_render)
61         return d
62
63     def data_file_size(self, ctx, data):
64         d = self.upload_results()
65         d.addCallback(lambda res: res.get_file_size())
66         return d
67
68     def _get_time(self, name):
69         d = self.upload_results()
70         d.addCallback(lambda res: res.get_timings().get(name))
71         return d
72
73     def data_time_total(self, ctx, data):
74         return self._get_time("total")
75
76     def data_time_storage_index(self, ctx, data):
77         return self._get_time("storage_index")
78
79     def data_time_contacting_helper(self, ctx, data):
80         return self._get_time("contacting_helper")
81
82     def data_time_cumulative_fetch(self, ctx, data):
83         return self._get_time("cumulative_fetch")
84
85     def data_time_helper_total(self, ctx, data):
86         return self._get_time("helper_total")
87
88     def data_time_peer_selection(self, ctx, data):
89         return self._get_time("peer_selection")
90
91     def data_time_total_encode_and_push(self, ctx, data):
92         return self._get_time("total_encode_and_push")
93
94     def data_time_cumulative_encoding(self, ctx, data):
95         return self._get_time("cumulative_encoding")
96
97     def data_time_cumulative_sending(self, ctx, data):
98         return self._get_time("cumulative_sending")
99
100     def data_time_hashes_and_close(self, ctx, data):
101         return self._get_time("hashes_and_close")
102
103     def _get_rate(self, name):
104         d = self.upload_results()
105         def _convert(r):
106             file_size = r.get_file_size()
107             time = r.get_timings().get(name)
108             return compute_rate(file_size, time)
109         d.addCallback(_convert)
110         return d
111
112     def data_rate_total(self, ctx, data):
113         return self._get_rate("total")
114
115     def data_rate_storage_index(self, ctx, data):
116         return self._get_rate("storage_index")
117
118     def data_rate_encode(self, ctx, data):
119         return self._get_rate("cumulative_encoding")
120
121     def data_rate_push(self, ctx, data):
122         return self._get_rate("cumulative_sending")
123
124     def data_rate_encode_and_push(self, ctx, data):
125         d = self.upload_results()
126         def _convert(r):
127             file_size = r.get_file_size()
128             time1 = r.get_timings().get("cumulative_encoding")
129             time2 = r.get_timings().get("cumulative_sending")
130             if (time1 is None or time2 is None):
131                 return None
132             else:
133                 return compute_rate(file_size, time1+time2)
134         d.addCallback(_convert)
135         return d
136
137     def data_rate_ciphertext_fetch(self, ctx, data):
138         d = self.upload_results()
139         def _convert(r):
140             fetch_size = r.get_ciphertext_fetched()
141             time = r.get_timings().get("cumulative_fetch")
142             return compute_rate(fetch_size, time)
143         d.addCallback(_convert)
144         return d
145
146 class UploadStatusPage(UploadResultsRendererMixin, rend.Page):
147     docFactory = getxmlfile("upload-status.xhtml")
148
149     def __init__(self, data):
150         rend.Page.__init__(self, data)
151         self.upload_status = data
152
153     def upload_results(self):
154         return defer.maybeDeferred(self.upload_status.get_results)
155
156     def render_results(self, ctx, data):
157         d = self.upload_results()
158         def _got_results(results):
159             if results:
160                 return ctx.tag
161             return ""
162         d.addCallback(_got_results)
163         return d
164
165     def render_started(self, ctx, data):
166         started_s = format_time(time.localtime(data.get_started()))
167         return started_s
168
169     def render_si(self, ctx, data):
170         si_s = base32.b2a_or_none(data.get_storage_index())
171         if si_s is None:
172             si_s = "(None)"
173         return si_s
174
175     def render_helper(self, ctx, data):
176         return {True: "Yes",
177                 False: "No"}[data.using_helper()]
178
179     def render_total_size(self, ctx, data):
180         size = data.get_size()
181         if size is None:
182             return "(unknown)"
183         return size
184
185     def render_progress_hash(self, ctx, data):
186         progress = data.get_progress()[0]
187         # TODO: make an ascii-art bar
188         return "%.1f%%" % (100.0 * progress)
189
190     def render_progress_ciphertext(self, ctx, data):
191         progress = data.get_progress()[1]
192         # TODO: make an ascii-art bar
193         return "%.1f%%" % (100.0 * progress)
194
195     def render_progress_encode_push(self, ctx, data):
196         progress = data.get_progress()[2]
197         # TODO: make an ascii-art bar
198         return "%.1f%%" % (100.0 * progress)
199
200     def render_status(self, ctx, data):
201         return data.get_status()
202
203 class DownloadResultsRendererMixin(RateAndTimeMixin):
204     # this requires a method named 'download_results'
205
206     def render_servermap(self, ctx, data):
207         d = self.download_results()
208         d.addCallback(lambda res: res.servermap)
209         def _render(servermap):
210             if servermap is None:
211                 return "None"
212             l = T.ul()
213             for peerid in sorted(servermap.keys()):
214                 peerid_s = idlib.shortnodeid_b2a(peerid)
215                 shares_s = ",".join(["#%d" % shnum
216                                      for shnum in servermap[peerid]])
217                 l[T.li["[%s] has share%s: %s" % (peerid_s,
218                                                  plural(servermap[peerid]),
219                                                  shares_s)]]
220             return l
221         d.addCallback(_render)
222         return d
223
224     def render_servers_used(self, ctx, data):
225         d = self.download_results()
226         d.addCallback(lambda res: res.servers_used)
227         def _got(servers_used):
228             if not servers_used:
229                 return ""
230             peerids_s = ", ".join(["[%s]" % idlib.shortnodeid_b2a(peerid)
231                                    for peerid in servers_used])
232             return T.li["Servers Used: ", peerids_s]
233         d.addCallback(_got)
234         return d
235
236     def render_problems(self, ctx, data):
237         d = self.download_results()
238         d.addCallback(lambda res: res.server_problems)
239         def _got(server_problems):
240             if not server_problems:
241                 return ""
242             l = T.ul()
243             for peerid in sorted(server_problems.keys()):
244                 peerid_s = idlib.shortnodeid_b2a(peerid)
245                 l[T.li["[%s]: %s" % (peerid_s, server_problems[peerid])]]
246             return T.li["Server Problems:", l]
247         d.addCallback(_got)
248         return d
249
250     def data_file_size(self, ctx, data):
251         d = self.download_results()
252         d.addCallback(lambda res: res.file_size)
253         return d
254
255     def _get_time(self, name):
256         d = self.download_results()
257         d.addCallback(lambda res: res.timings.get(name))
258         return d
259
260     def data_time_total(self, ctx, data):
261         return self._get_time("total")
262
263     def data_time_peer_selection(self, ctx, data):
264         return self._get_time("peer_selection")
265
266     def data_time_uri_extension(self, ctx, data):
267         return self._get_time("uri_extension")
268
269     def data_time_hashtrees(self, ctx, data):
270         return self._get_time("hashtrees")
271
272     def data_time_segments(self, ctx, data):
273         return self._get_time("segments")
274
275     def data_time_cumulative_fetch(self, ctx, data):
276         return self._get_time("cumulative_fetch")
277
278     def data_time_cumulative_decode(self, ctx, data):
279         return self._get_time("cumulative_decode")
280
281     def data_time_cumulative_decrypt(self, ctx, data):
282         return self._get_time("cumulative_decrypt")
283
284     def data_time_paused(self, ctx, data):
285         return self._get_time("paused")
286
287     def _get_rate(self, name):
288         d = self.download_results()
289         def _convert(r):
290             file_size = r.file_size
291             time = r.timings.get(name)
292             return compute_rate(file_size, time)
293         d.addCallback(_convert)
294         return d
295
296     def data_rate_total(self, ctx, data):
297         return self._get_rate("total")
298
299     def data_rate_segments(self, ctx, data):
300         return self._get_rate("segments")
301
302     def data_rate_fetch(self, ctx, data):
303         return self._get_rate("cumulative_fetch")
304
305     def data_rate_decode(self, ctx, data):
306         return self._get_rate("cumulative_decode")
307
308     def data_rate_decrypt(self, ctx, data):
309         return self._get_rate("cumulative_decrypt")
310
311     def render_server_timings(self, ctx, data):
312         d = self.download_results()
313         d.addCallback(lambda res: res.timings.get("fetch_per_server"))
314         def _render(per_server):
315             if per_server is None:
316                 return ""
317             l = T.ul()
318             for peerid in sorted(per_server.keys()):
319                 peerid_s = idlib.shortnodeid_b2a(peerid)
320                 times_s = ", ".join([self.render_time(None, t)
321                                      for t in per_server[peerid]])
322                 l[T.li["[%s]: %s" % (peerid_s, times_s)]]
323             return T.li["Per-Server Segment Fetch Response Times: ", l]
324         d.addCallback(_render)
325         return d
326
327 class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
328     docFactory = getxmlfile("download-status.xhtml")
329
330     def __init__(self, data):
331         rend.Page.__init__(self, data)
332         self.download_status = data
333
334     def child_timeline(self, ctx):
335         return DownloadStatusTimelinePage(self.download_status)
336
337     def download_results(self):
338         return defer.maybeDeferred(self.download_status.get_results)
339
340     def relative_time(self, t):
341         if t is None:
342             return t
343         if self.download_status.first_timestamp is not None:
344             return t - self.download_status.first_timestamp
345         return t
346     def short_relative_time(self, t):
347         t = self.relative_time(t)
348         if t is None:
349             return ""
350         return "+%.6fs" % t
351
352     def _find_overlap(self, events, start_key, end_key):
353         # given a list of event dicts, return a new list in which each event
354         # has an extra "row" key (an int, starting at 0), and if appropriate
355         # a "serverid" key (ascii-encoded server id), replacing the "server"
356         # key. This is a hint to our JS frontend about how to overlap the
357         # parts of the graph it is drawing.
358
359         # we must always make a copy, since we're going to be adding keys
360         # and don't want to change the original objects. If we're
361         # stringifying serverids, we'll also be changing the serverid keys.
362         new_events = []
363         rows = []
364         for ev in events:
365             ev = ev.copy()
366             if ev.has_key('server'):
367                 ev["serverid"] = ev["server"].get_longname()
368                 del ev["server"]
369             # find an empty slot in the rows
370             free_slot = None
371             for row,finished in enumerate(rows):
372                 if finished is not None:
373                     if ev[start_key] > finished:
374                         free_slot = row
375                         break
376             if free_slot is None:
377                 free_slot = len(rows)
378                 rows.append(ev[end_key])
379             else:
380                 rows[free_slot] = ev[end_key]
381             ev["row"] = free_slot
382             new_events.append(ev)
383         return new_events
384
385     def _find_overlap_requests(self, events):
386         """We compute a three-element 'row tuple' for each event: (serverid,
387         shnum, row). All elements are ints. The first is a mapping from
388         serverid to group number, the second is a mapping from shnum to
389         subgroup number. The third is a row within the subgroup.
390
391         We also return a list of lists of rowcounts, so renderers can decide
392         how much vertical space to give to each row.
393         """
394
395         serverid_to_group = {}
396         groupnum_to_rows = {} # maps groupnum to a table of rows. Each table
397                               # is a list with an element for each row number
398                               # (int starting from 0) that contains a
399                               # finish_time, indicating that the row is empty
400                               # beyond that time. If finish_time is None, it
401                               # indicate a response that has not yet
402                               # completed, so the row cannot be reused.
403         new_events = []
404         for ev in events:
405             # DownloadStatus promises to give us events in temporal order
406             ev = ev.copy()
407             ev["serverid"] = ev["server"].get_longname()
408             del ev["server"]
409             if ev["serverid"] not in serverid_to_group:
410                 groupnum = len(serverid_to_group)
411                 serverid_to_group[ev["serverid"]] = groupnum
412             groupnum = serverid_to_group[ev["serverid"]]
413             if groupnum not in groupnum_to_rows:
414                 groupnum_to_rows[groupnum] = []
415             rows = groupnum_to_rows[groupnum]
416             # find an empty slot in the rows
417             free_slot = None
418             for row,finished in enumerate(rows):
419                 if finished is not None:
420                     if ev["start_time"] > finished:
421                         free_slot = row
422                         break
423             if free_slot is None:
424                 free_slot = len(rows)
425                 rows.append(ev["finish_time"])
426             else:
427                 rows[free_slot] = ev["finish_time"]
428             ev["row"] = (groupnum, free_slot)
429             new_events.append(ev)
430         del groupnum
431         # maybe also return serverid_to_group, groupnum_to_rows, and some
432         # indication of the highest finish_time
433         #
434         # actually, return the highest rownum for each groupnum
435         highest_rownums = [len(groupnum_to_rows[groupnum])
436                            for groupnum in range(len(serverid_to_group))]
437         return new_events, highest_rownums
438
439     def child_event_json(self, ctx):
440         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
441         data = { } # this will be returned to the GET
442         ds = self.download_status
443
444         data["misc"] = self._find_overlap(ds.misc_events,
445                                           "start_time", "finish_time")
446         data["read"] = self._find_overlap(ds.read_events,
447                                           "start_time", "finish_time")
448         data["segment"] = self._find_overlap(ds.segment_events,
449                                              "start_time", "finish_time")
450         # TODO: overlap on DYHB isn't very useful, and usually gets in the
451         # way. So don't do it.
452         data["dyhb"] = self._find_overlap(ds.dyhb_requests,
453                                           "start_time", "finish_time")
454         data["block"],data["block_rownums"] = self._find_overlap_requests(ds.block_requests)
455
456         server_info = {} # maps longname to {num,color,short}
457         server_shortnames = {} # maps servernum to shortname
458         for d_ev in ds.dyhb_requests:
459             s = d_ev["server"]
460             longname = s.get_longname()
461             if longname not in server_info:
462                 num = len(server_info)
463                 server_info[longname] = {"num": num,
464                                          "color": self.color(s),
465                                          "short": s.get_name() }
466                 server_shortnames[str(num)] = s.get_name()
467
468         data["server_info"] = server_info
469         data["num_serverids"] = len(server_info)
470         # we'd prefer the keys of serverids[] to be ints, but this is JSON,
471         # so they get converted to strings. Stupid javascript.
472         data["serverids"] = server_shortnames
473         data["bounds"] = {"min": ds.first_timestamp, "max": ds.last_timestamp}
474         return simplejson.dumps(data, indent=1) + "\n"
475
476     def render_timeline_link(self, ctx, data):
477         from nevow import url
478         return T.a(href=url.URL.fromContext(ctx).child("timeline"))["timeline"]
479
480     def _rate_and_time(self, bytes, seconds):
481         time_s = self.render_time(None, seconds)
482         if seconds != 0:
483             rate = self.render_rate(None, 1.0 * bytes / seconds)
484             return T.span(title=rate)[time_s]
485         return T.span[time_s]
486
487     def render_events(self, ctx, data):
488         if not self.download_status.storage_index:
489             return
490         srt = self.short_relative_time
491         l = T.div()
492
493         t = T.table(align="left", class_="status-download-events")
494         t[T.tr[T.th["serverid"], T.th["sent"], T.th["received"],
495                T.th["shnums"], T.th["RTT"]]]
496         for d_ev in self.download_status.dyhb_requests:
497             server = d_ev["server"]
498             sent = d_ev["start_time"]
499             shnums = d_ev["response_shnums"]
500             received = d_ev["finish_time"]
501             rtt = None
502             if received is not None:
503                 rtt = received - sent
504             if not shnums:
505                 shnums = ["-"]
506             t[T.tr(style="background: %s" % self.color(server))[
507                 [T.td[server.get_name()], T.td[srt(sent)], T.td[srt(received)],
508                  T.td[",".join([str(shnum) for shnum in shnums])],
509                  T.td[self.render_time(None, rtt)],
510                  ]]]
511
512         l[T.h2["DYHB Requests:"], t]
513         l[T.br(clear="all")]
514
515         t = T.table(align="left",class_="status-download-events")
516         t[T.tr[T.th["range"], T.th["start"], T.th["finish"], T.th["got"],
517                T.th["time"], T.th["decrypttime"], T.th["pausedtime"],
518                T.th["speed"]]]
519         for r_ev in self.download_status.read_events:
520             start = r_ev["start"]
521             length = r_ev["length"]
522             bytes = r_ev["bytes_returned"]
523             decrypt_time = ""
524             if bytes:
525                 decrypt_time = self._rate_and_time(bytes, r_ev["decrypt_time"])
526             speed, rtt = "",""
527             if r_ev["finish_time"] is not None:
528                 rtt = r_ev["finish_time"] - r_ev["start_time"] - r_ev["paused_time"]
529                 speed = self.render_rate(None, compute_rate(bytes, rtt))
530                 rtt = self.render_time(None, rtt)
531             paused = self.render_time(None, r_ev["paused_time"])
532
533             t[T.tr[T.td["[%d:+%d]" % (start, length)],
534                    T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
535                    T.td[bytes], T.td[rtt],
536                    T.td[decrypt_time], T.td[paused],
537                    T.td[speed],
538                    ]]
539
540         l[T.h2["Read Events:"], t]
541         l[T.br(clear="all")]
542
543         t = T.table(align="left",class_="status-download-events")
544         t[T.tr[T.th["segnum"], T.th["start"], T.th["active"], T.th["finish"],
545                T.th["range"],
546                T.th["decodetime"], T.th["segtime"], T.th["speed"]]]
547         for s_ev in self.download_status.segment_events:
548             range_s = "-"
549             segtime_s = "-"
550             speed = "-"
551             decode_time = "-"
552             if s_ev["finish_time"] is not None:
553                 if s_ev["success"]:
554                     segtime = s_ev["finish_time"] - s_ev["active_time"]
555                     segtime_s = self.render_time(None, segtime)
556                     seglen = s_ev["segment_length"]
557                     range_s = "[%d:+%d]" % (s_ev["segment_start"], seglen)
558                     speed = self.render_rate(None, compute_rate(seglen, segtime))
559                     decode_time = self._rate_and_time(seglen, s_ev["decode_time"])
560                 else:
561                     # error
562                     range_s = "error"
563             else:
564                 # not finished yet
565                 pass
566
567             t[T.tr[T.td["seg%d" % s_ev["segment_number"]],
568                    T.td[srt(s_ev["start_time"])],
569                    T.td[srt(s_ev["active_time"])],
570                    T.td[srt(s_ev["finish_time"])],
571                    T.td[range_s],
572                    T.td[decode_time],
573                    T.td[segtime_s], T.td[speed]]]
574
575         l[T.h2["Segment Events:"], t]
576         l[T.br(clear="all")]
577         t = T.table(align="left",class_="status-download-events")
578         t[T.tr[T.th["serverid"], T.th["shnum"], T.th["range"],
579                T.th["txtime"], T.th["rxtime"],
580                T.th["received"], T.th["RTT"]]]
581         for r_ev in self.download_status.block_requests:
582             server = r_ev["server"]
583             rtt = None
584             if r_ev["finish_time"] is not None:
585                 rtt = r_ev["finish_time"] - r_ev["start_time"]
586             color = self.color(server)
587             t[T.tr(style="background: %s" % color)[
588                 T.td[server.get_name()], T.td[r_ev["shnum"]],
589                 T.td["[%d:+%d]" % (r_ev["start"], r_ev["length"])],
590                 T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
591                 T.td[r_ev["response_length"] or ""],
592                 T.td[self.render_time(None, rtt)],
593                 ]]
594
595         l[T.h2["Requests:"], t]
596         l[T.br(clear="all")]
597
598         return l
599
600     def color(self, server):
601         peerid = server.get_serverid() # binary
602         def m(c):
603             return min(ord(c) / 2 + 0x80, 0xff)
604         return "#%02x%02x%02x" % (m(peerid[0]), m(peerid[1]), m(peerid[2]))
605
606     def render_results(self, ctx, data):
607         d = self.download_results()
608         def _got_results(results):
609             if results:
610                 return ctx.tag
611             return ""
612         d.addCallback(_got_results)
613         return d
614
615     def render_started(self, ctx, data):
616         started_s = format_time(time.localtime(data.get_started()))
617         return started_s + " (%s)" % data.get_started()
618
619     def render_si(self, ctx, data):
620         si_s = base32.b2a_or_none(data.get_storage_index())
621         if si_s is None:
622             si_s = "(None)"
623         return si_s
624
625     def render_helper(self, ctx, data):
626         return {True: "Yes",
627                 False: "No"}[data.using_helper()]
628
629     def render_total_size(self, ctx, data):
630         size = data.get_size()
631         if size is None:
632             return "(unknown)"
633         return size
634
635     def render_progress(self, ctx, data):
636         progress = data.get_progress()
637         # TODO: make an ascii-art bar
638         return "%.1f%%" % (100.0 * progress)
639
640     def render_status(self, ctx, data):
641         return data.get_status()
642
643 class DownloadStatusTimelinePage(rend.Page):
644     docFactory = getxmlfile("download-status-timeline.xhtml")
645
646     def render_started(self, ctx, data):
647         started_s = format_time(time.localtime(data.get_started()))
648         return started_s + " (%s)" % data.get_started()
649
650     def render_si(self, ctx, data):
651         si_s = base32.b2a_or_none(data.get_storage_index())
652         if si_s is None:
653             si_s = "(None)"
654         return si_s
655
656     def render_helper(self, ctx, data):
657         return {True: "Yes",
658                 False: "No"}[data.using_helper()]
659
660     def render_total_size(self, ctx, data):
661         size = data.get_size()
662         if size is None:
663             return "(unknown)"
664         return size
665
666     def render_progress(self, ctx, data):
667         progress = data.get_progress()
668         # TODO: make an ascii-art bar
669         return "%.1f%%" % (100.0 * progress)
670
671     def render_status(self, ctx, data):
672         return data.get_status()
673
674 class RetrieveStatusPage(rend.Page, RateAndTimeMixin):
675     docFactory = getxmlfile("retrieve-status.xhtml")
676
677     def __init__(self, data):
678         rend.Page.__init__(self, data)
679         self.retrieve_status = data
680
681     def render_started(self, ctx, data):
682         started_s = format_time(time.localtime(data.get_started()))
683         return started_s
684
685     def render_si(self, ctx, data):
686         si_s = base32.b2a_or_none(data.get_storage_index())
687         if si_s is None:
688             si_s = "(None)"
689         return si_s
690
691     def render_helper(self, ctx, data):
692         return {True: "Yes",
693                 False: "No"}[data.using_helper()]
694
695     def render_current_size(self, ctx, data):
696         size = data.get_size()
697         if size is None:
698             size = "(unknown)"
699         return size
700
701     def render_progress(self, ctx, data):
702         progress = data.get_progress()
703         # TODO: make an ascii-art bar
704         return "%.1f%%" % (100.0 * progress)
705
706     def render_status(self, ctx, data):
707         return data.get_status()
708
709     def render_encoding(self, ctx, data):
710         k, n = data.get_encoding()
711         return ctx.tag["Encoding: %s of %s" % (k, n)]
712
713     def render_problems(self, ctx, data):
714         problems = data.get_problems()
715         if not problems:
716             return ""
717         l = T.ul()
718         for peerid in sorted(problems.keys()):
719             peerid_s = idlib.shortnodeid_b2a(peerid)
720             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
721         return ctx.tag["Server Problems:", l]
722
723     def _get_rate(self, data, name):
724         file_size = self.retrieve_status.get_size()
725         time = self.retrieve_status.timings.get(name)
726         return compute_rate(file_size, time)
727
728     def data_time_total(self, ctx, data):
729         return self.retrieve_status.timings.get("total")
730     def data_rate_total(self, ctx, data):
731         return self._get_rate(data, "total")
732
733     def data_time_fetch(self, ctx, data):
734         return self.retrieve_status.timings.get("fetch")
735     def data_rate_fetch(self, ctx, data):
736         return self._get_rate(data, "fetch")
737
738     def data_time_decode(self, ctx, data):
739         return self.retrieve_status.timings.get("decode")
740     def data_rate_decode(self, ctx, data):
741         return self._get_rate(data, "decode")
742
743     def data_time_decrypt(self, ctx, data):
744         return self.retrieve_status.timings.get("decrypt")
745     def data_rate_decrypt(self, ctx, data):
746         return self._get_rate(data, "decrypt")
747
748     def render_server_timings(self, ctx, data):
749         per_server = self.retrieve_status.timings.get("fetch_per_server")
750         if not per_server:
751             return ""
752         l = T.ul()
753         for server in sorted(per_server.keys(), key=lambda s: s.get_name()):
754             times_s = ", ".join([self.render_time(None, t)
755                                  for t in per_server[server]])
756             l[T.li["[%s]: %s" % (server.get_name(), times_s)]]
757         return T.li["Per-Server Fetch Response Times: ", l]
758
759
760 class PublishStatusPage(rend.Page, RateAndTimeMixin):
761     docFactory = getxmlfile("publish-status.xhtml")
762
763     def __init__(self, data):
764         rend.Page.__init__(self, data)
765         self.publish_status = data
766
767     def render_started(self, ctx, data):
768         started_s = format_time(time.localtime(data.get_started()))
769         return started_s
770
771     def render_si(self, ctx, data):
772         si_s = base32.b2a_or_none(data.get_storage_index())
773         if si_s is None:
774             si_s = "(None)"
775         return si_s
776
777     def render_helper(self, ctx, data):
778         return {True: "Yes",
779                 False: "No"}[data.using_helper()]
780
781     def render_current_size(self, ctx, data):
782         size = data.get_size()
783         if size is None:
784             size = "(unknown)"
785         return size
786
787     def render_progress(self, ctx, data):
788         progress = data.get_progress()
789         # TODO: make an ascii-art bar
790         return "%.1f%%" % (100.0 * progress)
791
792     def render_status(self, ctx, data):
793         return data.get_status()
794
795     def render_encoding(self, ctx, data):
796         k, n = data.get_encoding()
797         return ctx.tag["Encoding: %s of %s" % (k, n)]
798
799     def render_sharemap(self, ctx, data):
800         servermap = data.get_servermap()
801         if servermap is None:
802             return ctx.tag["None"]
803         l = T.ul()
804         sharemap = servermap.make_sharemap()
805         for shnum in sorted(sharemap.keys()):
806             l[T.li["%d -> Placed on " % shnum,
807                    ", ".join(["[%s]" % server.get_name()
808                               for server in sharemap[shnum]])]]
809         return ctx.tag["Sharemap:", l]
810
811     def render_problems(self, ctx, data):
812         problems = data.get_problems()
813         if not problems:
814             return ""
815         l = T.ul()
816         # XXX: is this exercised? I don't think PublishStatus.problems is
817         # ever populated
818         for peerid in sorted(problems.keys()):
819             peerid_s = idlib.shortnodeid_b2a(peerid)
820             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
821         return ctx.tag["Server Problems:", l]
822
823     def _get_rate(self, data, name):
824         file_size = self.publish_status.get_size()
825         time = self.publish_status.timings.get(name)
826         return compute_rate(file_size, time)
827
828     def data_time_total(self, ctx, data):
829         return self.publish_status.timings.get("total")
830     def data_rate_total(self, ctx, data):
831         return self._get_rate(data, "total")
832
833     def data_time_setup(self, ctx, data):
834         return self.publish_status.timings.get("setup")
835
836     def data_time_encrypt(self, ctx, data):
837         return self.publish_status.timings.get("encrypt")
838     def data_rate_encrypt(self, ctx, data):
839         return self._get_rate(data, "encrypt")
840
841     def data_time_encode(self, ctx, data):
842         return self.publish_status.timings.get("encode")
843     def data_rate_encode(self, ctx, data):
844         return self._get_rate(data, "encode")
845
846     def data_time_pack(self, ctx, data):
847         return self.publish_status.timings.get("pack")
848     def data_rate_pack(self, ctx, data):
849         return self._get_rate(data, "pack")
850     def data_time_sign(self, ctx, data):
851         return self.publish_status.timings.get("sign")
852
853     def data_time_push(self, ctx, data):
854         return self.publish_status.timings.get("push")
855     def data_rate_push(self, ctx, data):
856         return self._get_rate(data, "push")
857
858     def render_server_timings(self, ctx, data):
859         per_server = self.publish_status.timings.get("send_per_server")
860         if not per_server:
861             return ""
862         l = T.ul()
863         for server in sorted(per_server.keys(), key=lambda s: s.get_name()):
864             times_s = ", ".join([self.render_time(None, t)
865                                  for t in per_server[server]])
866             l[T.li["[%s]: %s" % (server.get_name(), times_s)]]
867         return T.li["Per-Server Response Times: ", l]
868
869 class MapupdateStatusPage(rend.Page, RateAndTimeMixin):
870     docFactory = getxmlfile("map-update-status.xhtml")
871
872     def __init__(self, data):
873         rend.Page.__init__(self, data)
874         self.update_status = data
875
876     def render_started(self, ctx, data):
877         started_s = format_time(time.localtime(data.get_started()))
878         return started_s
879
880     def render_finished(self, ctx, data):
881         when = data.get_finished()
882         if not when:
883             return "not yet"
884         started_s = format_time(time.localtime(data.get_finished()))
885         return started_s
886
887     def render_si(self, ctx, data):
888         si_s = base32.b2a_or_none(data.get_storage_index())
889         if si_s is None:
890             si_s = "(None)"
891         return si_s
892
893     def render_helper(self, ctx, data):
894         return {True: "Yes",
895                 False: "No"}[data.using_helper()]
896
897     def render_progress(self, ctx, data):
898         progress = data.get_progress()
899         # TODO: make an ascii-art bar
900         return "%.1f%%" % (100.0 * progress)
901
902     def render_status(self, ctx, data):
903         return data.get_status()
904
905     def render_problems(self, ctx, data):
906         problems = data.problems
907         if not problems:
908             return ""
909         l = T.ul()
910         for peerid in sorted(problems.keys()):
911             peerid_s = idlib.shortnodeid_b2a(peerid)
912             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
913         return ctx.tag["Server Problems:", l]
914
915     def render_privkey_from(self, ctx, data):
916         server = data.get_privkey_from()
917         if server:
918             return ctx.tag["Got privkey from: [%s]" % server.get_name()]
919         else:
920             return ""
921
922     def data_time_total(self, ctx, data):
923         return self.update_status.timings.get("total")
924
925     def data_time_initial_queries(self, ctx, data):
926         return self.update_status.timings.get("initial_queries")
927
928     def data_time_cumulative_verify(self, ctx, data):
929         return self.update_status.timings.get("cumulative_verify")
930
931     def render_server_timings(self, ctx, data):
932         per_server = self.update_status.timings.get("per_server")
933         if not per_server:
934             return ""
935         l = T.ul()
936         for server in sorted(per_server.keys(), key=lambda s: s.get_name()):
937             times = []
938             for op,started,t in per_server[server]:
939                 #times.append("%s/%.4fs/%s/%s" % (op,
940                 #                              started,
941                 #                              self.render_time(None, started - self.update_status.get_started()),
942                 #                              self.render_time(None,t)))
943                 if op == "query":
944                     times.append( self.render_time(None, t) )
945                 elif op == "late":
946                     times.append( "late(" + self.render_time(None, t) + ")" )
947                 else:
948                     times.append( "privkey(" + self.render_time(None, t) + ")" )
949             times_s = ", ".join(times)
950             l[T.li["[%s]: %s" % (server.get_name(), times_s)]]
951         return T.li["Per-Server Response Times: ", l]
952
953     def render_timing_chart(self, ctx, data):
954         imageurl = self._timing_chart()
955         return ctx.tag[imageurl]
956
957     def _timing_chart(self):
958         started = self.update_status.get_started()
959         total = self.update_status.timings.get("total")
960         per_server = self.update_status.timings.get("per_server")
961         # We'd like to use an https: URL here, but the site has a domain/cert mismatch.
962         base = "http://chart.apis.google.com/chart?"
963         pieces = ["cht=bhs"]
964         pieces.append("chco=ffffff,4d89f9,c6d9fd") # colors
965         data0 = []
966         data1 = []
967         data2 = []
968         nb_nodes = 0
969         graph_botom_margin= 21
970         graph_top_margin = 5
971         server_names = []
972         top_abs = started
973         # we sort the queries by the time at which we sent the first request
974         sorttable = [ (times[0][1], server)
975                       for server, times in per_server.items() ]
976         sorttable.sort()
977         servers = [t[1] for t in sorttable]
978
979         for server in servers:
980             nb_nodes += 1
981             times = per_server[server]
982             name = server.get_name()
983             server_names.append(name)
984             # for servermap updates, there are either one or two queries per
985             # peer. The second (if present) is to get the privkey.
986             op,q_started,q_elapsed = times[0]
987             data0.append("%.3f" % (q_started-started))
988             data1.append("%.3f" % q_elapsed)
989             top_abs = max(top_abs, q_started+q_elapsed)
990             if len(times) > 1:
991                 op,p_started,p_elapsed = times[0]
992                 data2.append("%.3f" % p_elapsed)
993                 top_abs = max(top_abs, p_started+p_elapsed)
994             else:
995                 data2.append("0.0")
996         finished = self.update_status.get_finished()
997         if finished:
998             top_abs = max(top_abs, finished)
999         top_rel = top_abs - started
1000         chs ="chs=400x%d" % ( (nb_nodes*28) + graph_top_margin + graph_botom_margin )
1001         chd = "chd=t:" + "|".join([",".join(data0),
1002                                    ",".join(data1),
1003                                    ",".join(data2)])
1004         pieces.append(chd)
1005         pieces.append(chs)
1006         chds = "chds=0,%0.3f" % top_rel
1007         pieces.append(chds)
1008         pieces.append("chxt=x,y")
1009         pieces.append("chxr=0,0.0,%0.3f" % top_rel)
1010         pieces.append("chxl=1:|" + "|".join(reversed(server_names)))
1011         # use up to 10 grid lines, at decimal multiples.
1012         # mathutil.next_power_of_k doesn't handle numbers smaller than one,
1013         # unfortunately.
1014         #pieces.append("chg="
1015
1016         if total is not None:
1017             finished_f = 1.0 * total / top_rel
1018             pieces.append("chm=r,FF0000,0,%0.3f,%0.3f" % (finished_f,
1019                                                           finished_f+0.01))
1020         url = base + "&".join(pieces)
1021         return T.img(src=url,border="1",align="right", float="right")
1022
1023
1024 class Status(rend.Page):
1025     docFactory = getxmlfile("status.xhtml")
1026     addSlash = True
1027
1028     def __init__(self, history):
1029         rend.Page.__init__(self, history)
1030         self.history = history
1031
1032     def renderHTTP(self, ctx):
1033         req = inevow.IRequest(ctx)
1034         t = get_arg(req, "t")
1035         if t == "json":
1036             return self.json(req)
1037         return rend.Page.renderHTTP(self, ctx)
1038
1039     def json(self, req):
1040         req.setHeader("content-type", "text/plain")
1041         data = {}
1042         data["active"] = active = []
1043         for s in self._get_active_operations():
1044             si_s = base32.b2a_or_none(s.get_storage_index())
1045             size = s.get_size()
1046             status = s.get_status()
1047             if IUploadStatus.providedBy(s):
1048                 h,c,e = s.get_progress()
1049                 active.append({"type": "upload",
1050                                "storage-index-string": si_s,
1051                                "total-size": size,
1052                                "status": status,
1053                                "progress-hash": h,
1054                                "progress-ciphertext": c,
1055                                "progress-encode-push": e,
1056                                })
1057             elif IDownloadStatus.providedBy(s):
1058                 active.append({"type": "download",
1059                                "storage-index-string": si_s,
1060                                "total-size": size,
1061                                "status": status,
1062                                "progress": s.get_progress(),
1063                                })
1064
1065         return simplejson.dumps(data, indent=1) + "\n"
1066
1067     def _get_all_statuses(self):
1068         h = self.history
1069         return itertools.chain(h.list_all_upload_statuses(),
1070                                h.list_all_download_statuses(),
1071                                h.list_all_mapupdate_statuses(),
1072                                h.list_all_publish_statuses(),
1073                                h.list_all_retrieve_statuses(),
1074                                h.list_all_helper_statuses(),
1075                                )
1076
1077     def data_active_operations(self, ctx, data):
1078         return self._get_active_operations()
1079
1080     def _get_active_operations(self):
1081         active = [s
1082                   for s in self._get_all_statuses()
1083                   if s.get_active()]
1084         return active
1085
1086     def data_recent_operations(self, ctx, data):
1087         return self._get_recent_operations()
1088
1089     def _get_recent_operations(self):
1090         recent = [s
1091                   for s in self._get_all_statuses()
1092                   if not s.get_active()]
1093         recent.sort(lambda a,b: cmp(a.get_started(), b.get_started()))
1094         recent.reverse()
1095         return recent
1096
1097     def render_row(self, ctx, data):
1098         s = data
1099
1100         started_s = format_time(time.localtime(s.get_started()))
1101         ctx.fillSlots("started", started_s)
1102
1103         si_s = base32.b2a_or_none(s.get_storage_index())
1104         if si_s is None:
1105             si_s = "(None)"
1106         ctx.fillSlots("si", si_s)
1107         ctx.fillSlots("helper", {True: "Yes",
1108                                  False: "No"}[s.using_helper()])
1109
1110         size = s.get_size()
1111         if size is None:
1112             size = "(unknown)"
1113         elif isinstance(size, (int, long, float)):
1114             size = abbreviate_size(size)
1115         ctx.fillSlots("total_size", size)
1116
1117         progress = data.get_progress()
1118         if IUploadStatus.providedBy(data):
1119             link = "up-%d" % data.get_counter()
1120             ctx.fillSlots("type", "upload")
1121             # TODO: make an ascii-art bar
1122             (chk, ciphertext, encandpush) = progress
1123             progress_s = ("hash: %.1f%%, ciphertext: %.1f%%, encode: %.1f%%" %
1124                           ( (100.0 * chk),
1125                             (100.0 * ciphertext),
1126                             (100.0 * encandpush) ))
1127             ctx.fillSlots("progress", progress_s)
1128         elif IDownloadStatus.providedBy(data):
1129             link = "down-%d" % data.get_counter()
1130             ctx.fillSlots("type", "download")
1131             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1132         elif IPublishStatus.providedBy(data):
1133             link = "publish-%d" % data.get_counter()
1134             ctx.fillSlots("type", "publish")
1135             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1136         elif IRetrieveStatus.providedBy(data):
1137             ctx.fillSlots("type", "retrieve")
1138             link = "retrieve-%d" % data.get_counter()
1139             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1140         else:
1141             assert IServermapUpdaterStatus.providedBy(data)
1142             ctx.fillSlots("type", "mapupdate %s" % data.get_mode())
1143             link = "mapupdate-%d" % data.get_counter()
1144             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1145         ctx.fillSlots("status", T.a(href=link)[s.get_status()])
1146         return ctx.tag
1147
1148     def childFactory(self, ctx, name):
1149         h = self.history
1150         stype,count_s = name.split("-")
1151         count = int(count_s)
1152         if stype == "up":
1153             for s in itertools.chain(h.list_all_upload_statuses(),
1154                                      h.list_all_helper_statuses()):
1155                 # immutable-upload helpers use the same status object as a
1156                 # regular immutable-upload
1157                 if s.get_counter() == count:
1158                     return UploadStatusPage(s)
1159         if stype == "down":
1160             for s in h.list_all_download_statuses():
1161                 if s.get_counter() == count:
1162                     return DownloadStatusPage(s)
1163         if stype == "mapupdate":
1164             for s in h.list_all_mapupdate_statuses():
1165                 if s.get_counter() == count:
1166                     return MapupdateStatusPage(s)
1167         if stype == "publish":
1168             for s in h.list_all_publish_statuses():
1169                 if s.get_counter() == count:
1170                     return PublishStatusPage(s)
1171         if stype == "retrieve":
1172             for s in h.list_all_retrieve_statuses():
1173                 if s.get_counter() == count:
1174                     return RetrieveStatusPage(s)
1175
1176
1177 class HelperStatus(rend.Page):
1178     docFactory = getxmlfile("helper.xhtml")
1179
1180     def __init__(self, helper):
1181         rend.Page.__init__(self, helper)
1182         self.helper = helper
1183
1184     def renderHTTP(self, ctx):
1185         req = inevow.IRequest(ctx)
1186         t = get_arg(req, "t")
1187         if t == "json":
1188             return self.render_JSON(req)
1189         return rend.Page.renderHTTP(self, ctx)
1190
1191     def data_helper_stats(self, ctx, data):
1192         return self.helper.get_stats()
1193
1194     def render_JSON(self, req):
1195         req.setHeader("content-type", "text/plain")
1196         if self.helper:
1197             stats = self.helper.get_stats()
1198             return simplejson.dumps(stats, indent=1) + "\n"
1199         return simplejson.dumps({}) + "\n"
1200
1201     def render_active_uploads(self, ctx, data):
1202         return data["chk_upload_helper.active_uploads"]
1203
1204     def render_incoming(self, ctx, data):
1205         return "%d bytes in %d files" % (data["chk_upload_helper.incoming_size"],
1206                                          data["chk_upload_helper.incoming_count"])
1207
1208     def render_encoding(self, ctx, data):
1209         return "%d bytes in %d files" % (data["chk_upload_helper.encoding_size"],
1210                                          data["chk_upload_helper.encoding_count"])
1211
1212     def render_upload_requests(self, ctx, data):
1213         return str(data["chk_upload_helper.upload_requests"])
1214
1215     def render_upload_already_present(self, ctx, data):
1216         return str(data["chk_upload_helper.upload_already_present"])
1217
1218     def render_upload_need_upload(self, ctx, data):
1219         return str(data["chk_upload_helper.upload_need_upload"])
1220
1221     def render_upload_bytes_fetched(self, ctx, data):
1222         return str(data["chk_upload_helper.fetched_bytes"])
1223
1224     def render_upload_bytes_encoded(self, ctx, data):
1225         return str(data["chk_upload_helper.encoded_bytes"])
1226
1227
1228 class Statistics(rend.Page):
1229     docFactory = getxmlfile("statistics.xhtml")
1230
1231     def __init__(self, provider):
1232         rend.Page.__init__(self, provider)
1233         self.provider = provider
1234
1235     def renderHTTP(self, ctx):
1236         req = inevow.IRequest(ctx)
1237         t = get_arg(req, "t")
1238         if t == "json":
1239             stats = self.provider.get_stats()
1240             req.setHeader("content-type", "text/plain")
1241             return simplejson.dumps(stats, indent=1) + "\n"
1242         return rend.Page.renderHTTP(self, ctx)
1243
1244     def data_get_stats(self, ctx, data):
1245         return self.provider.get_stats()
1246
1247     def render_load_average(self, ctx, data):
1248         return str(data["stats"].get("load_monitor.avg_load"))
1249
1250     def render_peak_load(self, ctx, data):
1251         return str(data["stats"].get("load_monitor.max_load"))
1252
1253     def render_uploads(self, ctx, data):
1254         files = data["counters"].get("uploader.files_uploaded", 0)
1255         bytes = data["counters"].get("uploader.bytes_uploaded", 0)
1256         return ("%s files / %s bytes (%s)" %
1257                 (files, bytes, abbreviate_size(bytes)))
1258
1259     def render_downloads(self, ctx, data):
1260         files = data["counters"].get("downloader.files_downloaded", 0)
1261         bytes = data["counters"].get("downloader.bytes_downloaded", 0)
1262         return ("%s files / %s bytes (%s)" %
1263                 (files, bytes, abbreviate_size(bytes)))
1264
1265     def render_publishes(self, ctx, data):
1266         files = data["counters"].get("mutable.files_published", 0)
1267         bytes = data["counters"].get("mutable.bytes_published", 0)
1268         return "%s files / %s bytes (%s)" % (files, bytes,
1269                                              abbreviate_size(bytes))
1270
1271     def render_retrieves(self, ctx, data):
1272         files = data["counters"].get("mutable.files_retrieved", 0)
1273         bytes = data["counters"].get("mutable.bytes_retrieved", 0)
1274         return "%s files / %s bytes (%s)" % (files, bytes,
1275                                              abbreviate_size(bytes))
1276
1277     def render_drop_monitored(self, ctx, data):
1278         dirs = data["counters"].get("drop_upload.dirs_monitored", 0)
1279         return "%s directories" % (dirs,)
1280
1281     def render_drop_uploads(self, ctx, data):
1282         # TODO: bytes uploaded
1283         files = data["counters"].get("drop_upload.files_uploaded", 0)
1284         return "%s files" % (files,)
1285
1286     def render_drop_queued(self, ctx, data):
1287         files = data["counters"].get("drop_upload.files_queued", 0)
1288         return "%s files" % (files,)
1289
1290     def render_drop_failed(self, ctx, data):
1291         files = data["counters"].get("drop_upload.files_failed", 0)
1292         return "%s files" % (files,)
1293
1294     def render_raw(self, ctx, data):
1295         raw = pprint.pformat(data)
1296         return ctx.tag[raw]