2 import time, pprint, itertools
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
12 class RateAndTimeMixin:
14 def render_time(self, ctx, data):
15 return abbreviate_time(data)
17 def render_rate(self, ctx, data):
18 return abbreviate_rate(data)
20 class UploadResultsRendererMixin(RateAndTimeMixin):
21 # this requires a method named 'upload_results'
23 def render_pushed_shares(self, ctx, data):
24 d = self.upload_results()
25 d.addCallback(lambda res: res.pushed_shares)
28 def render_preexisting_shares(self, ctx, data):
29 d = self.upload_results()
30 d.addCallback(lambda res: res.preexisting_shares)
33 def render_sharemap(self, ctx, data):
34 d = self.upload_results()
35 d.addCallback(lambda res: res.sharemap)
36 def _render(sharemap):
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)]]
44 d.addCallback(_render)
47 def render_servermap(self, ctx, data):
48 d = self.upload_results()
49 d.addCallback(lambda res: res.servermap)
50 def _render(servermap):
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]),
62 d.addCallback(_render)
65 def data_file_size(self, ctx, data):
66 d = self.upload_results()
67 d.addCallback(lambda res: res.file_size)
70 def _get_time(self, name):
71 d = self.upload_results()
72 d.addCallback(lambda res: res.timings.get(name))
75 def data_time_total(self, ctx, data):
76 return self._get_time("total")
78 def data_time_storage_index(self, ctx, data):
79 return self._get_time("storage_index")
81 def data_time_contacting_helper(self, ctx, data):
82 return self._get_time("contacting_helper")
84 def data_time_existence_check(self, ctx, data):
85 return self._get_time("existence_check")
87 def data_time_cumulative_fetch(self, ctx, data):
88 return self._get_time("cumulative_fetch")
90 def data_time_helper_total(self, ctx, data):
91 return self._get_time("helper_total")
93 def data_time_peer_selection(self, ctx, data):
94 return self._get_time("peer_selection")
96 def data_time_total_encode_and_push(self, ctx, data):
97 return self._get_time("total_encode_and_push")
99 def data_time_cumulative_encoding(self, ctx, data):
100 return self._get_time("cumulative_encoding")
102 def data_time_cumulative_sending(self, ctx, data):
103 return self._get_time("cumulative_sending")
105 def data_time_hashes_and_close(self, ctx, data):
106 return self._get_time("hashes_and_close")
108 def _get_rate(self, name):
109 d = self.upload_results()
111 file_size = r.file_size
112 time = r.timings.get(name)
113 return compute_rate(file_size, time)
114 d.addCallback(_convert)
117 def data_rate_total(self, ctx, data):
118 return self._get_rate("total")
120 def data_rate_storage_index(self, ctx, data):
121 return self._get_rate("storage_index")
123 def data_rate_encode(self, ctx, data):
124 return self._get_rate("cumulative_encoding")
126 def data_rate_push(self, ctx, data):
127 return self._get_rate("cumulative_sending")
129 def data_rate_encode_and_push(self, ctx, data):
130 d = self.upload_results()
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):
138 return compute_rate(file_size, time1+time2)
139 d.addCallback(_convert)
142 def data_rate_ciphertext_fetch(self, ctx, data):
143 d = self.upload_results()
145 fetch_size = r.ciphertext_fetched
146 time = r.timings.get("cumulative_fetch")
147 return compute_rate(fetch_size, time)
148 d.addCallback(_convert)
151 class UploadStatusPage(UploadResultsRendererMixin, rend.Page):
152 docFactory = getxmlfile("upload-status.xhtml")
154 def __init__(self, data):
155 rend.Page.__init__(self, data)
156 self.upload_status = data
158 def upload_results(self):
159 return defer.maybeDeferred(self.upload_status.get_results)
161 def render_results(self, ctx, data):
162 d = self.upload_results()
163 def _got_results(results):
167 d.addCallback(_got_results)
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()))
176 def render_si(self, ctx, data):
177 si_s = base32.b2a_or_none(data.get_storage_index())
182 def render_helper(self, ctx, data):
184 False: "No"}[data.using_helper()]
186 def render_total_size(self, ctx, data):
187 size = data.get_size()
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)
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)
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)
207 def render_status(self, ctx, data):
208 return data.get_status()
210 class DownloadResultsRendererMixin(RateAndTimeMixin):
211 # this requires a method named 'download_results'
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:
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]),
228 d.addCallback(_render)
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):
237 peerids_s = ", ".join(["[%s]" % idlib.shortnodeid_b2a(peerid)
238 for peerid in servers_used])
239 return T.li["Servers Used: ", peerids_s]
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:
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]
257 def data_file_size(self, ctx, data):
258 d = self.download_results()
259 d.addCallback(lambda res: res.file_size)
262 def _get_time(self, name):
263 d = self.download_results()
264 d.addCallback(lambda res: res.timings.get(name))
267 def data_time_total(self, ctx, data):
268 return self._get_time("total")
270 def data_time_peer_selection(self, ctx, data):
271 return self._get_time("peer_selection")
273 def data_time_uri_extension(self, ctx, data):
274 return self._get_time("uri_extension")
276 def data_time_hashtrees(self, ctx, data):
277 return self._get_time("hashtrees")
279 def data_time_segments(self, ctx, data):
280 return self._get_time("segments")
282 def data_time_cumulative_fetch(self, ctx, data):
283 return self._get_time("cumulative_fetch")
285 def data_time_cumulative_decode(self, ctx, data):
286 return self._get_time("cumulative_decode")
288 def data_time_cumulative_decrypt(self, ctx, data):
289 return self._get_time("cumulative_decrypt")
291 def data_time_paused(self, ctx, data):
292 return self._get_time("paused")
294 def _get_rate(self, name):
295 d = self.download_results()
297 file_size = r.file_size
298 time = r.timings.get(name)
299 return compute_rate(file_size, time)
300 d.addCallback(_convert)
303 def data_rate_total(self, ctx, data):
304 return self._get_rate("total")
306 def data_rate_segments(self, ctx, data):
307 return self._get_rate("segments")
309 def data_rate_fetch(self, ctx, data):
310 return self._get_rate("cumulative_fetch")
312 def data_rate_decode(self, ctx, data):
313 return self._get_rate("cumulative_decode")
315 def data_rate_decrypt(self, ctx, data):
316 return self._get_rate("cumulative_decrypt")
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:
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)
334 class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
335 docFactory = getxmlfile("download-status.xhtml")
337 def __init__(self, data):
338 rend.Page.__init__(self, data)
339 self.download_status = data
341 def child_timeline(self, ctx):
342 return DownloadStatusTimelinePage(self.download_status)
344 def download_results(self):
345 return defer.maybeDeferred(self.download_status.get_results)
347 def relative_time(self, t):
350 if self.download_status.first_timestamp is not None:
351 return t - self.download_status.first_timestamp
353 def short_relative_time(self, t):
354 t = self.relative_time(t)
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), and if appropriate
362 # a "serverid" key (ascii-encoded server id), replacing the "server"
363 # key. This is a hint to our JS frontend about how to overlap the
364 # parts of the graph it is drawing.
366 # we must always make a copy, since we're going to be adding keys
367 # and don't want to change the original objects. If we're
368 # stringifying serverids, we'll also be changing the serverid keys.
373 if ev.has_key('server'):
374 ev["serverid"] = base32.b2a(ev["server"].get_serverid())
376 # find an empty slot in the rows
378 for row,finished in enumerate(rows):
379 if finished is not None:
380 if ev[start_key] > finished:
383 if free_slot is None:
384 free_slot = len(rows)
385 rows.append(ev[end_key])
387 rows[free_slot] = ev[end_key]
388 ev["row"] = free_slot
389 new_events.append(ev)
392 def _find_overlap_requests(self, events):
393 """We compute a three-element 'row tuple' for each event: (serverid,
394 shnum, row). All elements are ints. The first is a mapping from
395 serverid to group number, the second is a mapping from shnum to
396 subgroup number. The third is a row within the subgroup.
398 We also return a list of lists of rowcounts, so renderers can decide
399 how much vertical space to give to each row.
402 serverid_to_group = {}
403 groupnum_to_rows = {} # maps groupnum to a table of rows. Each table
404 # is a list with an element for each row number
405 # (int starting from 0) that contains a
406 # finish_time, indicating that the row is empty
407 # beyond that time. If finish_time is None, it
408 # indicate a response that has not yet
409 # completed, so the row cannot be reused.
412 # DownloadStatus promises to give us events in temporal order
414 ev["serverid"] = base32.b2a(ev["server"].get_serverid())
416 if ev["serverid"] not in serverid_to_group:
417 groupnum = len(serverid_to_group)
418 serverid_to_group[ev["serverid"]] = groupnum
419 groupnum = serverid_to_group[ev["serverid"]]
420 if groupnum not in groupnum_to_rows:
421 groupnum_to_rows[groupnum] = []
422 rows = groupnum_to_rows[groupnum]
423 # find an empty slot in the rows
425 for row,finished in enumerate(rows):
426 if finished is not None:
427 if ev["start_time"] > finished:
430 if free_slot is None:
431 free_slot = len(rows)
432 rows.append(ev["finish_time"])
434 rows[free_slot] = ev["finish_time"]
435 ev["row"] = (groupnum, free_slot)
436 new_events.append(ev)
437 # maybe also return serverid_to_group, groupnum_to_rows, and some
438 # indication of the highest finish_time
440 # actually, return the highest rownum for each groupnum
441 highest_rownums = [len(groupnum_to_rows[groupnum])
442 for groupnum in range(len(serverid_to_group))]
443 return new_events, highest_rownums
445 def child_event_json(self, ctx):
446 inevow.IRequest(ctx).setHeader("content-type", "text/plain")
447 data = { } # this will be returned to the GET
448 ds = self.download_status
450 data["misc"] = self._find_overlap(ds.misc_events,
451 "start_time", "finish_time")
452 data["read"] = self._find_overlap(ds.read_events,
453 "start_time", "finish_time")
454 data["segment"] = self._find_overlap(ds.segment_events,
455 "start_time", "finish_time")
456 # TODO: overlap on DYHB isn't very useful, and usually gets in the
457 # way. So don't do it.
458 data["dyhb"] = self._find_overlap(ds.dyhb_requests,
459 "start_time", "finish_time")
460 data["block"],data["block_rownums"] = self._find_overlap_requests(ds.block_requests)
463 serverid_strings = {}
464 for d_ev in data["dyhb"]:
465 if d_ev["serverid"] not in servernums:
466 servernum = len(servernums)
467 servernums[d_ev["serverid"]] = servernum
468 #title= "%s: %s" % ( ",".join([str(shnum) for shnum in shnums]))
469 serverid_strings[servernum] = d_ev["serverid"][:4]
470 data["server_info"] = dict([(serverid, {"num": servernums[serverid],
471 "color": self.color(base32.a2b(serverid)),
472 "short": serverid_strings[servernums[serverid]],
474 for serverid in servernums.keys()])
475 data["num_serverids"] = len(serverid_strings)
476 # we'd prefer the keys of serverids[] to be ints, but this is JSON,
477 # so they get converted to strings. Stupid javascript.
478 data["serverids"] = serverid_strings
479 data["bounds"] = {"min": ds.first_timestamp, "max": ds.last_timestamp}
480 return simplejson.dumps(data, indent=1) + "\n"
482 def render_timeline_link(self, ctx, data):
483 from nevow import url
484 return T.a(href=url.URL.fromContext(ctx).child("timeline"))["timeline"]
486 def _rate_and_time(self, bytes, seconds):
487 time_s = self.render_time(None, seconds)
489 rate = self.render_rate(None, 1.0 * bytes / seconds)
490 return T.span(title=rate)[time_s]
491 return T.span[time_s]
493 def render_events(self, ctx, data):
494 if not self.download_status.storage_index:
496 srt = self.short_relative_time
499 t = T.table(align="left", class_="status-download-events")
500 t[T.tr[T.th["serverid"], T.th["sent"], T.th["received"],
501 T.th["shnums"], T.th["RTT"]]]
502 for d_ev in self.download_status.dyhb_requests:
503 server = d_ev["server"]
504 sent = d_ev["start_time"]
505 shnums = d_ev["response_shnums"]
506 received = d_ev["finish_time"]
508 if received is not None:
509 rtt = received - sent
512 t[T.tr(style="background: %s" % self.color(server.get_serverid()))[
513 [T.td[server.get_name()], T.td[srt(sent)], T.td[srt(received)],
514 T.td[",".join([str(shnum) for shnum in shnums])],
515 T.td[self.render_time(None, rtt)],
518 l[T.h2["DYHB Requests:"], t]
521 t = T.table(align="left",class_="status-download-events")
522 t[T.tr[T.th["range"], T.th["start"], T.th["finish"], T.th["got"],
523 T.th["time"], T.th["decrypttime"], T.th["pausedtime"],
525 for r_ev in self.download_status.read_events:
526 start = r_ev["start"]
527 length = r_ev["length"]
528 bytes = r_ev["bytes_returned"]
531 decrypt_time = self._rate_and_time(bytes, r_ev["decrypt_time"])
533 if r_ev["finish_time"] is not None:
534 rtt = r_ev["finish_time"] - r_ev["start_time"] - r_ev["paused_time"]
535 speed = self.render_rate(None, compute_rate(bytes, rtt))
536 rtt = self.render_time(None, rtt)
537 paused = self.render_time(None, r_ev["paused_time"])
539 t[T.tr[T.td["[%d:+%d]" % (start, length)],
540 T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
541 T.td[bytes], T.td[rtt],
542 T.td[decrypt_time], T.td[paused],
546 l[T.h2["Read Events:"], t]
549 t = T.table(align="left",class_="status-download-events")
550 t[T.tr[T.th["segnum"], T.th["start"], T.th["active"], T.th["finish"],
552 T.th["decodetime"], T.th["segtime"], T.th["speed"]]]
553 for s_ev in self.download_status.segment_events:
558 if s_ev["finish_time"] is not None:
560 segtime = s_ev["finish_time"] - s_ev["active_time"]
561 segtime_s = self.render_time(None, segtime)
562 seglen = s_ev["segment_length"]
563 range_s = "[%d:+%d]" % (s_ev["segment_start"], seglen)
564 speed = self.render_rate(None, compute_rate(seglen, segtime))
565 decode_time = self._rate_and_time(seglen, s_ev["decode_time"])
573 t[T.tr[T.td["seg%d" % s_ev["segment_number"]],
574 T.td[srt(s_ev["start_time"])],
575 T.td[srt(s_ev["active_time"])],
576 T.td[srt(s_ev["finish_time"])],
579 T.td[segtime_s], T.td[speed]]]
581 l[T.h2["Segment Events:"], t]
583 t = T.table(align="left",class_="status-download-events")
584 t[T.tr[T.th["serverid"], T.th["shnum"], T.th["range"],
585 T.th["txtime"], T.th["rxtime"],
586 T.th["received"], T.th["RTT"]]]
587 for r_ev in self.download_status.block_requests:
588 server = r_ev["server"]
590 if r_ev["finish_time"] is not None:
591 rtt = r_ev["finish_time"] - r_ev["start_time"]
592 color = self.color(server.get_serverid())
593 t[T.tr(style="background: %s" % color)[
594 T.td[server.get_name()], T.td[r_ev["shnum"]],
595 T.td["[%d:+%d]" % (r_ev["start"], r_ev["length"])],
596 T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
597 T.td[r_ev["response_length"] or ""],
598 T.td[self.render_time(None, rtt)],
601 l[T.h2["Requests:"], t]
606 def color(self, peerid):
608 return min(ord(c) / 2 + 0x80, 0xff)
609 return "#%02x%02x%02x" % (m(peerid[0]), m(peerid[1]), m(peerid[2]))
611 def render_results(self, ctx, data):
612 d = self.download_results()
613 def _got_results(results):
617 d.addCallback(_got_results)
620 def render_started(self, ctx, data):
621 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
622 started_s = time.strftime(TIME_FORMAT,
623 time.localtime(data.get_started()))
624 return started_s + " (%s)" % data.get_started()
626 def render_si(self, ctx, data):
627 si_s = base32.b2a_or_none(data.get_storage_index())
632 def render_helper(self, ctx, data):
634 False: "No"}[data.using_helper()]
636 def render_total_size(self, ctx, data):
637 size = data.get_size()
642 def render_progress(self, ctx, data):
643 progress = data.get_progress()
644 # TODO: make an ascii-art bar
645 return "%.1f%%" % (100.0 * progress)
647 def render_status(self, ctx, data):
648 return data.get_status()
650 class DownloadStatusTimelinePage(rend.Page):
651 docFactory = getxmlfile("download-status-timeline.xhtml")
653 def render_started(self, ctx, data):
654 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
655 started_s = time.strftime(TIME_FORMAT,
656 time.localtime(data.get_started()))
657 return started_s + " (%s)" % data.get_started()
659 def render_si(self, ctx, data):
660 si_s = base32.b2a_or_none(data.get_storage_index())
665 def render_helper(self, ctx, data):
667 False: "No"}[data.using_helper()]
669 def render_total_size(self, ctx, data):
670 size = data.get_size()
675 def render_progress(self, ctx, data):
676 progress = data.get_progress()
677 # TODO: make an ascii-art bar
678 return "%.1f%%" % (100.0 * progress)
680 def render_status(self, ctx, data):
681 return data.get_status()
683 class RetrieveStatusPage(rend.Page, RateAndTimeMixin):
684 docFactory = getxmlfile("retrieve-status.xhtml")
686 def __init__(self, data):
687 rend.Page.__init__(self, data)
688 self.retrieve_status = data
690 def render_started(self, ctx, data):
691 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
692 started_s = time.strftime(TIME_FORMAT,
693 time.localtime(data.get_started()))
696 def render_si(self, ctx, data):
697 si_s = base32.b2a_or_none(data.get_storage_index())
702 def render_helper(self, ctx, data):
704 False: "No"}[data.using_helper()]
706 def render_current_size(self, ctx, data):
707 size = data.get_size()
712 def render_progress(self, ctx, data):
713 progress = data.get_progress()
714 # TODO: make an ascii-art bar
715 return "%.1f%%" % (100.0 * progress)
717 def render_status(self, ctx, data):
718 return data.get_status()
720 def render_encoding(self, ctx, data):
721 k, n = data.get_encoding()
722 return ctx.tag["Encoding: %s of %s" % (k, n)]
724 def render_problems(self, ctx, data):
725 problems = data.get_problems()
729 for peerid in sorted(problems.keys()):
730 peerid_s = idlib.shortnodeid_b2a(peerid)
731 l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
732 return ctx.tag["Server Problems:", l]
734 def _get_rate(self, data, name):
735 file_size = self.retrieve_status.get_size()
736 time = self.retrieve_status.timings.get(name)
737 return compute_rate(file_size, time)
739 def data_time_total(self, ctx, data):
740 return self.retrieve_status.timings.get("total")
741 def data_rate_total(self, ctx, data):
742 return self._get_rate(data, "total")
744 def data_time_fetch(self, ctx, data):
745 return self.retrieve_status.timings.get("fetch")
746 def data_rate_fetch(self, ctx, data):
747 return self._get_rate(data, "fetch")
749 def data_time_decode(self, ctx, data):
750 return self.retrieve_status.timings.get("decode")
751 def data_rate_decode(self, ctx, data):
752 return self._get_rate(data, "decode")
754 def data_time_decrypt(self, ctx, data):
755 return self.retrieve_status.timings.get("decrypt")
756 def data_rate_decrypt(self, ctx, data):
757 return self._get_rate(data, "decrypt")
759 def render_server_timings(self, ctx, data):
760 per_server = self.retrieve_status.timings.get("fetch_per_server")
764 for peerid in sorted(per_server.keys()):
765 peerid_s = idlib.shortnodeid_b2a(peerid)
766 times_s = ", ".join([self.render_time(None, t)
767 for t in per_server[peerid]])
768 l[T.li["[%s]: %s" % (peerid_s, times_s)]]
769 return T.li["Per-Server Fetch Response Times: ", l]
772 class PublishStatusPage(rend.Page, RateAndTimeMixin):
773 docFactory = getxmlfile("publish-status.xhtml")
775 def __init__(self, data):
776 rend.Page.__init__(self, data)
777 self.publish_status = data
779 def render_started(self, ctx, data):
780 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
781 started_s = time.strftime(TIME_FORMAT,
782 time.localtime(data.get_started()))
785 def render_si(self, ctx, data):
786 si_s = base32.b2a_or_none(data.get_storage_index())
791 def render_helper(self, ctx, data):
793 False: "No"}[data.using_helper()]
795 def render_current_size(self, ctx, data):
796 size = data.get_size()
801 def render_progress(self, ctx, data):
802 progress = data.get_progress()
803 # TODO: make an ascii-art bar
804 return "%.1f%%" % (100.0 * progress)
806 def render_status(self, ctx, data):
807 return data.get_status()
809 def render_encoding(self, ctx, data):
810 k, n = data.get_encoding()
811 return ctx.tag["Encoding: %s of %s" % (k, n)]
813 def render_sharemap(self, ctx, data):
814 servermap = data.get_servermap()
815 if servermap is None:
816 return ctx.tag["None"]
818 sharemap = servermap.make_sharemap()
819 for shnum in sorted(sharemap.keys()):
820 l[T.li["%d -> Placed on " % shnum,
821 ", ".join(["[%s]" % server.get_name()
822 for server in sharemap[shnum]])]]
823 return ctx.tag["Sharemap:", l]
825 def render_problems(self, ctx, data):
826 problems = data.get_problems()
830 # XXX: is this exercised? I don't think PublishStatus.problems is
832 for peerid in sorted(problems.keys()):
833 peerid_s = idlib.shortnodeid_b2a(peerid)
834 l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
835 return ctx.tag["Server Problems:", l]
837 def _get_rate(self, data, name):
838 file_size = self.publish_status.get_size()
839 time = self.publish_status.timings.get(name)
840 return compute_rate(file_size, time)
842 def data_time_total(self, ctx, data):
843 return self.publish_status.timings.get("total")
844 def data_rate_total(self, ctx, data):
845 return self._get_rate(data, "total")
847 def data_time_setup(self, ctx, data):
848 return self.publish_status.timings.get("setup")
850 def data_time_encrypt(self, ctx, data):
851 return self.publish_status.timings.get("encrypt")
852 def data_rate_encrypt(self, ctx, data):
853 return self._get_rate(data, "encrypt")
855 def data_time_encode(self, ctx, data):
856 return self.publish_status.timings.get("encode")
857 def data_rate_encode(self, ctx, data):
858 return self._get_rate(data, "encode")
860 def data_time_pack(self, ctx, data):
861 return self.publish_status.timings.get("pack")
862 def data_rate_pack(self, ctx, data):
863 return self._get_rate(data, "pack")
864 def data_time_sign(self, ctx, data):
865 return self.publish_status.timings.get("sign")
867 def data_time_push(self, ctx, data):
868 return self.publish_status.timings.get("push")
869 def data_rate_push(self, ctx, data):
870 return self._get_rate(data, "push")
872 def render_server_timings(self, ctx, data):
873 per_server = self.publish_status.timings.get("send_per_server")
877 for peerid in sorted(per_server.keys()):
878 peerid_s = idlib.shortnodeid_b2a(peerid)
879 times_s = ", ".join([self.render_time(None, t)
880 for t in per_server[peerid]])
881 l[T.li["[%s]: %s" % (peerid_s, times_s)]]
882 return T.li["Per-Server Response Times: ", l]
884 class MapupdateStatusPage(rend.Page, RateAndTimeMixin):
885 docFactory = getxmlfile("map-update-status.xhtml")
887 def __init__(self, data):
888 rend.Page.__init__(self, data)
889 self.update_status = data
891 def render_started(self, ctx, data):
892 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
893 started_s = time.strftime(TIME_FORMAT,
894 time.localtime(data.get_started()))
897 def render_finished(self, ctx, data):
898 when = data.get_finished()
901 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
902 started_s = time.strftime(TIME_FORMAT,
903 time.localtime(data.get_finished()))
906 def render_si(self, ctx, data):
907 si_s = base32.b2a_or_none(data.get_storage_index())
912 def render_helper(self, ctx, data):
914 False: "No"}[data.using_helper()]
916 def render_progress(self, ctx, data):
917 progress = data.get_progress()
918 # TODO: make an ascii-art bar
919 return "%.1f%%" % (100.0 * progress)
921 def render_status(self, ctx, data):
922 return data.get_status()
924 def render_problems(self, ctx, data):
925 problems = data.problems
929 for peerid in sorted(problems.keys()):
930 peerid_s = idlib.shortnodeid_b2a(peerid)
931 l[T.li["[%s]: %s" % (peerid_s, problems[peerid])]]
932 return ctx.tag["Server Problems:", l]
934 def render_privkey_from(self, ctx, data):
935 peerid = data.get_privkey_from()
937 return ctx.tag["Got privkey from: [%s]"
938 % idlib.shortnodeid_b2a(peerid)]
942 def data_time_total(self, ctx, data):
943 return self.update_status.timings.get("total")
945 def data_time_initial_queries(self, ctx, data):
946 return self.update_status.timings.get("initial_queries")
948 def data_time_cumulative_verify(self, ctx, data):
949 return self.update_status.timings.get("cumulative_verify")
951 def render_server_timings(self, ctx, data):
952 per_server = self.update_status.timings.get("per_server")
956 for peerid in sorted(per_server.keys()):
957 peerid_s = idlib.shortnodeid_b2a(peerid)
959 for op,started,t in per_server[peerid]:
960 #times.append("%s/%.4fs/%s/%s" % (op,
962 # self.render_time(None, started - self.update_status.get_started()),
963 # self.render_time(None,t)))
965 times.append( self.render_time(None, t) )
967 times.append( "late(" + self.render_time(None, t) + ")" )
969 times.append( "privkey(" + self.render_time(None, t) + ")" )
970 times_s = ", ".join(times)
971 l[T.li["[%s]: %s" % (peerid_s, times_s)]]
972 return T.li["Per-Server Response Times: ", l]
974 def render_timing_chart(self, ctx, data):
975 imageurl = self._timing_chart()
976 return ctx.tag[imageurl]
978 def _timing_chart(self):
979 started = self.update_status.get_started()
980 total = self.update_status.timings.get("total")
981 per_server = self.update_status.timings.get("per_server")
982 base = "http://chart.apis.google.com/chart?"
984 pieces.append("chco=ffffff,4d89f9,c6d9fd") # colors
989 graph_botom_margin= 21
993 # we sort the queries by the time at which we sent the first request
994 sorttable = [ (times[0][1], peerid)
995 for peerid, times in per_server.items() ]
997 peerids = [t[1] for t in sorttable]
999 for peerid in peerids:
1001 times = per_server[peerid]
1002 peerid_s = idlib.shortnodeid_b2a(peerid)
1003 peerids_s.append(peerid_s)
1004 # for servermap updates, there are either one or two queries per
1005 # peer. The second (if present) is to get the privkey.
1006 op,q_started,q_elapsed = times[0]
1007 data0.append("%.3f" % (q_started-started))
1008 data1.append("%.3f" % q_elapsed)
1009 top_abs = max(top_abs, q_started+q_elapsed)
1011 op,p_started,p_elapsed = times[0]
1012 data2.append("%.3f" % p_elapsed)
1013 top_abs = max(top_abs, p_started+p_elapsed)
1016 finished = self.update_status.get_finished()
1018 top_abs = max(top_abs, finished)
1019 top_rel = top_abs - started
1020 chs ="chs=400x%d" % ( (nb_nodes*28) + graph_top_margin + graph_botom_margin )
1021 chd = "chd=t:" + "|".join([",".join(data0),
1026 chds = "chds=0,%0.3f" % top_rel
1028 pieces.append("chxt=x,y")
1029 pieces.append("chxr=0,0.0,%0.3f" % top_rel)
1030 pieces.append("chxl=1:|" + "|".join(reversed(peerids_s)))
1031 # use up to 10 grid lines, at decimal multiples.
1032 # mathutil.next_power_of_k doesn't handle numbers smaller than one,
1034 #pieces.append("chg="
1036 if total is not None:
1037 finished_f = 1.0 * total / top_rel
1038 pieces.append("chm=r,FF0000,0,%0.3f,%0.3f" % (finished_f,
1040 url = base + "&".join(pieces)
1041 return T.img(src=url,border="1",align="right", float="right")
1044 class Status(rend.Page):
1045 docFactory = getxmlfile("status.xhtml")
1048 def __init__(self, history):
1049 rend.Page.__init__(self, history)
1050 self.history = history
1052 def renderHTTP(self, ctx):
1053 req = inevow.IRequest(ctx)
1054 t = get_arg(req, "t")
1056 return self.json(req)
1057 return rend.Page.renderHTTP(self, ctx)
1059 def json(self, req):
1060 req.setHeader("content-type", "text/plain")
1062 data["active"] = active = []
1063 for s in self._get_active_operations():
1064 si_s = base32.b2a_or_none(s.get_storage_index())
1066 status = s.get_status()
1067 if IUploadStatus.providedBy(s):
1068 h,c,e = s.get_progress()
1069 active.append({"type": "upload",
1070 "storage-index-string": si_s,
1074 "progress-ciphertext": c,
1075 "progress-encode-push": e,
1077 elif IDownloadStatus.providedBy(s):
1078 active.append({"type": "download",
1079 "storage-index-string": si_s,
1082 "progress": s.get_progress(),
1085 return simplejson.dumps(data, indent=1) + "\n"
1087 def _get_all_statuses(self):
1089 return itertools.chain(h.list_all_upload_statuses(),
1090 h.list_all_download_statuses(),
1091 h.list_all_mapupdate_statuses(),
1092 h.list_all_publish_statuses(),
1093 h.list_all_retrieve_statuses(),
1094 h.list_all_helper_statuses(),
1097 def data_active_operations(self, ctx, data):
1098 return self._get_active_operations()
1100 def _get_active_operations(self):
1102 for s in self._get_all_statuses()
1106 def data_recent_operations(self, ctx, data):
1107 return self._get_recent_operations()
1109 def _get_recent_operations(self):
1111 for s in self._get_all_statuses()
1112 if not s.get_active()]
1113 recent.sort(lambda a,b: cmp(a.get_started(), b.get_started()))
1117 def render_row(self, ctx, data):
1120 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1121 started_s = time.strftime(TIME_FORMAT,
1122 time.localtime(s.get_started()))
1123 ctx.fillSlots("started", started_s)
1125 si_s = base32.b2a_or_none(s.get_storage_index())
1128 ctx.fillSlots("si", si_s)
1129 ctx.fillSlots("helper", {True: "Yes",
1130 False: "No"}[s.using_helper()])
1135 elif isinstance(size, (int, long, float)):
1136 size = abbreviate_size(size)
1137 ctx.fillSlots("total_size", size)
1139 progress = data.get_progress()
1140 if IUploadStatus.providedBy(data):
1141 link = "up-%d" % data.get_counter()
1142 ctx.fillSlots("type", "upload")
1143 # TODO: make an ascii-art bar
1144 (chk, ciphertext, encandpush) = progress
1145 progress_s = ("hash: %.1f%%, ciphertext: %.1f%%, encode: %.1f%%" %
1147 (100.0 * ciphertext),
1148 (100.0 * encandpush) ))
1149 ctx.fillSlots("progress", progress_s)
1150 elif IDownloadStatus.providedBy(data):
1151 link = "down-%d" % data.get_counter()
1152 ctx.fillSlots("type", "download")
1153 ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1154 elif IPublishStatus.providedBy(data):
1155 link = "publish-%d" % data.get_counter()
1156 ctx.fillSlots("type", "publish")
1157 ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1158 elif IRetrieveStatus.providedBy(data):
1159 ctx.fillSlots("type", "retrieve")
1160 link = "retrieve-%d" % data.get_counter()
1161 ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1163 assert IServermapUpdaterStatus.providedBy(data)
1164 ctx.fillSlots("type", "mapupdate %s" % data.get_mode())
1165 link = "mapupdate-%d" % data.get_counter()
1166 ctx.fillSlots("progress", "%.1f%%" % (100.0 * progress))
1167 ctx.fillSlots("status", T.a(href=link)[s.get_status()])
1170 def childFactory(self, ctx, name):
1172 stype,count_s = name.split("-")
1173 count = int(count_s)
1175 for s in itertools.chain(h.list_all_upload_statuses(),
1176 h.list_all_helper_statuses()):
1177 # immutable-upload helpers use the same status object as a
1178 # regular immutable-upload
1179 if s.get_counter() == count:
1180 return UploadStatusPage(s)
1182 for s in h.list_all_download_statuses():
1183 if s.get_counter() == count:
1184 return DownloadStatusPage(s)
1185 if stype == "mapupdate":
1186 for s in h.list_all_mapupdate_statuses():
1187 if s.get_counter() == count:
1188 return MapupdateStatusPage(s)
1189 if stype == "publish":
1190 for s in h.list_all_publish_statuses():
1191 if s.get_counter() == count:
1192 return PublishStatusPage(s)
1193 if stype == "retrieve":
1194 for s in h.list_all_retrieve_statuses():
1195 if s.get_counter() == count:
1196 return RetrieveStatusPage(s)
1199 class HelperStatus(rend.Page):
1200 docFactory = getxmlfile("helper.xhtml")
1202 def __init__(self, helper):
1203 rend.Page.__init__(self, helper)
1204 self.helper = helper
1206 def renderHTTP(self, ctx):
1207 req = inevow.IRequest(ctx)
1208 t = get_arg(req, "t")
1210 return self.render_JSON(req)
1211 return rend.Page.renderHTTP(self, ctx)
1213 def data_helper_stats(self, ctx, data):
1214 return self.helper.get_stats()
1216 def render_JSON(self, req):
1217 req.setHeader("content-type", "text/plain")
1219 stats = self.helper.get_stats()
1220 return simplejson.dumps(stats, indent=1) + "\n"
1221 return simplejson.dumps({}) + "\n"
1223 def render_active_uploads(self, ctx, data):
1224 return data["chk_upload_helper.active_uploads"]
1226 def render_incoming(self, ctx, data):
1227 return "%d bytes in %d files" % (data["chk_upload_helper.incoming_size"],
1228 data["chk_upload_helper.incoming_count"])
1230 def render_encoding(self, ctx, data):
1231 return "%d bytes in %d files" % (data["chk_upload_helper.encoding_size"],
1232 data["chk_upload_helper.encoding_count"])
1234 def render_upload_requests(self, ctx, data):
1235 return str(data["chk_upload_helper.upload_requests"])
1237 def render_upload_already_present(self, ctx, data):
1238 return str(data["chk_upload_helper.upload_already_present"])
1240 def render_upload_need_upload(self, ctx, data):
1241 return str(data["chk_upload_helper.upload_need_upload"])
1243 def render_upload_bytes_fetched(self, ctx, data):
1244 return str(data["chk_upload_helper.fetched_bytes"])
1246 def render_upload_bytes_encoded(self, ctx, data):
1247 return str(data["chk_upload_helper.encoded_bytes"])
1250 class Statistics(rend.Page):
1251 docFactory = getxmlfile("statistics.xhtml")
1253 def __init__(self, provider):
1254 rend.Page.__init__(self, provider)
1255 self.provider = provider
1257 def renderHTTP(self, ctx):
1258 req = inevow.IRequest(ctx)
1259 t = get_arg(req, "t")
1261 stats = self.provider.get_stats()
1262 req.setHeader("content-type", "text/plain")
1263 return simplejson.dumps(stats, indent=1) + "\n"
1264 return rend.Page.renderHTTP(self, ctx)
1266 def data_get_stats(self, ctx, data):
1267 return self.provider.get_stats()
1269 def render_load_average(self, ctx, data):
1270 return str(data["stats"].get("load_monitor.avg_load"))
1272 def render_peak_load(self, ctx, data):
1273 return str(data["stats"].get("load_monitor.max_load"))
1275 def render_uploads(self, ctx, data):
1276 files = data["counters"].get("uploader.files_uploaded", 0)
1277 bytes = data["counters"].get("uploader.bytes_uploaded", 0)
1278 return ("%s files / %s bytes (%s)" %
1279 (files, bytes, abbreviate_size(bytes)))
1281 def render_downloads(self, ctx, data):
1282 files = data["counters"].get("downloader.files_downloaded", 0)
1283 bytes = data["counters"].get("downloader.bytes_downloaded", 0)
1284 return ("%s files / %s bytes (%s)" %
1285 (files, bytes, abbreviate_size(bytes)))
1287 def render_publishes(self, ctx, data):
1288 files = data["counters"].get("mutable.files_published", 0)
1289 bytes = data["counters"].get("mutable.bytes_published", 0)
1290 return "%s files / %s bytes (%s)" % (files, bytes,
1291 abbreviate_size(bytes))
1293 def render_retrieves(self, ctx, data):
1294 files = data["counters"].get("mutable.files_retrieved", 0)
1295 bytes = data["counters"].get("mutable.bytes_retrieved", 0)
1296 return "%s files / %s bytes (%s)" % (files, bytes,
1297 abbreviate_size(bytes))
1299 def render_drop_monitored(self, ctx, data):
1300 dirs = data["counters"].get("drop_upload.dirs_monitored", 0)
1301 return "%s directories" % (dirs,)
1303 def render_drop_uploads(self, ctx, data):
1304 # TODO: bytes uploaded
1305 files = data["counters"].get("drop_upload.files_uploaded", 0)
1306 return "%s files" % (files,)
1308 def render_drop_queued(self, ctx, data):
1309 files = data["counters"].get("drop_upload.files_queued", 0)
1310 return "%s files" % (files,)
1312 def render_drop_failed(self, ctx, data):
1313 files = data["counters"].get("drop_upload.files_failed", 0)
1314 return "%s files" % (files,)
1316 def render_raw(self, ctx, data):
1317 raw = pprint.pformat(data)