rephist.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. /* Copyright 2004 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file rephist.c
  6. * \brief Basic history functionality for reputation module.
  7. **/
  8. #include "or.h"
  9. static void bw_arrays_init(void);
  10. /** History of an OR-\>OR link. */
  11. typedef struct link_history_t {
  12. /** When did we start tracking this list? */
  13. time_t since;
  14. /** When did we most recently note a change to this link */
  15. time_t changed;
  16. /** How many times did extending from OR1 to OR2 succeeed? */
  17. unsigned long n_extend_ok;
  18. /** How many times did extending from OR1 to OR2 fail? */
  19. unsigned long n_extend_fail;
  20. } link_history_t;
  21. /** History of an OR. */
  22. typedef struct or_history_t {
  23. /** When did we start tracking this OR? */
  24. time_t since;
  25. /** When did we most recently note a change to this OR? */
  26. time_t changed;
  27. /** How many times did we successfully connect? */
  28. unsigned long n_conn_ok;
  29. /** How many times did we try to connect and fail?*/
  30. unsigned long n_conn_fail;
  31. /** How many seconds have we been connected to this OR before
  32. * 'up_since'? */
  33. unsigned long uptime;
  34. /** How many seconds have we been unable to connect to this OR before
  35. * 'down_since'? */
  36. unsigned long downtime;
  37. /** If nonzero, we have been connected since this time. */
  38. time_t up_since;
  39. /** If nonzero, we have been unable to connect since this time. */
  40. time_t down_since;
  41. /** Map from hex OR2 identity digest to a link_history_t for the link
  42. * from this OR to OR2. */
  43. strmap_t *link_history_map;
  44. } or_history_t;
  45. /** Map from hex OR identity digest to or_history_t. */
  46. static strmap_t *history_map = NULL;
  47. /** Return the or_history_t for the named OR, creating it if necessary.
  48. */
  49. static or_history_t *get_or_history(const char* id)
  50. {
  51. or_history_t *hist;
  52. char hexid[HEX_DIGEST_LEN+1];
  53. base16_encode(hexid, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  54. if (!strcmp(hexid, "0000000000000000000000000000000000000000"))
  55. return NULL;
  56. hist = (or_history_t*) strmap_get(history_map, hexid);
  57. if (!hist) {
  58. hist = tor_malloc_zero(sizeof(or_history_t));
  59. hist->link_history_map = strmap_new();
  60. hist->since = hist->changed = time(NULL);
  61. strmap_set(history_map, hexid, hist);
  62. }
  63. return hist;
  64. }
  65. /** Return the link_history_t for the link from the first named OR to
  66. * the second, creating it if necessary. (ORs are identified by
  67. * identity digest)
  68. */
  69. static link_history_t *get_link_history(const char *from_id,
  70. const char *to_id)
  71. {
  72. or_history_t *orhist;
  73. link_history_t *lhist;
  74. char to_hexid[HEX_DIGEST_LEN+1];
  75. orhist = get_or_history(from_id);
  76. if (!orhist)
  77. return NULL;
  78. base16_encode(to_hexid, HEX_DIGEST_LEN+1, to_id, DIGEST_LEN);
  79. if (!strcmp(to_hexid, "0000000000000000000000000000000000000000"))
  80. return NULL;
  81. lhist = (link_history_t*) strmap_get(orhist->link_history_map, to_hexid);
  82. if (!lhist) {
  83. lhist = tor_malloc_zero(sizeof(link_history_t));
  84. lhist->since = lhist->changed = time(NULL);
  85. strmap_set(orhist->link_history_map, to_hexid, lhist);
  86. }
  87. return lhist;
  88. }
  89. static void
  90. _free_link_history(void *val)
  91. {
  92. tor_free(val);
  93. }
  94. static void
  95. free_or_history(or_history_t *hist)
  96. {
  97. strmap_free(hist->link_history_map, _free_link_history);
  98. tor_free(hist);
  99. }
  100. /** Update an or_history_t object <b>hist</b> so that its uptime/downtime
  101. * count is up-to-date as of <b>when</b>.
  102. */
  103. static void update_or_history(or_history_t *hist, time_t when)
  104. {
  105. tor_assert(hist);
  106. if (hist->up_since) {
  107. tor_assert(!hist->down_since);
  108. hist->uptime += (when - hist->up_since);
  109. hist->up_since = when;
  110. } else if (hist->down_since) {
  111. hist->downtime += (when - hist->down_since);
  112. hist->down_since = when;
  113. }
  114. }
  115. /** Initialize the static data structures for tracking history.
  116. */
  117. void rep_hist_init(void)
  118. {
  119. history_map = strmap_new();
  120. bw_arrays_init();
  121. }
  122. /** Remember that an attempt to connect to the OR with identity digest
  123. * <b>id</b> failed at <b>when</b>.
  124. */
  125. void rep_hist_note_connect_failed(const char* id, time_t when)
  126. {
  127. or_history_t *hist;
  128. hist = get_or_history(id);
  129. if (!hist)
  130. return;
  131. ++hist->n_conn_fail;
  132. if (hist->up_since) {
  133. hist->uptime += (when - hist->up_since);
  134. hist->up_since = 0;
  135. }
  136. if (!hist->down_since)
  137. hist->down_since = when;
  138. hist->changed = when;
  139. }
  140. /** Remember that an attempt to connect to the OR with identity digest
  141. * <b>id</b> succeeded at <b>when</b>.
  142. */
  143. void rep_hist_note_connect_succeeded(const char* id, time_t when)
  144. {
  145. or_history_t *hist;
  146. hist = get_or_history(id);
  147. if (!hist)
  148. return;
  149. ++hist->n_conn_ok;
  150. if (hist->down_since) {
  151. hist->downtime += (when - hist->down_since);
  152. hist->down_since = 0;
  153. }
  154. if (!hist->up_since)
  155. hist->up_since = when;
  156. hist->changed = when;
  157. }
  158. /** Remember that we intentionally closed our connection to the OR
  159. * with identity digest <b>id</b> at <b>when</b>.
  160. */
  161. void rep_hist_note_disconnect(const char* id, time_t when)
  162. {
  163. or_history_t *hist;
  164. hist = get_or_history(id);
  165. if (!hist)
  166. return;
  167. ++hist->n_conn_ok;
  168. if (hist->up_since) {
  169. hist->uptime += (when - hist->up_since);
  170. hist->up_since = 0;
  171. }
  172. hist->changed = when;
  173. }
  174. /** Remember that our connection to the OR with identity digest
  175. * <b>id</b> had an error and stopped working at <b>when</b>.
  176. */
  177. void rep_hist_note_connection_died(const char* id, time_t when)
  178. {
  179. or_history_t *hist;
  180. if(!id) {
  181. /* XXXX009 Well, everybody has an ID now. Hm. */
  182. /* If conn has no nickname, it's either an OP, or it is an OR
  183. * which didn't complete its handshake (or did and was unapproved).
  184. * Ignore it.
  185. */
  186. return;
  187. }
  188. hist = get_or_history(id);
  189. if (!hist)
  190. return;
  191. if (hist->up_since) {
  192. hist->uptime += (when - hist->up_since);
  193. hist->up_since = 0;
  194. }
  195. if (!hist->down_since)
  196. hist->down_since = when;
  197. hist->changed = when;
  198. }
  199. /** Remember that we successfully extended from the OR with identity
  200. * digest <b>from_id</b> to the OR with identity digest
  201. * <b>to_name</b>.
  202. */
  203. void rep_hist_note_extend_succeeded(const char *from_id,
  204. const char *to_id)
  205. {
  206. link_history_t *hist;
  207. /* log_fn(LOG_WARN, "EXTEND SUCCEEDED: %s->%s",from_name,to_name); */
  208. hist = get_link_history(from_id, to_id);
  209. if (!hist)
  210. return;
  211. ++hist->n_extend_ok;
  212. hist->changed = time(NULL);
  213. }
  214. /** Remember that we tried to extend from the OR with identity digest
  215. * <b>from_id</b> to the OR with identity digest <b>to_name</b>, but
  216. * failed.
  217. */
  218. void rep_hist_note_extend_failed(const char *from_id, const char *to_id)
  219. {
  220. link_history_t *hist;
  221. /* log_fn(LOG_WARN, "EXTEND FAILED: %s->%s",from_name,to_name); */
  222. hist = get_link_history(from_id, to_id);
  223. if (!hist)
  224. return;
  225. ++hist->n_extend_fail;
  226. hist->changed = time(NULL);
  227. }
  228. /** Log all the reliability data we have rememberred, with the chosen
  229. * severity.
  230. */
  231. void rep_hist_dump_stats(time_t now, int severity)
  232. {
  233. strmap_iter_t *lhist_it;
  234. strmap_iter_t *orhist_it;
  235. const char *name1, *name2, *hexdigest1, *hexdigest2;
  236. or_history_t *or_history;
  237. link_history_t *link_history;
  238. void *or_history_p, *link_history_p;
  239. double uptime;
  240. char buffer[2048];
  241. size_t len;
  242. int ret;
  243. unsigned long upt, downt;
  244. routerinfo_t *r;
  245. rep_history_clean(now-24*60*60);
  246. log(severity, "--------------- Dumping history information:");
  247. for (orhist_it = strmap_iter_init(history_map); !strmap_iter_done(orhist_it);
  248. orhist_it = strmap_iter_next(history_map,orhist_it)) {
  249. strmap_iter_get(orhist_it, &hexdigest1, &or_history_p);
  250. or_history = (or_history_t*) or_history_p;
  251. if ((r = router_get_by_hexdigest(hexdigest1)))
  252. name1 = r->nickname;
  253. else
  254. name1 = "(unknown)";
  255. update_or_history(or_history, now);
  256. upt = or_history->uptime;
  257. downt = or_history->downtime;
  258. if (upt+downt) {
  259. uptime = ((double)upt) / (upt+downt);
  260. } else {
  261. uptime=1.0;
  262. }
  263. log(severity,
  264. "OR %s [%s]: %ld/%ld good connections; uptime %ld/%ld sec (%.2f%%)",
  265. name1, hexdigest1,
  266. or_history->n_conn_ok, or_history->n_conn_fail+or_history->n_conn_ok,
  267. upt, upt+downt, uptime*100.0);
  268. if (!strmap_isempty(or_history->link_history_map)) {
  269. strlcpy(buffer, " Good extend attempts: ", sizeof(buffer));
  270. len = strlen(buffer);
  271. for (lhist_it = strmap_iter_init(or_history->link_history_map);
  272. !strmap_iter_done(lhist_it);
  273. lhist_it = strmap_iter_next(or_history->link_history_map, lhist_it)) {
  274. strmap_iter_get(lhist_it, &hexdigest2, &link_history_p);
  275. if ((r = router_get_by_hexdigest(hexdigest2)))
  276. name2 = r->nickname;
  277. else
  278. name2 = "(unknown)";
  279. link_history = (link_history_t*) link_history_p;
  280. ret = tor_snprintf(buffer+len, 2048-len, "%s(%ld/%ld); ", name2,
  281. link_history->n_extend_ok,
  282. link_history->n_extend_ok+link_history->n_extend_fail);
  283. if (ret<0)
  284. break;
  285. else
  286. len += ret;
  287. }
  288. log(severity, "%s", buffer);
  289. }
  290. }
  291. }
  292. /** Remove history info for routers/links that haven't changed since
  293. * <b>before</b> */
  294. void rep_history_clean(time_t before)
  295. {
  296. or_history_t *or_history;
  297. link_history_t *link_history;
  298. void *or_history_p, *link_history_p;
  299. strmap_iter_t *orhist_it, *lhist_it;
  300. const char *hd1, *hd2;
  301. orhist_it = strmap_iter_init(history_map);
  302. while (!strmap_iter_done(orhist_it)) {
  303. strmap_iter_get(orhist_it, &hd1, &or_history_p);
  304. or_history = or_history_p;
  305. if (or_history->changed < before) {
  306. free_or_history(or_history);
  307. orhist_it = strmap_iter_next_rmv(history_map, orhist_it);
  308. continue;
  309. }
  310. for (lhist_it = strmap_iter_init(or_history->link_history_map);
  311. !strmap_iter_done(lhist_it); ) {
  312. strmap_iter_get(lhist_it, &hd2, &link_history_p);
  313. link_history = link_history_p;
  314. if (link_history->changed < before) {
  315. tor_free(link_history);
  316. lhist_it = strmap_iter_next_rmv(or_history->link_history_map,lhist_it);
  317. continue;
  318. }
  319. lhist_it = strmap_iter_next(or_history->link_history_map,lhist_it);
  320. }
  321. orhist_it = strmap_iter_next(history_map, orhist_it);
  322. }
  323. }
  324. #if 0
  325. void write_rep_history(const char *filename)
  326. {
  327. FILE *f = NULL;
  328. char *tmpfile;
  329. int completed = 0;
  330. or_history_t *or_history;
  331. link_history_t *link_history;
  332. strmap_iter_t *lhist_it;
  333. strmap_iter_t *orhist_it;
  334. void *or_history_p, *link_history_p;
  335. const char *name1;
  336. tmpfile = tor_malloc(strlen(filename)+5);
  337. tor_snprintf(tmpfile, strlen(filename)+5, "%s_tmp", filename);
  338. f = fopen(tmpfile, "w");
  339. if (!f) goto done;
  340. for (orhist_it = strmap_iter_init(history_map); !strmap_iter_done(orhist_it);
  341. orhist_it = strmap_iter_next(history_map,orhist_it)) {
  342. strmap_iter_get(orhist_it, &name1, &or_history_p);
  343. or_history = (or_history_t*) or_history_p;
  344. fprintf(f, "link %s connected:u%ld failed:%uld uptime:%uld",
  345. name1, or_history->since1,
  346. }
  347. done:
  348. if (f)
  349. fclose(f);
  350. if (completed)
  351. replace_file(filename, tmpfile);
  352. else
  353. unlink(tmpfile);
  354. tor_free(tmpfile);
  355. }
  356. #endif
  357. #define NUM_SECS_ROLLING_MEASURE 10
  358. #define NUM_SECS_BW_SUM_IS_VALID (24*60*60) /* one day */
  359. #define NUM_SECS_BW_SUM_INTERVAL (15*60)
  360. #define NUM_TOTALS (NUM_SECS_BW_SUM_IS_VALID/NUM_SECS_BW_SUM_INTERVAL)
  361. /**
  362. * Structure to track bandwidth use, and remember the maxima for a given
  363. * time period.
  364. */
  365. typedef struct bw_array_t {
  366. /** Observation array: Total number of bytes transferred in each of the last
  367. * NUM_SECS_ROLLING_MEASURE seconds. This is used as a circular array. */
  368. int obs[NUM_SECS_ROLLING_MEASURE];
  369. int cur_obs_idx; /**< Current position in obs. */
  370. time_t cur_obs_time; /**< Time represented in obs[cur_obs_idx] */
  371. int total_obs; /**< Total for all members of obs except obs[cur_obs_idx] */
  372. int max_total; /**< Largest value that total_obs has taken on in the current
  373. * period. */
  374. int total_in_period; /**< Total bytes transferred in the current period. */
  375. /** When does the next period begin? */
  376. time_t next_period;
  377. /** Where in 'maxima' should the maximum bandwidth usage for the current
  378. * period be stored? */
  379. int next_max_idx;
  380. /** How many values in maxima/totals have been set ever? */
  381. int num_maxes_set;
  382. /** Circular array of the maximum
  383. * bandwidth-per-NUM_SECS_ROLLING_MEASURE usage for the last
  384. * NUM_TOTALS periods */
  385. int maxima[NUM_TOTALS];
  386. /** Circular array of the total bandwidth usage for the last NUM_TOTALS
  387. * periods */
  388. int totals[NUM_TOTALS];
  389. } bw_array_t;
  390. /** Shift the current period of b forward by one.
  391. */
  392. static void commit_max(bw_array_t *b) {
  393. /* Store total from current period. */
  394. b->totals[b->next_max_idx] = b->total_in_period;
  395. /* Store maximum from current period. */
  396. b->maxima[b->next_max_idx++] = b->max_total;
  397. /* Advance next_period and next_max_idx */
  398. b->next_period += NUM_SECS_BW_SUM_INTERVAL;
  399. if (b->next_max_idx == NUM_TOTALS)
  400. b->next_max_idx = 0;
  401. if (b->num_maxes_set < NUM_TOTALS)
  402. ++b->num_maxes_set;
  403. /* Reset max_total. */
  404. b->max_total = 0;
  405. /* Reset total_in_period. */
  406. b->total_in_period = 0;
  407. }
  408. /** Shift the current observation time of 'b' forward by one second.
  409. */
  410. static INLINE void advance_obs(bw_array_t *b) {
  411. int nextidx;
  412. int total;
  413. /* Calculate the total bandwidth for the last NUM_SECS_ROLLING_MEASURE
  414. * seconds; adjust max_total as needed.*/
  415. total = b->total_obs + b->obs[b->cur_obs_idx];
  416. if (total > b->max_total)
  417. b->max_total = total;
  418. nextidx = b->cur_obs_idx+1;
  419. if (nextidx == NUM_SECS_ROLLING_MEASURE)
  420. nextidx = 0;
  421. b->total_obs = total - b->obs[nextidx];
  422. b->obs[nextidx]=0;
  423. b->cur_obs_idx = nextidx;
  424. if (++b->cur_obs_time >= b->next_period)
  425. commit_max(b);
  426. }
  427. /** Add 'n' bytes to the number of bytes in b for second 'when'.
  428. */
  429. static INLINE void add_obs(bw_array_t *b, time_t when, int n) {
  430. /* Don't record data in the past. */
  431. if (when<b->cur_obs_time)
  432. return;
  433. /* If we're currently adding observations for an earlier second than
  434. * 'when', advance b->cur_obs_time and b->cur_obs_idx by an
  435. * appropriate number of seconds, and do all the other housekeeping */
  436. while (when>b->cur_obs_time)
  437. advance_obs(b);
  438. b->obs[b->cur_obs_idx] += n;
  439. b->total_in_period += n;
  440. }
  441. /** Allocate, initialize, and return a new bw_array.
  442. */
  443. static bw_array_t *bw_array_new(void) {
  444. bw_array_t *b;
  445. time_t start;
  446. b = tor_malloc_zero(sizeof(bw_array_t));
  447. start = time(NULL);
  448. b->cur_obs_time = start;
  449. b->next_period = start + NUM_SECS_BW_SUM_INTERVAL;
  450. return b;
  451. }
  452. static bw_array_t *read_array = NULL;
  453. static bw_array_t *write_array = NULL;
  454. /** Set up read_array and write_array
  455. */
  456. static void bw_arrays_init(void)
  457. {
  458. read_array = bw_array_new();
  459. write_array = bw_array_new();
  460. }
  461. /** We read <b>num_bytes</b> more bytes in second <b>when</b>.
  462. *
  463. * Add num_bytes to the current running total for <b>when</b>.
  464. *
  465. * <b>when</b> can go back to time, but it's safe to ignore calls
  466. * earlier than the latest <b>when</b> you've heard of.
  467. */
  468. void rep_hist_note_bytes_written(int num_bytes, time_t when) {
  469. /* Maybe a circular array for recent seconds, and step to a new point
  470. * every time a new second shows up. Or simpler is to just to have
  471. * a normal array and push down each item every second; it's short.
  472. */
  473. /* When a new second has rolled over, compute the sum of the bytes we've
  474. * seen over when-1 to when-1-NUM_SECS_ROLLING_MEASURE, and stick it
  475. * somewhere. See rep_hist_bandwidth_assess() below.
  476. */
  477. add_obs(write_array, when, num_bytes);
  478. }
  479. /** We wrote <b>num_bytes</b> more bytes in second <b>when</b>.
  480. * (like rep_hist_note_bytes_written() above)
  481. */
  482. void rep_hist_note_bytes_read(int num_bytes, time_t when) {
  483. /* if we're smart, we can make this func and the one above share code */
  484. add_obs(read_array, when, num_bytes);
  485. }
  486. /** Helper: Return the largest value in b->maxima. (This is equal to the
  487. * most bandwidth used in any NUM_SECS_ROLLING_MEASURE period for the last
  488. * NUM_SECS_BW_SUM_IS_VALID seconds.)
  489. */
  490. static int find_largest_max(bw_array_t *b)
  491. {
  492. int i,max;
  493. max=0;
  494. for (i=0; i<NUM_TOTALS; ++i) {
  495. if (b->maxima[i]>max)
  496. max = b->maxima[i];
  497. }
  498. return max;
  499. }
  500. /**
  501. * Find the largest sums in the past NUM_SECS_BW_SUM_IS_VALID (roughly)
  502. * seconds. Find one sum for reading and one for writing. They don't have
  503. * to be at the same time).
  504. *
  505. * Return the smaller of these sums, divided by NUM_SECS_ROLLING_MEASURE.
  506. */
  507. int rep_hist_bandwidth_assess(void) {
  508. int w,r;
  509. r = find_largest_max(read_array);
  510. w = find_largest_max(write_array);
  511. if (r>w)
  512. return (int)(w/(double)NUM_SECS_ROLLING_MEASURE);
  513. else
  514. return (int)(r/(double)NUM_SECS_ROLLING_MEASURE);
  515. return 0;
  516. }
  517. /**
  518. * Allocate and return lines for representing this server's bandwidth
  519. * history in its descriptor.
  520. */
  521. char *
  522. rep_hist_get_bandwidth_lines(void)
  523. {
  524. char *buf, *cp;
  525. char t[ISO_TIME_LEN+1];
  526. int r, i, n;
  527. bw_array_t *b;
  528. size_t len;
  529. /* opt (read|write)-history yyyy-mm-dd HH:MM:SS (n s) n,n,n,n,n... */
  530. len = (60+12*NUM_TOTALS)*2;
  531. buf = tor_malloc_zero(len);
  532. cp = buf;
  533. for (r=0;r<2;++r) {
  534. b = r?read_array:write_array;
  535. tor_assert(b);
  536. format_iso_time(t, b->next_period-NUM_SECS_BW_SUM_INTERVAL);
  537. tor_snprintf(cp, len-(cp-buf), "opt %s %s (%d s) ", r?"read-history ":"write-history", t,
  538. NUM_SECS_BW_SUM_INTERVAL);
  539. cp += strlen(cp);
  540. if (b->num_maxes_set <= b->next_max_idx)
  541. /* We haven't been through the circular array yet; time starts at i=0.*/
  542. i = 0;
  543. else
  544. /* We've been arround the array at least once. The next i to be
  545. overwritten is the oldest. */
  546. i = b->next_max_idx;
  547. for (n=0; n<b->num_maxes_set; ++n,++i) {
  548. while (i >= NUM_TOTALS) i -= NUM_TOTALS;
  549. if (n==(b->num_maxes_set-1))
  550. tor_snprintf(cp, len-(cp-buf), "%d", b->totals[i]);
  551. else
  552. tor_snprintf(cp, len-(cp-buf), "%d,", b->totals[i]);
  553. cp += strlen(cp);
  554. }
  555. strlcat(cp, "\n", len-(cp-buf));
  556. ++cp;
  557. }
  558. return buf;
  559. }