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_ident(const collectd::types::Identifier &msg, value_list_t *vl)
71 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
72 grpc::string("missing host name"));
73 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
77 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
78 grpc::string("missing plugin name"));
79 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
83 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
84 grpc::string("missing type name"));
85 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
87 s = msg.plugin_instance();
88 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
90 s = msg.type_instance();
91 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
93 return grpc::Status::OK;
94 } /* unmarshal_ident() */
96 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
98 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
99 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
101 auto status = unmarshal_ident(msg.identifier(), vl);
105 value_t *values = NULL;
106 size_t values_len = 0;
107 status = grpc::Status::OK;
109 for (auto v : msg.value()) {
110 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
112 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
113 grpc::string("failed to allocate values array"));
118 val = values + values_len;
121 switch (v.value_case()) {
122 case collectd::types::Value::ValueCase::kCounter:
123 val->counter = counter_t(v.counter());
125 case collectd::types::Value::ValueCase::kGauge:
126 val->gauge = gauge_t(v.gauge());
128 case collectd::types::Value::ValueCase::kDerive:
129 val->derive = derive_t(v.derive());
131 case collectd::types::Value::ValueCase::kAbsolute:
132 val->absolute = absolute_t(v.absolute());
135 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
136 grpc::string("unknown value type"));
145 vl->values_len = values_len;
152 } /* unmarshal_value_list() */
155 * request call-backs and call objects
158 static grpc::Status Process(grpc::ServerContext *ctx,
159 DispatchValuesRequest request, DispatchValuesReply *reply)
161 value_list_t vl = VALUE_LIST_INIT;
162 auto status = unmarshal_value_list(request.values(), &vl);
166 if (plugin_dispatch_values(&vl))
167 status = grpc::Status(grpc::StatusCode::INTERNAL,
168 grpc::string("failed to enqueue values for writing"));
170 } /* Process(): DispatchValues */
172 static grpc::Status Process(grpc::ServerContext *ctx,
173 ListValuesRequest request, ListValuesReply *reply)
176 cdtime_t *times = NULL;
179 if (uc_get_names(&names, ×, &n))
180 return grpc::Status(grpc::StatusCode::INTERNAL,
181 grpc::string("failed to retrieve values"));
183 for (i = 0; i < n; i++) {
184 auto v = reply->add_value();
185 auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(times[i]));
186 v->set_name(names[i]);
187 v->set_allocated_time(new google::protobuf::Timestamp(t));
193 return grpc::Status::OK;
194 } /* Process(): ListValues */
199 Call(Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
200 : service_(service), cq_(cq), status_(CREATE)
208 if (status_ == CREATE) {
212 else if (status_ == PROCESS) {
217 GPR_ASSERT(status_ == FINISH);
223 virtual void Create() = 0;
224 virtual void Process() = 0;
225 virtual void Finish() = 0;
227 Collectd::AsyncService *service_;
228 grpc::ServerCompletionQueue *cq_;
229 grpc::ServerContext ctx_;
232 enum CallStatus { CREATE, PROCESS, FINISH };
236 template<typename RequestT, typename ReplyT>
237 class RpcCall final : public Call
239 typedef void (Collectd::AsyncService::*CreatorT)(grpc::ServerContext *,
240 RequestT *, grpc::ServerAsyncResponseWriter<ReplyT> *,
241 grpc::CompletionQueue *, grpc::ServerCompletionQueue *, void *);
244 RpcCall(Collectd::AsyncService *service,
245 CreatorT creator, grpc::ServerCompletionQueue *cq)
246 : Call(service, cq), creator_(creator), responder_(&ctx_)
257 (service_->*creator_)(&ctx_, &request_, &responder_, cq_, cq_, this);
262 // Add a new request object to the queue.
263 new RpcCall<RequestT, ReplyT>(service_, creator_, cq_);
264 grpc::Status status = ::Process(&ctx_, request_, &reply_);
265 responder_.Finish(reply_, status, this);
278 grpc::ServerAsyncResponseWriter<ReplyT> responder_;
279 }; /* class RpcCall */
282 * gRPC server implementation
285 class CollectdServer final
290 // TODO: make configurable
291 auto auth = grpc::InsecureServerCredentials();
293 grpc::ServerBuilder builder;
295 if (!listeners_num) {
296 std::string default_addr("0.0.0.0:50051");
297 builder.AddListeningPort(default_addr, auth);
298 INFO("grpc: Listening on %s", default_addr.c_str());
302 for (i = 0; i < listeners_num; i++) {
303 auto l = listeners[i];
304 std::string addr(l.addr);
305 addr += std::string(":") + std::string(l.port);
306 builder.AddListeningPort(addr, auth);
307 INFO("grpc: Listening on %s", addr.c_str());
311 builder.RegisterService(&service_);
312 cq_ = builder.AddCompletionQueue();
313 server_ = builder.BuildAndStart();
324 // Register request types.
325 new RpcCall<DispatchValuesRequest, DispatchValuesReply>(&service_,
326 &Collectd::AsyncService::RequestDispatchValues, cq_.get());
327 new RpcCall<ListValuesRequest, ListValuesReply>(&service_,
328 &Collectd::AsyncService::RequestListValues, cq_.get());
334 if (!cq_->Next(&req, &ok))
335 break; // Queue shut down.
337 ERROR("grpc: Failed to read from queue");
341 static_cast<Call *>(req)->Handle();
346 Collectd::AsyncService service_;
348 std::unique_ptr<grpc::Server> server_;
349 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
350 }; /* class CollectdServer */
352 static CollectdServer *server = nullptr;
355 * collectd plugin interface
359 static pthread_t *workers;
360 static size_t workers_num = 5;
362 static void *worker_thread(void *arg)
364 CollectdServer *s = (CollectdServer *)arg;
367 } /* worker_thread() */
369 static int c_grpc_config_listen(oconfig_item_t *ci)
371 listener_t *listener;
374 if ((ci->values_num != 2)
375 || (ci->values[0].type != OCONFIG_TYPE_STRING)
376 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
377 ERROR("grpc: The `%s` config option needs exactly "
378 "two string argument (address and port).", ci->key);
382 listener = (listener_t *)realloc(listeners,
383 (listeners_num + 1) * sizeof(*listeners));
385 ERROR("grpc: Failed to allocate listeners");
388 listeners = listener;
389 listener = listeners + listeners_num;
392 listener->addr = strdup(ci->values[0].value.string);
393 listener->port = strdup(ci->values[1].value.string);
395 for (i = 0; i < ci->children_num; i++) {
396 oconfig_item_t *child = ci->children + i;
397 WARNING("grpc: Option `%s` not allowed in <%s> block.",
398 child->key, ci->key);
402 } /* c_grpc_config_listen() */
404 static int c_grpc_config(oconfig_item_t *ci)
408 for (i = 0; i < ci->children_num; i++) {
409 oconfig_item_t *child = ci->children + i;
411 if (!strcasecmp("Listen", child->key)) {
412 if (c_grpc_config_listen(child))
415 else if (!strcasecmp("WorkerThreads", child->key)) {
417 if (cf_util_get_int(child, &n))
419 workers_num = (size_t)n;
422 WARNING("grpc: Option `%s` not allowed here.", child->key);
427 } /* c_grpc_config() */
429 static int c_grpc_init(void)
431 server = new CollectdServer();
435 ERROR("grpc: Failed to create server");
439 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
444 ERROR("grpc: Failed to allocate worker threads");
449 for (i = 0; i < workers_num; i++) {
450 plugin_thread_create(&workers[i], /* attr = */ NULL,
451 worker_thread, server);
453 INFO("grpc: Started %zu workers", workers_num);
455 } /* c_grpc_init() */
457 static int c_grpc_shutdown(void)
466 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
467 for (i = 0; i < workers_num; i++)
468 pthread_join(workers[i], NULL);
477 } /* c_grpc_shutdown() */
479 void module_register(void)
481 plugin_register_complex_config("grpc", c_grpc_config);
482 plugin_register_init("grpc", c_grpc_init);
483 plugin_register_shutdown("grpc", c_grpc_shutdown);
484 } /* module_register() */
487 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */