Convert instances of tor_snprintf+strdup into tor_asprintf
[tor.git] / src / or / rephist.c
blob4129fe2bbd1a5302022951cb3c9ca54d006dea18
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rephist.c
7 * \brief Basic history and "reputation" functionality to remember
8 * which servers have worked in the past, how much bandwidth we've
9 * been using, which ports we tend to want, and so on; further,
10 * exit port statistics, cell statistics, and connection statistics.
11 **/
13 #include "or.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
16 #include "config.h"
17 #include "networkstatus.h"
18 #include "nodelist.h"
19 #include "rephist.h"
20 #include "router.h"
21 #include "routerlist.h"
22 #include "ht.h"
24 static void bw_arrays_init(void);
25 static void predicted_ports_init(void);
27 /** Total number of bytes currently allocated in fields used by rephist.c. */
28 uint64_t rephist_total_alloc=0;
29 /** Number of or_history_t objects currently allocated. */
30 uint32_t rephist_total_num=0;
32 /** If the total weighted run count of all runs for a router ever falls
33 * below this amount, the router can be treated as having 0 MTBF. */
34 #define STABILITY_EPSILON 0.0001
35 /** Value by which to discount all old intervals for MTBF purposes. This
36 * is compounded every STABILITY_INTERVAL. */
37 #define STABILITY_ALPHA 0.95
38 /** Interval at which to discount all old intervals for MTBF purposes. */
39 #define STABILITY_INTERVAL (12*60*60)
40 /* (This combination of ALPHA, INTERVAL, and EPSILON makes it so that an
41 * interval that just ended counts twice as much as one that ended a week ago,
42 * 20X as much as one that ended a month ago, and routers that have had no
43 * uptime data for about half a year will get forgotten.) */
45 /** History of an OR-\>OR link. */
46 typedef struct link_history_t {
47 /** When did we start tracking this list? */
48 time_t since;
49 /** When did we most recently note a change to this link */
50 time_t changed;
51 /** How many times did extending from OR1 to OR2 succeed? */
52 unsigned long n_extend_ok;
53 /** How many times did extending from OR1 to OR2 fail? */
54 unsigned long n_extend_fail;
55 } link_history_t;
57 /** History of an OR. */
58 typedef struct or_history_t {
59 /** When did we start tracking this OR? */
60 time_t since;
61 /** When did we most recently note a change to this OR? */
62 time_t changed;
63 /** How many times did we successfully connect? */
64 unsigned long n_conn_ok;
65 /** How many times did we try to connect and fail?*/
66 unsigned long n_conn_fail;
67 /** How many seconds have we been connected to this OR before
68 * 'up_since'? */
69 unsigned long uptime;
70 /** How many seconds have we been unable to connect to this OR before
71 * 'down_since'? */
72 unsigned long downtime;
73 /** If nonzero, we have been connected since this time. */
74 time_t up_since;
75 /** If nonzero, we have been unable to connect since this time. */
76 time_t down_since;
78 /** The address at which we most recently connected to this OR
79 * successfully. */
80 tor_addr_t last_reached_addr;
82 /** The port at which we most recently connected to this OR successfully */
83 uint16_t last_reached_port;
85 /* === For MTBF tracking: */
86 /** Weighted sum total of all times that this router has been online.
88 unsigned long weighted_run_length;
89 /** If the router is now online (according to stability-checking rules),
90 * when did it come online? */
91 time_t start_of_run;
92 /** Sum of weights for runs in weighted_run_length. */
93 double total_run_weights;
94 /* === For fractional uptime tracking: */
95 time_t start_of_downtime;
96 unsigned long weighted_uptime;
97 unsigned long total_weighted_time;
99 /** Map from hex OR2 identity digest to a link_history_t for the link
100 * from this OR to OR2. */
101 digestmap_t *link_history_map;
102 } or_history_t;
104 /** When did we last multiply all routers' weighted_run_length and
105 * total_run_weights by STABILITY_ALPHA? */
106 static time_t stability_last_downrated = 0;
108 /** */
109 static time_t started_tracking_stability = 0;
111 /** Map from hex OR identity digest to or_history_t. */
112 static digestmap_t *history_map = NULL;
114 /** Return the or_history_t for the OR with identity digest <b>id</b>,
115 * creating it if necessary. */
116 static or_history_t *
117 get_or_history(const char* id)
119 or_history_t *hist;
121 if (tor_digest_is_zero(id))
122 return NULL;
124 hist = digestmap_get(history_map, id);
125 if (!hist) {
126 hist = tor_malloc_zero(sizeof(or_history_t));
127 rephist_total_alloc += sizeof(or_history_t);
128 rephist_total_num++;
129 hist->link_history_map = digestmap_new();
130 hist->since = hist->changed = time(NULL);
131 tor_addr_make_unspec(&hist->last_reached_addr);
132 digestmap_set(history_map, id, hist);
134 return hist;
137 /** Return the link_history_t for the link from the first named OR to
138 * the second, creating it if necessary. (ORs are identified by
139 * identity digest.)
141 static link_history_t *
142 get_link_history(const char *from_id, const char *to_id)
144 or_history_t *orhist;
145 link_history_t *lhist;
146 orhist = get_or_history(from_id);
147 if (!orhist)
148 return NULL;
149 if (tor_digest_is_zero(to_id))
150 return NULL;
151 lhist = (link_history_t*) digestmap_get(orhist->link_history_map, to_id);
152 if (!lhist) {
153 lhist = tor_malloc_zero(sizeof(link_history_t));
154 rephist_total_alloc += sizeof(link_history_t);
155 lhist->since = lhist->changed = time(NULL);
156 digestmap_set(orhist->link_history_map, to_id, lhist);
158 return lhist;
161 /** Helper: free storage held by a single link history entry. */
162 static void
163 _free_link_history(void *val)
165 rephist_total_alloc -= sizeof(link_history_t);
166 tor_free(val);
169 /** Helper: free storage held by a single OR history entry. */
170 static void
171 free_or_history(void *_hist)
173 or_history_t *hist = _hist;
174 digestmap_free(hist->link_history_map, _free_link_history);
175 rephist_total_alloc -= sizeof(or_history_t);
176 rephist_total_num--;
177 tor_free(hist);
180 /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
181 * count is up-to-date as of <b>when</b>.
183 static void
184 update_or_history(or_history_t *hist, time_t when)
186 tor_assert(hist);
187 if (hist->up_since) {
188 tor_assert(!hist->down_since);
189 hist->uptime += (when - hist->up_since);
190 hist->up_since = when;
191 } else if (hist->down_since) {
192 hist->downtime += (when - hist->down_since);
193 hist->down_since = when;
197 /** Initialize the static data structures for tracking history. */
198 void
199 rep_hist_init(void)
201 history_map = digestmap_new();
202 bw_arrays_init();
203 predicted_ports_init();
206 /** Helper: note that we are no longer connected to the router with history
207 * <b>hist</b>. If <b>failed</b>, the connection failed; otherwise, it was
208 * closed correctly. */
209 static void
210 mark_or_down(or_history_t *hist, time_t when, int failed)
212 if (hist->up_since) {
213 hist->uptime += (when - hist->up_since);
214 hist->up_since = 0;
216 if (failed && !hist->down_since) {
217 hist->down_since = when;
221 /** Helper: note that we are connected to the router with history
222 * <b>hist</b>. */
223 static void
224 mark_or_up(or_history_t *hist, time_t when)
226 if (hist->down_since) {
227 hist->downtime += (when - hist->down_since);
228 hist->down_since = 0;
230 if (!hist->up_since) {
231 hist->up_since = when;
235 /** Remember that an attempt to connect to the OR with identity digest
236 * <b>id</b> failed at <b>when</b>.
238 void
239 rep_hist_note_connect_failed(const char* id, time_t when)
241 or_history_t *hist;
242 hist = get_or_history(id);
243 if (!hist)
244 return;
245 ++hist->n_conn_fail;
246 mark_or_down(hist, when, 1);
247 hist->changed = when;
250 /** Remember that an attempt to connect to the OR with identity digest
251 * <b>id</b> succeeded at <b>when</b>.
253 void
254 rep_hist_note_connect_succeeded(const char* id, time_t when)
256 or_history_t *hist;
257 hist = get_or_history(id);
258 if (!hist)
259 return;
260 ++hist->n_conn_ok;
261 mark_or_up(hist, when);
262 hist->changed = when;
265 /** Remember that we intentionally closed our connection to the OR
266 * with identity digest <b>id</b> at <b>when</b>.
268 void
269 rep_hist_note_disconnect(const char* id, time_t when)
271 or_history_t *hist;
272 hist = get_or_history(id);
273 if (!hist)
274 return;
275 mark_or_down(hist, when, 0);
276 hist->changed = when;
279 /** Remember that our connection to the OR with identity digest
280 * <b>id</b> had an error and stopped working at <b>when</b>.
282 void
283 rep_hist_note_connection_died(const char* id, time_t when)
285 or_history_t *hist;
286 if (!id) {
287 /* If conn has no identity, it didn't complete its handshake, or something
288 * went wrong. Ignore it.
290 return;
292 hist = get_or_history(id);
293 if (!hist)
294 return;
295 mark_or_down(hist, when, 1);
296 hist->changed = when;
299 /** We have just decided that this router with identity digest <b>id</b> is
300 * reachable, meaning we will give it a "Running" flag for the next while. */
301 void
302 rep_hist_note_router_reachable(const char *id, const tor_addr_t *at_addr,
303 const uint16_t at_port, time_t when)
305 or_history_t *hist = get_or_history(id);
306 int was_in_run = 1;
307 char tbuf[ISO_TIME_LEN+1];
308 int addr_changed, port_changed;
310 tor_assert(hist);
311 tor_assert((!at_addr && !at_port) || (at_addr && at_port));
313 addr_changed = at_addr &&
314 tor_addr_compare(at_addr, &hist->last_reached_addr, CMP_EXACT) != 0;
315 port_changed = at_port && at_port != hist->last_reached_port;
317 if (!started_tracking_stability)
318 started_tracking_stability = time(NULL);
319 if (!hist->start_of_run) {
320 hist->start_of_run = when;
321 was_in_run = 0;
323 if (hist->start_of_downtime) {
324 long down_length;
326 format_local_iso_time(tbuf, hist->start_of_downtime);
327 log_info(LD_HIST, "Router %s is now Running; it had been down since %s.",
328 hex_str(id, DIGEST_LEN), tbuf);
329 if (was_in_run)
330 log_info(LD_HIST, " (Paradoxically, it was already Running too.)");
332 down_length = when - hist->start_of_downtime;
333 hist->total_weighted_time += down_length;
334 hist->start_of_downtime = 0;
335 } else if (addr_changed || port_changed) {
336 /* If we're reachable, but the address changed, treat this as some
337 * downtime. */
338 int penalty = get_options()->TestingTorNetwork ? 240 : 3600;
339 networkstatus_t *ns;
341 if ((ns = networkstatus_get_latest_consensus())) {
342 int fresh_interval = (int)(ns->fresh_until - ns->valid_after);
343 int live_interval = (int)(ns->valid_until - ns->valid_after);
344 /* on average, a descriptor addr change takes .5 intervals to make it
345 * into a consensus, and half a liveness period to make it to
346 * clients. */
347 penalty = (int)(fresh_interval + live_interval) / 2;
349 format_local_iso_time(tbuf, hist->start_of_run);
350 log_info(LD_HIST,"Router %s still seems Running, but its address appears "
351 "to have changed since the last time it was reachable. I'm "
352 "going to treat it as having been down for %d seconds",
353 hex_str(id, DIGEST_LEN), penalty);
354 rep_hist_note_router_unreachable(id, when-penalty);
355 rep_hist_note_router_reachable(id, NULL, 0, when);
356 } else {
357 format_local_iso_time(tbuf, hist->start_of_run);
358 if (was_in_run)
359 log_debug(LD_HIST, "Router %s is still Running; it has been Running "
360 "since %s", hex_str(id, DIGEST_LEN), tbuf);
361 else
362 log_info(LD_HIST,"Router %s is now Running; it was previously untracked",
363 hex_str(id, DIGEST_LEN));
365 if (at_addr)
366 tor_addr_copy(&hist->last_reached_addr, at_addr);
367 if (at_port)
368 hist->last_reached_port = at_port;
371 /** We have just decided that this router is unreachable, meaning
372 * we are taking away its "Running" flag. */
373 void
374 rep_hist_note_router_unreachable(const char *id, time_t when)
376 or_history_t *hist = get_or_history(id);
377 char tbuf[ISO_TIME_LEN+1];
378 int was_running = 0;
379 if (!started_tracking_stability)
380 started_tracking_stability = time(NULL);
382 tor_assert(hist);
383 if (hist->start_of_run) {
384 /*XXXX We could treat failed connections differently from failed
385 * connect attempts. */
386 long run_length = when - hist->start_of_run;
387 format_local_iso_time(tbuf, hist->start_of_run);
389 hist->total_run_weights += 1.0;
390 hist->start_of_run = 0;
391 if (run_length < 0) {
392 unsigned long penalty = -run_length;
393 #define SUBTRACT_CLAMPED(var, penalty) \
394 do { (var) = (var) < (penalty) ? 0 : (var) - (penalty); } while (0)
396 SUBTRACT_CLAMPED(hist->weighted_run_length, penalty);
397 SUBTRACT_CLAMPED(hist->weighted_uptime, penalty);
398 } else {
399 hist->weighted_run_length += run_length;
400 hist->weighted_uptime += run_length;
401 hist->total_weighted_time += run_length;
403 was_running = 1;
404 log_info(LD_HIST, "Router %s is now non-Running: it had previously been "
405 "Running since %s. Its total weighted uptime is %lu/%lu.",
406 hex_str(id, DIGEST_LEN), tbuf, hist->weighted_uptime,
407 hist->total_weighted_time);
409 if (!hist->start_of_downtime) {
410 hist->start_of_downtime = when;
412 if (!was_running)
413 log_info(LD_HIST, "Router %s is now non-Running; it was previously "
414 "untracked.", hex_str(id, DIGEST_LEN));
415 } else {
416 if (!was_running) {
417 format_local_iso_time(tbuf, hist->start_of_downtime);
419 log_info(LD_HIST, "Router %s is still non-Running; it has been "
420 "non-Running since %s.", hex_str(id, DIGEST_LEN), tbuf);
425 /** Helper: Discount all old MTBF data, if it is time to do so. Return
426 * the time at which we should next discount MTBF data. */
427 time_t
428 rep_hist_downrate_old_runs(time_t now)
430 digestmap_iter_t *orhist_it;
431 const char *digest1;
432 or_history_t *hist;
433 void *hist_p;
434 double alpha = 1.0;
436 if (!history_map)
437 history_map = digestmap_new();
438 if (!stability_last_downrated)
439 stability_last_downrated = now;
440 if (stability_last_downrated + STABILITY_INTERVAL > now)
441 return stability_last_downrated + STABILITY_INTERVAL;
443 /* Okay, we should downrate the data. By how much? */
444 while (stability_last_downrated + STABILITY_INTERVAL < now) {
445 stability_last_downrated += STABILITY_INTERVAL;
446 alpha *= STABILITY_ALPHA;
449 log_info(LD_HIST, "Discounting all old stability info by a factor of %f",
450 alpha);
452 /* Multiply every w_r_l, t_r_w pair by alpha. */
453 for (orhist_it = digestmap_iter_init(history_map);
454 !digestmap_iter_done(orhist_it);
455 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
456 digestmap_iter_get(orhist_it, &digest1, &hist_p);
457 hist = hist_p;
459 hist->weighted_run_length =
460 (unsigned long)(hist->weighted_run_length * alpha);
461 hist->total_run_weights *= alpha;
463 hist->weighted_uptime = (unsigned long)(hist->weighted_uptime * alpha);
464 hist->total_weighted_time = (unsigned long)
465 (hist->total_weighted_time * alpha);
468 return stability_last_downrated + STABILITY_INTERVAL;
471 /** Helper: Return the weighted MTBF of the router with history <b>hist</b>. */
472 static double
473 get_stability(or_history_t *hist, time_t when)
475 long total = hist->weighted_run_length;
476 double total_weights = hist->total_run_weights;
478 if (hist->start_of_run) {
479 /* We're currently in a run. Let total and total_weights hold the values
480 * they would hold if the current run were to end now. */
481 total += (when-hist->start_of_run);
482 total_weights += 1.0;
484 if (total_weights < STABILITY_EPSILON) {
485 /* Round down to zero, and avoid divide-by-zero. */
486 return 0.0;
489 return total / total_weights;
492 /** Return the total amount of time we've been observing, with each run of
493 * time downrated by the appropriate factor. */
494 static long
495 get_total_weighted_time(or_history_t *hist, time_t when)
497 long total = hist->total_weighted_time;
498 if (hist->start_of_run) {
499 total += (when - hist->start_of_run);
500 } else if (hist->start_of_downtime) {
501 total += (when - hist->start_of_downtime);
503 return total;
506 /** Helper: Return the weighted percent-of-time-online of the router with
507 * history <b>hist</b>. */
508 static double
509 get_weighted_fractional_uptime(or_history_t *hist, time_t when)
511 long total = hist->total_weighted_time;
512 long up = hist->weighted_uptime;
514 if (hist->start_of_run) {
515 long run_length = (when - hist->start_of_run);
516 up += run_length;
517 total += run_length;
518 } else if (hist->start_of_downtime) {
519 total += (when - hist->start_of_downtime);
522 if (!total) {
523 /* Avoid calling anybody's uptime infinity (which should be impossible if
524 * the code is working), or NaN (which can happen for any router we haven't
525 * observed up or down yet). */
526 return 0.0;
529 return ((double) up) / total;
532 /** Return how long the router whose identity digest is <b>id</b> has
533 * been reachable. Return 0 if the router is unknown or currently deemed
534 * unreachable. */
535 long
536 rep_hist_get_uptime(const char *id, time_t when)
538 or_history_t *hist = get_or_history(id);
539 if (!hist)
540 return 0;
541 if (!hist->start_of_run || when < hist->start_of_run)
542 return 0;
543 return when - hist->start_of_run;
546 /** Return an estimated MTBF for the router whose identity digest is
547 * <b>id</b>. Return 0 if the router is unknown. */
548 double
549 rep_hist_get_stability(const char *id, time_t when)
551 or_history_t *hist = get_or_history(id);
552 if (!hist)
553 return 0.0;
555 return get_stability(hist, when);
558 /** Return an estimated percent-of-time-online for the router whose identity
559 * digest is <b>id</b>. Return 0 if the router is unknown. */
560 double
561 rep_hist_get_weighted_fractional_uptime(const char *id, time_t when)
563 or_history_t *hist = get_or_history(id);
564 if (!hist)
565 return 0.0;
567 return get_weighted_fractional_uptime(hist, when);
570 /** Return a number representing how long we've known about the router whose
571 * digest is <b>id</b>. Return 0 if the router is unknown.
573 * Be careful: this measure increases monotonically as we know the router for
574 * longer and longer, but it doesn't increase linearly.
576 long
577 rep_hist_get_weighted_time_known(const char *id, time_t when)
579 or_history_t *hist = get_or_history(id);
580 if (!hist)
581 return 0;
583 return get_total_weighted_time(hist, when);
586 /** Return true if we've been measuring MTBFs for long enough to
587 * pronounce on Stability. */
589 rep_hist_have_measured_enough_stability(void)
591 /* XXXX022 This doesn't do so well when we change our opinion
592 * as to whether we're tracking router stability. */
593 return started_tracking_stability < time(NULL) - 4*60*60;
596 /** Remember that we successfully extended from the OR with identity
597 * digest <b>from_id</b> to the OR with identity digest
598 * <b>to_name</b>.
600 void
601 rep_hist_note_extend_succeeded(const char *from_id, const char *to_id)
603 link_history_t *hist;
604 /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
605 hist = get_link_history(from_id, to_id);
606 if (!hist)
607 return;
608 ++hist->n_extend_ok;
609 hist->changed = time(NULL);
612 /** Remember that we tried to extend from the OR with identity digest
613 * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
614 * failed.
616 void
617 rep_hist_note_extend_failed(const char *from_id, const char *to_id)
619 link_history_t *hist;
620 /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
621 hist = get_link_history(from_id, to_id);
622 if (!hist)
623 return;
624 ++hist->n_extend_fail;
625 hist->changed = time(NULL);
628 /** Log all the reliability data we have remembered, with the chosen
629 * severity.
631 void
632 rep_hist_dump_stats(time_t now, int severity)
634 digestmap_iter_t *lhist_it;
635 digestmap_iter_t *orhist_it;
636 const char *name1, *name2, *digest1, *digest2;
637 char hexdigest1[HEX_DIGEST_LEN+1];
638 char hexdigest2[HEX_DIGEST_LEN+1];
639 or_history_t *or_history;
640 link_history_t *link_history;
641 void *or_history_p, *link_history_p;
642 double uptime;
643 char buffer[2048];
644 size_t len;
645 int ret;
646 unsigned long upt, downt;
647 const node_t *node;
649 rep_history_clean(now - get_options()->RephistTrackTime);
651 log(severity, LD_HIST, "--------------- Dumping history information:");
653 for (orhist_it = digestmap_iter_init(history_map);
654 !digestmap_iter_done(orhist_it);
655 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
656 double s;
657 long stability;
658 digestmap_iter_get(orhist_it, &digest1, &or_history_p);
659 or_history = (or_history_t*) or_history_p;
661 if ((node = node_get_by_id(digest1)) && node_get_nickname(node))
662 name1 = node_get_nickname(node);
663 else
664 name1 = "(unknown)";
665 base16_encode(hexdigest1, sizeof(hexdigest1), digest1, DIGEST_LEN);
666 update_or_history(or_history, now);
667 upt = or_history->uptime;
668 downt = or_history->downtime;
669 s = get_stability(or_history, now);
670 stability = (long)s;
671 if (upt+downt) {
672 uptime = ((double)upt) / (upt+downt);
673 } else {
674 uptime=1.0;
676 log(severity, LD_HIST,
677 "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
678 "wmtbf %lu:%02lu:%02lu",
679 name1, hexdigest1,
680 or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
681 upt, upt+downt, uptime*100.0,
682 stability/3600, (stability/60)%60, stability%60);
684 if (!digestmap_isempty(or_history->link_history_map)) {
685 strlcpy(buffer, " Extend attempts: ", sizeof(buffer));
686 len = strlen(buffer);
687 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
688 !digestmap_iter_done(lhist_it);
689 lhist_it = digestmap_iter_next(or_history->link_history_map,
690 lhist_it)) {
691 digestmap_iter_get(lhist_it, &digest2, &link_history_p);
692 if ((node = node_get_by_id(digest2)) && node_get_nickname(node))
693 name2 = node_get_nickname(node);
694 else
695 name2 = "(unknown)";
697 link_history = (link_history_t*) link_history_p;
699 base16_encode(hexdigest2, sizeof(hexdigest2), digest2, DIGEST_LEN);
700 ret = tor_snprintf(buffer+len, 2048-len, "%s [%s](%ld/%ld); ",
701 name2,
702 hexdigest2,
703 link_history->n_extend_ok,
704 link_history->n_extend_ok+link_history->n_extend_fail);
705 if (ret<0)
706 break;
707 else
708 len += ret;
710 log(severity, LD_HIST, "%s", buffer);
715 /** Remove history info for routers/links that haven't changed since
716 * <b>before</b>.
718 void
719 rep_history_clean(time_t before)
721 int authority = authdir_mode(get_options());
722 or_history_t *or_history;
723 link_history_t *link_history;
724 void *or_history_p, *link_history_p;
725 digestmap_iter_t *orhist_it, *lhist_it;
726 const char *d1, *d2;
728 orhist_it = digestmap_iter_init(history_map);
729 while (!digestmap_iter_done(orhist_it)) {
730 int remove;
731 digestmap_iter_get(orhist_it, &d1, &or_history_p);
732 or_history = or_history_p;
734 remove = authority ? (or_history->total_run_weights < STABILITY_EPSILON &&
735 !or_history->start_of_run)
736 : (or_history->changed < before);
737 if (remove) {
738 orhist_it = digestmap_iter_next_rmv(history_map, orhist_it);
739 free_or_history(or_history);
740 continue;
742 for (lhist_it = digestmap_iter_init(or_history->link_history_map);
743 !digestmap_iter_done(lhist_it); ) {
744 digestmap_iter_get(lhist_it, &d2, &link_history_p);
745 link_history = link_history_p;
746 if (link_history->changed < before) {
747 lhist_it = digestmap_iter_next_rmv(or_history->link_history_map,
748 lhist_it);
749 rephist_total_alloc -= sizeof(link_history_t);
750 tor_free(link_history);
751 continue;
753 lhist_it = digestmap_iter_next(or_history->link_history_map,lhist_it);
755 orhist_it = digestmap_iter_next(history_map, orhist_it);
759 /** Write MTBF data to disk. Return 0 on success, negative on failure.
761 * If <b>missing_means_down</b>, then if we're about to write an entry
762 * that is still considered up but isn't in our routerlist, consider it
763 * to be down. */
765 rep_hist_record_mtbf_data(time_t now, int missing_means_down)
767 char time_buf[ISO_TIME_LEN+1];
769 digestmap_iter_t *orhist_it;
770 const char *digest;
771 void *or_history_p;
772 or_history_t *hist;
773 open_file_t *open_file = NULL;
774 FILE *f;
777 char *filename = get_datadir_fname("router-stability");
778 f = start_writing_to_stdio_file(filename, OPEN_FLAGS_REPLACE|O_TEXT, 0600,
779 &open_file);
780 tor_free(filename);
781 if (!f)
782 return -1;
785 /* File format is:
786 * FormatLine *KeywordLine Data
788 * FormatLine = "format 1" NL
789 * KeywordLine = Keyword SP Arguments NL
790 * Data = "data" NL *RouterMTBFLine "." NL
791 * RouterMTBFLine = Fingerprint SP WeightedRunLen SP
792 * TotalRunWeights [SP S=StartRunTime] NL
794 #define PUT(s) STMT_BEGIN if (fputs((s),f)<0) goto err; STMT_END
795 #define PRINTF(args) STMT_BEGIN if (fprintf args <0) goto err; STMT_END
797 PUT("format 2\n");
799 format_iso_time(time_buf, time(NULL));
800 PRINTF((f, "stored-at %s\n", time_buf));
802 if (started_tracking_stability) {
803 format_iso_time(time_buf, started_tracking_stability);
804 PRINTF((f, "tracked-since %s\n", time_buf));
806 if (stability_last_downrated) {
807 format_iso_time(time_buf, stability_last_downrated);
808 PRINTF((f, "last-downrated %s\n", time_buf));
811 PUT("data\n");
813 /* XXX Nick: now bridge auths record this for all routers too.
814 * Should we make them record it only for bridge routers? -RD
815 * Not for 0.2.0. -NM */
816 for (orhist_it = digestmap_iter_init(history_map);
817 !digestmap_iter_done(orhist_it);
818 orhist_it = digestmap_iter_next(history_map,orhist_it)) {
819 char dbuf[HEX_DIGEST_LEN+1];
820 const char *t = NULL;
821 digestmap_iter_get(orhist_it, &digest, &or_history_p);
822 hist = (or_history_t*) or_history_p;
824 base16_encode(dbuf, sizeof(dbuf), digest, DIGEST_LEN);
826 if (missing_means_down && hist->start_of_run &&
827 !router_get_by_id_digest(digest)) {
828 /* We think this relay is running, but it's not listed in our
829 * routerlist. Somehow it fell out without telling us it went
830 * down. Complain and also correct it. */
831 log_info(LD_HIST,
832 "Relay '%s' is listed as up in rephist, but it's not in "
833 "our routerlist. Correcting.", dbuf);
834 rep_hist_note_router_unreachable(digest, now);
837 PRINTF((f, "R %s\n", dbuf));
838 if (hist->start_of_run > 0) {
839 format_iso_time(time_buf, hist->start_of_run);
840 t = time_buf;
842 PRINTF((f, "+MTBF %lu %.5lf%s%s\n",
843 hist->weighted_run_length, hist->total_run_weights,
844 t ? " S=" : "", t ? t : ""));
845 t = NULL;
846 if (hist->start_of_downtime > 0) {
847 format_iso_time(time_buf, hist->start_of_downtime);
848 t = time_buf;
850 PRINTF((f, "+WFU %lu %lu%s%s\n",
851 hist->weighted_uptime, hist->total_weighted_time,
852 t ? " S=" : "", t ? t : ""));
855 PUT(".\n");
857 #undef PUT
858 #undef PRINTF
860 return finish_writing_to_file(open_file);
861 err:
862 abort_writing_to_file(open_file);
863 return -1;
866 /** Format the current tracked status of the router in <b>hist</b> at time
867 * <b>now</b> for analysis; return it in a newly allocated string. */
868 static char *
869 rep_hist_format_router_status(or_history_t *hist, time_t now)
871 char sor_buf[ISO_TIME_LEN+1];
872 char sod_buf[ISO_TIME_LEN+1];
873 double wfu;
874 double mtbf;
875 int up = 0, down = 0;
876 char *cp = NULL;
878 if (hist->start_of_run) {
879 format_iso_time(sor_buf, hist->start_of_run);
880 up = 1;
882 if (hist->start_of_downtime) {
883 format_iso_time(sod_buf, hist->start_of_downtime);
884 down = 1;
887 wfu = get_weighted_fractional_uptime(hist, now);
888 mtbf = get_stability(hist, now);
889 tor_asprintf(&cp,
890 "%s%s%s"
891 "%s%s%s"
892 "wfu %0.3lf\n"
893 " weighted-time %lu\n"
894 " weighted-uptime %lu\n"
895 "mtbf %0.1lf\n"
896 " weighted-run-length %lu\n"
897 " total-run-weights %f\n",
898 up?"uptime-started ":"", up?sor_buf:"", up?" UTC\n":"",
899 down?"downtime-started ":"", down?sod_buf:"", down?" UTC\n":"",
900 wfu,
901 hist->total_weighted_time,
902 hist->weighted_uptime,
903 mtbf,
904 hist->weighted_run_length,
905 hist->total_run_weights
907 return cp;
910 /** The last stability analysis document that we created, or NULL if we never
911 * have created one. */
912 static char *last_stability_doc = NULL;
913 /** The last time we created a stability analysis document, or 0 if we never
914 * have created one. */
915 static time_t built_last_stability_doc_at = 0;
916 /** Shortest allowable time between building two stability documents. */
917 #define MAX_STABILITY_DOC_BUILD_RATE (3*60)
919 /** Return a pointer to a NUL-terminated document describing our view of the
920 * stability of the routers we've been tracking. Return NULL on failure. */
921 const char *
922 rep_hist_get_router_stability_doc(time_t now)
924 char *result;
925 smartlist_t *chunks;
926 if (built_last_stability_doc_at + MAX_STABILITY_DOC_BUILD_RATE > now)
927 return last_stability_doc;
929 if (!history_map)
930 return NULL;
932 tor_free(last_stability_doc);
933 chunks = smartlist_create();
935 if (rep_hist_have_measured_enough_stability()) {
936 smartlist_add(chunks, tor_strdup("we-have-enough-measurements\n"));
937 } else {
938 smartlist_add(chunks, tor_strdup("we-do-not-have-enough-measurements\n"));
941 DIGESTMAP_FOREACH(history_map, id, or_history_t *, hist) {
942 const node_t *node;
943 char dbuf[BASE64_DIGEST_LEN+1];
944 char *info;
945 digest_to_base64(dbuf, id);
946 node = node_get_by_id(id);
947 if (node) {
948 char ip[INET_NTOA_BUF_LEN+1];
949 char tbuf[ISO_TIME_LEN+1];
950 time_t published = node_get_published_on(node);
951 node_get_address_string(node,ip,sizeof(ip));
952 if (published > 0)
953 format_iso_time(tbuf, published);
954 else
955 strlcpy(tbuf, "???", sizeof(tbuf));
956 smartlist_add_asprintf(chunks,
957 "router %s %s %s\n"
958 "published %s\n"
959 "relevant-flags %s%s%s\n"
960 "declared-uptime %ld\n",
961 dbuf, node_get_nickname(node), ip,
962 tbuf,
963 node->is_running ? "Running " : "",
964 node->is_valid ? "Valid " : "",
965 node->ri && node->ri->is_hibernating ? "Hibernating " : "",
966 node_get_declared_uptime(node));
967 } else {
968 smartlist_add_asprintf(chunks,
969 "router %s {no descriptor}\n", dbuf);
971 info = rep_hist_format_router_status(hist, now);
972 if (info)
973 smartlist_add(chunks, info);
975 } DIGESTMAP_FOREACH_END;
977 result = smartlist_join_strings(chunks, "", 0, NULL);
978 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
979 smartlist_free(chunks);
981 last_stability_doc = result;
982 built_last_stability_doc_at = time(NULL);
983 return result;
986 /** Helper: return the first j >= i such that !strcmpstart(sl[j], prefix) and
987 * such that no line sl[k] with i <= k < j starts with "R ". Return -1 if no
988 * such line exists. */
989 static int
990 find_next_with(smartlist_t *sl, int i, const char *prefix)
992 for ( ; i < smartlist_len(sl); ++i) {
993 const char *line = smartlist_get(sl, i);
994 if (!strcmpstart(line, prefix))
995 return i;
996 if (!strcmpstart(line, "R "))
997 return -1;
999 return -1;
1002 /** How many bad times has parse_possibly_bad_iso_time() parsed? */
1003 static int n_bogus_times = 0;
1004 /** Parse the ISO-formatted time in <b>s</b> into *<b>time_out</b>, but
1005 * round any pre-1970 date to Jan 1, 1970. */
1006 static int
1007 parse_possibly_bad_iso_time(const char *s, time_t *time_out)
1009 int year;
1010 char b[5];
1011 strlcpy(b, s, sizeof(b));
1012 b[4] = '\0';
1013 year = (int)tor_parse_long(b, 10, 0, INT_MAX, NULL, NULL);
1014 if (year < 1970) {
1015 *time_out = 0;
1016 ++n_bogus_times;
1017 return 0;
1018 } else
1019 return parse_iso_time(s, time_out);
1022 /** We've read a time <b>t</b> from a file stored at <b>stored_at</b>, which
1023 * says we started measuring at <b>started_measuring</b>. Return a new number
1024 * that's about as much before <b>now</b> as <b>t</b> was before
1025 * <b>stored_at</b>.
1027 static INLINE time_t
1028 correct_time(time_t t, time_t now, time_t stored_at, time_t started_measuring)
1030 if (t < started_measuring - 24*60*60*365)
1031 return 0;
1032 else if (t < started_measuring)
1033 return started_measuring;
1034 else if (t > stored_at)
1035 return 0;
1036 else {
1037 long run_length = stored_at - t;
1038 t = now - run_length;
1039 if (t < started_measuring)
1040 t = started_measuring;
1041 return t;
1045 /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
1046 * on failure. */
1048 rep_hist_load_mtbf_data(time_t now)
1050 /* XXXX won't handle being called while history is already populated. */
1051 smartlist_t *lines;
1052 const char *line = NULL;
1053 int r=0, i;
1054 time_t last_downrated = 0, stored_at = 0, tracked_since = 0;
1055 time_t latest_possible_start = now;
1056 long format = -1;
1059 char *filename = get_datadir_fname("router-stability");
1060 char *d = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
1061 tor_free(filename);
1062 if (!d)
1063 return -1;
1064 lines = smartlist_create();
1065 smartlist_split_string(lines, d, "\n", SPLIT_SKIP_SPACE, 0);
1066 tor_free(d);
1070 const char *firstline;
1071 if (smartlist_len(lines)>4) {
1072 firstline = smartlist_get(lines, 0);
1073 if (!strcmpstart(firstline, "format "))
1074 format = tor_parse_long(firstline+strlen("format "),
1075 10, -1, LONG_MAX, NULL, NULL);
1078 if (format != 1 && format != 2) {
1079 log_warn(LD_HIST,
1080 "Unrecognized format in mtbf history file. Skipping.");
1081 goto err;
1083 for (i = 1; i < smartlist_len(lines); ++i) {
1084 line = smartlist_get(lines, i);
1085 if (!strcmp(line, "data"))
1086 break;
1087 if (!strcmpstart(line, "last-downrated ")) {
1088 if (parse_iso_time(line+strlen("last-downrated "), &last_downrated)<0)
1089 log_warn(LD_HIST,"Couldn't parse downrate time in mtbf "
1090 "history file.");
1092 if (!strcmpstart(line, "stored-at ")) {
1093 if (parse_iso_time(line+strlen("stored-at "), &stored_at)<0)
1094 log_warn(LD_HIST,"Couldn't parse stored time in mtbf "
1095 "history file.");
1097 if (!strcmpstart(line, "tracked-since ")) {
1098 if (parse_iso_time(line+strlen("tracked-since "), &tracked_since)<0)
1099 log_warn(LD_HIST,"Couldn't parse started-tracking time in mtbf "
1100 "history file.");
1103 if (last_downrated > now)
1104 last_downrated = now;
1105 if (tracked_since > now)
1106 tracked_since = now;
1108 if (!stored_at) {
1109 log_warn(LD_HIST, "No stored time recorded.");
1110 goto err;
1113 if (line && !strcmp(line, "data"))
1114 ++i;
1116 n_bogus_times = 0;
1118 for (; i < smartlist_len(lines); ++i) {
1119 char digest[DIGEST_LEN];
1120 char hexbuf[HEX_DIGEST_LEN+1];
1121 char mtbf_timebuf[ISO_TIME_LEN+1];
1122 char wfu_timebuf[ISO_TIME_LEN+1];
1123 time_t start_of_run = 0;
1124 time_t start_of_downtime = 0;
1125 int have_mtbf = 0, have_wfu = 0;
1126 long wrl = 0;
1127 double trw = 0;
1128 long wt_uptime = 0, total_wt_time = 0;
1129 int n;
1130 or_history_t *hist;
1131 line = smartlist_get(lines, i);
1132 if (!strcmp(line, "."))
1133 break;
1135 mtbf_timebuf[0] = '\0';
1136 wfu_timebuf[0] = '\0';
1138 if (format == 1) {
1139 n = sscanf(line, "%40s %ld %lf S=%10s %8s",
1140 hexbuf, &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1141 if (n != 3 && n != 5) {
1142 log_warn(LD_HIST, "Couldn't scan line %s", escaped(line));
1143 continue;
1145 have_mtbf = 1;
1146 } else {
1147 // format == 2.
1148 int mtbf_idx, wfu_idx;
1149 if (strcmpstart(line, "R ") || strlen(line) < 2+HEX_DIGEST_LEN)
1150 continue;
1151 strlcpy(hexbuf, line+2, sizeof(hexbuf));
1152 mtbf_idx = find_next_with(lines, i+1, "+MTBF ");
1153 wfu_idx = find_next_with(lines, i+1, "+WFU ");
1154 if (mtbf_idx >= 0) {
1155 const char *mtbfline = smartlist_get(lines, mtbf_idx);
1156 n = sscanf(mtbfline, "+MTBF %lu %lf S=%10s %8s",
1157 &wrl, &trw, mtbf_timebuf, mtbf_timebuf+11);
1158 if (n == 2 || n == 4) {
1159 have_mtbf = 1;
1160 } else {
1161 log_warn(LD_HIST, "Couldn't scan +MTBF line %s",
1162 escaped(mtbfline));
1165 if (wfu_idx >= 0) {
1166 const char *wfuline = smartlist_get(lines, wfu_idx);
1167 n = sscanf(wfuline, "+WFU %lu %lu S=%10s %8s",
1168 &wt_uptime, &total_wt_time,
1169 wfu_timebuf, wfu_timebuf+11);
1170 if (n == 2 || n == 4) {
1171 have_wfu = 1;
1172 } else {
1173 log_warn(LD_HIST, "Couldn't scan +WFU line %s", escaped(wfuline));
1176 if (wfu_idx > i)
1177 i = wfu_idx;
1178 if (mtbf_idx > i)
1179 i = mtbf_idx;
1181 if (base16_decode(digest, DIGEST_LEN, hexbuf, HEX_DIGEST_LEN) < 0) {
1182 log_warn(LD_HIST, "Couldn't hex string %s", escaped(hexbuf));
1183 continue;
1185 hist = get_or_history(digest);
1186 if (!hist)
1187 continue;
1189 if (have_mtbf) {
1190 if (mtbf_timebuf[0]) {
1191 mtbf_timebuf[10] = ' ';
1192 if (parse_possibly_bad_iso_time(mtbf_timebuf, &start_of_run)<0)
1193 log_warn(LD_HIST, "Couldn't parse time %s",
1194 escaped(mtbf_timebuf));
1196 hist->start_of_run = correct_time(start_of_run, now, stored_at,
1197 tracked_since);
1198 if (hist->start_of_run < latest_possible_start + wrl)
1199 latest_possible_start = hist->start_of_run - wrl;
1201 hist->weighted_run_length = wrl;
1202 hist->total_run_weights = trw;
1204 if (have_wfu) {
1205 if (wfu_timebuf[0]) {
1206 wfu_timebuf[10] = ' ';
1207 if (parse_possibly_bad_iso_time(wfu_timebuf, &start_of_downtime)<0)
1208 log_warn(LD_HIST, "Couldn't parse time %s", escaped(wfu_timebuf));
1211 hist->start_of_downtime = correct_time(start_of_downtime, now, stored_at,
1212 tracked_since);
1213 hist->weighted_uptime = wt_uptime;
1214 hist->total_weighted_time = total_wt_time;
1216 if (strcmp(line, "."))
1217 log_warn(LD_HIST, "Truncated MTBF file.");
1219 if (tracked_since < 86400*365) /* Recover from insanely early value. */
1220 tracked_since = latest_possible_start;
1222 stability_last_downrated = last_downrated;
1223 started_tracking_stability = tracked_since;
1225 goto done;
1226 err:
1227 r = -1;
1228 done:
1229 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1230 smartlist_free(lines);
1231 return r;
1234 /** For how many seconds do we keep track of individual per-second bandwidth
1235 * totals? */
1236 #define NUM_SECS_ROLLING_MEASURE 10
1237 /** How large are the intervals for which we track and report bandwidth use? */
1238 /* XXXX Watch out! Before Tor 0.2.2.21-alpha, using any other value here would
1239 * generate an unparseable state file. */
1240 #define NUM_SECS_BW_SUM_INTERVAL (15*60)
1241 /** How far in the past do we remember and publish bandwidth use? */
1242 #define NUM_SECS_BW_SUM_IS_VALID (24*60*60)
1243 /** How many bandwidth usage intervals do we remember? (derived) */
1244 #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
1246 /** Structure to track bandwidth use, and remember the maxima for a given
1247 * time period.
1249 typedef struct bw_array_t {
1250 /** Observation array: Total number of bytes transferred in each of the last
1251 * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
1252 uint64_t obs[NUM_SECS_ROLLING_MEASURE];
1253 int cur_obs_idx; /**< Current position in obs. */
1254 time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
1255 uint64_t total_obs; /**< Total for all members of obs except
1256 * obs[cur_obs_idx] */
1257 uint64_t max_total; /**< Largest value that total_obs has taken on in the
1258 * current period. */
1259 uint64_t total_in_period; /**< Total bytes transferred in the current
1260 * period. */
1262 /** When does the next period begin? */
1263 time_t next_period;
1264 /** Where in 'maxima' should the maximum bandwidth usage for the current
1265 * period be stored? */
1266 int next_max_idx;
1267 /** How many values in maxima/totals have been set ever? */
1268 int num_maxes_set;
1269 /** Circular array of the maximum
1270 * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
1271 * NUM_TOTALS periods */
1272 uint64_t maxima[NUM_TOTALS];
1273 /** Circular array of the total bandwidth usage for the last NUM_TOTALS
1274 * periods */
1275 uint64_t totals[NUM_TOTALS];
1276 } bw_array_t;
1278 /** Shift the current period of b forward by one. */
1279 static void
1280 commit_max(bw_array_t *b)
1282 /* Store total from current period. */
1283 b->totals[b->next_max_idx] = b->total_in_period;
1284 /* Store maximum from current period. */
1285 b->maxima[b->next_max_idx++] = b->max_total;
1286 /* Advance next_period and next_max_idx */
1287 b->next_period += NUM_SECS_BW_SUM_INTERVAL;
1288 if (b->next_max_idx == NUM_TOTALS)
1289 b->next_max_idx = 0;
1290 if (b->num_maxes_set < NUM_TOTALS)
1291 ++b->num_maxes_set;
1292 /* Reset max_total. */
1293 b->max_total = 0;
1294 /* Reset total_in_period. */
1295 b->total_in_period = 0;
1298 /** Shift the current observation time of <b>b</b> forward by one second. */
1299 static INLINE void
1300 advance_obs(bw_array_t *b)
1302 int nextidx;
1303 uint64_t total;
1305 /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
1306 * seconds; adjust max_total as needed.*/
1307 total = b->total_obs + b->obs[b->cur_obs_idx];
1308 if (total > b->max_total)
1309 b->max_total = total;
1311 nextidx = b->cur_obs_idx+1;
1312 if (nextidx == NUM_SECS_ROLLING_MEASURE)
1313 nextidx = 0;
1315 b->total_obs = total - b->obs[nextidx];
1316 b->obs[nextidx]=0;
1317 b->cur_obs_idx = nextidx;
1319 if (++b->cur_obs_time >= b->next_period)
1320 commit_max(b);
1323 /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
1324 * <b>when</b>. */
1325 static INLINE void
1326 add_obs(bw_array_t *b, time_t when, uint64_t n)
1328 if (when < b->cur_obs_time)
1329 return; /* Don't record data in the past. */
1331 /* If we're currently adding observations for an earlier second than
1332 * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
1333 * appropriate number of seconds, and do all the other housekeeping. */
1334 while (when > b->cur_obs_time) {
1335 /* Doing this one second at a time is potentially inefficient, if we start
1336 with a state file that is very old. Fortunately, it doesn't seem to
1337 show up in profiles, so we can just ignore it for now. */
1338 advance_obs(b);
1341 b->obs[b->cur_obs_idx] += n;
1342 b->total_in_period += n;
1345 /** Allocate, initialize, and return a new bw_array. */
1346 static bw_array_t *
1347 bw_array_new(void)
1349 bw_array_t *b;
1350 time_t start;
1351 b = tor_malloc_zero(sizeof(bw_array_t));
1352 rephist_total_alloc += sizeof(bw_array_t);
1353 start = time(NULL);
1354 b->cur_obs_time = start;
1355 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1356 return b;
1359 /** Recent history of bandwidth observations for read operations. */
1360 static bw_array_t *read_array = NULL;
1361 /** Recent history of bandwidth observations for write operations. */
1362 static bw_array_t *write_array = NULL;
1363 /** Recent history of bandwidth observations for read operations for the
1364 directory protocol. */
1365 static bw_array_t *dir_read_array = NULL;
1366 /** Recent history of bandwidth observations for write operations for the
1367 directory protocol. */
1368 static bw_array_t *dir_write_array = NULL;
1370 /** Set up [dir-]read_array and [dir-]write_array, freeing them if they
1371 * already exist. */
1372 static void
1373 bw_arrays_init(void)
1375 tor_free(read_array);
1376 tor_free(write_array);
1377 tor_free(dir_read_array);
1378 tor_free(dir_write_array);
1379 read_array = bw_array_new();
1380 write_array = bw_array_new();
1381 dir_read_array = bw_array_new();
1382 dir_write_array = bw_array_new();
1385 /** Remember that we read <b>num_bytes</b> bytes in second <b>when</b>.
1387 * Add num_bytes to the current running total for <b>when</b>.
1389 * <b>when</b> can go back to time, but it's safe to ignore calls
1390 * earlier than the latest <b>when</b> you've heard of.
1392 void
1393 rep_hist_note_bytes_written(size_t num_bytes, time_t when)
1395 /* Maybe a circular array for recent seconds, and step to a new point
1396 * every time a new second shows up. Or simpler is to just to have
1397 * a normal array and push down each item every second; it's short.
1399 /* When a new second has rolled over, compute the sum of the bytes we've
1400 * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
1401 * somewhere. See rep_hist_bandwidth_assess() below.
1403 add_obs(write_array, when, num_bytes);
1406 /** Remember that we wrote <b>num_bytes</b> bytes in second <b>when</b>.
1407 * (like rep_hist_note_bytes_written() above)
1409 void
1410 rep_hist_note_bytes_read(size_t num_bytes, time_t when)
1412 /* if we're smart, we can make this func and the one above share code */
1413 add_obs(read_array, when, num_bytes);
1416 /** Remember that we wrote <b>num_bytes</b> directory bytes in second
1417 * <b>when</b>. (like rep_hist_note_bytes_written() above)
1419 void
1420 rep_hist_note_dir_bytes_written(size_t num_bytes, time_t when)
1422 add_obs(dir_write_array, when, num_bytes);
1425 /** Remember that we read <b>num_bytes</b> directory bytes in second
1426 * <b>when</b>. (like rep_hist_note_bytes_written() above)
1428 void
1429 rep_hist_note_dir_bytes_read(size_t num_bytes, time_t when)
1431 add_obs(dir_read_array, when, num_bytes);
1434 /** Helper: Return the largest value in b->maxima. (This is equal to the
1435 * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
1436 * NUM_SECS_BW_SUM_IS_VALID seconds.)
1438 static uint64_t
1439 find_largest_max(bw_array_t *b)
1441 int i;
1442 uint64_t max;
1443 max=0;
1444 for (i=0; i<NUM_TOTALS; ++i) {
1445 if (b->maxima[i]>max)
1446 max = b->maxima[i];
1448 return max;
1451 /** Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
1452 * seconds. Find one sum for reading and one for writing. They don't have
1453 * to be at the same time.
1455 * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
1458 rep_hist_bandwidth_assess(void)
1460 uint64_t w,r;
1461 r = find_largest_max(read_array);
1462 w = find_largest_max(write_array);
1463 if (r>w)
1464 return (int)(U64_TO_DBL(w)/NUM_SECS_ROLLING_MEASURE);
1465 else
1466 return (int)(U64_TO_DBL(r)/NUM_SECS_ROLLING_MEASURE);
1469 /** Print the bandwidth history of b (either [dir-]read_array or
1470 * [dir-]write_array) into the buffer pointed to by buf. The format is
1471 * simply comma separated numbers, from oldest to newest.
1473 * It returns the number of bytes written.
1475 static size_t
1476 rep_hist_fill_bandwidth_history(char *buf, size_t len, const bw_array_t *b)
1478 char *cp = buf;
1479 int i, n;
1480 const or_options_t *options = get_options();
1481 uint64_t cutoff;
1483 if (b->num_maxes_set <= b->next_max_idx) {
1484 /* We haven't been through the circular array yet; time starts at i=0.*/
1485 i = 0;
1486 } else {
1487 /* We've been around the array at least once. The next i to be
1488 overwritten is the oldest. */
1489 i = b->next_max_idx;
1492 if (options->RelayBandwidthRate) {
1493 /* We don't want to report that we used more bandwidth than the max we're
1494 * willing to relay; otherwise everybody will know how much traffic
1495 * we used ourself. */
1496 cutoff = options->RelayBandwidthRate * NUM_SECS_BW_SUM_INTERVAL;
1497 } else {
1498 cutoff = UINT64_MAX;
1501 for (n=0; n<b->num_maxes_set; ++n,++i) {
1502 uint64_t total;
1503 if (i >= NUM_TOTALS)
1504 i -= NUM_TOTALS;
1505 tor_assert(i < NUM_TOTALS);
1506 /* Round the bandwidth used down to the nearest 1k. */
1507 total = b->totals[i] & ~0x3ff;
1508 if (total > cutoff)
1509 total = cutoff;
1511 if (n==(b->num_maxes_set-1))
1512 tor_snprintf(cp, len-(cp-buf), U64_FORMAT, U64_PRINTF_ARG(total));
1513 else
1514 tor_snprintf(cp, len-(cp-buf), U64_FORMAT",", U64_PRINTF_ARG(total));
1515 cp += strlen(cp);
1517 return cp-buf;
1520 /** Allocate and return lines for representing this server's bandwidth
1521 * history in its descriptor. We publish these lines in our extra-info
1522 * descriptor.
1524 char *
1525 rep_hist_get_bandwidth_lines(void)
1527 char *buf, *cp;
1528 char t[ISO_TIME_LEN+1];
1529 int r;
1530 bw_array_t *b = NULL;
1531 const char *desc = NULL;
1532 size_t len;
1534 /* opt [dirreq-](read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n... */
1535 /* The n,n,n part above. Largest representation of a uint64_t is 20 chars
1536 * long, plus the comma. */
1537 #define MAX_HIST_VALUE_LEN 21*NUM_TOTALS
1538 len = (67+MAX_HIST_VALUE_LEN)*4;
1539 buf = tor_malloc_zero(len);
1540 cp = buf;
1541 for (r=0;r<4;++r) {
1542 char tmp[MAX_HIST_VALUE_LEN];
1543 size_t slen;
1544 switch (r) {
1545 case 0:
1546 b = write_array;
1547 desc = "write-history";
1548 break;
1549 case 1:
1550 b = read_array;
1551 desc = "read-history";
1552 break;
1553 case 2:
1554 b = dir_write_array;
1555 desc = "dirreq-write-history";
1556 break;
1557 case 3:
1558 b = dir_read_array;
1559 desc = "dirreq-read-history";
1560 break;
1562 tor_assert(b);
1563 slen = rep_hist_fill_bandwidth_history(tmp, MAX_HIST_VALUE_LEN, b);
1564 /* If we don't have anything to write, skip to the next entry. */
1565 if (slen == 0)
1566 continue;
1567 format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
1568 tor_snprintf(cp, len-(cp-buf), "%s %s (%d s) ",
1569 desc, t, NUM_SECS_BW_SUM_INTERVAL);
1570 cp += strlen(cp);
1571 strlcat(cp, tmp, len-(cp-buf));
1572 cp += slen;
1573 strlcat(cp, "\n", len-(cp-buf));
1574 ++cp;
1576 return buf;
1579 /** Write a single bw_array_t into the Values, Ends, Interval, and Maximum
1580 * entries of an or_state_t. Done before writing out a new state file. */
1581 static void
1582 rep_hist_update_bwhist_state_section(or_state_t *state,
1583 const bw_array_t *b,
1584 smartlist_t **s_values,
1585 smartlist_t **s_maxima,
1586 time_t *s_begins,
1587 int *s_interval)
1589 int i,j;
1590 uint64_t maxval;
1592 if (*s_values) {
1593 SMARTLIST_FOREACH(*s_values, char *, val, tor_free(val));
1594 smartlist_free(*s_values);
1596 if (*s_maxima) {
1597 SMARTLIST_FOREACH(*s_maxima, char *, val, tor_free(val));
1598 smartlist_free(*s_maxima);
1600 if (! server_mode(get_options())) {
1601 /* Clients don't need to store bandwidth history persistently;
1602 * force these values to the defaults. */
1603 /* FFFF we should pull the default out of config.c's state table,
1604 * so we don't have two defaults. */
1605 if (*s_begins != 0 || *s_interval != 900) {
1606 time_t now = time(NULL);
1607 time_t save_at = get_options()->AvoidDiskWrites ? now+3600 : now+600;
1608 or_state_mark_dirty(state, save_at);
1610 *s_begins = 0;
1611 *s_interval = 900;
1612 *s_values = smartlist_create();
1613 *s_maxima = smartlist_create();
1614 return;
1616 *s_begins = b->next_period;
1617 *s_interval = NUM_SECS_BW_SUM_INTERVAL;
1619 *s_values = smartlist_create();
1620 *s_maxima = smartlist_create();
1621 /* Set i to first position in circular array */
1622 i = (b->num_maxes_set <= b->next_max_idx) ? 0 : b->next_max_idx;
1623 for (j=0; j < b->num_maxes_set; ++j,++i) {
1624 if (i >= NUM_TOTALS)
1625 i = 0;
1626 smartlist_add_asprintf(*s_values, U64_FORMAT,
1627 U64_PRINTF_ARG(b->totals[i] & ~0x3ff));
1628 maxval = b->maxima[i] / NUM_SECS_ROLLING_MEASURE;
1629 smartlist_add_asprintf(*s_maxima, U64_FORMAT,
1630 U64_PRINTF_ARG(maxval & ~0x3ff));
1632 smartlist_add_asprintf(*s_values, U64_FORMAT,
1633 U64_PRINTF_ARG(b->total_in_period & ~0x3ff));
1634 maxval = b->max_total / NUM_SECS_ROLLING_MEASURE;
1635 smartlist_add_asprintf(*s_maxima, U64_FORMAT,
1636 U64_PRINTF_ARG(maxval & ~0x3ff));
1639 /** Update <b>state</b> with the newest bandwidth history. Done before
1640 * writing out a new state file. */
1641 void
1642 rep_hist_update_state(or_state_t *state)
1644 #define UPDATE(arrname,st) \
1645 rep_hist_update_bwhist_state_section(state,\
1646 (arrname),\
1647 &state->BWHistory ## st ## Values, \
1648 &state->BWHistory ## st ## Maxima, \
1649 &state->BWHistory ## st ## Ends, \
1650 &state->BWHistory ## st ## Interval)
1652 UPDATE(write_array, Write);
1653 UPDATE(read_array, Read);
1654 UPDATE(dir_write_array, DirWrite);
1655 UPDATE(dir_read_array, DirRead);
1657 if (server_mode(get_options())) {
1658 or_state_mark_dirty(state, time(NULL)+(2*3600));
1660 #undef UPDATE
1663 /** Load a single bw_array_t from its Values, Ends, Maxima, and Interval
1664 * entries in an or_state_t. Done while reading the state file. */
1665 static int
1666 rep_hist_load_bwhist_state_section(bw_array_t *b,
1667 const smartlist_t *s_values,
1668 const smartlist_t *s_maxima,
1669 const time_t s_begins,
1670 const int s_interval)
1672 time_t now = time(NULL);
1673 int retval = 0;
1674 time_t start;
1676 uint64_t v, mv;
1677 int i,ok,ok_m;
1678 int have_maxima = (smartlist_len(s_values) == smartlist_len(s_maxima));
1680 if (s_values && s_begins >= now - NUM_SECS_BW_SUM_INTERVAL*NUM_TOTALS) {
1681 start = s_begins - s_interval*(smartlist_len(s_values));
1682 if (start > now)
1683 return 0;
1684 b->cur_obs_time = start;
1685 b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
1686 SMARTLIST_FOREACH_BEGIN(s_values, const char *, cp) {
1687 const char *maxstr = NULL;
1688 v = tor_parse_uint64(cp, 10, 0, UINT64_MAX, &ok, NULL);
1689 if (have_maxima) {
1690 maxstr = smartlist_get(s_maxima, cp_sl_idx);
1691 mv = tor_parse_uint64(maxstr, 10, 0, UINT64_MAX, &ok_m, NULL);
1692 mv *= NUM_SECS_ROLLING_MEASURE;
1693 } else {
1694 /* No maxima known; guess average rate to be conservative. */
1695 mv = (v / s_interval) * NUM_SECS_ROLLING_MEASURE;
1697 if (!ok) {
1698 retval = -1;
1699 log_notice(LD_HIST, "Could not parse value '%s' into a number.'",cp);
1701 if (maxstr && !ok_m) {
1702 retval = -1;
1703 log_notice(LD_HIST, "Could not parse maximum '%s' into a number.'",
1704 maxstr);
1707 if (start < now) {
1708 time_t cur_start = start;
1709 time_t actual_interval_len = s_interval;
1710 uint64_t cur_val = 0;
1711 /* Calculate the average per second. This is the best we can do
1712 * because our state file doesn't have per-second resolution. */
1713 if (start + s_interval > now)
1714 actual_interval_len = now - start;
1715 cur_val = v / actual_interval_len;
1716 /* This is potentially inefficient, but since we don't do it very
1717 * often it should be ok. */
1718 while (cur_start < start + actual_interval_len) {
1719 add_obs(b, cur_start, cur_val);
1720 ++cur_start;
1722 b->max_total = mv;
1723 /* This will result in some fairly choppy history if s_interval
1724 * is not the same as NUM_SECS_BW_SUM_INTERVAL. XXXX */
1725 start += actual_interval_len;
1727 } SMARTLIST_FOREACH_END(cp);
1730 /* Clean up maxima and observed */
1731 for (i=0; i<NUM_SECS_ROLLING_MEASURE; ++i) {
1732 b->obs[i] = 0;
1734 b->total_obs = 0;
1736 return retval;
1739 /** Set bandwidth history from the state file we just loaded. */
1741 rep_hist_load_state(or_state_t *state, char **err)
1743 int all_ok = 1;
1745 /* Assert they already have been malloced */
1746 tor_assert(read_array && write_array);
1747 tor_assert(dir_read_array && dir_write_array);
1749 #define LOAD(arrname,st) \
1750 if (rep_hist_load_bwhist_state_section( \
1751 (arrname), \
1752 state->BWHistory ## st ## Values, \
1753 state->BWHistory ## st ## Maxima, \
1754 state->BWHistory ## st ## Ends, \
1755 state->BWHistory ## st ## Interval)<0) \
1756 all_ok = 0
1758 LOAD(write_array, Write);
1759 LOAD(read_array, Read);
1760 LOAD(dir_write_array, DirWrite);
1761 LOAD(dir_read_array, DirRead);
1763 #undef LOAD
1764 if (!all_ok) {
1765 *err = tor_strdup("Parsing of bandwidth history values failed");
1766 /* and create fresh arrays */
1767 bw_arrays_init();
1768 return -1;
1770 return 0;
1773 /*********************************************************************/
1775 typedef struct predicted_port_t {
1776 uint16_t port;
1777 time_t time;
1778 } predicted_port_t;
1780 /** A list of port numbers that have been used recently. */
1781 static smartlist_t *predicted_ports_list=NULL;
1783 /** We just got an application request for a connection with
1784 * port <b>port</b>. Remember it for the future, so we can keep
1785 * some circuits open that will exit to this port.
1787 static void
1788 add_predicted_port(time_t now, uint16_t port)
1790 predicted_port_t *pp = tor_malloc(sizeof(predicted_port_t));
1791 pp->port = port;
1792 pp->time = now;
1793 rephist_total_alloc += sizeof(*pp);
1794 smartlist_add(predicted_ports_list, pp);
1797 /** Initialize whatever memory and structs are needed for predicting
1798 * which ports will be used. Also seed it with port 80, so we'll build
1799 * circuits on start-up.
1801 static void
1802 predicted_ports_init(void)
1804 predicted_ports_list = smartlist_create();
1805 add_predicted_port(time(NULL), 80); /* add one to kickstart us */
1808 /** Free whatever memory is needed for predicting which ports will
1809 * be used.
1811 static void
1812 predicted_ports_free(void)
1814 rephist_total_alloc -=
1815 smartlist_len(predicted_ports_list)*sizeof(predicted_port_t);
1816 SMARTLIST_FOREACH(predicted_ports_list, predicted_port_t *,
1817 pp, tor_free(pp));
1818 smartlist_free(predicted_ports_list);
1821 /** Remember that <b>port</b> has been asked for as of time <b>now</b>.
1822 * This is used for predicting what sorts of streams we'll make in the
1823 * future and making exit circuits to anticipate that.
1825 void
1826 rep_hist_note_used_port(time_t now, uint16_t port)
1828 tor_assert(predicted_ports_list);
1830 if (!port) /* record nothing */
1831 return;
1833 SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
1834 if (pp->port == port) {
1835 pp->time = now;
1836 return;
1838 } SMARTLIST_FOREACH_END(pp);
1839 /* it's not there yet; we need to add it */
1840 add_predicted_port(now, port);
1843 /** For this long after we've seen a request for a given port, assume that
1844 * we'll want to make connections to the same port in the future. */
1845 #define PREDICTED_CIRCS_RELEVANCE_TIME (60*60)
1847 /** Return a newly allocated pointer to a list of uint16_t * for ports that
1848 * are likely to be asked for in the near future.
1850 smartlist_t *
1851 rep_hist_get_predicted_ports(time_t now)
1853 smartlist_t *out = smartlist_create();
1854 tor_assert(predicted_ports_list);
1856 /* clean out obsolete entries */
1857 SMARTLIST_FOREACH_BEGIN(predicted_ports_list, predicted_port_t *, pp) {
1858 if (pp->time + PREDICTED_CIRCS_RELEVANCE_TIME < now) {
1859 log_debug(LD_CIRC, "Expiring predicted port %d", pp->port);
1861 rephist_total_alloc -= sizeof(predicted_port_t);
1862 tor_free(pp);
1863 SMARTLIST_DEL_CURRENT(predicted_ports_list, pp);
1864 } else {
1865 smartlist_add(out, tor_memdup(&pp->port, sizeof(uint16_t)));
1867 } SMARTLIST_FOREACH_END(pp);
1868 return out;
1871 /** The user asked us to do a resolve. Rather than keeping track of
1872 * timings and such of resolves, we fake it for now by treating
1873 * it the same way as a connection to port 80. This way we will continue
1874 * to have circuits lying around if the user only uses Tor for resolves.
1876 void
1877 rep_hist_note_used_resolve(time_t now)
1879 rep_hist_note_used_port(now, 80);
1882 /** The last time at which we needed an internal circ. */
1883 static time_t predicted_internal_time = 0;
1884 /** The last time we needed an internal circ with good uptime. */
1885 static time_t predicted_internal_uptime_time = 0;
1886 /** The last time we needed an internal circ with good capacity. */
1887 static time_t predicted_internal_capacity_time = 0;
1889 /** Remember that we used an internal circ at time <b>now</b>. */
1890 void
1891 rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
1893 predicted_internal_time = now;
1894 if (need_uptime)
1895 predicted_internal_uptime_time = now;
1896 if (need_capacity)
1897 predicted_internal_capacity_time = now;
1900 /** Return 1 if we've used an internal circ recently; else return 0. */
1902 rep_hist_get_predicted_internal(time_t now, int *need_uptime,
1903 int *need_capacity)
1905 if (!predicted_internal_time) { /* initialize it */
1906 predicted_internal_time = now;
1907 predicted_internal_uptime_time = now;
1908 predicted_internal_capacity_time = now;
1910 if (predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME < now)
1911 return 0; /* too long ago */
1912 if (predicted_internal_uptime_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now)
1913 *need_uptime = 1;
1914 // Always predict that we need capacity.
1915 *need_capacity = 1;
1916 return 1;
1919 /** Any ports used lately? These are pre-seeded if we just started
1920 * up or if we're running a hidden service. */
1922 any_predicted_circuits(time_t now)
1924 return smartlist_len(predicted_ports_list) ||
1925 predicted_internal_time + PREDICTED_CIRCS_RELEVANCE_TIME >= now;
1928 /** Return 1 if we have no need for circuits currently, else return 0. */
1930 rep_hist_circbuilding_dormant(time_t now)
1932 if (any_predicted_circuits(now))
1933 return 0;
1935 /* see if we'll still need to build testing circuits */
1936 if (server_mode(get_options()) &&
1937 (!check_whether_orport_reachable() || !circuit_enough_testing_circs()))
1938 return 0;
1939 if (!check_whether_dirport_reachable())
1940 return 0;
1942 return 1;
1945 /** Structure to track how many times we've done each public key operation. */
1946 static struct {
1947 /** How many directory objects have we signed? */
1948 unsigned long n_signed_dir_objs;
1949 /** How many routerdescs have we signed? */
1950 unsigned long n_signed_routerdescs;
1951 /** How many directory objects have we verified? */
1952 unsigned long n_verified_dir_objs;
1953 /** How many routerdescs have we verified */
1954 unsigned long n_verified_routerdescs;
1955 /** How many onionskins have we encrypted to build circuits? */
1956 unsigned long n_onionskins_encrypted;
1957 /** How many onionskins have we decrypted to do circuit build requests? */
1958 unsigned long n_onionskins_decrypted;
1959 /** How many times have we done the TLS handshake as a client? */
1960 unsigned long n_tls_client_handshakes;
1961 /** How many times have we done the TLS handshake as a server? */
1962 unsigned long n_tls_server_handshakes;
1963 /** How many PK operations have we done as a hidden service client? */
1964 unsigned long n_rend_client_ops;
1965 /** How many PK operations have we done as a hidden service midpoint? */
1966 unsigned long n_rend_mid_ops;
1967 /** How many PK operations have we done as a hidden service provider? */
1968 unsigned long n_rend_server_ops;
1969 } pk_op_counts = {0,0,0,0,0,0,0,0,0,0,0};
1971 /** Increment the count of the number of times we've done <b>operation</b>. */
1972 void
1973 note_crypto_pk_op(pk_op_t operation)
1975 switch (operation)
1977 case SIGN_DIR:
1978 pk_op_counts.n_signed_dir_objs++;
1979 break;
1980 case SIGN_RTR:
1981 pk_op_counts.n_signed_routerdescs++;
1982 break;
1983 case VERIFY_DIR:
1984 pk_op_counts.n_verified_dir_objs++;
1985 break;
1986 case VERIFY_RTR:
1987 pk_op_counts.n_verified_routerdescs++;
1988 break;
1989 case ENC_ONIONSKIN:
1990 pk_op_counts.n_onionskins_encrypted++;
1991 break;
1992 case DEC_ONIONSKIN:
1993 pk_op_counts.n_onionskins_decrypted++;
1994 break;
1995 case TLS_HANDSHAKE_C:
1996 pk_op_counts.n_tls_client_handshakes++;
1997 break;
1998 case TLS_HANDSHAKE_S:
1999 pk_op_counts.n_tls_server_handshakes++;
2000 break;
2001 case REND_CLIENT:
2002 pk_op_counts.n_rend_client_ops++;
2003 break;
2004 case REND_MID:
2005 pk_op_counts.n_rend_mid_ops++;
2006 break;
2007 case REND_SERVER:
2008 pk_op_counts.n_rend_server_ops++;
2009 break;
2010 default:
2011 log_warn(LD_BUG, "Unknown pk operation %d", operation);
2015 /** Log the number of times we've done each public/private-key operation. */
2016 void
2017 dump_pk_ops(int severity)
2019 log(severity, LD_HIST,
2020 "PK operations: %lu directory objects signed, "
2021 "%lu directory objects verified, "
2022 "%lu routerdescs signed, "
2023 "%lu routerdescs verified, "
2024 "%lu onionskins encrypted, "
2025 "%lu onionskins decrypted, "
2026 "%lu client-side TLS handshakes, "
2027 "%lu server-side TLS handshakes, "
2028 "%lu rendezvous client operations, "
2029 "%lu rendezvous middle operations, "
2030 "%lu rendezvous server operations.",
2031 pk_op_counts.n_signed_dir_objs,
2032 pk_op_counts.n_verified_dir_objs,
2033 pk_op_counts.n_signed_routerdescs,
2034 pk_op_counts.n_verified_routerdescs,
2035 pk_op_counts.n_onionskins_encrypted,
2036 pk_op_counts.n_onionskins_decrypted,
2037 pk_op_counts.n_tls_client_handshakes,
2038 pk_op_counts.n_tls_server_handshakes,
2039 pk_op_counts.n_rend_client_ops,
2040 pk_op_counts.n_rend_mid_ops,
2041 pk_op_counts.n_rend_server_ops);
2044 /*** Exit port statistics ***/
2046 /* Some constants */
2047 /** To what multiple should byte numbers be rounded up? */
2048 #define EXIT_STATS_ROUND_UP_BYTES 1024
2049 /** To what multiple should stream counts be rounded up? */
2050 #define EXIT_STATS_ROUND_UP_STREAMS 4
2051 /** Number of TCP ports */
2052 #define EXIT_STATS_NUM_PORTS 65536
2053 /** Top n ports that will be included in exit stats. */
2054 #define EXIT_STATS_TOP_N_PORTS 10
2056 /* The following data structures are arrays and no fancy smartlists or maps,
2057 * so that all write operations can be done in constant time. This comes at
2058 * the price of some memory (1.25 MB) and linear complexity when writing
2059 * stats for measuring relays. */
2060 /** Number of bytes read in current period by exit port */
2061 static uint64_t *exit_bytes_read = NULL;
2062 /** Number of bytes written in current period by exit port */
2063 static uint64_t *exit_bytes_written = NULL;
2064 /** Number of streams opened in current period by exit port */
2065 static uint32_t *exit_streams = NULL;
2067 /** Start time of exit stats or 0 if we're not collecting exit stats. */
2068 static time_t start_of_exit_stats_interval;
2070 /** Initialize exit port stats. */
2071 void
2072 rep_hist_exit_stats_init(time_t now)
2074 start_of_exit_stats_interval = now;
2075 exit_bytes_read = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2076 sizeof(uint64_t));
2077 exit_bytes_written = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2078 sizeof(uint64_t));
2079 exit_streams = tor_malloc_zero(EXIT_STATS_NUM_PORTS *
2080 sizeof(uint32_t));
2083 /** Reset counters for exit port statistics. */
2084 void
2085 rep_hist_reset_exit_stats(time_t now)
2087 start_of_exit_stats_interval = now;
2088 memset(exit_bytes_read, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2089 memset(exit_bytes_written, 0, EXIT_STATS_NUM_PORTS * sizeof(uint64_t));
2090 memset(exit_streams, 0, EXIT_STATS_NUM_PORTS * sizeof(uint32_t));
2093 /** Stop collecting exit port stats in a way that we can re-start doing
2094 * so in rep_hist_exit_stats_init(). */
2095 void
2096 rep_hist_exit_stats_term(void)
2098 start_of_exit_stats_interval = 0;
2099 tor_free(exit_bytes_read);
2100 tor_free(exit_bytes_written);
2101 tor_free(exit_streams);
2104 /** Helper for qsort: compare two ints. Does not handle overflow properly,
2105 * but works fine for sorting an array of port numbers, which is what we use
2106 * it for. */
2107 static int
2108 _compare_int(const void *x, const void *y)
2110 return (*(int*)x - *(int*)y);
2113 /** Return a newly allocated string containing the exit port statistics
2114 * until <b>now</b>, or NULL if we're not collecting exit stats. Caller
2115 * must ensure start_of_exit_stats_interval is in the past. */
2116 char *
2117 rep_hist_format_exit_stats(time_t now)
2119 int i, j, top_elements = 0, cur_min_idx = 0, cur_port;
2120 uint64_t top_bytes[EXIT_STATS_TOP_N_PORTS];
2121 int top_ports[EXIT_STATS_TOP_N_PORTS];
2122 uint64_t cur_bytes = 0, other_read = 0, other_written = 0,
2123 total_read = 0, total_written = 0;
2124 uint32_t total_streams = 0, other_streams = 0;
2125 smartlist_t *written_strings, *read_strings, *streams_strings;
2126 char *written_string, *read_string, *streams_string;
2127 char t[ISO_TIME_LEN+1];
2128 char *result;
2130 if (!start_of_exit_stats_interval)
2131 return NULL; /* Not initialized. */
2133 tor_assert(now >= start_of_exit_stats_interval);
2135 /* Go through all ports to find the n ports that saw most written and
2136 * read bytes.
2138 * Invariant: at the end of the loop for iteration i,
2139 * total_read is the sum of all exit_bytes_read[0..i]
2140 * total_written is the sum of all exit_bytes_written[0..i]
2141 * total_stream is the sum of all exit_streams[0..i]
2143 * top_elements = MAX(EXIT_STATS_TOP_N_PORTS,
2144 * #{j | 0 <= j <= i && volume(i) > 0})
2146 * For all 0 <= j < top_elements,
2147 * top_bytes[j] > 0
2148 * 0 <= top_ports[j] <= 65535
2149 * top_bytes[j] = volume(top_ports[j])
2151 * There is no j in 0..i and k in 0..top_elements such that:
2152 * volume(j) > top_bytes[k] AND j is not in top_ports[0..top_elements]
2154 * There is no j!=cur_min_idx in 0..top_elements such that:
2155 * top_bytes[j] < top_bytes[cur_min_idx]
2157 * where volume(x) == exit_bytes_read[x]+exit_bytes_written[x]
2159 * Worst case: O(EXIT_STATS_NUM_PORTS * EXIT_STATS_TOP_N_PORTS)
2161 for (i = 1; i < EXIT_STATS_NUM_PORTS; i++) {
2162 total_read += exit_bytes_read[i];
2163 total_written += exit_bytes_written[i];
2164 total_streams += exit_streams[i];
2165 cur_bytes = exit_bytes_read[i] + exit_bytes_written[i];
2166 if (cur_bytes == 0) {
2167 continue;
2169 if (top_elements < EXIT_STATS_TOP_N_PORTS) {
2170 top_bytes[top_elements] = cur_bytes;
2171 top_ports[top_elements++] = i;
2172 } else if (cur_bytes > top_bytes[cur_min_idx]) {
2173 top_bytes[cur_min_idx] = cur_bytes;
2174 top_ports[cur_min_idx] = i;
2175 } else {
2176 continue;
2178 cur_min_idx = 0;
2179 for (j = 1; j < top_elements; j++) {
2180 if (top_bytes[j] < top_bytes[cur_min_idx]) {
2181 cur_min_idx = j;
2186 /* Add observations of top ports to smartlists. */
2187 written_strings = smartlist_create();
2188 read_strings = smartlist_create();
2189 streams_strings = smartlist_create();
2190 other_read = total_read;
2191 other_written = total_written;
2192 other_streams = total_streams;
2193 /* Sort the ports; this puts them out of sync with top_bytes, but we
2194 * won't be using top_bytes again anyway */
2195 qsort(top_ports, top_elements, sizeof(int), _compare_int);
2196 for (j = 0; j < top_elements; j++) {
2197 cur_port = top_ports[j];
2198 if (exit_bytes_written[cur_port] > 0) {
2199 uint64_t num = round_uint64_to_next_multiple_of(
2200 exit_bytes_written[cur_port],
2201 EXIT_STATS_ROUND_UP_BYTES);
2202 num /= 1024;
2203 smartlist_add_asprintf(written_strings, "%d="U64_FORMAT,
2204 cur_port, U64_PRINTF_ARG(num));
2205 other_written -= exit_bytes_written[cur_port];
2207 if (exit_bytes_read[cur_port] > 0) {
2208 uint64_t num = round_uint64_to_next_multiple_of(
2209 exit_bytes_read[cur_port],
2210 EXIT_STATS_ROUND_UP_BYTES);
2211 num /= 1024;
2212 smartlist_add_asprintf(read_strings, "%d="U64_FORMAT,
2213 cur_port, U64_PRINTF_ARG(num));
2214 other_read -= exit_bytes_read[cur_port];
2216 if (exit_streams[cur_port] > 0) {
2217 uint32_t num = round_uint32_to_next_multiple_of(
2218 exit_streams[cur_port],
2219 EXIT_STATS_ROUND_UP_STREAMS);
2220 smartlist_add_asprintf(streams_strings, "%d=%u", cur_port, num);
2221 other_streams -= exit_streams[cur_port];
2225 /* Add observations of other ports in a single element. */
2226 other_written = round_uint64_to_next_multiple_of(other_written,
2227 EXIT_STATS_ROUND_UP_BYTES);
2228 other_written /= 1024;
2229 smartlist_add_asprintf(written_strings, "other="U64_FORMAT,
2230 U64_PRINTF_ARG(other_written));
2231 other_read = round_uint64_to_next_multiple_of(other_read,
2232 EXIT_STATS_ROUND_UP_BYTES);
2233 other_read /= 1024;
2234 smartlist_add_asprintf(read_strings, "other="U64_FORMAT,
2235 U64_PRINTF_ARG(other_read));
2236 other_streams = round_uint32_to_next_multiple_of(other_streams,
2237 EXIT_STATS_ROUND_UP_STREAMS);
2238 smartlist_add_asprintf(streams_strings, "other=%u", other_streams);
2240 /* Join all observations in single strings. */
2241 written_string = smartlist_join_strings(written_strings, ",", 0, NULL);
2242 read_string = smartlist_join_strings(read_strings, ",", 0, NULL);
2243 streams_string = smartlist_join_strings(streams_strings, ",", 0, NULL);
2244 SMARTLIST_FOREACH(written_strings, char *, cp, tor_free(cp));
2245 SMARTLIST_FOREACH(read_strings, char *, cp, tor_free(cp));
2246 SMARTLIST_FOREACH(streams_strings, char *, cp, tor_free(cp));
2247 smartlist_free(written_strings);
2248 smartlist_free(read_strings);
2249 smartlist_free(streams_strings);
2251 /* Put everything together. */
2252 format_iso_time(t, now);
2253 tor_asprintf(&result, "exit-stats-end %s (%d s)\n"
2254 "exit-kibibytes-written %s\n"
2255 "exit-kibibytes-read %s\n"
2256 "exit-streams-opened %s\n",
2257 t, (unsigned) (now - start_of_exit_stats_interval),
2258 written_string,
2259 read_string,
2260 streams_string);
2261 tor_free(written_string);
2262 tor_free(read_string);
2263 tor_free(streams_string);
2264 return result;
2267 /** If 24 hours have passed since the beginning of the current exit port
2268 * stats period, write exit stats to $DATADIR/stats/exit-stats (possibly
2269 * overwriting an existing file) and reset counters. Return when we would
2270 * next want to write exit stats or 0 if we never want to write. */
2271 time_t
2272 rep_hist_exit_stats_write(time_t now)
2274 char *statsdir = NULL, *filename = NULL, *str = NULL;
2276 if (!start_of_exit_stats_interval)
2277 return 0; /* Not initialized. */
2278 if (start_of_exit_stats_interval + WRITE_STATS_INTERVAL > now)
2279 goto done; /* Not ready to write. */
2281 log_info(LD_HIST, "Writing exit port statistics to disk.");
2283 /* Generate history string. */
2284 str = rep_hist_format_exit_stats(now);
2286 /* Reset counters. */
2287 rep_hist_reset_exit_stats(now);
2289 /* Try to write to disk. */
2290 statsdir = get_datadir_fname("stats");
2291 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
2292 log_warn(LD_HIST, "Unable to create stats/ directory!");
2293 goto done;
2295 filename = get_datadir_fname2("stats", "exit-stats");
2296 if (write_str_to_file(filename, str, 0) < 0)
2297 log_warn(LD_HIST, "Unable to write exit port statistics to disk!");
2299 done:
2300 tor_free(str);
2301 tor_free(statsdir);
2302 tor_free(filename);
2303 return start_of_exit_stats_interval + WRITE_STATS_INTERVAL;
2306 /** Note that we wrote <b>num_written</b> bytes and read <b>num_read</b>
2307 * bytes to/from an exit connection to <b>port</b>. */
2308 void
2309 rep_hist_note_exit_bytes(uint16_t port, size_t num_written,
2310 size_t num_read)
2312 if (!start_of_exit_stats_interval)
2313 return; /* Not initialized. */
2314 exit_bytes_written[port] += num_written;
2315 exit_bytes_read[port] += num_read;
2316 log_debug(LD_HIST, "Written %lu bytes and read %lu bytes to/from an "
2317 "exit connection to port %d.",
2318 (unsigned long)num_written, (unsigned long)num_read, port);
2321 /** Note that we opened an exit stream to <b>port</b>. */
2322 void
2323 rep_hist_note_exit_stream_opened(uint16_t port)
2325 if (!start_of_exit_stats_interval)
2326 return; /* Not initialized. */
2327 exit_streams[port]++;
2328 log_debug(LD_HIST, "Opened exit stream to port %d", port);
2331 /*** cell statistics ***/
2333 /** Start of the current buffer stats interval or 0 if we're not
2334 * collecting buffer statistics. */
2335 static time_t start_of_buffer_stats_interval;
2337 /** Initialize buffer stats. */
2338 void
2339 rep_hist_buffer_stats_init(time_t now)
2341 start_of_buffer_stats_interval = now;
2344 /** Statistics from a single circuit. Collected when the circuit closes, or
2345 * when we flush statistics to disk. */
2346 typedef struct circ_buffer_stats_t {
2347 /** Average number of cells in the circuit's queue */
2348 double mean_num_cells_in_queue;
2349 /** Average time a cell waits in the queue. */
2350 double mean_time_cells_in_queue;
2351 /** Total number of cells sent over this circuit */
2352 uint32_t processed_cells;
2353 } circ_buffer_stats_t;
2355 /** List of circ_buffer_stats_t. */
2356 static smartlist_t *circuits_for_buffer_stats = NULL;
2358 /** Remember cell statistics <b>mean_num_cells_in_queue</b>,
2359 * <b>mean_time_cells_in_queue</b>, and <b>processed_cells</b> of a
2360 * circuit. */
2361 void
2362 rep_hist_add_buffer_stats(double mean_num_cells_in_queue,
2363 double mean_time_cells_in_queue, uint32_t processed_cells)
2365 circ_buffer_stats_t *stat;
2366 if (!start_of_buffer_stats_interval)
2367 return; /* Not initialized. */
2368 stat = tor_malloc_zero(sizeof(circ_buffer_stats_t));
2369 stat->mean_num_cells_in_queue = mean_num_cells_in_queue;
2370 stat->mean_time_cells_in_queue = mean_time_cells_in_queue;
2371 stat->processed_cells = processed_cells;
2372 if (!circuits_for_buffer_stats)
2373 circuits_for_buffer_stats = smartlist_create();
2374 smartlist_add(circuits_for_buffer_stats, stat);
2377 /** Remember cell statistics for circuit <b>circ</b> at time
2378 * <b>end_of_interval</b> and reset cell counters in case the circuit
2379 * remains open in the next measurement interval. */
2380 void
2381 rep_hist_buffer_stats_add_circ(circuit_t *circ, time_t end_of_interval)
2383 time_t start_of_interval;
2384 int interval_length;
2385 or_circuit_t *orcirc;
2386 double mean_num_cells_in_queue, mean_time_cells_in_queue;
2387 uint32_t processed_cells;
2388 if (CIRCUIT_IS_ORIGIN(circ))
2389 return;
2390 orcirc = TO_OR_CIRCUIT(circ);
2391 if (!orcirc->processed_cells)
2392 return;
2393 start_of_interval = (circ->timestamp_created.tv_sec >
2394 start_of_buffer_stats_interval) ?
2395 circ->timestamp_created.tv_sec :
2396 start_of_buffer_stats_interval;
2397 interval_length = (int) (end_of_interval - start_of_interval);
2398 if (interval_length <= 0)
2399 return;
2400 processed_cells = orcirc->processed_cells;
2401 /* 1000.0 for s -> ms; 2.0 because of app-ward and exit-ward queues */
2402 mean_num_cells_in_queue = (double) orcirc->total_cell_waiting_time /
2403 (double) interval_length / 1000.0 / 2.0;
2404 mean_time_cells_in_queue =
2405 (double) orcirc->total_cell_waiting_time /
2406 (double) orcirc->processed_cells;
2407 orcirc->total_cell_waiting_time = 0;
2408 orcirc->processed_cells = 0;
2409 rep_hist_add_buffer_stats(mean_num_cells_in_queue,
2410 mean_time_cells_in_queue,
2411 processed_cells);
2414 /** Sorting helper: return -1, 1, or 0 based on comparison of two
2415 * circ_buffer_stats_t */
2416 static int
2417 _buffer_stats_compare_entries(const void **_a, const void **_b)
2419 const circ_buffer_stats_t *a = *_a, *b = *_b;
2420 if (a->processed_cells < b->processed_cells)
2421 return 1;
2422 else if (a->processed_cells > b->processed_cells)
2423 return -1;
2424 else
2425 return 0;
2428 /** Stop collecting cell stats in a way that we can re-start doing so in
2429 * rep_hist_buffer_stats_init(). */
2430 void
2431 rep_hist_buffer_stats_term(void)
2433 rep_hist_reset_buffer_stats(0);
2436 /** Clear history of circuit statistics and set the measurement interval
2437 * start to <b>now</b>. */
2438 void
2439 rep_hist_reset_buffer_stats(time_t now)
2441 if (!circuits_for_buffer_stats)
2442 circuits_for_buffer_stats = smartlist_create();
2443 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *,
2444 stat, tor_free(stat));
2445 smartlist_clear(circuits_for_buffer_stats);
2446 start_of_buffer_stats_interval = now;
2449 /** Return a newly allocated string containing the buffer statistics until
2450 * <b>now</b>, or NULL if we're not collecting buffer stats. Caller must
2451 * ensure start_of_buffer_stats_interval is in the past. */
2452 char *
2453 rep_hist_format_buffer_stats(time_t now)
2455 #define SHARES 10
2456 int processed_cells[SHARES], circs_in_share[SHARES],
2457 number_of_circuits, i;
2458 double queued_cells[SHARES], time_in_queue[SHARES];
2459 smartlist_t *processed_cells_strings, *queued_cells_strings,
2460 *time_in_queue_strings;
2461 char *processed_cells_string, *queued_cells_string,
2462 *time_in_queue_string;
2463 char t[ISO_TIME_LEN+1];
2464 char *result;
2466 if (!start_of_buffer_stats_interval)
2467 return NULL; /* Not initialized. */
2469 tor_assert(now >= start_of_buffer_stats_interval);
2471 /* Calculate deciles if we saw at least one circuit. */
2472 memset(processed_cells, 0, SHARES * sizeof(int));
2473 memset(circs_in_share, 0, SHARES * sizeof(int));
2474 memset(queued_cells, 0, SHARES * sizeof(double));
2475 memset(time_in_queue, 0, SHARES * sizeof(double));
2476 if (!circuits_for_buffer_stats)
2477 circuits_for_buffer_stats = smartlist_create();
2478 number_of_circuits = smartlist_len(circuits_for_buffer_stats);
2479 if (number_of_circuits > 0) {
2480 smartlist_sort(circuits_for_buffer_stats,
2481 _buffer_stats_compare_entries);
2482 i = 0;
2483 SMARTLIST_FOREACH_BEGIN(circuits_for_buffer_stats,
2484 circ_buffer_stats_t *, stat)
2486 int share = i++ * SHARES / number_of_circuits;
2487 processed_cells[share] += stat->processed_cells;
2488 queued_cells[share] += stat->mean_num_cells_in_queue;
2489 time_in_queue[share] += stat->mean_time_cells_in_queue;
2490 circs_in_share[share]++;
2492 SMARTLIST_FOREACH_END(stat);
2495 /* Write deciles to strings. */
2496 processed_cells_strings = smartlist_create();
2497 queued_cells_strings = smartlist_create();
2498 time_in_queue_strings = smartlist_create();
2499 for (i = 0; i < SHARES; i++) {
2500 smartlist_add_asprintf(processed_cells_strings,
2501 "%d", !circs_in_share[i] ? 0 :
2502 processed_cells[i] / circs_in_share[i]);
2504 for (i = 0; i < SHARES; i++) {
2505 smartlist_add_asprintf(queued_cells_strings, "%.2f",
2506 circs_in_share[i] == 0 ? 0.0 :
2507 queued_cells[i] / (double) circs_in_share[i]);
2509 for (i = 0; i < SHARES; i++) {
2510 smartlist_add_asprintf(time_in_queue_strings, "%.0f",
2511 circs_in_share[i] == 0 ? 0.0 :
2512 time_in_queue[i] / (double) circs_in_share[i]);
2515 /* Join all observations in single strings. */
2516 processed_cells_string = smartlist_join_strings(processed_cells_strings,
2517 ",", 0, NULL);
2518 queued_cells_string = smartlist_join_strings(queued_cells_strings,
2519 ",", 0, NULL);
2520 time_in_queue_string = smartlist_join_strings(time_in_queue_strings,
2521 ",", 0, NULL);
2522 SMARTLIST_FOREACH(processed_cells_strings, char *, cp, tor_free(cp));
2523 SMARTLIST_FOREACH(queued_cells_strings, char *, cp, tor_free(cp));
2524 SMARTLIST_FOREACH(time_in_queue_strings, char *, cp, tor_free(cp));
2525 smartlist_free(processed_cells_strings);
2526 smartlist_free(queued_cells_strings);
2527 smartlist_free(time_in_queue_strings);
2529 /* Put everything together. */
2530 format_iso_time(t, now);
2531 tor_asprintf(&result, "cell-stats-end %s (%d s)\n"
2532 "cell-processed-cells %s\n"
2533 "cell-queued-cells %s\n"
2534 "cell-time-in-queue %s\n"
2535 "cell-circuits-per-decile %d\n",
2536 t, (unsigned) (now - start_of_buffer_stats_interval),
2537 processed_cells_string,
2538 queued_cells_string,
2539 time_in_queue_string,
2540 (number_of_circuits + SHARES - 1) / SHARES);
2541 tor_free(processed_cells_string);
2542 tor_free(queued_cells_string);
2543 tor_free(time_in_queue_string);
2544 return result;
2545 #undef SHARES
2548 /** If 24 hours have passed since the beginning of the current buffer
2549 * stats period, write buffer stats to $DATADIR/stats/buffer-stats
2550 * (possibly overwriting an existing file) and reset counters. Return
2551 * when we would next want to write buffer stats or 0 if we never want to
2552 * write. */
2553 time_t
2554 rep_hist_buffer_stats_write(time_t now)
2556 circuit_t *circ;
2557 char *statsdir = NULL, *filename = NULL, *str = NULL;
2559 if (!start_of_buffer_stats_interval)
2560 return 0; /* Not initialized. */
2561 if (start_of_buffer_stats_interval + WRITE_STATS_INTERVAL > now)
2562 goto done; /* Not ready to write */
2564 /* Add open circuits to the history. */
2565 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
2566 rep_hist_buffer_stats_add_circ(circ, now);
2569 /* Generate history string. */
2570 str = rep_hist_format_buffer_stats(now);
2572 /* Reset both buffer history and counters of open circuits. */
2573 rep_hist_reset_buffer_stats(now);
2575 /* Try to write to disk. */
2576 statsdir = get_datadir_fname("stats");
2577 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
2578 log_warn(LD_HIST, "Unable to create stats/ directory!");
2579 goto done;
2581 filename = get_datadir_fname2("stats", "buffer-stats");
2582 if (write_str_to_file(filename, str, 0) < 0)
2583 log_warn(LD_HIST, "Unable to write buffer stats to disk!");
2585 done:
2586 tor_free(str);
2587 tor_free(filename);
2588 tor_free(statsdir);
2589 return start_of_buffer_stats_interval + WRITE_STATS_INTERVAL;
2592 /*** Descriptor serving statistics ***/
2594 /** Digestmap to track which descriptors were downloaded this stats
2595 * collection interval. It maps descriptor digest to pointers to 1,
2596 * effectively turning this into a list. */
2597 static digestmap_t *served_descs = NULL;
2599 /** Number of how many descriptors were downloaded in total during this
2600 * interval. */
2601 static unsigned long total_descriptor_downloads;
2603 /** Start time of served descs stats or 0 if we're not collecting those. */
2604 static time_t start_of_served_descs_stats_interval;
2606 /** Initialize descriptor stats. */
2607 void
2608 rep_hist_desc_stats_init(time_t now)
2610 if (served_descs) {
2611 log_warn(LD_BUG, "Called rep_hist_desc_stats_init() when desc stats were "
2612 "already initialized. This is probably harmless.");
2613 return; // Already initialized
2615 served_descs = digestmap_new();
2616 total_descriptor_downloads = 0;
2617 start_of_served_descs_stats_interval = now;
2620 /** Reset served descs stats to empty, starting a new interval <b>now</b>. */
2621 static void
2622 rep_hist_reset_desc_stats(time_t now)
2624 rep_hist_desc_stats_term();
2625 rep_hist_desc_stats_init(now);
2628 /** Stop collecting served descs stats, so that rep_hist_desc_stats_init() is
2629 * safe to be called again. */
2630 void
2631 rep_hist_desc_stats_term(void)
2633 digestmap_free(served_descs, NULL);
2634 served_descs = NULL;
2635 start_of_served_descs_stats_interval = 0;
2636 total_descriptor_downloads = 0;
2639 /** Helper for rep_hist_desc_stats_write(). Return a newly allocated string
2640 * containing the served desc statistics until now, or NULL if we're not
2641 * collecting served desc stats. Caller must ensure that now is not before
2642 * start_of_served_descs_stats_interval. */
2643 static char *
2644 rep_hist_format_desc_stats(time_t now)
2646 char t[ISO_TIME_LEN+1];
2647 char *result;
2649 digestmap_iter_t *iter;
2650 const char *key;
2651 void *val;
2652 unsigned size;
2653 int *vals;
2654 int n = 0;
2656 if (!start_of_served_descs_stats_interval)
2657 return NULL;
2659 size = digestmap_size(served_descs);
2660 vals = tor_malloc(size * sizeof(int));
2662 for (iter = digestmap_iter_init(served_descs); !digestmap_iter_done(iter);
2663 iter = digestmap_iter_next(served_descs, iter) ) {
2664 uintptr_t count;
2665 digestmap_iter_get(iter, &key, &val);
2666 count = (uintptr_t)val;
2667 vals[n++] = (int)count;
2668 (void)key;
2671 format_iso_time(t, now);
2673 tor_asprintf(&result,
2674 "served-descs-stats-end %s (%d s) total=%lu unique=%u "
2675 "max=%d q3=%d md=%d q1=%d min=%d\n",
2677 (unsigned) (now - start_of_served_descs_stats_interval),
2678 total_descriptor_downloads,
2679 size,
2680 find_nth_int(vals, size, size-1),
2681 find_nth_int(vals, size, (3*size-1)/4),
2682 find_nth_int(vals, size, (size-1)/2),
2683 find_nth_int(vals, size, (size-1)/4),
2684 find_nth_int(vals, size, 0));
2686 tor_free(vals);
2687 return result;
2690 /** If WRITE_STATS_INTERVAL seconds have passed since the beginning of
2691 * the current served desc stats interval, write the stats to
2692 * $DATADIR/stats/served-desc-stats (possibly appending to an existing file)
2693 * and reset the state for the next interval. Return when we would next want
2694 * to write served desc stats or 0 if we won't want to write. */
2695 time_t
2696 rep_hist_desc_stats_write(time_t now)
2698 char *statsdir = NULL, *filename = NULL, *str = NULL;
2700 if (!start_of_served_descs_stats_interval)
2701 return 0; /* We're not collecting stats. */
2702 if (start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL > now)
2703 return start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL;
2705 str = rep_hist_format_desc_stats(now);
2707 statsdir = get_datadir_fname("stats");
2708 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
2709 log_warn(LD_HIST, "Unable to create stats/ directory!");
2710 goto done;
2712 filename = get_datadir_fname2("stats", "served-desc-stats");
2713 if (append_bytes_to_file(filename, str, strlen(str), 0) < 0)
2714 log_warn(LD_HIST, "Unable to write served descs statistics to disk!");
2716 rep_hist_reset_desc_stats(now);
2718 done:
2719 tor_free(statsdir);
2720 tor_free(filename);
2721 tor_free(str);
2722 return start_of_served_descs_stats_interval + WRITE_STATS_INTERVAL;
2725 void
2726 rep_hist_note_desc_served(const char * desc)
2728 void *val;
2729 uintptr_t count;
2730 if (!served_descs)
2731 return; // We're not collecting stats
2732 val = digestmap_get(served_descs, desc);
2733 count = (uintptr_t)val;
2734 if (count != INT_MAX)
2735 ++count;
2736 digestmap_set(served_descs, desc, (void*)count);
2737 total_descriptor_downloads++;
2740 /*** Connection statistics ***/
2742 /** Start of the current connection stats interval or 0 if we're not
2743 * collecting connection statistics. */
2744 static time_t start_of_conn_stats_interval;
2746 /** Initialize connection stats. */
2747 void
2748 rep_hist_conn_stats_init(time_t now)
2750 start_of_conn_stats_interval = now;
2753 /* Count connections that we read and wrote less than these many bytes
2754 * from/to as below threshold. */
2755 #define BIDI_THRESHOLD 20480
2757 /* Count connections that we read or wrote at least this factor as many
2758 * bytes from/to than we wrote or read to/from as mostly reading or
2759 * writing. */
2760 #define BIDI_FACTOR 10
2762 /* Interval length in seconds for considering read and written bytes for
2763 * connection stats. */
2764 #define BIDI_INTERVAL 10
2766 /* Start of next BIDI_INTERVAL second interval. */
2767 static time_t bidi_next_interval = 0;
2769 /* Number of connections that we read and wrote less than BIDI_THRESHOLD
2770 * bytes from/to in BIDI_INTERVAL seconds. */
2771 static uint32_t below_threshold = 0;
2773 /* Number of connections that we read at least BIDI_FACTOR times more
2774 * bytes from than we wrote to in BIDI_INTERVAL seconds. */
2775 static uint32_t mostly_read = 0;
2777 /* Number of connections that we wrote at least BIDI_FACTOR times more
2778 * bytes to than we read from in BIDI_INTERVAL seconds. */
2779 static uint32_t mostly_written = 0;
2781 /* Number of connections that we read and wrote at least BIDI_THRESHOLD
2782 * bytes from/to, but not BIDI_FACTOR times more in either direction in
2783 * BIDI_INTERVAL seconds. */
2784 static uint32_t both_read_and_written = 0;
2786 /* Entry in a map from connection ID to the number of read and written
2787 * bytes on this connection in a BIDI_INTERVAL second interval. */
2788 typedef struct bidi_map_entry_t {
2789 HT_ENTRY(bidi_map_entry_t) node;
2790 uint64_t conn_id; /**< Connection ID */
2791 size_t read; /**< Number of read bytes */
2792 size_t written; /**< Number of written bytes */
2793 } bidi_map_entry_t;
2795 /** Map of OR connections together with the number of read and written
2796 * bytes in the current BIDI_INTERVAL second interval. */
2797 static HT_HEAD(bidimap, bidi_map_entry_t) bidi_map =
2798 HT_INITIALIZER();
2800 static int
2801 bidi_map_ent_eq(const bidi_map_entry_t *a, const bidi_map_entry_t *b)
2803 return a->conn_id == b->conn_id;
2806 static unsigned
2807 bidi_map_ent_hash(const bidi_map_entry_t *entry)
2809 return (unsigned) entry->conn_id;
2812 HT_PROTOTYPE(bidimap, bidi_map_entry_t, node, bidi_map_ent_hash,
2813 bidi_map_ent_eq);
2814 HT_GENERATE(bidimap, bidi_map_entry_t, node, bidi_map_ent_hash,
2815 bidi_map_ent_eq, 0.6, malloc, realloc, free);
2817 static void
2818 bidi_map_free(void)
2820 bidi_map_entry_t **ptr, **next, *ent;
2821 for (ptr = HT_START(bidimap, &bidi_map); ptr; ptr = next) {
2822 ent = *ptr;
2823 next = HT_NEXT_RMV(bidimap, &bidi_map, ptr);
2824 tor_free(ent);
2826 HT_CLEAR(bidimap, &bidi_map);
2829 /** Reset counters for conn statistics. */
2830 void
2831 rep_hist_reset_conn_stats(time_t now)
2833 start_of_conn_stats_interval = now;
2834 below_threshold = 0;
2835 mostly_read = 0;
2836 mostly_written = 0;
2837 both_read_and_written = 0;
2838 bidi_map_free();
2841 /** Stop collecting connection stats in a way that we can re-start doing
2842 * so in rep_hist_conn_stats_init(). */
2843 void
2844 rep_hist_conn_stats_term(void)
2846 rep_hist_reset_conn_stats(0);
2849 /** We read <b>num_read</b> bytes and wrote <b>num_written</b> from/to OR
2850 * connection <b>conn_id</b> in second <b>when</b>. If this is the first
2851 * observation in a new interval, sum up the last observations. Add bytes
2852 * for this connection. */
2853 void
2854 rep_hist_note_or_conn_bytes(uint64_t conn_id, size_t num_read,
2855 size_t num_written, time_t when)
2857 if (!start_of_conn_stats_interval)
2858 return;
2859 /* Initialize */
2860 if (bidi_next_interval == 0)
2861 bidi_next_interval = when + BIDI_INTERVAL;
2862 /* Sum up last period's statistics */
2863 if (when >= bidi_next_interval) {
2864 bidi_map_entry_t **ptr, **next, *ent;
2865 for (ptr = HT_START(bidimap, &bidi_map); ptr; ptr = next) {
2866 ent = *ptr;
2867 if (ent->read + ent->written < BIDI_THRESHOLD)
2868 below_threshold++;
2869 else if (ent->read >= ent->written * BIDI_FACTOR)
2870 mostly_read++;
2871 else if (ent->written >= ent->read * BIDI_FACTOR)
2872 mostly_written++;
2873 else
2874 both_read_and_written++;
2875 next = HT_NEXT_RMV(bidimap, &bidi_map, ptr);
2876 tor_free(ent);
2878 while (when >= bidi_next_interval)
2879 bidi_next_interval += BIDI_INTERVAL;
2880 log_info(LD_GENERAL, "%d below threshold, %d mostly read, "
2881 "%d mostly written, %d both read and written.",
2882 below_threshold, mostly_read, mostly_written,
2883 both_read_and_written);
2885 /* Add this connection's bytes. */
2886 if (num_read > 0 || num_written > 0) {
2887 bidi_map_entry_t *entry, lookup;
2888 lookup.conn_id = conn_id;
2889 entry = HT_FIND(bidimap, &bidi_map, &lookup);
2890 if (entry) {
2891 entry->written += num_written;
2892 entry->read += num_read;
2893 } else {
2894 entry = tor_malloc_zero(sizeof(bidi_map_entry_t));
2895 entry->conn_id = conn_id;
2896 entry->written = num_written;
2897 entry->read = num_read;
2898 HT_INSERT(bidimap, &bidi_map, entry);
2903 /** Return a newly allocated string containing the connection statistics
2904 * until <b>now</b>, or NULL if we're not collecting conn stats. Caller must
2905 * ensure start_of_conn_stats_interval is in the past. */
2906 char *
2907 rep_hist_format_conn_stats(time_t now)
2909 char *result, written[ISO_TIME_LEN+1];
2911 if (!start_of_conn_stats_interval)
2912 return NULL; /* Not initialized. */
2914 tor_assert(now >= start_of_conn_stats_interval);
2916 format_iso_time(written, now);
2917 tor_asprintf(&result, "conn-bi-direct %s (%d s) %d,%d,%d,%d\n",
2918 written,
2919 (unsigned) (now - start_of_conn_stats_interval),
2920 below_threshold,
2921 mostly_read,
2922 mostly_written,
2923 both_read_and_written);
2924 return result;
2927 /** If 24 hours have passed since the beginning of the current conn stats
2928 * period, write conn stats to $DATADIR/stats/conn-stats (possibly
2929 * overwriting an existing file) and reset counters. Return when we would
2930 * next want to write conn stats or 0 if we never want to write. */
2931 time_t
2932 rep_hist_conn_stats_write(time_t now)
2934 char *statsdir = NULL, *filename = NULL, *str = NULL;
2936 if (!start_of_conn_stats_interval)
2937 return 0; /* Not initialized. */
2938 if (start_of_conn_stats_interval + WRITE_STATS_INTERVAL > now)
2939 goto done; /* Not ready to write */
2941 /* Generate history string. */
2942 str = rep_hist_format_conn_stats(now);
2944 /* Reset counters. */
2945 rep_hist_reset_conn_stats(now);
2947 /* Try to write to disk. */
2948 statsdir = get_datadir_fname("stats");
2949 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
2950 log_warn(LD_HIST, "Unable to create stats/ directory!");
2951 goto done;
2953 filename = get_datadir_fname2("stats", "conn-stats");
2954 if (write_str_to_file(filename, str, 0) < 0)
2955 log_warn(LD_HIST, "Unable to write conn stats to disk!");
2957 done:
2958 tor_free(str);
2959 tor_free(filename);
2960 tor_free(statsdir);
2961 return start_of_conn_stats_interval + WRITE_STATS_INTERVAL;
2964 /** Free all storage held by the OR/link history caches, by the
2965 * bandwidth history arrays, by the port history, or by statistics . */
2966 void
2967 rep_hist_free_all(void)
2969 digestmap_free(history_map, free_or_history);
2970 tor_free(read_array);
2971 tor_free(write_array);
2972 tor_free(last_stability_doc);
2973 tor_free(exit_bytes_read);
2974 tor_free(exit_bytes_written);
2975 tor_free(exit_streams);
2976 built_last_stability_doc_at = 0;
2977 predicted_ports_free();
2978 bidi_map_free();
2980 if (circuits_for_buffer_stats) {
2981 SMARTLIST_FOREACH(circuits_for_buffer_stats, circ_buffer_stats_t *, s,
2982 tor_free(s));
2983 smartlist_free(circuits_for_buffer_stats);
2984 circuits_for_buffer_stats = NULL;
2986 rep_hist_desc_stats_term();
2987 total_descriptor_downloads = 0;