1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2009, 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 /** Possible values of hibernate_state */
28 /** We are running normally. */
29 HIBERNATE_STATE_LIVE
=1,
30 /** We're trying to shut down cleanly, and we'll kill all active connections
31 * at shutdown_time. */
32 HIBERNATE_STATE_EXITING
=2,
33 /** We're running low on allocated bandwidth for this period, so we won't
34 * accept any new connections. */
35 HIBERNATE_STATE_LOWBANDWIDTH
=3,
36 /** We are hibernating, and we won't wake up till there's more bandwidth to
38 HIBERNATE_STATE_DORMANT
=4
41 extern long stats_n_seconds_working
; /* published uptime */
43 /** Are we currently awake, asleep, running out of bandwidth, or shutting
45 static hibernate_state_t hibernate_state
= HIBERNATE_STATE_LIVE
;
46 /** If are hibernating, when do we plan to wake up? Set to 0 if we
47 * aren't hibernating. */
48 static time_t hibernate_end_time
= 0;
49 /** If we are shutting down, when do we plan finally exit? Set to 0 if
50 * we aren't shutting down. */
51 static time_t shutdown_time
= 0;
53 /** Possible accounting periods. */
55 UNIT_MONTH
=1, UNIT_WEEK
=2, UNIT_DAY
=3,
58 /* Fields for accounting logic. Accounting overview:
60 * Accounting is designed to ensure that no more than N bytes are sent in
61 * either direction over a given interval (currently, one month, one week, or
63 * try to do this by choking our bandwidth to a trickle, but that
64 * would make our streams useless. Instead, we estimate what our
65 * bandwidth usage will be, and guess how long we'll be able to
66 * provide that much bandwidth before hitting our limit. We then
67 * choose a random time within the accounting interval to come up (so
68 * that we don't get 50 Tors running on the 1st of the month and none
71 * Each interval runs as follows:
73 * 1. We guess our bandwidth usage, based on how much we used
74 * last time. We choose a "wakeup time" within the interval to come up.
75 * 2. Until the chosen wakeup time, we hibernate.
76 * 3. We come up at the wakeup time, and provide bandwidth until we are
77 * "very close" to running out.
78 * 4. Then we go into low-bandwidth mode, and stop accepting new
79 * connections, but provide bandwidth until we run out.
80 * 5. Then we hibernate until the end of the interval.
82 * If the interval ends before we run out of bandwidth, we go back to
86 /** How many bytes have we read in this accounting interval? */
87 static uint64_t n_bytes_read_in_interval
= 0;
88 /** How many bytes have we written in this accounting interval? */
89 static uint64_t n_bytes_written_in_interval
= 0;
90 /** How many seconds have we been running this interval? */
91 static uint32_t n_seconds_active_in_interval
= 0;
92 /** When did this accounting interval start? */
93 static time_t interval_start_time
= 0;
94 /** When will this accounting interval end? */
95 static time_t interval_end_time
= 0;
96 /** How far into the accounting interval should we hibernate? */
97 static time_t interval_wakeup_time
= 0;
98 /** How much bandwidth do we 'expect' to use per minute? (0 if we have no
99 * info from the last period.) */
100 static uint64_t expected_bandwidth_usage
= 0;
101 /** What unit are we using for our accounting? */
102 static time_unit_t cfg_unit
= UNIT_MONTH
;
104 /** How many days,hours,minutes into each unit does our accounting interval
106 static int cfg_start_day
= 0,
110 static void reset_accounting(time_t now
);
111 static int read_bandwidth_usage(void);
112 static time_t start_of_accounting_period_after(time_t now
);
113 static time_t start_of_accounting_period_containing(time_t now
);
114 static void accounting_set_wakeup_time(void);
117 * Functions for bandwidth accounting.
120 /** Configure accounting start/end time settings based on
121 * options->AccountingStart. Return 0 on success, -1 on failure. If
122 * <b>validate_only</b> is true, do not change the current settings. */
124 accounting_parse_options(or_options_t
*options
, int validate_only
)
130 const char *v
= options
->AccountingStart
;
135 if (!validate_only
) {
136 cfg_unit
= UNIT_MONTH
;
144 items
= smartlist_create();
145 smartlist_split_string(items
, v
, NULL
,
146 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
,0);
147 if (smartlist_len(items
)<2) {
148 log_warn(LD_CONFIG
, "Too few arguments to AccountingStart");
151 s
= smartlist_get(items
,0);
152 if (0==strcasecmp(s
, "month")) {
154 } else if (0==strcasecmp(s
, "week")) {
156 } else if (0==strcasecmp(s
, "day")) {
160 "Unrecognized accounting unit '%s': only 'month', 'week',"
161 " and 'day' are supported.", s
);
167 d
= tor_parse_long(smartlist_get(items
,1), 10, 1, 7, &ok
, NULL
);
169 log_warn(LD_CONFIG
, "Weekly accounting must begin on a day between "
170 "1 (Monday) and 7 (Sunday)");
175 d
= tor_parse_long(smartlist_get(items
,1), 10, 1, 28, &ok
, NULL
);
177 log_warn(LD_CONFIG
, "Monthly accounting must begin on a day between "
185 /* Coverity dislikes unreachable default cases; some compilers warn on
186 * switch statements missing a case. Tell Coverity not to worry. */
187 /* coverity[dead_error_begin] */
192 idx
= unit
==UNIT_DAY
?1:2;
193 if (smartlist_len(items
) != (idx
+1)) {
194 log_warn(LD_CONFIG
,"Accounting unit '%s' requires %d argument%s.",
195 s
, idx
, (idx
>1)?"s":"");
198 s
= smartlist_get(items
, idx
);
199 h
= tor_parse_long(s
, 10, 0, 23, &ok
, &cp
);
201 log_warn(LD_CONFIG
,"Accounting start time not parseable: bad hour.");
204 if (!cp
|| *cp
!=':') {
206 "Accounting start time not parseable: not in HH:MM format");
209 m
= tor_parse_long(cp
+1, 10, 0, 59, &ok
, &cp
);
211 log_warn(LD_CONFIG
, "Accounting start time not parseable: bad minute");
214 if (!cp
|| *cp
!='\0') {
216 "Accounting start time not parseable: not in HH:MM format");
220 if (!validate_only
) {
222 cfg_start_day
= (int)d
;
223 cfg_start_hour
= (int)h
;
224 cfg_start_min
= (int)m
;
226 SMARTLIST_FOREACH(items
, char *, item
, tor_free(item
));
227 smartlist_free(items
);
230 SMARTLIST_FOREACH(items
, char *, item
, tor_free(item
));
231 smartlist_free(items
);
235 /** If we want to manage the accounting system and potentially
236 * hibernate, return 1, else return 0.
239 accounting_is_enabled(or_options_t
*options
)
241 if (options
->AccountingMax
)
246 /** Called from main.c to tell us that <b>seconds</b> seconds have
247 * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
248 * bytes have been written. */
250 accounting_add_bytes(size_t n_read
, size_t n_written
, int seconds
)
252 n_bytes_read_in_interval
+= n_read
;
253 n_bytes_written_in_interval
+= n_written
;
254 /* If we haven't been called in 10 seconds, we're probably jumping
256 n_seconds_active_in_interval
+= (seconds
< 10) ? seconds
: 0;
259 /** If get_end, return the end of the accounting period that contains
260 * the time <b>now</b>. Else, return the start of the accounting
261 * period that contains the time <b>now</b> */
263 edge_of_accounting_period_containing(time_t now
, int get_end
)
267 tor_localtime_r(&now
, &tm
);
269 /* Set 'before' to true iff the current time is before the hh:mm
270 * changeover time for today. */
271 before
= tm
.tm_hour
< cfg_start_hour
||
272 (tm
.tm_hour
== cfg_start_hour
&& tm
.tm_min
< cfg_start_min
);
274 /* Dispatch by unit. First, find the start day of the given period;
275 * then, if get_end is true, increment to the end day. */
279 /* If this is before the Nth, we want the Nth of last month. */
280 if (tm
.tm_mday
< cfg_start_day
||
281 (tm
.tm_mday
< cfg_start_day
&& before
)) {
284 /* Otherwise, the month is correct. */
285 tm
.tm_mday
= cfg_start_day
;
291 /* What is the 'target' day of the week in struct tm format? (We
292 say Sunday==7; struct tm says Sunday==0.) */
293 int wday
= cfg_start_day
% 7;
294 /* How many days do we subtract from today to get to the right day? */
295 int delta
= (7+tm
.tm_wday
-wday
)%7;
296 /* If we are on the right day, but the changeover hasn't happened yet,
297 * then subtract a whole week. */
298 if (delta
== 0 && before
)
315 tm
.tm_hour
= cfg_start_hour
;
316 tm
.tm_min
= cfg_start_min
;
318 tm
.tm_isdst
= -1; /* Autodetect DST */
322 /** Return the start of the accounting period containing the time
325 start_of_accounting_period_containing(time_t now
)
327 return edge_of_accounting_period_containing(now
, 0);
330 /** Return the start of the accounting period that comes after the one
331 * containing the time <b>now</b>. */
333 start_of_accounting_period_after(time_t now
)
335 return edge_of_accounting_period_containing(now
, 1);
338 /** Initialize the accounting subsystem. */
340 configure_accounting(time_t now
)
342 /* Try to remember our recorded usage. */
343 if (!interval_start_time
)
344 read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
346 if (!interval_start_time
||
347 start_of_accounting_period_after(interval_start_time
) <= now
) {
348 /* We didn't have recorded usage, or we don't have recorded usage
349 * for this interval. Start a new interval. */
350 log_info(LD_ACCT
, "Starting new accounting interval.");
351 reset_accounting(now
);
352 } else if (interval_start_time
==
353 start_of_accounting_period_containing(interval_start_time
)) {
354 log_info(LD_ACCT
, "Continuing accounting interval.");
355 /* We are in the interval we thought we were in. Do nothing.*/
356 interval_end_time
= start_of_accounting_period_after(interval_start_time
);
359 "Mismatched accounting interval; starting a fresh one.");
360 reset_accounting(now
);
362 accounting_set_wakeup_time();
365 /** Set expected_bandwidth_usage based on how much we sent/received
366 * per minute last interval (if we were up for at least 30 minutes),
367 * or based on our declared bandwidth otherwise. */
369 update_expected_bandwidth(void)
371 uint64_t used
, expected
;
372 uint64_t max_configured
= (get_options()->BandwidthRate
* 60);
374 if (n_seconds_active_in_interval
< 1800) {
375 /* If we haven't gotten enough data last interval, set 'expected'
376 * to 0. This will set our wakeup to the start of the interval.
377 * Next interval, we'll choose our starting time based on how much
378 * we sent this interval.
382 used
= n_bytes_written_in_interval
< n_bytes_read_in_interval
?
383 n_bytes_read_in_interval
: n_bytes_written_in_interval
;
384 expected
= used
/ (n_seconds_active_in_interval
/ 60);
385 if (expected
> max_configured
)
386 expected
= max_configured
;
388 expected_bandwidth_usage
= expected
;
391 /** Called at the start of a new accounting interval: reset our
392 * expected bandwidth usage based on what happened last time, set up
393 * the start and end of the interval, and clear byte/time totals.
396 reset_accounting(time_t now
)
398 log_info(LD_ACCT
, "Starting new accounting interval.");
399 update_expected_bandwidth();
400 interval_start_time
= start_of_accounting_period_containing(now
);
401 interval_end_time
= start_of_accounting_period_after(interval_start_time
);
402 n_bytes_read_in_interval
= 0;
403 n_bytes_written_in_interval
= 0;
404 n_seconds_active_in_interval
= 0;
407 /** Return true iff we should save our bandwidth usage to disk. */
409 time_to_record_bandwidth_usage(time_t now
)
411 /* Note every 600 sec */
412 #define NOTE_INTERVAL (600)
413 /* Or every 20 megabytes */
414 #define NOTE_BYTES 20*(1024*1024)
415 static uint64_t last_read_bytes_noted
= 0;
416 static uint64_t last_written_bytes_noted
= 0;
417 static time_t last_time_noted
= 0;
419 if (last_time_noted
+ NOTE_INTERVAL
<= now
||
420 last_read_bytes_noted
+ NOTE_BYTES
<= n_bytes_read_in_interval
||
421 last_written_bytes_noted
+ NOTE_BYTES
<= n_bytes_written_in_interval
||
422 (interval_end_time
&& interval_end_time
<= now
)) {
423 last_time_noted
= now
;
424 last_read_bytes_noted
= n_bytes_read_in_interval
;
425 last_written_bytes_noted
= n_bytes_written_in_interval
;
431 /** Invoked once per second. Checks whether it is time to hibernate,
432 * record bandwidth used, etc. */
434 accounting_run_housekeeping(time_t now
)
436 if (now
>= interval_end_time
) {
437 configure_accounting(now
);
439 if (time_to_record_bandwidth_usage(now
)) {
440 if (accounting_record_bandwidth_usage(now
, get_or_state())) {
441 log_warn(LD_FS
, "Couldn't record bandwidth usage to disk.");
446 /** When we have no idea how fast we are, how long do we assume it will take
447 * us to exhaust our bandwidth? */
448 #define GUESS_TIME_TO_USE_BANDWIDTH (24*60*60)
450 /** Based on our interval and our estimated bandwidth, choose a
451 * deterministic (but random-ish) time to wake up. */
453 accounting_set_wakeup_time(void)
455 char buf
[ISO_TIME_LEN
+1];
456 char digest
[DIGEST_LEN
];
457 crypto_digest_env_t
*d_env
;
458 int time_in_interval
;
459 uint64_t time_to_exhaust_bw
;
460 int time_to_consider
;
462 if (! identity_key_is_set()) {
463 if (init_keys() < 0) {
464 log_err(LD_BUG
, "Error initializing keys");
469 format_iso_time(buf
, interval_start_time
);
470 crypto_pk_get_digest(get_identity_key(), digest
);
472 d_env
= crypto_new_digest_env();
473 crypto_digest_add_bytes(d_env
, buf
, ISO_TIME_LEN
);
474 crypto_digest_add_bytes(d_env
, digest
, DIGEST_LEN
);
475 crypto_digest_get_digest(d_env
, digest
, DIGEST_LEN
);
476 crypto_free_digest_env(d_env
);
478 if (!expected_bandwidth_usage
) {
479 char buf1
[ISO_TIME_LEN
+1];
480 char buf2
[ISO_TIME_LEN
+1];
481 format_local_iso_time(buf1
, interval_start_time
);
482 format_local_iso_time(buf2
, interval_end_time
);
483 time_to_exhaust_bw
= GUESS_TIME_TO_USE_BANDWIDTH
;
484 interval_wakeup_time
= interval_start_time
;
487 "Configured hibernation. This interval begins at %s "
488 "and ends at %s. We have no prior estimate for bandwidth, so "
489 "we will start out awake and hibernate when we exhaust our quota.",
494 time_in_interval
= (int)(interval_end_time
- interval_start_time
);
497 (get_options()->AccountingMax
/expected_bandwidth_usage
)*60;
498 if (time_to_exhaust_bw
> TIME_MAX
) {
499 time_to_exhaust_bw
= TIME_MAX
;
500 time_to_consider
= 0;
502 time_to_consider
= time_in_interval
- (int)time_to_exhaust_bw
;
505 if (time_to_consider
<=0) {
506 interval_wakeup_time
= interval_start_time
;
508 /* XXX can we simplify this just by picking a random (non-deterministic)
509 * time to be up? If we go down and come up, then we pick a new one. Is
510 * that good enough? -RD */
512 /* This is not a perfectly unbiased conversion, but it is good enough:
513 * in the worst case, the first half of the day is 0.06 percent likelier
514 * to be chosen than the last half. */
515 interval_wakeup_time
= interval_start_time
+
516 (get_uint32(digest
) % time_to_consider
);
518 format_iso_time(buf
, interval_wakeup_time
);
522 char buf1
[ISO_TIME_LEN
+1];
523 char buf2
[ISO_TIME_LEN
+1];
524 char buf3
[ISO_TIME_LEN
+1];
525 char buf4
[ISO_TIME_LEN
+1];
527 if (interval_wakeup_time
+time_to_exhaust_bw
> TIME_MAX
)
528 down_time
= TIME_MAX
;
530 down_time
= (time_t)(interval_wakeup_time
+time_to_exhaust_bw
);
531 if (down_time
>interval_end_time
)
532 down_time
= interval_end_time
;
533 format_local_iso_time(buf1
, interval_start_time
);
534 format_local_iso_time(buf2
, interval_wakeup_time
);
535 format_local_iso_time(buf3
, down_time
);
536 format_local_iso_time(buf4
, interval_end_time
);
539 "Configured hibernation. This interval began at %s; "
540 "the scheduled wake-up time %s %s; "
541 "we expect%s to exhaust our quota for this interval around %s; "
542 "the next interval begins at %s (all times local)",
544 time(NULL
)<interval_wakeup_time
?"is":"was", buf2
,
545 time(NULL
)<down_time
?"":"ed", buf3
,
550 /* This rounds 0 up to 1000, but that's actually a feature. */
551 #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
552 /** Save all our bandwidth tracking information to disk. Return 0 on
553 * success, -1 on failure. */
555 accounting_record_bandwidth_usage(time_t now
, or_state_t
*state
)
557 /* Just update the state */
558 state
->AccountingIntervalStart
= interval_start_time
;
559 state
->AccountingBytesReadInInterval
= ROUND_UP(n_bytes_read_in_interval
);
560 state
->AccountingBytesWrittenInInterval
=
561 ROUND_UP(n_bytes_written_in_interval
);
562 state
->AccountingSecondsActive
= n_seconds_active_in_interval
;
563 state
->AccountingExpectedUsage
= expected_bandwidth_usage
;
565 or_state_mark_dirty(state
,
566 now
+(get_options()->AvoidDiskWrites
? 7200 : 60));
572 /** Read stored accounting information from disk. Return 0 on success;
573 * return -1 and change nothing on failure. */
575 read_bandwidth_usage(void)
577 or_state_t
*state
= get_or_state();
580 char *fname
= get_datadir_fname("bw_accounting");
588 /* Okay; it looks like the state file is more up-to-date than the
589 * bw_accounting file, or the bw_accounting file is nonexistent,
590 * or the bw_accounting file is corrupt.
592 log_info(LD_ACCT
, "Reading bandwidth accounting data from state file");
593 n_bytes_read_in_interval
= state
->AccountingBytesReadInInterval
;
594 n_bytes_written_in_interval
= state
->AccountingBytesWrittenInInterval
;
595 n_seconds_active_in_interval
= state
->AccountingSecondsActive
;
596 interval_start_time
= state
->AccountingIntervalStart
;
597 expected_bandwidth_usage
= state
->AccountingExpectedUsage
;
600 char tbuf1
[ISO_TIME_LEN
+1];
601 char tbuf2
[ISO_TIME_LEN
+1];
602 format_iso_time(tbuf1
, state
->LastWritten
);
603 format_iso_time(tbuf2
, state
->AccountingIntervalStart
);
606 "Successfully read bandwidth accounting info from state written at %s "
607 "for interval starting at %s. We have been active for %lu seconds in "
608 "this interval. At the start of the interval, we expected to use "
609 "about %lu KB per second. ("U64_FORMAT
" bytes read so far, "
610 U64_FORMAT
" bytes written so far)",
612 (unsigned long)n_seconds_active_in_interval
,
613 (unsigned long)(expected_bandwidth_usage
*1024/60),
614 U64_PRINTF_ARG(n_bytes_read_in_interval
),
615 U64_PRINTF_ARG(n_bytes_written_in_interval
));
621 /** Return true iff we have sent/received all the bytes we are willing
622 * to send/receive this interval. */
624 hibernate_hard_limit_reached(void)
626 uint64_t hard_limit
= get_options()->AccountingMax
;
629 return n_bytes_read_in_interval
>= hard_limit
630 || n_bytes_written_in_interval
>= hard_limit
;
633 /** Return true iff we have sent/received almost all the bytes we are willing
634 * to send/receive this interval. */
636 hibernate_soft_limit_reached(void)
638 uint64_t soft_limit
= DBL_TO_U64(U64_TO_DBL(get_options()->AccountingMax
)
642 return n_bytes_read_in_interval
>= soft_limit
643 || n_bytes_written_in_interval
>= soft_limit
;
646 /** Called when we get a SIGINT, or when bandwidth soft limit is
647 * reached. Puts us into "loose hibernation": we don't accept new
648 * connections, but we continue handling old ones. */
650 hibernate_begin(hibernate_state_t new_state
, time_t now
)
653 or_options_t
*options
= get_options();
655 if (new_state
== HIBERNATE_STATE_EXITING
&&
656 hibernate_state
!= HIBERNATE_STATE_LIVE
) {
657 log_notice(LD_GENERAL
,"SIGINT received %s; exiting now.",
658 hibernate_state
== HIBERNATE_STATE_EXITING
?
659 "a second time" : "while hibernating");
664 /* close listeners. leave control listener(s). */
665 while ((conn
= connection_get_by_type(CONN_TYPE_OR_LISTENER
)) ||
666 (conn
= connection_get_by_type(CONN_TYPE_AP_LISTENER
)) ||
667 (conn
= connection_get_by_type(CONN_TYPE_AP_TRANS_LISTENER
)) ||
668 (conn
= connection_get_by_type(CONN_TYPE_AP_DNS_LISTENER
)) ||
669 (conn
= connection_get_by_type(CONN_TYPE_AP_NATD_LISTENER
)) ||
670 (conn
= connection_get_by_type(CONN_TYPE_DIR_LISTENER
))) {
671 log_info(LD_NET
,"Closing listener type %d", conn
->type
);
672 connection_mark_for_close(conn
);
675 /* XXX kill intro point circs */
676 /* XXX upload rendezvous service descriptors with no intro points */
678 if (new_state
== HIBERNATE_STATE_EXITING
) {
679 log_notice(LD_GENERAL
,"Interrupt: will shut down in %d seconds. Interrupt "
680 "again to exit now.", options
->ShutdownWaitLength
);
681 shutdown_time
= time(NULL
) + options
->ShutdownWaitLength
;
682 } else { /* soft limit reached */
683 hibernate_end_time
= interval_end_time
;
686 hibernate_state
= new_state
;
687 accounting_record_bandwidth_usage(now
, get_or_state());
689 or_state_mark_dirty(get_or_state(),
690 get_options()->AvoidDiskWrites
? now
+600 : 0);
693 /** Called when we've been hibernating and our timeout is reached. */
695 hibernate_end(hibernate_state_t new_state
)
697 tor_assert(hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
||
698 hibernate_state
== HIBERNATE_STATE_DORMANT
);
700 /* listeners will be relaunched in run_scheduled_events() in main.c */
701 log_notice(LD_ACCT
,"Hibernation period ended. Resuming normal activity.");
703 hibernate_state
= new_state
;
704 hibernate_end_time
= 0; /* no longer hibernating */
705 stats_n_seconds_working
= 0; /* reset published uptime */
708 /** A wrapper around hibernate_begin, for when we get SIGINT. */
710 hibernate_begin_shutdown(void)
712 hibernate_begin(HIBERNATE_STATE_EXITING
, time(NULL
));
715 /** Return true iff we are currently hibernating. */
717 we_are_hibernating(void)
719 return hibernate_state
!= HIBERNATE_STATE_LIVE
;
722 /** If we aren't currently dormant, close all connections and become
725 hibernate_go_dormant(time_t now
)
729 if (hibernate_state
== HIBERNATE_STATE_DORMANT
)
731 else if (hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
)
732 hibernate_state
= HIBERNATE_STATE_DORMANT
;
734 hibernate_begin(HIBERNATE_STATE_DORMANT
, now
);
736 log_notice(LD_ACCT
,"Going dormant. Blowing away remaining connections.");
738 /* Close all OR/AP/exit conns. Leave dir conns because we still want
739 * to be able to upload server descriptors so people know we're still
740 * running, and download directories so we can detect if we're obsolete.
741 * Leave control conns because we still want to be controllable.
743 while ((conn
= connection_get_by_type(CONN_TYPE_OR
)) ||
744 (conn
= connection_get_by_type(CONN_TYPE_AP
)) ||
745 (conn
= connection_get_by_type(CONN_TYPE_EXIT
))) {
746 if (CONN_IS_EDGE(conn
))
747 connection_edge_end(TO_EDGE_CONN(conn
), END_STREAM_REASON_HIBERNATING
);
748 log_info(LD_NET
,"Closing conn type %d", conn
->type
);
749 if (conn
->type
== CONN_TYPE_AP
) /* send socks failure if needed */
750 connection_mark_unattached_ap(TO_EDGE_CONN(conn
),
751 END_STREAM_REASON_HIBERNATING
);
753 connection_mark_for_close(conn
);
756 if (now
< interval_wakeup_time
)
757 hibernate_end_time
= interval_wakeup_time
;
759 hibernate_end_time
= interval_end_time
;
761 accounting_record_bandwidth_usage(now
, get_or_state());
763 or_state_mark_dirty(get_or_state(),
764 get_options()->AvoidDiskWrites
? now
+600 : 0);
767 /** Called when hibernate_end_time has arrived. */
769 hibernate_end_time_elapsed(time_t now
)
771 char buf
[ISO_TIME_LEN
+1];
773 /* The interval has ended, or it is wakeup time. Find out which. */
774 accounting_run_housekeeping(now
);
775 if (interval_wakeup_time
<= now
) {
776 /* The interval hasn't changed, but interval_wakeup_time has passed.
777 * It's time to wake up and start being a server. */
778 hibernate_end(HIBERNATE_STATE_LIVE
);
781 /* The interval has changed, and it isn't time to wake up yet. */
782 hibernate_end_time
= interval_wakeup_time
;
783 format_iso_time(buf
,interval_wakeup_time
);
784 if (hibernate_state
!= HIBERNATE_STATE_DORMANT
) {
785 /* We weren't sleeping before; we should sleep now. */
787 "Accounting period ended. Commencing hibernation until "
789 hibernate_go_dormant(now
);
792 "Accounting period ended. This period, we will hibernate"
793 " until %s GMT",buf
);
798 /** Consider our environment and decide if it's time
799 * to start/stop hibernating.
802 consider_hibernation(time_t now
)
804 int accounting_enabled
= get_options()->AccountingMax
!= 0;
805 char buf
[ISO_TIME_LEN
+1];
807 /* If we're in 'exiting' mode, then we just shut down after the interval
809 if (hibernate_state
== HIBERNATE_STATE_EXITING
) {
810 tor_assert(shutdown_time
);
811 if (shutdown_time
<= now
) {
812 log_notice(LD_GENERAL
, "Clean shutdown finished. Exiting.");
816 return; /* if exiting soon, don't worry about bandwidth limits */
819 if (hibernate_state
== HIBERNATE_STATE_DORMANT
) {
820 /* We've been hibernating because of bandwidth accounting. */
821 tor_assert(hibernate_end_time
);
822 if (hibernate_end_time
> now
&& accounting_enabled
) {
823 /* If we're hibernating, don't wake up until it's time, regardless of
824 * whether we're in a new interval. */
827 hibernate_end_time_elapsed(now
);
831 /* Else, we aren't hibernating. See if it's time to start hibernating, or to
833 if (hibernate_state
== HIBERNATE_STATE_LIVE
) {
834 if (hibernate_soft_limit_reached()) {
836 "Bandwidth soft limit reached; commencing hibernation.");
837 hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH
, now
);
838 } else if (accounting_enabled
&& now
< interval_wakeup_time
) {
839 format_local_iso_time(buf
,interval_wakeup_time
);
841 "Commencing hibernation. We will wake up at %s local time.",
843 hibernate_go_dormant(now
);
847 if (hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
) {
848 if (!accounting_enabled
) {
849 hibernate_end_time_elapsed(now
);
850 } else if (hibernate_hard_limit_reached()) {
851 hibernate_go_dormant(now
);
852 } else if (hibernate_end_time
<= now
) {
853 /* The hibernation period ended while we were still in lowbandwidth.*/
854 hibernate_end_time_elapsed(now
);
859 /** Helper function: called when we get a GETINFO request for an
860 * accounting-related key on the control connection <b>conn</b>. If we can
861 * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
862 * allocated string holding the result. Otherwise, set *<b>answer</b> to
865 getinfo_helper_accounting(control_connection_t
*conn
,
866 const char *question
, char **answer
)
869 if (!strcmp(question
, "accounting/enabled")) {
870 *answer
= tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
871 } else if (!strcmp(question
, "accounting/hibernating")) {
872 if (hibernate_state
== HIBERNATE_STATE_DORMANT
)
873 *answer
= tor_strdup("hard");
874 else if (hibernate_state
== HIBERNATE_STATE_LOWBANDWIDTH
)
875 *answer
= tor_strdup("soft");
877 *answer
= tor_strdup("awake");
878 } else if (!strcmp(question
, "accounting/bytes")) {
879 *answer
= tor_malloc(32);
880 tor_snprintf(*answer
, 32, U64_FORMAT
" "U64_FORMAT
,
881 U64_PRINTF_ARG(n_bytes_read_in_interval
),
882 U64_PRINTF_ARG(n_bytes_written_in_interval
));
883 } else if (!strcmp(question
, "accounting/bytes-left")) {
884 uint64_t limit
= get_options()->AccountingMax
;
885 uint64_t read_left
= 0, write_left
= 0;
886 if (n_bytes_read_in_interval
< limit
)
887 read_left
= limit
- n_bytes_read_in_interval
;
888 if (n_bytes_written_in_interval
< limit
)
889 write_left
= limit
- n_bytes_written_in_interval
;
890 *answer
= tor_malloc(64);
891 tor_snprintf(*answer
, 64, U64_FORMAT
" "U64_FORMAT
,
892 U64_PRINTF_ARG(read_left
), U64_PRINTF_ARG(write_left
));
893 } else if (!strcmp(question
, "accounting/interval-start")) {
894 *answer
= tor_malloc(ISO_TIME_LEN
+1);
895 format_iso_time(*answer
, interval_start_time
);
896 } else if (!strcmp(question
, "accounting/interval-wake")) {
897 *answer
= tor_malloc(ISO_TIME_LEN
+1);
898 format_iso_time(*answer
, interval_wakeup_time
);
899 } else if (!strcmp(question
, "accounting/interval-end")) {
900 *answer
= tor_malloc(ISO_TIME_LEN
+1);
901 format_iso_time(*answer
, interval_end_time
);