]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/status.py
add more download-status data, fix tests
[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 download_results(self):
342         return defer.maybeDeferred(self.download_status.get_results)
343
344     def relative_time(self, t):
345         if t is None:
346             return t
347         if self.download_status.first_timestamp is not None:
348             return t - self.download_status.first_timestamp
349         return t
350     def short_relative_time(self, t):
351         t = self.relative_time(t)
352         if t is None:
353             return ""
354         return "+%.6fs" % t
355
356     def _find_overlap(self, events, start_key, end_key):
357         # given a list of event dicts, return a new list in which each event
358         # has an extra "row" key (an int, starting at 0). This is a hint to
359         # our JS frontend about how to overlap the parts of the graph it is
360         # drawing.
361
362         # we must always make a copy, since we're going to be adding "row"
363         # keys and don't want to change the original objects. If we're
364         # stringifying serverids, we'll also be changing the serverid keys.
365         new_events = []
366         rows = []
367         for ev in events:
368             ev = ev.copy()
369             if "serverid" in ev:
370                 ev["serverid"] = base32.b2a(ev["serverid"])
371             # find an empty slot in the rows
372             free_slot = None
373             for row,finished in enumerate(rows):
374                 if finished is not None:
375                     if ev[start_key] > finished:
376                         free_slot = row
377                         break
378             if free_slot is None:
379                 free_slot = len(rows)
380                 rows.append(ev[end_key])
381             else:
382                 rows[free_slot] = ev[end_key]
383             ev["row"] = free_slot
384             new_events.append(ev)
385         return new_events
386
387     def _find_overlap_requests(self, events):
388         """We compute a three-element 'row tuple' for each event: (serverid,
389         shnum, row). All elements are ints. The first is a mapping from
390         serverid to group number, the second is a mapping from shnum to
391         subgroup number. The third is a row within the subgroup.
392
393         We also return a list of lists of rowcounts, so renderers can decide
394         how much vertical space to give to each row.
395         """
396
397         serverid_to_group = {}
398         groupnum_to_rows = {} # maps groupnum to a table of rows. Each table
399                               # is a list with an element for each row number
400                               # (int starting from 0) that contains a
401                               # finish_time, indicating that the row is empty
402                               # beyond that time. If finish_time is None, it
403                               # indicate a response that has not yet
404                               # completed, so the row cannot be reused.
405         new_events = []
406         for ev in events:
407             # DownloadStatus promises to give us events in temporal order
408             ev = ev.copy()
409             ev["serverid"] = base32.b2a(ev["serverid"])
410             if ev["serverid"] not in serverid_to_group:
411                 groupnum = len(serverid_to_group)
412                 serverid_to_group[ev["serverid"]] = groupnum
413             groupnum = serverid_to_group[ev["serverid"]]
414             if groupnum not in groupnum_to_rows:
415                 groupnum_to_rows[groupnum] = []
416             rows = groupnum_to_rows[groupnum]
417             # find an empty slot in the rows
418             free_slot = None
419             for row,finished in enumerate(rows):
420                 if finished is not None:
421                     if ev["start_time"] > finished:
422                         free_slot = row
423                         break
424             if free_slot is None:
425                 free_slot = len(rows)
426                 rows.append(ev["finish_time"])
427             else:
428                 rows[free_slot] = ev["finish_time"]
429             ev["row"] = (groupnum, free_slot)
430             new_events.append(ev)
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["read"] = self._find_overlap(ds.read_events,
445                                           "start_time", "finish_time")
446         data["segment"] = self._find_overlap(ds.segment_events,
447                                              "start_time", "finish_time")
448         data["dyhb"] = self._find_overlap(ds.dyhb_requests,
449                                           "start_time", "finish_time")
450         data["block"],data["block_rownums"] = self._find_overlap_requests(ds.block_requests)
451
452         servernums = {}
453         serverid_strings = {}
454         for d_ev in data["dyhb"]:
455             if d_ev["serverid"] not in servernums:
456                 servernum = len(servernums)
457                 servernums[d_ev["serverid"]] = servernum
458                 #title= "%s: %s" % ( ",".join([str(shnum) for shnum in shnums]))
459                 serverid_strings[servernum] = d_ev["serverid"][:4]
460         data["server_info"] = dict([(serverid, {"num": servernums[serverid],
461                                                 "color": self.color(base32.a2b(serverid)),
462                                                 "short": serverid_strings[servernums[serverid]],
463                                                 })
464                                    for serverid in servernums.keys()])
465         data["num_serverids"] = len(serverid_strings)
466         # we'd prefer the keys of serverids[] to be ints, but this is JSON,
467         # so they get converted to strings. Stupid javascript.
468         data["serverids"] = serverid_strings
469         data["bounds"] = {"min": ds.first_timestamp,
470                           "max": ds.last_timestamp,
471                           }
472         # for testing
473         ## data["bounds"]["max"] = tfmt(max([d_ev["finish_time"]
474         ##                                   for d_ev in data["dyhb"]
475         ##                                   if d_ev["finish_time"] is not None]
476         ##                                  ))
477         return simplejson.dumps(data, indent=1) + "\n"
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 RetrieveStatusPage(rend.Page, RateAndTimeMixin):
644     docFactory = getxmlfile("retrieve-status.xhtml")
645
646     def __init__(self, data):
647         rend.Page.__init__(self, data)
648         self.retrieve_status = data
649
650     def render_started(self, ctx, data):
651         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
652         started_s = time.strftime(TIME_FORMAT,
653                                   time.localtime(data.get_started()))
654         return started_s
655
656     def render_si(self, ctx, data):
657         si_s = base32.b2a_or_none(data.get_storage_index())
658         if si_s is None:
659             si_s = "(None)"
660         return si_s
661
662     def render_helper(self, ctx, data):
663         return {True: "Yes",
664                 False: "No"}[data.using_helper()]
665
666     def render_current_size(self, ctx, data):
667         size = data.get_size()
668         if size is None:
669             size = "(unknown)"
670         return size
671
672     def render_progress(self, ctx, data):
673         progress = data.get_progress()
674         # TODO: make an ascii-art bar
675         return "%.1f%%" % (100.0 * progress)
676
677     def render_status(self, ctx, data):
678         return data.get_status()
679
680     def render_encoding(self, ctx, data):
681         k, n = data.get_encoding()
682         return ctx.tag["Encoding: %s of %s" % (k, n)]
683
684     def render_problems(self, ctx, data):
685         problems = data.problems
686         if not problems:
687             return ""
688         l = T.ul()
689         for peerid in sorted(problems.keys()):
690             peerid_s = idlib.shortnodeid_b2a(peerid)
691             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
692         return ctx.tag["Server Problems:", l]
693
694     def _get_rate(self, data, name):
695         file_size = self.retrieve_status.get_size()
696         time = self.retrieve_status.timings.get(name)
697         return compute_rate(file_size, time)
698
699     def data_time_total(self, ctx, data):
700         return self.retrieve_status.timings.get("total")
701     def data_rate_total(self, ctx, data):
702         return self._get_rate(data, "total")
703
704     def data_time_fetch(self, ctx, data):
705         return self.retrieve_status.timings.get("fetch")
706     def data_rate_fetch(self, ctx, data):
707         return self._get_rate(data, "fetch")
708
709     def data_time_decode(self, ctx, data):
710         return self.retrieve_status.timings.get("decode")
711     def data_rate_decode(self, ctx, data):
712         return self._get_rate(data, "decode")
713
714     def data_time_decrypt(self, ctx, data):
715         return self.retrieve_status.timings.get("decrypt")
716     def data_rate_decrypt(self, ctx, data):
717         return self._get_rate(data, "decrypt")
718
719     def render_server_timings(self, ctx, data):
720         per_server = self.retrieve_status.timings.get("fetch_per_server")
721         if not per_server:
722             return ""
723         l = T.ul()
724         for peerid in sorted(per_server.keys()):
725             peerid_s = idlib.shortnodeid_b2a(peerid)
726             times_s = ", ".join([self.render_time(None, t)
727                                  for t in per_server[peerid]])
728             l[T.li["[%s]: %s" % (peerid_s, times_s)]]
729         return T.li["Per-Server Fetch Response Times: ", l]
730
731
732 class PublishStatusPage(rend.Page, RateAndTimeMixin):
733     docFactory = getxmlfile("publish-status.xhtml")
734
735     def __init__(self, data):
736         rend.Page.__init__(self, data)
737         self.publish_status = data
738
739     def render_started(self, ctx, data):
740         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
741         started_s = time.strftime(TIME_FORMAT,
742                                   time.localtime(data.get_started()))
743         return started_s
744
745     def render_si(self, ctx, data):
746         si_s = base32.b2a_or_none(data.get_storage_index())
747         if si_s is None:
748             si_s = "(None)"
749         return si_s
750
751     def render_helper(self, ctx, data):
752         return {True: "Yes",
753                 False: "No"}[data.using_helper()]
754
755     def render_current_size(self, ctx, data):
756         size = data.get_size()
757         if size is None:
758             size = "(unknown)"
759         return size
760
761     def render_progress(self, ctx, data):
762         progress = data.get_progress()
763         # TODO: make an ascii-art bar
764         return "%.1f%%" % (100.0 * progress)
765
766     def render_status(self, ctx, data):
767         return data.get_status()
768
769     def render_encoding(self, ctx, data):
770         k, n = data.get_encoding()
771         return ctx.tag["Encoding: %s of %s" % (k, n)]
772
773     def render_sharemap(self, ctx, data):
774         servermap = data.get_servermap()
775         if servermap is None:
776             return ctx.tag["None"]
777         l = T.ul()
778         sharemap = servermap.make_sharemap()
779         for shnum in sorted(sharemap.keys()):
780             l[T.li["%d -> Placed on " % shnum,
781                    ", ".join(["[%s]" % idlib.shortnodeid_b2a(peerid)
782                               for peerid in sharemap[shnum]])]]
783         return ctx.tag["Sharemap:", l]
784
785     def render_problems(self, ctx, data):
786         problems = data.problems
787         if not problems:
788             return ""
789         l = T.ul()
790         for peerid in sorted(problems.keys()):
791             peerid_s = idlib.shortnodeid_b2a(peerid)
792             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
793         return ctx.tag["Server Problems:", l]
794
795     def _get_rate(self, data, name):
796         file_size = self.publish_status.get_size()
797         time = self.publish_status.timings.get(name)
798         return compute_rate(file_size, time)
799
800     def data_time_total(self, ctx, data):
801         return self.publish_status.timings.get("total")
802     def data_rate_total(self, ctx, data):
803         return self._get_rate(data, "total")
804
805     def data_time_setup(self, ctx, data):
806         return self.publish_status.timings.get("setup")
807
808     def data_time_encrypt(self, ctx, data):
809         return self.publish_status.timings.get("encrypt")
810     def data_rate_encrypt(self, ctx, data):
811         return self._get_rate(data, "encrypt")
812
813     def data_time_encode(self, ctx, data):
814         return self.publish_status.timings.get("encode")
815     def data_rate_encode(self, ctx, data):
816         return self._get_rate(data, "encode")
817
818     def data_time_pack(self, ctx, data):
819         return self.publish_status.timings.get("pack")
820     def data_rate_pack(self, ctx, data):
821         return self._get_rate(data, "pack")
822     def data_time_sign(self, ctx, data):
823         return self.publish_status.timings.get("sign")
824
825     def data_time_push(self, ctx, data):
826         return self.publish_status.timings.get("push")
827     def data_rate_push(self, ctx, data):
828         return self._get_rate(data, "push")
829
830     def render_server_timings(self, ctx, data):
831         per_server = self.publish_status.timings.get("send_per_server")
832         if not per_server:
833             return ""
834         l = T.ul()
835         for peerid in sorted(per_server.keys()):
836             peerid_s = idlib.shortnodeid_b2a(peerid)
837             times_s = ", ".join([self.render_time(None, t)
838                                  for t in per_server[peerid]])
839             l[T.li["[%s]: %s" % (peerid_s, times_s)]]
840         return T.li["Per-Server Response Times: ", l]
841
842 class MapupdateStatusPage(rend.Page, RateAndTimeMixin):
843     docFactory = getxmlfile("map-update-status.xhtml")
844
845     def __init__(self, data):
846         rend.Page.__init__(self, data)
847         self.update_status = data
848
849     def render_started(self, ctx, data):
850         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
851         started_s = time.strftime(TIME_FORMAT,
852                                   time.localtime(data.get_started()))
853         return started_s
854
855     def render_finished(self, ctx, data):
856         when = data.get_finished()
857         if not when:
858             return "not yet"
859         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
860         started_s = time.strftime(TIME_FORMAT,
861                                   time.localtime(data.get_finished()))
862         return started_s
863
864     def render_si(self, ctx, data):
865         si_s = base32.b2a_or_none(data.get_storage_index())
866         if si_s is None:
867             si_s = "(None)"
868         return si_s
869
870     def render_helper(self, ctx, data):
871         return {True: "Yes",
872                 False: "No"}[data.using_helper()]
873
874     def render_progress(self, ctx, data):
875         progress = data.get_progress()
876         # TODO: make an ascii-art bar
877         return "%.1f%%" % (100.0 * progress)
878
879     def render_status(self, ctx, data):
880         return data.get_status()
881
882     def render_problems(self, ctx, data):
883         problems = data.problems
884         if not problems:
885             return ""
886         l = T.ul()
887         for peerid in sorted(problems.keys()):
888             peerid_s = idlib.shortnodeid_b2a(peerid)
889             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
890         return ctx.tag["Server Problems:", l]
891
892     def render_privkey_from(self, ctx, data):
893         peerid = data.get_privkey_from()
894         if peerid:
895             return ctx.tag["Got privkey from: [%s]"
896                            % idlib.shortnodeid_b2a(peerid)]
897         else:
898             return ""
899
900     def data_time_total(self, ctx, data):
901         return self.update_status.timings.get("total")
902
903     def data_time_initial_queries(self, ctx, data):
904         return self.update_status.timings.get("initial_queries")
905
906     def data_time_cumulative_verify(self, ctx, data):
907         return self.update_status.timings.get("cumulative_verify")
908
909     def render_server_timings(self, ctx, data):
910         per_server = self.update_status.timings.get("per_server")
911         if not per_server:
912             return ""
913         l = T.ul()
914         for peerid in sorted(per_server.keys()):
915             peerid_s = idlib.shortnodeid_b2a(peerid)
916             times = []
917             for op,started,t in per_server[peerid]:
918                 #times.append("%s/%.4fs/%s/%s" % (op,
919                 #                              started,
920                 #                              self.render_time(None, started - self.update_status.get_started()),
921                 #                              self.render_time(None,t)))
922                 if op == "query":
923                     times.append( self.render_time(None, t) )
924                 elif op == "late":
925                     times.append( "late(" + self.render_time(None, t) + ")" )
926                 else:
927                     times.append( "privkey(" + self.render_time(None, t) + ")" )
928             times_s = ", ".join(times)
929             l[T.li["[%s]: %s" % (peerid_s, times_s)]]
930         return T.li["Per-Server Response Times: ", l]
931
932     def render_timing_chart(self, ctx, data):
933         imageurl = self._timing_chart()
934         return ctx.tag[imageurl]
935
936     def _timing_chart(self):
937         started = self.update_status.get_started()
938         total = self.update_status.timings.get("total")
939         per_server = self.update_status.timings.get("per_server")
940         base = "http://chart.apis.google.com/chart?"
941         pieces = ["cht=bhs"]
942         pieces.append("chco=ffffff,4d89f9,c6d9fd") # colors
943         data0 = []
944         data1 = []
945         data2 = []
946         nb_nodes = 0
947         graph_botom_margin= 21
948         graph_top_margin = 5
949         peerids_s = []
950         top_abs = started
951         # we sort the queries by the time at which we sent the first request
952         sorttable = [ (times[0][1], peerid)
953                       for peerid, times in per_server.items() ]
954         sorttable.sort()
955         peerids = [t[1] for t in sorttable]
956
957         for peerid in peerids:
958             nb_nodes += 1
959             times = per_server[peerid]
960             peerid_s = idlib.shortnodeid_b2a(peerid)
961             peerids_s.append(peerid_s)
962             # for servermap updates, there are either one or two queries per
963             # peer. The second (if present) is to get the privkey.
964             op,q_started,q_elapsed = times[0]
965             data0.append("%.3f" % (q_started-started))
966             data1.append("%.3f" % q_elapsed)
967             top_abs = max(top_abs, q_started+q_elapsed)
968             if len(times) > 1:
969                 op,p_started,p_elapsed = times[0]
970                 data2.append("%.3f" % p_elapsed)
971                 top_abs = max(top_abs, p_started+p_elapsed)
972             else:
973                 data2.append("0.0")
974         finished = self.update_status.get_finished()
975         if finished:
976             top_abs = max(top_abs, finished)
977         top_rel = top_abs - started
978         chs ="chs=400x%d" % ( (nb_nodes*28) + graph_top_margin + graph_botom_margin )
979         chd = "chd=t:" + "|".join([",".join(data0),
980                                    ",".join(data1),
981                                    ",".join(data2)])
982         pieces.append(chd)
983         pieces.append(chs)
984         chds = "chds=0,%0.3f" % top_rel
985         pieces.append(chds)
986         pieces.append("chxt=x,y")
987         pieces.append("chxr=0,0.0,%0.3f" % top_rel)
988         pieces.append("chxl=1:|" + "|".join(reversed(peerids_s)))
989         # use up to 10 grid lines, at decimal multiples.
990         # mathutil.next_power_of_k doesn't handle numbers smaller than one,
991         # unfortunately.
992         #pieces.append("chg="
993
994         if total is not None:
995             finished_f = 1.0 * total / top_rel
996             pieces.append("chm=r,FF0000,0,%0.3f,%0.3f" % (finished_f,
997                                                           finished_f+0.01))
998         url = base + "&".join(pieces)
999         return T.img(src=url,border="1",align="right", float="right")
1000
1001
1002 class Status(rend.Page):
1003     docFactory = getxmlfile("status.xhtml")
1004     addSlash = True
1005
1006     def __init__(self, history):
1007         rend.Page.__init__(self, history)
1008         self.history = history
1009
1010     def renderHTTP(self, ctx):
1011         req = inevow.IRequest(ctx)
1012         t = get_arg(req, "t")
1013         if t == "json":
1014             return self.json(req)
1015         return rend.Page.renderHTTP(self, ctx)
1016
1017     def json(self, req):
1018         req.setHeader("content-type", "text/plain")
1019         data = {}
1020         data["active"] = active = []
1021         for s in self._get_active_operations():
1022             si_s = base32.b2a_or_none(s.get_storage_index())
1023             size = s.get_size()
1024             status = s.get_status()
1025             if IUploadStatus.providedBy(s):
1026                 h,c,e = s.get_progress()
1027                 active.append({"type": "upload",
1028                                "storage-index-string": si_s,
1029                                "total-size": size,
1030                                "status": status,
1031                                "progress-hash": h,
1032                                "progress-ciphertext": c,
1033                                "progress-encode-push": e,
1034                                })
1035             elif IDownloadStatus.providedBy(s):
1036                 active.append({"type": "download",
1037                                "storage-index-string": si_s,
1038                                "total-size": size,
1039                                "status": status,
1040                                "progress": s.get_progress(),
1041                                })
1042
1043         return simplejson.dumps(data, indent=1) + "\n"
1044
1045     def _get_all_statuses(self):
1046         h = self.history
1047         return itertools.chain(h.list_all_upload_statuses(),
1048                                h.list_all_download_statuses(),
1049                                h.list_all_mapupdate_statuses(),
1050                                h.list_all_publish_statuses(),
1051                                h.list_all_retrieve_statuses(),
1052                                h.list_all_helper_statuses(),
1053                                )
1054
1055     def data_active_operations(self, ctx, data):
1056         return self._get_active_operations()
1057
1058     def _get_active_operations(self):
1059         active = [s
1060                   for s in self._get_all_statuses()
1061                   if s.get_active()]
1062         return active
1063
1064     def data_recent_operations(self, ctx, data):
1065         return self._get_recent_operations()
1066
1067     def _get_recent_operations(self):
1068         recent = [s
1069                   for s in self._get_all_statuses()
1070                   if not s.get_active()]
1071         recent.sort(lambda a,b: cmp(a.get_started(), b.get_started()))
1072         recent.reverse()
1073         return recent
1074
1075     def render_row(self, ctx, data):
1076         s = data
1077
1078         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1079         started_s = time.strftime(TIME_FORMAT,
1080                                   time.localtime(s.get_started()))
1081         ctx.fillSlots("started", started_s)
1082
1083         si_s = base32.b2a_or_none(s.get_storage_index())
1084         if si_s is None:
1085             si_s = "(None)"
1086         ctx.fillSlots("si", si_s)
1087         ctx.fillSlots("helper", {True: "Yes",
1088                                  False: "No"}[s.using_helper()])
1089
1090         size = s.get_size()
1091         if size is None:
1092             size = "(unknown)"
1093         elif isinstance(size, (int, long, float)):
1094             size = abbreviate_size(size)
1095         ctx.fillSlots("total_size", size)
1096
1097         progress = data.get_progress()
1098         if IUploadStatus.providedBy(data):
1099             link = "up-%d" % data.get_counter()
1100             ctx.fillSlots("type", "upload")
1101             # TODO: make an ascii-art bar
1102             (chk, ciphertext, encandpush) = progress
1103             progress_s = ("hash: %.1f%%, ciphertext: %.1f%%, encode: %.1f%%" %
1104                           ( (100.0 * chk),
1105                             (100.0 * ciphertext),
1106                             (100.0 * encandpush) ))
1107             ctx.fillSlots("progress", progress_s)
1108         elif IDownloadStatus.providedBy(data):
1109             link = "down-%d" % data.get_counter()
1110             ctx.fillSlots("type", "download")
1111             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1112         elif IPublishStatus.providedBy(data):
1113             link = "publish-%d" % data.get_counter()
1114             ctx.fillSlots("type", "publish")
1115             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1116         elif IRetrieveStatus.providedBy(data):
1117             ctx.fillSlots("type", "retrieve")
1118             link = "retrieve-%d" % data.get_counter()
1119             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1120         else:
1121             assert IServermapUpdaterStatus.providedBy(data)
1122             ctx.fillSlots("type", "mapupdate %s" % data.get_mode())
1123             link = "mapupdate-%d" % data.get_counter()
1124             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1125         ctx.fillSlots("status", T.a(href=link)[s.get_status()])
1126         return ctx.tag
1127
1128     def childFactory(self, ctx, name):
1129         h = self.history
1130         stype,count_s = name.split("-")
1131         count = int(count_s)
1132         if stype == "up":
1133             for s in itertools.chain(h.list_all_upload_statuses(),
1134                                      h.list_all_helper_statuses()):
1135                 # immutable-upload helpers use the same status object as a
1136                 # regular immutable-upload
1137                 if s.get_counter() == count:
1138                     return UploadStatusPage(s)
1139         if stype == "down":
1140             for s in h.list_all_download_statuses():
1141                 if s.get_counter() == count:
1142                     return DownloadStatusPage(s)
1143         if stype == "mapupdate":
1144             for s in h.list_all_mapupdate_statuses():
1145                 if s.get_counter() == count:
1146                     return MapupdateStatusPage(s)
1147         if stype == "publish":
1148             for s in h.list_all_publish_statuses():
1149                 if s.get_counter() == count:
1150                     return PublishStatusPage(s)
1151         if stype == "retrieve":
1152             for s in h.list_all_retrieve_statuses():
1153                 if s.get_counter() == count:
1154                     return RetrieveStatusPage(s)
1155
1156
1157 class HelperStatus(rend.Page):
1158     docFactory = getxmlfile("helper.xhtml")
1159
1160     def __init__(self, helper):
1161         rend.Page.__init__(self, helper)
1162         self.helper = helper
1163
1164     def renderHTTP(self, ctx):
1165         req = inevow.IRequest(ctx)
1166         t = get_arg(req, "t")
1167         if t == "json":
1168             return self.render_JSON(req)
1169         return rend.Page.renderHTTP(self, ctx)
1170
1171     def data_helper_stats(self, ctx, data):
1172         return self.helper.get_stats()
1173
1174     def render_JSON(self, req):
1175         req.setHeader("content-type", "text/plain")
1176         if self.helper:
1177             stats = self.helper.get_stats()
1178             return simplejson.dumps(stats, indent=1) + "\n"
1179         return simplejson.dumps({}) + "\n"
1180
1181     def render_active_uploads(self, ctx, data):
1182         return data["chk_upload_helper.active_uploads"]
1183
1184     def render_incoming(self, ctx, data):
1185         return "%d bytes in %d files" % (data["chk_upload_helper.incoming_size"],
1186                                          data["chk_upload_helper.incoming_count"])
1187
1188     def render_encoding(self, ctx, data):
1189         return "%d bytes in %d files" % (data["chk_upload_helper.encoding_size"],
1190                                          data["chk_upload_helper.encoding_count"])
1191
1192     def render_upload_requests(self, ctx, data):
1193         return str(data["chk_upload_helper.upload_requests"])
1194
1195     def render_upload_already_present(self, ctx, data):
1196         return str(data["chk_upload_helper.upload_already_present"])
1197
1198     def render_upload_need_upload(self, ctx, data):
1199         return str(data["chk_upload_helper.upload_need_upload"])
1200
1201     def render_upload_bytes_fetched(self, ctx, data):
1202         return str(data["chk_upload_helper.fetched_bytes"])
1203
1204     def render_upload_bytes_encoded(self, ctx, data):
1205         return str(data["chk_upload_helper.encoded_bytes"])
1206
1207
1208 class Statistics(rend.Page):
1209     docFactory = getxmlfile("statistics.xhtml")
1210
1211     def __init__(self, provider):
1212         rend.Page.__init__(self, provider)
1213         self.provider = provider
1214
1215     def renderHTTP(self, ctx):
1216         req = inevow.IRequest(ctx)
1217         t = get_arg(req, "t")
1218         if t == "json":
1219             stats = self.provider.get_stats()
1220             req.setHeader("content-type", "text/plain")
1221             return simplejson.dumps(stats, indent=1) + "\n"
1222         return rend.Page.renderHTTP(self, ctx)
1223
1224     def data_get_stats(self, ctx, data):
1225         return self.provider.get_stats()
1226
1227     def render_load_average(self, ctx, data):
1228         return str(data["stats"].get("load_monitor.avg_load"))
1229
1230     def render_peak_load(self, ctx, data):
1231         return str(data["stats"].get("load_monitor.max_load"))
1232
1233     def render_uploads(self, ctx, data):
1234         files = data["counters"].get("uploader.files_uploaded", 0)
1235         bytes = data["counters"].get("uploader.bytes_uploaded", 0)
1236         return ("%s files / %s bytes (%s)" %
1237                 (files, bytes, abbreviate_size(bytes)))
1238
1239     def render_downloads(self, ctx, data):
1240         files = data["counters"].get("downloader.files_downloaded", 0)
1241         bytes = data["counters"].get("downloader.bytes_downloaded", 0)
1242         return ("%s files / %s bytes (%s)" %
1243                 (files, bytes, abbreviate_size(bytes)))
1244
1245     def render_publishes(self, ctx, data):
1246         files = data["counters"].get("mutable.files_published", 0)
1247         bytes = data["counters"].get("mutable.bytes_published", 0)
1248         return "%s files / %s bytes (%s)" % (files, bytes,
1249                                              abbreviate_size(bytes))
1250
1251     def render_retrieves(self, ctx, data):
1252         files = data["counters"].get("mutable.files_retrieved", 0)
1253         bytes = data["counters"].get("mutable.bytes_retrieved", 0)
1254         return "%s files / %s bytes (%s)" % (files, bytes,
1255                                              abbreviate_size(bytes))
1256
1257     def render_raw(self, ctx, data):
1258         raw = pprint.pformat(data)
1259         return ctx.tag[raw]