forked from lizan/service-control-client-cxx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distribution_helper.cc
309 lines (275 loc) · 11.1 KB
/
distribution_helper.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "distribution_helper.h"
#include <algorithm>
#include <cmath>
#include <iterator>
#include <sstream>
using ::google::api::servicecontrol::v1::Distribution;
using ::google::protobuf::util::Status;
using ::google::protobuf::util::error::Code;
namespace google {
namespace service_control_client {
namespace {
// Concatenate a string with an non string.
template <class T>
std::string StrCat(const char* str, T v) {
std::ostringstream buffer;
buffer.str(str);
buffer << v;
return buffer.str();
}
// Updates general statistics other than bucket count.
void UpdateGeneralStatictics(double value, Distribution* distribution) {
if (distribution->count() == 0) {
distribution->set_count(1);
distribution->set_maximum(value);
distribution->set_minimum(value);
distribution->set_mean(value);
distribution->set_sum_of_squared_deviation(0);
} else {
int64_t count = distribution->count();
double mean = distribution->mean();
double new_mean = (count * mean + value) / (count + 1);
// The formula is optimized for minimum round off error (no large values in
// intermediate results).
distribution->set_sum_of_squared_deviation(
distribution->sum_of_squared_deviation() +
((value - mean) * (value - new_mean)));
distribution->set_count(count + 1);
distribution->set_minimum(std::min(value, distribution->minimum()));
distribution->set_maximum(std::max(value, distribution->maximum()));
distribution->set_mean(new_mean);
}
}
inline bool IsCloseEnough(double x, double y) {
const double epsilon = 1e-5;
return std::abs(x - y) <= epsilon * std::abs(x);
}
// Checks whether the bucket definitions in the two distributions are
// approximately equal. We use this instead of
// MessageDifferencer::ApproximatelyEquals mainly for performance reasons.
bool BucketsApproximatelyEqual(const Distribution& first,
const Distribution& second) {
if (first.bucket_option_case() != second.bucket_option_case()) {
return false;
}
switch (first.bucket_option_case()) {
case Distribution::kLinearBuckets: {
const auto& first_linear = first.linear_buckets();
const auto& second_linear = second.linear_buckets();
if (first_linear.num_finite_buckets() !=
second_linear.num_finite_buckets()) {
return false;
}
if (!IsCloseEnough(first_linear.width(), second_linear.width())) {
return false;
}
if (!IsCloseEnough(first_linear.offset(), second_linear.offset())) {
return false;
}
break;
}
case Distribution::kExponentialBuckets: {
const auto& first_exponential = first.exponential_buckets();
const auto& second_exponential = second.exponential_buckets();
if (first_exponential.num_finite_buckets() !=
second_exponential.num_finite_buckets()) {
return false;
}
if (!IsCloseEnough(first_exponential.growth_factor(),
second_exponential.growth_factor())) {
return false;
}
if (!IsCloseEnough(first_exponential.scale(),
second_exponential.scale())) {
return false;
}
break;
}
case Distribution::kExplicitBuckets: {
const auto& first_explicit = first.explicit_buckets();
const auto& second_explicit = second.explicit_buckets();
if (first_explicit.bounds_size() != second_explicit.bounds_size()) {
return false;
}
for (int i = 0; i < first_explicit.bounds_size(); ++i) {
if (!IsCloseEnough(first_explicit.bounds(i),
second_explicit.bounds(i))) {
return false;
}
}
break;
}
default:
return false;
}
return true;
}
void UpdateExponentialBucketCount(double value, Distribution* distribution) {
const auto& exponential = distribution->exponential_buckets();
int bucket_index = 0;
if (value >= exponential.scale()) {
// Should be put into bucket bucket_index, starting from 0.
bucket_index = 1 + static_cast<int>(log2(value / exponential.scale()) /
log2(exponential.growth_factor()));
if (bucket_index > exponential.num_finite_buckets() + 1) {
bucket_index = exponential.num_finite_buckets() + 1;
}
}
distribution->set_bucket_counts(
bucket_index, distribution->bucket_counts(bucket_index) + 1);
}
void UpdateLinearBucketCount(double value, Distribution* distribution) {
const auto& linear = distribution->linear_buckets();
double upper_bound =
linear.offset() + linear.num_finite_buckets() * linear.width();
double lower_bound = linear.offset();
int bucket_index;
if (value < lower_bound || std::isnan(value)) {
bucket_index = 0;
} else if (value >= upper_bound) {
bucket_index = linear.num_finite_buckets() + 1;
} else {
bucket_index = 1 + static_cast<int>((value - lower_bound) / linear.width());
}
distribution->set_bucket_counts(
bucket_index, distribution->bucket_counts(bucket_index) + 1);
}
void UpdateExplicitBucketCount(double value, Distribution* distribution) {
const auto& bounds = distribution->explicit_buckets().bounds();
int bucket_index = 0;
if (value >= bounds.Get(0)) {
// -inf < b0 < b1 < b2 < b3 < +inf (4 values in "bounds")
// | 0 | 1 | 2 | 3 | 4 | (5 buckets)
// std::upper_bound returns the first value that is greater than given one.
bucket_index = std::distance(
bounds.begin(), std::upper_bound(bounds.begin(), bounds.end(), value));
}
distribution->set_bucket_counts(
bucket_index, distribution->bucket_counts(bucket_index) + 1);
}
} // namespace
Status DistributionHelper::InitExponential(int num_finite_buckets,
double growth_factor, double scale,
Distribution* distribution) {
if (num_finite_buckets <= 0) {
return Status(Code::INVALID_ARGUMENT,
StrCat("Argument num_finite_buckets should be > 0. pass in: ",
num_finite_buckets));
}
if (growth_factor <= 1.0) {
return Status(Code::INVALID_ARGUMENT,
StrCat("Argument growth_factor should be > 1.0. pass in: ",
growth_factor));
}
if (scale <= 0) {
return Status(Code::INVALID_ARGUMENT,
StrCat("Argument scale should be > 0. pass in: ", scale));
}
auto* exponential = distribution->mutable_exponential_buckets();
exponential->set_num_finite_buckets(num_finite_buckets);
exponential->set_growth_factor(growth_factor);
exponential->set_scale(scale);
distribution->mutable_bucket_counts()->Resize(num_finite_buckets + 2, 0);
return Status::OK;
}
Status DistributionHelper::InitLinear(int num_finite_buckets, double width,
double offset,
Distribution* distribution) {
if (num_finite_buckets <= 0) {
return Status(Code::INVALID_ARGUMENT,
StrCat("Argument num_finite_buckets should be > 0. pass in: ",
num_finite_buckets));
}
if (width <= 0.0) {
return Status(Code::INVALID_ARGUMENT,
StrCat("Argument width should be > 0.0. pass in: ", width));
}
auto* linear = distribution->mutable_linear_buckets();
linear->set_num_finite_buckets(num_finite_buckets);
linear->set_width(width);
linear->set_offset(offset);
distribution->mutable_bucket_counts()->Resize(num_finite_buckets + 2, 0);
return Status::OK;
}
Status DistributionHelper::InitExplicit(const std::vector<double>& bounds,
Distribution* distribution) {
if (!std::is_sorted(bounds.begin(), bounds.end())) {
return Status(Code::INVALID_ARGUMENT, "Argument bounds should be sorted.");
}
if (std::adjacent_find(bounds.begin(), bounds.end()) != bounds.end()) {
return Status(
Code::INVALID_ARGUMENT,
"Two adjacent elements in argument bounds should NOT be the same.");
}
auto* explicit_buckets = distribution->mutable_explicit_buckets();
for (unsigned int i = 0; i < bounds.size(); ++i) {
explicit_buckets->mutable_bounds()->Add(bounds.at(i));
}
distribution->mutable_bucket_counts()->Resize(bounds.size() + 1, 0);
return Status::OK;
}
Status DistributionHelper::AddSample(double value, Distribution* distribution) {
switch (distribution->bucket_option_case()) {
case Distribution::kExponentialBuckets:
UpdateGeneralStatictics(value, distribution);
UpdateExponentialBucketCount(value, distribution);
break;
case Distribution::kLinearBuckets:
UpdateGeneralStatictics(value, distribution);
UpdateLinearBucketCount(value, distribution);
break;
case Distribution::kExplicitBuckets:
UpdateGeneralStatictics(value, distribution);
UpdateExplicitBucketCount(value, distribution);
break;
default:
return Status(Code::INVALID_ARGUMENT,
StrCat("Unknown bucket option case: ",
distribution->bucket_option_case()));
}
return Status::OK;
}
Status DistributionHelper::Merge(const Distribution& from, Distribution* to) {
if (!BucketsApproximatelyEqual(from, *to)) {
return Status(Code::INVALID_ARGUMENT,
std::string("Bucket options don't match. From: ") +
from.DebugString() + " to: " + to->DebugString());
}
// TODO(chengliang): Make merging more tolerant here.
if (from.bucket_counts_size() != to->bucket_counts_size()) {
return Status(Code::INVALID_ARGUMENT, "Bucket counts size don't match.");
}
if (from.count() <= 0) return Status::OK;
if (to->count() <= 0) {
*to = from;
return Status::OK;
}
int64_t count = to->count();
double mean = to->mean();
double sum_of_squared_deviation = to->sum_of_squared_deviation();
to->set_count(to->count() + from.count());
to->set_minimum(std::min(from.minimum(), to->minimum()));
to->set_maximum(std::max(from.maximum(), to->maximum()));
to->set_mean((count * mean + from.count() * from.mean()) / to->count());
to->set_sum_of_squared_deviation(
sum_of_squared_deviation + from.sum_of_squared_deviation() +
count * (to->mean() - mean) * (to->mean() - mean) +
from.count() * (to->mean() - from.mean()) * (to->mean() - from.mean()));
for (int i = 0; i < from.bucket_counts_size(); i++) {
to->set_bucket_counts(i, to->bucket_counts(i) + from.bucket_counts(i));
}
return Status::OK;
}
} // namespace service_control_client
} // namespace google