hibernate.c 34 KB

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