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"
42 #include "configfile.h"
45 #include "daemon/utils_cache.h"
48 using collectd::Collectd;
50 using collectd::DispatchValuesRequest;
51 using collectd::DispatchValuesReply;
52 using collectd::QueryValuesRequest;
53 using collectd::QueryValuesReply;
55 using google::protobuf::util::TimeUtil;
65 grpc::SslServerCredentialsOptions *ssl;
67 static std::vector<Listener> listeners;
68 static grpc::string default_addr("0.0.0.0:50051");
74 static bool ident_matches(const value_list_t *vl, const value_list_t *matcher)
76 if (fnmatch(matcher->host, vl->host, 0))
79 if (fnmatch(matcher->plugin, vl->plugin, 0))
81 if (fnmatch(matcher->plugin_instance, vl->plugin_instance, 0))
84 if (fnmatch(matcher->type, vl->type, 0))
86 if (fnmatch(matcher->type_instance, vl->type_instance, 0))
92 static grpc::string read_file(const char *filename)
95 grpc::string s, content;
99 ERROR("grpc: Failed to open '%s'", filename);
103 while (std::getline(f, s)) {
105 content.push_back('\n');
115 static void marshal_ident(const value_list_t *vl, collectd::types::Identifier *msg)
117 msg->set_host(vl->host);
118 msg->set_plugin(vl->plugin);
119 if (vl->plugin_instance[0] != '\0')
120 msg->set_plugin_instance(vl->plugin_instance);
121 msg->set_type(vl->type);
122 if (vl->type_instance[0] != '\0')
123 msg->set_type_instance(vl->type_instance);
124 } /* marshal_ident */
126 static grpc::Status unmarshal_ident(const collectd::types::Identifier &msg, value_list_t *vl,
132 if (!s.length() && require_fields)
133 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
134 grpc::string("missing host name"));
135 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
138 if (!s.length() && require_fields)
139 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
140 grpc::string("missing plugin name"));
141 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
144 if (!s.length() && require_fields)
145 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
146 grpc::string("missing type name"));
147 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
149 s = msg.plugin_instance();
150 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
152 s = msg.type_instance();
153 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
155 return grpc::Status::OK;
156 } /* unmarshal_ident() */
158 static grpc::Status marshal_value_list(const value_list_t *vl, collectd::types::ValueList *msg)
160 auto id = msg->mutable_identifier();
161 marshal_ident(vl, id);
163 auto ds = plugin_get_ds(vl->type);
164 if ((ds == NULL) || (ds->ds_num != vl->values_len)) {
165 return grpc::Status(grpc::StatusCode::INTERNAL,
166 grpc::string("failed to retrieve data-set for values"));
169 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(vl->time));
170 auto d = TimeUtil::NanosecondsToDuration(CDTIME_T_TO_NS(vl->interval));
171 msg->set_allocated_time(new google::protobuf::Timestamp(t));
172 msg->set_allocated_interval(new google::protobuf::Duration(d));
174 for (size_t i = 0; i < vl->values_len; ++i) {
175 auto v = msg->add_value();
176 switch (ds->ds[i].type) {
177 case DS_TYPE_COUNTER:
178 v->set_counter(vl->values[i].counter);
181 v->set_gauge(vl->values[i].gauge);
184 v->set_derive(vl->values[i].derive);
186 case DS_TYPE_ABSOLUTE:
187 v->set_absolute(vl->values[i].absolute);
190 return grpc::Status(grpc::StatusCode::INTERNAL,
191 grpc::string("unknown value type"));
195 return grpc::Status::OK;
196 } /* marshal_value_list */
198 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
200 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
201 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
203 auto status = unmarshal_ident(msg.identifier(), vl, true);
207 value_t *values = NULL;
208 size_t values_len = 0;
210 status = grpc::Status::OK;
211 for (auto v : msg.value()) {
212 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
214 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
215 grpc::string("failed to allocate values array"));
220 val = values + values_len;
223 switch (v.value_case()) {
224 case collectd::types::Value::ValueCase::kCounter:
225 val->counter = counter_t(v.counter());
227 case collectd::types::Value::ValueCase::kGauge:
228 val->gauge = gauge_t(v.gauge());
230 case collectd::types::Value::ValueCase::kDerive:
231 val->derive = derive_t(v.derive());
233 case collectd::types::Value::ValueCase::kAbsolute:
234 val->absolute = absolute_t(v.absolute());
237 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
238 grpc::string("unknown value type"));
247 vl->values_len = values_len;
254 } /* unmarshal_value_list() */
257 * request call-backs and call objects
260 static grpc::Status Process(grpc::ServerContext *ctx,
261 DispatchValuesRequest request, DispatchValuesReply *reply)
263 value_list_t vl = VALUE_LIST_INIT;
264 auto status = unmarshal_value_list(request.values(), &vl);
268 if (plugin_dispatch_values(&vl))
269 status = grpc::Status(grpc::StatusCode::INTERNAL,
270 grpc::string("failed to enqueue values for writing"));
272 } /* Process(): DispatchValues */
274 static grpc::Status Process(grpc::ServerContext *ctx,
275 QueryValuesRequest request, QueryValuesReply *reply)
280 value_list_t matcher;
281 auto status = unmarshal_ident(request.identifier(), &matcher, false);
285 if ((iter = uc_get_iterator()) == NULL) {
286 return grpc::Status(grpc::StatusCode::INTERNAL,
287 grpc::string("failed to query values: cannot create iterator"));
290 while (uc_iterator_next(iter, &name) == 0) {
292 if (parse_identifier_vl(name, &res) != 0) {
293 uc_iterator_destroy(iter);
294 return grpc::Status(grpc::StatusCode::INTERNAL,
295 grpc::string("failed to parse identifier"));
298 if (!ident_matches(&res, &matcher))
301 if (uc_iterator_get_time(iter, &res.time) < 0) {
302 uc_iterator_destroy(iter);
303 return grpc::Status(grpc::StatusCode::INTERNAL,
304 grpc::string("failed to retrieve value timestamp"));
306 if (uc_iterator_get_interval(iter, &res.interval) < 0) {
307 uc_iterator_destroy(iter);
308 return grpc::Status(grpc::StatusCode::INTERNAL,
309 grpc::string("failed to retrieve value interval"));
311 if (uc_iterator_get_values(iter, &res.values, &res.values_len) < 0) {
312 uc_iterator_destroy(iter);
313 return grpc::Status(grpc::StatusCode::INTERNAL,
314 grpc::string("failed to retrieve values"));
317 auto vl = reply->add_values();
318 status = marshal_value_list(&res, vl);
321 uc_iterator_destroy(iter);
326 uc_iterator_destroy(iter);
328 return grpc::Status::OK;
329 } /* Process(): QueryValues */
334 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
335 : service_(service), cq_(cq), status_(CREATE)
343 if (status_ == CREATE) {
347 else if (status_ == PROCESS) {
352 GPR_ASSERT(status_ == FINISH);
358 virtual void Create() = 0;
359 virtual void Process() = 0;
360 virtual void Finish() = 0;
362 Collectd::AsyncService *service_;
363 grpc::ServerCompletionQueue *cq_;
364 grpc::ServerContext ctx_;
367 enum CallStatus { CREATE, PROCESS, FINISH };
371 template<typename RequestT, typename ReplyT>
372 class RpcCall final : public Call
374 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
375 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
376 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
379 RpcCall(Collectd::AsyncService *service,
380 CreatorT creator, grpc::ServerCompletionQueue *cq)
381 : Call(service, cq), creator_(creator), responder_(&ctx_)
392 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
397 // Add a new request object to the queue.
398 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
399 grpc::Status status = ::Process(&ctx_, request_, &reply_);
400 responder_.Finish(reply_, status, this);
413 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
414 }; /* class RpcCall */
417 * gRPC server implementation
420 class CollectdServer final
425 auto auth = grpc::InsecureServerCredentials();
427 grpc::ServerBuilder builder;
429 if (listeners.empty()) {
430 builder.AddListeningPort(default_addr, auth);
431 INFO("grpc: Listening on %s", default_addr.c_str());
434 for (auto l : listeners) {
435 grpc::string addr = l.addr + ":" + l.port;
437 auto use_ssl = grpc::string("");
439 if (l.ssl != nullptr) {
440 use_ssl = grpc::string(" (SSL enabled)");
441 a = grpc::SslServerCredentials(*l.ssl);
444 builder.AddListeningPort(addr, a);
445 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
449 builder.RegisterService(&service_);
450 cq_ = builder.AddCompletionQueue();
451 server_ = builder.BuildAndStart();
462 // Register request types.
463 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
464 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
465 new RpcCall<QueryValuesRequest, QueryValuesReply>(&service_,
466 &Collectd::AsyncService::RequestQueryValues, cq_.get());
472 if (!cq_->Next(&req, &ok))
473 break; // Queue shut down.
475 ERROR("grpc: Failed to read from queue");
479 static_cast<Call *>(req)->Handle();
484 Collectd::AsyncService service_;
486 std::unique_ptr<grpc::Server> server_;
487 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
488 }; /* class CollectdServer */
490 static CollectdServer *server = nullptr;
493 * collectd plugin interface
497 static pthread_t *workers;
498 static size_t workers_num = 5;
500 static void *worker_thread(void *arg)
502 CollectdServer *s = (CollectdServer *)arg;
505 } /* worker_thread() */
507 static int c_grpc_config_listen(oconfig_item_t *ci)
509 if ((ci->values_num != 2)
510 || (ci->values[0].type != OCONFIG_TYPE_STRING)
511 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
512 ERROR("grpc: The `%s` config option needs exactly "
513 "two string argument (address and port).", ci->key);
517 auto listener = Listener();
518 listener.addr = grpc::string(ci->values[0].value.string);
519 listener.port = grpc::string(ci->values[1].value.string);
520 listener.ssl = nullptr;
522 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
523 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
524 bool use_ssl = false;
526 for (int i = 0; i < ci->children_num; i++) {
527 oconfig_item_t *child = ci->children + i;
529 if (!strcasecmp("EnableSSL", child->key)) {
530 if (cf_util_get_boolean(child, &use_ssl)) {
531 ERROR("grpc: Option `%s` expects a boolean value",
536 else if (!strcasecmp("SSLRootCerts", child->key)) {
538 if (cf_util_get_string(child, &certs)) {
539 ERROR("grpc: Option `%s` expects a string value",
543 ssl_opts->pem_root_certs = read_file(certs);
545 else if (!strcasecmp("SSLServerKey", child->key)) {
547 if (cf_util_get_string(child, &key)) {
548 ERROR("grpc: Option `%s` expects a string value",
552 pkcp.private_key = read_file(key);
554 else if (!strcasecmp("SSLServerCert", child->key)) {
556 if (cf_util_get_string(child, &cert)) {
557 ERROR("grpc: Option `%s` expects a string value",
561 pkcp.cert_chain = read_file(cert);
564 WARNING("grpc: Option `%s` not allowed in <%s> block.",
565 child->key, ci->key);
569 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
571 listener.ssl = ssl_opts;
575 listeners.push_back(listener);
577 } /* c_grpc_config_listen() */
579 static int c_grpc_config(oconfig_item_t *ci)
583 for (i = 0; i < ci->children_num; i++) {
584 oconfig_item_t *child = ci->children + i;
586 if (!strcasecmp("Listen", child->key)) {
587 if (c_grpc_config_listen(child))
590 else if (!strcasecmp("WorkerThreads", child->key)) {
592 if (cf_util_get_int(child, &n))
594 workers_num = (size_t)n;
597 WARNING("grpc: Option `%s` not allowed here.", child->key);
602 } /* c_grpc_config() */
604 static int c_grpc_init(void)
606 server = new CollectdServer();
610 ERROR("grpc: Failed to create server");
614 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
619 ERROR("grpc: Failed to allocate worker threads");
624 for (i = 0; i < workers_num; i++) {
625 plugin_thread_create(&workers[i], /* attr = */ NULL,
626 worker_thread, server);
628 INFO("grpc: Started %zu workers", workers_num);
630 } /* c_grpc_init() */
632 static int c_grpc_shutdown(void)
641 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
642 for (i = 0; i < workers_num; i++)
643 pthread_join(workers[i], NULL);
652 } /* c_grpc_shutdown() */
654 void module_register(void)
656 plugin_register_complex_config("grpc", c_grpc_config);
657 plugin_register_init("grpc", c_grpc_init);
658 plugin_register_shutdown("grpc", c_grpc_shutdown);
659 } /* module_register() */
662 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */