hibernate.c 30 KB

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