Directory: | cvmfs/ |
---|---|
File: | cvmfs/backoff.cc |
Date: | 2025-02-09 02:34:19 |
Exec | Total | Coverage | |
---|---|---|---|
Lines: | 38 | 39 | 97.4% |
Branches: | 8 | 10 | 80.0% |
Line | Branch | Exec | Source |
---|---|---|---|
1 | /** | ||
2 | * This file is part of the CernVM File System. | ||
3 | * | ||
4 | * Exponential backoff (sleep) with cutoff. | ||
5 | */ | ||
6 | |||
7 | |||
8 | #include "backoff.h" | ||
9 | |||
10 | #include <ctime> | ||
11 | |||
12 | #include "util/logging.h" | ||
13 | #include "util/posix.h" | ||
14 | #include "util/smalloc.h" | ||
15 | |||
16 | using namespace std; // NOLINT | ||
17 | |||
18 | 250105 | void BackoffThrottle::Init(const unsigned init_delay_ms, | |
19 | const unsigned max_delay_ms, | ||
20 | const unsigned reset_after_ms) | ||
21 | { | ||
22 | 250105 | init_delay_ms_ = init_delay_ms; | |
23 | 250105 | max_delay_ms_ = max_delay_ms; | |
24 | 250105 | reset_after_ms_ = reset_after_ms; | |
25 | 250105 | prng_.InitLocaltime(); | |
26 | |||
27 | 250126 | lock_ = | |
28 | 250138 | reinterpret_cast<pthread_mutex_t *>(smalloc(sizeof(pthread_mutex_t))); | |
29 | 250126 | int retval = pthread_mutex_init(lock_, NULL); | |
30 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 250135 times.
|
250135 | assert(retval == 0); |
31 | |||
32 | 250135 | Reset(); | |
33 | 250158 | } | |
34 | |||
35 | |||
36 | 249773 | BackoffThrottle::~BackoffThrottle() { | |
37 | 249773 | pthread_mutex_destroy(lock_); | |
38 | 249775 | free(lock_); | |
39 | 249775 | } | |
40 | |||
41 | |||
42 | 250161 | void BackoffThrottle::Reset() { | |
43 | 250161 | pthread_mutex_lock(lock_); | |
44 | 250205 | delay_range_ = 0; | |
45 | 250205 | last_throttle_ = 0; | |
46 | 250205 | pthread_mutex_unlock(lock_); | |
47 | 250184 | } | |
48 | |||
49 | |||
50 | 15 | void BackoffThrottle::Throttle() { | |
51 | 15 | time_t now = time(NULL); | |
52 | |||
53 | 15 | pthread_mutex_lock(lock_); | |
54 |
2/2✓ Branch 0 taken 9 times.
✓ Branch 1 taken 6 times.
|
15 | if (unsigned(now - last_throttle_) < reset_after_ms_/1000) { |
55 |
2/2✓ Branch 0 taken 7 times.
✓ Branch 1 taken 2 times.
|
9 | if (delay_range_ < max_delay_ms_) { |
56 |
2/2✓ Branch 0 taken 3 times.
✓ Branch 1 taken 4 times.
|
7 | if (delay_range_ == 0) |
57 | 3 | delay_range_ = init_delay_ms_; | |
58 | else | ||
59 | 4 | delay_range_ *= 2; | |
60 | } | ||
61 | 9 | unsigned delay = prng_.Next(delay_range_) + 1; | |
62 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 9 times.
|
9 | if (delay > max_delay_ms_) |
63 | ✗ | delay = max_delay_ms_; | |
64 | |||
65 | 9 | pthread_mutex_unlock(lock_); | |
66 | 9 | LogCvmfs(kLogCvmfs, kLogDebug, "backoff throttle %d ms", delay); | |
67 | 9 | SafeSleepMs(delay); | |
68 | 9 | pthread_mutex_lock(lock_); | |
69 | } | ||
70 | 15 | last_throttle_ = now; | |
71 | 15 | pthread_mutex_unlock(lock_); | |
72 | 15 | } | |
73 |