2 * collectd - src/grpc.cc
3 * Copyright (C) 2015 Sebastian Harl
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Sebastian Harl <sh at tokkee.org>
27 #include <grpc++/grpc++.h>
28 #include <google/protobuf/util/time_util.h>
30 #include "collectd.grpc.pb.h"
38 #include "configfile.h"
41 #include "daemon/utils_cache.h"
48 static listener_t *listeners;
49 static size_t listeners_num;
52 using google::protobuf::util::TimeUtil;
58 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
60 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
61 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
67 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
68 grpc::string("missing host name"));
69 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
73 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
74 grpc::string("missing plugin name"));
75 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
79 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
80 grpc::string("missing type name"));
81 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
83 s = msg.plugin_instance();
85 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
87 s = msg.type_instance();
89 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
91 value_t *values = NULL;
92 size_t values_len = 0;
93 auto status = grpc::Status::OK;
95 for (auto v : msg.value()) {
96 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
98 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
99 grpc::string("failed to allocate values array"));
104 val = values + values_len;
107 switch (v.value_case()) {
108 case collectd::types::Value::ValueCase::kCounter:
109 val->counter = counter_t(v.counter());
111 case collectd::types::Value::ValueCase::kGauge:
112 val->gauge = gauge_t(v.gauge());
114 case collectd::types::Value::ValueCase::kDerive:
115 val->derive = derive_t(v.derive());
117 case collectd::types::Value::ValueCase::kAbsolute:
118 val->absolute = absolute_t(v.absolute());
121 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
122 grpc::string("unkown value type"));
131 vl->values_len = values_len;
138 } /* unmarshal_value_list() */
141 * request call objects
147 Call(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
148 : service_(service), cq_(cq), status_(CREATE)
156 if (status_ == CREATE) {
160 else if (status_ == PROCESS) {
165 GPR_ASSERT(status_ == FINISH);
171 virtual void Create() = 0;
172 virtual void Process() = 0;
173 virtual void Finish() = 0;
175 collectd::Collectd::AsyncService *service_;
176 grpc::ServerCompletionQueue *cq_;
177 grpc::ServerContext ctx_;
180 enum CallStatus { CREATE, PROCESS, FINISH };
184 class DispatchValuesCall : public Call
187 DispatchValuesCall(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
188 : Call(service, cq), responder_(&ctx_)
191 } /* DispatchValuesCall() */
193 virtual ~DispatchValuesCall()
199 service_->RequestDispatchValues(&ctx_, &request_, &responder_, cq_, cq_, this);
204 // Add a new request object to the queue.
205 new DispatchValuesCall(service_, cq_);
207 value_list_t vl = VALUE_LIST_INIT;
208 auto status = unmarshal_value_list(request_.values(), &vl);
210 responder_.Finish(reply_, status, this);
214 if (plugin_dispatch_values(&vl))
215 status = grpc::Status(grpc::StatusCode::INTERNAL,
216 grpc::string("failed to enqueue values for writing"));
218 responder_.Finish(reply_, status, this);
226 collectd::DispatchValuesRequest request_;
227 collectd::DispatchValuesReply reply_;
229 grpc::ServerAsyncResponseWriter<collectd::DispatchValuesReply> responder_;
230 }; /* class DispatchValuesCall */
232 class ListValuesCall : public Call
235 ListValuesCall(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
236 : Call(service, cq), responder_(&ctx_)
239 } /* ListValuesCall() */
241 virtual ~ListValuesCall()
247 service_->RequestListValues(&ctx_, &request_, &responder_, cq_, cq_, this);
252 new ListValuesCall(service_, cq_);
255 cdtime_t *times = NULL;
258 auto status = grpc::Status::OK;
259 if (uc_get_names(&names, ×, &n)) {
260 status = grpc::Status(grpc::StatusCode::INTERNAL,
261 grpc::string("failed to retrieve values"));
264 for (i = 0; i < n; i++) {
265 auto v = reply_.add_value();
266 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(times[i]));
267 v->set_name(names[i]);
268 v->set_allocated_time(new google::protobuf::Timestamp(t));
274 responder_.Finish(reply_, status, this);
282 collectd::ListValuesRequest request_;
283 collectd::ListValuesReply reply_;
285 grpc::ServerAsyncResponseWriter<collectd::ListValuesReply> responder_;
286 }; /* class ListValuesCall */
289 * gRPC server implementation
292 class CollectdServer final
297 // TODO: make configurable
298 auto auth = grpc::InsecureServerCredentials();
300 grpc::ServerBuilder builder;
302 if (!listeners_num) {
303 std::string default_addr("0.0.0.0:50051");
304 builder.AddListeningPort(default_addr, auth);
305 INFO("grpc: Listening on %s", default_addr.c_str());
309 for (i = 0; i < listeners_num; i++) {
310 auto l = listeners[i];
311 std::string addr(l.addr);
312 addr += std::string(":") + std::string(l.port);
313 builder.AddListeningPort(addr, auth);
314 INFO("grpc: Listening on %s", addr.c_str());
318 builder.RegisterAsyncService(&service_);
319 cq_ = builder.AddCompletionQueue();
320 server_ = builder.BuildAndStart();
331 // Register request types.
332 new DispatchValuesCall(&service_, cq_.get());
333 new ListValuesCall(&service_, cq_.get());
339 if (!cq_->Next(&req, &ok))
340 break; // Queue shut down.
342 ERROR("grpc: Failed to read from queue");
346 static_cast<Call *>(req)->Handle();
351 collectd::Collectd::AsyncService service_;
353 std::unique_ptr<grpc::Server> server_;
354 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
355 }; /* class CollectdServer */
357 static CollectdServer *server = nullptr;
360 * collectd plugin interface
364 static pthread_t *workers;
365 static size_t workers_num = 5;
367 static void *worker_thread(void *arg)
369 CollectdServer *s = (CollectdServer *)arg;
372 } /* worker_thread() */
374 static int c_grpc_config_listen(oconfig_item_t *ci)
376 listener_t *listener;
379 if ((ci->values_num != 2)
380 || (ci->values[0].type != OCONFIG_TYPE_STRING)
381 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
382 ERROR("grpc: The `%s` config option needs exactly "
383 "two string argument (address and port).", ci->key);
387 listener = (listener_t *)realloc(listeners,
388 (listeners_num + 1) * sizeof(*listeners));
390 ERROR("grpc: Failed to allocate listeners");
393 listeners = listener;
394 listener = listeners + listeners_num;
397 listener->addr = strdup(ci->values[0].value.string);
398 listener->port = strdup(ci->values[1].value.string);
400 for (i = 0; i < ci->children_num; i++) {
401 oconfig_item_t *child = ci->children + i;
402 WARNING("grpc: Option `%s` not allowed in <%s> block.",
403 child->key, ci->key);
407 } /* c_grpc_config_listen() */
409 static int c_grpc_config(oconfig_item_t *ci)
413 for (i = 0; i < ci->children_num; i++) {
414 oconfig_item_t *child = ci->children + i;
416 if (!strcasecmp("Listen", child->key)) {
417 if (c_grpc_config_listen(child))
420 else if (!strcasecmp("WorkerThreads", child->key)) {
422 if (cf_util_get_int(child, &n))
424 workers_num = (size_t)n;
427 WARNING("grpc: Option `%s` not allowed here.", child->key);
432 } /* c_grpc_config() */
434 static int c_grpc_init(void)
436 server = new CollectdServer();
440 ERROR("grpc: Failed to create server");
444 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
449 ERROR("grpc: Failed to allocate worker threads");
454 for (i = 0; i < workers_num; i++) {
455 pthread_create(&workers[i], /* attr = */ NULL,
456 worker_thread, server);
458 INFO("grpc: Started %zu workers", workers_num);
460 } /* c_grpc_init() */
462 static int c_grpc_shutdown(void)
471 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
472 for (i = 0; i < workers_num; i++)
473 pthread_join(workers[i], NULL);
482 } /* c_grpc_shutdown() */
484 void module_register(void)
486 plugin_register_complex_config("grpc", c_grpc_config);
487 plugin_register_init("grpc", c_grpc_init);
488 plugin_register_shutdown("grpc", c_grpc_shutdown);
489 } /* module_register() */
492 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */