1 /**
2 * collectd - src/grpc.cc
3 * Copyright (C) 2015-2016 Sebastian Harl
4 *
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:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
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.
22 *
23 * Authors:
24 * Sebastian Harl <sh at tokkee.org>
25 **/
27 #include <grpc++/grpc++.h>
28 #include <google/protobuf/util/time_util.h>
30 #include <fstream>
31 #include <iostream>
32 #include <queue>
33 #include <vector>
35 #include "collectd.grpc.pb.h"
37 extern "C" {
38 #include <fnmatch.h>
39 #include <stdbool.h>
41 #include "collectd.h"
42 #include "common.h"
43 #include "plugin.h"
45 #include "daemon/utils_cache.h"
46 }
48 using collectd::Collectd;
50 using collectd::DispatchValuesRequest;
51 using collectd::DispatchValuesResponse;
52 using collectd::QueryValuesRequest;
53 using collectd::QueryValuesResponse;
55 using google::protobuf::util::TimeUtil;
57 /*
58 * private types
59 */
61 struct Listener {
62 grpc::string addr;
63 grpc::string port;
65 grpc::SslServerCredentialsOptions *ssl;
66 };
67 static std::vector<Listener> listeners;
68 static grpc::string default_addr("0.0.0.0:50051");
70 /*
71 * helper functions
72 */
74 static bool ident_matches(const value_list_t *vl, const value_list_t *matcher)
75 {
76 if (fnmatch(matcher->host, vl->host, 0))
77 return false;
79 if (fnmatch(matcher->plugin, vl->plugin, 0))
80 return false;
81 if (fnmatch(matcher->plugin_instance, vl->plugin_instance, 0))
82 return false;
84 if (fnmatch(matcher->type, vl->type, 0))
85 return false;
86 if (fnmatch(matcher->type_instance, vl->type_instance, 0))
87 return false;
89 return true;
90 } /* ident_matches */
92 static grpc::string read_file(const char *filename)
93 {
94 std::ifstream f;
95 grpc::string s, content;
97 f.open(filename);
98 if (!f.is_open()) {
99 ERROR("grpc: Failed to open '%s'", filename);
100 return "";
101 }
103 while (std::getline(f, s)) {
104 content += s;
105 content.push_back('\n');
106 }
107 f.close();
108 return content;
109 } /* read_file */
111 /*
112 * proto conversion
113 */
115 static void marshal_ident(const value_list_t *vl, collectd::types::Identifier *msg)
116 {
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,
127 bool require_fields)
128 {
129 std::string s;
131 s = msg.host();
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));
137 s = msg.plugin();
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));
143 s = msg.type();
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)
159 {
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"));
167 }
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);
179 break;
180 case DS_TYPE_GAUGE:
181 v->set_gauge(vl->values[i].gauge);
182 break;
183 case DS_TYPE_DERIVE:
184 v->set_derive(vl->values[i].derive);
185 break;
186 case DS_TYPE_ABSOLUTE:
187 v->set_absolute(vl->values[i].absolute);
188 break;
189 default:
190 return grpc::Status(grpc::StatusCode::INTERNAL,
191 grpc::string("unknown value type"));
192 }
194 auto name = msg->add_ds_names();
195 name->assign(ds->ds[i].name);
196 }
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)
202 {
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);
207 if (!status.ok())
208 return status;
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));
216 if (!val) {
217 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
218 grpc::string("failed to allocate values array"));
219 break;
220 }
222 values = val;
223 val = values + values_len;
224 values_len++;
226 switch (v.value_case()) {
227 case collectd::types::Value::ValueCase::kCounter:
228 val->counter = counter_t(v.counter());
229 break;
230 case collectd::types::Value::ValueCase::kGauge:
231 val->gauge = gauge_t(v.gauge());
232 break;
233 case collectd::types::Value::ValueCase::kDerive:
234 val->derive = derive_t(v.derive());
235 break;
236 case collectd::types::Value::ValueCase::kAbsolute:
237 val->absolute = absolute_t(v.absolute());
238 break;
239 default:
240 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
241 grpc::string("unknown value type"));
242 break;
243 }
245 if (!status.ok())
246 break;
247 }
248 if (status.ok()) {
249 vl->values = values;
250 vl->values_len = values_len;
251 }
252 else if (values) {
253 free(values);
254 }
256 return status;
257 } /* unmarshal_value_list() */
259 /*
260 * Collectd service
261 */
262 class CollectdImpl : public collectd::Collectd::Service {
263 public:
264 grpc::Status QueryValues(grpc::ServerContext *ctx, QueryValuesRequest const *req, grpc::ServerWriter<QueryValuesResponse> *writer) override {
265 value_list_t match;
266 auto status = unmarshal_ident(req->identifier(), &match, false);
267 if (!status.ok()) {
268 return status;
269 }
271 std::queue<value_list_t> value_lists;
272 status = this->queryValuesRead(&match, &value_lists);
273 if (status.ok()) {
274 status = this->queryValuesWrite(ctx, writer, &value_lists);
275 }
277 while (!value_lists.empty()) {
278 auto vl = value_lists.front();
279 value_lists.pop();
280 sfree(vl.values);
281 }
283 return status;
284 }
286 grpc::Status DispatchValues(grpc::ServerContext *ctx,
287 grpc::ServerReader<DispatchValuesRequest> *reader,
288 DispatchValuesResponse *res) override {
289 DispatchValuesRequest req;
291 while (reader->Read(&req)) {
292 value_list_t vl = VALUE_LIST_INIT;
293 auto status = unmarshal_value_list(req.value_list(), &vl);
294 if (!status.ok())
295 return status;
297 if (plugin_dispatch_values(&vl))
298 return grpc::Status(grpc::StatusCode::INTERNAL,
299 grpc::string("failed to enqueue values for writing"));
300 }
302 res->Clear();
303 return grpc::Status::OK;
304 }
306 private:
307 grpc::Status queryValuesRead(value_list_t const *match, std::queue<value_list_t> *value_lists) {
308 uc_iter_t *iter;
309 if ((iter = uc_get_iterator()) == NULL) {
310 return grpc::Status(grpc::StatusCode::INTERNAL,
311 grpc::string("failed to query values: cannot create iterator"));
312 }
314 grpc::Status status = grpc::Status::OK;
315 char *name = NULL;
316 while (uc_iterator_next(iter, &name) == 0) {
317 value_list_t vl;
318 if (parse_identifier_vl(name, &vl) != 0) {
319 status = grpc::Status(grpc::StatusCode::INTERNAL,
320 grpc::string("failed to parse identifier"));
321 break;
322 }
324 if (!ident_matches(&vl, match))
325 continue;
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"));
330 break;
331 }
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"));
335 break;
336 }
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"));
340 break;
341 }
343 value_lists->push(vl);
344 } // while (uc_iterator_next(iter, &name) == 0)
346 uc_iterator_destroy(iter);
347 return status;
348 }
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;
356 res.Clear();
358 auto status = marshal_value_list(&vl, res.mutable_value_list());
359 if (!status.ok()) {
360 return status;
361 }
363 if (!writer->Write(res)) {
364 return grpc::Status::CANCELLED;
365 }
367 value_lists->pop();
368 sfree(vl.values);
369 }
371 return grpc::Status::OK;
372 }
373 };
375 /*
376 * gRPC server implementation
377 */
378 class CollectdServer final
379 {
380 public:
381 void Start()
382 {
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());
390 }
391 else {
392 for (auto l : listeners) {
393 grpc::string addr = l.addr + ":" + l.port;
395 auto use_ssl = grpc::string("");
396 auto a = auth;
397 if (l.ssl != nullptr) {
398 use_ssl = grpc::string(" (SSL enabled)");
399 a = grpc::SslServerCredentials(*l.ssl);
400 }
402 builder.AddListeningPort(addr, a);
403 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
404 }
405 }
407 builder.RegisterService(&collectd_service_);
409 server_ = builder.BuildAndStart();
410 } /* Start() */
412 void Shutdown()
413 {
414 server_->Shutdown();
415 } /* Shutdown() */
417 private:
418 CollectdImpl collectd_service_;
420 std::unique_ptr<grpc::Server> server_;
421 }; /* class CollectdServer */
423 static CollectdServer *server = nullptr;
425 /*
426 * collectd plugin interface
427 */
428 extern "C" {
429 static int c_grpc_config_listen(oconfig_item_t *ci)
430 {
431 if ((ci->values_num != 2)
432 || (ci->values[0].type != OCONFIG_TYPE_STRING)
433 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
434 ERROR("grpc: The `%s` config option needs exactly "
435 "two string argument (address and port).", ci->key);
436 return -1;
437 }
439 auto listener = Listener();
440 listener.addr = grpc::string(ci->values[0].value.string);
441 listener.port = grpc::string(ci->values[1].value.string);
442 listener.ssl = nullptr;
444 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
445 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
446 bool use_ssl = false;
448 for (int i = 0; i < ci->children_num; i++) {
449 oconfig_item_t *child = ci->children + i;
451 if (!strcasecmp("EnableSSL", child->key)) {
452 if (cf_util_get_boolean(child, &use_ssl)) {
453 ERROR("grpc: Option `%s` expects a boolean value",
454 child->key);
455 return -1;
456 }
457 }
458 else if (!strcasecmp("SSLRootCerts", child->key)) {
459 char *certs = NULL;
460 if (cf_util_get_string(child, &certs)) {
461 ERROR("grpc: Option `%s` expects a string value",
462 child->key);
463 return -1;
464 }
465 ssl_opts->pem_root_certs = read_file(certs);
466 }
467 else if (!strcasecmp("SSLServerKey", child->key)) {
468 char *key = NULL;
469 if (cf_util_get_string(child, &key)) {
470 ERROR("grpc: Option `%s` expects a string value",
471 child->key);
472 return -1;
473 }
474 pkcp.private_key = read_file(key);
475 }
476 else if (!strcasecmp("SSLServerCert", child->key)) {
477 char *cert = NULL;
478 if (cf_util_get_string(child, &cert)) {
479 ERROR("grpc: Option `%s` expects a string value",
480 child->key);
481 return -1;
482 }
483 pkcp.cert_chain = read_file(cert);
484 }
485 else {
486 WARNING("grpc: Option `%s` not allowed in <%s> block.",
487 child->key, ci->key);
488 }
489 }
491 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
492 if (use_ssl)
493 listener.ssl = ssl_opts;
494 else
495 delete(ssl_opts);
497 listeners.push_back(listener);
498 return 0;
499 } /* c_grpc_config_listen() */
501 static int c_grpc_config(oconfig_item_t *ci)
502 {
503 int i;
505 for (i = 0; i < ci->children_num; i++) {
506 oconfig_item_t *child = ci->children + i;
508 if (!strcasecmp("Listen", child->key)) {
509 if (c_grpc_config_listen(child))
510 return -1;
511 }
512 else {
513 WARNING("grpc: Option `%s` not allowed here.", child->key);
514 }
515 }
517 return 0;
518 } /* c_grpc_config() */
520 static int c_grpc_init(void)
521 {
522 server = new CollectdServer();
523 if (!server) {
524 ERROR("grpc: Failed to create server");
525 return -1;
526 }
528 server->Start();
529 return 0;
530 } /* c_grpc_init() */
532 static int c_grpc_shutdown(void)
533 {
534 if (!server)
535 return 0;
537 server->Shutdown();
539 delete server;
540 server = nullptr;
542 return 0;
543 } /* c_grpc_shutdown() */
545 void module_register(void)
546 {
547 plugin_register_complex_config("grpc", c_grpc_config);
548 plugin_register_init("grpc", c_grpc_init);
549 plugin_register_shutdown("grpc", c_grpc_shutdown);
550 } /* module_register() */
551 } /* extern "C" */
553 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */