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"
43 #include "configfile.h"
46 #include "daemon/utils_cache.h"
49 using collectd::Collectd;
51 using collectd::DispatchValuesRequest;
52 using collectd::DispatchValuesResponse;
53 using collectd::QueryValuesRequest;
54 using collectd::QueryValuesResponse;
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_values();
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"));
195 auto name = msg->add_ds_names();
196 name->assign(ds->ds[i].name);
199 return grpc::Status::OK;
200 } /* marshal_value_list */
202 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
204 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
205 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
207 auto status = unmarshal_ident(msg.identifier(), vl, true);
211 value_t *values = NULL;
212 size_t values_len = 0;
214 status = grpc::Status::OK;
215 for (auto v : msg.values()) {
216 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
218 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
219 grpc::string("failed to allocate values array"));
224 val = values + values_len;
227 switch (v.value_case()) {
228 case collectd::types::Value::ValueCase::kCounter:
229 val->counter = counter_t(v.counter());
231 case collectd::types::Value::ValueCase::kGauge:
232 val->gauge = gauge_t(v.gauge());
234 case collectd::types::Value::ValueCase::kDerive:
235 val->derive = derive_t(v.derive());
237 case collectd::types::Value::ValueCase::kAbsolute:
238 val->absolute = absolute_t(v.absolute());
241 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
242 grpc::string("unknown value type"));
251 vl->values_len = values_len;
258 } /* unmarshal_value_list() */
263 class CollectdImpl : public collectd::Collectd::Service {
265 grpc::Status QueryValues(grpc::ServerContext *ctx, QueryValuesRequest const *req, grpc::ServerWriter<QueryValuesResponse> *writer) override {
267 auto err = unmarshal_ident(req->identifier(), &match, false);
272 std::queue<value_list_t> value_lists;
273 err = this->queryValuesRead(&match, &value_lists);
275 err = this->queryValuesWrite(ctx, writer, &value_lists);
278 while (!value_lists.empty()) {
279 auto vl = value_lists.front();
287 grpc::Status DispatchValues(grpc::ServerContext *ctx,
288 grpc::ServerReader<DispatchValuesRequest> *reader,
289 DispatchValuesResponse *res) override {
290 DispatchValuesRequest req;
292 while (reader->Read(&req)) {
293 value_list_t vl = VALUE_LIST_INIT;
294 auto status = unmarshal_value_list(req.value_list(), &vl);
298 if (plugin_dispatch_values(&vl))
299 return grpc::Status(grpc::StatusCode::INTERNAL,
300 grpc::string("failed to enqueue values for writing"));
304 return grpc::Status::OK;
308 grpc::Status queryValuesRead(value_list_t const *match, std::queue<value_list_t> *value_lists) {
310 if ((iter = uc_get_iterator()) == NULL) {
311 return grpc::Status(grpc::StatusCode::INTERNAL,
312 grpc::string("failed to query values: cannot create iterator"));
315 grpc::Status status = grpc::Status::OK;
317 while (uc_iterator_next(iter, &name) == 0) {
319 if (parse_identifier_vl(name, &vl) != 0) {
320 status = grpc::Status(grpc::StatusCode::INTERNAL,
321 grpc::string("failed to parse identifier"));
325 if (!ident_matches(&vl, match))
328 if (uc_iterator_get_time(iter, &vl.time) < 0) {
329 status = grpc::Status(grpc::StatusCode::INTERNAL,
330 grpc::string("failed to retrieve value timestamp"));
333 if (uc_iterator_get_interval(iter, &vl.interval) < 0) {
334 status = grpc::Status(grpc::StatusCode::INTERNAL,
335 grpc::string("failed to retrieve value interval"));
338 if (uc_iterator_get_values(iter, &vl.values, &vl.values_len) < 0) {
339 status = grpc::Status(grpc::StatusCode::INTERNAL,
340 grpc::string("failed to retrieve values"));
344 value_lists->push(vl);
345 } // while (uc_iterator_next(iter, &name) == 0)
347 uc_iterator_destroy(iter);
351 grpc::Status queryValuesWrite(grpc::ServerContext *ctx,
352 grpc::ServerWriter<QueryValuesResponse> *writer,
353 std::queue<value_list_t> *value_lists) {
354 while (!value_lists->empty()) {
355 auto vl = value_lists->front();
356 QueryValuesResponse res;
359 auto err = marshal_value_list(&vl, res.mutable_value_list());
364 if (!writer->Write(res)) {
365 return grpc::Status::CANCELLED;
372 return grpc::Status::OK;
377 * gRPC server implementation
379 class CollectdServer final
384 auto auth = grpc::InsecureServerCredentials();
386 grpc::ServerBuilder builder;
388 if (listeners.empty()) {
389 builder.AddListeningPort(default_addr, auth);
390 INFO("grpc: Listening on %s", default_addr.c_str());
393 for (auto l : listeners) {
394 grpc::string addr = l.addr + ":" + l.port;
396 auto use_ssl = grpc::string("");
398 if (l.ssl != nullptr) {
399 use_ssl = grpc::string(" (SSL enabled)");
400 a = grpc::SslServerCredentials(*l.ssl);
403 builder.AddListeningPort(addr, a);
404 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
408 builder.RegisterService(&collectd_service_);
410 server_ = builder.BuildAndStart();
419 CollectdImpl collectd_service_;
421 std::unique_ptr<grpc::Server> server_;
422 }; /* class CollectdServer */
424 static CollectdServer *server = nullptr;
427 * collectd plugin interface
430 static int c_grpc_config_listen(oconfig_item_t *ci)
432 if ((ci->values_num != 2)
433 || (ci->values[0].type != OCONFIG_TYPE_STRING)
434 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
435 ERROR("grpc: The `%s` config option needs exactly "
436 "two string argument (address and port).", ci->key);
440 auto listener = Listener();
441 listener.addr = grpc::string(ci->values[0].value.string);
442 listener.port = grpc::string(ci->values[1].value.string);
443 listener.ssl = nullptr;
445 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
446 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
447 bool use_ssl = false;
449 for (int i = 0; i < ci->children_num; i++) {
450 oconfig_item_t *child = ci->children + i;
452 if (!strcasecmp("EnableSSL", child->key)) {
453 if (cf_util_get_boolean(child, &use_ssl)) {
454 ERROR("grpc: Option `%s` expects a boolean value",
459 else if (!strcasecmp("SSLRootCerts", child->key)) {
461 if (cf_util_get_string(child, &certs)) {
462 ERROR("grpc: Option `%s` expects a string value",
466 ssl_opts->pem_root_certs = read_file(certs);
468 else if (!strcasecmp("SSLServerKey", child->key)) {
470 if (cf_util_get_string(child, &key)) {
471 ERROR("grpc: Option `%s` expects a string value",
475 pkcp.private_key = read_file(key);
477 else if (!strcasecmp("SSLServerCert", child->key)) {
479 if (cf_util_get_string(child, &cert)) {
480 ERROR("grpc: Option `%s` expects a string value",
484 pkcp.cert_chain = read_file(cert);
487 WARNING("grpc: Option `%s` not allowed in <%s> block.",
488 child->key, ci->key);
492 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
494 listener.ssl = ssl_opts;
498 listeners.push_back(listener);
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))
514 WARNING("grpc: Option `%s` not allowed here.", child->key);
519 } /* c_grpc_config() */
521 static int c_grpc_init(void)
523 server = new CollectdServer();
525 ERROR("grpc: Failed to create server");
531 } /* c_grpc_init() */
533 static int c_grpc_shutdown(void)
544 } /* c_grpc_shutdown() */
546 void module_register(void)
548 plugin_register_complex_config("grpc", c_grpc_config);
549 plugin_register_init("grpc", c_grpc_init);
550 plugin_register_shutdown("grpc", c_grpc_shutdown);
551 } /* module_register() */
554 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */