Add some "to-be-safe" escaped() wrappers to log statements in rend*.c, though I am...
[tor.git] / src / or / hibernate.c
blobffd06a96b3d7285425a7bb61c9fd02ee6a66047b
1 /* Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
4 const char hibernate_c_id[] =
5 "$Id$";
7 /**
8 * \file hibernate.c
9 * \brief Functions to close listeners, stop allowing new circuits,
10 * etc in preparation for closing down or going dormant; and to track
11 * bandwidth and time intervals to know when to hibernate and when to
12 * stop hibernating.
13 **/
16 hibernating, phase 1:
17 - send destroy in response to create cells
18 - send end (policy failed) in response to begin cells
19 - close an OR conn when it has no circuits
21 hibernating, phase 2:
22 (entered when bandwidth hard limit reached)
23 - close all OR/AP/exit conns)
26 #include "or.h"
28 #define HIBERNATE_STATE_LIVE 1
29 #define HIBERNATE_STATE_EXITING 2
30 #define HIBERNATE_STATE_LOWBANDWIDTH 3
31 #define HIBERNATE_STATE_DORMANT 4
33 extern long stats_n_seconds_working; /* published uptime */
35 static int hibernate_state = HIBERNATE_STATE_LIVE;
36 /** If are hibernating, when do we plan to wake up? Set to 0 if we
37 * aren't hibernating. */
38 static time_t hibernate_end_time = 0;
40 typedef enum {
41 UNIT_MONTH=1, UNIT_WEEK=2, UNIT_DAY=3,
42 } time_unit_t;
44 /* Fields for accounting logic. Accounting overview:
46 * Accounting is designed to ensure that no more than N bytes are sent
47 * in either direction over a given interval (currently, one month,
48 * starting at 0:00 GMT an arbitrary day within the month). We could
49 * try to do this by choking our bandwidth to a trickle, but that
50 * would make our streams useless. Instead, we estimate what our
51 * bandwidth usage will be, and guess how long we'll be able to
52 * provide that much bandwidth before hitting our limit. We then
53 * choose a random time within the accounting interval to come up (so
54 * that we don't get 50 Tors running on the 1st of the month and none
55 * on the 30th).
57 * Each interval runs as follows:
59 * 1. We guess our bandwidth usage, based on how much we used
60 * last time. We choose a "wakeup time" within the interval to come up.
61 * 2. Until the chosen wakeup time, we hibernate.
62 * 3. We come up at the wakeup time, and provide bandwidth until we are
63 * "very close" to running out.
64 * 4. Then we go into low-bandwidth mode, and stop accepting new
65 * connections, but provide bandwidth until we run out.
66 * 5. Then we hibernate until the end of the interval.
68 * If the interval ends before we run out of bandwidth, we go back to
69 * step one.
72 /** How many bytes have we read/written in this accounting interval? */
73 static uint64_t n_bytes_read_in_interval = 0;
74 static uint64_t n_bytes_written_in_interval = 0;
75 /** How many seconds have we been running this interval? */
76 static uint32_t n_seconds_active_in_interval = 0;
77 /** When did this accounting interval start? */
78 static time_t interval_start_time = 0;
79 /** When will this accounting interval end? */
80 static time_t interval_end_time = 0;
81 /** How far into the accounting interval should we hibernate? */
82 static time_t interval_wakeup_time = 0;
83 /** How much bandwidth do we 'expect' to use per minute? (0 if we have no
84 * info from the last period.) */
85 static uint32_t expected_bandwidth_usage = 0;
86 /** What unit are we using for our accounting? */
87 static time_unit_t cfg_unit = UNIT_MONTH;
88 /** How many days,hours,minutes into each unit does our accounting interval
89 * start? */
90 static int cfg_start_day = 0;
91 static int cfg_start_hour = 0;
92 static int cfg_start_min = 0;
94 static void reset_accounting(time_t now);
95 static int read_bandwidth_usage(void);
96 static time_t start_of_accounting_period_after(time_t now);
97 static time_t start_of_accounting_period_containing(time_t now);
98 static void accounting_set_wakeup_time(void);
100 /* ************
101 * Functions for bandwidth accounting.
102 * ************/
104 /** Configure accounting start/end time settings based on
105 * options->AccountingStart. Return 0 on success, -1 on failure. If
106 * <b>validate_only</b> is true, do not change the current settings. */
108 accounting_parse_options(or_options_t *options, int validate_only)
110 time_unit_t unit;
111 int ok, idx;
112 long d,h,m;
113 smartlist_t *items;
114 const char *v = options->AccountingStart;
115 const char *s;
116 char *cp;
118 if (!v) {
119 if (!validate_only) {
120 cfg_unit = UNIT_MONTH;
121 cfg_start_day = 1;
122 cfg_start_hour = 0;
123 cfg_start_min = 0;
125 return 0;
128 items = smartlist_create();
129 smartlist_split_string(items, v, NULL,
130 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
131 if (smartlist_len(items)<2) {
132 log_warn(LD_CONFIG, "Too few arguments to AccountingStart");
133 goto err;
135 s = smartlist_get(items,0);
136 if (0==strcasecmp(s, "month")) {
137 unit = UNIT_MONTH;
138 } else if (0==strcasecmp(s, "week")) {
139 unit = UNIT_WEEK;
140 } else if (0==strcasecmp(s, "day")) {
141 unit = UNIT_DAY;
142 } else {
143 log_warn(LD_CONFIG,
144 "Unrecognized accounting unit '%s': only 'month', 'week',"
145 " and 'day' are supported.", s);
146 goto err;
149 switch (unit) {
150 case UNIT_WEEK:
151 d = tor_parse_long(smartlist_get(items,1), 10, 1, 7, &ok, NULL);
152 if (!ok) {
153 log_warn(LD_CONFIG, "Weekly accounting must begin on a day between "
154 "1 (Monday) and 7 (Sunday)");
155 goto err;
157 break;
158 case UNIT_MONTH:
159 d = tor_parse_long(smartlist_get(items,1), 10, 1, 28, &ok, NULL);
160 if (!ok) {
161 log_warn(LD_CONFIG, "Monthly accounting must begin on a day between "
162 "1 and 28");
163 goto err;
165 break;
166 case UNIT_DAY:
167 d = 0;
168 break;
169 default:
170 tor_assert(0);
173 idx = unit==UNIT_DAY?1:2;
174 if (smartlist_len(items) != (idx+1)) {
175 log_warn(LD_CONFIG,"Accounting unit '%s' requires %d argument%s.",
176 s, idx, (idx>1)?"s":"");
177 goto err;
179 s = smartlist_get(items, idx);
180 h = tor_parse_long(s, 10, 0, 23, &ok, &cp);
181 if (!ok) {
182 log_warn(LD_CONFIG,"Accounting start time not parseable: bad hour.");
183 goto err;
185 if (!cp || *cp!=':') {
186 log_warn(LD_CONFIG,
187 "Accounting start time not parseable: not in HH:MM format");
188 goto err;
190 m = tor_parse_long(cp+1, 10, 0, 59, &ok, &cp);
191 if (!ok) {
192 log_warn(LD_CONFIG, "Accounting start time not parseable: bad minute");
193 goto err;
195 if (!cp || *cp!='\0') {
196 log_warn(LD_CONFIG,
197 "Accounting start time not parseable: not in HH:MM format");
198 goto err;
201 if (!validate_only) {
202 cfg_unit = unit;
203 cfg_start_day = (int)d;
204 cfg_start_hour = (int)h;
205 cfg_start_min = (int)m;
207 SMARTLIST_FOREACH(items, char *, s, tor_free(s));
208 smartlist_free(items);
209 return 0;
210 err:
211 SMARTLIST_FOREACH(items, char *, s, tor_free(s));
212 smartlist_free(items);
213 return -1;
216 /** If we want to manage the accounting system and potentially
217 * hibernate, return 1, else return 0.
220 accounting_is_enabled(or_options_t *options)
222 if (options->AccountingMax)
223 return 1;
224 return 0;
227 /** Called from main.c to tell us that <b>seconds</b> seconds have
228 * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
229 * bytes have been written. */
230 void
231 accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
233 n_bytes_read_in_interval += n_read;
234 n_bytes_written_in_interval += n_written;
235 /* If we haven't been called in 10 seconds, we're probably jumping
236 * around in time. */
237 n_seconds_active_in_interval += (seconds < 10) ? seconds : 0;
240 /** If get_end, return the end of the accounting period that contains
241 * the time <b>now</b>. Else, return the start of the accounting
242 * period that contains the time <b>now</b> */
243 static time_t
244 edge_of_accounting_period_containing(time_t now, int get_end)
246 int before;
247 struct tm tm;
248 tor_localtime_r(&now, &tm);
250 /* Set 'before' to true iff the current time is before the hh:mm
251 * changeover time for today. */
252 before = tm.tm_hour < cfg_start_hour ||
253 (tm.tm_hour == cfg_start_hour && tm.tm_min < cfg_start_min);
255 /* Dispatch by unit. First, find the start day of the given period;
256 * then, if get_end is true, increment to the end day. */
257 switch (cfg_unit)
259 case UNIT_MONTH: {
260 /* If this is before the Nth, we want the Nth of last month. */
261 if (tm.tm_mday < cfg_start_day ||
262 (tm.tm_mday < cfg_start_day && before)) {
263 --tm.tm_mon;
265 /* Otherwise, the month is correct. */
266 tm.tm_mday = cfg_start_day;
267 if (get_end)
268 ++tm.tm_mon;
269 break;
271 case UNIT_WEEK: {
272 /* What is the 'target' day of the week in struct tm format? (We
273 say Sunday==7; struct tm says Sunday==0.) */
274 int wday = cfg_start_day % 7;
275 /* How many days do we subtract from today to get to the right day? */
276 int delta = (7+tm.tm_wday-wday)%7;
277 /* If we are on the right day, but the changeover hasn't happened yet,
278 * then subtract a whole week. */
279 if (delta == 0 && before)
280 delta = 7;
281 tm.tm_mday -= delta;
282 if (get_end)
283 tm.tm_mday += 7;
284 break;
286 case UNIT_DAY:
287 if (before)
288 --tm.tm_mday;
289 if (get_end)
290 ++tm.tm_mday;
291 break;
292 default:
293 tor_assert(0);
296 tm.tm_hour = cfg_start_hour;
297 tm.tm_min = cfg_start_min;
298 tm.tm_sec = 0;
299 tm.tm_isdst = -1; /* Autodetect DST */
300 return mktime(&tm);
303 /** Return the start of the accounting period containing the time
304 * <b>now</b>. */
305 static time_t
306 start_of_accounting_period_containing(time_t now)
308 return edge_of_accounting_period_containing(now, 0);
311 /** Return the start of the accounting period that comes after the one
312 * containing the time <b>now</b>. */
313 static time_t
314 start_of_accounting_period_after(time_t now)
316 return edge_of_accounting_period_containing(now, 1);
319 /** Initialize the accounting subsystem. */
320 void
321 configure_accounting(time_t now)
323 /* Try to remember our recorded usage. */
324 if (!interval_start_time)
325 read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
326 * reset below.*/
327 if (!interval_start_time ||
328 start_of_accounting_period_after(interval_start_time) <= now) {
329 /* We didn't have recorded usage, or we don't have recorded usage
330 * for this interval. Start a new interval. */
331 log_info(LD_ACCT, "Starting new accounting interval.");
332 reset_accounting(now);
333 } else if (interval_start_time ==
334 start_of_accounting_period_containing(interval_start_time)) {
335 log_info(LD_ACCT, "Continuing accounting interval.");
336 /* We are in the interval we thought we were in. Do nothing.*/
337 interval_end_time = start_of_accounting_period_after(interval_start_time);
338 } else {
339 log_warn(LD_ACCT,
340 "Mismatched accounting interval; starting a fresh one.");
341 reset_accounting(now);
343 accounting_set_wakeup_time();
346 /** Set expected_bandwidth_usage based on how much we sent/received
347 * per minute last interval (if we were up for at least 30 minutes),
348 * or based on our declared bandwidth otherwise. */
349 static void
350 update_expected_bandwidth(void)
352 uint64_t used, expected;
353 uint64_t max_configured = (get_options()->BandwidthRate * 60);
355 if (n_seconds_active_in_interval < 1800) {
356 /* If we haven't gotten enough data last interval, set 'expected'
357 * to 0. This will set our wakeup to the start of the interval.
358 * Next interval, we'll choose our starting time based on how much
359 * we sent this interval.
361 expected = 0;
362 } else {
363 used = n_bytes_written_in_interval < n_bytes_read_in_interval ?
364 n_bytes_read_in_interval : n_bytes_written_in_interval;
365 expected = used / (n_seconds_active_in_interval / 60);
366 if (expected > max_configured)
367 expected = max_configured;
369 if (expected > UINT32_MAX)
370 expected = UINT32_MAX;
371 expected_bandwidth_usage = (uint32_t) expected;
374 /** Called at the start of a new accounting interval: reset our
375 * expected bandwidth usage based on what happened last time, set up
376 * the start and end of the interval, and clear byte/time totals.
378 static void
379 reset_accounting(time_t now)
381 log_info(LD_ACCT, "Starting new accounting interval.");
382 update_expected_bandwidth();
383 interval_start_time = start_of_accounting_period_containing(now);
384 interval_end_time = start_of_accounting_period_after(interval_start_time);
385 n_bytes_read_in_interval = 0;
386 n_bytes_written_in_interval = 0;
387 n_seconds_active_in_interval = 0;
390 /** Return true iff we should save our bandwidth usage to disk. */
391 static INLINE int
392 time_to_record_bandwidth_usage(time_t now)
394 /* Note every 60 sec */
395 #define NOTE_INTERVAL (60)
396 /* Or every 20 megabytes */
397 #define NOTE_BYTES 20*(1024*1024)
398 static uint64_t last_read_bytes_noted = 0;
399 static uint64_t last_written_bytes_noted = 0;
400 static time_t last_time_noted = 0;
402 if (last_time_noted + NOTE_INTERVAL <= now ||
403 last_read_bytes_noted + NOTE_BYTES <= n_bytes_read_in_interval ||
404 last_written_bytes_noted + NOTE_BYTES <= n_bytes_written_in_interval ||
405 (interval_end_time && interval_end_time <= now)) {
406 last_time_noted = now;
407 last_read_bytes_noted = n_bytes_read_in_interval;
408 last_written_bytes_noted = n_bytes_written_in_interval;
409 return 1;
411 return 0;
414 /** Invoked once per second. Checks whether it is time to hibernate,
415 * record bandwidth used, etc. */
416 void
417 accounting_run_housekeeping(time_t now)
419 if (now >= interval_end_time) {
420 configure_accounting(now);
422 if (time_to_record_bandwidth_usage(now)) {
423 if (accounting_record_bandwidth_usage(now)) {
424 log_err(LD_FS, "Couldn't record bandwidth usage to disk; exiting.");
425 /* This can fail when we're out of fd's, causing a crash.
426 * The current answer is to reserve 32 more than we need, in
427 * set_max_file_descriptors(). */
428 exit(1);
433 /** Based on our interval and our estimated bandwidth, choose a
434 * deterministic (but random-ish) time to wake up. */
435 static void
436 accounting_set_wakeup_time(void)
438 char buf[ISO_TIME_LEN+1];
439 char digest[DIGEST_LEN];
440 crypto_digest_env_t *d_env;
441 int time_in_interval;
442 int time_to_exhaust_bw;
443 int time_to_consider;
445 if (! identity_key_is_set()) {
446 if (init_keys() < 0) {
447 log_err(LD_BUG, "Error initializing keys");
448 tor_assert(0);
452 format_iso_time(buf, interval_start_time);
453 crypto_pk_get_digest(get_identity_key(), digest);
455 d_env = crypto_new_digest_env();
456 crypto_digest_add_bytes(d_env, buf, ISO_TIME_LEN);
457 crypto_digest_add_bytes(d_env, digest, DIGEST_LEN);
458 crypto_digest_get_digest(d_env, digest, DIGEST_LEN);
459 crypto_free_digest_env(d_env);
461 if (!expected_bandwidth_usage) {
462 char buf1[ISO_TIME_LEN+1];
463 char buf2[ISO_TIME_LEN+1];
464 format_local_iso_time(buf1, interval_start_time);
465 format_local_iso_time(buf2, interval_end_time);
466 time_to_exhaust_bw = 24*60*60;
467 interval_wakeup_time = interval_start_time;
469 log_notice(LD_ACCT,
470 "Configured hibernation. This interval begins at %s "
471 "and ends at %s. We have no prior estimate for bandwidth, so "
472 "we will start out awake and hibernate when we exhaust our quota.",
473 buf1, buf2);
474 return;
477 time_to_exhaust_bw = (int)
478 (get_options()->AccountingMax/expected_bandwidth_usage)*60;
479 time_in_interval = interval_end_time - interval_start_time;
480 time_to_consider = time_in_interval - time_to_exhaust_bw;
482 if (time_to_consider<=0) {
483 interval_wakeup_time = interval_start_time;
484 } else {
485 /* XXX can we simplify this just by picking a random (non-deterministic)
486 * time to be up? If we go down and come up, then we pick a new one. Is
487 * that good enough? -RD */
489 /* This is not a perfectly unbiased conversion, but it is good enough:
490 * in the worst case, the first half of the day is 0.06 percent likelier
491 * to be chosen than the last half. */
492 interval_wakeup_time = interval_start_time +
493 (get_uint32(digest) % time_to_consider);
495 format_iso_time(buf, interval_wakeup_time);
499 char buf1[ISO_TIME_LEN+1];
500 char buf2[ISO_TIME_LEN+1];
501 char buf3[ISO_TIME_LEN+1];
502 char buf4[ISO_TIME_LEN+1];
503 time_t down_time = interval_wakeup_time+time_to_exhaust_bw;
504 if (down_time>interval_end_time)
505 down_time = interval_end_time;
506 format_local_iso_time(buf1, interval_start_time);
507 format_local_iso_time(buf2, interval_wakeup_time);
508 format_local_iso_time(buf3,
509 down_time<interval_end_time?down_time:interval_end_time);
510 format_local_iso_time(buf4, interval_end_time);
512 log_notice(LD_ACCT,
513 "Configured hibernation. This interval began at %s; "
514 "the scheduled wake-up time %s %s; "
515 "we expect%s to exhaust our quota for this interval around %s; "
516 "the next interval begins at %s (all times local)",
517 buf1,
518 time(NULL)<interval_wakeup_time?"is":"was", buf2,
519 time(NULL)<down_time?"":"ed", buf3,
520 buf4);
524 #define BW_ACCOUNTING_VERSION 1
525 /** Save all our bandwidth tracking information to disk. Return 0 on
526 * success, -1 on failure*/
528 accounting_record_bandwidth_usage(time_t now)
530 char buf[128];
531 char fname[512];
532 char time1[ISO_TIME_LEN+1];
533 char time2[ISO_TIME_LEN+1];
534 char *cp = buf;
535 /* Format is:
536 Version\nTime\nTime\nRead\nWrite\nSeconds\nExpected-Rate\n */
538 format_iso_time(time1, interval_start_time);
539 format_iso_time(time2, now);
540 tor_snprintf(cp, sizeof(buf),
541 "%d\n%s\n%s\n"U64_FORMAT"\n"U64_FORMAT"\n%lu\n%lu\n",
542 BW_ACCOUNTING_VERSION,
543 time1,
544 time2,
545 U64_PRINTF_ARG(n_bytes_read_in_interval),
546 U64_PRINTF_ARG(n_bytes_written_in_interval),
547 (unsigned long)n_seconds_active_in_interval,
548 (unsigned long)expected_bandwidth_usage);
549 tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
550 get_options()->DataDirectory);
552 return write_str_to_file(fname, buf, 0);
555 /** Read stored accounting information from disk. Return 0 on success;
556 * return -1 and change nothing on failure. */
557 static int
558 read_bandwidth_usage(void)
560 char *s = NULL;
561 char fname[512];
562 time_t t1, t2;
563 uint64_t n_read, n_written;
564 uint32_t expected_bw, n_seconds;
565 smartlist_t *elts;
566 int ok;
568 tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
569 get_options()->DataDirectory);
570 if (!(s = read_file_to_str(fname, 0))) {
571 return 0;
573 elts = smartlist_create();
574 smartlist_split_string(elts, s, "\n", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
575 tor_free(s);
577 if (smartlist_len(elts)<1 ||
578 atoi(smartlist_get(elts,0)) != BW_ACCOUNTING_VERSION) {
579 log_warn(LD_ACCT, "Unrecognized bw_accounting file version: %s",
580 (const char*)smartlist_get(elts,0));
581 goto err;
583 if (smartlist_len(elts) < 7) {
584 log_warn(LD_ACCT, "Corrupted bw_accounting file: %d lines",
585 smartlist_len(elts));
586 goto err;
588 if (parse_iso_time(smartlist_get(elts,1), &t1)) {
589 log_warn(LD_ACCT, "Error parsing bandwidth usage start time.");
590 goto err;
592 if (parse_iso_time(smartlist_get(elts,2), &t2)) {
593 log_warn(LD_ACCT, "Error parsing bandwidth usage last-written time");
594 goto err;
596 n_read = tor_parse_uint64(smartlist_get(elts,3), 10, 0, UINT64_MAX,
597 &ok, NULL);
598 if (!ok) {
599 log_warn(LD_ACCT, "Error parsing number of bytes read");
600 goto err;
602 n_written = tor_parse_uint64(smartlist_get(elts,4), 10, 0, UINT64_MAX,
603 &ok, NULL);
604 if (!ok) {
605 log_warn(LD_ACCT, "Error parsing number of bytes read");
606 goto err;
608 n_seconds = (uint32_t)tor_parse_ulong(smartlist_get(elts,5), 10,0,ULONG_MAX,
609 &ok, NULL);
610 if (!ok) {
611 log_warn(LD_ACCT, "Error parsing number of seconds live");
612 goto err;
614 expected_bw =(uint32_t)tor_parse_ulong(smartlist_get(elts,6), 10,0,ULONG_MAX,
615 &ok, NULL);
616 if (!ok) {
617 log_warn(LD_ACCT, "Error parsing expected bandwidth");
618 goto err;
621 n_bytes_read_in_interval = n_read;
622 n_bytes_written_in_interval = n_written;
623 n_seconds_active_in_interval = n_seconds;
624 interval_start_time = t1;
625 expected_bandwidth_usage = expected_bw;
627 log_info(LD_ACCT,
628 "Successfully read bandwidth accounting file written at %s "
629 "for interval starting at %s. We have been active for %lu seconds in "
630 "this interval. At the start of the interval, we expected to use "
631 "about %lu KB per second. ("U64_FORMAT" bytes read so far, "
632 U64_FORMAT" bytes written so far)",
633 (char*)smartlist_get(elts,2),
634 (char*)smartlist_get(elts,1),
635 (unsigned long)n_seconds_active_in_interval,
636 (unsigned long)((uint64_t)expected_bandwidth_usage*1024/60),
637 U64_PRINTF_ARG(n_bytes_read_in_interval),
638 U64_PRINTF_ARG(n_bytes_written_in_interval));
639 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
640 smartlist_free(elts);
642 return 0;
643 err:
644 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
645 smartlist_free(elts);
646 return -1;
649 /** Return true iff we have sent/received all the bytes we are willing
650 * to send/receive this interval. */
651 static int
652 hibernate_hard_limit_reached(void)
654 uint64_t hard_limit = get_options()->AccountingMax;
655 if (!hard_limit)
656 return 0;
657 return n_bytes_read_in_interval >= hard_limit
658 || n_bytes_written_in_interval >= hard_limit;
661 /** Return true iff we have sent/received almost all the bytes we are willing
662 * to send/receive this interval. */
663 static int
664 hibernate_soft_limit_reached(void)
666 uint64_t soft_limit = (uint64_t) ((get_options()->AccountingMax) * .95);
667 if (!soft_limit)
668 return 0;
669 return n_bytes_read_in_interval >= soft_limit
670 || n_bytes_written_in_interval >= soft_limit;
673 /** Called when we get a SIGINT, or when bandwidth soft limit is
674 * reached. Puts us into "loose hibernation": we don't accept new
675 * connections, but we continue handling old ones. */
676 static void
677 hibernate_begin(int new_state, time_t now)
679 connection_t *conn;
680 or_options_t *options = get_options();
682 if (new_state == HIBERNATE_STATE_EXITING &&
683 hibernate_state != HIBERNATE_STATE_LIVE) {
684 log_notice(LD_GENERAL,"Sigint received %s; exiting now.",
685 hibernate_state == HIBERNATE_STATE_EXITING ?
686 "a second time" : "while hibernating");
687 tor_cleanup();
688 exit(0);
691 /* close listeners. leave control listener(s). */
692 while ((conn = connection_get_by_type(CONN_TYPE_OR_LISTENER)) ||
693 (conn = connection_get_by_type(CONN_TYPE_AP_LISTENER)) ||
694 (conn = connection_get_by_type(CONN_TYPE_DIR_LISTENER))) {
695 log_info(LD_NET,"Closing listener type %d", conn->type);
696 connection_mark_for_close(conn);
699 /* XXX kill intro point circs */
700 /* XXX upload rendezvous service descriptors with no intro points */
702 if (new_state == HIBERNATE_STATE_EXITING) {
703 log_notice(LD_GENERAL,"Interrupt: will shut down in %d seconds. Interrupt "
704 "again to exit now.", options->ShutdownWaitLength);
705 hibernate_end_time = time(NULL) + options->ShutdownWaitLength;
706 } else { /* soft limit reached */
707 hibernate_end_time = interval_end_time;
710 hibernate_state = new_state;
711 accounting_record_bandwidth_usage(now);
714 /** Called when we've been hibernating and our timeout is reached. */
715 static void
716 hibernate_end(int new_state)
718 tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
719 hibernate_state == HIBERNATE_STATE_DORMANT);
721 /* listeners will be relaunched in run_scheduled_events() in main.c */
722 log_notice(LD_ACCT,"Hibernation period ended. Resuming normal activity.");
724 hibernate_state = new_state;
725 hibernate_end_time = 0; /* no longer hibernating */
726 stats_n_seconds_working = 0; /* reset published uptime */
729 /** A wrapper around hibernate_begin, for when we get SIGINT. */
730 void
731 hibernate_begin_shutdown(void)
733 hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
736 /** Return true iff we are currently hibernating. */
738 we_are_hibernating(void)
740 return hibernate_state != HIBERNATE_STATE_LIVE;
743 /** If we aren't currently dormant, close all connections and become
744 * dormant. */
745 static void
746 hibernate_go_dormant(time_t now)
748 connection_t *conn;
750 if (hibernate_state == HIBERNATE_STATE_DORMANT)
751 return;
752 else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
753 hibernate_state = HIBERNATE_STATE_DORMANT;
754 else
755 hibernate_begin(HIBERNATE_STATE_DORMANT, now);
757 log_notice(LD_ACCT,"Going dormant. Blowing away remaining connections.");
759 /* Close all OR/AP/exit conns. Leave dir conns because we still want
760 * to be able to upload server descriptors so people know we're still
761 * running, and download directories so we can detect if we're obsolete.
762 * Leave control conns because we still want to be controllable.
764 while ((conn = connection_get_by_type(CONN_TYPE_OR)) ||
765 (conn = connection_get_by_type(CONN_TYPE_AP)) ||
766 (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
767 if (CONN_IS_EDGE(conn))
768 connection_edge_end(conn, END_STREAM_REASON_HIBERNATING,
769 conn->cpath_layer);
770 log_info(LD_NET,"Closing conn type %d", conn->type);
771 if (conn->type == CONN_TYPE_AP) /* send socks failure if needed */
772 connection_mark_unattached_ap(conn, END_STREAM_REASON_HIBERNATING);
773 else
774 connection_mark_for_close(conn);
777 accounting_record_bandwidth_usage(now);
780 /** Called when hibernate_end_time has arrived. */
781 static void
782 hibernate_end_time_elapsed(time_t now)
784 char buf[ISO_TIME_LEN+1];
786 /* The interval has ended, or it is wakeup time. Find out which. */
787 accounting_run_housekeeping(now);
788 if (interval_wakeup_time <= now) {
789 /* The interval hasn't changed, but interval_wakeup_time has passed.
790 * It's time to wake up and start being a server. */
791 hibernate_end(HIBERNATE_STATE_LIVE);
792 return;
793 } else {
794 /* The interval has changed, and it isn't time to wake up yet. */
795 hibernate_end_time = interval_wakeup_time;
796 format_iso_time(buf,interval_wakeup_time);
797 if (hibernate_state != HIBERNATE_STATE_DORMANT) {
798 /* We weren't sleeping before; we should sleep now. */
799 log_notice(LD_ACCT,
800 "Accounting period ended. Commencing hibernation until "
801 "%s GMT", buf);
802 hibernate_go_dormant(now);
803 } else {
804 log_notice(LD_ACCT,
805 "Accounting period ended. This period, we will hibernate"
806 " until %s GMT",buf);
811 /** Consider our environment and decide if it's time
812 * to start/stop hibernating.
814 void
815 consider_hibernation(time_t now)
817 int accounting_enabled = get_options()->AccountingMax != 0;
818 char buf[ISO_TIME_LEN+1];
820 /* If we're in 'exiting' mode, then we just shut down after the interval
821 * elapses. */
822 if (hibernate_state == HIBERNATE_STATE_EXITING) {
823 tor_assert(hibernate_end_time);
824 if (hibernate_end_time <= now) {
825 log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
826 tor_cleanup();
827 exit(0);
829 return; /* if exiting soon, don't worry about bandwidth limits */
832 if (hibernate_state == HIBERNATE_STATE_DORMANT) {
833 /* We've been hibernating because of bandwidth accounting. */
834 tor_assert(hibernate_end_time);
835 if (hibernate_end_time > now && accounting_enabled) {
836 /* If we're hibernating, don't wake up until it's time, regardless of
837 * whether we're in a new interval. */
838 return ;
839 } else {
840 hibernate_end_time_elapsed(now);
844 /* Else, we aren't hibernating. See if it's time to start hibernating, or to
845 * go dormant. */
846 if (hibernate_state == HIBERNATE_STATE_LIVE) {
847 if (hibernate_soft_limit_reached()) {
848 log_notice(LD_ACCT,
849 "Bandwidth soft limit reached; commencing hibernation.");
850 hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
851 } else if (accounting_enabled && now < interval_wakeup_time) {
852 format_iso_time(buf,interval_wakeup_time);
853 log_notice(LD_ACCT,
854 "Commencing hibernation. We will wake up at %s GMT", buf);
855 hibernate_go_dormant(now);
859 if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
860 if (!accounting_enabled) {
861 hibernate_end_time_elapsed(now);
862 } else if (hibernate_hard_limit_reached()) {
863 hibernate_go_dormant(now);
864 } else if (hibernate_end_time <= now) {
865 /* The hibernation period ended while we were still in lowbandwidth.*/
866 hibernate_end_time_elapsed(now);
871 /** DOCDOC */
873 accounting_getinfo_helper(const char *question, char **answer)
875 if (!strcmp(question, "accounting/enabled")) {
876 *answer = tor_strdup(get_options()->AccountingMax ? "1" : "0");
877 } else if (!strcmp(question, "accounting/hibernating")) {
878 if (hibernate_state == HIBERNATE_STATE_DORMANT)
879 *answer = tor_strdup("hard");
880 else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
881 *answer = tor_strdup("soft");
882 else
883 *answer = tor_strdup("awake");
884 } else if (!strcmp(question, "accounting/bytes")) {
885 *answer = tor_malloc(32);
886 tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
887 U64_PRINTF_ARG(n_bytes_read_in_interval),
888 U64_PRINTF_ARG(n_bytes_written_in_interval));
889 } else if (!strcmp(question, "accounting/bytes-left")) {
890 uint64_t limit = get_options()->AccountingMax;
891 *answer = tor_malloc(32);
892 tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
893 U64_PRINTF_ARG(limit - n_bytes_read_in_interval),
894 U64_PRINTF_ARG(limit - n_bytes_written_in_interval));
895 } else if (!strcmp(question, "accounting/interval-start")) {
896 *answer = tor_malloc(ISO_TIME_LEN+1);
897 format_iso_time(*answer, interval_start_time);
898 } else if (!strcmp(question, "accounting/interval-wake")) {
899 *answer = tor_malloc(ISO_TIME_LEN+1);
900 format_iso_time(*answer, interval_wakeup_time);
901 } else if (!strcmp(question, "accounting/interval-end")) {
902 *answer = tor_malloc(ISO_TIME_LEN+1);
903 format_iso_time(*answer, interval_end_time);
904 } else {
905 *answer = NULL;
907 return 0;