1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2010, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief Functions to close listeners, stop allowing new circuits,
8 * etc in preparation for closing down or going dormant; and to track
9 * bandwidth and time intervals to know when to hibernate and when to
15 - send destroy in response to create cells
16 - send end (policy failed) in response to begin cells
17 - close an OR conn when it has no circuits
20 (entered when bandwidth hard limit reached)
21 - close all OR/AP/exit conns)
26 #include "connection.h"
27 #include "connection_edge.h"
28 #include "hibernate.h"
32 /** Possible values of hibernate_state */
34 /** We are running normally. */
35 HIBERNATE_STATE_LIVE
=1,
36 /** We're trying to shut down cleanly, and we'll kill all active connections
37 * at shutdown_time. */
38 HIBERNATE_STATE_EXITING
=2,
39 /** We're running low on allocated bandwidth for this period, so we won't
40 * accept any new connections. */
41 HIBERNATE_STATE_LOWBANDWIDTH
=3,
42 /** We are hibernating, and we won't wake up till there's more bandwidth to
44 HIBERNATE_STATE_DORMANT
=4
47 extern long stats_n_seconds_working
; /* published uptime */
49 /** Are we currently awake, asleep, running out of bandwidth, or shutting
51 static hibernate_state_t hibernate_state
= HIBERNATE_STATE_LIVE
;
52 /** If are hibernating, when do we plan to wake up? Set to 0 if we
53 * aren't hibernating. */
54 static time_t hibernate_end_time
= 0;
55 /** If we are shutting down, when do we plan finally exit? Set to 0 if
56 * we aren't shutting down. */
57 static time_t shutdown_time
= 0;
59 /** Possible accounting periods. */
61 UNIT_MONTH
=1, UNIT_WEEK
=2, UNIT_DAY
=3,
64 /* Fields for accounting logic. Accounting overview:
66 * Accounting is designed to ensure that no more than N bytes are sent in
67 * either direction over a given interval (currently, one month, one week, or
69 * try to do this by choking our bandwidth to a trickle, but that
70 * would make our streams useless. Instead, we estimate what our
71 * bandwidth usage will be, and guess how long we'll be able to
72 * provide that much bandwidth before hitting our limit. We then
73 * choose a random time within the accounting interval to come up (so
74 * that we don't get 50 Tors running on the 1st of the month and none
77 * Each interval runs as follows:
79 * 1. We guess our bandwidth usage, based on how much we used
80 * last time. We choose a "wakeup time" within the interval to come up.
81 * 2. Until the chosen wakeup time, we hibernate.
82 * 3. We come up at the wakeup time, and provide bandwidth until we are
83 * "very close" to running out.
84 * 4. Then we go into low-bandwidth mode, and stop accepting new
85 * connections, but provide bandwidth until we run out.
86 * 5. Then we hibernate until the end of the interval.
88 * If the interval ends before we run out of bandwidth, we go back to
92 /** How many bytes have we read in this accounting interval? */
93 static uint64_t n_bytes_read_in_interval
= 0;
94 /** How many bytes have we written in this accounting interval? */
95 static uint64_t n_bytes_written_in_interval
= 0;
96 /** How many seconds have we been running this interval? */
97 static uint32_t n_seconds_active_in_interval
= 0;
98 /** How many seconds were we active in this interval before we hit our soft
100 static int n_seconds_to_hit_soft_limit
= 0;
101 /** When in this interval was the soft limit hit. */
102 static time_t soft_limit_hit_at
= 0;
103 /** How many bytes had we read/written when we hit the soft limit? */
104 static uint64_t n_bytes_at_soft_limit
= 0;
105 /** When did this accounting interval start? */
106 static time_t interval_start_time
= 0;
107 /** When will this accounting interval end? */
108 static time_t interval_end_time
= 0;
109 /** How far into the accounting interval should we hibernate? */
110 static time_t interval_wakeup_time
= 0;
111 /** How much bandwidth do we 'expect' to use per minute? (0 if we have no
112 * info from the last period.) */
113 static uint64_t expected_bandwidth_usage
= 0;
114 /** What unit are we using for our accounting? */
115 static time_unit_t cfg_unit
= UNIT_MONTH
;
117 /** How many days,hours,minutes into each unit does our accounting interval
119 static int cfg_start_day
= 0,
123 static void reset_accounting(time_t now
);
124 static int read_bandwidth_usage(void);
125 static time_t start_of_accounting_period_after(time_t now
);
126 static time_t start_of_accounting_period_containing(time_t now
);
127 static void accounting_set_wakeup_time(void);
130 * Functions for bandwidth accounting.
133 /** Configure accounting start/end time settings based on
134 * options->AccountingStart. Return 0 on success, -1 on failure. If
135 * <b>validate_only</b> is true, do not change the current settings. */
137 accounting_parse_options(or_options_t
*options
, int validate_only
)
143 const char *v
= options
->AccountingStart
;
148 if (!validate_only
) {
149 cfg_unit
= UNIT_MONTH
;
157 items
= smartlist_create();
158 smartlist_split_string(items
, v
, NULL
,
159 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
,0);
160 if (smartlist_len(items
)<2) {
161 log_warn(LD_CONFIG
, "Too few arguments to AccountingStart");
164 s
= smartlist_get(items
,0);
165 if (0==strcasecmp(s
, "month")) {
167 } else if (0==strcasecmp(s
, "week")) {
169 } else if (0==strcasecmp(s
, "day")) {
173 "Unrecognized accounting unit '%s': only 'month', 'week',"
174 " and 'day' are supported.", s
);
180 d
= tor_parse_long(smartlist_get(items
,1), 10, 1, 7, &ok
, NULL
);
182 log_warn(LD_CONFIG
, "Weekly accounting must begin on a day between "
183 "1 (Monday) and 7 (Sunday)");
188 d
= tor_parse_long(smartlist_get(items
,1), 10, 1, 28, &ok
, NULL
);
190 log_warn(LD_CONFIG
, "Monthly accounting must begin on a day between "
198 /* Coverity dislikes unreachable default cases; some compilers warn on
199 * switch statements missing a case. Tell Coverity not to worry. */
200 /* coverity[dead_error_begin] */
205 idx
= unit
==UNIT_DAY
?1:2;
206 if (smartlist_len(items
) != (idx
+1)) {
207 log_warn(LD_CONFIG
,"Accounting unit '%s' requires %d argument%s.",
208 s
, idx
, (idx
>1)?"s":"");
211 s
= smartlist_get(items
, idx
);
212 h
= tor_parse_long(s
, 10, 0, 23, &ok
, &cp
);
214 log_warn(LD_CONFIG
,"Accounting start time not parseable: bad hour.");
217 if (!cp
|| *cp
!=':') {
219 "Accounting start time not parseable: not in HH:MM format");
222 m
= tor_parse_long(cp
+1, 10, 0, 59, &ok
, &cp
);
224 log_warn(LD_CONFIG
, "Accounting start time not parseable: bad minute");
227 if (!cp
|| *cp
!='\0') {
229 "Accounting start time not parseable: not in HH:MM format");
233 if (!validate_only
) {
235 cfg_start_day
= (int)d
;
236 cfg_start_hour
= (int)h
;
237 cfg_start_min
= (int)m
;
239 SMARTLIST_FOREACH(items
, char *, item
, tor_free(item
));
240 smartlist_free(items
);
243 SMARTLIST_FOREACH(items
, char *, item
, tor_free(item
));
244 smartlist_free(items
);
248 /** If we want to manage the accounting system and potentially
249 * hibernate, return 1, else return 0.
252 accounting_is_enabled(or_options_t
*options
)
254 if (options
->AccountingMax
)
259 /** Called from main.c to tell us that <b>seconds</b> seconds have
260 * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
261 * bytes have been written. */
263 accounting_add_bytes(size_t n_read
, size_t n_written
, int seconds
)
265 n_bytes_read_in_interval
+= n_read
;
266 n_bytes_written_in_interval
+= n_written
;
267 /* If we haven't been called in 10 seconds, we're probably jumping
269 n_seconds_active_in_interval
+= (seconds
< 10) ? seconds
: 0;
272 /** If get_end, return the end of the accounting period that contains
273 * the time <b>now</b>. Else, return the start of the accounting
274 * period that contains the time <b>now</b> */
276 edge_of_accounting_period_containing(time_t now
, int get_end
)
280 tor_localtime_r(&now
, &tm
);
282 /* Set 'before' to true iff the current time is before the hh:mm
283 * changeover time for today. */
284 before
= tm
.tm_hour
< cfg_start_hour
||
285 (tm
.tm_hour
== cfg_start_hour
&& tm
.tm_min
< cfg_start_min
);
287 /* Dispatch by unit. First, find the start day of the given period;
288 * then, if get_end is true, increment to the end day. */
292 /* If this is before the Nth, we want the Nth of last month. */
293 if (tm
.tm_mday
< cfg_start_day
||
294 (tm
.tm_mday
< cfg_start_day
&& before
)) {
297 /* Otherwise, the month is correct. */
298 tm
.tm_mday
= cfg_start_day
;
304 /* What is the 'target' day of the week in struct tm format? (We
305 say Sunday==7; struct tm says Sunday==0.) */
306 int wday
= cfg_start_day
% 7;
307 /* How many days do we subtract from today to get to the right day? */
308 int delta
= (7+tm
.tm_wday
-wday
)%7;
309 /* If we are on the right day, but the changeover hasn't happened yet,
310 * then subtract a whole week. */
311 if (delta
== 0 && before
)
328 tm
.tm_hour
= cfg_start_hour
;
329 tm
.tm_min
= cfg_start_min
;
331 tm
.tm_isdst
= -1; /* Autodetect DST */
335 /** Return the start of the accounting period containing the time
338 start_of_accounting_period_containing(time_t now
)
340 return edge_of_accounting_period_containing(now
, 0);
343 /** Return the start of the accounting period that comes after the one
344 * containing the time <b>now</b>. */
346 start_of_accounting_period_after(time_t now
)
348 return edge_of_accounting_period_containing(now
, 1);
351 /** Return the length of the accounting period containing the time
354 length_of_accounting_period_containing(time_t now
)
356 return edge_of_accounting_period_containing(now
, 1) -
357 edge_of_accounting_period_containing(now
, 0);
360 /** Initialize the accounting subsystem. */
362 configure_accounting(time_t now
)
365 /* Try to remember our recorded usage. */
366 if (!interval_start_time
)
367 read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
370 s_now
= start_of_accounting_period_containing(now
);
372 if (!interval_start_time
) {
373 /* We didn't have recorded usage; Start a new interval. */
374 log_info(LD_ACCT
, "Starting new accounting interval.");
375 reset_accounting(now
);
376 } else if (s_now
== interval_start_time
) {
377 log_info(LD_ACCT
, "Continuing accounting interval.");
378 /* We are in the interval we thought we were in. Do nothing.*/
379 interval_end_time
= start_of_accounting_period_after(interval_start_time
);
381 long duration
= length_of_accounting_period_containing(now
);
382 double delta
= ((double)(s_now
- interval_start_time
)) / duration
;
383 if (-0.50 <= delta
&& delta
<= 0.50) {
384 /* The start of the period is now a little later or earlier than we
385 * remembered. That's fine; we might lose some bytes we could otherwise
386 * have written, but better to err on the side of obeying people's
387 * accounting settings. */
388 log_info(LD_ACCT
, "Accounting interval moved by %.02f%%; "
389 "that's fine.", delta
*100);
390 interval_end_time
= start_of_accounting_period_after(now
);
391 } else if (delta
>= 0.99) {
392 /* This is the regular time-moved-forward case; don't be too noisy
393 * about it or people will complain */
394 log_info(LD_ACCT
, "Accounting interval elapsed; starting a new one");
395 reset_accounting(now
);
398 "Mismatched accounting interval: moved by %.02f%%. "
399 "Starting a fresh one.", delta
*100);
400 reset_accounting(now
);
403 accounting_set_wakeup_time();
406 /** Set expected_bandwidth_usage based on how much we sent/received
407 * per minute last interval (if we were up for at least 30 minutes),
408 * or based on our declared bandwidth otherwise. */
410 update_expected_bandwidth(void)
413 or_options_t
*options
= get_options();
414 uint64_t max_configured
= (options
->RelayBandwidthRate
> 0 ?
415 options
->RelayBandwidthRate
:
416 options
->BandwidthRate
) * 60;
418 #define MIN_TIME_FOR_MEASUREMENT (1800)
420 if (soft_limit_hit_at
> interval_start_time
&& n_bytes_at_soft_limit
&&
421 (soft_limit_hit_at
- interval_start_time
) > MIN_TIME_FOR_MEASUREMENT
) {
422 /* If we hit our soft limit last time, only count the bytes up to that
423 * time. This is a better predictor of our actual bandwidth than
424 * considering the entirety of the last interval, since we likely started
425 * using bytes very slowly once we hit our soft limit. */
426 expected
= n_bytes_at_soft_limit
/
427 (soft_limit_hit_at
- interval_start_time
);
429 } else if (n_seconds_active_in_interval
>= MIN_TIME_FOR_MEASUREMENT
) {
430 /* Otherwise, we either measured enough time in the last interval but
431 * never hit our soft limit, or we're using a state file from a Tor that
432 * doesn't know to store soft-limit info. Just take rate at which
433 * we were reading/writing in the last interval as our expected rate.
435 uint64_t used
= MAX(n_bytes_written_in_interval
,
436 n_bytes_read_in_interval
);
437 expected
= used
/ (n_seconds_active_in_interval
/ 60);
439 /* If we haven't gotten enough data last interval, set 'expected'
440 * to 0. This will set our wakeup to the start of the interval.
441 * Next interval, we'll choose our starting time based on how much
442 * we sent this interval.
446 if (expected
> max_configured
)
447 expected
= max_configured
;
448 expected_bandwidth_usage
= expected
;
451 /** Called at the start of a new accounting interval: reset our
452 * expected bandwidth usage based on what happened last time, set up
453 * the start and end of the interval, and clear byte/time totals.
456 reset_accounting(time_t now
)
458 log_info(LD_ACCT
, "Starting new accounting interval.");
459 update_expected_bandwidth();
460 interval_start_time
= start_of_accounting_period_containing(now
);
461 interval_end_time
= start_of_accounting_period_after(interval_start_time
);
462 n_bytes_read_in_interval
= 0;
463 n_bytes_written_in_interval
= 0;
464 n_seconds_active_in_interval
= 0;
465 n_bytes_at_soft_limit
= 0;
466 soft_limit_hit_at
= 0;
467 n_seconds_to_hit_soft_limit
= 0;
470 /** Return true iff we should save our bandwidth usage to disk. */
472 time_to_record_bandwidth_usage(time_t now
)
474 /* Note every 600 sec */
475 #define NOTE_INTERVAL (600)
476 /* Or every 20 megabytes */
477 #define NOTE_BYTES 20*(1024*1024)
478 static uint64_t last_read_bytes_noted
= 0;
479 static uint64_t last_written_bytes_noted
= 0;
480 static time_t last_time_noted
= 0;
482 if (last_time_noted
+ NOTE_INTERVAL
<= now
||
483 last_read_bytes_noted
+ NOTE_BYTES
<= n_bytes_read_in_interval
||
484 last_written_bytes_noted
+ NOTE_BYTES
<= n_bytes_written_in_interval
||
485 (interval_end_time
&& interval_end_time
<= now
)) {
486 last_time_noted
= now
;
487 last_read_bytes_noted
= n_bytes_read_in_interval
;
488 last_written_bytes_noted
= n_bytes_written_in_interval
;
494 /** Invoked once per second. Checks whether it is time to hibernate,
495 * record bandwidth used, etc. */
497 accounting_run_housekeeping(time_t now
)
499 if (now
>= interval_end_time
) {
500 configure_accounting(now
);
502 if (time_to_record_bandwidth_usage(now
)) {
503 if (accounting_record_bandwidth_usage(now
, get_or_state())) {
504 log_warn(LD_FS
, "Couldn't record bandwidth usage to disk.");
509 /** When we have no idea how fast we are, how long do we assume it will take
510 * us to exhaust our bandwidth? */
511 #define GUESS_TIME_TO_USE_BANDWIDTH (24*60*60)
513 /** Based on our interval and our estimated bandwidth, choose a
514 * deterministic (but random-ish) time to wake up. */
516 accounting_set_wakeup_time(void)
518 char buf
[ISO_TIME_LEN
+1];
519 char digest
[DIGEST_LEN
];
520 crypto_digest_env_t
*d_env
;
521 int time_in_interval
;
522 uint64_t time_to_exhaust_bw
;
523 int time_to_consider
;
525 if (! identity_key_is_set()) {
526 if (init_keys() < 0) {
527 log_err(LD_BUG
, "Error initializing keys");
532 format_iso_time(buf
, interval_start_time
);
533 crypto_pk_get_digest(get_identity_key(), digest
);
535 d_env
= crypto_new_digest_env();
536 crypto_digest_add_bytes(d_env
, buf
, ISO_TIME_LEN
);
537 crypto_digest_add_bytes(d_env
, digest
, DIGEST_LEN
);
538 crypto_digest_get_digest(d_env
, digest
, DIGEST_LEN
);
539 crypto_free_digest_env(d_env
);
541 if (!expected_bandwidth_usage
) {
542 char buf1
[ISO_TIME_LEN
+1];
543 char buf2
[ISO_TIME_LEN
+1];
544 format_local_iso_time(buf1
, interval_start_time
);
545 format_local_iso_time(buf2
, interval_end_time
);
546 time_to_exhaust_bw
= GUESS_TIME_TO_USE_BANDWIDTH
;
547 interval_wakeup_time
= interval_start_time
;
550 "Configured hibernation. This interval begins at %s "
551 "and ends at %s. We have no prior estimate for bandwidth, so "
552 "we will start out awake and hibernate when we exhaust our quota.",
557 time_in_interval
= (int)(interval_end_time
- interval_start_time
);
560 (get_options()->AccountingMax
/expected_bandwidth_usage
)*60;
561 if (time_to_exhaust_bw
> TIME_MAX
) {
562 time_to_exhaust_bw
= TIME_MAX
;
563 time_to_consider
= 0;
565 time_to_consider
= time_in_interval
- (int)time_to_exhaust_bw
;
568 if (time_to_consider
<=0) {
569 interval_wakeup_time
= interval_start_time
;
571 /* XXX can we simplify this just by picking a random (non-deterministic)
572 * time to be up? If we go down and come up, then we pick a new one. Is
573 * that good enough? -RD */
575 /* This is not a perfectly unbiased conversion, but it is good enough:
576 * in the worst case, the first half of the day is 0.06 percent likelier
577 * to be chosen than the last half. */
578 interval_wakeup_time
= interval_start_time
+
579 (get_uint32(digest
) % time_to_consider
);
581 format_iso_time(buf
, interval_wakeup_time
);
585 char buf1
[ISO_TIME_LEN
+1];
586 char buf2
[ISO_TIME_LEN
+1];
587 char buf3
[ISO_TIME_LEN
+1];
588 char buf4
[ISO_TIME_LEN
+1];
590 if (interval_wakeup_time
+time_to_exhaust_bw
> TIME_MAX
)
591 down_time
= TIME_MAX
;
593 down_time
= (time_t)(interval_wakeup_time
+time_to_exhaust_bw
);
594 if (down_time
>interval_end_time
)
595 down_time
= interval_end_time
;
596 format_local_iso_time(buf1
, interval_start_time
);
597 format_local_iso_time(buf2
, interval_wakeup_time
);
598 format_local_iso_time(buf3
, down_time
);
599 format_local_iso_time(buf4
, interval_end_time
);
602 "Configured hibernation. This interval began at %s; "
603 "the scheduled wake-up time %s %s; "
604 "we expect%s to exhaust our quota for this interval around %s; "
605 "the next interval begins at %s (all times local)",
607 time(NULL
)<interval_wakeup_time
?"is":"was", buf2
,
608 time(NULL
)<down_time
?"":"ed", buf3
,
613 /* This rounds 0 up to 1000, but that's actually a feature. */
614 #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
615 /** Save all our bandwidth tracking information to disk. Return 0 on
616 * success, -1 on failure. */
618 accounting_record_bandwidth_usage(time_t now
, or_state_t
*state
)
620 /* Just update the state */
621 state
->AccountingIntervalStart
= interval_start_time
;
622 state
->AccountingBytesReadInInterval
= ROUND_UP(n_bytes_read_in_interval
);
623 state
->AccountingBytesWrittenInInterval
=
624 ROUND_UP(n_bytes_written_in_interval
);
625 state
->AccountingSecondsActive
= n_seconds_active_in_interval
;
626 state
->AccountingExpectedUsage
= expected_bandwidth_usage
;
628 state
->AccountingSecondsToReachSoftLimit
= n_seconds_to_hit_soft_limit
;
629 state
->AccountingSoftLimitHitAt
= soft_limit_hit_at
;
630 state
->AccountingBytesAtSoftLimit
= n_bytes_at_soft_limit
;
632 or_state_mark_dirty(state
,
633 now
+(get_options()->AvoidDiskWrites
? 7200 : 60));
639 /** Read stored accounting information from disk. Return 0 on success;
640 * return -1 and change nothing on failure. */
642 read_bandwidth_usage(void)
644 or_state_t
*state
= get_or_state();
647 char *fname
= get_datadir_fname("bw_accounting");
655 log_info(LD_ACCT
, "Reading bandwidth accounting data from state file");
656 n_bytes_read_in_interval
= state
->AccountingBytesReadInInterval
;
657 n_bytes_written_in_interval
= state
->AccountingBytesWrittenInInterval
;
658 n_seconds_active_in_interval
= state
->AccountingSecondsActive
;
659 interval_start_time
= state
->AccountingIntervalStart
;
660 expected_bandwidth_usage
= state
->AccountingExpectedUsage
;
662 /* Older versions of Tor (before 0.2.2.17-alpha or so) didn't generate these
663 * fields. If you switch back and forth, you might get an
664 * AccountingSoftLimitHitAt value from long before the most recent
665 * interval_start_time. If that's so, then ignore the softlimit-related
667 if (state
->AccountingSoftLimitHitAt
> interval_start_time
) {
668 soft_limit_hit_at
= state
->AccountingSoftLimitHitAt
;
669 n_bytes_at_soft_limit
= state
->AccountingBytesAtSoftLimit
;
670 n_seconds_to_hit_soft_limit
= state
->AccountingSecondsToReachSoftLimit
;
672 soft_limit_hit_at
= 0;
673 n_bytes_at_soft_limit
= 0;
674 n_seconds_to_hit_soft_limit
= 0;
678 char tbuf1
[ISO_TIME_LEN
+1];
679 char tbuf2
[ISO_TIME_LEN
+1];
680 format_iso_time(tbuf1
, state
->LastWritten
);
681 format_iso_time(tbuf2
, state
->AccountingIntervalStart
);
684 "Successfully read bandwidth accounting info from state written at %s "
685 "for interval starting at %s. We have been active for %lu seconds in "
686 "this interval. At the start of the interval, we expected to use "
687 "about %lu KB per second. ("U64_FORMAT
" bytes read so far, "
688 U64_FORMAT
" bytes written so far)",
690 (unsigned long)n_seconds_active_in_interval
,
691 (unsigned long)(expected_bandwidth_usage
*1024/60),
692 U64_PRINTF_ARG(n_bytes_read_in_interval
),
693 U64_PRINTF_ARG(n_bytes_written_in_interval
));
699 /** Return true iff we have sent/received all the bytes we are willing
700 * to send/receive this interval. */
702 hibernate_hard_limit_reached(void)
704 uint64_t hard_limit
= get_options()->AccountingMax
;
707 return n_bytes_read_in_interval
>= hard_limit
708 || n_bytes_written_in_interval
>= hard_limit
;
711 /** Return true iff we have sent/received almost all the bytes we are willing
712 * to send/receive this interval. */
714 hibernate_soft_limit_reached(void)
716 const uint64_t acct_max
= get_options()->AccountingMax
;
717 #define SOFT_LIM_PCT (.95)
718 #define SOFT_LIM_BYTES (500*1024*1024)
719 #define SOFT_LIM_MINUTES (3*60)
720 /* The 'soft limit' is a fair bit more complicated now than once it was.
721 * We want to stop accepting connections when ALL of the following are true:
722 * - We expect to use up the remaining bytes in under 3 hours
723 * - We have used up 95% of our bytes.
724 * - We have less than 500MB of bytes left.
726 uint64_t soft_limit
= DBL_TO_U64(U64_TO_DBL(acct_max
) * SOFT_LIM_PCT
);
727 if (acct_max
> SOFT_LIM_BYTES
&& acct_max
- SOFT_LIM_BYTES
> soft_limit
) {
728 soft_limit
= acct_max
- SOFT_LIM_BYTES
;
730 if (expected_bandwidth_usage
) {
731 const uint64_t expected_usage
=
732 expected_bandwidth_usage
* SOFT_LIM_MINUTES
;
733 if (acct_max
> expected_usage
&& acct_max
- expected_usage
> soft_limit
)
734 soft_limit
= acct_max
- expected_usage
;
739 return n_bytes_read_in_interval
>= soft_limit
740 || n_bytes_written_in_interval
>= soft_limit
;
743 /** Called when we get a SIGINT, or when bandwidth soft limit is
744 * reached. Puts us into "loose hibernation": we don't accept new
745 * connections, but we continue handling old ones. */
747 hibernate_begin(hibernate_state_t new_state
, time_t now
)
750 or_options_t
*options
= get_options();
752 if (new_state
== HIBERNATE_STATE_EXITING
&&
753 hibernate_state
!= HIBERNATE_STATE_LIVE
) {
754 log_notice(LD_GENERAL
,"SIGINT received %s; exiting now.",
755 hibernate_state
== HIBERNATE_STATE_EXITING
?
756 "a second time" : "while hibernating");
761 if (new_state
== HIBERNATE_STATE_LOWBANDWIDTH
&&
762 hibernate_state
== HIBERNATE_STATE_LIVE
) {
763 soft_limit_hit_at
= now
;
764 n_seconds_to_hit_soft_limit
= n_seconds_active_in_interval
;
765 n_bytes_at_soft_limit
= MAX(n_bytes_read_in_interval
,
766 n_bytes_written_in_interval
);
769 /* close listeners. leave control listener(s). */
770 while ((conn
= connection_get_by_type(CONN_TYPE_OR_LISTENER
)) ||
771 (conn
= connection_get_by_type(CONN_TYPE_AP_LISTENER
)) ||
772 (conn
= connection_get_by_type(CONN_TYPE_AP_TRANS_LISTENER
)) ||
773 (conn
= connection_get_by_type(CONN_TYPE_AP_DNS_LISTENER
)) ||
774 (conn
= connection_get_by_type(CONN_TYPE_AP_NATD_LISTENER
)) ||
775 (conn
= connection_get_by_type(CONN_TYPE_DIR_LISTENER
))) {
776 log_info(LD_NET
,"Closing listener type %d", conn
->type
);
777 connection_mark_for_close(conn
);
780 /* XXX kill intro point circs */
781 /* XXX upload rendezvous service descriptors with no intro points */
783 if (new_state
== HIBERNATE_STATE_EXITING
) {
784 log_notice(LD_GENERAL
,"Interrupt: will shut down in %d seconds. Interrupt "
785 "again to exit now.", options
->ShutdownWaitLength
);
786 shutdown_time
= time(NULL
) + options
->ShutdownWaitLength
;
787 } else { /* soft limit reached */
788 hibernate_end_time
= interval_end_time
;
791 hibernate_state
= new_state
;
792 accounting_record_bandwidth_usage(now
, get_or_state());
794 or_state_mark_dirty(get_or_state(),
795 get_options()->AvoidDiskWrites
? now
+600 : 0);
798 /** Called when we've been hibernating and our timeout is reached. */
800 hibernate_end(hibernate_state_t new_state
)
802 tor_assert(hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
||
803 hibernate_state
== HIBERNATE_STATE_DORMANT
);
805 /* listeners will be relaunched in run_scheduled_events() in main.c */
806 log_notice(LD_ACCT
,"Hibernation period ended. Resuming normal activity.");
808 hibernate_state
= new_state
;
809 hibernate_end_time
= 0; /* no longer hibernating */
810 stats_n_seconds_working
= 0; /* reset published uptime */
813 /** A wrapper around hibernate_begin, for when we get SIGINT. */
815 hibernate_begin_shutdown(void)
817 hibernate_begin(HIBERNATE_STATE_EXITING
, time(NULL
));
820 /** Return true iff we are currently hibernating. */
822 we_are_hibernating(void)
824 return hibernate_state
!= HIBERNATE_STATE_LIVE
;
827 /** If we aren't currently dormant, close all connections and become
830 hibernate_go_dormant(time_t now
)
834 if (hibernate_state
== HIBERNATE_STATE_DORMANT
)
836 else if (hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
)
837 hibernate_state
= HIBERNATE_STATE_DORMANT
;
839 hibernate_begin(HIBERNATE_STATE_DORMANT
, now
);
841 log_notice(LD_ACCT
,"Going dormant. Blowing away remaining connections.");
843 /* Close all OR/AP/exit conns. Leave dir conns because we still want
844 * to be able to upload server descriptors so people know we're still
845 * running, and download directories so we can detect if we're obsolete.
846 * Leave control conns because we still want to be controllable.
848 while ((conn
= connection_get_by_type(CONN_TYPE_OR
)) ||
849 (conn
= connection_get_by_type(CONN_TYPE_AP
)) ||
850 (conn
= connection_get_by_type(CONN_TYPE_EXIT
))) {
851 if (CONN_IS_EDGE(conn
))
852 connection_edge_end(TO_EDGE_CONN(conn
), END_STREAM_REASON_HIBERNATING
);
853 log_info(LD_NET
,"Closing conn type %d", conn
->type
);
854 if (conn
->type
== CONN_TYPE_AP
) /* send socks failure if needed */
855 connection_mark_unattached_ap(TO_EDGE_CONN(conn
),
856 END_STREAM_REASON_HIBERNATING
);
858 connection_mark_for_close(conn
);
861 if (now
< interval_wakeup_time
)
862 hibernate_end_time
= interval_wakeup_time
;
864 hibernate_end_time
= interval_end_time
;
866 accounting_record_bandwidth_usage(now
, get_or_state());
868 or_state_mark_dirty(get_or_state(),
869 get_options()->AvoidDiskWrites
? now
+600 : 0);
872 /** Called when hibernate_end_time has arrived. */
874 hibernate_end_time_elapsed(time_t now
)
876 char buf
[ISO_TIME_LEN
+1];
878 /* The interval has ended, or it is wakeup time. Find out which. */
879 accounting_run_housekeeping(now
);
880 if (interval_wakeup_time
<= now
) {
881 /* The interval hasn't changed, but interval_wakeup_time has passed.
882 * It's time to wake up and start being a server. */
883 hibernate_end(HIBERNATE_STATE_LIVE
);
886 /* The interval has changed, and it isn't time to wake up yet. */
887 hibernate_end_time
= interval_wakeup_time
;
888 format_iso_time(buf
,interval_wakeup_time
);
889 if (hibernate_state
!= HIBERNATE_STATE_DORMANT
) {
890 /* We weren't sleeping before; we should sleep now. */
892 "Accounting period ended. Commencing hibernation until "
894 hibernate_go_dormant(now
);
897 "Accounting period ended. This period, we will hibernate"
898 " until %s GMT",buf
);
903 /** Consider our environment and decide if it's time
904 * to start/stop hibernating.
907 consider_hibernation(time_t now
)
909 int accounting_enabled
= get_options()->AccountingMax
!= 0;
910 char buf
[ISO_TIME_LEN
+1];
912 /* If we're in 'exiting' mode, then we just shut down after the interval
914 if (hibernate_state
== HIBERNATE_STATE_EXITING
) {
915 tor_assert(shutdown_time
);
916 if (shutdown_time
<= now
) {
917 log_notice(LD_GENERAL
, "Clean shutdown finished. Exiting.");
921 return; /* if exiting soon, don't worry about bandwidth limits */
924 if (hibernate_state
== HIBERNATE_STATE_DORMANT
) {
925 /* We've been hibernating because of bandwidth accounting. */
926 tor_assert(hibernate_end_time
);
927 if (hibernate_end_time
> now
&& accounting_enabled
) {
928 /* If we're hibernating, don't wake up until it's time, regardless of
929 * whether we're in a new interval. */
932 hibernate_end_time_elapsed(now
);
936 /* Else, we aren't hibernating. See if it's time to start hibernating, or to
938 if (hibernate_state
== HIBERNATE_STATE_LIVE
) {
939 if (hibernate_soft_limit_reached()) {
941 "Bandwidth soft limit reached; commencing hibernation.");
942 hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH
, now
);
943 } else if (accounting_enabled
&& now
< interval_wakeup_time
) {
944 format_local_iso_time(buf
,interval_wakeup_time
);
946 "Commencing hibernation. We will wake up at %s local time.",
948 hibernate_go_dormant(now
);
952 if (hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
) {
953 if (!accounting_enabled
) {
954 hibernate_end_time_elapsed(now
);
955 } else if (hibernate_hard_limit_reached()) {
956 hibernate_go_dormant(now
);
957 } else if (hibernate_end_time
<= now
) {
958 /* The hibernation period ended while we were still in lowbandwidth.*/
959 hibernate_end_time_elapsed(now
);
964 /** Helper function: called when we get a GETINFO request for an
965 * accounting-related key on the control connection <b>conn</b>. If we can
966 * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
967 * allocated string holding the result. Otherwise, set *<b>answer</b> to
970 getinfo_helper_accounting(control_connection_t
*conn
,
971 const char *question
, char **answer
,
976 if (!strcmp(question
, "accounting/enabled")) {
977 *answer
= tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
978 } else if (!strcmp(question
, "accounting/hibernating")) {
979 if (hibernate_state
== HIBERNATE_STATE_DORMANT
)
980 *answer
= tor_strdup("hard");
981 else if (hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
)
982 *answer
= tor_strdup("soft");
984 *answer
= tor_strdup("awake");
985 } else if (!strcmp(question
, "accounting/bytes")) {
986 *answer
= tor_malloc(32);
987 tor_snprintf(*answer
, 32, U64_FORMAT
" "U64_FORMAT
,
988 U64_PRINTF_ARG(n_bytes_read_in_interval
),
989 U64_PRINTF_ARG(n_bytes_written_in_interval
));
990 } else if (!strcmp(question
, "accounting/bytes-left")) {
991 uint64_t limit
= get_options()->AccountingMax
;
992 uint64_t read_left
= 0, write_left
= 0;
993 if (n_bytes_read_in_interval
< limit
)
994 read_left
= limit
- n_bytes_read_in_interval
;
995 if (n_bytes_written_in_interval
< limit
)
996 write_left
= limit
- n_bytes_written_in_interval
;
997 *answer
= tor_malloc(64);
998 tor_snprintf(*answer
, 64, U64_FORMAT
" "U64_FORMAT
,
999 U64_PRINTF_ARG(read_left
), U64_PRINTF_ARG(write_left
));
1000 } else if (!strcmp(question
, "accounting/interval-start")) {
1001 *answer
= tor_malloc(ISO_TIME_LEN
+1);
1002 format_iso_time(*answer
, interval_start_time
);
1003 } else if (!strcmp(question
, "accounting/interval-wake")) {
1004 *answer
= tor_malloc(ISO_TIME_LEN
+1);
1005 format_iso_time(*answer
, interval_wakeup_time
);
1006 } else if (!strcmp(question
, "accounting/interval-end")) {
1007 *answer
= tor_malloc(ISO_TIME_LEN
+1);
1008 format_iso_time(*answer
, interval_end_time
);