hibernate.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. /* Copyright 2004 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file hibernate.c
  6. * \brief Functions to close listeners, stop allowing new circuits,
  7. * etc in preparation for closing down or going dormant; and to track
  8. * bandwidth and time intervals to know when to hibernate and when to
  9. * stop hibernating.
  10. **/
  11. /*
  12. hibernating, phase 1:
  13. - send destroy in response to create cells
  14. - send end (policy failed) in response to begin cells
  15. - close an OR conn when it has no circuits
  16. hibernating, phase 2:
  17. (entered when bandwidth hard limit reached)
  18. - close all OR/AP/exit conns)
  19. */
  20. #include "or.h"
  21. #define HIBERNATE_STATE_LIVE 1
  22. #define HIBERNATE_STATE_EXITING 2
  23. #define HIBERNATE_STATE_LOWBANDWIDTH 3
  24. #define HIBERNATE_STATE_DORMANT 4
  25. #define SHUTDOWN_WAIT_LENGTH 30 /* seconds */
  26. static int hibernate_state = HIBERNATE_STATE_LIVE;
  27. /** If are hibernating, when do we plan to wake up? Set to 0 if we
  28. * aren't hibernating. */
  29. static time_t hibernate_end_time = 0;
  30. typedef enum {
  31. UNIT_MONTH=1, UNIT_WEEK=2, UNIT_DAY=3,
  32. } time_unit_t;
  33. /* Fields for accounting logic. Accounting overview:
  34. *
  35. * Accounting is designed to ensure that no more than N bytes are sent
  36. * in either direction over a given interval (currently, one month,
  37. * starting at 0:00 GMT an arbitrary day within the month). We could
  38. * try to do this by choking our bandwidth to a trickle, but that
  39. * would make our streams useless. Instead, we estimate what our
  40. * bandwidth usage will be, and guess how long we'll be able to
  41. * provide that much bandwidth before hitting our limit. We then
  42. * choose a random time within the accounting interval to come up (so
  43. * that we don't get 50 Tors running on the 1st of the month and none
  44. * on the 30th).
  45. *
  46. * Each interval runs as follows:
  47. *
  48. * 1. We guess our bandwidth usage, based on how much we used
  49. * last time. We choose a "wakeup time" within the interval to come up.
  50. * 2. Until the chosen wakeup time, we hibernate.
  51. * 3. We come up at the wakeup time, and provide bandwidth until we are
  52. * "very close" to running out.
  53. * 4. Then we go into low-bandwidth mode, and stop accepting new
  54. * connections, but provide bandwidth until we run out.
  55. * 5. Then we hibernate until the end of the interval.
  56. *
  57. * If the interval ends before we run out of bandwdith, we go back to
  58. * step one.
  59. */
  60. /** How many bytes have we read/written in this accounting interval? */
  61. static uint64_t n_bytes_read_in_interval = 0;
  62. static uint64_t n_bytes_written_in_interval = 0;
  63. /** How many seconds have we been running this interval? */
  64. static uint32_t n_seconds_active_in_interval = 0;
  65. /** When did this accounting interval start? */
  66. static time_t interval_start_time = 0;
  67. /** When will this accounting interval end? */
  68. static time_t interval_end_time = 0;
  69. /** How far into the accounting interval should we hibernate? */
  70. static time_t interval_wakeup_time = 0;
  71. /** How much bandwidth do we 'expect' to use per minute? (0 if we have no
  72. * info from the last period.) */
  73. static uint32_t expected_bandwidth_usage = 0;
  74. /** What unit are we using for our accounting? */
  75. static time_unit_t cfg_unit = UNIT_MONTH;
  76. /** How many days,hours,minutes into each unit does our accounting interval
  77. * start? */
  78. static int cfg_start_day = 0;
  79. static int cfg_start_hour = 0;
  80. static int cfg_start_min = 0;
  81. static void reset_accounting(time_t now);
  82. static int read_bandwidth_usage(void);
  83. static time_t start_of_accounting_period_after(time_t now);
  84. static time_t start_of_accounting_period_containing(time_t now);
  85. static void accounting_set_wakeup_time(void);
  86. /* ************
  87. * Functions for bandwidth accounting.
  88. * ************/
  89. /** Configure accounting start/end time settings based on
  90. * options->AccountingStart. Return 0 on success, -1 on failure. If
  91. * <b>validate_only</b> is true, do not change the current settings. */
  92. int
  93. accounting_parse_options(or_options_t *options, int validate_only)
  94. {
  95. time_unit_t unit;
  96. int ok, idx;
  97. long d,h,m;
  98. smartlist_t *items;
  99. const char *v = options->AccountingStart;
  100. const char *s;
  101. char *cp;
  102. if (!v) {
  103. if (!validate_only) {
  104. cfg_unit = UNIT_MONTH;
  105. cfg_start_day = 1;
  106. cfg_start_hour = 0;
  107. cfg_start_min = 0;
  108. }
  109. return 0;
  110. }
  111. items = smartlist_create();
  112. smartlist_split_string(items, v, " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
  113. if (smartlist_len(items)<2) {
  114. log_fn(LOG_WARN, "Too few arguments to AccountingStart");
  115. goto err;
  116. }
  117. s = smartlist_get(items,0);
  118. if (0==strcasecmp(s, "month")) {
  119. unit = UNIT_MONTH;
  120. } else if (0==strcasecmp(s, "week")) {
  121. unit = UNIT_WEEK;
  122. } else if (0==strcasecmp(s, "day")) {
  123. unit = UNIT_DAY;
  124. } else {
  125. log_fn(LOG_WARN, "Unrecognized accounting unit '%s': only 'month', 'week', and 'day' are supported.", s);
  126. goto err;
  127. }
  128. switch (unit) {
  129. case UNIT_WEEK:
  130. d = tor_parse_long(smartlist_get(items,1), 10, 1, 7, &ok, NULL);
  131. if (!ok) {
  132. log_fn(LOG_WARN, "Weekly accounting must start begin on a day between 1(Monday) and 7 (Sunday)");
  133. goto err;
  134. }
  135. break;
  136. case UNIT_MONTH:
  137. d = tor_parse_long(smartlist_get(items,1), 10, 1, 28, &ok, NULL);
  138. if (!ok) {
  139. log_fn(LOG_WARN, "Monthy accounting must start begin on a day between 1 and 28");
  140. goto err;
  141. }
  142. break;
  143. case UNIT_DAY:
  144. d = 0;
  145. break;
  146. default:
  147. tor_assert(0);
  148. }
  149. idx = unit==UNIT_DAY?1:2;
  150. if (smartlist_len(items) != (idx+1)) {
  151. log_fn(LOG_WARN, "Accounting unit '%s' requires %d arguments",
  152. s, idx+1);
  153. goto err;
  154. }
  155. s = smartlist_get(items, idx);
  156. h = tor_parse_long(s, 10, 0, 23, &ok, &cp);
  157. if (!ok) {
  158. log_fn(LOG_WARN, "Accounting start time not parseable: bad hour.");
  159. goto err;
  160. }
  161. if (!cp || *cp!=':') {
  162. log_fn(LOG_WARN,"Accounting start time not parseable: not in HH:MM format");
  163. goto err;
  164. }
  165. m = tor_parse_long(cp+1, 10, 0, 59, &ok, &cp);
  166. if (!ok) {
  167. log_fn(LOG_WARN, "Accounting start time not parseable: bad minute");
  168. goto err;
  169. }
  170. if (!cp || *cp!='\0') {
  171. log_fn(LOG_WARN,"Accounting start time not parseable: not in HH:MM format");
  172. goto err;
  173. }
  174. if (!validate_only) {
  175. cfg_unit = unit;
  176. cfg_start_day = (int)d;
  177. cfg_start_hour = (int)h;
  178. cfg_start_min = (int)m;
  179. }
  180. SMARTLIST_FOREACH(items, char *, s, tor_free(s));
  181. smartlist_free(items);
  182. return 0;
  183. err:
  184. SMARTLIST_FOREACH(items, char *, s, tor_free(s));
  185. smartlist_free(items);
  186. return -1;
  187. }
  188. /** If we want to manage the accounting system and potentially
  189. * hibernate, return 1, else return 0.
  190. */
  191. int accounting_is_enabled(or_options_t *options) {
  192. if (options->AccountingMax)
  193. return 1;
  194. return 0;
  195. }
  196. /** Called from main.c to tell us that <b>seconds</b> seconds have
  197. * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
  198. * bytes have been written. */
  199. void
  200. accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
  201. {
  202. n_bytes_read_in_interval += n_read;
  203. n_bytes_written_in_interval += n_written;
  204. /* If we haven't been called in 10 seconds, we're probably jumping
  205. * around in time. */
  206. n_seconds_active_in_interval += (seconds < 10) ? seconds : 0;
  207. }
  208. /** If get_end, return the end of the accounting period that contains
  209. * the time <b>now</b>. Else, return the start of the accounting
  210. * period that contains the time <b>now</b> */
  211. static time_t
  212. edge_of_accounting_period_containing(time_t now, int get_end)
  213. {
  214. int before;
  215. struct tm *tm;
  216. tm = localtime(&now);
  217. /* Set 'before' to true iff the current time is before the hh:mm
  218. * changeover time for today. */
  219. before = tm->tm_hour < cfg_start_hour ||
  220. (tm->tm_hour == cfg_start_hour && tm->tm_min < cfg_start_min);
  221. /* Dispatch by unit. First, find the start day of the given period;
  222. * then, if get_end is true, increment to the end day. */
  223. switch (cfg_unit)
  224. {
  225. case UNIT_MONTH: {
  226. /* If this is before the Nth, we want the Nth of last month. */
  227. if (tm->tm_mday < cfg_start_day ||
  228. (tm->tm_mday < cfg_start_day && before)) {
  229. --tm->tm_mon;
  230. }
  231. /* Otherwise, the month is correct. */
  232. tm->tm_mday = cfg_start_day;
  233. if (get_end)
  234. ++tm->tm_mon;
  235. break;
  236. }
  237. case UNIT_WEEK: {
  238. /* What is the 'target' day of the week in struct tm format? (We
  239. say Sunday==7; struct tm says Sunday==0.) */
  240. int wday = cfg_start_day % 7;
  241. /* How many days do we subtract from today to get to the right day? */
  242. int delta = (7+tm->tm_wday-wday)%7;
  243. /* If we are on the right day, but the changeover hasn't happened yet,
  244. * then subtract a whole week. */
  245. if (delta == 0 && before)
  246. delta = 7;
  247. tm->tm_mday -= delta;
  248. if (get_end)
  249. tm->tm_mday += 7;
  250. break;
  251. }
  252. case UNIT_DAY:
  253. if (before)
  254. --tm->tm_mday;
  255. if (get_end)
  256. ++tm->tm_mday;
  257. break;
  258. default:
  259. tor_assert(0);
  260. }
  261. tm->tm_hour = cfg_start_hour;
  262. tm->tm_min = cfg_start_min;
  263. tm->tm_sec = 0;
  264. tm->tm_isdst = -1; /* Autodetect DST */
  265. return mktime(tm);
  266. }
  267. /** Return the start of the accounting period containing the time
  268. * <b>now</b>. */
  269. static time_t
  270. start_of_accounting_period_containing(time_t now)
  271. {
  272. return edge_of_accounting_period_containing(now, 0);
  273. }
  274. /** Return the start of the accounting period that comes after the one
  275. * containing the time <b>now</b>. */
  276. static time_t
  277. start_of_accounting_period_after(time_t now)
  278. {
  279. return edge_of_accounting_period_containing(now, 1);
  280. }
  281. /** Initialize the accounting subsystem. */
  282. void
  283. configure_accounting(time_t now)
  284. {
  285. /* Try to remember our recorded usage. */
  286. if (!interval_start_time)
  287. read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
  288. * reset below.*/
  289. if (!interval_start_time ||
  290. start_of_accounting_period_after(interval_start_time) <= now) {
  291. /* We didn't have recorded usage, or we don't have recorded usage
  292. * for this interval. Start a new interval. */
  293. log_fn(LOG_INFO, "Starting new accounting interval.");
  294. reset_accounting(now);
  295. } else if (interval_start_time ==
  296. start_of_accounting_period_containing(interval_start_time)) {
  297. log_fn(LOG_INFO, "Continuing accounting interval.");
  298. /* We are in the interval we thought we were in. Do nothing.*/
  299. interval_end_time = start_of_accounting_period_after(interval_start_time);
  300. } else {
  301. log_fn(LOG_WARN, "Mismatched accounting interval; starting a fresh one.");
  302. reset_accounting(now);
  303. }
  304. accounting_set_wakeup_time();
  305. }
  306. /** Set expected_bandwidth_usage based on how much we sent/received
  307. * per minute last interval (if we were up for at least 30 minutes),
  308. * or based on our declared bandwidth otherwise. */
  309. static void
  310. update_expected_bandwidth(void)
  311. {
  312. uint64_t used, expected;
  313. uint64_t max_configured = (get_options()->BandwidthRate * 60);
  314. if (n_seconds_active_in_interval < 1800) {
  315. /* If we haven't gotten enough data last interval, set 'expected'
  316. * to 0. This will set our wakeup to the start of the interval.
  317. * Next interval, we'll choose our starting time based on how much
  318. * we sent this interval.
  319. */
  320. expected = 0;
  321. } else {
  322. used = n_bytes_written_in_interval < n_bytes_read_in_interval ?
  323. n_bytes_read_in_interval : n_bytes_written_in_interval;
  324. expected = used / (n_seconds_active_in_interval / 60);
  325. if (expected > max_configured)
  326. expected = max_configured;
  327. }
  328. if (expected > UINT32_MAX)
  329. expected = UINT32_MAX;
  330. expected_bandwidth_usage = (uint32_t) expected;
  331. }
  332. /** Called at the start of a new accounting interval: reset our
  333. * expected bandwidth usage based on what happened last time, set up
  334. * the start and end of the interval, and clear byte/time totals.
  335. */
  336. static void
  337. reset_accounting(time_t now) {
  338. log_fn(LOG_INFO, "Starting new accounting interval.");
  339. update_expected_bandwidth();
  340. interval_start_time = start_of_accounting_period_containing(now);
  341. interval_end_time = start_of_accounting_period_after(interval_start_time);
  342. n_bytes_read_in_interval = 0;
  343. n_bytes_written_in_interval = 0;
  344. n_seconds_active_in_interval = 0;
  345. }
  346. /** Return true iff we should save our bandwidth usage to disk. */
  347. static INLINE int
  348. time_to_record_bandwidth_usage(time_t now)
  349. {
  350. /* Note every 60 sec */
  351. #define NOTE_INTERVAL (60)
  352. /* Or every 20 megabytes */
  353. #define NOTE_BYTES 20*(1024*1024)
  354. static uint64_t last_read_bytes_noted = 0;
  355. static uint64_t last_written_bytes_noted = 0;
  356. static time_t last_time_noted = 0;
  357. if (last_time_noted + NOTE_INTERVAL <= now ||
  358. last_read_bytes_noted + NOTE_BYTES <= n_bytes_read_in_interval ||
  359. last_written_bytes_noted + NOTE_BYTES <= n_bytes_written_in_interval ||
  360. (interval_end_time && interval_end_time <= now)) {
  361. last_time_noted = now;
  362. last_read_bytes_noted = n_bytes_read_in_interval;
  363. last_written_bytes_noted = n_bytes_written_in_interval;
  364. return 1;
  365. }
  366. return 0;
  367. }
  368. void
  369. accounting_run_housekeeping(time_t now)
  370. {
  371. if (now >= interval_end_time) {
  372. configure_accounting(now);
  373. }
  374. if (time_to_record_bandwidth_usage(now)) {
  375. if (accounting_record_bandwidth_usage(now)) {
  376. log_fn(LOG_ERR, "Couldn't record bandwidth usage; exiting.");
  377. exit(1);
  378. }
  379. }
  380. }
  381. /** Based on our interval and our estimated bandwidth, choose a
  382. * deterministic (but random-ish) time to wake up. */
  383. static void
  384. accounting_set_wakeup_time(void)
  385. {
  386. char buf[ISO_TIME_LEN+1];
  387. char digest[DIGEST_LEN];
  388. crypto_digest_env_t *d_env;
  389. int time_in_interval;
  390. int time_to_exhaust_bw;
  391. int time_to_consider;
  392. if (! identity_key_is_set()) {
  393. if (init_keys() < 0) {
  394. log_fn(LOG_ERR, "Error initializing keys");
  395. tor_assert(0);
  396. }
  397. }
  398. format_iso_time(buf, interval_start_time);
  399. crypto_pk_get_digest(get_identity_key(), digest);
  400. d_env = crypto_new_digest_env();
  401. crypto_digest_add_bytes(d_env, buf, ISO_TIME_LEN);
  402. crypto_digest_add_bytes(d_env, digest, DIGEST_LEN);
  403. crypto_digest_get_digest(d_env, digest, DIGEST_LEN);
  404. crypto_free_digest_env(d_env);
  405. if (!expected_bandwidth_usage) {
  406. char buf1[ISO_TIME_LEN+1];
  407. char buf2[ISO_TIME_LEN+1];
  408. format_local_iso_time(buf1, interval_start_time);
  409. format_local_iso_time(buf2, interval_end_time);
  410. time_to_exhaust_bw = 24*60*60;
  411. interval_wakeup_time = interval_start_time;
  412. log_fn(LOG_NOTICE, "Configured hibernation. This interval begins at %s "
  413. "and ends at %s. We have no prior estimate for bandwidth, so "
  414. "we will start out awake and hibernate when we exhaust our bandwidth.",
  415. buf1, buf2);
  416. return;
  417. }
  418. time_to_exhaust_bw = (int)
  419. (get_options()->AccountingMax/expected_bandwidth_usage)*60;
  420. time_in_interval = interval_end_time - interval_start_time;
  421. time_to_consider = time_in_interval - time_to_exhaust_bw;
  422. if (time_to_consider<=0) {
  423. interval_wakeup_time = interval_start_time;
  424. } else {
  425. /* XXX can we simplify this just by picking a random (non-deterministic)
  426. * time to be up? If we go down and come up, then we pick a new one. Is
  427. * that good enough? -RD */
  428. /* This is not a perfectly unbiased conversion, but it is good enough:
  429. * in the worst case, the first half of the day is 0.06 percent likelier
  430. * to be chosen than the last half. */
  431. interval_wakeup_time = interval_start_time +
  432. (get_uint32(digest) % time_to_consider);
  433. format_iso_time(buf, interval_wakeup_time);
  434. }
  435. {
  436. char buf1[ISO_TIME_LEN+1];
  437. char buf2[ISO_TIME_LEN+1];
  438. char buf3[ISO_TIME_LEN+1];
  439. char buf4[ISO_TIME_LEN+1];
  440. time_t down_time = interval_wakeup_time+time_to_exhaust_bw;
  441. if (down_time>interval_end_time)
  442. down_time = interval_end_time;
  443. format_local_iso_time(buf1, interval_start_time);
  444. format_local_iso_time(buf2, interval_wakeup_time);
  445. format_local_iso_time(buf3,
  446. down_time<interval_end_time?down_time:interval_end_time);
  447. format_local_iso_time(buf4, interval_end_time);
  448. log_fn(LOG_NOTICE, "Configured hibernation. This interval began at %s; "
  449. "the scheduled wake-up time %s %s; "
  450. "we expect%s to exhaust our bandwidth for this interval around %s; "
  451. "the next interval begins at %s (all times local)",
  452. buf1,
  453. time(NULL)<interval_wakeup_time?"is":"was", buf2,
  454. time(NULL)<down_time?"":"ed", buf3,
  455. buf4);
  456. }
  457. }
  458. #define BW_ACCOUNTING_VERSION 1
  459. /** Save all our bandwidth tracking information to disk. Return 0 on
  460. * success, -1 on failure*/
  461. int
  462. accounting_record_bandwidth_usage(time_t now)
  463. {
  464. char buf[128];
  465. char fname[512];
  466. char time1[ISO_TIME_LEN+1];
  467. char time2[ISO_TIME_LEN+1];
  468. char *cp = buf;
  469. /* Format is:
  470. Version\nTime\nTime\nRead\nWrite\nSeconds\nExpected-Rate\n */
  471. format_iso_time(time1, interval_start_time);
  472. format_iso_time(time2, now);
  473. tor_snprintf(cp, sizeof(buf),
  474. "%d\n%s\n%s\n"U64_FORMAT"\n"U64_FORMAT"\n%lu\n%lu\n",
  475. BW_ACCOUNTING_VERSION,
  476. time1,
  477. time2,
  478. U64_PRINTF_ARG(n_bytes_read_in_interval),
  479. U64_PRINTF_ARG(n_bytes_written_in_interval),
  480. (unsigned long)n_seconds_active_in_interval,
  481. (unsigned long)expected_bandwidth_usage);
  482. tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
  483. get_options()->DataDirectory);
  484. return write_str_to_file(fname, buf, 0);
  485. }
  486. /** Read stored accounting information from disk. Return 0 on success;
  487. * return -1 and change nothing on failure. */
  488. static int
  489. read_bandwidth_usage(void)
  490. {
  491. char *s = NULL;
  492. char fname[512];
  493. time_t t1, t2;
  494. uint64_t n_read, n_written;
  495. uint32_t expected_bw, n_seconds;
  496. smartlist_t *elts;
  497. int ok;
  498. tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
  499. get_options()->DataDirectory);
  500. if (!(s = read_file_to_str(fname, 0))) {
  501. return 0;
  502. }
  503. elts = smartlist_create();
  504. smartlist_split_string(elts, s, "\n", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
  505. tor_free(s);
  506. if (smartlist_len(elts)<1 ||
  507. atoi(smartlist_get(elts,0)) != BW_ACCOUNTING_VERSION) {
  508. log_fn(LOG_WARN, "Unrecognized bw_accounting file version: %s",
  509. (const char*)smartlist_get(elts,0));
  510. goto err;
  511. }
  512. if (smartlist_len(elts) < 7) {
  513. log_fn(LOG_WARN, "Corrupted bw_accounting file: %d lines",
  514. smartlist_len(elts));
  515. goto err;
  516. }
  517. if (parse_iso_time(smartlist_get(elts,1), &t1)) {
  518. log_fn(LOG_WARN, "Error parsing bandwidth usage start time.");
  519. goto err;
  520. }
  521. if (parse_iso_time(smartlist_get(elts,2), &t2)) {
  522. log_fn(LOG_WARN, "Error parsing bandwidth usage last-written time");
  523. goto err;
  524. }
  525. n_read = tor_parse_uint64(smartlist_get(elts,3), 10, 0, UINT64_MAX,
  526. &ok, NULL);
  527. if (!ok) {
  528. log_fn(LOG_WARN, "Error parsing number of bytes read");
  529. goto err;
  530. }
  531. n_written = tor_parse_uint64(smartlist_get(elts,4), 10, 0, UINT64_MAX,
  532. &ok, NULL);
  533. if (!ok) {
  534. log_fn(LOG_WARN, "Error parsing number of bytes read");
  535. goto err;
  536. }
  537. n_seconds = (uint32_t)tor_parse_ulong(smartlist_get(elts,5), 10,0,ULONG_MAX,
  538. &ok, NULL);
  539. if (!ok) {
  540. log_fn(LOG_WARN, "Error parsing number of seconds live");
  541. goto err;
  542. }
  543. expected_bw =(uint32_t)tor_parse_ulong(smartlist_get(elts,6), 10,0,ULONG_MAX,
  544. &ok, NULL);
  545. if (!ok) {
  546. log_fn(LOG_WARN, "Error parsing expected bandwidth");
  547. goto err;
  548. }
  549. n_bytes_read_in_interval = n_read;
  550. n_bytes_written_in_interval = n_written;
  551. n_seconds_active_in_interval = n_seconds;
  552. interval_start_time = t1;
  553. expected_bandwidth_usage = expected_bw;
  554. return 0;
  555. err:
  556. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  557. smartlist_free(elts);
  558. return -1;
  559. }
  560. /** Return true iff we have sent/received all the bytes we are willing
  561. * to send/receive this interval. */
  562. static int
  563. hibernate_hard_limit_reached(void)
  564. {
  565. uint64_t hard_limit = get_options()->AccountingMax;
  566. if (!hard_limit)
  567. return 0;
  568. return n_bytes_read_in_interval >= hard_limit
  569. || n_bytes_written_in_interval >= hard_limit;
  570. }
  571. /** Return true iff we have sent/received almost all the bytes we are willing
  572. * to send/receive this interval. */
  573. static int hibernate_soft_limit_reached(void)
  574. {
  575. uint64_t soft_limit = (uint64_t) ((get_options()->AccountingMax) * .99);
  576. if (!soft_limit)
  577. return 0;
  578. return n_bytes_read_in_interval >= soft_limit
  579. || n_bytes_written_in_interval >= soft_limit;
  580. }
  581. /** Called when we get a SIGINT, or when bandwidth soft limit is
  582. * reached. Puts us into "loose hibernation": we don't accept new
  583. * connections, but we continue handling old ones. */
  584. static void hibernate_begin(int new_state, time_t now) {
  585. connection_t *conn;
  586. if(hibernate_state == HIBERNATE_STATE_EXITING) {
  587. /* we've been called twice now. close immediately. */
  588. log(LOG_NOTICE,"Second sigint received; exiting now.");
  589. tor_cleanup();
  590. exit(0);
  591. }
  592. /* close listeners. leave control listener(s). */
  593. while((conn = connection_get_by_type(CONN_TYPE_OR_LISTENER)) ||
  594. (conn = connection_get_by_type(CONN_TYPE_AP_LISTENER)) ||
  595. (conn = connection_get_by_type(CONN_TYPE_DIR_LISTENER))) {
  596. log_fn(LOG_INFO,"Closing listener type %d", conn->type);
  597. connection_mark_for_close(conn);
  598. }
  599. /* XXX kill intro point circs */
  600. /* XXX upload rendezvous service descriptors with no intro points */
  601. if(new_state == HIBERNATE_STATE_EXITING) {
  602. log(LOG_NOTICE,"Interrupt: will shut down in %d seconds. Interrupt again to exit now.", SHUTDOWN_WAIT_LENGTH);
  603. hibernate_end_time = time(NULL) + SHUTDOWN_WAIT_LENGTH;
  604. } else { /* soft limit reached */
  605. hibernate_end_time = interval_end_time;
  606. }
  607. hibernate_state = new_state;
  608. accounting_record_bandwidth_usage(now);
  609. }
  610. /** Called when we've been hibernating and our timeout is reached. */
  611. static void
  612. hibernate_end(int new_state) {
  613. tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
  614. hibernate_state == HIBERNATE_STATE_DORMANT);
  615. /* listeners will be relaunched in run_scheduled_events() in main.c */
  616. log_fn(LOG_NOTICE,"Hibernation period ended. Resuming normal activity.");
  617. hibernate_state = new_state;
  618. hibernate_end_time = 0; /* no longer hibernating */
  619. }
  620. /** A wrapper around hibernate_begin, for when we get SIGINT. */
  621. void
  622. hibernate_begin_shutdown(void) {
  623. hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
  624. }
  625. /** Return true iff we are currently hibernating. */
  626. int
  627. we_are_hibernating(void) {
  628. return hibernate_state != HIBERNATE_STATE_LIVE;
  629. }
  630. /** If we aren't currently dormant, close all connections and become
  631. * dormant. */
  632. static void
  633. hibernate_go_dormant(time_t now) {
  634. connection_t *conn;
  635. if (hibernate_state == HIBERNATE_STATE_DORMANT)
  636. return;
  637. else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
  638. hibernate_state = HIBERNATE_STATE_DORMANT;
  639. else
  640. hibernate_begin(HIBERNATE_STATE_DORMANT, now);
  641. log_fn(LOG_NOTICE,"Going dormant. Blowing away remaining connections.");
  642. /* Close all OR/AP/exit conns. Leave dir conns because we still want
  643. * to be able to upload server descriptors so people know we're still
  644. * running, and download directories so we can detect if we're obsolete.
  645. * Leave control conns because we still want to be controllable.
  646. */
  647. while((conn = connection_get_by_type(CONN_TYPE_OR)) ||
  648. (conn = connection_get_by_type(CONN_TYPE_AP)) ||
  649. (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
  650. log_fn(LOG_INFO,"Closing conn type %d", conn->type);
  651. connection_mark_for_close(conn);
  652. }
  653. accounting_record_bandwidth_usage(now);
  654. }
  655. /** Called when hibernate_end_time has arrived. */
  656. static void
  657. hibernate_end_time_elapsed(time_t now)
  658. {
  659. char buf[ISO_TIME_LEN+1];
  660. /* The interval has ended, or it is wakeup time. Find out which. */
  661. accounting_run_housekeeping(now);
  662. if (interval_wakeup_time <= now) {
  663. /* The interval hasn't changed, but interval_wakeup_time has passed.
  664. * It's time to wake up and start being a server. */
  665. hibernate_end(HIBERNATE_STATE_LIVE);
  666. return;
  667. } else {
  668. /* The interval has changed, and it isn't time to wake up yet. */
  669. hibernate_end_time = interval_wakeup_time;
  670. format_iso_time(buf,interval_wakeup_time);
  671. if (hibernate_state != HIBERNATE_STATE_DORMANT) {
  672. /* We weren't sleeping before; we should sleep now. */
  673. log_fn(LOG_NOTICE, "Accounting period ended. Commencing hibernation until %s GMT",buf);
  674. hibernate_go_dormant(now);
  675. } else {
  676. log_fn(LOG_NOTICE, "Accounting period ended. This period, we will hibernate until %s GMT",buf);
  677. }
  678. }
  679. }
  680. /** The big function. Consider our environment and decide if it's time
  681. * to start/stop hibernating.
  682. */
  683. void consider_hibernation(time_t now) {
  684. int accounting_enabled = get_options()->AccountingMax != 0;
  685. char buf[ISO_TIME_LEN+1];
  686. /* If we're in 'exiting' mode, then we just shut down after the interval
  687. * elapses. */
  688. if (hibernate_state == HIBERNATE_STATE_EXITING) {
  689. tor_assert(hibernate_end_time);
  690. if(hibernate_end_time <= now) {
  691. log(LOG_NOTICE,"Clean shutdown finished. Exiting.");
  692. tor_cleanup();
  693. exit(0);
  694. }
  695. return; /* if exiting soon, don't worry about bandwidth limits */
  696. }
  697. if(hibernate_state == HIBERNATE_STATE_DORMANT) {
  698. /* We've been hibernating because of bandwidth accounting. */
  699. tor_assert(hibernate_end_time);
  700. if (hibernate_end_time > now && accounting_enabled) {
  701. /* If we're hibernating, don't wake up until it's time, regardless of
  702. * whether we're in a new interval. */
  703. return ;
  704. } else {
  705. hibernate_end_time_elapsed(now);
  706. }
  707. }
  708. /* Else, we aren't hibernating. See if it's time to start hibernating, or to
  709. * go dormant. */
  710. if (hibernate_state == HIBERNATE_STATE_LIVE) {
  711. if (hibernate_soft_limit_reached()) {
  712. log_fn(LOG_NOTICE,"Bandwidth soft limit reached; commencing hibernation.");
  713. hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
  714. } else if (accounting_enabled && now < interval_wakeup_time) {
  715. format_iso_time(buf,interval_wakeup_time);
  716. log_fn(LOG_NOTICE, "Commencing hibernation. We will wake up at %s GMT",buf);
  717. hibernate_go_dormant(now);
  718. }
  719. }
  720. if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
  721. if (!accounting_enabled) {
  722. hibernate_end_time_elapsed(now);
  723. } else if (hibernate_hard_limit_reached()) {
  724. hibernate_go_dormant(now);
  725. } else if (hibernate_end_time <= now) {
  726. /* The hibernation period ended while we were still in lowbandwidth.*/
  727. hibernate_end_time_elapsed(now);
  728. }
  729. }
  730. }