hibernate.c 29 KB

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