X-Git-Url: https://git.octo.it/?a=blobdiff_plain;f=src%2Fgrpc.cc;h=0ae80bb898fa8d00ebd63e7714a7797c670f5c84;hb=87e53c90047eb1ff8818105762ff997a5cfea4ad;hp=aeb1c6d058a4fd65fbfef62ef2a0860c8aa720f6;hpb=ac69a17e48a7c8c6e499de74031d6d78ec586d23;p=collectd.git diff --git a/src/grpc.cc b/src/grpc.cc index aeb1c6d0..0ae80bb8 100644 --- a/src/grpc.cc +++ b/src/grpc.cc @@ -1,6 +1,7 @@ /** * collectd - src/grpc.cc * Copyright (C) 2015-2016 Sebastian Harl + * Copyright (C) 2016 Florian octo Forster * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -22,6 +23,7 @@ * * Authors: * Sebastian Harl + * Florian octo Forster **/ #include @@ -40,17 +42,15 @@ extern "C" { #include "collectd.h" #include "common.h" -#include "configfile.h" #include "plugin.h" #include "daemon/utils_cache.h" } using collectd::Collectd; -using collectd::Dispatch; -using collectd::DispatchValuesRequest; -using collectd::DispatchValuesResponse; +using collectd::PutValuesRequest; +using collectd::PutValuesResponse; using collectd::QueryValuesRequest; using collectd::QueryValuesResponse; @@ -259,94 +259,62 @@ static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, } /* unmarshal_value_list() */ /* - * request call-backs and call objects + * Collectd service */ -static grpc::Status DispatchValue(grpc::ServerContext *ctx, DispatchValuesRequest request, DispatchValuesResponse *reply) -{ - value_list_t vl = VALUE_LIST_INIT; - auto status = unmarshal_value_list(request.value_list(), &vl); - if (!status.ok()) - return status; - - if (plugin_dispatch_values(&vl)) - status = grpc::Status(grpc::StatusCode::INTERNAL, - grpc::string("failed to enqueue values for writing")); - - reply->Clear(); - return status; -} /* grpc::Status DispatchValue */ - -// CallData is the abstract base class for asynchronous calls. -class CallData { +class CollectdImpl : public collectd::Collectd::Service { public: - virtual ~CallData() {} - virtual void process(bool ok) = 0; - -protected: - CallData() {} + grpc::Status QueryValues(grpc::ServerContext *ctx, QueryValuesRequest const *req, grpc::ServerWriter *writer) override { + value_list_t match; + auto status = unmarshal_ident(req->identifier(), &match, false); + if (!status.ok()) { + return status; + } -private: - CallData(const CallData&) = delete; - CallData& operator=(const CallData&) = delete; -}; + std::queue value_lists; + status = this->queryValuesRead(&match, &value_lists); + if (status.ok()) { + status = this->queryValuesWrite(ctx, writer, &value_lists); + } -/* - * Collectd service - */ + while (!value_lists.empty()) { + auto vl = value_lists.front(); + value_lists.pop(); + sfree(vl.values); + } -// QueryValuesCallData holds the state and implements the logic for QueryValues calls. -class QueryValuesCallData : public CallData { -public: - QueryValuesCallData(Collectd::AsyncService* service, grpc::ServerCompletionQueue* cq) - : cq_(cq), service_(service), writer_(&context_) { - process(true); + return status; } - void process(bool ok) final { - if (status_ == Status::INIT) { - status_ = Status::READ; - service_->RequestQueryValues(&context_, &request_, &writer_, cq_, cq_, this); - } else if (status_ == Status::READ) { - auto err = queryValues(); - if (!err.ok()) { - writer_.Finish(err, this); - status_ = Status::DONE; - return; - } - respond(); - } else if (status_ == Status::WRITE) { - respond(); - } else if (status_ == Status::DONE) { - new QueryValuesCallData(service_, cq_); - delete this; - } else { - throw std::logic_error("Unhandled state enum."); + grpc::Status PutValues(grpc::ServerContext *ctx, + grpc::ServerReader *reader, + PutValuesResponse *res) override { + PutValuesRequest req; + + while (reader->Read(&req)) { + value_list_t vl = {0}; + auto status = unmarshal_value_list(req.value_list(), &vl); + if (!status.ok()) + return status; + + if (plugin_dispatch_values(&vl)) + return grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("failed to enqueue values for writing")); } + + res->Clear(); + return grpc::Status::OK; } private: - enum class Status { - INIT, - READ, - WRITE, - DONE, - }; - - grpc::Status queryValues (void) { + grpc::Status queryValuesRead(value_list_t const *match, std::queue *value_lists) { uc_iter_t *iter; - char *name = NULL; - - value_list_t matcher; - auto status = unmarshal_ident(request_.identifier(), &matcher, false); - if (!status.ok()) - return status; - if ((iter = uc_get_iterator()) == NULL) { return grpc::Status(grpc::StatusCode::INTERNAL, grpc::string("failed to query values: cannot create iterator")); } - status = grpc::Status::OK; + grpc::Status status = grpc::Status::OK; + char *name = NULL; while (uc_iterator_next(iter, &name) == 0) { value_list_t vl; if (parse_identifier_vl(name, &vl) != 0) { @@ -355,7 +323,7 @@ private: break; } - if (!ident_matches(&vl, &matcher)) + if (!ident_matches(&vl, match)) continue; if (uc_iterator_get_time(iter, &vl.time) < 0) { @@ -374,97 +342,36 @@ private: break; } - value_lists_.push(vl); - } + value_lists->push(vl); + } // while (uc_iterator_next(iter, &name) == 0) uc_iterator_destroy(iter); return status; } - void respond() { - if (value_lists_.empty()) { - writer_.Finish(grpc::Status::OK, this); - status_ = Status::DONE; - return; - } + grpc::Status queryValuesWrite(grpc::ServerContext *ctx, + grpc::ServerWriter *writer, + std::queue *value_lists) { + while (!value_lists->empty()) { + auto vl = value_lists->front(); + QueryValuesResponse res; + res.Clear(); + + auto status = marshal_value_list(&vl, res.mutable_value_list()); + if (!status.ok()) { + return status; + } - auto vl = value_lists_.front(); + if (!writer->Write(res)) { + return grpc::Status::CANCELLED; + } - response_.Clear(); - auto err = marshal_value_list(&vl, response_.mutable_value_list()); - if (!err.ok()) { - writer_.Finish(err, this); - status_ = Status::DONE; - return; + value_lists->pop(); + sfree(vl.values); } - value_lists_.pop(); - free(vl.values); - - writer_.Write(response_, this); - status_ = Status::WRITE; + return grpc::Status::OK; } - - Status status_ = Status::INIT; - grpc::ServerContext context_; - grpc::ServerCompletionQueue* cq_; - Collectd::AsyncService* service_; - QueryValuesRequest request_; - std::queue value_lists_; - QueryValuesResponse response_; - grpc::ServerAsyncWriter writer_; -}; - -/* - * Dispatch service - */ -// DispatchValuesCallData holds the state and implements the logic for DispatchValues calls. -class DispatchValuesCallData : public CallData { -public: - DispatchValuesCallData(Dispatch::AsyncService* service, grpc::ServerCompletionQueue* cq) - : cq_(cq), service_(service), reader_(&context_) { - process(true); - } - - void process(bool ok) final { - if (status == Status::INIT) { - service_->RequestDispatchValues(&context_, &reader_, cq_, cq_, this); - status = Status::CALL; - } else if (status == Status::CALL) { - reader_.Read(&request_, this); - status = Status::READ; - } else if (status == Status::READ && ok) { - (void) DispatchValue(&context_, request_, &response_); - - reader_.Read(&request_, this); - } else if (status == Status::READ) { - response_.Clear(); - - status = Status::DONE; - } else if (status == Status::DONE) { - new DispatchValuesCallData(service_, cq_); - delete this; - } else { - ERROR("grpc: DispatchValuesCallData: invalid state"); - } - } - -private: - enum class Status { - INIT, - CALL, - READ, - DONE, - }; - Status status = Status::INIT; - - grpc::ServerContext context_; - grpc::ServerCompletionQueue* cq_; - Dispatch::AsyncService* service_; - - DispatchValuesRequest request_; - DispatchValuesResponse response_; - grpc::ServerAsyncReader reader_; }; /* @@ -499,45 +406,58 @@ public: } } - cq_ = builder.AddCompletionQueue(); - builder.RegisterService(&collectd_service_); - builder.RegisterService(&dispatch_service_); server_ = builder.BuildAndStart(); - new QueryValuesCallData(&collectd_service_, cq_.get()); - new DispatchValuesCallData(&dispatch_service_, cq_.get()); } /* Start() */ void Shutdown() { server_->Shutdown(); - cq_->Shutdown(); } /* Shutdown() */ - void Mainloop() - { - while (true) { - void *tag = NULL; - bool ok = false; +private: + CollectdImpl collectd_service_; + + std::unique_ptr server_; +}; /* class CollectdServer */ + +class CollectdClient final +{ +public: + CollectdClient(std::shared_ptr channel) : stub_(Collectd::NewStub(channel)) { + } - // Block waiting to read the next event from the completion queue. - // The event is uniquely identified by its tag, which in this case - // is the memory address of a CallData instance. - if (!cq_->Next(&tag, &ok)) - break; // Queue shut down. + int PutValues(value_list_t const *vl) { + grpc::ClientContext ctx; - static_cast(tag)->process(ok); + PutValuesRequest req; + auto status = marshal_value_list(vl, req.mutable_value_list()); + if (!status.ok()) { + ERROR("grpc: Marshalling value_list_t failed."); + return -1; } - } /* Mainloop() */ -private: - Collectd::AsyncService collectd_service_; - Dispatch::AsyncService dispatch_service_; + PutValuesResponse res; + auto stream = stub_->PutValues(&ctx, &res); + if (!stream->Write(req)) { + NOTICE("grpc: Broken stream."); + /* intentionally not returning. */ + } - std::unique_ptr server_; - std::unique_ptr cq_; -}; /* class CollectdServer */ + stream->WritesDone(); + status = stream->Finish(); + if (!status.ok()) { + ERROR ("grpc: Error while closing stream."); + return -1; + } + + return 0; + } /* int PutValues */ + +private: + std::unique_ptr stub_; +}; static CollectdServer *server = nullptr; @@ -545,15 +465,16 @@ static CollectdServer *server = nullptr; * collectd plugin interface */ extern "C" { - static pthread_t *workers; - static size_t workers_num = 5; + static void c_grpc_destroy_write_callback (void *ptr) { + delete (CollectdClient *) ptr; + } - static void *worker_thread(void *arg) - { - CollectdServer *s = (CollectdServer *)arg; - s->Mainloop(); - return NULL; - } /* worker_thread() */ + static int c_grpc_write(__attribute__((unused)) data_set_t const *ds, + value_list_t const *vl, + user_data_t *ud) { + CollectdClient *c = (CollectdClient *) ud->data; + return c->PutValues(vl); + } static int c_grpc_config_listen(oconfig_item_t *ci) { @@ -584,7 +505,7 @@ extern "C" { return -1; } } - else if (!strcasecmp("SSLRootCerts", child->key)) { + else if (!strcasecmp("SSLCACertificateFile", child->key)) { char *certs = NULL; if (cf_util_get_string(child, &certs)) { ERROR("grpc: Option `%s` expects a string value", @@ -593,7 +514,7 @@ extern "C" { } ssl_opts->pem_root_certs = read_file(certs); } - else if (!strcasecmp("SSLServerKey", child->key)) { + else if (!strcasecmp("SSLCertificateKeyFile", child->key)) { char *key = NULL; if (cf_util_get_string(child, &key)) { ERROR("grpc: Option `%s` expects a string value", @@ -602,7 +523,7 @@ extern "C" { } pkcp.private_key = read_file(key); } - else if (!strcasecmp("SSLServerCert", child->key)) { + else if (!strcasecmp("SSLCertificateFile", child->key)) { char *cert = NULL; if (cf_util_get_string(child, &cert)) { ERROR("grpc: Option `%s` expects a string value", @@ -627,6 +548,78 @@ extern "C" { return 0; } /* c_grpc_config_listen() */ + static int c_grpc_config_server(oconfig_item_t *ci) + { + if ((ci->values_num != 2) + || (ci->values[0].type != OCONFIG_TYPE_STRING) + || (ci->values[1].type != OCONFIG_TYPE_STRING)) { + ERROR("grpc: The `%s` config option needs exactly " + "two string argument (address and port).", ci->key); + return -1; + } + + grpc::SslCredentialsOptions ssl_opts; + bool use_ssl = false; + + for (int i = 0; i < ci->children_num; i++) { + oconfig_item_t *child = ci->children + i; + + if (!strcasecmp("EnableSSL", child->key)) { + if (cf_util_get_boolean(child, &use_ssl)) { + return -1; + } + } + else if (!strcasecmp("SSLCACertificateFile", child->key)) { + char *certs = NULL; + if (cf_util_get_string(child, &certs)) { + return -1; + } + ssl_opts.pem_root_certs = read_file(certs); + } + else if (!strcasecmp("SSLCertificateKeyFile", child->key)) { + char *key = NULL; + if (cf_util_get_string(child, &key)) { + return -1; + } + ssl_opts.pem_private_key = read_file(key); + } + else if (!strcasecmp("SSLCertificateFile", child->key)) { + char *cert = NULL; + if (cf_util_get_string(child, &cert)) { + return -1; + } + ssl_opts.pem_cert_chain = read_file(cert); + } + else { + WARNING("grpc: Option `%s` not allowed in <%s> block.", + child->key, ci->key); + } + } + + auto node = grpc::string(ci->values[0].value.string); + auto service = grpc::string(ci->values[1].value.string); + auto addr = node + ":" + service; + + CollectdClient *client; + if (use_ssl) { + auto channel_creds = grpc::SslCredentials(ssl_opts); + auto channel = grpc::CreateChannel(addr, channel_creds); + client = new CollectdClient(channel); + } else { + auto channel = grpc::CreateChannel(addr, grpc::InsecureChannelCredentials()); + client = new CollectdClient(channel); + } + + auto callback_name = grpc::string("grpc/") + addr; + user_data_t ud = { + .data = client, + .free_func = c_grpc_destroy_write_callback, + }; + + plugin_register_write (callback_name.c_str(), c_grpc_write, &ud); + return 0; + } /* c_grpc_config_server() */ + static int c_grpc_config(oconfig_item_t *ci) { int i; @@ -638,12 +631,11 @@ extern "C" { if (c_grpc_config_listen(child)) return -1; } - else if (!strcasecmp("WorkerThreads", child->key)) { - int n; - if (cf_util_get_int(child, &n)) + else if (!strcasecmp("Server", child->key)) { + if (c_grpc_config_server(child)) return -1; - workers_num = (size_t)n; } + else { WARNING("grpc: Option `%s` not allowed here.", child->key); } @@ -655,47 +647,22 @@ extern "C" { static int c_grpc_init(void) { server = new CollectdServer(); - size_t i; - - if (! server) { + if (!server) { ERROR("grpc: Failed to create server"); return -1; } - workers = (pthread_t *)calloc(workers_num, sizeof(*workers)); - if (! workers) { - delete server; - server = nullptr; - - ERROR("grpc: Failed to allocate worker threads"); - return -1; - } - server->Start(); - for (i = 0; i < workers_num; i++) { - plugin_thread_create(&workers[i], /* attr = */ NULL, - worker_thread, server); - } - INFO("grpc: Started %zu workers", workers_num); return 0; } /* c_grpc_init() */ static int c_grpc_shutdown(void) { - size_t i; - if (!server) - return -1; + return 0; server->Shutdown(); - INFO("grpc: Waiting for %zu workers to terminate", workers_num); - for (i = 0; i < workers_num; i++) - pthread_join(workers[i], NULL); - free(workers); - workers = NULL; - workers_num = 0; - delete server; server = nullptr;