hibernate.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  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. #include "config.h"
  22. #include "connection.h"
  23. #include "connection_edge.h"
  24. #include "hibernate.h"
  25. #include "main.h"
  26. #include "router.h"
  27. /** Possible values of hibernate_state */
  28. typedef enum {
  29. /** We are running normally. */
  30. HIBERNATE_STATE_LIVE=1,
  31. /** We're trying to shut down cleanly, and we'll kill all active connections
  32. * at shutdown_time. */
  33. HIBERNATE_STATE_EXITING=2,
  34. /** We're running low on allocated bandwidth for this period, so we won't
  35. * accept any new connections. */
  36. HIBERNATE_STATE_LOWBANDWIDTH=3,
  37. /** We are hibernating, and we won't wake up till there's more bandwidth to
  38. * use. */
  39. HIBERNATE_STATE_DORMANT=4
  40. } hibernate_state_t;
  41. extern long stats_n_seconds_working; /* published uptime */
  42. /** Are we currently awake, asleep, running out of bandwidth, or shutting
  43. * down? */
  44. static hibernate_state_t hibernate_state = HIBERNATE_STATE_LIVE;
  45. /** If are hibernating, when do we plan to wake up? Set to 0 if we
  46. * aren't hibernating. */
  47. static time_t hibernate_end_time = 0;
  48. /** If we are shutting down, when do we plan finally exit? Set to 0 if
  49. * we aren't shutting down. */
  50. static time_t shutdown_time = 0;
  51. /** Possible accounting periods. */
  52. typedef enum {
  53. UNIT_MONTH=1, UNIT_WEEK=2, UNIT_DAY=3,
  54. } time_unit_t;
  55. /* Fields for accounting logic. Accounting overview:
  56. *
  57. * Accounting is designed to ensure that no more than N bytes are sent in
  58. * either direction over a given interval (currently, one month, one week, or
  59. * one day) We could
  60. * try to do this by choking our bandwidth to a trickle, but that
  61. * would make our streams useless. Instead, we estimate what our
  62. * bandwidth usage will be, and guess how long we'll be able to
  63. * provide that much bandwidth before hitting our limit. We then
  64. * choose a random time within the accounting interval to come up (so
  65. * that we don't get 50 Tors running on the 1st of the month and none
  66. * on the 30th).
  67. *
  68. * Each interval runs as follows:
  69. *
  70. * 1. We guess our bandwidth usage, based on how much we used
  71. * last time. We choose a "wakeup time" within the interval to come up.
  72. * 2. Until the chosen wakeup time, we hibernate.
  73. * 3. We come up at the wakeup time, and provide bandwidth until we are
  74. * "very close" to running out.
  75. * 4. Then we go into low-bandwidth mode, and stop accepting new
  76. * connections, but provide bandwidth until we run out.
  77. * 5. Then we hibernate until the end of the interval.
  78. *
  79. * If the interval ends before we run out of bandwidth, we go back to
  80. * step one.
  81. */
  82. /** How many bytes have we read in this accounting interval? */
  83. static uint64_t n_bytes_read_in_interval = 0;
  84. /** How many bytes have we written in this accounting interval? */
  85. static uint64_t n_bytes_written_in_interval = 0;
  86. /** How many seconds have we been running this interval? */
  87. static uint32_t n_seconds_active_in_interval = 0;
  88. /** When did this accounting interval start? */
  89. static time_t interval_start_time = 0;
  90. /** When will this accounting interval end? */
  91. static time_t interval_end_time = 0;
  92. /** How far into the accounting interval should we hibernate? */
  93. static time_t interval_wakeup_time = 0;
  94. /** How much bandwidth do we 'expect' to use per minute? (0 if we have no
  95. * info from the last period.) */
  96. static uint64_t expected_bandwidth_usage = 0;
  97. /** What unit are we using for our accounting? */
  98. static time_unit_t cfg_unit = UNIT_MONTH;
  99. /** How many days,hours,minutes into each unit does our accounting interval
  100. * start? */
  101. static int cfg_start_day = 0,
  102. cfg_start_hour = 0,
  103. cfg_start_min = 0;
  104. static void reset_accounting(time_t now);
  105. static int read_bandwidth_usage(void);
  106. static time_t start_of_accounting_period_after(time_t now);
  107. static time_t start_of_accounting_period_containing(time_t now);
  108. static void accounting_set_wakeup_time(void);
  109. /* ************
  110. * Functions for bandwidth accounting.
  111. * ************/
  112. /** Configure accounting start/end time settings based on
  113. * options->AccountingStart. Return 0 on success, -1 on failure. If
  114. * <b>validate_only</b> is true, do not change the current settings. */
  115. int
  116. accounting_parse_options(or_options_t *options, int validate_only)
  117. {
  118. time_unit_t unit;
  119. int ok, idx;
  120. long d,h,m;
  121. smartlist_t *items;
  122. const char *v = options->AccountingStart;
  123. const char *s;
  124. char *cp;
  125. if (!v) {
  126. if (!validate_only) {
  127. cfg_unit = UNIT_MONTH;
  128. cfg_start_day = 1;
  129. cfg_start_hour = 0;
  130. cfg_start_min = 0;
  131. }
  132. return 0;
  133. }
  134. items = smartlist_create();
  135. smartlist_split_string(items, v, NULL,
  136. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,0);
  137. if (smartlist_len(items)<2) {
  138. log_warn(LD_CONFIG, "Too few arguments to AccountingStart");
  139. goto err;
  140. }
  141. s = smartlist_get(items,0);
  142. if (0==strcasecmp(s, "month")) {
  143. unit = UNIT_MONTH;
  144. } else if (0==strcasecmp(s, "week")) {
  145. unit = UNIT_WEEK;
  146. } else if (0==strcasecmp(s, "day")) {
  147. unit = UNIT_DAY;
  148. } else {
  149. log_warn(LD_CONFIG,
  150. "Unrecognized accounting unit '%s': only 'month', 'week',"
  151. " and 'day' are supported.", s);
  152. goto err;
  153. }
  154. switch (unit) {
  155. case UNIT_WEEK:
  156. d = tor_parse_long(smartlist_get(items,1), 10, 1, 7, &ok, NULL);
  157. if (!ok) {
  158. log_warn(LD_CONFIG, "Weekly accounting must begin on a day between "
  159. "1 (Monday) and 7 (Sunday)");
  160. goto err;
  161. }
  162. break;
  163. case UNIT_MONTH:
  164. d = tor_parse_long(smartlist_get(items,1), 10, 1, 28, &ok, NULL);
  165. if (!ok) {
  166. log_warn(LD_CONFIG, "Monthly accounting must begin on a day between "
  167. "1 and 28");
  168. goto err;
  169. }
  170. break;
  171. case UNIT_DAY:
  172. d = 0;
  173. break;
  174. /* Coverity dislikes unreachable default cases; some compilers warn on
  175. * switch statements missing a case. Tell Coverity not to worry. */
  176. /* coverity[dead_error_begin] */
  177. default:
  178. tor_assert(0);
  179. }
  180. idx = unit==UNIT_DAY?1:2;
  181. if (smartlist_len(items) != (idx+1)) {
  182. log_warn(LD_CONFIG,"Accounting unit '%s' requires %d argument%s.",
  183. s, idx, (idx>1)?"s":"");
  184. goto err;
  185. }
  186. s = smartlist_get(items, idx);
  187. h = tor_parse_long(s, 10, 0, 23, &ok, &cp);
  188. if (!ok) {
  189. log_warn(LD_CONFIG,"Accounting start time not parseable: bad hour.");
  190. goto err;
  191. }
  192. if (!cp || *cp!=':') {
  193. log_warn(LD_CONFIG,
  194. "Accounting start time not parseable: not in HH:MM format");
  195. goto err;
  196. }
  197. m = tor_parse_long(cp+1, 10, 0, 59, &ok, &cp);
  198. if (!ok) {
  199. log_warn(LD_CONFIG, "Accounting start time not parseable: bad minute");
  200. goto err;
  201. }
  202. if (!cp || *cp!='\0') {
  203. log_warn(LD_CONFIG,
  204. "Accounting start time not parseable: not in HH:MM format");
  205. goto err;
  206. }
  207. if (!validate_only) {
  208. cfg_unit = unit;
  209. cfg_start_day = (int)d;
  210. cfg_start_hour = (int)h;
  211. cfg_start_min = (int)m;
  212. }
  213. SMARTLIST_FOREACH(items, char *, item, tor_free(item));
  214. smartlist_free(items);
  215. return 0;
  216. err:
  217. SMARTLIST_FOREACH(items, char *, item, tor_free(item));
  218. smartlist_free(items);
  219. return -1;
  220. }
  221. /** If we want to manage the accounting system and potentially
  222. * hibernate, return 1, else return 0.
  223. */
  224. int
  225. accounting_is_enabled(or_options_t *options)
  226. {
  227. if (options->AccountingMax)
  228. return 1;
  229. return 0;
  230. }
  231. /** Called from main.c to tell us that <b>seconds</b> seconds have
  232. * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
  233. * bytes have been written. */
  234. void
  235. accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
  236. {
  237. n_bytes_read_in_interval += n_read;
  238. n_bytes_written_in_interval += n_written;
  239. /* If we haven't been called in 10 seconds, we're probably jumping
  240. * around in time. */
  241. n_seconds_active_in_interval += (seconds < 10) ? seconds : 0;
  242. }
  243. /** If get_end, return the end of the accounting period that contains
  244. * the time <b>now</b>. Else, return the start of the accounting
  245. * period that contains the time <b>now</b> */
  246. static time_t
  247. edge_of_accounting_period_containing(time_t now, int get_end)
  248. {
  249. int before;
  250. struct tm tm;
  251. tor_localtime_r(&now, &tm);
  252. /* Set 'before' to true iff the current time is before the hh:mm
  253. * changeover time for today. */
  254. before = tm.tm_hour < cfg_start_hour ||
  255. (tm.tm_hour == cfg_start_hour && tm.tm_min < cfg_start_min);
  256. /* Dispatch by unit. First, find the start day of the given period;
  257. * then, if get_end is true, increment to the end day. */
  258. switch (cfg_unit)
  259. {
  260. case UNIT_MONTH: {
  261. /* If this is before the Nth, we want the Nth of last month. */
  262. if (tm.tm_mday < cfg_start_day ||
  263. (tm.tm_mday < cfg_start_day && before)) {
  264. --tm.tm_mon;
  265. }
  266. /* Otherwise, the month is correct. */
  267. tm.tm_mday = cfg_start_day;
  268. if (get_end)
  269. ++tm.tm_mon;
  270. break;
  271. }
  272. case UNIT_WEEK: {
  273. /* What is the 'target' day of the week in struct tm format? (We
  274. say Sunday==7; struct tm says Sunday==0.) */
  275. int wday = cfg_start_day % 7;
  276. /* How many days do we subtract from today to get to the right day? */
  277. int delta = (7+tm.tm_wday-wday)%7;
  278. /* If we are on the right day, but the changeover hasn't happened yet,
  279. * then subtract a whole week. */
  280. if (delta == 0 && before)
  281. delta = 7;
  282. tm.tm_mday -= delta;
  283. if (get_end)
  284. tm.tm_mday += 7;
  285. break;
  286. }
  287. case UNIT_DAY:
  288. if (before)
  289. --tm.tm_mday;
  290. if (get_end)
  291. ++tm.tm_mday;
  292. break;
  293. default:
  294. tor_assert(0);
  295. }
  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);
  301. }
  302. /** Return the start of the accounting period containing the time
  303. * <b>now</b>. */
  304. static time_t
  305. start_of_accounting_period_containing(time_t now)
  306. {
  307. return edge_of_accounting_period_containing(now, 0);
  308. }
  309. /** Return the start of the accounting period that comes after the one
  310. * containing the time <b>now</b>. */
  311. static time_t
  312. start_of_accounting_period_after(time_t now)
  313. {
  314. return edge_of_accounting_period_containing(now, 1);
  315. }
  316. /** Initialize the accounting subsystem. */
  317. void
  318. configure_accounting(time_t now)
  319. {
  320. /* Try to remember our recorded usage. */
  321. if (!interval_start_time)
  322. read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
  323. * reset below.*/
  324. if (!interval_start_time ||
  325. start_of_accounting_period_after(interval_start_time) <= now) {
  326. /* We didn't have recorded usage, or we don't have recorded usage
  327. * for this interval. Start a new interval. */
  328. log_info(LD_ACCT, "Starting new accounting interval.");
  329. reset_accounting(now);
  330. } else if (interval_start_time ==
  331. start_of_accounting_period_containing(interval_start_time)) {
  332. log_info(LD_ACCT, "Continuing accounting interval.");
  333. /* We are in the interval we thought we were in. Do nothing.*/
  334. interval_end_time = start_of_accounting_period_after(interval_start_time);
  335. } else {
  336. log_warn(LD_ACCT,
  337. "Mismatched accounting interval; starting a fresh one.");
  338. reset_accounting(now);
  339. }
  340. accounting_set_wakeup_time();
  341. }
  342. /** Set expected_bandwidth_usage based on how much we sent/received
  343. * per minute last interval (if we were up for at least 30 minutes),
  344. * or based on our declared bandwidth otherwise. */
  345. static void
  346. update_expected_bandwidth(void)
  347. {
  348. uint64_t used, expected;
  349. uint64_t max_configured = (get_options()->BandwidthRate * 60);
  350. if (n_seconds_active_in_interval < 1800) {
  351. /* If we haven't gotten enough data last interval, set 'expected'
  352. * to 0. This will set our wakeup to the start of the interval.
  353. * Next interval, we'll choose our starting time based on how much
  354. * we sent this interval.
  355. */
  356. expected = 0;
  357. } else {
  358. used = n_bytes_written_in_interval < n_bytes_read_in_interval ?
  359. n_bytes_read_in_interval : n_bytes_written_in_interval;
  360. expected = used / (n_seconds_active_in_interval / 60);
  361. if (expected > max_configured)
  362. expected = max_configured;
  363. }
  364. expected_bandwidth_usage = expected;
  365. }
  366. /** Called at the start of a new accounting interval: reset our
  367. * expected bandwidth usage based on what happened last time, set up
  368. * the start and end of the interval, and clear byte/time totals.
  369. */
  370. static void
  371. reset_accounting(time_t now)
  372. {
  373. log_info(LD_ACCT, "Starting new accounting interval.");
  374. update_expected_bandwidth();
  375. interval_start_time = start_of_accounting_period_containing(now);
  376. interval_end_time = start_of_accounting_period_after(interval_start_time);
  377. n_bytes_read_in_interval = 0;
  378. n_bytes_written_in_interval = 0;
  379. n_seconds_active_in_interval = 0;
  380. }
  381. /** Return true iff we should save our bandwidth usage to disk. */
  382. static INLINE int
  383. time_to_record_bandwidth_usage(time_t now)
  384. {
  385. /* Note every 600 sec */
  386. #define NOTE_INTERVAL (600)
  387. /* Or every 20 megabytes */
  388. #define NOTE_BYTES 20*(1024*1024)
  389. static uint64_t last_read_bytes_noted = 0;
  390. static uint64_t last_written_bytes_noted = 0;
  391. static time_t last_time_noted = 0;
  392. if (last_time_noted + NOTE_INTERVAL <= now ||
  393. last_read_bytes_noted + NOTE_BYTES <= n_bytes_read_in_interval ||
  394. last_written_bytes_noted + NOTE_BYTES <= n_bytes_written_in_interval ||
  395. (interval_end_time && interval_end_time <= now)) {
  396. last_time_noted = now;
  397. last_read_bytes_noted = n_bytes_read_in_interval;
  398. last_written_bytes_noted = n_bytes_written_in_interval;
  399. return 1;
  400. }
  401. return 0;
  402. }
  403. /** Invoked once per second. Checks whether it is time to hibernate,
  404. * record bandwidth used, etc. */
  405. void
  406. accounting_run_housekeeping(time_t now)
  407. {
  408. if (now >= interval_end_time) {
  409. configure_accounting(now);
  410. }
  411. if (time_to_record_bandwidth_usage(now)) {
  412. if (accounting_record_bandwidth_usage(now, get_or_state())) {
  413. log_warn(LD_FS, "Couldn't record bandwidth usage to disk.");
  414. }
  415. }
  416. }
  417. /** When we have no idea how fast we are, how long do we assume it will take
  418. * us to exhaust our bandwidth? */
  419. #define GUESS_TIME_TO_USE_BANDWIDTH (24*60*60)
  420. /** Based on our interval and our estimated bandwidth, choose a
  421. * deterministic (but random-ish) time to wake up. */
  422. static void
  423. accounting_set_wakeup_time(void)
  424. {
  425. char buf[ISO_TIME_LEN+1];
  426. char digest[DIGEST_LEN];
  427. crypto_digest_env_t *d_env;
  428. int time_in_interval;
  429. uint64_t time_to_exhaust_bw;
  430. int time_to_consider;
  431. if (! identity_key_is_set()) {
  432. if (init_keys() < 0) {
  433. log_err(LD_BUG, "Error initializing keys");
  434. tor_assert(0);
  435. }
  436. }
  437. format_iso_time(buf, interval_start_time);
  438. crypto_pk_get_digest(get_identity_key(), digest);
  439. d_env = crypto_new_digest_env();
  440. crypto_digest_add_bytes(d_env, buf, ISO_TIME_LEN);
  441. crypto_digest_add_bytes(d_env, digest, DIGEST_LEN);
  442. crypto_digest_get_digest(d_env, digest, DIGEST_LEN);
  443. crypto_free_digest_env(d_env);
  444. if (!expected_bandwidth_usage) {
  445. char buf1[ISO_TIME_LEN+1];
  446. char buf2[ISO_TIME_LEN+1];
  447. format_local_iso_time(buf1, interval_start_time);
  448. format_local_iso_time(buf2, interval_end_time);
  449. time_to_exhaust_bw = GUESS_TIME_TO_USE_BANDWIDTH;
  450. interval_wakeup_time = interval_start_time;
  451. log_notice(LD_ACCT,
  452. "Configured hibernation. This interval begins at %s "
  453. "and ends at %s. We have no prior estimate for bandwidth, so "
  454. "we will start out awake and hibernate when we exhaust our quota.",
  455. buf1, buf2);
  456. return;
  457. }
  458. time_in_interval = (int)(interval_end_time - interval_start_time);
  459. time_to_exhaust_bw =
  460. (get_options()->AccountingMax/expected_bandwidth_usage)*60;
  461. if (time_to_exhaust_bw > TIME_MAX) {
  462. time_to_exhaust_bw = TIME_MAX;
  463. time_to_consider = 0;
  464. } else {
  465. time_to_consider = time_in_interval - (int)time_to_exhaust_bw;
  466. }
  467. if (time_to_consider<=0) {
  468. interval_wakeup_time = interval_start_time;
  469. } else {
  470. /* XXX can we simplify this just by picking a random (non-deterministic)
  471. * time to be up? If we go down and come up, then we pick a new one. Is
  472. * that good enough? -RD */
  473. /* This is not a perfectly unbiased conversion, but it is good enough:
  474. * in the worst case, the first half of the day is 0.06 percent likelier
  475. * to be chosen than the last half. */
  476. interval_wakeup_time = interval_start_time +
  477. (get_uint32(digest) % time_to_consider);
  478. format_iso_time(buf, interval_wakeup_time);
  479. }
  480. {
  481. char buf1[ISO_TIME_LEN+1];
  482. char buf2[ISO_TIME_LEN+1];
  483. char buf3[ISO_TIME_LEN+1];
  484. char buf4[ISO_TIME_LEN+1];
  485. time_t down_time;
  486. if (interval_wakeup_time+time_to_exhaust_bw > TIME_MAX)
  487. down_time = TIME_MAX;
  488. else
  489. down_time = (time_t)(interval_wakeup_time+time_to_exhaust_bw);
  490. if (down_time>interval_end_time)
  491. down_time = interval_end_time;
  492. format_local_iso_time(buf1, interval_start_time);
  493. format_local_iso_time(buf2, interval_wakeup_time);
  494. format_local_iso_time(buf3, down_time);
  495. format_local_iso_time(buf4, interval_end_time);
  496. log_notice(LD_ACCT,
  497. "Configured hibernation. This interval began at %s; "
  498. "the scheduled wake-up time %s %s; "
  499. "we expect%s to exhaust our quota for this interval around %s; "
  500. "the next interval begins at %s (all times local)",
  501. buf1,
  502. time(NULL)<interval_wakeup_time?"is":"was", buf2,
  503. time(NULL)<down_time?"":"ed", buf3,
  504. buf4);
  505. }
  506. }
  507. /* This rounds 0 up to 1000, but that's actually a feature. */
  508. #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
  509. /** Save all our bandwidth tracking information to disk. Return 0 on
  510. * success, -1 on failure. */
  511. int
  512. accounting_record_bandwidth_usage(time_t now, or_state_t *state)
  513. {
  514. /* Just update the state */
  515. state->AccountingIntervalStart = interval_start_time;
  516. state->AccountingBytesReadInInterval = ROUND_UP(n_bytes_read_in_interval);
  517. state->AccountingBytesWrittenInInterval =
  518. ROUND_UP(n_bytes_written_in_interval);
  519. state->AccountingSecondsActive = n_seconds_active_in_interval;
  520. state->AccountingExpectedUsage = expected_bandwidth_usage;
  521. or_state_mark_dirty(state,
  522. now+(get_options()->AvoidDiskWrites ? 7200 : 60));
  523. return 0;
  524. }
  525. #undef ROUND_UP
  526. /** Read stored accounting information from disk. Return 0 on success;
  527. * return -1 and change nothing on failure. */
  528. static int
  529. read_bandwidth_usage(void)
  530. {
  531. or_state_t *state = get_or_state();
  532. {
  533. char *fname = get_datadir_fname("bw_accounting");
  534. unlink(fname);
  535. tor_free(fname);
  536. }
  537. if (!state)
  538. return -1;
  539. /* Okay; it looks like the state file is more up-to-date than the
  540. * bw_accounting file, or the bw_accounting file is nonexistent,
  541. * or the bw_accounting file is corrupt.
  542. */
  543. log_info(LD_ACCT, "Reading bandwidth accounting data from state file");
  544. n_bytes_read_in_interval = state->AccountingBytesReadInInterval;
  545. n_bytes_written_in_interval = state->AccountingBytesWrittenInInterval;
  546. n_seconds_active_in_interval = state->AccountingSecondsActive;
  547. interval_start_time = state->AccountingIntervalStart;
  548. expected_bandwidth_usage = state->AccountingExpectedUsage;
  549. {
  550. char tbuf1[ISO_TIME_LEN+1];
  551. char tbuf2[ISO_TIME_LEN+1];
  552. format_iso_time(tbuf1, state->LastWritten);
  553. format_iso_time(tbuf2, state->AccountingIntervalStart);
  554. log_info(LD_ACCT,
  555. "Successfully read bandwidth accounting info from state written at %s "
  556. "for interval starting at %s. We have been active for %lu seconds in "
  557. "this interval. At the start of the interval, we expected to use "
  558. "about %lu KB per second. ("U64_FORMAT" bytes read so far, "
  559. U64_FORMAT" bytes written so far)",
  560. tbuf1, tbuf2,
  561. (unsigned long)n_seconds_active_in_interval,
  562. (unsigned long)(expected_bandwidth_usage*1024/60),
  563. U64_PRINTF_ARG(n_bytes_read_in_interval),
  564. U64_PRINTF_ARG(n_bytes_written_in_interval));
  565. }
  566. return 0;
  567. }
  568. /** Return true iff we have sent/received all the bytes we are willing
  569. * to send/receive this interval. */
  570. static int
  571. hibernate_hard_limit_reached(void)
  572. {
  573. uint64_t hard_limit = get_options()->AccountingMax;
  574. if (!hard_limit)
  575. return 0;
  576. return n_bytes_read_in_interval >= hard_limit
  577. || n_bytes_written_in_interval >= hard_limit;
  578. }
  579. /** Return true iff we have sent/received almost all the bytes we are willing
  580. * to send/receive this interval. */
  581. static int
  582. hibernate_soft_limit_reached(void)
  583. {
  584. uint64_t soft_limit = DBL_TO_U64(U64_TO_DBL(get_options()->AccountingMax)
  585. * .95);
  586. if (!soft_limit)
  587. return 0;
  588. return n_bytes_read_in_interval >= soft_limit
  589. || n_bytes_written_in_interval >= soft_limit;
  590. }
  591. /** Called when we get a SIGINT, or when bandwidth soft limit is
  592. * reached. Puts us into "loose hibernation": we don't accept new
  593. * connections, but we continue handling old ones. */
  594. static void
  595. hibernate_begin(hibernate_state_t new_state, time_t now)
  596. {
  597. connection_t *conn;
  598. or_options_t *options = get_options();
  599. if (new_state == HIBERNATE_STATE_EXITING &&
  600. hibernate_state != HIBERNATE_STATE_LIVE) {
  601. log_notice(LD_GENERAL,"SIGINT received %s; exiting now.",
  602. hibernate_state == HIBERNATE_STATE_EXITING ?
  603. "a second time" : "while hibernating");
  604. tor_cleanup();
  605. exit(0);
  606. }
  607. /* close listeners. leave control listener(s). */
  608. while ((conn = connection_get_by_type(CONN_TYPE_OR_LISTENER)) ||
  609. (conn = connection_get_by_type(CONN_TYPE_AP_LISTENER)) ||
  610. (conn = connection_get_by_type(CONN_TYPE_AP_TRANS_LISTENER)) ||
  611. (conn = connection_get_by_type(CONN_TYPE_AP_DNS_LISTENER)) ||
  612. (conn = connection_get_by_type(CONN_TYPE_AP_NATD_LISTENER)) ||
  613. (conn = connection_get_by_type(CONN_TYPE_DIR_LISTENER))) {
  614. log_info(LD_NET,"Closing listener type %d", conn->type);
  615. connection_mark_for_close(conn);
  616. }
  617. /* XXX kill intro point circs */
  618. /* XXX upload rendezvous service descriptors with no intro points */
  619. if (new_state == HIBERNATE_STATE_EXITING) {
  620. log_notice(LD_GENERAL,"Interrupt: will shut down in %d seconds. Interrupt "
  621. "again to exit now.", options->ShutdownWaitLength);
  622. shutdown_time = time(NULL) + options->ShutdownWaitLength;
  623. } else { /* soft limit reached */
  624. hibernate_end_time = interval_end_time;
  625. }
  626. hibernate_state = new_state;
  627. accounting_record_bandwidth_usage(now, get_or_state());
  628. or_state_mark_dirty(get_or_state(),
  629. get_options()->AvoidDiskWrites ? now+600 : 0);
  630. }
  631. /** Called when we've been hibernating and our timeout is reached. */
  632. static void
  633. hibernate_end(hibernate_state_t new_state)
  634. {
  635. tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
  636. hibernate_state == HIBERNATE_STATE_DORMANT);
  637. /* listeners will be relaunched in run_scheduled_events() in main.c */
  638. log_notice(LD_ACCT,"Hibernation period ended. Resuming normal activity.");
  639. hibernate_state = new_state;
  640. hibernate_end_time = 0; /* no longer hibernating */
  641. stats_n_seconds_working = 0; /* reset published uptime */
  642. }
  643. /** A wrapper around hibernate_begin, for when we get SIGINT. */
  644. void
  645. hibernate_begin_shutdown(void)
  646. {
  647. hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
  648. }
  649. /** Return true iff we are currently hibernating. */
  650. int
  651. we_are_hibernating(void)
  652. {
  653. return hibernate_state != HIBERNATE_STATE_LIVE;
  654. }
  655. /** If we aren't currently dormant, close all connections and become
  656. * dormant. */
  657. static void
  658. hibernate_go_dormant(time_t now)
  659. {
  660. connection_t *conn;
  661. if (hibernate_state == HIBERNATE_STATE_DORMANT)
  662. return;
  663. else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
  664. hibernate_state = HIBERNATE_STATE_DORMANT;
  665. else
  666. hibernate_begin(HIBERNATE_STATE_DORMANT, now);
  667. log_notice(LD_ACCT,"Going dormant. Blowing away remaining connections.");
  668. /* Close all OR/AP/exit conns. Leave dir conns because we still want
  669. * to be able to upload server descriptors so people know we're still
  670. * running, and download directories so we can detect if we're obsolete.
  671. * Leave control conns because we still want to be controllable.
  672. */
  673. while ((conn = connection_get_by_type(CONN_TYPE_OR)) ||
  674. (conn = connection_get_by_type(CONN_TYPE_AP)) ||
  675. (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
  676. if (CONN_IS_EDGE(conn))
  677. connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_HIBERNATING);
  678. log_info(LD_NET,"Closing conn type %d", conn->type);
  679. if (conn->type == CONN_TYPE_AP) /* send socks failure if needed */
  680. connection_mark_unattached_ap(TO_EDGE_CONN(conn),
  681. END_STREAM_REASON_HIBERNATING);
  682. else
  683. connection_mark_for_close(conn);
  684. }
  685. if (now < interval_wakeup_time)
  686. hibernate_end_time = interval_wakeup_time;
  687. else
  688. hibernate_end_time = interval_end_time;
  689. accounting_record_bandwidth_usage(now, get_or_state());
  690. or_state_mark_dirty(get_or_state(),
  691. get_options()->AvoidDiskWrites ? now+600 : 0);
  692. }
  693. /** Called when hibernate_end_time has arrived. */
  694. static void
  695. hibernate_end_time_elapsed(time_t now)
  696. {
  697. char buf[ISO_TIME_LEN+1];
  698. /* The interval has ended, or it is wakeup time. Find out which. */
  699. accounting_run_housekeeping(now);
  700. if (interval_wakeup_time <= now) {
  701. /* The interval hasn't changed, but interval_wakeup_time has passed.
  702. * It's time to wake up and start being a server. */
  703. hibernate_end(HIBERNATE_STATE_LIVE);
  704. return;
  705. } else {
  706. /* The interval has changed, and it isn't time to wake up yet. */
  707. hibernate_end_time = interval_wakeup_time;
  708. format_iso_time(buf,interval_wakeup_time);
  709. if (hibernate_state != HIBERNATE_STATE_DORMANT) {
  710. /* We weren't sleeping before; we should sleep now. */
  711. log_notice(LD_ACCT,
  712. "Accounting period ended. Commencing hibernation until "
  713. "%s GMT", buf);
  714. hibernate_go_dormant(now);
  715. } else {
  716. log_notice(LD_ACCT,
  717. "Accounting period ended. This period, we will hibernate"
  718. " until %s GMT",buf);
  719. }
  720. }
  721. }
  722. /** Consider our environment and decide if it's time
  723. * to start/stop hibernating.
  724. */
  725. void
  726. consider_hibernation(time_t now)
  727. {
  728. int accounting_enabled = get_options()->AccountingMax != 0;
  729. char buf[ISO_TIME_LEN+1];
  730. /* If we're in 'exiting' mode, then we just shut down after the interval
  731. * elapses. */
  732. if (hibernate_state == HIBERNATE_STATE_EXITING) {
  733. tor_assert(shutdown_time);
  734. if (shutdown_time <= now) {
  735. log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
  736. tor_cleanup();
  737. exit(0);
  738. }
  739. return; /* if exiting soon, don't worry about bandwidth limits */
  740. }
  741. if (hibernate_state == HIBERNATE_STATE_DORMANT) {
  742. /* We've been hibernating because of bandwidth accounting. */
  743. tor_assert(hibernate_end_time);
  744. if (hibernate_end_time > now && accounting_enabled) {
  745. /* If we're hibernating, don't wake up until it's time, regardless of
  746. * whether we're in a new interval. */
  747. return ;
  748. } else {
  749. hibernate_end_time_elapsed(now);
  750. }
  751. }
  752. /* Else, we aren't hibernating. See if it's time to start hibernating, or to
  753. * go dormant. */
  754. if (hibernate_state == HIBERNATE_STATE_LIVE) {
  755. if (hibernate_soft_limit_reached()) {
  756. log_notice(LD_ACCT,
  757. "Bandwidth soft limit reached; commencing hibernation.");
  758. hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
  759. } else if (accounting_enabled && now < interval_wakeup_time) {
  760. format_local_iso_time(buf,interval_wakeup_time);
  761. log_notice(LD_ACCT,
  762. "Commencing hibernation. We will wake up at %s local time.",
  763. buf);
  764. hibernate_go_dormant(now);
  765. }
  766. }
  767. if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
  768. if (!accounting_enabled) {
  769. hibernate_end_time_elapsed(now);
  770. } else if (hibernate_hard_limit_reached()) {
  771. hibernate_go_dormant(now);
  772. } else if (hibernate_end_time <= now) {
  773. /* The hibernation period ended while we were still in lowbandwidth.*/
  774. hibernate_end_time_elapsed(now);
  775. }
  776. }
  777. }
  778. /** Helper function: called when we get a GETINFO request for an
  779. * accounting-related key on the control connection <b>conn</b>. If we can
  780. * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
  781. * allocated string holding the result. Otherwise, set *<b>answer</b> to
  782. * NULL. */
  783. int
  784. getinfo_helper_accounting(control_connection_t *conn,
  785. const char *question, char **answer,
  786. const char **errmsg)
  787. {
  788. (void) conn;
  789. (void) errmsg;
  790. if (!strcmp(question, "accounting/enabled")) {
  791. *answer = tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
  792. } else if (!strcmp(question, "accounting/hibernating")) {
  793. if (hibernate_state == HIBERNATE_STATE_DORMANT)
  794. *answer = tor_strdup("hard");
  795. else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
  796. *answer = tor_strdup("soft");
  797. else
  798. *answer = tor_strdup("awake");
  799. } else if (!strcmp(question, "accounting/bytes")) {
  800. *answer = tor_malloc(32);
  801. tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
  802. U64_PRINTF_ARG(n_bytes_read_in_interval),
  803. U64_PRINTF_ARG(n_bytes_written_in_interval));
  804. } else if (!strcmp(question, "accounting/bytes-left")) {
  805. uint64_t limit = get_options()->AccountingMax;
  806. uint64_t read_left = 0, write_left = 0;
  807. if (n_bytes_read_in_interval < limit)
  808. read_left = limit - n_bytes_read_in_interval;
  809. if (n_bytes_written_in_interval < limit)
  810. write_left = limit - n_bytes_written_in_interval;
  811. *answer = tor_malloc(64);
  812. tor_snprintf(*answer, 64, U64_FORMAT" "U64_FORMAT,
  813. U64_PRINTF_ARG(read_left), U64_PRINTF_ARG(write_left));
  814. } else if (!strcmp(question, "accounting/interval-start")) {
  815. *answer = tor_malloc(ISO_TIME_LEN+1);
  816. format_iso_time(*answer, interval_start_time);
  817. } else if (!strcmp(question, "accounting/interval-wake")) {
  818. *answer = tor_malloc(ISO_TIME_LEN+1);
  819. format_iso_time(*answer, interval_wakeup_time);
  820. } else if (!strcmp(question, "accounting/interval-end")) {
  821. *answer = tor_malloc(ISO_TIME_LEN+1);
  822. format_iso_time(*answer, interval_end_time);
  823. } else {
  824. *answer = NULL;
  825. }
  826. return 0;
  827. }