grpc plugin: Add the "ds_names" field to the ValueList message.
[collectd.git] / src / grpc.cc
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  **/
26
27 #include <grpc++/grpc++.h>
28 #include <google/protobuf/util/time_util.h>
29
30 #include <fstream>
31 #include <iostream>
32 #include <vector>
33
34 #include "collectd.grpc.pb.h"
35
36 extern "C" {
37 #include <fnmatch.h>
38 #include <stdbool.h>
39
40 #include "collectd.h"
41 #include "common.h"
42 #include "configfile.h"
43 #include "plugin.h"
44
45 #include "daemon/utils_cache.h"
46 }
47
48 using collectd::Collectd;
49
50 using collectd::DispatchValuesRequest;
51 using collectd::DispatchValuesReply;
52 using collectd::QueryValuesRequest;
53 using collectd::QueryValuesReply;
54
55 using google::protobuf::util::TimeUtil;
56
57 /*
58  * private types
59  */
60
61 struct Listener {
62         grpc::string addr;
63         grpc::string port;
64
65         grpc::SslServerCredentialsOptions *ssl;
66 };
67 static std::vector<Listener> listeners;
68 static grpc::string default_addr("0.0.0.0:50051");
69
70 /*
71  * helper functions
72  */
73
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;
78
79         if (fnmatch(matcher->plugin, vl->plugin, 0))
80                 return false;
81         if (fnmatch(matcher->plugin_instance, vl->plugin_instance, 0))
82                 return false;
83
84         if (fnmatch(matcher->type, vl->type, 0))
85                 return false;
86         if (fnmatch(matcher->type_instance, vl->type_instance, 0))
87                 return false;
88
89         return true;
90 } /* ident_matches */
91
92 static grpc::string read_file(const char *filename)
93 {
94         std::ifstream f;
95         grpc::string s, content;
96
97         f.open(filename);
98         if (!f.is_open()) {
99                 ERROR("grpc: Failed to open '%s'", filename);
100                 return "";
101         }
102
103         while (std::getline(f, s)) {
104                 content += s;
105                 content.push_back('\n');
106         }
107         f.close();
108         return content;
109 } /* read_file */
110
111 /*
112  * proto conversion
113  */
114
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 */
125
126 static grpc::Status unmarshal_ident(const collectd::types::Identifier &msg, value_list_t *vl,
127                 bool require_fields)
128 {
129         std::string s;
130
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));
136
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));
142
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));
148
149         s = msg.plugin_instance();
150         sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
151
152         s = msg.type_instance();
153         sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
154
155         return grpc::Status::OK;
156 } /* unmarshal_ident() */
157
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);
162
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         }
168
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));
173
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                 }
193
194                 auto name = msg->add_ds_names();
195                 name->assign(ds->ds[i].name);
196         }
197
198         return grpc::Status::OK;
199 } /* marshal_value_list */
200
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()));
205
206         auto status = unmarshal_ident(msg.identifier(), vl, true);
207         if (!status.ok())
208                 return status;
209
210         value_t *values = NULL;
211         size_t values_len = 0;
212
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                 }
221
222                 values = val;
223                 val = values + values_len;
224                 values_len++;
225
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                 }
244
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         }
255
256         return status;
257 } /* unmarshal_value_list() */
258
259 /*
260  * request call-backs and call objects
261  */
262
263 static grpc::Status Process(grpc::ServerContext *ctx,
264                 DispatchValuesRequest request, DispatchValuesReply *reply)
265 {
266         value_list_t vl = VALUE_LIST_INIT;
267         auto status = unmarshal_value_list(request.value_list(), &vl);
268         if (!status.ok())
269                 return status;
270
271         if (plugin_dispatch_values(&vl))
272                 status = grpc::Status(grpc::StatusCode::INTERNAL,
273                                 grpc::string("failed to enqueue values for writing"));
274         return status;
275 } /* Process(): DispatchValues */
276
277 static grpc::Status Process(grpc::ServerContext *ctx,
278                 QueryValuesRequest request, QueryValuesReply *reply)
279 {
280         uc_iter_t *iter;
281         char *name = NULL;
282
283         value_list_t matcher;
284         auto status = unmarshal_ident(request.identifier(), &matcher, false);
285         if (!status.ok())
286                 return status;
287
288         if ((iter = uc_get_iterator()) == NULL) {
289                 return grpc::Status(grpc::StatusCode::INTERNAL,
290                                 grpc::string("failed to query values: cannot create iterator"));
291         }
292
293         status = grpc::Status::OK;
294         while (uc_iterator_next(iter, &name) == 0) {
295                 value_list_t res;
296                 if (parse_identifier_vl(name, &res) != 0) {
297                         status = grpc::Status(grpc::StatusCode::INTERNAL,
298                                         grpc::string("failed to parse identifier"));
299                         break;
300                 }
301
302                 if (!ident_matches(&res, &matcher))
303                         continue;
304
305                 if (uc_iterator_get_time(iter, &res.time) < 0) {
306                         status = grpc::Status(grpc::StatusCode::INTERNAL,
307                                         grpc::string("failed to retrieve value timestamp"));
308                         break;
309                 }
310                 if (uc_iterator_get_interval(iter, &res.interval) < 0) {
311                         status = grpc::Status(grpc::StatusCode::INTERNAL,
312                                         grpc::string("failed to retrieve value interval"));
313                         break;
314                 }
315                 if (uc_iterator_get_values(iter, &res.values, &res.values_len) < 0) {
316                         status = grpc::Status(grpc::StatusCode::INTERNAL,
317                                         grpc::string("failed to retrieve values"));
318                         break;
319                 }
320
321                 auto vl = reply->add_value_lists();
322                 status = marshal_value_list(&res, vl);
323                 free(res.values);
324                 if (!status.ok())
325                         break;
326         }
327
328         uc_iterator_destroy(iter);
329
330         return status;
331 } /* Process(): QueryValues */
332
333 class Call
334 {
335 public:
336         Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
337                 : service_(service), cq_(cq), status_(CREATE)
338         { }
339
340         virtual ~Call()
341         { }
342
343         void Handle()
344         {
345                 if (status_ == CREATE) {
346                         Create();
347                         status_ = PROCESS;
348                 }
349                 else if (status_ == PROCESS) {
350                         Process();
351                         status_ = FINISH;
352                 }
353                 else {
354                         GPR_ASSERT(status_ == FINISH);
355                         Finish();
356                 }
357         } /* Handle() */
358
359 protected:
360         virtual void Create() = 0;
361         virtual void Process() = 0;
362         virtual void Finish() = 0;
363
364         Collectd::AsyncService *service_;
365         grpc::ServerCompletionQueue *cq_;
366         grpc::ServerContext ctx_;
367
368 private:
369         enum CallStatus { CREATE, PROCESS, FINISH };
370         CallStatus status_;
371 }; /* class Call */
372
373 template<typename RequestT, typename ReplyT>
374 class RpcCall final : public Call
375 {
376         typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
377                         RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
378                         grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
379
380 public:
381         RpcCall(Collectd::AsyncService *service,
382                         CreatorT creator, grpc::ServerCompletionQueue *cq)
383                 : Call(service, cq), creator_(creator), responder_(&ctx_)
384         {
385                 Handle();
386         } /* RpcCall() */
387
388         virtual ~RpcCall()
389         { }
390
391 private:
392         void Create()
393         {
394                 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
395         } /* Create() */
396
397         void Process()
398         {
399                 // Add a new request object to the queue.
400                 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
401                 grpc::Status status = ::Process(&ctx_, request_, &reply_);
402                 responder_.Finish(reply_, status, this);
403         } /* Process() */
404
405         void Finish()
406         {
407                 delete this;
408         } /* Finish() */
409
410         CreatorT creator_;
411
412         RequestT request_;
413         ReplyT reply_;
414
415         grpc::ServerAsyncResponseWriter<ReplyT> responder_;
416 }; /* class RpcCall */
417
418 /*
419  * gRPC server implementation
420  */
421
422 class CollectdServer final
423 {
424 public:
425         void Start()
426         {
427                 auto auth = grpc::InsecureServerCredentials();
428
429                 grpc::ServerBuilder builder;
430
431                 if (listeners.empty()) {
432                         builder.AddListeningPort(default_addr, auth);
433                         INFO("grpc: Listening on %s", default_addr.c_str());
434                 }
435                 else {
436                         for (auto l : listeners) {
437                                 grpc::string addr = l.addr + ":" + l.port;
438
439                                 auto use_ssl = grpc::string("");
440                                 auto a = auth;
441                                 if (l.ssl != nullptr) {
442                                         use_ssl = grpc::string(" (SSL enabled)");
443                                         a = grpc::SslServerCredentials(*l.ssl);
444                                 }
445
446                                 builder.AddListeningPort(addr, a);
447                                 INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str());
448                         }
449                 }
450
451                 builder.RegisterService(&service_);
452                 cq_ = builder.AddCompletionQueue();
453                 server_ = builder.BuildAndStart();
454         } /* Start() */
455
456         void Shutdown()
457         {
458                 server_->Shutdown();
459                 cq_->Shutdown();
460         } /* Shutdown() */
461
462         void Mainloop()
463         {
464                 // Register request types.
465                 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
466                                 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
467                 new RpcCall<QueryValuesRequest, QueryValuesReply>(&service_,
468                                 &Collectd::AsyncService::RequestQueryValues, cq_.get());
469
470                 while (true) {
471                         void *req = NULL;
472                         bool ok = false;
473
474                         if (!cq_->Next(&req, &ok))
475                                 break; // Queue shut down.
476                         if (!ok) {
477                                 ERROR("grpc: Failed to read from queue");
478                                 break;
479                         }
480
481                         static_cast<Call *>(req)->Handle();
482                 }
483         } /* Mainloop() */
484
485 private:
486         Collectd::AsyncService service_;
487
488         std::unique_ptr<grpc::Server> server_;
489         std::unique_ptr<grpc::ServerCompletionQueue> cq_;
490 }; /* class CollectdServer */
491
492 static CollectdServer *server = nullptr;
493
494 /*
495  * collectd plugin interface
496  */
497
498 extern "C" {
499         static pthread_t *workers;
500         static size_t workers_num = 5;
501
502         static void *worker_thread(void *arg)
503         {
504                 CollectdServer *s = (CollectdServer *)arg;
505                 s->Mainloop();
506                 return NULL;
507         } /* worker_thread() */
508
509         static int c_grpc_config_listen(oconfig_item_t *ci)
510         {
511                 if ((ci->values_num != 2)
512                                 || (ci->values[0].type != OCONFIG_TYPE_STRING)
513                                 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
514                         ERROR("grpc: The `%s` config option needs exactly "
515                                         "two string argument (address and port).", ci->key);
516                         return -1;
517                 }
518
519                 auto listener = Listener();
520                 listener.addr = grpc::string(ci->values[0].value.string);
521                 listener.port = grpc::string(ci->values[1].value.string);
522                 listener.ssl = nullptr;
523
524                 auto ssl_opts = new(grpc::SslServerCredentialsOptions);
525                 grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {};
526                 bool use_ssl = false;
527
528                 for (int i = 0; i < ci->children_num; i++) {
529                         oconfig_item_t *child = ci->children + i;
530
531                         if (!strcasecmp("EnableSSL", child->key)) {
532                                 if (cf_util_get_boolean(child, &use_ssl)) {
533                                         ERROR("grpc: Option `%s` expects a boolean value",
534                                                         child->key);
535                                         return -1;
536                                 }
537                         }
538                         else if (!strcasecmp("SSLRootCerts", child->key)) {
539                                 char *certs = NULL;
540                                 if (cf_util_get_string(child, &certs)) {
541                                         ERROR("grpc: Option `%s` expects a string value",
542                                                         child->key);
543                                         return -1;
544                                 }
545                                 ssl_opts->pem_root_certs = read_file(certs);
546                         }
547                         else if (!strcasecmp("SSLServerKey", child->key)) {
548                                 char *key = NULL;
549                                 if (cf_util_get_string(child, &key)) {
550                                         ERROR("grpc: Option `%s` expects a string value",
551                                                         child->key);
552                                         return -1;
553                                 }
554                                 pkcp.private_key = read_file(key);
555                         }
556                         else if (!strcasecmp("SSLServerCert", child->key)) {
557                                 char *cert = NULL;
558                                 if (cf_util_get_string(child, &cert)) {
559                                         ERROR("grpc: Option `%s` expects a string value",
560                                                         child->key);
561                                         return -1;
562                                 }
563                                 pkcp.cert_chain = read_file(cert);
564                         }
565                         else {
566                                 WARNING("grpc: Option `%s` not allowed in <%s> block.",
567                                                 child->key, ci->key);
568                         }
569                 }
570
571                 ssl_opts->pem_key_cert_pairs.push_back(pkcp);
572                 if (use_ssl)
573                         listener.ssl = ssl_opts;
574                 else
575                         delete(ssl_opts);
576
577                 listeners.push_back(listener);
578                 return 0;
579         } /* c_grpc_config_listen() */
580
581         static int c_grpc_config(oconfig_item_t *ci)
582         {
583                 int i;
584
585                 for (i = 0; i < ci->children_num; i++) {
586                         oconfig_item_t *child = ci->children + i;
587
588                         if (!strcasecmp("Listen", child->key)) {
589                                 if (c_grpc_config_listen(child))
590                                         return -1;
591                         }
592                         else if (!strcasecmp("WorkerThreads", child->key)) {
593                                 int n;
594                                 if (cf_util_get_int(child, &n))
595                                         return -1;
596                                 workers_num = (size_t)n;
597                         }
598                         else {
599                                 WARNING("grpc: Option `%s` not allowed here.", child->key);
600                         }
601                 }
602
603                 return 0;
604         } /* c_grpc_config() */
605
606         static int c_grpc_init(void)
607         {
608                 server = new CollectdServer();
609                 size_t i;
610
611                 if (! server) {
612                         ERROR("grpc: Failed to create server");
613                         return -1;
614                 }
615
616                 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
617                 if (! workers) {
618                         delete server;
619                         server = nullptr;
620
621                         ERROR("grpc: Failed to allocate worker threads");
622                         return -1;
623                 }
624
625                 server->Start();
626                 for (i = 0; i < workers_num; i++) {
627                         plugin_thread_create(&workers[i], /* attr = */ NULL,
628                                         worker_thread, server);
629                 }
630                 INFO("grpc: Started %zu workers", workers_num);
631                 return 0;
632         } /* c_grpc_init() */
633
634         static int c_grpc_shutdown(void)
635         {
636                 size_t i;
637
638                 if (!server)
639                         return -1;
640
641                 server->Shutdown();
642
643                 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
644                 for (i = 0; i < workers_num; i++)
645                         pthread_join(workers[i], NULL);
646                 free(workers);
647                 workers = NULL;
648                 workers_num = 0;
649
650                 delete server;
651                 server = nullptr;
652
653                 return 0;
654         } /* c_grpc_shutdown() */
655
656         void module_register(void)
657         {
658                 plugin_register_complex_config("grpc", c_grpc_config);
659                 plugin_register_init("grpc", c_grpc_init);
660                 plugin_register_shutdown("grpc", c_grpc_shutdown);
661         } /* module_register() */
662 } /* extern "C" */
663
664 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */