]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/status.py
remove get_serverid from DownloadStatus.add_block_request and customers
[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["server"].get_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             server = r_ev["server"]
583             rtt = None
584             if r_ev["finish_time"] is not None:
585                 rtt = r_ev["finish_time"] - r_ev["start_time"]
586             color = self.color(server.get_serverid())
587             t[T.tr(style="background: %s" % color)[
588                 T.td[server.get_name()], T.td[r_ev["shnum"]],
589                 T.td["[%d:+%d]" % (r_ev["start"], r_ev["length"])],
590                 T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
591                 T.td[r_ev["response_length"] or ""],
592                 T.td[self.render_time(None, rtt)],
593                 ]]
594
595         l[T.h2["Requests:"], t]
596         l[T.br(clear="all")]
597
598         return l
599
600     def color(self, peerid):
601         def m(c):
602             return min(ord(c) / 2 + 0x80, 0xff)
603         return "#%02x%02x%02x" % (m(peerid[0]), m(peerid[1]), m(peerid[2]))
604
605     def render_results(self, ctx, data):
606         d = self.download_results()
607         def _got_results(results):
608             if results:
609                 return ctx.tag
610             return ""
611         d.addCallback(_got_results)
612         return d
613
614     def render_started(self, ctx, data):
615         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
616         started_s = time.strftime(TIME_FORMAT,
617                                   time.localtime(data.get_started()))
618         return started_s + " (%s)" % data.get_started()
619
620     def render_si(self, ctx, data):
621         si_s = base32.b2a_or_none(data.get_storage_index())
622         if si_s is None:
623             si_s = "(None)"
624         return si_s
625
626     def render_helper(self, ctx, data):
627         return {True: "Yes",
628                 False: "No"}[data.using_helper()]
629
630     def render_total_size(self, ctx, data):
631         size = data.get_size()
632         if size is None:
633             return "(unknown)"
634         return size
635
636     def render_progress(self, ctx, data):
637         progress = data.get_progress()
638         # TODO: make an ascii-art bar
639         return "%.1f%%" % (100.0 * progress)
640
641     def render_status(self, ctx, data):
642         return data.get_status()
643
644 class DownloadStatusTimelinePage(rend.Page):
645     docFactory = getxmlfile("download-status-timeline.xhtml")
646
647     def render_started(self, ctx, data):
648         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
649         started_s = time.strftime(TIME_FORMAT,
650                                   time.localtime(data.get_started()))
651         return started_s + " (%s)" % data.get_started()
652
653     def render_si(self, ctx, data):
654         si_s = base32.b2a_or_none(data.get_storage_index())
655         if si_s is None:
656             si_s = "(None)"
657         return si_s
658
659     def render_helper(self, ctx, data):
660         return {True: "Yes",
661                 False: "No"}[data.using_helper()]
662
663     def render_total_size(self, ctx, data):
664         size = data.get_size()
665         if size is None:
666             return "(unknown)"
667         return size
668
669     def render_progress(self, ctx, data):
670         progress = data.get_progress()
671         # TODO: make an ascii-art bar
672         return "%.1f%%" % (100.0 * progress)
673
674     def render_status(self, ctx, data):
675         return data.get_status()
676
677 class RetrieveStatusPage(rend.Page, RateAndTimeMixin):
678     docFactory = getxmlfile("retrieve-status.xhtml")
679
680     def __init__(self, data):
681         rend.Page.__init__(self, data)
682         self.retrieve_status = data
683
684     def render_started(self, ctx, data):
685         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
686         started_s = time.strftime(TIME_FORMAT,
687                                   time.localtime(data.get_started()))
688         return started_s
689
690     def render_si(self, ctx, data):
691         si_s = base32.b2a_or_none(data.get_storage_index())
692         if si_s is None:
693             si_s = "(None)"
694         return si_s
695
696     def render_helper(self, ctx, data):
697         return {True: "Yes",
698                 False: "No"}[data.using_helper()]
699
700     def render_current_size(self, ctx, data):
701         size = data.get_size()
702         if size is None:
703             size = "(unknown)"
704         return size
705
706     def render_progress(self, ctx, data):
707         progress = data.get_progress()
708         # TODO: make an ascii-art bar
709         return "%.1f%%" % (100.0 * progress)
710
711     def render_status(self, ctx, data):
712         return data.get_status()
713
714     def render_encoding(self, ctx, data):
715         k, n = data.get_encoding()
716         return ctx.tag["Encoding: %s of %s" % (k, n)]
717
718     def render_problems(self, ctx, data):
719         problems = data.problems
720         if not problems:
721             return ""
722         l = T.ul()
723         for peerid in sorted(problems.keys()):
724             peerid_s = idlib.shortnodeid_b2a(peerid)
725             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
726         return ctx.tag["Server Problems:", l]
727
728     def _get_rate(self, data, name):
729         file_size = self.retrieve_status.get_size()
730         time = self.retrieve_status.timings.get(name)
731         return compute_rate(file_size, time)
732
733     def data_time_total(self, ctx, data):
734         return self.retrieve_status.timings.get("total")
735     def data_rate_total(self, ctx, data):
736         return self._get_rate(data, "total")
737
738     def data_time_fetch(self, ctx, data):
739         return self.retrieve_status.timings.get("fetch")
740     def data_rate_fetch(self, ctx, data):
741         return self._get_rate(data, "fetch")
742
743     def data_time_decode(self, ctx, data):
744         return self.retrieve_status.timings.get("decode")
745     def data_rate_decode(self, ctx, data):
746         return self._get_rate(data, "decode")
747
748     def data_time_decrypt(self, ctx, data):
749         return self.retrieve_status.timings.get("decrypt")
750     def data_rate_decrypt(self, ctx, data):
751         return self._get_rate(data, "decrypt")
752
753     def render_server_timings(self, ctx, data):
754         per_server = self.retrieve_status.timings.get("fetch_per_server")
755         if not per_server:
756             return ""
757         l = T.ul()
758         for peerid in sorted(per_server.keys()):
759             peerid_s = idlib.shortnodeid_b2a(peerid)
760             times_s = ", ".join([self.render_time(None, t)
761                                  for t in per_server[peerid]])
762             l[T.li["[%s]: %s" % (peerid_s, times_s)]]
763         return T.li["Per-Server Fetch Response Times: ", l]
764
765
766 class PublishStatusPage(rend.Page, RateAndTimeMixin):
767     docFactory = getxmlfile("publish-status.xhtml")
768
769     def __init__(self, data):
770         rend.Page.__init__(self, data)
771         self.publish_status = data
772
773     def render_started(self, ctx, data):
774         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
775         started_s = time.strftime(TIME_FORMAT,
776                                   time.localtime(data.get_started()))
777         return started_s
778
779     def render_si(self, ctx, data):
780         si_s = base32.b2a_or_none(data.get_storage_index())
781         if si_s is None:
782             si_s = "(None)"
783         return si_s
784
785     def render_helper(self, ctx, data):
786         return {True: "Yes",
787                 False: "No"}[data.using_helper()]
788
789     def render_current_size(self, ctx, data):
790         size = data.get_size()
791         if size is None:
792             size = "(unknown)"
793         return size
794
795     def render_progress(self, ctx, data):
796         progress = data.get_progress()
797         # TODO: make an ascii-art bar
798         return "%.1f%%" % (100.0 * progress)
799
800     def render_status(self, ctx, data):
801         return data.get_status()
802
803     def render_encoding(self, ctx, data):
804         k, n = data.get_encoding()
805         return ctx.tag["Encoding: %s of %s" % (k, n)]
806
807     def render_sharemap(self, ctx, data):
808         servermap = data.get_servermap()
809         if servermap is None:
810             return ctx.tag["None"]
811         l = T.ul()
812         sharemap = servermap.make_sharemap()
813         for shnum in sorted(sharemap.keys()):
814             l[T.li["%d -> Placed on " % shnum,
815                    ", ".join(["[%s]" % idlib.shortnodeid_b2a(peerid)
816                               for peerid in sharemap[shnum]])]]
817         return ctx.tag["Sharemap:", l]
818
819     def render_problems(self, ctx, data):
820         problems = data.problems
821         if not problems:
822             return ""
823         l = T.ul()
824         for peerid in sorted(problems.keys()):
825             peerid_s = idlib.shortnodeid_b2a(peerid)
826             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
827         return ctx.tag["Server Problems:", l]
828
829     def _get_rate(self, data, name):
830         file_size = self.publish_status.get_size()
831         time = self.publish_status.timings.get(name)
832         return compute_rate(file_size, time)
833
834     def data_time_total(self, ctx, data):
835         return self.publish_status.timings.get("total")
836     def data_rate_total(self, ctx, data):
837         return self._get_rate(data, "total")
838
839     def data_time_setup(self, ctx, data):
840         return self.publish_status.timings.get("setup")
841
842     def data_time_encrypt(self, ctx, data):
843         return self.publish_status.timings.get("encrypt")
844     def data_rate_encrypt(self, ctx, data):
845         return self._get_rate(data, "encrypt")
846
847     def data_time_encode(self, ctx, data):
848         return self.publish_status.timings.get("encode")
849     def data_rate_encode(self, ctx, data):
850         return self._get_rate(data, "encode")
851
852     def data_time_pack(self, ctx, data):
853         return self.publish_status.timings.get("pack")
854     def data_rate_pack(self, ctx, data):
855         return self._get_rate(data, "pack")
856     def data_time_sign(self, ctx, data):
857         return self.publish_status.timings.get("sign")
858
859     def data_time_push(self, ctx, data):
860         return self.publish_status.timings.get("push")
861     def data_rate_push(self, ctx, data):
862         return self._get_rate(data, "push")
863
864     def render_server_timings(self, ctx, data):
865         per_server = self.publish_status.timings.get("send_per_server")
866         if not per_server:
867             return ""
868         l = T.ul()
869         for peerid in sorted(per_server.keys()):
870             peerid_s = idlib.shortnodeid_b2a(peerid)
871             times_s = ", ".join([self.render_time(None, t)
872                                  for t in per_server[peerid]])
873             l[T.li["[%s]: %s" % (peerid_s, times_s)]]
874         return T.li["Per-Server Response Times: ", l]
875
876 class MapupdateStatusPage(rend.Page, RateAndTimeMixin):
877     docFactory = getxmlfile("map-update-status.xhtml")
878
879     def __init__(self, data):
880         rend.Page.__init__(self, data)
881         self.update_status = data
882
883     def render_started(self, ctx, data):
884         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
885         started_s = time.strftime(TIME_FORMAT,
886                                   time.localtime(data.get_started()))
887         return started_s
888
889     def render_finished(self, ctx, data):
890         when = data.get_finished()
891         if not when:
892             return "not yet"
893         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
894         started_s = time.strftime(TIME_FORMAT,
895                                   time.localtime(data.get_finished()))
896         return started_s
897
898     def render_si(self, ctx, data):
899         si_s = base32.b2a_or_none(data.get_storage_index())
900         if si_s is None:
901             si_s = "(None)"
902         return si_s
903
904     def render_helper(self, ctx, data):
905         return {True: "Yes",
906                 False: "No"}[data.using_helper()]
907
908     def render_progress(self, ctx, data):
909         progress = data.get_progress()
910         # TODO: make an ascii-art bar
911         return "%.1f%%" % (100.0 * progress)
912
913     def render_status(self, ctx, data):
914         return data.get_status()
915
916     def render_problems(self, ctx, data):
917         problems = data.problems
918         if not problems:
919             return ""
920         l = T.ul()
921         for peerid in sorted(problems.keys()):
922             peerid_s = idlib.shortnodeid_b2a(peerid)
923             l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
924         return ctx.tag["Server Problems:", l]
925
926     def render_privkey_from(self, ctx, data):
927         peerid = data.get_privkey_from()
928         if peerid:
929             return ctx.tag["Got privkey from: [%s]"
930                            % idlib.shortnodeid_b2a(peerid)]
931         else:
932             return ""
933
934     def data_time_total(self, ctx, data):
935         return self.update_status.timings.get("total")
936
937     def data_time_initial_queries(self, ctx, data):
938         return self.update_status.timings.get("initial_queries")
939
940     def data_time_cumulative_verify(self, ctx, data):
941         return self.update_status.timings.get("cumulative_verify")
942
943     def render_server_timings(self, ctx, data):
944         per_server = self.update_status.timings.get("per_server")
945         if not per_server:
946             return ""
947         l = T.ul()
948         for peerid in sorted(per_server.keys()):
949             peerid_s = idlib.shortnodeid_b2a(peerid)
950             times = []
951             for op,started,t in per_server[peerid]:
952                 #times.append("%s/%.4fs/%s/%s" % (op,
953                 #                              started,
954                 #                              self.render_time(None, started - self.update_status.get_started()),
955                 #                              self.render_time(None,t)))
956                 if op == "query":
957                     times.append( self.render_time(None, t) )
958                 elif op == "late":
959                     times.append( "late(" + self.render_time(None, t) + ")" )
960                 else:
961                     times.append( "privkey(" + self.render_time(None, t) + ")" )
962             times_s = ", ".join(times)
963             l[T.li["[%s]: %s" % (peerid_s, times_s)]]
964         return T.li["Per-Server Response Times: ", l]
965
966     def render_timing_chart(self, ctx, data):
967         imageurl = self._timing_chart()
968         return ctx.tag[imageurl]
969
970     def _timing_chart(self):
971         started = self.update_status.get_started()
972         total = self.update_status.timings.get("total")
973         per_server = self.update_status.timings.get("per_server")
974         base = "http://chart.apis.google.com/chart?"
975         pieces = ["cht=bhs"]
976         pieces.append("chco=ffffff,4d89f9,c6d9fd") # colors
977         data0 = []
978         data1 = []
979         data2 = []
980         nb_nodes = 0
981         graph_botom_margin= 21
982         graph_top_margin = 5
983         peerids_s = []
984         top_abs = started
985         # we sort the queries by the time at which we sent the first request
986         sorttable = [ (times[0][1], peerid)
987                       for peerid, times in per_server.items() ]
988         sorttable.sort()
989         peerids = [t[1] for t in sorttable]
990
991         for peerid in peerids:
992             nb_nodes += 1
993             times = per_server[peerid]
994             peerid_s = idlib.shortnodeid_b2a(peerid)
995             peerids_s.append(peerid_s)
996             # for servermap updates, there are either one or two queries per
997             # peer. The second (if present) is to get the privkey.
998             op,q_started,q_elapsed = times[0]
999             data0.append("%.3f" % (q_started-started))
1000             data1.append("%.3f" % q_elapsed)
1001             top_abs = max(top_abs, q_started+q_elapsed)
1002             if len(times) > 1:
1003                 op,p_started,p_elapsed = times[0]
1004                 data2.append("%.3f" % p_elapsed)
1005                 top_abs = max(top_abs, p_started+p_elapsed)
1006             else:
1007                 data2.append("0.0")
1008         finished = self.update_status.get_finished()
1009         if finished:
1010             top_abs = max(top_abs, finished)
1011         top_rel = top_abs - started
1012         chs ="chs=400x%d" % ( (nb_nodes*28) + graph_top_margin + graph_botom_margin )
1013         chd = "chd=t:" + "|".join([",".join(data0),
1014                                    ",".join(data1),
1015                                    ",".join(data2)])
1016         pieces.append(chd)
1017         pieces.append(chs)
1018         chds = "chds=0,%0.3f" % top_rel
1019         pieces.append(chds)
1020         pieces.append("chxt=x,y")
1021         pieces.append("chxr=0,0.0,%0.3f" % top_rel)
1022         pieces.append("chxl=1:|" + "|".join(reversed(peerids_s)))
1023         # use up to 10 grid lines, at decimal multiples.
1024         # mathutil.next_power_of_k doesn't handle numbers smaller than one,
1025         # unfortunately.
1026         #pieces.append("chg="
1027
1028         if total is not None:
1029             finished_f = 1.0 * total / top_rel
1030             pieces.append("chm=r,FF0000,0,%0.3f,%0.3f" % (finished_f,
1031                                                           finished_f+0.01))
1032         url = base + "&".join(pieces)
1033         return T.img(src=url,border="1",align="right", float="right")
1034
1035
1036 class Status(rend.Page):
1037     docFactory = getxmlfile("status.xhtml")
1038     addSlash = True
1039
1040     def __init__(self, history):
1041         rend.Page.__init__(self, history)
1042         self.history = history
1043
1044     def renderHTTP(self, ctx):
1045         req = inevow.IRequest(ctx)
1046         t = get_arg(req, "t")
1047         if t == "json":
1048             return self.json(req)
1049         return rend.Page.renderHTTP(self, ctx)
1050
1051     def json(self, req):
1052         req.setHeader("content-type", "text/plain")
1053         data = {}
1054         data["active"] = active = []
1055         for s in self._get_active_operations():
1056             si_s = base32.b2a_or_none(s.get_storage_index())
1057             size = s.get_size()
1058             status = s.get_status()
1059             if IUploadStatus.providedBy(s):
1060                 h,c,e = s.get_progress()
1061                 active.append({"type": "upload",
1062                                "storage-index-string": si_s,
1063                                "total-size": size,
1064                                "status": status,
1065                                "progress-hash": h,
1066                                "progress-ciphertext": c,
1067                                "progress-encode-push": e,
1068                                })
1069             elif IDownloadStatus.providedBy(s):
1070                 active.append({"type": "download",
1071                                "storage-index-string": si_s,
1072                                "total-size": size,
1073                                "status": status,
1074                                "progress": s.get_progress(),
1075                                })
1076
1077         return simplejson.dumps(data, indent=1) + "\n"
1078
1079     def _get_all_statuses(self):
1080         h = self.history
1081         return itertools.chain(h.list_all_upload_statuses(),
1082                                h.list_all_download_statuses(),
1083                                h.list_all_mapupdate_statuses(),
1084                                h.list_all_publish_statuses(),
1085                                h.list_all_retrieve_statuses(),
1086                                h.list_all_helper_statuses(),
1087                                )
1088
1089     def data_active_operations(self, ctx, data):
1090         return self._get_active_operations()
1091
1092     def _get_active_operations(self):
1093         active = [s
1094                   for s in self._get_all_statuses()
1095                   if s.get_active()]
1096         return active
1097
1098     def data_recent_operations(self, ctx, data):
1099         return self._get_recent_operations()
1100
1101     def _get_recent_operations(self):
1102         recent = [s
1103                   for s in self._get_all_statuses()
1104                   if not s.get_active()]
1105         recent.sort(lambda a,b: cmp(a.get_started(), b.get_started()))
1106         recent.reverse()
1107         return recent
1108
1109     def render_row(self, ctx, data):
1110         s = data
1111
1112         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1113         started_s = time.strftime(TIME_FORMAT,
1114                                   time.localtime(s.get_started()))
1115         ctx.fillSlots("started", started_s)
1116
1117         si_s = base32.b2a_or_none(s.get_storage_index())
1118         if si_s is None:
1119             si_s = "(None)"
1120         ctx.fillSlots("si", si_s)
1121         ctx.fillSlots("helper", {True: "Yes",
1122                                  False: "No"}[s.using_helper()])
1123
1124         size = s.get_size()
1125         if size is None:
1126             size = "(unknown)"
1127         elif isinstance(size, (int, long, float)):
1128             size = abbreviate_size(size)
1129         ctx.fillSlots("total_size", size)
1130
1131         progress = data.get_progress()
1132         if IUploadStatus.providedBy(data):
1133             link = "up-%d" % data.get_counter()
1134             ctx.fillSlots("type", "upload")
1135             # TODO: make an ascii-art bar
1136             (chk, ciphertext, encandpush) = progress
1137             progress_s = ("hash: %.1f%%, ciphertext: %.1f%%, encode: %.1f%%" %
1138                           ( (100.0 * chk),
1139                             (100.0 * ciphertext),
1140                             (100.0 * encandpush) ))
1141             ctx.fillSlots("progress", progress_s)
1142         elif IDownloadStatus.providedBy(data):
1143             link = "down-%d" % data.get_counter()
1144             ctx.fillSlots("type", "download")
1145             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1146         elif IPublishStatus.providedBy(data):
1147             link = "publish-%d" % data.get_counter()
1148             ctx.fillSlots("type", "publish")
1149             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1150         elif IRetrieveStatus.providedBy(data):
1151             ctx.fillSlots("type", "retrieve")
1152             link = "retrieve-%d" % data.get_counter()
1153             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1154         else:
1155             assert IServermapUpdaterStatus.providedBy(data)
1156             ctx.fillSlots("type", "mapupdate %s" % data.get_mode())
1157             link = "mapupdate-%d" % data.get_counter()
1158             ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1159         ctx.fillSlots("status", T.a(href=link)[s.get_status()])
1160         return ctx.tag
1161
1162     def childFactory(self, ctx, name):
1163         h = self.history
1164         stype,count_s = name.split("-")
1165         count = int(count_s)
1166         if stype == "up":
1167             for s in itertools.chain(h.list_all_upload_statuses(),
1168                                      h.list_all_helper_statuses()):
1169                 # immutable-upload helpers use the same status object as a
1170                 # regular immutable-upload
1171                 if s.get_counter() == count:
1172                     return UploadStatusPage(s)
1173         if stype == "down":
1174             for s in h.list_all_download_statuses():
1175                 if s.get_counter() == count:
1176                     return DownloadStatusPage(s)
1177         if stype == "mapupdate":
1178             for s in h.list_all_mapupdate_statuses():
1179                 if s.get_counter() == count:
1180                     return MapupdateStatusPage(s)
1181         if stype == "publish":
1182             for s in h.list_all_publish_statuses():
1183                 if s.get_counter() == count:
1184                     return PublishStatusPage(s)
1185         if stype == "retrieve":
1186             for s in h.list_all_retrieve_statuses():
1187                 if s.get_counter() == count:
1188                     return RetrieveStatusPage(s)
1189
1190
1191 class HelperStatus(rend.Page):
1192     docFactory = getxmlfile("helper.xhtml")
1193
1194     def __init__(self, helper):
1195         rend.Page.__init__(self, helper)
1196         self.helper = helper
1197
1198     def renderHTTP(self, ctx):
1199         req = inevow.IRequest(ctx)
1200         t = get_arg(req, "t")
1201         if t == "json":
1202             return self.render_JSON(req)
1203         return rend.Page.renderHTTP(self, ctx)
1204
1205     def data_helper_stats(self, ctx, data):
1206         return self.helper.get_stats()
1207
1208     def render_JSON(self, req):
1209         req.setHeader("content-type", "text/plain")
1210         if self.helper:
1211             stats = self.helper.get_stats()
1212             return simplejson.dumps(stats, indent=1) + "\n"
1213         return simplejson.dumps({}) + "\n"
1214
1215     def render_active_uploads(self, ctx, data):
1216         return data["chk_upload_helper.active_uploads"]
1217
1218     def render_incoming(self, ctx, data):
1219         return "%d bytes in %d files" % (data["chk_upload_helper.incoming_size"],
1220                                          data["chk_upload_helper.incoming_count"])
1221
1222     def render_encoding(self, ctx, data):
1223         return "%d bytes in %d files" % (data["chk_upload_helper.encoding_size"],
1224                                          data["chk_upload_helper.encoding_count"])
1225
1226     def render_upload_requests(self, ctx, data):
1227         return str(data["chk_upload_helper.upload_requests"])
1228
1229     def render_upload_already_present(self, ctx, data):
1230         return str(data["chk_upload_helper.upload_already_present"])
1231
1232     def render_upload_need_upload(self, ctx, data):
1233         return str(data["chk_upload_helper.upload_need_upload"])
1234
1235     def render_upload_bytes_fetched(self, ctx, data):
1236         return str(data["chk_upload_helper.fetched_bytes"])
1237
1238     def render_upload_bytes_encoded(self, ctx, data):
1239         return str(data["chk_upload_helper.encoded_bytes"])
1240
1241
1242 class Statistics(rend.Page):
1243     docFactory = getxmlfile("statistics.xhtml")
1244
1245     def __init__(self, provider):
1246         rend.Page.__init__(self, provider)
1247         self.provider = provider
1248
1249     def renderHTTP(self, ctx):
1250         req = inevow.IRequest(ctx)
1251         t = get_arg(req, "t")
1252         if t == "json":
1253             stats = self.provider.get_stats()
1254             req.setHeader("content-type", "text/plain")
1255             return simplejson.dumps(stats, indent=1) + "\n"
1256         return rend.Page.renderHTTP(self, ctx)
1257
1258     def data_get_stats(self, ctx, data):
1259         return self.provider.get_stats()
1260
1261     def render_load_average(self, ctx, data):
1262         return str(data["stats"].get("load_monitor.avg_load"))
1263
1264     def render_peak_load(self, ctx, data):
1265         return str(data["stats"].get("load_monitor.max_load"))
1266
1267     def render_uploads(self, ctx, data):
1268         files = data["counters"].get("uploader.files_uploaded", 0)
1269         bytes = data["counters"].get("uploader.bytes_uploaded", 0)
1270         return ("%s files / %s bytes (%s)" %
1271                 (files, bytes, abbreviate_size(bytes)))
1272
1273     def render_downloads(self, ctx, data):
1274         files = data["counters"].get("downloader.files_downloaded", 0)
1275         bytes = data["counters"].get("downloader.bytes_downloaded", 0)
1276         return ("%s files / %s bytes (%s)" %
1277                 (files, bytes, abbreviate_size(bytes)))
1278
1279     def render_publishes(self, ctx, data):
1280         files = data["counters"].get("mutable.files_published", 0)
1281         bytes = data["counters"].get("mutable.bytes_published", 0)
1282         return "%s files / %s bytes (%s)" % (files, bytes,
1283                                              abbreviate_size(bytes))
1284
1285     def render_retrieves(self, ctx, data):
1286         files = data["counters"].get("mutable.files_retrieved", 0)
1287         bytes = data["counters"].get("mutable.bytes_retrieved", 0)
1288         return "%s files / %s bytes (%s)" % (files, bytes,
1289                                              abbreviate_size(bytes))
1290
1291     def render_raw(self, ctx, data):
1292         raw = pprint.pformat(data)
1293         return ctx.tag[raw]