hibernate.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. 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. time_t
  238. accounting_get_end_time(void)
  239. {
  240. return interval_end_time;
  241. }
  242. /** Called from main.c to tell us that <b>seconds</b> seconds have
  243. * passed, <b>n_read</b> bytes have been read, and <b>n_written</b>
  244. * bytes have been written. */
  245. void
  246. accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
  247. {
  248. n_bytes_read_in_interval += n_read;
  249. n_bytes_written_in_interval += n_written;
  250. /* If we haven't been called in 10 seconds, we're probably jumping
  251. * around in time. */
  252. n_seconds_active_in_interval += (seconds < 10) ? seconds : 0;
  253. }
  254. /** If get_end, return the end of the accounting period that contains
  255. * the time <b>now</b>. Else, return the start of the accounting
  256. * period that contains the time <b>now</b> */
  257. static time_t
  258. edge_of_accounting_period_containing(time_t now, int get_end)
  259. {
  260. int before;
  261. struct tm tm;
  262. tor_localtime_r(&now, &tm);
  263. /* Set 'before' to true iff the current time is before the hh:mm
  264. * changeover time for today. */
  265. before = tm.tm_hour < cfg_start_hour ||
  266. (tm.tm_hour == cfg_start_hour && tm.tm_min < cfg_start_min);
  267. /* Dispatch by unit. First, find the start day of the given period;
  268. * then, if get_end is true, increment to the end day. */
  269. switch (cfg_unit)
  270. {
  271. case UNIT_MONTH: {
  272. /* If this is before the Nth, we want the Nth of last month. */
  273. if (tm.tm_mday < cfg_start_day ||
  274. (tm.tm_mday < cfg_start_day && before)) {
  275. --tm.tm_mon;
  276. }
  277. /* Otherwise, the month is correct. */
  278. tm.tm_mday = cfg_start_day;
  279. if (get_end)
  280. ++tm.tm_mon;
  281. break;
  282. }
  283. case UNIT_WEEK: {
  284. /* What is the 'target' day of the week in struct tm format? (We
  285. say Sunday==7; struct tm says Sunday==0.) */
  286. int wday = cfg_start_day % 7;
  287. /* How many days do we subtract from today to get to the right day? */
  288. int delta = (7+tm.tm_wday-wday)%7;
  289. /* If we are on the right day, but the changeover hasn't happened yet,
  290. * then subtract a whole week. */
  291. if (delta == 0 && before)
  292. delta = 7;
  293. tm.tm_mday -= delta;
  294. if (get_end)
  295. tm.tm_mday += 7;
  296. break;
  297. }
  298. case UNIT_DAY:
  299. if (before)
  300. --tm.tm_mday;
  301. if (get_end)
  302. ++tm.tm_mday;
  303. break;
  304. default:
  305. tor_assert(0);
  306. }
  307. tm.tm_hour = cfg_start_hour;
  308. tm.tm_min = cfg_start_min;
  309. tm.tm_sec = 0;
  310. tm.tm_isdst = -1; /* Autodetect DST */
  311. return mktime(&tm);
  312. }
  313. /** Return the start of the accounting period containing the time
  314. * <b>now</b>. */
  315. static time_t
  316. start_of_accounting_period_containing(time_t now)
  317. {
  318. return edge_of_accounting_period_containing(now, 0);
  319. }
  320. /** Return the start of the accounting period that comes after the one
  321. * containing the time <b>now</b>. */
  322. static time_t
  323. start_of_accounting_period_after(time_t now)
  324. {
  325. return edge_of_accounting_period_containing(now, 1);
  326. }
  327. /** Return the length of the accounting period containing the time
  328. * <b>now</b>. */
  329. static long
  330. length_of_accounting_period_containing(time_t now)
  331. {
  332. return edge_of_accounting_period_containing(now, 1) -
  333. edge_of_accounting_period_containing(now, 0);
  334. }
  335. /** Initialize the accounting subsystem. */
  336. void
  337. configure_accounting(time_t now)
  338. {
  339. time_t s_now;
  340. /* Try to remember our recorded usage. */
  341. if (!interval_start_time)
  342. read_bandwidth_usage(); /* If we fail, we'll leave values at zero, and
  343. * reset below.*/
  344. s_now = start_of_accounting_period_containing(now);
  345. if (!interval_start_time) {
  346. /* We didn't have recorded usage; Start a new interval. */
  347. log_info(LD_ACCT, "Starting new accounting interval.");
  348. reset_accounting(now);
  349. } else if (s_now == interval_start_time) {
  350. log_info(LD_ACCT, "Continuing accounting interval.");
  351. /* We are in the interval we thought we were in. Do nothing.*/
  352. interval_end_time = start_of_accounting_period_after(interval_start_time);
  353. } else {
  354. long duration =
  355. length_of_accounting_period_containing(interval_start_time);
  356. double delta = ((double)(s_now - interval_start_time)) / duration;
  357. if (-0.50 <= delta && delta <= 0.50) {
  358. /* The start of the period is now a little later or earlier than we
  359. * remembered. That's fine; we might lose some bytes we could otherwise
  360. * have written, but better to err on the side of obeying people's
  361. * accounting settings. */
  362. log_info(LD_ACCT, "Accounting interval moved by %.02f%%; "
  363. "that's fine.", delta*100);
  364. interval_end_time = start_of_accounting_period_after(now);
  365. } else if (delta >= 0.99) {
  366. /* This is the regular time-moved-forward case; don't be too noisy
  367. * about it or people will complain */
  368. log_info(LD_ACCT, "Accounting interval elapsed; starting a new one");
  369. reset_accounting(now);
  370. } else {
  371. log_warn(LD_ACCT,
  372. "Mismatched accounting interval: moved by %.02f%%. "
  373. "Starting a fresh one.", delta*100);
  374. reset_accounting(now);
  375. }
  376. }
  377. accounting_set_wakeup_time();
  378. }
  379. /** Set expected_bandwidth_usage based on how much we sent/received
  380. * per minute last interval (if we were up for at least 30 minutes),
  381. * or based on our declared bandwidth otherwise. */
  382. static void
  383. update_expected_bandwidth(void)
  384. {
  385. uint64_t expected;
  386. const or_options_t *options= get_options();
  387. uint64_t max_configured = (options->RelayBandwidthRate > 0 ?
  388. options->RelayBandwidthRate :
  389. options->BandwidthRate) * 60;
  390. #define MIN_TIME_FOR_MEASUREMENT (1800)
  391. if (soft_limit_hit_at > interval_start_time && n_bytes_at_soft_limit &&
  392. (soft_limit_hit_at - interval_start_time) > MIN_TIME_FOR_MEASUREMENT) {
  393. /* If we hit our soft limit last time, only count the bytes up to that
  394. * time. This is a better predictor of our actual bandwidth than
  395. * considering the entirety of the last interval, since we likely started
  396. * using bytes very slowly once we hit our soft limit. */
  397. expected = n_bytes_at_soft_limit /
  398. (soft_limit_hit_at - interval_start_time);
  399. expected /= 60;
  400. } else if (n_seconds_active_in_interval >= MIN_TIME_FOR_MEASUREMENT) {
  401. /* Otherwise, we either measured enough time in the last interval but
  402. * never hit our soft limit, or we're using a state file from a Tor that
  403. * doesn't know to store soft-limit info. Just take rate at which
  404. * we were reading/writing in the last interval as our expected rate.
  405. */
  406. uint64_t used = MAX(n_bytes_written_in_interval,
  407. n_bytes_read_in_interval);
  408. expected = used / (n_seconds_active_in_interval / 60);
  409. } else {
  410. /* If we haven't gotten enough data last interval, set 'expected'
  411. * to 0. This will set our wakeup to the start of the interval.
  412. * Next interval, we'll choose our starting time based on how much
  413. * we sent this interval.
  414. */
  415. expected = 0;
  416. }
  417. if (expected > max_configured)
  418. expected = max_configured;
  419. expected_bandwidth_usage = expected;
  420. }
  421. /** Called at the start of a new accounting interval: reset our
  422. * expected bandwidth usage based on what happened last time, set up
  423. * the start and end of the interval, and clear byte/time totals.
  424. */
  425. static void
  426. reset_accounting(time_t now)
  427. {
  428. log_info(LD_ACCT, "Starting new accounting interval.");
  429. update_expected_bandwidth();
  430. interval_start_time = start_of_accounting_period_containing(now);
  431. interval_end_time = start_of_accounting_period_after(interval_start_time);
  432. n_bytes_read_in_interval = 0;
  433. n_bytes_written_in_interval = 0;
  434. n_seconds_active_in_interval = 0;
  435. n_bytes_at_soft_limit = 0;
  436. soft_limit_hit_at = 0;
  437. n_seconds_to_hit_soft_limit = 0;
  438. }
  439. /** Return true iff we should save our bandwidth usage to disk. */
  440. static INLINE int
  441. time_to_record_bandwidth_usage(time_t now)
  442. {
  443. /* Note every 600 sec */
  444. #define NOTE_INTERVAL (600)
  445. /* Or every 20 megabytes */
  446. #define NOTE_BYTES 20*(1024*1024)
  447. static uint64_t last_read_bytes_noted = 0;
  448. static uint64_t last_written_bytes_noted = 0;
  449. static time_t last_time_noted = 0;
  450. if (last_time_noted + NOTE_INTERVAL <= now ||
  451. last_read_bytes_noted + NOTE_BYTES <= n_bytes_read_in_interval ||
  452. last_written_bytes_noted + NOTE_BYTES <= n_bytes_written_in_interval ||
  453. (interval_end_time && interval_end_time <= now)) {
  454. last_time_noted = now;
  455. last_read_bytes_noted = n_bytes_read_in_interval;
  456. last_written_bytes_noted = n_bytes_written_in_interval;
  457. return 1;
  458. }
  459. return 0;
  460. }
  461. /** Invoked once per second. Checks whether it is time to hibernate,
  462. * record bandwidth used, etc. */
  463. void
  464. accounting_run_housekeeping(time_t now)
  465. {
  466. if (now >= interval_end_time) {
  467. configure_accounting(now);
  468. }
  469. if (time_to_record_bandwidth_usage(now)) {
  470. if (accounting_record_bandwidth_usage(now, get_or_state())) {
  471. log_warn(LD_FS, "Couldn't record bandwidth usage to disk.");
  472. }
  473. }
  474. }
  475. /** Based on our interval and our estimated bandwidth, choose a
  476. * deterministic (but random-ish) time to wake up. */
  477. static void
  478. accounting_set_wakeup_time(void)
  479. {
  480. char digest[DIGEST_LEN];
  481. crypto_digest_t *d_env;
  482. uint64_t time_to_exhaust_bw;
  483. int time_to_consider;
  484. if (! server_identity_key_is_set()) {
  485. if (init_keys() < 0) {
  486. log_err(LD_BUG, "Error initializing keys");
  487. tor_assert(0);
  488. }
  489. }
  490. if (server_identity_key_is_set()) {
  491. char buf[ISO_TIME_LEN+1];
  492. format_iso_time(buf, interval_start_time);
  493. crypto_pk_get_digest(get_server_identity_key(), digest);
  494. d_env = crypto_digest_new();
  495. crypto_digest_add_bytes(d_env, buf, ISO_TIME_LEN);
  496. crypto_digest_add_bytes(d_env, digest, DIGEST_LEN);
  497. crypto_digest_get_digest(d_env, digest, DIGEST_LEN);
  498. crypto_digest_free(d_env);
  499. } else {
  500. crypto_rand(digest, DIGEST_LEN);
  501. }
  502. if (!expected_bandwidth_usage) {
  503. char buf1[ISO_TIME_LEN+1];
  504. char buf2[ISO_TIME_LEN+1];
  505. format_local_iso_time(buf1, interval_start_time);
  506. format_local_iso_time(buf2, interval_end_time);
  507. interval_wakeup_time = interval_start_time;
  508. log_notice(LD_ACCT,
  509. "Configured hibernation. This interval begins at %s "
  510. "and ends at %s. We have no prior estimate for bandwidth, so "
  511. "we will start out awake and hibernate when we exhaust our quota.",
  512. buf1, buf2);
  513. return;
  514. }
  515. time_to_exhaust_bw =
  516. (get_options()->AccountingMax/expected_bandwidth_usage)*60;
  517. if (time_to_exhaust_bw > INT_MAX) {
  518. time_to_exhaust_bw = INT_MAX;
  519. time_to_consider = 0;
  520. } else {
  521. time_to_consider = accounting_get_interval_length() -
  522. (int)time_to_exhaust_bw;
  523. }
  524. if (time_to_consider<=0) {
  525. interval_wakeup_time = interval_start_time;
  526. } else {
  527. /* XXX can we simplify this just by picking a random (non-deterministic)
  528. * time to be up? If we go down and come up, then we pick a new one. Is
  529. * that good enough? -RD */
  530. /* This is not a perfectly unbiased conversion, but it is good enough:
  531. * in the worst case, the first half of the day is 0.06 percent likelier
  532. * to be chosen than the last half. */
  533. interval_wakeup_time = interval_start_time +
  534. (get_uint32(digest) % time_to_consider);
  535. }
  536. {
  537. char buf1[ISO_TIME_LEN+1];
  538. char buf2[ISO_TIME_LEN+1];
  539. char buf3[ISO_TIME_LEN+1];
  540. char buf4[ISO_TIME_LEN+1];
  541. time_t down_time;
  542. if (interval_wakeup_time+time_to_exhaust_bw > TIME_MAX)
  543. down_time = TIME_MAX;
  544. else
  545. down_time = (time_t)(interval_wakeup_time+time_to_exhaust_bw);
  546. if (down_time>interval_end_time)
  547. down_time = interval_end_time;
  548. format_local_iso_time(buf1, interval_start_time);
  549. format_local_iso_time(buf2, interval_wakeup_time);
  550. format_local_iso_time(buf3, down_time);
  551. format_local_iso_time(buf4, interval_end_time);
  552. log_notice(LD_ACCT,
  553. "Configured hibernation. This interval began at %s; "
  554. "the scheduled wake-up time %s %s; "
  555. "we expect%s to exhaust our quota for this interval around %s; "
  556. "the next interval begins at %s (all times local)",
  557. buf1,
  558. time(NULL)<interval_wakeup_time?"is":"was", buf2,
  559. time(NULL)<down_time?"":"ed", buf3,
  560. buf4);
  561. }
  562. }
  563. /* This rounds 0 up to 1000, but that's actually a feature. */
  564. #define ROUND_UP(x) (((x) + 0x3ff) & ~0x3ff)
  565. /** Save all our bandwidth tracking information to disk. Return 0 on
  566. * success, -1 on failure. */
  567. int
  568. accounting_record_bandwidth_usage(time_t now, or_state_t *state)
  569. {
  570. /* Just update the state */
  571. state->AccountingIntervalStart = interval_start_time;
  572. state->AccountingBytesReadInInterval = ROUND_UP(n_bytes_read_in_interval);
  573. state->AccountingBytesWrittenInInterval =
  574. ROUND_UP(n_bytes_written_in_interval);
  575. state->AccountingSecondsActive = n_seconds_active_in_interval;
  576. state->AccountingExpectedUsage = expected_bandwidth_usage;
  577. state->AccountingSecondsToReachSoftLimit = n_seconds_to_hit_soft_limit;
  578. state->AccountingSoftLimitHitAt = soft_limit_hit_at;
  579. state->AccountingBytesAtSoftLimit = n_bytes_at_soft_limit;
  580. or_state_mark_dirty(state,
  581. now+(get_options()->AvoidDiskWrites ? 7200 : 60));
  582. return 0;
  583. }
  584. #undef ROUND_UP
  585. /** Read stored accounting information from disk. Return 0 on success;
  586. * return -1 and change nothing on failure. */
  587. static int
  588. read_bandwidth_usage(void)
  589. {
  590. or_state_t *state = get_or_state();
  591. {
  592. char *fname = get_datadir_fname("bw_accounting");
  593. unlink(fname);
  594. tor_free(fname);
  595. }
  596. if (!state)
  597. return -1;
  598. log_info(LD_ACCT, "Reading bandwidth accounting data from state file");
  599. n_bytes_read_in_interval = state->AccountingBytesReadInInterval;
  600. n_bytes_written_in_interval = state->AccountingBytesWrittenInInterval;
  601. n_seconds_active_in_interval = state->AccountingSecondsActive;
  602. interval_start_time = state->AccountingIntervalStart;
  603. expected_bandwidth_usage = state->AccountingExpectedUsage;
  604. /* Older versions of Tor (before 0.2.2.17-alpha or so) didn't generate these
  605. * fields. If you switch back and forth, you might get an
  606. * AccountingSoftLimitHitAt value from long before the most recent
  607. * interval_start_time. If that's so, then ignore the softlimit-related
  608. * values. */
  609. if (state->AccountingSoftLimitHitAt > interval_start_time) {
  610. soft_limit_hit_at = state->AccountingSoftLimitHitAt;
  611. n_bytes_at_soft_limit = state->AccountingBytesAtSoftLimit;
  612. n_seconds_to_hit_soft_limit = state->AccountingSecondsToReachSoftLimit;
  613. } else {
  614. soft_limit_hit_at = 0;
  615. n_bytes_at_soft_limit = 0;
  616. n_seconds_to_hit_soft_limit = 0;
  617. }
  618. {
  619. char tbuf1[ISO_TIME_LEN+1];
  620. char tbuf2[ISO_TIME_LEN+1];
  621. format_iso_time(tbuf1, state->LastWritten);
  622. format_iso_time(tbuf2, state->AccountingIntervalStart);
  623. log_info(LD_ACCT,
  624. "Successfully read bandwidth accounting info from state written at %s "
  625. "for interval starting at %s. We have been active for %lu seconds in "
  626. "this interval. At the start of the interval, we expected to use "
  627. "about %lu KB per second. ("U64_FORMAT" bytes read so far, "
  628. U64_FORMAT" bytes written so far)",
  629. tbuf1, tbuf2,
  630. (unsigned long)n_seconds_active_in_interval,
  631. (unsigned long)(expected_bandwidth_usage*1024/60),
  632. U64_PRINTF_ARG(n_bytes_read_in_interval),
  633. U64_PRINTF_ARG(n_bytes_written_in_interval));
  634. }
  635. return 0;
  636. }
  637. /** Return true iff we have sent/received all the bytes we are willing
  638. * to send/receive this interval. */
  639. static int
  640. hibernate_hard_limit_reached(void)
  641. {
  642. uint64_t hard_limit = get_options()->AccountingMax;
  643. if (!hard_limit)
  644. return 0;
  645. return n_bytes_read_in_interval >= hard_limit
  646. || n_bytes_written_in_interval >= hard_limit;
  647. }
  648. /** Return true iff we have sent/received almost all the bytes we are willing
  649. * to send/receive this interval. */
  650. static int
  651. hibernate_soft_limit_reached(void)
  652. {
  653. const uint64_t acct_max = get_options()->AccountingMax;
  654. #define SOFT_LIM_PCT (.95)
  655. #define SOFT_LIM_BYTES (500*1024*1024)
  656. #define SOFT_LIM_MINUTES (3*60)
  657. /* The 'soft limit' is a fair bit more complicated now than once it was.
  658. * We want to stop accepting connections when ALL of the following are true:
  659. * - We expect to use up the remaining bytes in under 3 hours
  660. * - We have used up 95% of our bytes.
  661. * - We have less than 500MB of bytes left.
  662. */
  663. uint64_t soft_limit = DBL_TO_U64(U64_TO_DBL(acct_max) * SOFT_LIM_PCT);
  664. if (acct_max > SOFT_LIM_BYTES && acct_max - SOFT_LIM_BYTES > soft_limit) {
  665. soft_limit = acct_max - SOFT_LIM_BYTES;
  666. }
  667. if (expected_bandwidth_usage) {
  668. const uint64_t expected_usage =
  669. expected_bandwidth_usage * SOFT_LIM_MINUTES;
  670. if (acct_max > expected_usage && acct_max - expected_usage > soft_limit)
  671. soft_limit = acct_max - expected_usage;
  672. }
  673. if (!soft_limit)
  674. return 0;
  675. return n_bytes_read_in_interval >= soft_limit
  676. || n_bytes_written_in_interval >= soft_limit;
  677. }
  678. /** Called when we get a SIGINT, or when bandwidth soft limit is
  679. * reached. Puts us into "loose hibernation": we don't accept new
  680. * connections, but we continue handling old ones. */
  681. static void
  682. hibernate_begin(hibernate_state_t new_state, time_t now)
  683. {
  684. const or_options_t *options = get_options();
  685. if (new_state == HIBERNATE_STATE_EXITING &&
  686. hibernate_state != HIBERNATE_STATE_LIVE) {
  687. log_notice(LD_GENERAL,"SIGINT received %s; exiting now.",
  688. hibernate_state == HIBERNATE_STATE_EXITING ?
  689. "a second time" : "while hibernating");
  690. tor_cleanup();
  691. exit(0);
  692. }
  693. if (new_state == HIBERNATE_STATE_LOWBANDWIDTH &&
  694. hibernate_state == HIBERNATE_STATE_LIVE) {
  695. soft_limit_hit_at = now;
  696. n_seconds_to_hit_soft_limit = n_seconds_active_in_interval;
  697. n_bytes_at_soft_limit = MAX(n_bytes_read_in_interval,
  698. n_bytes_written_in_interval);
  699. }
  700. /* close listeners. leave control listener(s). */
  701. connection_mark_all_noncontrol_listeners();
  702. /* XXX kill intro point circs */
  703. /* XXX upload rendezvous service descriptors with no intro points */
  704. if (new_state == HIBERNATE_STATE_EXITING) {
  705. log_notice(LD_GENERAL,"Interrupt: we have stopped accepting new "
  706. "connections, and will shut down in %d seconds. Interrupt "
  707. "again to exit now.", options->ShutdownWaitLength);
  708. shutdown_time = time(NULL) + options->ShutdownWaitLength;
  709. } else { /* soft limit reached */
  710. hibernate_end_time = interval_end_time;
  711. }
  712. hibernate_state = new_state;
  713. accounting_record_bandwidth_usage(now, get_or_state());
  714. or_state_mark_dirty(get_or_state(),
  715. get_options()->AvoidDiskWrites ? now+600 : 0);
  716. }
  717. /** Called when we've been hibernating and our timeout is reached. */
  718. static void
  719. hibernate_end(hibernate_state_t new_state)
  720. {
  721. tor_assert(hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH ||
  722. hibernate_state == HIBERNATE_STATE_DORMANT ||
  723. hibernate_state == HIBERNATE_STATE_INITIAL);
  724. /* listeners will be relaunched in run_scheduled_events() in main.c */
  725. if (hibernate_state != HIBERNATE_STATE_INITIAL)
  726. log_notice(LD_ACCT,"Hibernation period ended. Resuming normal activity.");
  727. hibernate_state = new_state;
  728. hibernate_end_time = 0; /* no longer hibernating */
  729. stats_n_seconds_working = 0; /* reset published uptime */
  730. }
  731. /** A wrapper around hibernate_begin, for when we get SIGINT. */
  732. void
  733. hibernate_begin_shutdown(void)
  734. {
  735. hibernate_begin(HIBERNATE_STATE_EXITING, time(NULL));
  736. }
  737. /** Return true iff we are currently hibernating. */
  738. int
  739. we_are_hibernating(void)
  740. {
  741. return hibernate_state != HIBERNATE_STATE_LIVE;
  742. }
  743. /** If we aren't currently dormant, close all connections and become
  744. * dormant. */
  745. static void
  746. hibernate_go_dormant(time_t now)
  747. {
  748. connection_t *conn;
  749. if (hibernate_state == HIBERNATE_STATE_DORMANT)
  750. return;
  751. else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
  752. hibernate_state = HIBERNATE_STATE_DORMANT;
  753. else
  754. hibernate_begin(HIBERNATE_STATE_DORMANT, now);
  755. log_notice(LD_ACCT,"Going dormant. Blowing away remaining connections.");
  756. /* Close all OR/AP/exit conns. Leave dir conns because we still want
  757. * to be able to upload server descriptors so people know we're still
  758. * running, and download directories so we can detect if we're obsolete.
  759. * Leave control conns because we still want to be controllable.
  760. */
  761. while ((conn = connection_get_by_type(CONN_TYPE_OR)) ||
  762. (conn = connection_get_by_type(CONN_TYPE_AP)) ||
  763. (conn = connection_get_by_type(CONN_TYPE_EXIT))) {
  764. if (CONN_IS_EDGE(conn))
  765. connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_HIBERNATING);
  766. log_info(LD_NET,"Closing conn type %d", conn->type);
  767. if (conn->type == CONN_TYPE_AP) /* send socks failure if needed */
  768. connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
  769. END_STREAM_REASON_HIBERNATING);
  770. else if (conn->type == CONN_TYPE_OR) {
  771. if (TO_OR_CONN(conn)->chan) {
  772. channel_mark_for_close(TLS_CHAN_TO_BASE(TO_OR_CONN(conn)->chan));
  773. } else {
  774. connection_mark_for_close(conn);
  775. }
  776. } else
  777. connection_mark_for_close(conn);
  778. }
  779. if (now < interval_wakeup_time)
  780. hibernate_end_time = interval_wakeup_time;
  781. else
  782. hibernate_end_time = interval_end_time;
  783. accounting_record_bandwidth_usage(now, get_or_state());
  784. or_state_mark_dirty(get_or_state(),
  785. get_options()->AvoidDiskWrites ? now+600 : 0);
  786. }
  787. /** Called when hibernate_end_time has arrived. */
  788. static void
  789. hibernate_end_time_elapsed(time_t now)
  790. {
  791. char buf[ISO_TIME_LEN+1];
  792. /* The interval has ended, or it is wakeup time. Find out which. */
  793. accounting_run_housekeeping(now);
  794. if (interval_wakeup_time <= now) {
  795. /* The interval hasn't changed, but interval_wakeup_time has passed.
  796. * It's time to wake up and start being a server. */
  797. hibernate_end(HIBERNATE_STATE_LIVE);
  798. return;
  799. } else {
  800. /* The interval has changed, and it isn't time to wake up yet. */
  801. hibernate_end_time = interval_wakeup_time;
  802. format_iso_time(buf,interval_wakeup_time);
  803. if (hibernate_state != HIBERNATE_STATE_DORMANT) {
  804. /* We weren't sleeping before; we should sleep now. */
  805. log_notice(LD_ACCT,
  806. "Accounting period ended. Commencing hibernation until "
  807. "%s UTC", buf);
  808. hibernate_go_dormant(now);
  809. } else {
  810. log_notice(LD_ACCT,
  811. "Accounting period ended. This period, we will hibernate"
  812. " until %s UTC",buf);
  813. }
  814. }
  815. }
  816. /** Consider our environment and decide if it's time
  817. * to start/stop hibernating.
  818. */
  819. void
  820. consider_hibernation(time_t now)
  821. {
  822. int accounting_enabled = get_options()->AccountingMax != 0;
  823. char buf[ISO_TIME_LEN+1];
  824. /* If we're in 'exiting' mode, then we just shut down after the interval
  825. * elapses. */
  826. if (hibernate_state == HIBERNATE_STATE_EXITING) {
  827. tor_assert(shutdown_time);
  828. if (shutdown_time <= now) {
  829. log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
  830. tor_cleanup();
  831. exit(0);
  832. }
  833. return; /* if exiting soon, don't worry about bandwidth limits */
  834. }
  835. if (hibernate_state == HIBERNATE_STATE_DORMANT) {
  836. /* We've been hibernating because of bandwidth accounting. */
  837. tor_assert(hibernate_end_time);
  838. if (hibernate_end_time > now && accounting_enabled) {
  839. /* If we're hibernating, don't wake up until it's time, regardless of
  840. * whether we're in a new interval. */
  841. return ;
  842. } else {
  843. hibernate_end_time_elapsed(now);
  844. }
  845. }
  846. /* Else, we aren't hibernating. See if it's time to start hibernating, or to
  847. * go dormant. */
  848. if (hibernate_state == HIBERNATE_STATE_LIVE ||
  849. hibernate_state == HIBERNATE_STATE_INITIAL) {
  850. if (hibernate_soft_limit_reached()) {
  851. log_notice(LD_ACCT,
  852. "Bandwidth soft limit reached; commencing hibernation. "
  853. "No new connections will be accepted");
  854. hibernate_begin(HIBERNATE_STATE_LOWBANDWIDTH, now);
  855. } else if (accounting_enabled && now < interval_wakeup_time) {
  856. format_local_iso_time(buf,interval_wakeup_time);
  857. log_notice(LD_ACCT,
  858. "Commencing hibernation. We will wake up at %s local time.",
  859. buf);
  860. hibernate_go_dormant(now);
  861. } else if (hibernate_state == HIBERNATE_STATE_INITIAL) {
  862. hibernate_end(HIBERNATE_STATE_LIVE);
  863. }
  864. }
  865. if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH) {
  866. if (!accounting_enabled) {
  867. hibernate_end_time_elapsed(now);
  868. } else if (hibernate_hard_limit_reached()) {
  869. hibernate_go_dormant(now);
  870. } else if (hibernate_end_time <= now) {
  871. /* The hibernation period ended while we were still in lowbandwidth.*/
  872. hibernate_end_time_elapsed(now);
  873. }
  874. }
  875. }
  876. /** Helper function: called when we get a GETINFO request for an
  877. * accounting-related key on the control connection <b>conn</b>. If we can
  878. * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
  879. * allocated string holding the result. Otherwise, set *<b>answer</b> to
  880. * NULL. */
  881. int
  882. getinfo_helper_accounting(control_connection_t *conn,
  883. const char *question, char **answer,
  884. const char **errmsg)
  885. {
  886. (void) conn;
  887. (void) errmsg;
  888. if (!strcmp(question, "accounting/enabled")) {
  889. *answer = tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
  890. } else if (!strcmp(question, "accounting/hibernating")) {
  891. if (hibernate_state == HIBERNATE_STATE_DORMANT)
  892. *answer = tor_strdup("hard");
  893. else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
  894. *answer = tor_strdup("soft");
  895. else
  896. *answer = tor_strdup("awake");
  897. } else if (!strcmp(question, "accounting/bytes")) {
  898. tor_asprintf(answer, U64_FORMAT" "U64_FORMAT,
  899. U64_PRINTF_ARG(n_bytes_read_in_interval),
  900. U64_PRINTF_ARG(n_bytes_written_in_interval));
  901. } else if (!strcmp(question, "accounting/bytes-left")) {
  902. uint64_t limit = get_options()->AccountingMax;
  903. uint64_t read_left = 0, write_left = 0;
  904. if (n_bytes_read_in_interval < limit)
  905. read_left = limit - n_bytes_read_in_interval;
  906. if (n_bytes_written_in_interval < limit)
  907. write_left = limit - n_bytes_written_in_interval;
  908. tor_asprintf(answer, U64_FORMAT" "U64_FORMAT,
  909. U64_PRINTF_ARG(read_left), U64_PRINTF_ARG(write_left));
  910. } else if (!strcmp(question, "accounting/interval-start")) {
  911. *answer = tor_malloc(ISO_TIME_LEN+1);
  912. format_iso_time(*answer, interval_start_time);
  913. } else if (!strcmp(question, "accounting/interval-wake")) {
  914. *answer = tor_malloc(ISO_TIME_LEN+1);
  915. format_iso_time(*answer, interval_wakeup_time);
  916. } else if (!strcmp(question, "accounting/interval-end")) {
  917. *answer = tor_malloc(ISO_TIME_LEN+1);
  918. format_iso_time(*answer, interval_end_time);
  919. } else {
  920. *answer = NULL;
  921. }
  922. return 0;
  923. }
  924. #ifdef TOR_UNIT_TESTS
  925. /**
  926. * Manually change the hibernation state. Private; used only by the unit
  927. * tests.
  928. */
  929. void
  930. hibernate_set_state_for_testing_(hibernate_state_t newstate)
  931. {
  932. hibernate_state = newstate;
  933. }
  934. #endif