0330aa0d5225c02e7e8852e3c3415e653ac51636
1 /**
2 * collectd - src/grpc.cc
3 * Copyright (C) 2015 Sebastian Harl
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 *
23 * Authors:
24 * Sebastian Harl <sh at tokkee.org>
25 **/
27 #include <grpc++/grpc++.h>
28 #include <google/protobuf/util/time_util.h>
30 #include "collectd.grpc.pb.h"
32 extern "C" {
33 #include <stdbool.h>
34 #include <pthread.h>
36 #include "collectd.h"
37 #include "common.h"
38 #include "configfile.h"
39 #include "plugin.h"
41 #include "daemon/utils_cache.h"
43 typedef struct {
44 char *addr;
45 char *port;
46 } listener_t;
48 static listener_t *listeners;
49 static size_t listeners_num;
50 }
52 using collectd::Collectd;
54 using collectd::DispatchValuesRequest;
55 using collectd::DispatchValuesReply;
56 using collectd::ListValuesRequest;
57 using collectd::ListValuesReply;
59 using google::protobuf::util::TimeUtil;
61 /*
62 * proto conversion
63 */
65 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
66 {
67 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
68 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
70 std::string s;
72 s = msg.host();
73 if (!s.length())
74 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
75 grpc::string("missing host name"));
76 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
78 s = msg.plugin();
79 if (!s.length())
80 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
81 grpc::string("missing plugin name"));
82 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
84 s = msg.type();
85 if (!s.length())
86 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
87 grpc::string("missing type name"));
88 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
90 s = msg.plugin_instance();
91 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
93 s = msg.type_instance();
94 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
96 value_t *values = NULL;
97 size_t values_len = 0;
98 auto status = grpc::Status::OK;
100 for (auto v : msg.value()) {
101 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
102 if (!val) {
103 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
104 grpc::string("failed to allocate values array"));
105 break;
106 }
108 values = val;
109 val = values + values_len;
110 values_len++;
112 switch (v.value_case()) {
113 case collectd::types::Value::ValueCase::kCounter:
114 val->counter = counter_t(v.counter());
115 break;
116 case collectd::types::Value::ValueCase::kGauge:
117 val->gauge = gauge_t(v.gauge());
118 break;
119 case collectd::types::Value::ValueCase::kDerive:
120 val->derive = derive_t(v.derive());
121 break;
122 case collectd::types::Value::ValueCase::kAbsolute:
123 val->absolute = absolute_t(v.absolute());
124 break;
125 default:
126 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
127 grpc::string("unknown value type"));
128 break;
129 }
131 if (!status.ok())
132 break;
133 }
134 if (status.ok()) {
135 vl->values = values;
136 vl->values_len = values_len;
137 }
138 else if (values) {
139 free(values);
140 }
142 return status;
143 } /* unmarshal_value_list() */
145 /*
146 * request call-backs and call objects
147 */
149 static grpc::Status Process(grpc::ServerContext *ctx,
150 DispatchValuesRequest request, DispatchValuesReply *reply)
151 {
152 value_list_t vl = VALUE_LIST_INIT;
153 auto status = unmarshal_value_list(request.values(), &vl);
154 if (!status.ok())
155 return status;
157 if (plugin_dispatch_values(&vl))
158 status = grpc::Status(grpc::StatusCode::INTERNAL,
159 grpc::string("failed to enqueue values for writing"));
160 return status;
161 } /* Process(): DispatchValues */
163 static grpc::Status Process(grpc::ServerContext *ctx,
164 ListValuesRequest request, ListValuesReply *reply)
165 {
166 char **names = NULL;
167 cdtime_t *times = NULL;
168 size_t i, n = 0;
170 if (uc_get_names(&names, ×, &n))
171 return grpc::Status(grpc::StatusCode::INTERNAL,
172 grpc::string("failed to retrieve values"));
174 for (i = 0; i < n; i++) {
175 auto v = reply->add_value();
176 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(times[i]));
177 v->set_name(names[i]);
178 v->set_allocated_time(new google::protobuf::Timestamp(t));
179 sfree(names[i]);
180 }
181 sfree(names);
182 sfree(times);
184 return grpc::Status::OK;
185 } /* Process(): ListValues */
187 class Call
188 {
189 public:
190 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
191 : service_(service), cq_(cq), status_(CREATE)
192 { }
194 virtual ~Call()
195 { }
197 void Handle()
198 {
199 if (status_ == CREATE) {
200 Create();
201 status_ = PROCESS;
202 }
203 else if (status_ == PROCESS) {
204 Process();
205 status_ = FINISH;
206 }
207 else {
208 GPR_ASSERT(status_ == FINISH);
209 Finish();
210 }
211 } /* Handle() */
213 protected:
214 virtual void Create() = 0;
215 virtual void Process() = 0;
216 virtual void Finish() = 0;
218 Collectd::AsyncService *service_;
219 grpc::ServerCompletionQueue *cq_;
220 grpc::ServerContext ctx_;
222 private:
223 enum CallStatus { CREATE, PROCESS, FINISH };
224 CallStatus status_;
225 }; /* class Call */
227 template<typename RequestT, typename ReplyT>
228 class RpcCall final : public Call
229 {
230 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
231 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
232 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
234 public:
235 RpcCall(Collectd::AsyncService *service,
236 CreatorT creator, grpc::ServerCompletionQueue *cq)
237 : Call(service, cq), creator_(creator), responder_(&ctx_)
238 {
239 Handle();
240 } /* RpcCall() */
242 virtual ~RpcCall()
243 { }
245 private:
246 void Create()
247 {
248 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
249 } /* Create() */
251 void Process()
252 {
253 // Add a new request object to the queue.
254 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
255 grpc::Status status = ::Process(&ctx_, request_, &reply_);
256 responder_.Finish(reply_, status, this);
257 } /* Process() */
259 void Finish()
260 {
261 delete this;
262 } /* Finish() */
264 CreatorT creator_;
266 RequestT request_;
267 ReplyT reply_;
269 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
270 }; /* class RpcCall */
272 /*
273 * gRPC server implementation
274 */
276 class CollectdServer final
277 {
278 public:
279 void Start()
280 {
281 // TODO: make configurable
282 auto auth = grpc::InsecureServerCredentials();
284 grpc::ServerBuilder builder;
286 if (!listeners_num) {
287 std::string default_addr("0.0.0.0:50051");
288 builder.AddListeningPort(default_addr, auth);
289 INFO("grpc: Listening on %s", default_addr.c_str());
290 }
291 else {
292 size_t i;
293 for (i = 0; i < listeners_num; i++) {
294 auto l = listeners[i];
295 std::string addr(l.addr);
296 addr += std::string(":") + std::string(l.port);
297 builder.AddListeningPort(addr, auth);
298 INFO("grpc: Listening on %s", addr.c_str());
299 }
300 }
302 builder.RegisterService(&service_);
303 cq_ = builder.AddCompletionQueue();
304 server_ = builder.BuildAndStart();
305 } /* Start() */
307 void Shutdown()
308 {
309 server_->Shutdown();
310 cq_->Shutdown();
311 } /* Shutdown() */
313 void Mainloop()
314 {
315 // Register request types.
316 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
317 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
318 new RpcCall<ListValuesRequest, ListValuesReply>(&service_,
319 &Collectd::AsyncService::RequestListValues, cq_.get());
321 while (true) {
322 void *req = NULL;
323 bool ok = false;
325 if (!cq_->Next(&req, &ok))
326 break; // Queue shut down.
327 if (!ok) {
328 ERROR("grpc: Failed to read from queue");
329 break;
330 }
332 static_cast<Call *>(req)->Handle();
333 }
334 } /* Mainloop() */
336 private:
337 Collectd::AsyncService service_;
339 std::unique_ptr<grpc::Server> server_;
340 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
341 }; /* class CollectdServer */
343 static CollectdServer *server = nullptr;
345 /*
346 * collectd plugin interface
347 */
349 extern "C" {
350 static pthread_t *workers;
351 static size_t workers_num = 5;
353 static void *worker_thread(void *arg)
354 {
355 CollectdServer *s = (CollectdServer *)arg;
356 s->Mainloop();
357 return NULL;
358 } /* worker_thread() */
360 static int c_grpc_config_listen(oconfig_item_t *ci)
361 {
362 listener_t *listener;
363 int i;
365 if ((ci->values_num != 2)
366 || (ci->values[0].type != OCONFIG_TYPE_STRING)
367 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
368 ERROR("grpc: The `%s` config option needs exactly "
369 "two string argument (address and port).", ci->key);
370 return -1;
371 }
373 listener = (listener_t *)realloc(listeners,
374 (listeners_num + 1) * sizeof(*listeners));
375 if (!listener) {
376 ERROR("grpc: Failed to allocate listeners");
377 return -1;
378 }
379 listeners = listener;
380 listener = listeners + listeners_num;
381 listeners_num++;
383 listener->addr = strdup(ci->values[0].value.string);
384 listener->port = strdup(ci->values[1].value.string);
386 for (i = 0; i < ci->children_num; i++) {
387 oconfig_item_t *child = ci->children + i;
388 WARNING("grpc: Option `%s` not allowed in <%s> block.",
389 child->key, ci->key);
390 }
392 return 0;
393 } /* c_grpc_config_listen() */
395 static int c_grpc_config(oconfig_item_t *ci)
396 {
397 int i;
399 for (i = 0; i < ci->children_num; i++) {
400 oconfig_item_t *child = ci->children + i;
402 if (!strcasecmp("Listen", child->key)) {
403 if (c_grpc_config_listen(child))
404 return -1;
405 }
406 else if (!strcasecmp("WorkerThreads", child->key)) {
407 int n;
408 if (cf_util_get_int(child, &n))
409 return -1;
410 workers_num = (size_t)n;
411 }
412 else {
413 WARNING("grpc: Option `%s` not allowed here.", child->key);
414 }
415 }
417 return 0;
418 } /* c_grpc_config() */
420 static int c_grpc_init(void)
421 {
422 server = new CollectdServer();
423 size_t i;
425 if (! server) {
426 ERROR("grpc: Failed to create server");
427 return -1;
428 }
430 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
431 if (! workers) {
432 delete server;
433 server = nullptr;
435 ERROR("grpc: Failed to allocate worker threads");
436 return -1;
437 }
439 server->Start();
440 for (i = 0; i < workers_num; i++) {
441 pthread_create(&workers[i], /* attr = */ NULL,
442 worker_thread, server);
443 }
444 INFO("grpc: Started %zu workers", workers_num);
445 return 0;
446 } /* c_grpc_init() */
448 static int c_grpc_shutdown(void)
449 {
450 size_t i;
452 if (!server)
453 return -1;
455 server->Shutdown();
457 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
458 for (i = 0; i < workers_num; i++)
459 pthread_join(workers[i], NULL);
460 free(workers);
461 workers = NULL;
462 workers_num = 0;
464 delete server;
465 server = nullptr;
467 return 0;
468 } /* c_grpc_shutdown() */
470 void module_register(void)
471 {
472 plugin_register_complex_config("grpc", c_grpc_config);
473 plugin_register_init("grpc", c_grpc_init);
474 plugin_register_shutdown("grpc", c_grpc_shutdown);
475 } /* module_register() */
476 } /* extern "C" */
478 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */