1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
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.
14 #include "circuitlist.h"
15 #include "circuituse.h"
17 #include "networkstatus.h"
21 #include "routerlist.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? */
49 /** When did we most recently note a change to this link */
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
;
57 /** History of an OR. */
58 typedef struct or_history_t
{
59 /** When did we start tracking this OR? */
61 /** When did we most recently note a change to this OR? */
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
70 /** How many seconds have we been unable to connect to this OR before
72 unsigned long downtime
;
73 /** If nonzero, we have been connected since this time. */
75 /** If nonzero, we have been unable to connect since this time. */
78 /** The address at which we most recently connected to this OR
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? */
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
;
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;
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
)
121 if (tor_digest_is_zero(id
))
124 hist
= digestmap_get(history_map
, id
);
126 hist
= tor_malloc_zero(sizeof(or_history_t
));
127 rephist_total_alloc
+= sizeof(or_history_t
);
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
);
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
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
);
149 if (tor_digest_is_zero(to_id
))
151 lhist
= (link_history_t
*) digestmap_get(orhist
->link_history_map
, to_id
);
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
);
161 /** Helper: free storage held by a single link history entry. */
163 _free_link_history(void *val
)
165 rephist_total_alloc
-= sizeof(link_history_t
);
169 /** Helper: free storage held by a single OR history entry. */
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
);
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>.
184 update_or_history(or_history_t
*hist
, time_t when
)
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. */
201 history_map
= digestmap_new();
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. */
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
);
216 if (failed
&& !hist
->down_since
) {
217 hist
->down_since
= when
;
221 /** Helper: note that we are connected to the router with history
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>.
239 rep_hist_note_connect_failed(const char* id
, time_t when
)
242 hist
= get_or_history(id
);
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>.
254 rep_hist_note_connect_succeeded(const char* id
, time_t when
)
257 hist
= get_or_history(id
);
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>.
269 rep_hist_note_disconnect(const char* id
, time_t when
)
272 hist
= get_or_history(id
);
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>.
283 rep_hist_note_connection_died(const char* id
, time_t when
)
287 /* If conn has no identity, it didn't complete its handshake, or something
288 * went wrong. Ignore it.
292 hist
= get_or_history(id
);
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. */
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
);
307 char tbuf
[ISO_TIME_LEN
+1];
308 int addr_changed
, port_changed
;
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
;
323 if (hist
->start_of_downtime
) {
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
);
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
338 int penalty
= get_options()->TestingTorNetwork
? 240 : 3600;
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
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
);
357 format_local_iso_time(tbuf
, hist
->start_of_run
);
359 log_debug(LD_HIST
, "Router %s is still Running; it has been Running "
360 "since %s", hex_str(id
, DIGEST_LEN
), tbuf
);
362 log_info(LD_HIST
,"Router %s is now Running; it was previously untracked",
363 hex_str(id
, DIGEST_LEN
));
366 tor_addr_copy(&hist
->last_reached_addr
, at_addr
);
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. */
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];
379 if (!started_tracking_stability
)
380 started_tracking_stability
= time(NULL
);
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
);
399 hist
->weighted_run_length
+= run_length
;
400 hist
->weighted_uptime
+= run_length
;
401 hist
->total_weighted_time
+= run_length
;
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
;
413 log_info(LD_HIST
, "Router %s is now non-Running; it was previously "
414 "untracked.", hex_str(id
, DIGEST_LEN
));
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. */
428 rep_hist_downrate_old_runs(time_t now
)
430 digestmap_iter_t
*orhist_it
;
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",
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
);
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>. */
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. */
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. */
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
);
506 /** Helper: Return the weighted percent-of-time-online of the router with
507 * history <b>hist</b>. */
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
);
518 } else if (hist
->start_of_downtime
) {
519 total
+= (when
- hist
->start_of_downtime
);
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). */
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
536 rep_hist_get_uptime(const char *id
, time_t when
)
538 or_history_t
*hist
= get_or_history(id
);
541 if (!hist
->start_of_run
|| when
< hist
->start_of_run
)
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. */
549 rep_hist_get_stability(const char *id
, time_t when
)
551 or_history_t
*hist
= get_or_history(id
);
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. */
561 rep_hist_get_weighted_fractional_uptime(const char *id
, time_t when
)
563 or_history_t
*hist
= get_or_history(id
);
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.
577 rep_hist_get_weighted_time_known(const char *id
, time_t when
)
579 or_history_t
*hist
= get_or_history(id
);
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
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
);
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
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
);
624 ++hist
->n_extend_fail
;
625 hist
->changed
= time(NULL
);
628 /** Log all the reliability data we have remembered, with the chosen
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
;
646 unsigned long upt
, downt
;
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
)) {
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
);
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
);
672 uptime
= ((double)upt
) / (upt
+downt
);
676 log(severity
, LD_HIST
,
677 "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%); "
678 "wmtbf %lu:%02lu:%02lu",
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
,
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
);
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); ",
703 link_history
->n_extend_ok
,
704 link_history
->n_extend_ok
+link_history
->n_extend_fail
);
710 log(severity
, LD_HIST
, "%s", buffer
);
715 /** Remove history info for routers/links that haven't changed since
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
;
728 orhist_it
= digestmap_iter_init(history_map
);
729 while (!digestmap_iter_done(orhist_it
)) {
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
);
738 orhist_it
= digestmap_iter_next_rmv(history_map
, orhist_it
);
739 free_or_history(or_history
);
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
,
749 rephist_total_alloc
-= sizeof(link_history_t
);
750 tor_free(link_history
);
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
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
;
773 open_file_t
*open_file
= NULL
;
777 char *filename
= get_datadir_fname("router-stability");
778 f
= start_writing_to_stdio_file(filename
, OPEN_FLAGS_REPLACE
|O_TEXT
, 0600,
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
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
));
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. */
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
);
842 PRINTF((f
, "+MTBF %lu %.5lf%s%s\n",
843 hist
->weighted_run_length
, hist
->total_run_weights
,
844 t
? " S=" : "", t
? t
: ""));
846 if (hist
->start_of_downtime
> 0) {
847 format_iso_time(time_buf
, hist
->start_of_downtime
);
850 PRINTF((f
, "+WFU %lu %lu%s%s\n",
851 hist
->weighted_uptime
, hist
->total_weighted_time
,
852 t
? " S=" : "", t
? t
: ""));
860 return finish_writing_to_file(open_file
);
862 abort_writing_to_file(open_file
);
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. */
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];
875 int up
= 0, down
= 0;
878 if (hist
->start_of_run
) {
879 format_iso_time(sor_buf
, hist
->start_of_run
);
882 if (hist
->start_of_downtime
) {
883 format_iso_time(sod_buf
, hist
->start_of_downtime
);
887 wfu
= get_weighted_fractional_uptime(hist
, now
);
888 mtbf
= get_stability(hist
, now
);
893 " weighted-time %lu\n"
894 " weighted-uptime %lu\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":"",
901 hist
->total_weighted_time
,
902 hist
->weighted_uptime
,
904 hist
->weighted_run_length
,
905 hist
->total_run_weights
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. */
922 rep_hist_get_router_stability_doc(time_t now
)
926 if (built_last_stability_doc_at
+ MAX_STABILITY_DOC_BUILD_RATE
> now
)
927 return last_stability_doc
;
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"));
938 smartlist_add(chunks
, tor_strdup("we-do-not-have-enough-measurements\n"));
941 DIGESTMAP_FOREACH(history_map
, id
, or_history_t
*, hist
) {
943 char dbuf
[BASE64_DIGEST_LEN
+1];
945 digest_to_base64(dbuf
, id
);
946 node
= node_get_by_id(id
);
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
));
953 format_iso_time(tbuf
, published
);
955 strlcpy(tbuf
, "???", sizeof(tbuf
));
956 smartlist_add_asprintf(chunks
,
959 "relevant-flags %s%s%s\n"
960 "declared-uptime %ld\n",
961 dbuf
, node_get_nickname(node
), ip
,
963 node
->is_running
? "Running " : "",
964 node
->is_valid
? "Valid " : "",
965 node
->ri
&& node
->ri
->is_hibernating
? "Hibernating " : "",
966 node_get_declared_uptime(node
));
968 smartlist_add_asprintf(chunks
,
969 "router %s {no descriptor}\n", dbuf
);
971 info
= rep_hist_format_router_status(hist
, now
);
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
);
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. */
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
))
996 if (!strcmpstart(line
, "R "))
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. */
1007 parse_possibly_bad_iso_time(const char *s
, time_t *time_out
)
1011 strlcpy(b
, s
, sizeof(b
));
1013 year
= (int)tor_parse_long(b
, 10, 0, INT_MAX
, NULL
, NULL
);
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
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)
1032 else if (t
< started_measuring
)
1033 return started_measuring
;
1034 else if (t
> stored_at
)
1037 long run_length
= stored_at
- t
;
1038 t
= now
- run_length
;
1039 if (t
< started_measuring
)
1040 t
= started_measuring
;
1045 /** Load MTBF data from disk. Returns 0 on success or recoverable error, -1
1048 rep_hist_load_mtbf_data(time_t now
)
1050 /* XXXX won't handle being called while history is already populated. */
1052 const char *line
= NULL
;
1054 time_t last_downrated
= 0, stored_at
= 0, tracked_since
= 0;
1055 time_t latest_possible_start
= now
;
1059 char *filename
= get_datadir_fname("router-stability");
1060 char *d
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
1064 lines
= smartlist_create();
1065 smartlist_split_string(lines
, d
, "\n", SPLIT_SKIP_SPACE
, 0);
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) {
1080 "Unrecognized format in mtbf history file. Skipping.");
1083 for (i
= 1; i
< smartlist_len(lines
); ++i
) {
1084 line
= smartlist_get(lines
, i
);
1085 if (!strcmp(line
, "data"))
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 "
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 "
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 "
1103 if (last_downrated
> now
)
1104 last_downrated
= now
;
1105 if (tracked_since
> now
)
1106 tracked_since
= now
;
1109 log_warn(LD_HIST
, "No stored time recorded.");
1113 if (line
&& !strcmp(line
, "data"))
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;
1128 long wt_uptime
= 0, total_wt_time
= 0;
1131 line
= smartlist_get(lines
, i
);
1132 if (!strcmp(line
, "."))
1135 mtbf_timebuf
[0] = '\0';
1136 wfu_timebuf
[0] = '\0';
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
));
1148 int mtbf_idx
, wfu_idx
;
1149 if (strcmpstart(line
, "R ") || strlen(line
) < 2+HEX_DIGEST_LEN
)
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) {
1161 log_warn(LD_HIST
, "Couldn't scan +MTBF line %s",
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) {
1173 log_warn(LD_HIST
, "Couldn't scan +WFU line %s", escaped(wfuline
));
1181 if (base16_decode(digest
, DIGEST_LEN
, hexbuf
, HEX_DIGEST_LEN
) < 0) {
1182 log_warn(LD_HIST
, "Couldn't hex string %s", escaped(hexbuf
));
1185 hist
= get_or_history(digest
);
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
,
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
;
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
,
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
;
1229 SMARTLIST_FOREACH(lines
, char *, cp
, tor_free(cp
));
1230 smartlist_free(lines
);
1234 /** For how many seconds do we keep track of individual per-second bandwidth
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
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
1262 /** When does the next period begin? */
1264 /** Where in 'maxima' should the maximum bandwidth usage for the current
1265 * period be stored? */
1267 /** How many values in maxima/totals have been set ever? */
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
1275 uint64_t totals
[NUM_TOTALS
];
1278 /** Shift the current period of b forward by one. */
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
)
1292 /* Reset max_total. */
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. */
1300 advance_obs(bw_array_t
*b
)
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
)
1315 b
->total_obs
= total
- b
->obs
[nextidx
];
1317 b
->cur_obs_idx
= nextidx
;
1319 if (++b
->cur_obs_time
>= b
->next_period
)
1323 /** Add <b>n</b> bytes to the number of bytes in <b>b</b> for second
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. */
1341 b
->obs
[b
->cur_obs_idx
] += n
;
1342 b
->total_in_period
+= n
;
1345 /** Allocate, initialize, and return a new bw_array. */
1351 b
= tor_malloc_zero(sizeof(bw_array_t
));
1352 rephist_total_alloc
+= sizeof(bw_array_t
);
1354 b
->cur_obs_time
= start
;
1355 b
->next_period
= start
+ NUM_SECS_BW_SUM_INTERVAL
;
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
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.
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)
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)
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)
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.)
1439 find_largest_max(bw_array_t
*b
)
1444 for (i
=0; i
<NUM_TOTALS
; ++i
) {
1445 if (b
->maxima
[i
]>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)
1461 r
= find_largest_max(read_array
);
1462 w
= find_largest_max(write_array
);
1464 return (int)(U64_TO_DBL(w
)/NUM_SECS_ROLLING_MEASURE
);
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.
1476 rep_hist_fill_bandwidth_history(char *buf
, size_t len
, const bw_array_t
*b
)
1480 const or_options_t
*options
= get_options();
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.*/
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
;
1498 cutoff
= UINT64_MAX
;
1501 for (n
=0; n
<b
->num_maxes_set
; ++n
,++i
) {
1503 if (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;
1511 if (n
==(b
->num_maxes_set
-1))
1512 tor_snprintf(cp
, len
-(cp
-buf
), U64_FORMAT
, U64_PRINTF_ARG(total
));
1514 tor_snprintf(cp
, len
-(cp
-buf
), U64_FORMAT
",", U64_PRINTF_ARG(total
));
1520 /** Allocate and return lines for representing this server's bandwidth
1521 * history in its descriptor. We publish these lines in our extra-info
1525 rep_hist_get_bandwidth_lines(void)
1528 char t
[ISO_TIME_LEN
+1];
1530 bw_array_t
*b
= NULL
;
1531 const char *desc
= NULL
;
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
);
1542 char tmp
[MAX_HIST_VALUE_LEN
];
1547 desc
= "write-history";
1551 desc
= "read-history";
1554 b
= dir_write_array
;
1555 desc
= "dirreq-write-history";
1559 desc
= "dirreq-read-history";
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. */
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
);
1571 strlcat(cp
, tmp
, len
-(cp
-buf
));
1573 strlcat(cp
, "\n", len
-(cp
-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. */
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
,
1593 SMARTLIST_FOREACH(*s_values
, char *, val
, tor_free(val
));
1594 smartlist_free(*s_values
);
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
);
1612 *s_values
= smartlist_create();
1613 *s_maxima
= smartlist_create();
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
)
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. */
1642 rep_hist_update_state(or_state_t
*state
)
1644 #define UPDATE(arrname,st) \
1645 rep_hist_update_bwhist_state_section(state,\
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));
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. */
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
);
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
));
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
);
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
;
1694 /* No maxima known; guess average rate to be conservative. */
1695 mv
= (v
/ s_interval
) * NUM_SECS_ROLLING_MEASURE
;
1699 log_notice(LD_HIST
, "Could not parse value '%s' into a number.'",cp
);
1701 if (maxstr
&& !ok_m
) {
1703 log_notice(LD_HIST
, "Could not parse maximum '%s' into a number.'",
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
);
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
) {
1739 /** Set bandwidth history from the state file we just loaded. */
1741 rep_hist_load_state(or_state_t
*state
, char **err
)
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( \
1752 state->BWHistory ## st ## Values, \
1753 state->BWHistory ## st ## Maxima, \
1754 state->BWHistory ## st ## Ends, \
1755 state->BWHistory ## st ## Interval)<0) \
1758 LOAD(write_array
, Write
);
1759 LOAD(read_array
, Read
);
1760 LOAD(dir_write_array
, DirWrite
);
1761 LOAD(dir_read_array
, DirRead
);
1765 *err
= tor_strdup("Parsing of bandwidth history values failed");
1766 /* and create fresh arrays */
1773 /*********************************************************************/
1775 typedef struct 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.
1788 add_predicted_port(time_t now
, uint16_t port
)
1790 predicted_port_t
*pp
= tor_malloc(sizeof(predicted_port_t
));
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.
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
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
*,
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.
1826 rep_hist_note_used_port(time_t now
, uint16_t port
)
1828 tor_assert(predicted_ports_list
);
1830 if (!port
) /* record nothing */
1833 SMARTLIST_FOREACH_BEGIN(predicted_ports_list
, predicted_port_t
*, pp
) {
1834 if (pp
->port
== port
) {
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.
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
);
1863 SMARTLIST_DEL_CURRENT(predicted_ports_list
, pp
);
1865 smartlist_add(out
, tor_memdup(&pp
->port
, sizeof(uint16_t)));
1867 } SMARTLIST_FOREACH_END(pp
);
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.
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>. */
1891 rep_hist_note_used_internal(time_t now
, int need_uptime
, int need_capacity
)
1893 predicted_internal_time
= now
;
1895 predicted_internal_uptime_time
= now
;
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
,
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
)
1914 // Always predict that we need capacity.
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
))
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()))
1939 if (!check_whether_dirport_reachable())
1945 /** Structure to track how many times we've done each public key operation. */
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>. */
1973 note_crypto_pk_op(pk_op_t operation
)
1978 pk_op_counts
.n_signed_dir_objs
++;
1981 pk_op_counts
.n_signed_routerdescs
++;
1984 pk_op_counts
.n_verified_dir_objs
++;
1987 pk_op_counts
.n_verified_routerdescs
++;
1990 pk_op_counts
.n_onionskins_encrypted
++;
1993 pk_op_counts
.n_onionskins_decrypted
++;
1995 case TLS_HANDSHAKE_C
:
1996 pk_op_counts
.n_tls_client_handshakes
++;
1998 case TLS_HANDSHAKE_S
:
1999 pk_op_counts
.n_tls_server_handshakes
++;
2002 pk_op_counts
.n_rend_client_ops
++;
2005 pk_op_counts
.n_rend_mid_ops
++;
2008 pk_op_counts
.n_rend_server_ops
++;
2011 log_warn(LD_BUG
, "Unknown pk operation %d", operation
);
2015 /** Log the number of times we've done each public/private-key operation. */
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. */
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
*
2077 exit_bytes_written
= tor_malloc_zero(EXIT_STATS_NUM_PORTS
*
2079 exit_streams
= tor_malloc_zero(EXIT_STATS_NUM_PORTS
*
2083 /** Reset counters for exit port statistics. */
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(). */
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
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. */
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];
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
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,
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) {
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
;
2179 for (j
= 1; j
< top_elements
; j
++) {
2180 if (top_bytes
[j
] < top_bytes
[cur_min_idx
]) {
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
);
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
);
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
);
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
),
2261 tor_free(written_string
);
2262 tor_free(read_string
);
2263 tor_free(streams_string
);
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. */
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!");
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!");
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>. */
2309 rep_hist_note_exit_bytes(uint16_t port
, size_t num_written
,
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>. */
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. */
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
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. */
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
))
2390 orcirc
= TO_OR_CIRCUIT(circ
);
2391 if (!orcirc
->processed_cells
)
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)
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
,
2414 /** Sorting helper: return -1, 1, or 0 based on comparison of two
2415 * circ_buffer_stats_t */
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
)
2422 else if (a
->processed_cells
> b
->processed_cells
)
2428 /** Stop collecting cell stats in a way that we can re-start doing so in
2429 * rep_hist_buffer_stats_init(). */
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>. */
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. */
2453 rep_hist_format_buffer_stats(time_t now
)
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];
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
);
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
,
2518 queued_cells_string
= smartlist_join_strings(queued_cells_strings
,
2520 time_in_queue_string
= smartlist_join_strings(time_in_queue_strings
,
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
);
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
2554 rep_hist_buffer_stats_write(time_t now
)
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!");
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!");
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
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. */
2608 rep_hist_desc_stats_init(time_t now
)
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>. */
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. */
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. */
2644 rep_hist_format_desc_stats(time_t now
)
2646 char t
[ISO_TIME_LEN
+1];
2649 digestmap_iter_t
*iter
;
2656 if (!start_of_served_descs_stats_interval
)
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
) ) {
2665 digestmap_iter_get(iter
, &key
, &val
);
2666 count
= (uintptr_t)val
;
2667 vals
[n
++] = (int)count
;
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
,
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));
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. */
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!");
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
);
2722 return start_of_served_descs_stats_interval
+ WRITE_STATS_INTERVAL
;
2726 rep_hist_note_desc_served(const char * desc
)
2731 return; // We're not collecting stats
2732 val
= digestmap_get(served_descs
, desc
);
2733 count
= (uintptr_t)val
;
2734 if (count
!= INT_MAX
)
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. */
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
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 */
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
=
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
;
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
,
2814 HT_GENERATE(bidimap
, bidi_map_entry_t
, node
, bidi_map_ent_hash
,
2815 bidi_map_ent_eq
, 0.6, malloc
, realloc
, free
);
2820 bidi_map_entry_t
**ptr
, **next
, *ent
;
2821 for (ptr
= HT_START(bidimap
, &bidi_map
); ptr
; ptr
= next
) {
2823 next
= HT_NEXT_RMV(bidimap
, &bidi_map
, ptr
);
2826 HT_CLEAR(bidimap
, &bidi_map
);
2829 /** Reset counters for conn statistics. */
2831 rep_hist_reset_conn_stats(time_t now
)
2833 start_of_conn_stats_interval
= now
;
2834 below_threshold
= 0;
2837 both_read_and_written
= 0;
2841 /** Stop collecting connection stats in a way that we can re-start doing
2842 * so in rep_hist_conn_stats_init(). */
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. */
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
)
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
) {
2867 if (ent
->read
+ ent
->written
< BIDI_THRESHOLD
)
2869 else if (ent
->read
>= ent
->written
* BIDI_FACTOR
)
2871 else if (ent
->written
>= ent
->read
* BIDI_FACTOR
)
2874 both_read_and_written
++;
2875 next
= HT_NEXT_RMV(bidimap
, &bidi_map
, ptr
);
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
);
2891 entry
->written
+= num_written
;
2892 entry
->read
+= num_read
;
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. */
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",
2919 (unsigned) (now
- start_of_conn_stats_interval
),
2923 both_read_and_written
);
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. */
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!");
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!");
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 . */
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();
2980 if (circuits_for_buffer_stats
) {
2981 SMARTLIST_FOREACH(circuits_for_buffer_stats
, circ_buffer_stats_t
*, 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;