ratelim.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file ratelim.h
  7. * \brief Summarize similar messages that would otherwise flood the logs.
  8. **/
  9. #ifndef TOR_RATELIM_H
  10. #define TOR_RATELIM_H
  11. #include <time.h>
  12. /* Rate-limiter */
  13. /** A ratelim_t remembers how often an event is occurring, and how often
  14. * it's allowed to occur. Typical usage is something like:
  15. *
  16. <pre>
  17. if (possibly_very_frequent_event()) {
  18. const int INTERVAL = 300;
  19. static ratelim_t warning_limit = RATELIM_INIT(INTERVAL);
  20. char *m;
  21. if ((m = rate_limit_log(&warning_limit, approx_time()))) {
  22. log_warn(LD_GENERAL, "The event occurred!%s", m);
  23. tor_free(m);
  24. }
  25. }
  26. </pre>
  27. As a convenience wrapper for logging, you can replace the above with:
  28. <pre>
  29. if (possibly_very_frequent_event()) {
  30. static ratelim_t warning_limit = RATELIM_INIT(300);
  31. log_fn_ratelim(&warning_limit, LOG_WARN, LD_GENERAL,
  32. "The event occurred!");
  33. }
  34. </pre>
  35. */
  36. typedef struct ratelim_t {
  37. int rate;
  38. time_t last_allowed;
  39. int n_calls_since_last_time;
  40. } ratelim_t;
  41. #define RATELIM_INIT(r) { (r), 0, 0 }
  42. #define RATELIM_TOOMANY (16*1000*1000)
  43. char *rate_limit_log(ratelim_t *lim, time_t now);
  44. #endif