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 <vector>
34 #include "collectd.grpc.pb.h"
36 extern "C" {
37 #include <fnmatch.h>
38 #include <stdbool.h>
40 #include "collectd.h"
41 #include "common.h"
42 #include "configfile.h"
43 #include "plugin.h"
45 #include "daemon/utils_cache.h"
46 }
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;
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_value();
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 }
193 }
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)
199 {
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);
204 if (!status.ok())
205 return status;
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));
213 if (!val) {
214 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
215 grpc::string("failed to allocate values array"));
216 break;
217 }
219 values = val;
220 val = values + values_len;
221 values_len++;
223 switch (v.value_case()) {
224 case collectd::types::Value::ValueCase::kCounter:
225 val->counter = counter_t(v.counter());
226 break;
227 case collectd::types::Value::ValueCase::kGauge:
228 val->gauge = gauge_t(v.gauge());
229 break;
230 case collectd::types::Value::ValueCase::kDerive:
231 val->derive = derive_t(v.derive());
232 break;
233 case collectd::types::Value::ValueCase::kAbsolute:
234 val->absolute = absolute_t(v.absolute());
235 break;
236 default:
237 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
238 grpc::string("unknown value type"));
239 break;
240 }
242 if (!status.ok())
243 break;
244 }
245 if (status.ok()) {
246 vl->values = values;
247 vl->values_len = values_len;
248 }
249 else if (values) {
250 free(values);
251 }
253 return status;
254 } /* unmarshal_value_list() */
256 /*
257 * request call-backs and call objects
258 */
260 static grpc::Status Process(grpc::ServerContext *ctx,
261 DispatchValuesRequest request, DispatchValuesReply *reply)
262 {
263 value_list_t vl = VALUE_LIST_INIT;
264 auto status = unmarshal_value_list(request.values(), &vl);
265 if (!status.ok())
266 return status;
268 if (plugin_dispatch_values(&vl))
269 status = grpc::Status(grpc::StatusCode::INTERNAL,
270 grpc::string("failed to enqueue values for writing"));
271 return status;
272 } /* Process(): DispatchValues */
274 static grpc::Status Process(grpc::ServerContext *ctx,
275 QueryValuesRequest request, QueryValuesReply *reply)
276 {
277 uc_iter_t *iter;
278 char *name = NULL;
280 value_list_t matcher;
281 auto status = unmarshal_ident(request.identifier(), &matcher, false);
282 if (!status.ok())
283 return status;
285 if ((iter = uc_get_iterator()) == NULL) {
286 return grpc::Status(grpc::StatusCode::INTERNAL,
287 grpc::string("failed to query values: cannot create iterator"));
288 }
290 while (uc_iterator_next(iter, &name) == 0) {
291 value_list_t res;
292 if (parse_identifier_vl(name, &res) != 0)
293 return grpc::Status(grpc::StatusCode::INTERNAL,
294 grpc::string("failed to parse identifier"));
296 if (!ident_matches(&res, &matcher))
297 continue;
299 if (uc_iterator_get_time(iter, &res.time) < 0)
300 return grpc::Status(grpc::StatusCode::INTERNAL,
301 grpc::string("failed to retrieve value timestamp"));
302 if (uc_iterator_get_interval(iter, &res.interval) < 0)
303 return grpc::Status(grpc::StatusCode::INTERNAL,
304 grpc::string("failed to retrieve value interval"));
305 if (uc_iterator_get_values(iter, &res.values, &res.values_len) < 0)
306 return grpc::Status(grpc::StatusCode::INTERNAL,
307 grpc::string("failed to retrieve values"));
309 auto vl = reply->add_values();
310 status = marshal_value_list(&res, vl);
311 free(res.values);
312 if (!status.ok())
313 return status;
314 }
316 uc_iterator_destroy(iter);
318 return grpc::Status::OK;
319 } /* Process(): QueryValues */
321 class Call
322 {
323 public:
324 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
325 : service_(service), cq_(cq), status_(CREATE)
326 { }
328 virtual ~Call()
329 { }
331 void Handle()
332 {
333 if (status_ == CREATE) {
334 Create();
335 status_ = PROCESS;
336 }
337 else if (status_ == PROCESS) {
338 Process();
339 status_ = FINISH;
340 }
341 else {
342 GPR_ASSERT(status_ == FINISH);
343 Finish();
344 }
345 } /* Handle() */
347 protected:
348 virtual void Create() = 0;
349 virtual void Process() = 0;
350 virtual void Finish() = 0;
352 Collectd::AsyncService *service_;
353 grpc::ServerCompletionQueue *cq_;
354 grpc::ServerContext ctx_;
356 private:
357 enum CallStatus { CREATE, PROCESS, FINISH };
358 CallStatus status_;
359 }; /* class Call */
361 template<typename RequestT, typename ReplyT>
362 class RpcCall final : public Call
363 {
364 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
365 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
366 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
368 public:
369 RpcCall(Collectd::AsyncService *service,
370 CreatorT creator, grpc::ServerCompletionQueue *cq)
371 : Call(service, cq), creator_(creator), responder_(&ctx_)
372 {
373 Handle();
374 } /* RpcCall() */
376 virtual ~RpcCall()
377 { }
379 private:
380 void Create()
381 {
382 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
383 } /* Create() */
385 void Process()
386 {
387 // Add a new request object to the queue.
388 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
389 grpc::Status status = ::Process(&ctx_, request_, &reply_);
390 responder_.Finish(reply_, status, this);
391 } /* Process() */
393 void Finish()
394 {
395 delete this;
396 } /* Finish() */
398 CreatorT creator_;
400 RequestT request_;
401 ReplyT reply_;
403 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
404 }; /* class RpcCall */
406 /*
407 * gRPC server implementation
408 */
410 class CollectdServer final
411 {
412 public:
413 void Start()
414 {
415 auto auth = grpc::InsecureServerCredentials();
417 grpc::ServerBuilder builder;
419 if (listeners.empty()) {
420 builder.AddListeningPort(default_addr, auth);
421 INFO("grpc: Listening on %s", default_addr.c_str());
422 }
423 else {
424 for (auto l : listeners) {
425 grpc::string addr = l.addr + ":" + l.port;
427 auto use_ssl = grpc::string("");
428 auto a = auth;
429 if (l.ssl != nullptr) {
430 use_ssl = grpc::string(" (SSL enabled)");
431 a = grpc::SslServerCredentials(*l.ssl);
432 }
434 builder.AddListeningPort(addr, a);
435 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
436 }
437 }
439 builder.RegisterService(&service_);
440 cq_ = builder.AddCompletionQueue();
441 server_ = builder.BuildAndStart();
442 } /* Start() */
444 void Shutdown()
445 {
446 server_->Shutdown();
447 cq_->Shutdown();
448 } /* Shutdown() */
450 void Mainloop()
451 {
452 // Register request types.
453 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
454 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
455 new RpcCall<QueryValuesRequest, QueryValuesReply>(&service_,
456 &Collectd::AsyncService::RequestQueryValues, cq_.get());
458 while (true) {
459 void *req = NULL;
460 bool ok = false;
462 if (!cq_->Next(&req, &ok))
463 break; // Queue shut down.
464 if (!ok) {
465 ERROR("grpc: Failed to read from queue");
466 break;
467 }
469 static_cast<Call *>(req)->Handle();
470 }
471 } /* Mainloop() */
473 private:
474 Collectd::AsyncService service_;
476 std::unique_ptr<grpc::Server> server_;
477 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
478 }; /* class CollectdServer */
480 static CollectdServer *server = nullptr;
482 /*
483 * collectd plugin interface
484 */
486 extern "C" {
487 static pthread_t *workers;
488 static size_t workers_num = 5;
490 static void *worker_thread(void *arg)
491 {
492 CollectdServer *s = (CollectdServer *)arg;
493 s->Mainloop();
494 return NULL;
495 } /* worker_thread() */
497 static int c_grpc_config_listen(oconfig_item_t *ci)
498 {
499 if ((ci->values_num != 2)
500 || (ci->values[0].type != OCONFIG_TYPE_STRING)
501 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
502 ERROR("grpc: The `%s` config option needs exactly "
503 "two string argument (address and port).", ci->key);
504 return -1;
505 }
507 auto listener = Listener();
508 listener.addr = grpc::string(ci->values[0].value.string);
509 listener.port = grpc::string(ci->values[1].value.string);
510 listener.ssl = nullptr;
512 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
513 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
514 bool use_ssl = false;
516 for (int i = 0; i < ci->children_num; i++) {
517 oconfig_item_t *child = ci->children + i;
519 if (!strcasecmp("EnableSSL", child->key)) {
520 if (cf_util_get_boolean(child, &use_ssl)) {
521 ERROR("grpc: Option `%s` expects a boolean value",
522 child->key);
523 return -1;
524 }
525 }
526 else if (!strcasecmp("SSLRootCerts", child->key)) {
527 char *certs = NULL;
528 if (cf_util_get_string(child, &certs)) {
529 ERROR("grpc: Option `%s` expects a string value",
530 child->key);
531 return -1;
532 }
533 ssl_opts->pem_root_certs = read_file(certs);
534 }
535 else if (!strcasecmp("SSLServerKey", child->key)) {
536 char *key = NULL;
537 if (cf_util_get_string(child, &key)) {
538 ERROR("grpc: Option `%s` expects a string value",
539 child->key);
540 return -1;
541 }
542 pkcp.private_key = read_file(key);
543 }
544 else if (!strcasecmp("SSLServerCert", child->key)) {
545 char *cert = NULL;
546 if (cf_util_get_string(child, &cert)) {
547 ERROR("grpc: Option `%s` expects a string value",
548 child->key);
549 return -1;
550 }
551 pkcp.cert_chain = read_file(cert);
552 }
553 else {
554 WARNING("grpc: Option `%s` not allowed in <%s> block.",
555 child->key, ci->key);
556 }
557 }
559 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
560 if (use_ssl)
561 listener.ssl = ssl_opts;
562 else
563 delete(ssl_opts);
565 listeners.push_back(listener);
566 return 0;
567 } /* c_grpc_config_listen() */
569 static int c_grpc_config(oconfig_item_t *ci)
570 {
571 int i;
573 for (i = 0; i < ci->children_num; i++) {
574 oconfig_item_t *child = ci->children + i;
576 if (!strcasecmp("Listen", child->key)) {
577 if (c_grpc_config_listen(child))
578 return -1;
579 }
580 else if (!strcasecmp("WorkerThreads", child->key)) {
581 int n;
582 if (cf_util_get_int(child, &n))
583 return -1;
584 workers_num = (size_t)n;
585 }
586 else {
587 WARNING("grpc: Option `%s` not allowed here.", child->key);
588 }
589 }
591 return 0;
592 } /* c_grpc_config() */
594 static int c_grpc_init(void)
595 {
596 server = new CollectdServer();
597 size_t i;
599 if (! server) {
600 ERROR("grpc: Failed to create server");
601 return -1;
602 }
604 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
605 if (! workers) {
606 delete server;
607 server = nullptr;
609 ERROR("grpc: Failed to allocate worker threads");
610 return -1;
611 }
613 server->Start();
614 for (i = 0; i < workers_num; i++) {
615 plugin_thread_create(&workers[i], /* attr = */ NULL,
616 worker_thread, server);
617 }
618 INFO("grpc: Started %zu workers", workers_num);
619 return 0;
620 } /* c_grpc_init() */
622 static int c_grpc_shutdown(void)
623 {
624 size_t i;
626 if (!server)
627 return -1;
629 server->Shutdown();
631 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
632 for (i = 0; i < workers_num; i++)
633 pthread_join(workers[i], NULL);
634 free(workers);
635 workers = NULL;
636 workers_num = 0;
638 delete server;
639 server = nullptr;
641 return 0;
642 } /* c_grpc_shutdown() */
644 void module_register(void)
645 {
646 plugin_register_complex_config("grpc", c_grpc_config);
647 plugin_register_init("grpc", c_grpc_init);
648 plugin_register_shutdown("grpc", c_grpc_shutdown);
649 } /* module_register() */
650 } /* extern "C" */
652 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */