grpc plugin: Always populate *instance fields in a value-list.
[collectd.git] / src / grpc.cc
1 /**
2  * collectd - src/grpc.cc
3  * Copyright (C) 2015 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 "collectd.grpc.pb.h"
31
32 extern "C" {
33 #include <stdbool.h>
34 #include <pthread.h>
35
36 #include "collectd.h"
37 #include "common.h"
38 #include "configfile.h"
39 #include "plugin.h"
40
41 #include "daemon/utils_cache.h"
42
43         typedef struct {
44                 char *addr;
45                 char *port;
46         } listener_t;
47
48         static listener_t *listeners;
49         static size_t listeners_num;
50 }
51
52 using collectd::Collectd;
53
54 using collectd::DispatchValuesRequest;
55 using collectd::DispatchValuesReply;
56 using collectd::ListValuesRequest;
57 using collectd::ListValuesReply;
58
59 using google::protobuf::util::TimeUtil;
60
61 /*
62  * proto conversion
63  */
64
65 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
66 {
67         vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
68         vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
69
70         std::string s;
71
72         s = msg.host();
73         if (!s.length())
74                 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
75                                 grpc::string("missing host name"));
76         sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
77
78         s = msg.plugin();
79         if (!s.length())
80                 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
81                                 grpc::string("missing plugin name"));
82         sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
83
84         s = msg.type();
85         if (!s.length())
86                 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
87                                 grpc::string("missing type name"));
88         sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
89
90         s = msg.plugin_instance();
91         sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
92
93         s = msg.type_instance();
94         sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
95
96         value_t *values = NULL;
97         size_t values_len = 0;
98         auto status = grpc::Status::OK;
99
100         for (auto v : msg.value()) {
101                 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
102                 if (!val) {
103                         status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
104                                         grpc::string("failed to allocate values array"));
105                         break;
106                 }
107
108                 values = val;
109                 val = values + values_len;
110                 values_len++;
111
112                 switch (v.value_case()) {
113                 case collectd::types::Value::ValueCase::kCounter:
114                         val->counter = counter_t(v.counter());
115                         break;
116                 case collectd::types::Value::ValueCase::kGauge:
117                         val->gauge = gauge_t(v.gauge());
118                         break;
119                 case collectd::types::Value::ValueCase::kDerive:
120                         val->derive = derive_t(v.derive());
121                         break;
122                 case collectd::types::Value::ValueCase::kAbsolute:
123                         val->absolute = absolute_t(v.absolute());
124                         break;
125                 default:
126                         status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
127                                         grpc::string("unknown value type"));
128                         break;
129                 }
130
131                 if (!status.ok())
132                         break;
133         }
134         if (status.ok()) {
135                 vl->values = values;
136                 vl->values_len = values_len;
137         }
138         else if (values) {
139                 free(values);
140         }
141
142         return status;
143 } /* unmarshal_value_list() */
144
145 /*
146  * request call-backs and call objects
147  */
148
149 static grpc::Status Process(grpc::ServerContext *ctx,
150                 DispatchValuesRequest request, DispatchValuesReply *reply)
151 {
152         value_list_t vl = VALUE_LIST_INIT;
153         auto status = unmarshal_value_list(request.values(), &vl);
154         if (!status.ok())
155                 return status;
156
157         if (plugin_dispatch_values(&vl))
158                 status = grpc::Status(grpc::StatusCode::INTERNAL,
159                                 grpc::string("failed to enqueue values for writing"));
160         return status;
161 } /* Process(): DispatchValues */
162
163 static grpc::Status Process(grpc::ServerContext *ctx,
164                 ListValuesRequest request, ListValuesReply *reply)
165 {
166         char **names = NULL;
167         cdtime_t *times = NULL;
168         size_t i, n = 0;
169
170         if (uc_get_names(&names, &times, &n))
171                 return grpc::Status(grpc::StatusCode::INTERNAL,
172                                 grpc::string("failed to retrieve values"));
173
174         for (i = 0; i < n; i++) {
175                 auto v = reply->add_value();
176                 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(times[i]));
177                 v->set_name(names[i]);
178                 v->set_allocated_time(new google::protobuf::Timestamp(t));
179                 sfree(names[i]);
180         }
181         sfree(names);
182         sfree(times);
183
184         return grpc::Status::OK;
185 } /* Process(): ListValues */
186
187 class Call
188 {
189 public:
190         Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
191                 : service_(service), cq_(cq), status_(CREATE)
192         { }
193
194         virtual ~Call()
195         { }
196
197         void Handle()
198         {
199                 if (status_ == CREATE) {
200                         Create();
201                         status_ = PROCESS;
202                 }
203                 else if (status_ == PROCESS) {
204                         Process();
205                         status_ = FINISH;
206                 }
207                 else {
208                         GPR_ASSERT(status_ == FINISH);
209                         Finish();
210                 }
211         } /* Handle() */
212
213 protected:
214         virtual void Create() = 0;
215         virtual void Process() = 0;
216         virtual void Finish() = 0;
217
218         Collectd::AsyncService *service_;
219         grpc::ServerCompletionQueue *cq_;
220         grpc::ServerContext ctx_;
221
222 private:
223         enum CallStatus { CREATE, PROCESS, FINISH };
224         CallStatus status_;
225 }; /* class Call */
226
227 template<typename RequestT, typename ReplyT>
228 class RpcCall final : public Call
229 {
230         typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
231                         RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
232                         grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
233
234 public:
235         RpcCall(Collectd::AsyncService *service,
236                         CreatorT creator, grpc::ServerCompletionQueue *cq)
237                 : Call(service, cq), creator_(creator), responder_(&ctx_)
238         {
239                 Handle();
240         } /* RpcCall() */
241
242         virtual ~RpcCall()
243         { }
244
245 private:
246         void Create()
247         {
248                 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
249         } /* Create() */
250
251         void Process()
252         {
253                 // Add a new request object to the queue.
254                 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
255                 grpc::Status status = ::Process(&ctx_, request_, &reply_);
256                 responder_.Finish(reply_, status, this);
257         } /* Process() */
258
259         void Finish()
260         {
261                 delete this;
262         } /* Finish() */
263
264         CreatorT creator_;
265
266         RequestT request_;
267         ReplyT reply_;
268
269         grpc::ServerAsyncResponseWriter<ReplyT> responder_;
270 }; /* class RpcCall */
271
272 /*
273  * gRPC server implementation
274  */
275
276 class CollectdServer final
277 {
278 public:
279         void Start()
280         {
281                 // TODO: make configurable
282                 auto auth = grpc::InsecureServerCredentials();
283
284                 grpc::ServerBuilder builder;
285
286                 if (!listeners_num) {
287                         std::string default_addr("0.0.0.0:50051");
288                         builder.AddListeningPort(default_addr, auth);
289                         INFO("grpc: Listening on %s", default_addr.c_str());
290                 }
291                 else {
292                         size_t i;
293                         for (i = 0; i < listeners_num; i++) {
294                                 auto l = listeners[i];
295                                 std::string addr(l.addr);
296                                 addr += std::string(":") + std::string(l.port);
297                                 builder.AddListeningPort(addr, auth);
298                                 INFO("grpc: Listening on %s", addr.c_str());
299                         }
300                 }
301
302                 builder.RegisterService(&service_);
303                 cq_ = builder.AddCompletionQueue();
304                 server_ = builder.BuildAndStart();
305         } /* Start() */
306
307         void Shutdown()
308         {
309                 server_->Shutdown();
310                 cq_->Shutdown();
311         } /* Shutdown() */
312
313         void Mainloop()
314         {
315                 // Register request types.
316                 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
317                                 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
318                 new RpcCall<ListValuesRequest, ListValuesReply>(&service_,
319                                 &Collectd::AsyncService::RequestListValues, cq_.get());
320
321                 while (true) {
322                         void *req = NULL;
323                         bool ok = false;
324
325                         if (!cq_->Next(&req, &ok))
326                                 break; // Queue shut down.
327                         if (!ok) {
328                                 ERROR("grpc: Failed to read from queue");
329                                 break;
330                         }
331
332                         static_cast<Call *>(req)->Handle();
333                 }
334         } /* Mainloop() */
335
336 private:
337         Collectd::AsyncService service_;
338
339         std::unique_ptr<grpc::Server> server_;
340         std::unique_ptr<grpc::ServerCompletionQueue> cq_;
341 }; /* class CollectdServer */
342
343 static CollectdServer *server = nullptr;
344
345 /*
346  * collectd plugin interface
347  */
348
349 extern "C" {
350         static pthread_t *workers;
351         static size_t workers_num = 5;
352
353         static void *worker_thread(void *arg)
354         {
355                 CollectdServer *s = (CollectdServer *)arg;
356                 s->Mainloop();
357                 return NULL;
358         } /* worker_thread() */
359
360         static int c_grpc_config_listen(oconfig_item_t *ci)
361         {
362                 listener_t *listener;
363                 int i;
364
365                 if ((ci->values_num != 2)
366                                 || (ci->values[0].type != OCONFIG_TYPE_STRING)
367                                 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
368                         ERROR("grpc: The `%s` config option needs exactly "
369                                         "two string argument (address and port).", ci->key);
370                         return -1;
371                 }
372
373                 listener = (listener_t *)realloc(listeners,
374                                 (listeners_num + 1) * sizeof(*listeners));
375                 if (!listener) {
376                         ERROR("grpc: Failed to allocate listeners");
377                         return -1;
378                 }
379                 listeners = listener;
380                 listener = listeners + listeners_num;
381                 listeners_num++;
382
383                 listener->addr = strdup(ci->values[0].value.string);
384                 listener->port = strdup(ci->values[1].value.string);
385
386                 for (i = 0; i < ci->children_num; i++) {
387                         oconfig_item_t *child = ci->children + i;
388                         WARNING("grpc: Option `%s` not allowed in <%s> block.",
389                                         child->key, ci->key);
390                 }
391
392                 return 0;
393         } /* c_grpc_config_listen() */
394
395         static int c_grpc_config(oconfig_item_t *ci)
396         {
397                 int i;
398
399                 for (i = 0; i < ci->children_num; i++) {
400                         oconfig_item_t *child = ci->children + i;
401
402                         if (!strcasecmp("Listen", child->key)) {
403                                 if (c_grpc_config_listen(child))
404                                         return -1;
405                         }
406                         else if (!strcasecmp("WorkerThreads", child->key)) {
407                                 int n;
408                                 if (cf_util_get_int(child, &n))
409                                         return -1;
410                                 workers_num = (size_t)n;
411                         }
412                         else {
413                                 WARNING("grpc: Option `%s` not allowed here.", child->key);
414                         }
415                 }
416
417                 return 0;
418         } /* c_grpc_config() */
419
420         static int c_grpc_init(void)
421         {
422                 server = new CollectdServer();
423                 size_t i;
424
425                 if (! server) {
426                         ERROR("grpc: Failed to create server");
427                         return -1;
428                 }
429
430                 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
431                 if (! workers) {
432                         delete server;
433                         server = nullptr;
434
435                         ERROR("grpc: Failed to allocate worker threads");
436                         return -1;
437                 }
438
439                 server->Start();
440                 for (i = 0; i < workers_num; i++) {
441                         pthread_create(&workers[i], /* attr = */ NULL,
442                                         worker_thread, server);
443                 }
444                 INFO("grpc: Started %zu workers", workers_num);
445                 return 0;
446         } /* c_grpc_init() */
447
448         static int c_grpc_shutdown(void)
449         {
450                 size_t i;
451
452                 if (!server)
453                         return -1;
454
455                 server->Shutdown();
456
457                 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
458                 for (i = 0; i < workers_num; i++)
459                         pthread_join(workers[i], NULL);
460                 free(workers);
461                 workers = NULL;
462                 workers_num = 0;
463
464                 delete server;
465                 server = nullptr;
466
467                 return 0;
468         } /* c_grpc_shutdown() */
469
470         void module_register(void)
471         {
472                 plugin_register_complex_config("grpc", c_grpc_config);
473                 plugin_register_init("grpc", c_grpc_init);
474                 plugin_register_shutdown("grpc", c_grpc_shutdown);
475         } /* module_register() */
476 } /* extern "C" */
477
478 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */