2 * collectd - src/grpc.cc
3 * Copyright (C) 2015-2016 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"
39 #include "configfile.h"
42 #include "daemon/utils_cache.h"
49 static listener_t *listeners;
50 static size_t listeners_num;
53 using collectd::Collectd;
55 using collectd::DispatchValuesRequest;
56 using collectd::DispatchValuesReply;
57 using collectd::QueryValuesRequest;
58 using collectd::QueryValuesReply;
60 using google::protobuf::util::TimeUtil;
66 static bool ident_matches(const value_list_t *vl, const value_list_t *matcher)
68 if (fnmatch(matcher->host, vl->host, 0))
71 if (fnmatch(matcher->plugin, vl->plugin, 0))
73 if (fnmatch(matcher->plugin_instance, vl->plugin_instance, 0))
76 if (fnmatch(matcher->type, vl->type, 0))
78 if (fnmatch(matcher->type_instance, vl->type_instance, 0))
88 static void marshal_ident(const value_list_t *vl, collectd::types::Identifier *msg)
90 msg->set_host(vl->host);
91 msg->set_plugin(vl->plugin);
92 if (vl->plugin_instance[0] != '\0')
93 msg->set_plugin_instance(vl->plugin_instance);
94 msg->set_type(vl->type);
95 if (vl->type_instance[0] != '\0')
96 msg->set_type_instance(vl->type_instance);
99 static grpc::Status unmarshal_ident(const collectd::types::Identifier &msg, value_list_t *vl,
105 if (!s.length() && require_fields)
106 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
107 grpc::string("missing host name"));
108 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
111 if (!s.length() && require_fields)
112 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
113 grpc::string("missing plugin name"));
114 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
117 if (!s.length() && require_fields)
118 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
119 grpc::string("missing type name"));
120 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
122 s = msg.plugin_instance();
123 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
125 s = msg.type_instance();
126 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
128 return grpc::Status::OK;
129 } /* unmarshal_ident() */
131 static grpc::Status marshal_value_list(const value_list_t *vl, collectd::types::ValueList *msg)
133 auto id = msg->mutable_identifier();
134 marshal_ident(vl, id);
136 auto ds = plugin_get_ds(vl->type);
137 if ((ds == NULL) || (ds->ds_num != vl->values_len)) {
138 return grpc::Status(grpc::StatusCode::INTERNAL,
139 grpc::string("failed to retrieve data-set for values"));
142 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(vl->time));
143 auto d = TimeUtil::NanosecondsToDuration(CDTIME_T_TO_NS(vl->interval));
144 msg->set_allocated_time(new google::protobuf::Timestamp(t));
145 msg->set_allocated_interval(new google::protobuf::Duration(d));
147 for (size_t i = 0; i < vl->values_len; ++i) {
148 auto v = msg->add_value();
149 switch (ds->ds[i].type) {
150 case DS_TYPE_COUNTER:
151 v->set_counter(vl->values[i].counter);
154 v->set_gauge(vl->values[i].gauge);
157 v->set_derive(vl->values[i].derive);
159 case DS_TYPE_ABSOLUTE:
160 v->set_absolute(vl->values[i].absolute);
163 return grpc::Status(grpc::StatusCode::INTERNAL,
164 grpc::string("unknown value type"));
168 return grpc::Status::OK;
169 } /* marshal_value_list */
171 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
173 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
174 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
176 auto status = unmarshal_ident(msg.identifier(), vl, true);
180 value_t *values = NULL;
181 size_t values_len = 0;
183 status = grpc::Status::OK;
184 for (auto v : msg.value()) {
185 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
187 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
188 grpc::string("failed to allocate values array"));
193 val = values + values_len;
196 switch (v.value_case()) {
197 case collectd::types::Value::ValueCase::kCounter:
198 val->counter = counter_t(v.counter());
200 case collectd::types::Value::ValueCase::kGauge:
201 val->gauge = gauge_t(v.gauge());
203 case collectd::types::Value::ValueCase::kDerive:
204 val->derive = derive_t(v.derive());
206 case collectd::types::Value::ValueCase::kAbsolute:
207 val->absolute = absolute_t(v.absolute());
210 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
211 grpc::string("unknown value type"));
220 vl->values_len = values_len;
227 } /* unmarshal_value_list() */
230 * request call-backs and call objects
233 static grpc::Status Process(grpc::ServerContext *ctx,
234 DispatchValuesRequest request, DispatchValuesReply *reply)
236 value_list_t vl = VALUE_LIST_INIT;
237 auto status = unmarshal_value_list(request.values(), &vl);
241 if (plugin_dispatch_values(&vl))
242 status = grpc::Status(grpc::StatusCode::INTERNAL,
243 grpc::string("failed to enqueue values for writing"));
245 } /* Process(): DispatchValues */
247 static grpc::Status Process(grpc::ServerContext *ctx,
248 QueryValuesRequest request, QueryValuesReply *reply)
253 value_list_t matcher;
254 auto status = unmarshal_ident(request.identifier(), &matcher, false);
258 if ((iter = uc_get_iterator()) == NULL) {
259 return grpc::Status(grpc::StatusCode::INTERNAL,
260 grpc::string("failed to query values: cannot create iterator"));
263 while (uc_iterator_next(iter, &name) == 0) {
265 if (parse_identifier_vl(name, &res) != 0)
266 return grpc::Status(grpc::StatusCode::INTERNAL,
267 grpc::string("failed to parse identifier"));
269 if (!ident_matches(&res, &matcher))
272 if (uc_iterator_get_time(iter, &res.time) < 0)
273 return grpc::Status(grpc::StatusCode::INTERNAL,
274 grpc::string("failed to retrieve value timestamp"));
275 if (uc_iterator_get_interval(iter, &res.interval) < 0)
276 return grpc::Status(grpc::StatusCode::INTERNAL,
277 grpc::string("failed to retrieve value interval"));
278 if (uc_iterator_get_values(iter, &res.values, &res.values_len) < 0)
279 return grpc::Status(grpc::StatusCode::INTERNAL,
280 grpc::string("failed to retrieve values"));
282 auto vl = reply->add_values();
283 status = marshal_value_list(&res, vl);
289 uc_iterator_destroy(iter);
291 return grpc::Status::OK;
292 } /* Process(): QueryValues */
297 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
298 : service_(service), cq_(cq), status_(CREATE)
306 if (status_ == CREATE) {
310 else if (status_ == PROCESS) {
315 GPR_ASSERT(status_ == FINISH);
321 virtual void Create() = 0;
322 virtual void Process() = 0;
323 virtual void Finish() = 0;
325 Collectd::AsyncService *service_;
326 grpc::ServerCompletionQueue *cq_;
327 grpc::ServerContext ctx_;
330 enum CallStatus { CREATE, PROCESS, FINISH };
334 template<typename RequestT, typename ReplyT>
335 class RpcCall final : public Call
337 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
338 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
339 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
342 RpcCall(Collectd::AsyncService *service,
343 CreatorT creator, grpc::ServerCompletionQueue *cq)
344 : Call(service, cq), creator_(creator), responder_(&ctx_)
355 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
360 // Add a new request object to the queue.
361 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
362 grpc::Status status = ::Process(&ctx_, request_, &reply_);
363 responder_.Finish(reply_, status, this);
376 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
377 }; /* class RpcCall */
380 * gRPC server implementation
383 class CollectdServer final
388 // TODO: make configurable
389 auto auth = grpc::InsecureServerCredentials();
391 grpc::ServerBuilder builder;
393 if (!listeners_num) {
394 std::string default_addr("0.0.0.0:50051");
395 builder.AddListeningPort(default_addr, auth);
396 INFO("grpc: Listening on %s", default_addr.c_str());
400 for (i = 0; i < listeners_num; i++) {
401 auto l = listeners[i];
402 std::string addr(l.addr);
403 addr += std::string(":") + std::string(l.port);
404 builder.AddListeningPort(addr, auth);
405 INFO("grpc: Listening on %s", addr.c_str());
409 builder.RegisterService(&service_);
410 cq_ = builder.AddCompletionQueue();
411 server_ = builder.BuildAndStart();
422 // Register request types.
423 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
424 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
425 new RpcCall<QueryValuesRequest, QueryValuesReply>(&service_,
426 &Collectd::AsyncService::RequestQueryValues, cq_.get());
432 if (!cq_->Next(&req, &ok))
433 break; // Queue shut down.
435 ERROR("grpc: Failed to read from queue");
439 static_cast<Call *>(req)->Handle();
444 Collectd::AsyncService service_;
446 std::unique_ptr<grpc::Server> server_;
447 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
448 }; /* class CollectdServer */
450 static CollectdServer *server = nullptr;
453 * collectd plugin interface
457 static pthread_t *workers;
458 static size_t workers_num = 5;
460 static void *worker_thread(void *arg)
462 CollectdServer *s = (CollectdServer *)arg;
465 } /* worker_thread() */
467 static int c_grpc_config_listen(oconfig_item_t *ci)
469 listener_t *listener;
472 if ((ci->values_num != 2)
473 || (ci->values[0].type != OCONFIG_TYPE_STRING)
474 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
475 ERROR("grpc: The `%s` config option needs exactly "
476 "two string argument (address and port).", ci->key);
480 listener = (listener_t *)realloc(listeners,
481 (listeners_num + 1) * sizeof(*listeners));
483 ERROR("grpc: Failed to allocate listeners");
486 listeners = listener;
487 listener = listeners + listeners_num;
490 listener->addr = strdup(ci->values[0].value.string);
491 listener->port = strdup(ci->values[1].value.string);
493 for (i = 0; i < ci->children_num; i++) {
494 oconfig_item_t *child = ci->children + i;
495 WARNING("grpc: Option `%s` not allowed in <%s> block.",
496 child->key, ci->key);
500 } /* c_grpc_config_listen() */
502 static int c_grpc_config(oconfig_item_t *ci)
506 for (i = 0; i < ci->children_num; i++) {
507 oconfig_item_t *child = ci->children + i;
509 if (!strcasecmp("Listen", child->key)) {
510 if (c_grpc_config_listen(child))
513 else if (!strcasecmp("WorkerThreads", child->key)) {
515 if (cf_util_get_int(child, &n))
517 workers_num = (size_t)n;
520 WARNING("grpc: Option `%s` not allowed here.", child->key);
525 } /* c_grpc_config() */
527 static int c_grpc_init(void)
529 server = new CollectdServer();
533 ERROR("grpc: Failed to create server");
537 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
542 ERROR("grpc: Failed to allocate worker threads");
547 for (i = 0; i < workers_num; i++) {
548 plugin_thread_create(&workers[i], /* attr = */ NULL,
549 worker_thread, server);
551 INFO("grpc: Started %zu workers", workers_num);
553 } /* c_grpc_init() */
555 static int c_grpc_shutdown(void)
564 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
565 for (i = 0; i < workers_num; i++)
566 pthread_join(workers[i], NULL);
575 } /* c_grpc_shutdown() */
577 void module_register(void)
579 plugin_register_complex_config("grpc", c_grpc_config);
580 plugin_register_init("grpc", c_grpc_init);
581 plugin_register_shutdown("grpc", c_grpc_shutdown);
582 } /* module_register() */
585 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */