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