hibernate.c 35 KB

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