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>
34 #include "collectd.grpc.pb.h"
43 #include "configfile.h"
46 #include "daemon/utils_cache.h"
49 using collectd::Collectd;
51 using collectd::DispatchValuesRequest;
52 using collectd::DispatchValuesReply;
53 using collectd::QueryValuesRequest;
54 using collectd::QueryValuesReply;
56 using google::protobuf::util::TimeUtil;
66 grpc::SslServerCredentialsOptions *ssl;
68 static std::vector<Listener> listeners;
69 static grpc::string default_addr("0.0.0.0:50051");
75 static bool ident_matches(const value_list_t *vl, const value_list_t *matcher)
77 if (fnmatch(matcher->host, vl->host, 0))
80 if (fnmatch(matcher->plugin, vl->plugin, 0))
82 if (fnmatch(matcher->plugin_instance, vl->plugin_instance, 0))
85 if (fnmatch(matcher->type, vl->type, 0))
87 if (fnmatch(matcher->type_instance, vl->type_instance, 0))
93 static grpc::string read_file(const char *filename)
96 grpc::string s, content;
100 ERROR("grpc: Failed to open '%s'", filename);
104 while (std::getline(f, s)) {
106 content.push_back('\n');
116 static void marshal_ident(const value_list_t *vl, collectd::types::Identifier *msg)
118 msg->set_host(vl->host);
119 msg->set_plugin(vl->plugin);
120 if (vl->plugin_instance[0] != '\0')
121 msg->set_plugin_instance(vl->plugin_instance);
122 msg->set_type(vl->type);
123 if (vl->type_instance[0] != '\0')
124 msg->set_type_instance(vl->type_instance);
125 } /* marshal_ident */
127 static grpc::Status unmarshal_ident(const collectd::types::Identifier &msg, value_list_t *vl,
133 if (!s.length() && require_fields)
134 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
135 grpc::string("missing host name"));
136 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
139 if (!s.length() && require_fields)
140 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
141 grpc::string("missing plugin name"));
142 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
145 if (!s.length() && require_fields)
146 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
147 grpc::string("missing type name"));
148 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
150 s = msg.plugin_instance();
151 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
153 s = msg.type_instance();
154 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
156 return grpc::Status::OK;
157 } /* unmarshal_ident() */
159 static grpc::Status marshal_value_list(const value_list_t *vl, collectd::types::ValueList *msg)
161 auto id = msg->mutable_identifier();
162 marshal_ident(vl, id);
164 auto ds = plugin_get_ds(vl->type);
165 if ((ds == NULL) || (ds->ds_num != vl->values_len)) {
166 return grpc::Status(grpc::StatusCode::INTERNAL,
167 grpc::string("failed to retrieve data-set for values"));
170 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(vl->time));
171 auto d = TimeUtil::NanosecondsToDuration(CDTIME_T_TO_NS(vl->interval));
172 msg->set_allocated_time(new google::protobuf::Timestamp(t));
173 msg->set_allocated_interval(new google::protobuf::Duration(d));
175 for (size_t i = 0; i < vl->values_len; ++i) {
176 auto v = msg->add_value();
177 switch (ds->ds[i].type) {
178 case DS_TYPE_COUNTER:
179 v->set_counter(vl->values[i].counter);
182 v->set_gauge(vl->values[i].gauge);
185 v->set_derive(vl->values[i].derive);
187 case DS_TYPE_ABSOLUTE:
188 v->set_absolute(vl->values[i].absolute);
191 return grpc::Status(grpc::StatusCode::INTERNAL,
192 grpc::string("unknown value type"));
196 return grpc::Status::OK;
197 } /* marshal_value_list */
199 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
201 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
202 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
204 auto status = unmarshal_ident(msg.identifier(), vl, true);
208 value_t *values = NULL;
209 size_t values_len = 0;
211 status = grpc::Status::OK;
212 for (auto v : msg.value()) {
213 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
215 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
216 grpc::string("failed to allocate values array"));
221 val = values + values_len;
224 switch (v.value_case()) {
225 case collectd::types::Value::ValueCase::kCounter:
226 val->counter = counter_t(v.counter());
228 case collectd::types::Value::ValueCase::kGauge:
229 val->gauge = gauge_t(v.gauge());
231 case collectd::types::Value::ValueCase::kDerive:
232 val->derive = derive_t(v.derive());
234 case collectd::types::Value::ValueCase::kAbsolute:
235 val->absolute = absolute_t(v.absolute());
238 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
239 grpc::string("unknown value type"));
248 vl->values_len = values_len;
255 } /* unmarshal_value_list() */
258 * request call-backs and call objects
261 static grpc::Status Process(grpc::ServerContext *ctx,
262 DispatchValuesRequest request, DispatchValuesReply *reply)
264 value_list_t vl = VALUE_LIST_INIT;
265 auto status = unmarshal_value_list(request.values(), &vl);
269 if (plugin_dispatch_values(&vl))
270 status = grpc::Status(grpc::StatusCode::INTERNAL,
271 grpc::string("failed to enqueue values for writing"));
273 } /* Process(): DispatchValues */
275 static grpc::Status Process(grpc::ServerContext *ctx,
276 QueryValuesRequest request, QueryValuesReply *reply)
281 value_list_t matcher;
282 auto status = unmarshal_ident(request.identifier(), &matcher, false);
286 if ((iter = uc_get_iterator()) == NULL) {
287 return grpc::Status(grpc::StatusCode::INTERNAL,
288 grpc::string("failed to query values: cannot create iterator"));
291 while (uc_iterator_next(iter, &name) == 0) {
293 if (parse_identifier_vl(name, &res) != 0)
294 return grpc::Status(grpc::StatusCode::INTERNAL,
295 grpc::string("failed to parse identifier"));
297 if (!ident_matches(&res, &matcher))
300 if (uc_iterator_get_time(iter, &res.time) < 0)
301 return grpc::Status(grpc::StatusCode::INTERNAL,
302 grpc::string("failed to retrieve value timestamp"));
303 if (uc_iterator_get_interval(iter, &res.interval) < 0)
304 return grpc::Status(grpc::StatusCode::INTERNAL,
305 grpc::string("failed to retrieve value interval"));
306 if (uc_iterator_get_values(iter, &res.values, &res.values_len) < 0)
307 return grpc::Status(grpc::StatusCode::INTERNAL,
308 grpc::string("failed to retrieve values"));
310 auto vl = reply->add_values();
311 status = marshal_value_list(&res, vl);
317 uc_iterator_destroy(iter);
319 return grpc::Status::OK;
320 } /* Process(): QueryValues */
325 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
326 : service_(service), cq_(cq), status_(CREATE)
334 if (status_ == CREATE) {
338 else if (status_ == PROCESS) {
343 GPR_ASSERT(status_ == FINISH);
349 virtual void Create() = 0;
350 virtual void Process() = 0;
351 virtual void Finish() = 0;
353 Collectd::AsyncService *service_;
354 grpc::ServerCompletionQueue *cq_;
355 grpc::ServerContext ctx_;
358 enum CallStatus { CREATE, PROCESS, FINISH };
362 template<typename RequestT, typename ReplyT>
363 class RpcCall final : public Call
365 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
366 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
367 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
370 RpcCall(Collectd::AsyncService *service,
371 CreatorT creator, grpc::ServerCompletionQueue *cq)
372 : Call(service, cq), creator_(creator), responder_(&ctx_)
383 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
388 // Add a new request object to the queue.
389 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
390 grpc::Status status = ::Process(&ctx_, request_, &reply_);
391 responder_.Finish(reply_, status, this);
404 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
405 }; /* class RpcCall */
408 * gRPC server implementation
411 class CollectdServer final
416 auto auth = grpc::InsecureServerCredentials();
418 grpc::ServerBuilder builder;
420 if (listeners.empty()) {
421 builder.AddListeningPort(default_addr, auth);
422 INFO("grpc: Listening on %s", default_addr.c_str());
425 for (auto l : listeners) {
426 grpc::string addr = l.addr + ":" + l.port;
428 auto use_ssl = grpc::string("");
430 if (l.ssl != nullptr) {
431 use_ssl = grpc::string(" (SSL enabled)");
432 a = grpc::SslServerCredentials(*l.ssl);
435 builder.AddListeningPort(addr, a);
436 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
440 builder.RegisterService(&service_);
441 cq_ = builder.AddCompletionQueue();
442 server_ = builder.BuildAndStart();
453 // Register request types.
454 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
455 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
456 new RpcCall<QueryValuesRequest, QueryValuesReply>(&service_,
457 &Collectd::AsyncService::RequestQueryValues, cq_.get());
463 if (!cq_->Next(&req, &ok))
464 break; // Queue shut down.
466 ERROR("grpc: Failed to read from queue");
470 static_cast<Call *>(req)->Handle();
475 Collectd::AsyncService service_;
477 std::unique_ptr<grpc::Server> server_;
478 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
479 }; /* class CollectdServer */
481 static CollectdServer *server = nullptr;
484 * collectd plugin interface
488 static pthread_t *workers;
489 static size_t workers_num = 5;
491 static void *worker_thread(void *arg)
493 CollectdServer *s = (CollectdServer *)arg;
496 } /* worker_thread() */
498 static int c_grpc_config_listen(oconfig_item_t *ci)
500 if ((ci->values_num != 2)
501 || (ci->values[0].type != OCONFIG_TYPE_STRING)
502 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
503 ERROR("grpc: The `%s` config option needs exactly "
504 "two string argument (address and port).", ci->key);
508 auto listener = Listener();
509 listener.addr = grpc::string(ci->values[0].value.string);
510 listener.port = grpc::string(ci->values[1].value.string);
511 listener.ssl = nullptr;
513 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
514 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
515 bool use_ssl = false;
517 for (int i = 0; i < ci->children_num; i++) {
518 oconfig_item_t *child = ci->children + i;
520 if (!strcasecmp("EnableSSL", child->key)) {
521 if (cf_util_get_boolean(child, &use_ssl)) {
522 ERROR("grpc: Option `%s` expects a boolean value",
527 else if (!strcasecmp("SSLRootCerts", child->key)) {
529 if (cf_util_get_string(child, &certs)) {
530 ERROR("grpc: Option `%s` expects a string value",
534 ssl_opts->pem_root_certs = read_file(certs);
536 else if (!strcasecmp("SSLServerKey", child->key)) {
538 if (cf_util_get_string(child, &key)) {
539 ERROR("grpc: Option `%s` expects a string value",
543 pkcp.private_key = read_file(key);
545 else if (!strcasecmp("SSLServerCert", child->key)) {
547 if (cf_util_get_string(child, &cert)) {
548 ERROR("grpc: Option `%s` expects a string value",
552 pkcp.cert_chain = read_file(cert);
555 WARNING("grpc: Option `%s` not allowed in <%s> block.",
556 child->key, ci->key);
560 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
562 listener.ssl = ssl_opts;
566 listeners.push_back(listener);
568 } /* c_grpc_config_listen() */
570 static int c_grpc_config(oconfig_item_t *ci)
574 for (i = 0; i < ci->children_num; i++) {
575 oconfig_item_t *child = ci->children + i;
577 if (!strcasecmp("Listen", child->key)) {
578 if (c_grpc_config_listen(child))
581 else if (!strcasecmp("WorkerThreads", child->key)) {
583 if (cf_util_get_int(child, &n))
585 workers_num = (size_t)n;
588 WARNING("grpc: Option `%s` not allowed here.", child->key);
593 } /* c_grpc_config() */
595 static int c_grpc_init(void)
597 server = new CollectdServer();
601 ERROR("grpc: Failed to create server");
605 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
610 ERROR("grpc: Failed to allocate worker threads");
615 for (i = 0; i < workers_num; i++) {
616 plugin_thread_create(&workers[i], /* attr = */ NULL,
617 worker_thread, server);
619 INFO("grpc: Started %zu workers", workers_num);
621 } /* c_grpc_init() */
623 static int c_grpc_shutdown(void)
632 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
633 for (i = 0; i < workers_num; i++)
634 pthread_join(workers[i], NULL);
643 } /* c_grpc_shutdown() */
645 void module_register(void)
647 plugin_register_complex_config("grpc", c_grpc_config);
648 plugin_register_init("grpc", c_grpc_init);
649 plugin_register_shutdown("grpc", c_grpc_shutdown);
650 } /* module_register() */
653 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */