Update Tor Project copyright years
[tor/rransom.git] / src / or / hibernate.c
blob5ebe5b1c5a475939a52dc81a965a3e5997f6fc29
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2010, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file hibernate.c
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
10 * stop hibernating.
11 **/
14 hibernating, phase 1:
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
19 hibernating, phase 2:
20 (entered when bandwidth hard limit reached)
21 - close all OR/AP/exit conns)
24 #include "or.h"
26 /** Possible values of hibernate_state */
27 typedef enum {
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
37 * use. */
38 HIBERNATE_STATE_DORMANT=4
39 } hibernate_state_t;
41 extern long stats_n_seconds_working; /* published uptime */
43 /** Are we currently awake, asleep, running out of bandwidth, or shutting
44 * down? */
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. */
54 typedef enum {
55 UNIT_MONTH=1, UNIT_WEEK=2, UNIT_DAY=3,
56 } time_unit_t;
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
62 * one day) We could
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
69 * on the 30th).
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
83 * step one.
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
105 * start? */
106 static int cfg_start_day = 0,
107 cfg_start_hour = 0,
108 cfg_start_min = 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);
116 /* ************
117 * Functions for bandwidth accounting.
118 * ************/
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)
126 time_unit_t unit;
127 int ok, idx;
128 long d,h,m;
129 smartlist_t *items;
130 const char *v = options->AccountingStart;
131 const char *s;
132 char *cp;
134 if (!v) {
135 if (!validate_only) {
136 cfg_unit = UNIT_MONTH;
137 cfg_start_day = 1;
138 cfg_start_hour = 0;
139 cfg_start_min = 0;
141 return 0;
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");
149 goto err;
151 s = smartlist_get(items,0);
152 if (0==strcasecmp(s, "month")) {
153 unit = UNIT_MONTH;
154 } else if (0==strcasecmp(s, "week")) {
155 unit = UNIT_WEEK;
156 } else if (0==strcasecmp(s, "day")) {
157 unit = UNIT_DAY;
158 } else {
159 log_warn(LD_CONFIG,
160 "Unrecognized accounting unit '%s': only 'month', 'week',"
161 " and 'day' are supported.", s);
162 goto err;
165 switch (unit) {
166 case UNIT_WEEK:
167 d = tor_parse_long(smartlist_get(items,1), 10, 1, 7, &ok, NULL);
168 if (!ok) {
169 log_warn(LD_CONFIG, "Weekly accounting must begin on a day between "
170 "1 (Monday) and 7 (Sunday)");
171 goto err;
173 break;
174 case UNIT_MONTH:
175 d = tor_parse_long(smartlist_get(items,1), 10, 1, 28, &ok, NULL);
176 if (!ok) {
177 log_warn(LD_CONFIG, "Monthly accounting must begin on a day between "
178 "1 and 28");
179 goto err;
181 break;
182 case UNIT_DAY:
183 d = 0;
184 break;
185 default:
186 tor_assert(0);
189 idx = unit==UNIT_DAY?1:2;
190 if (smartlist_len(items) != (idx+1)) {
191 log_warn(LD_CONFIG,"Accounting unit '%s' requires %d argument%s.",
192 s, idx, (idx>1)?"s":"");
193 goto err;
195 s = smartlist_get(items, idx);
196 h = tor_parse_long(s, 10, 0, 23, &ok, &cp);
197 if (!ok) {
198 log_warn(LD_CONFIG,"Accounting start time not parseable: bad hour.");
199 goto err;
201 if (!cp || *cp!=':') {
202 log_warn(LD_CONFIG,
203 "Accounting start time not parseable: not in HH:MM format");
204 goto err;
206 m = tor_parse_long(cp+1, 10, 0, 59, &ok, &cp);
207 if (!ok) {
208 log_warn(LD_CONFIG, "Accounting start time not parseable: bad minute");
209 goto err;
211 if (!cp || *cp!='\0') {
212 log_warn(LD_CONFIG,
213 "Accounting start time not parseable: not in HH:MM format");
214 goto err;
217 if (!validate_only) {
218 cfg_unit = unit;
219 cfg_start_day = (int)d;
220 cfg_start_hour = (int)h;
221 cfg_start_min = (int)m;
223 SMARTLIST_FOREACH(items, char *, item, tor_free(item));
224 smartlist_free(items);
225 return 0;
226 err:
227 SMARTLIST_FOREACH(items, char *, item, tor_free(item));
228 smartlist_free(items);
229 return -1;
232 /** If we want to manage the accounting system and potentially
233 * hibernate, return 1, else return 0.
236 accounting_is_enabled(or_options_t *options)
238 if (options->AccountingMax)
239 return 1;
240 return 0;
243 /** Called from main.c to tell us that <b>seconds</b> seconds have
244 * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
245 * bytes have been written. */
246 void
247 accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
249 n_bytes_read_in_interval += n_read;
250 n_bytes_written_in_interval += n_written;
251 /* If we haven't been called in 10 seconds, we're probably jumping
252 * around in time. */
253 n_seconds_active_in_interval += (seconds < 10) ? seconds : 0;
256 /** If get_end, return the end of the accounting period that contains
257 * the time <b>now</b>. Else, return the start of the accounting
258 * period that contains the time <b>now</b> */
259 static time_t
260 edge_of_accounting_period_containing(time_t now, int get_end)
262 int before;
263 struct tm tm;
264 tor_localtime_r(&now, &tm);
266 /* Set 'before' to true iff the current time is before the hh:mm
267 * changeover time for today. */
268 before = tm.tm_hour < cfg_start_hour ||
269 (tm.tm_hour == cfg_start_hour && tm.tm_min < cfg_start_min);
271 /* Dispatch by unit. First, find the start day of the given period;
272 * then, if get_end is true, increment to the end day. */
273 switch (cfg_unit)
275 case UNIT_MONTH: {
276 /* If this is before the Nth, we want the Nth of last month. */
277 if (tm.tm_mday < cfg_start_day ||
278 (tm.tm_mday < cfg_start_day && before)) {
279 --tm.tm_mon;
281 /* Otherwise, the month is correct. */
282 tm.tm_mday = cfg_start_day;
283 if (get_end)
284 ++tm.tm_mon;
285 break;
287 case UNIT_WEEK: {
288 /* What is the 'target' day of the week in struct tm format? (We
289 say Sunday==7; struct tm says Sunday==0.) */
290 int wday = cfg_start_day % 7;
291 /* How many days do we subtract from today to get to the right day? */
292 int delta = (7+tm.tm_wday-wday)%7;
293 /* If we are on the right day, but the changeover hasn't happened yet,
294 * then subtract a whole week. */
295 if (delta == 0 && before)
296 delta = 7;
297 tm.tm_mday -= delta;
298 if (get_end)
299 tm.tm_mday += 7;
300 break;
302 case UNIT_DAY:
303 if (before)
304 --tm.tm_mday;
305 if (get_end)
306 ++tm.tm_mday;
307 break;
308 default:
309 tor_assert(0);
312 tm.tm_hour = cfg_start_hour;
313 tm.tm_min = cfg_start_min;
314 tm.tm_sec = 0;
315 tm.tm_isdst = -1; /* Autodetect DST */
316 return mktime(&tm);
319 /** Return the start of the accounting period containing the time
320 * <b>now</b>. */
321 static time_t
322 start_of_accounting_period_containing(time_t now)
324 return edge_of_accounting_period_containing(now, 0);
327 /** Return the start of the accounting period that comes after the one
328 * containing the time <b>now</b>. */
329 static time_t
330 start_of_accounting_period_after(time_t now)
332 return edge_of_accounting_period_containing(now, 1);
335 /** Initialize the accounting subsystem. */
336 void
337 configure_accounting(time_t now)
339 /* Try to remember our recorded usage. */
340 if (!interval_start_time)
341 read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
342 * reset below.*/
343 if (!interval_start_time ||
344 start_of_accounting_period_after(interval_start_time) <= now) {
345 /* We didn't have recorded usage, or we don't have recorded usage
346 * for this interval. Start a new interval. */
347 log_info(LD_ACCT, "Starting new accounting interval.");
348 reset_accounting(now);
349 } else if (interval_start_time ==
350 start_of_accounting_period_containing(interval_start_time)) {
351 log_info(LD_ACCT, "Continuing accounting interval.");
352 /* We are in the interval we thought we were in. Do nothing.*/
353 interval_end_time = start_of_accounting_period_after(interval_start_time);
354 } else {
355 log_warn(LD_ACCT,
356 "Mismatched accounting interval; starting a fresh one.");
357 reset_accounting(now);
359 accounting_set_wakeup_time();
362 /** Set expected_bandwidth_usage based on how much we sent/received
363 * per minute last interval (if we were up for at least 30 minutes),
364 * or based on our declared bandwidth otherwise. */
365 static void
366 update_expected_bandwidth(void)
368 uint64_t used, expected;
369 uint64_t max_configured = (get_options()->BandwidthRate * 60);
371 if (n_seconds_active_in_interval < 1800) {
372 /* If we haven't gotten enough data last interval, set 'expected'
373 * to 0. This will set our wakeup to the start of the interval.
374 * Next interval, we'll choose our starting time based on how much
375 * we sent this interval.
377 expected = 0;
378 } else {
379 used = n_bytes_written_in_interval < n_bytes_read_in_interval ?
380 n_bytes_read_in_interval : n_bytes_written_in_interval;
381 expected = used / (n_seconds_active_in_interval / 60);
382 if (expected > max_configured)
383 expected = max_configured;
385 expected_bandwidth_usage = expected;
388 /** Called at the start of a new accounting interval: reset our
389 * expected bandwidth usage based on what happened last time, set up
390 * the start and end of the interval, and clear byte/time totals.
392 static void
393 reset_accounting(time_t now)
395 log_info(LD_ACCT, "Starting new accounting interval.");
396 update_expected_bandwidth();
397 interval_start_time = start_of_accounting_period_containing(now);
398 interval_end_time = start_of_accounting_period_after(interval_start_time);
399 n_bytes_read_in_interval = 0;
400 n_bytes_written_in_interval = 0;
401 n_seconds_active_in_interval = 0;
404 /** Return true iff we should save our bandwidth usage to disk. */
405 static INLINE int
406 time_to_record_bandwidth_usage(time_t now)
408 /* Note every 600 sec */
409 #define NOTE_INTERVAL (600)
410 /* Or every 20 megabytes */
411 #define NOTE_BYTES 20*(1024*1024)
412 static uint64_t last_read_bytes_noted = 0;
413 static uint64_t last_written_bytes_noted = 0;
414 static time_t last_time_noted = 0;
416 if (last_time_noted + NOTE_INTERVAL <= now ||
417 last_read_bytes_noted + NOTE_BYTES <= n_bytes_read_in_interval ||
418 last_written_bytes_noted + NOTE_BYTES <= n_bytes_written_in_interval ||
419 (interval_end_time && interval_end_time <= now)) {
420 last_time_noted = now;
421 last_read_bytes_noted = n_bytes_read_in_interval;
422 last_written_bytes_noted = n_bytes_written_in_interval;
423 return 1;
425 return 0;
428 /** Invoked once per second. Checks whether it is time to hibernate,
429 * record bandwidth used, etc. */
430 void
431 accounting_run_housekeeping(time_t now)
433 if (now >= interval_end_time) {
434 configure_accounting(now);
436 if (time_to_record_bandwidth_usage(now)) {
437 if (accounting_record_bandwidth_usage(now, get_or_state())) {
438 log_warn(LD_FS, "Couldn't record bandwidth usage to disk.");
443 /** When we have no idea how fast we are, how long do we assume it will take
444 * us to exhaust our bandwidth? */
445 #define GUESS_TIME_TO_USE_BANDWIDTH (24*60*60)
447 /** Based on our interval and our estimated bandwidth, choose a
448 * deterministic (but random-ish) time to wake up. */
449 static void
450 accounting_set_wakeup_time(void)
452 char buf[ISO_TIME_LEN+1];
453 char digest[DIGEST_LEN];
454 crypto_digest_env_t *d_env;
455 int time_in_interval;
456 uint64_t time_to_exhaust_bw;
457 int time_to_consider;
459 if (! identity_key_is_set()) {
460 if (init_keys() < 0) {
461 log_err(LD_BUG, "Error initializing keys");
462 tor_assert(0);
466 format_iso_time(buf, interval_start_time);
467 crypto_pk_get_digest(get_identity_key(), digest);
469 d_env = crypto_new_digest_env();
470 crypto_digest_add_bytes(d_env, buf, ISO_TIME_LEN);
471 crypto_digest_add_bytes(d_env, digest, DIGEST_LEN);
472 crypto_digest_get_digest(d_env, digest, DIGEST_LEN);
473 crypto_free_digest_env(d_env);
475 if (!expected_bandwidth_usage) {
476 char buf1[ISO_TIME_LEN+1];
477 char buf2[ISO_TIME_LEN+1];
478 format_local_iso_time(buf1, interval_start_time);
479 format_local_iso_time(buf2, interval_end_time);
480 time_to_exhaust_bw = GUESS_TIME_TO_USE_BANDWIDTH;
481 interval_wakeup_time = interval_start_time;
483 log_notice(LD_ACCT,
484 "Configured hibernation. This interval begins at %s "
485 "and ends at %s. We have no prior estimate for bandwidth, so "
486 "we will start out awake and hibernate when we exhaust our quota.",
487 buf1, buf2);
488 return;
491 time_in_interval = (int)(interval_end_time - interval_start_time);
493 time_to_exhaust_bw =
494 (get_options()->AccountingMax/expected_bandwidth_usage)*60;
495 if (time_to_exhaust_bw > TIME_MAX) {
496 time_to_exhaust_bw = TIME_MAX;
497 time_to_consider = 0;
498 } else {
499 time_to_consider = time_in_interval - (int)time_to_exhaust_bw;
502 if (time_to_consider<=0) {
503 interval_wakeup_time = interval_start_time;
504 } else {
505 /* XXX can we simplify this just by picking a random (non-deterministic)
506 * time to be up? If we go down and come up, then we pick a new one. Is
507 * that good enough? -RD */
509 /* This is not a perfectly unbiased conversion, but it is good enough:
510 * in the worst case, the first half of the day is 0.06 percent likelier
511 * to be chosen than the last half. */
512 interval_wakeup_time = interval_start_time +
513 (get_uint32(digest) % time_to_consider);
515 format_iso_time(buf, interval_wakeup_time);
519 char buf1[ISO_TIME_LEN+1];
520 char buf2[ISO_TIME_LEN+1];
521 char buf3[ISO_TIME_LEN+1];
522 char buf4[ISO_TIME_LEN+1];
523 time_t down_time;
524 if (interval_wakeup_time+time_to_exhaust_bw > TIME_MAX)
525 down_time = TIME_MAX;
526 else
527 down_time = (time_t)(interval_wakeup_time+time_to_exhaust_bw);
528 if (down_time>interval_end_time)
529 down_time = interval_end_time;
530 format_local_iso_time(buf1, interval_start_time);
531 format_local_iso_time(buf2, interval_wakeup_time);
532 format_local_iso_time(buf3, down_time);
533 format_local_iso_time(buf4, interval_end_time);
535 log_notice(LD_ACCT,
536 "Configured hibernation. This interval began at %s; "
537 "the scheduled wake-up time %s %s; "
538 "we expect%s to exhaust our quota for this interval around %s; "
539 "the next interval begins at %s (all times local)",
540 buf1,
541 time(NULL)<interval_wakeup_time?"is":"was", buf2,
542 time(NULL)<down_time?"":"ed", buf3,
543 buf4);
547 /* This rounds 0 up to 1000, but that's actually a feature. */
548 #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
549 /** Save all our bandwidth tracking information to disk. Return 0 on
550 * success, -1 on failure. */
552 accounting_record_bandwidth_usage(time_t now, or_state_t *state)
554 /* Just update the state */
555 state->AccountingIntervalStart = interval_start_time;
556 state->AccountingBytesReadInInterval = ROUND_UP(n_bytes_read_in_interval);
557 state->AccountingBytesWrittenInInterval =
558 ROUND_UP(n_bytes_written_in_interval);
559 state->AccountingSecondsActive = n_seconds_active_in_interval;
560 state->AccountingExpectedUsage = expected_bandwidth_usage;
562 or_state_mark_dirty(state,
563 now+(get_options()->AvoidDiskWrites ? 7200 : 60));
565 return 0;
567 #undef ROUND_UP
569 /** Read stored accounting information from disk. Return 0 on success;
570 * return -1 and change nothing on failure. */
571 static int
572 read_bandwidth_usage(void)
574 or_state_t *state = get_or_state();
577 char *fname = get_datadir_fname("bw_accounting");
578 unlink(fname);
579 tor_free(fname);
582 if (!state)
583 return -1;
585 /* Okay; it looks like the state file is more up-to-date than the
586 * bw_accounting file, or the bw_accounting file is nonexistent,
587 * or the bw_accounting file is corrupt.
589 log_info(LD_ACCT, "Reading bandwidth accounting data from state file");
590 n_bytes_read_in_interval = state->AccountingBytesReadInInterval;
591 n_bytes_written_in_interval = state->AccountingBytesWrittenInInterval;
592 n_seconds_active_in_interval = state->AccountingSecondsActive;
593 interval_start_time = state->AccountingIntervalStart;
594 expected_bandwidth_usage = state->AccountingExpectedUsage;
597 char tbuf1[ISO_TIME_LEN+1];
598 char tbuf2[ISO_TIME_LEN+1];
599 format_iso_time(tbuf1, state->LastWritten);
600 format_iso_time(tbuf2, state->AccountingIntervalStart);
602 log_info(LD_ACCT,
603 "Successfully read bandwidth accounting info from state written at %s "
604 "for interval starting at %s. We have been active for %lu seconds in "
605 "this interval. At the start of the interval, we expected to use "
606 "about %lu KB per second. ("U64_FORMAT" bytes read so far, "
607 U64_FORMAT" bytes written so far)",
608 tbuf1, tbuf2,
609 (unsigned long)n_seconds_active_in_interval,
610 (unsigned long)(expected_bandwidth_usage*1024/60),
611 U64_PRINTF_ARG(n_bytes_read_in_interval),
612 U64_PRINTF_ARG(n_bytes_written_in_interval));
615 return 0;
618 /** Return true iff we have sent/received all the bytes we are willing
619 * to send/receive this interval. */
620 static int
621 hibernate_hard_limit_reached(void)
623 uint64_t hard_limit = get_options()->AccountingMax;
624 if (!hard_limit)
625 return 0;
626 return n_bytes_read_in_interval >= hard_limit
627 || n_bytes_written_in_interval >= hard_limit;
630 /** Return true iff we have sent/received almost all the bytes we are willing
631 * to send/receive this interval. */
632 static int
633 hibernate_soft_limit_reached(void)
635 uint64_t soft_limit = DBL_TO_U64(U64_TO_DBL(get_options()->AccountingMax)
636 * .95);
637 if (!soft_limit)
638 return 0;
639 return n_bytes_read_in_interval >= soft_limit
640 || n_bytes_written_in_interval >= soft_limit;
643 /** Called when we get a SIGINT, or when bandwidth soft limit is
644 * reached. Puts us into "loose hibernation": we don't accept new
645 * connections, but we continue handling old ones. */
646 static void
647 hibernate_begin(hibernate_state_t new_state, time_t now)
649 connection_t *conn;
650 or_options_t *options = get_options();
652 if (new_state == HIBERNATE_STATE_EXITING &&
653 hibernate_state != HIBERNATE_STATE_LIVE) {
654 log_notice(LD_GENERAL,"SIGINT received %s; exiting now.",
655 hibernate_state == HIBERNATE_STATE_EXITING ?
656 "a second time" : "while hibernating");
657 tor_cleanup();
658 exit(0);
661 /* close listeners. leave control listener(s). */
662 while ((conn = connection_get_by_type(CONN_TYPE_OR_LISTENER)) ||
663 (conn = connection_get_by_type(CONN_TYPE_AP_LISTENER)) ||
664 (conn = connection_get_by_type(CONN_TYPE_AP_TRANS_LISTENER)) ||
665 (conn = connection_get_by_type(CONN_TYPE_AP_DNS_LISTENER)) ||
666 (conn = connection_get_by_type(CONN_TYPE_AP_NATD_LISTENER)) ||
667 (conn = connection_get_by_type(CONN_TYPE_DIR_LISTENER))) {
668 log_info(LD_NET,"Closing listener type %d", conn->type);
669 connection_mark_for_close(conn);
672 /* XXX kill intro point circs */
673 /* XXX upload rendezvous service descriptors with no intro points */
675 if (new_state == HIBERNATE_STATE_EXITING) {
676 log_notice(LD_GENERAL,"Interrupt: will shut down in %d seconds. Interrupt "
677 "again to exit now.", options->ShutdownWaitLength);
678 shutdown_time = time(NULL) + options->ShutdownWaitLength;
679 } else { /* soft limit reached */
680 hibernate_end_time = interval_end_time;
683 hibernate_state = new_state;
684 accounting_record_bandwidth_usage(now, get_or_state());
686 or_state_mark_dirty(get_or_state(),
687 get_options()->AvoidDiskWrites ? now+600 : 0);
690 /** Called when we've been hibernating and our timeout is reached. */
691 static void
692 hibernate_end(hibernate_state_t new_state)
694 tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
695 hibernate_state == HIBERNATE_STATE_DORMANT);
697 /* listeners will be relaunched in run_scheduled_events() in main.c */
698 log_notice(LD_ACCT,"Hibernation period ended. Resuming normal activity.");
700 hibernate_state = new_state;
701 hibernate_end_time = 0; /* no longer hibernating */
702 stats_n_seconds_working = 0; /* reset published uptime */
705 /** A wrapper around hibernate_begin, for when we get SIGINT. */
706 void
707 hibernate_begin_shutdown(void)
709 hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
712 /** Return true iff we are currently hibernating. */
714 we_are_hibernating(void)
716 return hibernate_state != HIBERNATE_STATE_LIVE;
719 /** If we aren't currently dormant, close all connections and become
720 * dormant. */
721 static void
722 hibernate_go_dormant(time_t now)
724 connection_t *conn;
726 if (hibernate_state == HIBERNATE_STATE_DORMANT)
727 return;
728 else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
729 hibernate_state = HIBERNATE_STATE_DORMANT;
730 else
731 hibernate_begin(HIBERNATE_STATE_DORMANT, now);
733 log_notice(LD_ACCT,"Going dormant. Blowing away remaining connections.");
735 /* Close all OR/AP/exit conns. Leave dir conns because we still want
736 * to be able to upload server descriptors so people know we're still
737 * running, and download directories so we can detect if we're obsolete.
738 * Leave control conns because we still want to be controllable.
740 while ((conn = connection_get_by_type(CONN_TYPE_OR)) ||
741 (conn = connection_get_by_type(CONN_TYPE_AP)) ||
742 (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
743 if (CONN_IS_EDGE(conn))
744 connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_HIBERNATING);
745 log_info(LD_NET,"Closing conn type %d", conn->type);
746 if (conn->type == CONN_TYPE_AP) /* send socks failure if needed */
747 connection_mark_unattached_ap(TO_EDGE_CONN(conn),
748 END_STREAM_REASON_HIBERNATING);
749 else
750 connection_mark_for_close(conn);
753 if (now < interval_wakeup_time)
754 hibernate_end_time = interval_wakeup_time;
755 else
756 hibernate_end_time = interval_end_time;
758 accounting_record_bandwidth_usage(now, get_or_state());
760 or_state_mark_dirty(get_or_state(),
761 get_options()->AvoidDiskWrites ? now+600 : 0);
764 /** Called when hibernate_end_time has arrived. */
765 static void
766 hibernate_end_time_elapsed(time_t now)
768 char buf[ISO_TIME_LEN+1];
770 /* The interval has ended, or it is wakeup time. Find out which. */
771 accounting_run_housekeeping(now);
772 if (interval_wakeup_time <= now) {
773 /* The interval hasn't changed, but interval_wakeup_time has passed.
774 * It's time to wake up and start being a server. */
775 hibernate_end(HIBERNATE_STATE_LIVE);
776 return;
777 } else {
778 /* The interval has changed, and it isn't time to wake up yet. */
779 hibernate_end_time = interval_wakeup_time;
780 format_iso_time(buf,interval_wakeup_time);
781 if (hibernate_state != HIBERNATE_STATE_DORMANT) {
782 /* We weren't sleeping before; we should sleep now. */
783 log_notice(LD_ACCT,
784 "Accounting period ended. Commencing hibernation until "
785 "%s GMT", buf);
786 hibernate_go_dormant(now);
787 } else {
788 log_notice(LD_ACCT,
789 "Accounting period ended. This period, we will hibernate"
790 " until %s GMT",buf);
795 /** Consider our environment and decide if it's time
796 * to start/stop hibernating.
798 void
799 consider_hibernation(time_t now)
801 int accounting_enabled = get_options()->AccountingMax != 0;
802 char buf[ISO_TIME_LEN+1];
804 /* If we're in 'exiting' mode, then we just shut down after the interval
805 * elapses. */
806 if (hibernate_state == HIBERNATE_STATE_EXITING) {
807 tor_assert(shutdown_time);
808 if (shutdown_time <= now) {
809 log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
810 tor_cleanup();
811 exit(0);
813 return; /* if exiting soon, don't worry about bandwidth limits */
816 if (hibernate_state == HIBERNATE_STATE_DORMANT) {
817 /* We've been hibernating because of bandwidth accounting. */
818 tor_assert(hibernate_end_time);
819 if (hibernate_end_time > now && accounting_enabled) {
820 /* If we're hibernating, don't wake up until it's time, regardless of
821 * whether we're in a new interval. */
822 return ;
823 } else {
824 hibernate_end_time_elapsed(now);
828 /* Else, we aren't hibernating. See if it's time to start hibernating, or to
829 * go dormant. */
830 if (hibernate_state == HIBERNATE_STATE_LIVE) {
831 if (hibernate_soft_limit_reached()) {
832 log_notice(LD_ACCT,
833 "Bandwidth soft limit reached; commencing hibernation.");
834 hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
835 } else if (accounting_enabled && now < interval_wakeup_time) {
836 format_local_iso_time(buf,interval_wakeup_time);
837 log_notice(LD_ACCT,
838 "Commencing hibernation. We will wake up at %s local time.",
839 buf);
840 hibernate_go_dormant(now);
844 if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
845 if (!accounting_enabled) {
846 hibernate_end_time_elapsed(now);
847 } else if (hibernate_hard_limit_reached()) {
848 hibernate_go_dormant(now);
849 } else if (hibernate_end_time <= now) {
850 /* The hibernation period ended while we were still in lowbandwidth.*/
851 hibernate_end_time_elapsed(now);
856 /** Helper function: called when we get a GETINFO request for an
857 * accounting-related key on the control connection <b>conn</b>. If we can
858 * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
859 * allocated string holding the result. Otherwise, set *<b>answer</b> to
860 * NULL. */
862 getinfo_helper_accounting(control_connection_t *conn,
863 const char *question, char **answer)
865 (void) conn;
866 if (!strcmp(question, "accounting/enabled")) {
867 *answer = tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
868 } else if (!strcmp(question, "accounting/hibernating")) {
869 if (hibernate_state == HIBERNATE_STATE_DORMANT)
870 *answer = tor_strdup("hard");
871 else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
872 *answer = tor_strdup("soft");
873 else
874 *answer = tor_strdup("awake");
875 } else if (!strcmp(question, "accounting/bytes")) {
876 *answer = tor_malloc(32);
877 tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
878 U64_PRINTF_ARG(n_bytes_read_in_interval),
879 U64_PRINTF_ARG(n_bytes_written_in_interval));
880 } else if (!strcmp(question, "accounting/bytes-left")) {
881 uint64_t limit = get_options()->AccountingMax;
882 uint64_t read_left = 0, write_left = 0;
883 if (n_bytes_read_in_interval < limit)
884 read_left = limit - n_bytes_read_in_interval;
885 if (n_bytes_written_in_interval < limit)
886 write_left = limit - n_bytes_written_in_interval;
887 *answer = tor_malloc(64);
888 tor_snprintf(*answer, 64, U64_FORMAT" "U64_FORMAT,
889 U64_PRINTF_ARG(read_left), U64_PRINTF_ARG(write_left));
890 } else if (!strcmp(question, "accounting/interval-start")) {
891 *answer = tor_malloc(ISO_TIME_LEN+1);
892 format_iso_time(*answer, interval_start_time);
893 } else if (!strcmp(question, "accounting/interval-wake")) {
894 *answer = tor_malloc(ISO_TIME_LEN+1);
895 format_iso_time(*answer, interval_wakeup_time);
896 } else if (!strcmp(question, "accounting/interval-end")) {
897 *answer = tor_malloc(ISO_TIME_LEN+1);
898 format_iso_time(*answer, interval_end_time);
899 } else {
900 *answer = NULL;
902 return 0;