rephist.c 16 KB

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