Debian Codegraph @

src/cpp/server/load_reporter/load_reporter.h

raw
1 /*
2 *
3 * Copyright 2018 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #ifndef GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_REPORTER_H
20 #define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_REPORTER_H
21
22 #include <grpc/support/port_platform.h>
23
24 #include <stddef.h>
25
26 #include <atomic>
27 #include <chrono>
28 #include <cstdint>
29 #include <deque>
30 #include <memory>
31 #include <string>
32 #include <unordered_map>
33 #include <utility>
34 #include <vector>
35
36 #include <google/protobuf/repeated_ptr_field.h>
37
38 #include "opencensus/stats/stats.h"
39 #include "opencensus/tags/tag_key.h"
40
41 #include "src/core/lib/gprpp/sync.h"
42 #include "src/cpp/server/load_reporter/load_data_store.h"
43 #include "src/proto/grpc/lb/v1/load_reporter.pb.h"
44
45 namespace grpc {
46 namespace load_reporter {
47
48 // The interface to get the Census stats. Abstracted for mocking.
49 class CensusViewProvider {
50 public:
51 // Maps from the view name to the view data.
52 using ViewDataMap =
53 std::unordered_map<std::string, ::opencensus::stats::ViewData>;
54 // Maps from the view name to the view descriptor.
55 using ViewDescriptorMap =
56 std::unordered_map<std::string, ::opencensus::stats::ViewDescriptor>;
57
58 CensusViewProvider();
59 virtual ~CensusViewProvider() = default;
60
61 // Fetches the view data accumulated since last fetching, and returns it as a
62 // map from the view name to the view data.
63 virtual ViewDataMap FetchViewData() = 0;
64
65 // A helper function that gets a row with the input tag values from the view
66 // data. Only used when we know that row must exist because we have seen a row
67 // with the same tag values in a related view data. Several ViewData's are
68 // considered related if their views are based on the measures that are always
69 // recorded at the same time.
70 static double GetRelatedViewDataRowDouble(
71 const ViewDataMap& view_data_map, const char* view_name,
72 size_t view_name_len, const std::vector<std::string>& tag_values);
73 static uint64_t GetRelatedViewDataRowInt(
74 const ViewDataMap& view_data_map, const char* view_name,
75 size_t view_name_len, const std::vector<std::string>& tag_values);
76
77 protected:
78 const ViewDescriptorMap& view_descriptor_map() const {
79 return view_descriptor_map_;
80 }
81
82 private:
83 ViewDescriptorMap view_descriptor_map_;
84 // Tag keys.
85 ::opencensus::tags::TagKey tag_key_token_;
86 ::opencensus::tags::TagKey tag_key_host_;
87 ::opencensus::tags::TagKey tag_key_user_id_;
88 ::opencensus::tags::TagKey tag_key_status_;
89 ::opencensus::tags::TagKey tag_key_metric_name_;
90 };
91
92 // The default implementation fetches the real stats from Census.
93 class CensusViewProviderDefaultImpl : public CensusViewProvider {
94 public:
95 CensusViewProviderDefaultImpl();
96
97 ViewDataMap FetchViewData() override;
98
99 private:
100 std::unordered_map<std::string, ::opencensus::stats::View> view_map_;
101 };
102
103 // The interface to get the CPU stats. Abstracted for mocking.
104 class CpuStatsProvider {
105 public:
106 // The used and total amounts of CPU usage.
107 using CpuStatsSample = std::pair<uint64_t, uint64_t>;
108
109 virtual ~CpuStatsProvider() = default;
110
111 // Gets the cumulative used CPU and total CPU resource.
112 virtual CpuStatsSample GetCpuStats() = 0;
113 };
114
115 // The default implementation reads CPU jiffies from the system to calculate CPU
116 // utilization.
117 class CpuStatsProviderDefaultImpl : public CpuStatsProvider {
118 public:
119 CpuStatsSample GetCpuStats() override;
120 };
121
122 // Maintains all the load data and load reporting streams.
123 class LoadReporter {
124 public:
125 // TODO(juanlishen): Allow config for providers from users.
126 LoadReporter(uint32_t feedback_sample_window_seconds,
127 std::unique_ptr<CensusViewProvider> census_view_provider,
128 std::unique_ptr<CpuStatsProvider> cpu_stats_provider)
129 : feedback_sample_window_seconds_(feedback_sample_window_seconds),
130 census_view_provider_(std::move(census_view_provider)),
131 cpu_stats_provider_(std::move(cpu_stats_provider)) {
132 // Append the initial record so that the next real record can have a base.
133 AppendNewFeedbackRecord(0, 0);
134 }
135
136 // Fetches the latest data from Census and merge it into the data store.
137 // Also adds a new sample to the LB feedback sliding window.
138 // Thread-unsafe. (1). The access to the load data store and feedback records
139 // has locking. (2). The access to the Census view provider and CPU stats
140 // provider lacks locking, but we only access these two members in this method
141 // (in testing, we also access them when setting up expectation). So the
142 // invocations of this method must be serialized.
143 void FetchAndSample();
144
145 // Generates a report for that host and balancer. The report contains
146 // all the stats data accumulated between the last report (i.e., the last
147 // consumption) and the last fetch from Census (i.e., the last production).
148 // Thread-safe.
149 ::google::protobuf::RepeatedPtrField<grpc::lb::v1::Load> GenerateLoads(
150 const std::string& hostname, const std::string& lb_id);
151
152 // The feedback is calculated from the stats data recorded in the sliding
153 // window. Outdated records are discarded.
154 // Thread-safe.
155 grpc::lb::v1::LoadBalancingFeedback GenerateLoadBalancingFeedback();
156
157 // Wrapper around LoadDataStore::ReportStreamCreated.
158 // Thread-safe.
159 void ReportStreamCreated(const std::string& hostname,
160 const std::string& lb_id,
161 const std::string& load_key);
162
163 // Wrapper around LoadDataStore::ReportStreamClosed.
164 // Thread-safe.
165 void ReportStreamClosed(const std::string& hostname,
166 const std::string& lb_id);
167
168 // Generates a unique LB ID of length kLbIdLength. Returns an empty string
169 // upon failure. Thread-safe.
170 std::string GenerateLbId();
171
172 // Accessors only for testing.
173 CensusViewProvider* census_view_provider() {
174 return census_view_provider_.get();
175 }
176 CpuStatsProvider* cpu_stats_provider() { return cpu_stats_provider_.get(); }
177
178 private:
179 struct LoadBalancingFeedbackRecord {
180 std::chrono::system_clock::time_point end_time;
181 uint64_t rpcs;
182 uint64_t errors;
183 uint64_t cpu_usage;
184 uint64_t cpu_limit;
185
186 LoadBalancingFeedbackRecord(
187 const std::chrono::system_clock::time_point& end_time, uint64_t rpcs,
188 uint64_t errors, uint64_t cpu_usage, uint64_t cpu_limit)
189 : end_time(end_time),
190 rpcs(rpcs),
191 errors(errors),
192 cpu_usage(cpu_usage),
193 cpu_limit(cpu_limit) {}
194 };
195
196 // Finds the view data about starting call from the view_data_map and merges
197 // the data to the load data store.
198 void ProcessViewDataCallStart(
199 const CensusViewProvider::ViewDataMap& view_data_map);
200 // Finds the view data about ending call from the view_data_map and merges the
201 // data to the load data store.
202 void ProcessViewDataCallEnd(
203 const CensusViewProvider::ViewDataMap& view_data_map);
204 // Finds the view data about the customized call metrics from the
205 // view_data_map and merges the data to the load data store.
206 void ProcessViewDataOtherCallMetrics(
207 const CensusViewProvider::ViewDataMap& view_data_map);
208
209 bool IsRecordInWindow(const LoadBalancingFeedbackRecord& record,
210 std::chrono::system_clock::time_point now) {
211 return record.end_time > now - feedback_sample_window_seconds_;
212 }
213
214 void AppendNewFeedbackRecord(uint64_t rpcs, uint64_t errors);
215
216 // Extracts an OrphanedLoadIdentifier from the per-balancer store and attaches
217 // it to the load.
218 void AttachOrphanLoadId(grpc::lb::v1::Load* load,
219 const PerBalancerStore& per_balancer_store);
220
221 std::atomic<int64_t> next_lb_id_{0};
222 const std::chrono::seconds feedback_sample_window_seconds_;
223 grpc_core::Mutex feedback_mu_;
224 std::deque<LoadBalancingFeedbackRecord> feedback_records_;
225 // TODO(juanlishen): Lock in finer grain. Locking the whole store may be
226 // too expensive.
227 grpc_core::Mutex store_mu_;
228 LoadDataStore load_data_store_;
229 std::unique_ptr<CensusViewProvider> census_view_provider_;
230 std::unique_ptr<CpuStatsProvider> cpu_stats_provider_;
231 };
232
233 } // namespace load_reporter
234 } // namespace grpc
235
236 #endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_REPORTER_H