2 * collectd - src/grpc.cc
3 * Copyright (C) 2015 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>
30 #include "collectd.grpc.pb.h"
38 #include "configfile.h"
41 #include "daemon/utils_cache.h"
48 static listener_t *listeners;
49 static size_t listeners_num;
52 using collectd::Collectd;
54 using collectd::DispatchValuesRequest;
55 using collectd::DispatchValuesReply;
56 using collectd::ListValuesRequest;
57 using collectd::ListValuesReply;
59 using google::protobuf::util::TimeUtil;
65 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
67 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
68 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
74 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
75 grpc::string("missing host name"));
76 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
80 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
81 grpc::string("missing plugin name"));
82 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
86 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
87 grpc::string("missing type name"));
88 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
90 s = msg.plugin_instance();
91 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
93 s = msg.type_instance();
94 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
96 value_t *values = NULL;
97 size_t values_len = 0;
98 auto status = grpc::Status::OK;
100 for (auto v : msg.value()) {
101 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
103 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
104 grpc::string("failed to allocate values array"));
109 val = values + values_len;
112 switch (v.value_case()) {
113 case collectd::types::Value::ValueCase::kCounter:
114 val->counter = counter_t(v.counter());
116 case collectd::types::Value::ValueCase::kGauge:
117 val->gauge = gauge_t(v.gauge());
119 case collectd::types::Value::ValueCase::kDerive:
120 val->derive = derive_t(v.derive());
122 case collectd::types::Value::ValueCase::kAbsolute:
123 val->absolute = absolute_t(v.absolute());
126 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
127 grpc::string("unknown value type"));
136 vl->values_len = values_len;
143 } /* unmarshal_value_list() */
146 * request call-backs and call objects
149 static grpc::Status Process(grpc::ServerContext *ctx,
150 DispatchValuesRequest request, DispatchValuesReply *reply)
152 value_list_t vl = VALUE_LIST_INIT;
153 auto status = unmarshal_value_list(request.values(), &vl);
157 if (plugin_dispatch_values(&vl))
158 status = grpc::Status(grpc::StatusCode::INTERNAL,
159 grpc::string("failed to enqueue values for writing"));
161 } /* Process(): DispatchValues */
163 static grpc::Status Process(grpc::ServerContext *ctx,
164 ListValuesRequest request, ListValuesReply *reply)
167 cdtime_t *times = NULL;
170 if (uc_get_names(&names, ×, &n))
171 return grpc::Status(grpc::StatusCode::INTERNAL,
172 grpc::string("failed to retrieve values"));
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));
184 return grpc::Status::OK;
185 } /* Process(): ListValues */
190 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
191 : service_(service), cq_(cq), status_(CREATE)
199 if (status_ == CREATE) {
203 else if (status_ == PROCESS) {
208 GPR_ASSERT(status_ == FINISH);
214 virtual void Create() = 0;
215 virtual void Process() = 0;
216 virtual void Finish() = 0;
218 Collectd::AsyncService *service_;
219 grpc::ServerCompletionQueue *cq_;
220 grpc::ServerContext ctx_;
223 enum CallStatus { CREATE, PROCESS, FINISH };
227 template<typename RequestT, typename ReplyT>
228 class RpcCall final : public Call
230 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
231 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
232 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
235 RpcCall(Collectd::AsyncService *service,
236 CreatorT creator, grpc::ServerCompletionQueue *cq)
237 : Call(service, cq), creator_(creator), responder_(&ctx_)
248 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
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);
269 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
270 }; /* class RpcCall */
273 * gRPC server implementation
276 class CollectdServer final
281 // TODO: make configurable
282 auto auth = grpc::InsecureServerCredentials();
284 grpc::ServerBuilder builder;
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());
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());
302 builder.RegisterService(&service_);
303 cq_ = builder.AddCompletionQueue();
304 server_ = builder.BuildAndStart();
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());
325 if (!cq_->Next(&req, &ok))
326 break; // Queue shut down.
328 ERROR("grpc: Failed to read from queue");
332 static_cast<Call *>(req)->Handle();
337 Collectd::AsyncService service_;
339 std::unique_ptr<grpc::Server> server_;
340 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
341 }; /* class CollectdServer */
343 static CollectdServer *server = nullptr;
346 * collectd plugin interface
350 static pthread_t *workers;
351 static size_t workers_num = 5;
353 static void *worker_thread(void *arg)
355 CollectdServer *s = (CollectdServer *)arg;
358 } /* worker_thread() */
360 static int c_grpc_config_listen(oconfig_item_t *ci)
362 listener_t *listener;
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);
373 listener = (listener_t *)realloc(listeners,
374 (listeners_num + 1) * sizeof(*listeners));
376 ERROR("grpc: Failed to allocate listeners");
379 listeners = listener;
380 listener = listeners + listeners_num;
383 listener->addr = strdup(ci->values[0].value.string);
384 listener->port = strdup(ci->values[1].value.string);
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);
393 } /* c_grpc_config_listen() */
395 static int c_grpc_config(oconfig_item_t *ci)
399 for (i = 0; i < ci->children_num; i++) {
400 oconfig_item_t *child = ci->children + i;
402 if (!strcasecmp("Listen", child->key)) {
403 if (c_grpc_config_listen(child))
406 else if (!strcasecmp("WorkerThreads", child->key)) {
408 if (cf_util_get_int(child, &n))
410 workers_num = (size_t)n;
413 WARNING("grpc: Option `%s` not allowed here.", child->key);
418 } /* c_grpc_config() */
420 static int c_grpc_init(void)
422 server = new CollectdServer();
426 ERROR("grpc: Failed to create server");
430 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
435 ERROR("grpc: Failed to allocate worker threads");
440 for (i = 0; i < workers_num; i++) {
441 plugin_thread_create(&workers[i], /* attr = */ NULL,
442 worker_thread, server);
444 INFO("grpc: Started %zu workers", workers_num);
446 } /* c_grpc_init() */
448 static int c_grpc_shutdown(void)
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);
468 } /* c_grpc_shutdown() */
470 void module_register(void)
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() */
478 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */