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"
46 static listener_t *listeners;
47 static size_t listeners_num;
50 using google::protobuf::util::TimeUtil;
56 static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl)
58 vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time()));
59 vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval()));
65 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
66 grpc::string("missing host name"));
67 sstrncpy(vl->host, s.c_str(), sizeof(vl->host));
71 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
72 grpc::string("missing plugin name"));
73 sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin));
77 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
78 grpc::string("missing type name"));
79 sstrncpy(vl->type, s.c_str(), sizeof(vl->type));
81 s = msg.plugin_instance();
83 sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance));
85 s = msg.type_instance();
87 sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance));
89 value_t *values = NULL;
90 size_t values_len = 0;
91 auto status = grpc::Status::OK;
93 for (auto v : msg.value()) {
94 value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values));
96 status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
97 grpc::string("failed to allocate values array"));
102 val = values + values_len;
105 switch (v.value_case()) {
106 case collectd::types::Value::ValueCase::kCounter:
107 val->counter = counter_t(v.counter());
109 case collectd::types::Value::ValueCase::kGauge:
110 val->gauge = gauge_t(v.gauge());
112 case collectd::types::Value::ValueCase::kDerive:
113 val->derive = derive_t(v.derive());
115 case collectd::types::Value::ValueCase::kAbsolute:
116 val->absolute = absolute_t(v.absolute());
119 status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
120 grpc::string("unkown value type"));
129 vl->values_len = values_len;
136 } /* unmarshal_value_list() */
139 * request call objects
145 Call(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
146 : service_(service), cq_(cq), status_(CREATE)
154 if (status_ == CREATE) {
158 else if (status_ == PROCESS) {
163 GPR_ASSERT(status_ == FINISH);
169 virtual void Create() = 0;
170 virtual void Process() = 0;
171 virtual void Finish() = 0;
173 collectd::Collectd::AsyncService *service_;
174 grpc::ServerCompletionQueue *cq_;
175 grpc::ServerContext ctx_;
178 enum CallStatus { CREATE, PROCESS, FINISH };
182 class DispatchValuesCall : public Call
185 DispatchValuesCall(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq)
186 : Call(service, cq), responder_(&ctx_)
189 } /* DispatchValuesCall() */
191 virtual ~DispatchValuesCall()
197 service_->RequestDispatchValues(&ctx_, &request_, &responder_, cq_, cq_, this);
202 // Add a new request object to the queue.
203 new DispatchValuesCall(service_, cq_);
205 value_list_t vl = VALUE_LIST_INIT;
206 auto status = unmarshal_value_list(request_.values(), &vl);
208 responder_.Finish(reply_, status, this);
212 if (plugin_dispatch_values(&vl))
213 status = grpc::Status(grpc::StatusCode::INTERNAL,
214 grpc::string("failed to enqueue values for writing"));
216 responder_.Finish(reply_, status, this);
224 collectd::DispatchValuesRequest request_;
225 collectd::DispatchValuesReply reply_;
227 grpc::ServerAsyncResponseWriter<collectd::DispatchValuesReply> responder_;
231 * gRPC server implementation
234 class CollectdServer final
239 // TODO: make configurable
240 auto auth = grpc::InsecureServerCredentials();
242 grpc::ServerBuilder builder;
244 if (!listeners_num) {
245 std::string default_addr("0.0.0.0:50051");
246 builder.AddListeningPort(default_addr, auth);
247 INFO("grpc: Listening on %s", default_addr.c_str());
251 for (i = 0; i < listeners_num; i++) {
252 auto l = listeners[i];
253 std::string addr(l.addr);
254 addr += std::string(":") + std::string(l.port);
255 builder.AddListeningPort(addr, auth);
256 INFO("grpc: Listening on %s", addr.c_str());
260 builder.RegisterAsyncService(&service_);
261 cq_ = builder.AddCompletionQueue();
262 server_ = builder.BuildAndStart();
273 // Register request types.
274 new DispatchValuesCall(&service_, cq_.get());
280 if (!cq_->Next(&req, &ok))
281 break; // Queue shut down.
283 ERROR("grpc: Failed to read from queue");
287 static_cast<Call *>(req)->Handle();
292 collectd::Collectd::AsyncService service_;
294 std::unique_ptr<grpc::Server> server_;
295 std::unique_ptr<grpc::ServerCompletionQueue> cq_;
296 }; /* class CollectdServer */
298 static CollectdServer *server = nullptr;
301 * collectd plugin interface
305 static pthread_t *workers;
306 static size_t workers_num = 5;
308 static void *worker_thread(void *arg)
310 CollectdServer *s = (CollectdServer *)arg;
313 } /* worker_thread() */
315 static int c_grpc_config_listen(oconfig_item_t *ci)
317 listener_t *listener;
320 if ((ci->values_num != 2)
321 || (ci->values[0].type != OCONFIG_TYPE_STRING)
322 || (ci->values[1].type != OCONFIG_TYPE_STRING)) {
323 ERROR("grpc: The `%s` config option needs exactly "
324 "two string argument (address and port).", ci->key);
328 listener = (listener_t *)realloc(listeners,
329 (listeners_num + 1) * sizeof(*listeners));
331 ERROR("grpc: Failed to allocate listeners");
334 listeners = listener;
335 listener = listeners + listeners_num;
338 listener->addr = strdup(ci->values[0].value.string);
339 listener->port = strdup(ci->values[1].value.string);
341 for (i = 0; i < ci->children_num; i++) {
342 oconfig_item_t *child = ci->children + i;
343 WARNING("grpc: Option `%s` not allowed in <%s> block.",
344 child->key, ci->key);
348 } /* c_grpc_config_listen() */
350 static int c_grpc_config(oconfig_item_t *ci)
354 for (i = 0; i < ci->children_num; i++) {
355 oconfig_item_t *child = ci->children + i;
357 if (!strcasecmp("Listen", child->key)) {
358 if (c_grpc_config_listen(child))
361 else if (!strcasecmp("WorkerThreads", child->key)) {
363 if (cf_util_get_int(child, &n))
365 workers_num = (size_t)n;
368 WARNING("grpc: Option `%s` not allowed here.", child->key);
373 } /* c_grpc_config() */
375 static int c_grpc_init(void)
377 server = new CollectdServer();
381 ERROR("grpc: Failed to create server");
385 workers = (pthread_t *)calloc(workers_num, sizeof(*workers));
390 ERROR("grpc: Failed to allocate worker threads");
395 for (i = 0; i < workers_num; i++) {
396 pthread_create(&workers[i], /* attr = */ NULL,
397 worker_thread, server);
399 INFO("grpc: Started %zu workers", workers_num);
401 } /* c_grpc_init() */
403 static int c_grpc_shutdown(void)
412 INFO("grpc: Waiting for %zu workers to terminate", workers_num);
413 for (i = 0; i < workers_num; i++)
414 pthread_join(workers[i], NULL);
423 } /* c_grpc_shutdown() */
425 void module_register(void)
427 plugin_register_complex_config("grpc", c_grpc_config);
428 plugin_register_init("grpc", c_grpc_init);
429 plugin_register_shutdown("grpc", c_grpc_shutdown);
430 } /* module_register() */
433 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */