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>
35 #include "collectd.grpc.pb.h"
45 #include "daemon/utils_cache.h"
48 using collectd::Collectd;
50 using collectd::PutValuesRequest;
51 using collectd::PutValuesResponse;
52 using collectd::QueryValuesRequest;
53 using collectd::QueryValuesResponse;
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_values();
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"));
194 auto name = msg->add_ds_names();
195 name->assign(ds->ds[i].name);
198 return grpc::Status::OK;
199 } /* marshal_value_list */
201 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
203 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
204 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
206 auto status = unmarshal_ident(msg.identifier(), vl, true);
210 value_t *values = NULL;
211 size_t values_len = 0;
213 status = grpc::Status::OK;
214 for (auto v : msg.values()) {
215 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
217 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
218 grpc::string("failed to allocate values array"));
223 val = values + values_len;
226 switch (v.value_case()) {
227 case collectd::types::Value::ValueCase::kCounter:
228 val->counter = counter_t(v.counter());
230 case collectd::types::Value::ValueCase::kGauge:
231 val->gauge = gauge_t(v.gauge());
233 case collectd::types::Value::ValueCase::kDerive:
234 val->derive = derive_t(v.derive());
236 case collectd::types::Value::ValueCase::kAbsolute:
237 val->absolute = absolute_t(v.absolute());
240 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
241 grpc::string("unknown value type"));
250 vl->values_len = values_len;
257 } /* unmarshal_value_list() */
262 class CollectdImpl : public collectd::Collectd::Service {
264 grpc::Status QueryValues(grpc::ServerContext *ctx, QueryValuesRequest const *req, grpc::ServerWriter<QueryValuesResponse> *writer) override {
266 auto status = unmarshal_ident(req->identifier(), &match, false);
271 std::queue<value_list_t> value_lists;
272 status = this->queryValuesRead(&match, &value_lists);
274 status = this->queryValuesWrite(ctx, writer, &value_lists);
277 while (!value_lists.empty()) {
278 auto vl = value_lists.front();
286 grpc::Status PutValues(grpc::ServerContext *ctx,
287 grpc::ServerReader<PutValuesRequest> *reader,
288 PutValuesResponse *res) override {
289 PutValuesRequest req;
291 while (reader->Read(&req)) {
292 value_list_t vl = VALUE_LIST_INIT;
293 auto status = unmarshal_value_list(req.value_list(), &vl);
297 if (plugin_dispatch_values(&vl))
298 return grpc::Status(grpc::StatusCode::INTERNAL,
299 grpc::string("failed to enqueue values for writing"));
303 return grpc::Status::OK;
307 grpc::Status queryValuesRead(value_list_t const *match, std::queue<value_list_t> *value_lists) {
309 if ((iter = uc_get_iterator()) == NULL) {
310 return grpc::Status(grpc::StatusCode::INTERNAL,
311 grpc::string("failed to query values: cannot create iterator"));
314 grpc::Status status = grpc::Status::OK;
316 while (uc_iterator_next(iter, &name) == 0) {
318 if (parse_identifier_vl(name, &vl) != 0) {
319 status = grpc::Status(grpc::StatusCode::INTERNAL,
320 grpc::string("failed to parse identifier"));
324 if (!ident_matches(&vl, match))
327 if (uc_iterator_get_time(iter, &vl.time) < 0) {
328 status = grpc::Status(grpc::StatusCode::INTERNAL,
329 grpc::string("failed to retrieve value timestamp"));
332 if (uc_iterator_get_interval(iter, &vl.interval) < 0) {
333 status = grpc::Status(grpc::StatusCode::INTERNAL,
334 grpc::string("failed to retrieve value interval"));
337 if (uc_iterator_get_values(iter, &vl.values, &vl.values_len) < 0) {
338 status = grpc::Status(grpc::StatusCode::INTERNAL,
339 grpc::string("failed to retrieve values"));
343 value_lists->push(vl);
344 } // while (uc_iterator_next(iter, &name) == 0)
346 uc_iterator_destroy(iter);
350 grpc::Status queryValuesWrite(grpc::ServerContext *ctx,
351 grpc::ServerWriter<QueryValuesResponse> *writer,
352 std::queue<value_list_t> *value_lists) {
353 while (!value_lists->empty()) {
354 auto vl = value_lists->front();
355 QueryValuesResponse res;
358 auto status = marshal_value_list(&vl, res.mutable_value_list());
363 if (!writer->Write(res)) {
364 return grpc::Status::CANCELLED;
371 return grpc::Status::OK;
376 * gRPC server implementation
378 class CollectdServer final
383 auto auth = grpc::InsecureServerCredentials();
385 grpc::ServerBuilder builder;
387 if (listeners.empty()) {
388 builder.AddListeningPort(default_addr, auth);
389 INFO("grpc: Listening on %s", default_addr.c_str());
392 for (auto l : listeners) {
393 grpc::string addr = l.addr + ":" + l.port;
395 auto use_ssl = grpc::string("");
397 if (l.ssl != nullptr) {
398 use_ssl = grpc::string(" (SSL enabled)");
399 a = grpc::SslServerCredentials(*l.ssl);
402 builder.AddListeningPort(addr, a);
403 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
407 builder.RegisterService(&collectd_service_);
409 server_ = builder.BuildAndStart();
418 CollectdImpl collectd_service_;
420 std::unique_ptr<grpc::Server> server_;
421 }; /* class CollectdServer */
423 class CollectdClient final
426 CollectdClient(std::shared_ptr<grpc::ChannelInterface> channel) : stub_(Collectd::NewStub(channel)) {
429 int PutValues(value_list_t const *vl) {
430 grpc::ClientContext ctx;
432 PutValuesRequest req;
433 auto status = marshal_value_list(vl, req.mutable_value_list());
435 ERROR("grpc: Marshalling value_list_t failed.");
439 PutValuesResponse res;
440 auto stream = stub_->PutValues(&ctx, &res);
441 if (!stream->Write(req)) {
442 NOTICE("grpc: Broken stream.");
443 /* intentionally not returning. */
446 stream->WritesDone();
447 status = stream->Finish();
449 ERROR ("grpc: Error while closing stream.");
454 } /* int PutValues */
457 std::unique_ptr<Collectd::Stub> stub_;
460 static CollectdServer *server = nullptr;
463 * collectd plugin interface
466 static void c_grpc_destroy_write_callback (void *ptr) {
467 delete (CollectdClient *) ptr;
470 static int c_grpc_write(__attribute__((unused)) data_set_t const *ds,
471 value_list_t const *vl,
473 CollectdClient *c = (CollectdClient *) ud->data;
474 return c->PutValues(vl);
477 static int c_grpc_config_listen(oconfig_item_t *ci)
479 if ((ci->values_num != 2)
480 || (ci->values[0].type != OCONFIG_TYPE_STRING)
481 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
482 ERROR("grpc: The `%s` config option needs exactly "
483 "two string argument (address and port).", ci->key);
487 auto listener = Listener();
488 listener.addr = grpc::string(ci->values[0].value.string);
489 listener.port = grpc::string(ci->values[1].value.string);
490 listener.ssl = nullptr;
492 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
493 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
494 bool use_ssl = false;
496 for (int i = 0; i < ci->children_num; i++) {
497 oconfig_item_t *child = ci->children + i;
499 if (!strcasecmp("EnableSSL", child->key)) {
500 if (cf_util_get_boolean(child, &use_ssl)) {
501 ERROR("grpc: Option `%s` expects a boolean value",
506 else if (!strcasecmp("SSLCACertificateFile", child->key)) {
508 if (cf_util_get_string(child, &certs)) {
509 ERROR("grpc: Option `%s` expects a string value",
513 ssl_opts->pem_root_certs = read_file(certs);
515 else if (!strcasecmp("SSLCertificateKeyFile", child->key)) {
517 if (cf_util_get_string(child, &key)) {
518 ERROR("grpc: Option `%s` expects a string value",
522 pkcp.private_key = read_file(key);
524 else if (!strcasecmp("SSLCertificateFile", child->key)) {
526 if (cf_util_get_string(child, &cert)) {
527 ERROR("grpc: Option `%s` expects a string value",
531 pkcp.cert_chain = read_file(cert);
534 WARNING("grpc: Option `%s` not allowed in <%s> block.",
535 child->key, ci->key);
539 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
541 listener.ssl = ssl_opts;
545 listeners.push_back(listener);
547 } /* c_grpc_config_listen() */
549 static int c_grpc_config_server(oconfig_item_t *ci)
551 if ((ci->values_num != 2)
552 || (ci->values[0].type != OCONFIG_TYPE_STRING)
553 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
554 ERROR("grpc: The `%s` config option needs exactly "
555 "two string argument (address and port).", ci->key);
559 grpc::SslCredentialsOptions ssl_opts;
560 bool use_ssl = false;
562 for (int i = 0; i < ci->children_num; i++) {
563 oconfig_item_t *child = ci->children + i;
565 if (!strcasecmp("EnableSSL", child->key)) {
566 if (cf_util_get_boolean(child, &use_ssl)) {
570 else if (!strcasecmp("SSLCACertificateFile", child->key)) {
572 if (cf_util_get_string(child, &certs)) {
575 ssl_opts.pem_root_certs = read_file(certs);
577 else if (!strcasecmp("SSLCertificateKeyFile", child->key)) {
579 if (cf_util_get_string(child, &key)) {
582 ssl_opts.pem_private_key = read_file(key);
584 else if (!strcasecmp("SSLCertificateFile", child->key)) {
586 if (cf_util_get_string(child, &cert)) {
589 ssl_opts.pem_cert_chain = read_file(cert);
592 WARNING("grpc: Option `%s` not allowed in <%s> block.",
593 child->key, ci->key);
597 auto node = grpc::string(ci->values[0].value.string);
598 auto service = grpc::string(ci->values[1].value.string);
599 auto addr = node + ":" + service;
601 CollectdClient *client;
603 auto channel_creds = grpc::SslCredentials(ssl_opts);
604 auto channel = grpc::CreateChannel(addr, channel_creds);
605 client = new CollectdClient(channel);
607 auto channel = grpc::CreateChannel(addr, grpc::InsecureChannelCredentials());
608 client = new CollectdClient(channel);
611 auto callback_name = grpc::string("grpc/") + addr;
614 .free_func = c_grpc_destroy_write_callback,
617 plugin_register_write (callback_name.c_str(), c_grpc_write, &ud);
619 } /* c_grpc_config_server() */
621 static int c_grpc_config(oconfig_item_t *ci)
625 for (i = 0; i < ci->children_num; i++) {
626 oconfig_item_t *child = ci->children + i;
628 if (!strcasecmp("Listen", child->key)) {
629 if (c_grpc_config_listen(child))
632 else if (!strcasecmp("Server", child->key)) {
633 if (c_grpc_config_server(child))
638 WARNING("grpc: Option `%s` not allowed here.", child->key);
643 } /* c_grpc_config() */
645 static int c_grpc_init(void)
647 server = new CollectdServer();
649 ERROR("grpc: Failed to create server");
655 } /* c_grpc_init() */
657 static int c_grpc_shutdown(void)
668 } /* c_grpc_shutdown() */
670 void module_register(void)
672 plugin_register_complex_config("grpc", c_grpc_config);
673 plugin_register_init("grpc", c_grpc_init);
674 plugin_register_shutdown("grpc", c_grpc_shutdown);
675 } /* module_register() */
678 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */