Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for an external clock in token bucket. #234

Merged
merged 2 commits into from
Apr 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions userspace/engine/token_bucket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,24 @@ token_bucket::~token_bucket()
{
}

void token_bucket::init(uint32_t rate, uint32_t max_tokens)
void token_bucket::init(double rate, double max_tokens)
{
m_rate = rate;
m_max_tokens = max_tokens;
m_tokens = max_tokens;
m_last_seen = sinsp_utils::get_current_time_ns();
}

bool token_bucket::claim()
bool token_bucket::claim(uint64_t now)
{
// Determine the number of tokens gained. Delta between
// last_seen and now, divided by the rate.
uint64_t now = sinsp_utils::get_current_time_ns();
uint64_t tokens_gained = (now - m_last_seen) / (m_rate * 1000000000);
if(now == 0)
{
now = sinsp_utils::get_current_time_ns();
}

double tokens_gained = (now - m_last_seen) / (m_rate * 1000000000);
m_last_seen = now;

m_tokens += tokens_gained;
Expand Down
10 changes: 5 additions & 5 deletions userspace/engine/token_bucket.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,30 +31,30 @@ class token_bucket
//
// Initialize the token bucket and start accumulating tokens
//
void init(uint32_t rate, uint32_t max_tokens);
void init(double rate, double max_tokens);

//
// Returns true if a token can be claimed. Also updates
// internal metrics.
//
bool claim();
bool claim(uint64_t now = 0);
private:

//
// The number of tokens generated per second.
//
uint64_t m_rate;
double m_rate;

//
// The maximum number of tokens that can be banked for future
// claim()s.
//
uint64_t m_max_tokens;
double m_max_tokens;

//
// The current number of tokens
//
uint64_t m_tokens;
double m_tokens;

//
// The last time claim() was called (or the object was created).
Expand Down