r11479@Kushana: nickm | 2006-12-07 23:38:54 -0500
[tor.git] / src / or / hibernate.c
blob2063ccdbd2776cfbe7cb5a9da0c708896179c0ce
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 600 sec */
395 #define NOTE_INTERVAL (600)
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, get_or_state())) {
424 log_warn(LD_FS, "Couldn't record bandwidth usage to disk.");
429 /** When we have no idea how fast we are, how long do we assume it will take
430 * us to exhaust our bandwidth? */
431 #define GUESS_TIME_TO_USE_BANDWIDTH (24*60*60)
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 uint64_t 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 = GUESS_TIME_TO_USE_BANDWIDTH;
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_in_interval = interval_end_time - interval_start_time;
479 time_to_exhaust_bw =
480 (get_options()->AccountingMax/expected_bandwidth_usage)*60;
481 if (time_to_exhaust_bw > TIME_MAX) {
482 time_to_exhaust_bw = TIME_MAX;
483 time_to_consider = 0;
484 } else {
485 time_to_consider = time_in_interval - (int)time_to_exhaust_bw;
488 if (time_to_consider<=0) {
489 interval_wakeup_time = interval_start_time;
490 } else {
491 /* XXX can we simplify this just by picking a random (non-deterministic)
492 * time to be up? If we go down and come up, then we pick a new one. Is
493 * that good enough? -RD */
495 /* This is not a perfectly unbiased conversion, but it is good enough:
496 * in the worst case, the first half of the day is 0.06 percent likelier
497 * to be chosen than the last half. */
498 interval_wakeup_time = interval_start_time +
499 (get_uint32(digest) % time_to_consider);
501 format_iso_time(buf, interval_wakeup_time);
505 char buf1[ISO_TIME_LEN+1];
506 char buf2[ISO_TIME_LEN+1];
507 char buf3[ISO_TIME_LEN+1];
508 char buf4[ISO_TIME_LEN+1];
509 time_t down_time;
510 if (interval_wakeup_time+time_to_exhaust_bw > TIME_MAX)
511 down_time = TIME_MAX;
512 else
513 down_time = (time_t)(interval_wakeup_time+time_to_exhaust_bw);
514 if (down_time>interval_end_time)
515 down_time = interval_end_time;
516 format_local_iso_time(buf1, interval_start_time);
517 format_local_iso_time(buf2, interval_wakeup_time);
518 format_local_iso_time(buf3, down_time);
519 format_local_iso_time(buf4, interval_end_time);
521 log_notice(LD_ACCT,
522 "Configured hibernation. This interval began at %s; "
523 "the scheduled wake-up time %s %s; "
524 "we expect%s to exhaust our quota for this interval around %s; "
525 "the next interval begins at %s (all times local)",
526 buf1,
527 time(NULL)<interval_wakeup_time?"is":"was", buf2,
528 time(NULL)<down_time?"":"ed", buf3,
529 buf4);
533 #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
534 #define BW_ACCOUNTING_VERSION 1
535 /** Save all our bandwidth tracking information to disk. Return 0 on
536 * success, -1 on failure. */
538 accounting_record_bandwidth_usage(time_t now, or_state_t *state)
540 char buf[128];
541 char fname[512];
542 char time1[ISO_TIME_LEN+1];
543 char time2[ISO_TIME_LEN+1];
544 char *cp = buf;
545 time_t tmp;
546 int r;
548 /* First, update bw_accounting. Until 0.1.2.5-x, this was the only place
549 * we stored this information. The format is:
550 * Version\nTime\nTime\nRead\nWrite\nSeconds\nExpected-Rate\n */
552 format_iso_time(time1, interval_start_time);
553 format_iso_time(time2, now);
554 /* now check to see if they're valid times -- if they're not,
555 * and we write them, then tor will refuse to start next time. */
556 if (parse_iso_time(time1, &tmp) || parse_iso_time(time2, &tmp)) {
557 log_warn(LD_ACCT, "Created a time that we refused to parse.");
558 return -1;
560 tor_snprintf(cp, sizeof(buf),
561 "%d\n%s\n%s\n"U64_FORMAT"\n"U64_FORMAT"\n%lu\n%lu\n",
562 BW_ACCOUNTING_VERSION,
563 time1,
564 time2,
565 U64_PRINTF_ARG(ROUND_UP(n_bytes_read_in_interval)),
566 U64_PRINTF_ARG(ROUND_UP(n_bytes_written_in_interval)),
567 (unsigned long)n_seconds_active_in_interval,
568 (unsigned long)expected_bandwidth_usage);
569 tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
570 get_options()->DataDirectory);
571 r = write_str_to_file(fname, buf, 0);
573 /* Now update the state */
574 state->AccountingIntervalStart = interval_start_time;
575 state->AccountingBytesReadInInterval = ROUND_UP(n_bytes_read_in_interval);
576 state->AccountingBytesWrittenInInterval =
577 ROUND_UP(n_bytes_written_in_interval);
578 state->AccountingSecondsActive = n_seconds_active_in_interval;
579 state->AccountingExpectedUsage = expected_bandwidth_usage;
580 or_state_mark_dirty(state, 60);
582 return r;
584 #undef ROUND_UP
586 /** Read stored accounting information from disk. Return 0 on success;
587 * return -1 and change nothing on failure. */
588 static int
589 read_bandwidth_usage(void)
591 char *s = NULL;
592 char fname[512];
593 time_t t1, t2;
594 uint64_t n_read, n_written;
595 uint32_t expected_bw, n_seconds;
596 smartlist_t *elts = NULL;
597 int ok, use_state=0, r=-1;
598 or_state_t *state = get_or_state();
600 tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
601 get_options()->DataDirectory);
602 elts = smartlist_create();
603 if ((s = read_file_to_str(fname, 0, NULL)) == NULL) {
604 /* We have an old-format bw_accounting file. */
605 use_state = 1;
607 if (!use_state) {
608 smartlist_split_string(elts, s, "\n",
609 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
610 tor_free(s);
612 if (smartlist_len(elts)<1 ||
613 atoi(smartlist_get(elts,0)) != BW_ACCOUNTING_VERSION) {
614 log_warn(LD_ACCT, "Unrecognized bw_accounting file version: %s",
615 (const char*)smartlist_get(elts,0));
616 use_state = 1;
619 if (!use_state && smartlist_len(elts) < 7) {
620 log_warn(LD_ACCT, "Corrupted bw_accounting file: %d lines",
621 smartlist_len(elts));
622 use_state = 1;
624 if (!use_state && parse_iso_time(smartlist_get(elts,2), &t2)) {
625 log_warn(LD_ACCT, "Error parsing bandwidth usage last-written time");
626 use_state = 1;
628 if (use_state || t2 <= state->LastWritten) {
629 /* Okay; it looks like the state file is more up-to-date than the
630 * bw_accounting file, or the bw_accounting file is nonexistant,
631 * or the bw_accounting file is corrupt.
633 log_info(LD_ACCT, "Reading bandwdith accounting data from state file");
634 n_bytes_read_in_interval = state->AccountingBytesReadInInterval;
635 n_bytes_written_in_interval = state->AccountingBytesWrittenInInterval;
636 n_seconds_active_in_interval = state->AccountingSecondsActive;
637 interval_start_time = state->AccountingIntervalStart;
638 expected_bandwidth_usage = state->AccountingExpectedUsage;
639 r = 0;
640 goto done;
643 if (parse_iso_time(smartlist_get(elts,1), &t1)) {
644 log_warn(LD_ACCT, "Error parsing bandwidth usage start time.");
645 goto done;
647 n_read = tor_parse_uint64(smartlist_get(elts,3), 10, 0, UINT64_MAX,
648 &ok, NULL);
649 if (!ok) {
650 log_warn(LD_ACCT, "Error parsing number of bytes read");
651 goto done;
653 n_written = tor_parse_uint64(smartlist_get(elts,4), 10, 0, UINT64_MAX,
654 &ok, NULL);
655 if (!ok) {
656 log_warn(LD_ACCT, "Error parsing number of bytes written");
657 goto done;
659 n_seconds = (uint32_t)tor_parse_ulong(smartlist_get(elts,5), 10,0,ULONG_MAX,
660 &ok, NULL);
661 if (!ok) {
662 log_warn(LD_ACCT, "Error parsing number of seconds live");
663 goto done;
665 expected_bw =(uint32_t)tor_parse_ulong(smartlist_get(elts,6), 10,0,ULONG_MAX,
666 &ok, NULL);
667 if (!ok) {
668 log_warn(LD_ACCT, "Error parsing expected bandwidth");
669 goto done;
672 n_bytes_read_in_interval = n_read;
673 n_bytes_written_in_interval = n_written;
674 n_seconds_active_in_interval = n_seconds;
675 interval_start_time = t1;
676 expected_bandwidth_usage = expected_bw;
678 log_info(LD_ACCT,
679 "Successfully read bandwidth accounting file written at %s "
680 "for interval starting at %s. We have been active for %lu seconds in "
681 "this interval. At the start of the interval, we expected to use "
682 "about %lu KB per second. ("U64_FORMAT" bytes read so far, "
683 U64_FORMAT" bytes written so far)",
684 (char*)smartlist_get(elts,2),
685 (char*)smartlist_get(elts,1),
686 (unsigned long)n_seconds_active_in_interval,
687 (unsigned long)((uint64_t)expected_bandwidth_usage*1024/60),
688 U64_PRINTF_ARG(n_bytes_read_in_interval),
689 U64_PRINTF_ARG(n_bytes_written_in_interval));
691 r = 0;
692 done:
693 if (elts) {
694 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
695 smartlist_free(elts);
697 return r;
700 /** Return true iff we have sent/received all the bytes we are willing
701 * to send/receive this interval. */
702 static int
703 hibernate_hard_limit_reached(void)
705 uint64_t hard_limit = get_options()->AccountingMax;
706 if (!hard_limit)
707 return 0;
708 return n_bytes_read_in_interval >= hard_limit
709 || n_bytes_written_in_interval >= hard_limit;
712 /** Return true iff we have sent/received almost all the bytes we are willing
713 * to send/receive this interval. */
714 static int
715 hibernate_soft_limit_reached(void)
717 uint64_t soft_limit = DBL_TO_U64(U64_TO_DBL(get_options()->AccountingMax)
718 * .95);
719 if (!soft_limit)
720 return 0;
721 return n_bytes_read_in_interval >= soft_limit
722 || n_bytes_written_in_interval >= soft_limit;
725 /** Called when we get a SIGINT, or when bandwidth soft limit is
726 * reached. Puts us into "loose hibernation": we don't accept new
727 * connections, but we continue handling old ones. */
728 static void
729 hibernate_begin(int new_state, time_t now)
731 connection_t *conn;
732 or_options_t *options = get_options();
734 if (new_state == HIBERNATE_STATE_EXITING &&
735 hibernate_state != HIBERNATE_STATE_LIVE) {
736 log_notice(LD_GENERAL,"Sigint received %s; exiting now.",
737 hibernate_state == HIBERNATE_STATE_EXITING ?
738 "a second time" : "while hibernating");
739 tor_cleanup();
740 exit(0);
743 /* close listeners. leave control listener(s). */
744 while ((conn = connection_get_by_type(CONN_TYPE_OR_LISTENER)) ||
745 (conn = connection_get_by_type(CONN_TYPE_AP_LISTENER)) ||
746 (conn = connection_get_by_type(CONN_TYPE_AP_TRANS_LISTENER)) ||
747 (conn = connection_get_by_type(CONN_TYPE_AP_NATD_LISTENER)) ||
748 (conn = connection_get_by_type(CONN_TYPE_DIR_LISTENER))) {
749 log_info(LD_NET,"Closing listener type %d", conn->type);
750 connection_mark_for_close(conn);
753 /* XXX kill intro point circs */
754 /* XXX upload rendezvous service descriptors with no intro points */
756 if (new_state == HIBERNATE_STATE_EXITING) {
757 log_notice(LD_GENERAL,"Interrupt: will shut down in %d seconds. Interrupt "
758 "again to exit now.", options->ShutdownWaitLength);
759 hibernate_end_time = time(NULL) + options->ShutdownWaitLength;
760 } else { /* soft limit reached */
761 hibernate_end_time = interval_end_time;
764 hibernate_state = new_state;
765 accounting_record_bandwidth_usage(now, get_or_state());
766 or_state_mark_dirty(get_or_state(), 0);
769 /** Called when we've been hibernating and our timeout is reached. */
770 static void
771 hibernate_end(int new_state)
773 tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
774 hibernate_state == HIBERNATE_STATE_DORMANT);
776 /* listeners will be relaunched in run_scheduled_events() in main.c */
777 log_notice(LD_ACCT,"Hibernation period ended. Resuming normal activity.");
779 hibernate_state = new_state;
780 hibernate_end_time = 0; /* no longer hibernating */
781 stats_n_seconds_working = 0; /* reset published uptime */
784 /** A wrapper around hibernate_begin, for when we get SIGINT. */
785 void
786 hibernate_begin_shutdown(void)
788 hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
791 /** Return true iff we are currently hibernating. */
793 we_are_hibernating(void)
795 return hibernate_state != HIBERNATE_STATE_LIVE;
798 /** If we aren't currently dormant, close all connections and become
799 * dormant. */
800 static void
801 hibernate_go_dormant(time_t now)
803 connection_t *conn;
805 if (hibernate_state == HIBERNATE_STATE_DORMANT)
806 return;
807 else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
808 hibernate_state = HIBERNATE_STATE_DORMANT;
809 else
810 hibernate_begin(HIBERNATE_STATE_DORMANT, now);
812 log_notice(LD_ACCT,"Going dormant. Blowing away remaining connections.");
814 /* Close all OR/AP/exit conns. Leave dir conns because we still want
815 * to be able to upload server descriptors so people know we're still
816 * running, and download directories so we can detect if we're obsolete.
817 * Leave control conns because we still want to be controllable.
819 while ((conn = connection_get_by_type(CONN_TYPE_OR)) ||
820 (conn = connection_get_by_type(CONN_TYPE_AP)) ||
821 (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
822 if (CONN_IS_EDGE(conn))
823 connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_HIBERNATING,
824 TO_EDGE_CONN(conn)->cpath_layer);
825 log_info(LD_NET,"Closing conn type %d", conn->type);
826 if (conn->type == CONN_TYPE_AP) /* send socks failure if needed */
827 connection_mark_unattached_ap(TO_EDGE_CONN(conn),
828 END_STREAM_REASON_HIBERNATING);
829 else
830 connection_mark_for_close(conn);
833 accounting_record_bandwidth_usage(now, get_or_state());
834 or_state_mark_dirty(get_or_state(), 0);
837 /** Called when hibernate_end_time has arrived. */
838 static void
839 hibernate_end_time_elapsed(time_t now)
841 char buf[ISO_TIME_LEN+1];
843 /* The interval has ended, or it is wakeup time. Find out which. */
844 accounting_run_housekeeping(now);
845 if (interval_wakeup_time <= now) {
846 /* The interval hasn't changed, but interval_wakeup_time has passed.
847 * It's time to wake up and start being a server. */
848 hibernate_end(HIBERNATE_STATE_LIVE);
849 return;
850 } else {
851 /* The interval has changed, and it isn't time to wake up yet. */
852 hibernate_end_time = interval_wakeup_time;
853 format_iso_time(buf,interval_wakeup_time);
854 if (hibernate_state != HIBERNATE_STATE_DORMANT) {
855 /* We weren't sleeping before; we should sleep now. */
856 log_notice(LD_ACCT,
857 "Accounting period ended. Commencing hibernation until "
858 "%s GMT", buf);
859 hibernate_go_dormant(now);
860 } else {
861 log_notice(LD_ACCT,
862 "Accounting period ended. This period, we will hibernate"
863 " until %s GMT",buf);
868 /** Consider our environment and decide if it's time
869 * to start/stop hibernating.
871 void
872 consider_hibernation(time_t now)
874 int accounting_enabled = get_options()->AccountingMax != 0;
875 char buf[ISO_TIME_LEN+1];
877 /* If we're in 'exiting' mode, then we just shut down after the interval
878 * elapses. */
879 if (hibernate_state == HIBERNATE_STATE_EXITING) {
880 tor_assert(hibernate_end_time);
881 if (hibernate_end_time <= now) {
882 log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
883 tor_cleanup();
884 exit(0);
886 return; /* if exiting soon, don't worry about bandwidth limits */
889 if (hibernate_state == HIBERNATE_STATE_DORMANT) {
890 /* We've been hibernating because of bandwidth accounting. */
891 tor_assert(hibernate_end_time);
892 if (hibernate_end_time > now && accounting_enabled) {
893 /* If we're hibernating, don't wake up until it's time, regardless of
894 * whether we're in a new interval. */
895 return ;
896 } else {
897 hibernate_end_time_elapsed(now);
901 /* Else, we aren't hibernating. See if it's time to start hibernating, or to
902 * go dormant. */
903 if (hibernate_state == HIBERNATE_STATE_LIVE) {
904 if (hibernate_soft_limit_reached()) {
905 log_notice(LD_ACCT,
906 "Bandwidth soft limit reached; commencing hibernation.");
907 hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
908 } else if (accounting_enabled && now < interval_wakeup_time) {
909 format_local_iso_time(buf,interval_wakeup_time);
910 log_notice(LD_ACCT,
911 "Commencing hibernation. We will wake up at %s local time.",
912 buf);
913 hibernate_go_dormant(now);
917 if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
918 if (!accounting_enabled) {
919 hibernate_end_time_elapsed(now);
920 } else if (hibernate_hard_limit_reached()) {
921 hibernate_go_dormant(now);
922 } else if (hibernate_end_time <= now) {
923 /* The hibernation period ended while we were still in lowbandwidth.*/
924 hibernate_end_time_elapsed(now);
929 /** DOCDOC */
931 getinfo_helper_accounting(control_connection_t *conn,
932 const char *question, char **answer)
934 (void) conn;
935 if (!strcmp(question, "accounting/enabled")) {
936 *answer = tor_strdup(get_options()->AccountingMax ? "1" : "0");
937 } else if (!strcmp(question, "accounting/hibernating")) {
938 if (hibernate_state == HIBERNATE_STATE_DORMANT)
939 *answer = tor_strdup("hard");
940 else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
941 *answer = tor_strdup("soft");
942 else
943 *answer = tor_strdup("awake");
944 } else if (!strcmp(question, "accounting/bytes")) {
945 *answer = tor_malloc(32);
946 tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
947 U64_PRINTF_ARG(n_bytes_read_in_interval),
948 U64_PRINTF_ARG(n_bytes_written_in_interval));
949 } else if (!strcmp(question, "accounting/bytes-left")) {
950 uint64_t limit = get_options()->AccountingMax;
951 *answer = tor_malloc(32);
952 tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
953 U64_PRINTF_ARG(limit - n_bytes_read_in_interval),
954 U64_PRINTF_ARG(limit - n_bytes_written_in_interval));
955 } else if (!strcmp(question, "accounting/interval-start")) {
956 *answer = tor_malloc(ISO_TIME_LEN+1);
957 format_iso_time(*answer, interval_start_time);
958 } else if (!strcmp(question, "accounting/interval-wake")) {
959 *answer = tor_malloc(ISO_TIME_LEN+1);
960 format_iso_time(*answer, interval_wakeup_time);
961 } else if (!strcmp(question, "accounting/interval-end")) {
962 *answer = tor_malloc(ISO_TIME_LEN+1);
963 format_iso_time(*answer, interval_end_time);
964 } else {
965 *answer = NULL;
967 return 0;