You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

131 lines
1.9 KiB

6 years ago
6 years ago
  1. #include "policy_cache.hpp"
  2. #include <cstdlib>
  3. #include <map>
  4. #include <string>
  5. #include <time.h>
  6. using std::map;
  7. using std::string;
  8. static const uint64_t DEFAULT_TIMEOUT = 0;
  9. namespace l
  10. {
  11. static
  12. uint64_t
  13. get_time(void)
  14. {
  15. uint64_t rv;
  16. rv = ::time(NULL);
  17. return rv;
  18. }
  19. }
  20. PolicyCache::Value::Value()
  21. : time(0),
  22. paths()
  23. {
  24. }
  25. PolicyCache::PolicyCache(void)
  26. : timeout(DEFAULT_TIMEOUT)
  27. {
  28. pthread_mutex_init(&_lock,NULL);
  29. }
  30. void
  31. PolicyCache::erase(const char *fusepath_)
  32. {
  33. if(timeout == 0)
  34. return;
  35. pthread_mutex_lock(&_lock);
  36. _cache.erase(fusepath_);
  37. pthread_mutex_unlock(&_lock);
  38. }
  39. void
  40. PolicyCache::cleanup(const int prob_)
  41. {
  42. uint64_t now;
  43. map<string,Value>::iterator i;
  44. if(timeout == 0)
  45. return;
  46. if(rand() % prob_)
  47. return;
  48. now = l::get_time();
  49. pthread_mutex_lock(&_lock);
  50. i = _cache.begin();
  51. while(i != _cache.end())
  52. {
  53. if((now - i->second.time) >= timeout)
  54. _cache.erase(i++);
  55. else
  56. ++i;
  57. }
  58. pthread_mutex_unlock(&_lock);
  59. }
  60. void
  61. PolicyCache::clear(void)
  62. {
  63. pthread_mutex_lock(&_lock);
  64. _cache.clear();
  65. pthread_mutex_unlock(&_lock);
  66. }
  67. int
  68. PolicyCache::operator()(const Policy::Search &policy_,
  69. const Branches &branches_,
  70. const char *fusepath_,
  71. StrVec *paths_)
  72. {
  73. int rv;
  74. Value *v;
  75. uint64_t now;
  76. if(timeout == 0)
  77. return policy_(branches_,fusepath_,paths_);
  78. now = l::get_time();
  79. pthread_mutex_lock(&_lock);
  80. v = &_cache[fusepath_];
  81. if((now - v->time) >= timeout)
  82. {
  83. pthread_mutex_unlock(&_lock);
  84. rv = policy_(branches_,fusepath_,paths_);
  85. if(rv == -1)
  86. return -1;
  87. pthread_mutex_lock(&_lock);
  88. v->time = now;
  89. v->paths = *paths_;
  90. }
  91. else
  92. {
  93. *paths_ = v->paths;
  94. }
  95. pthread_mutex_unlock(&_lock);
  96. return 0;
  97. }