X-Git-Url: https://git.verplant.org/?a=blobdiff_plain;f=src%2Fgrpc.cc;h=ca3314ecf10cf743828d076c79b4e2217968fc91;hb=d26dd5c1db5c3310c9e69b2b910c6547469c99ce;hp=9523fc2513dd2cf6804a2fdec8ab2029bbeb04c8;hpb=1faf439320a1a875cbbd44179aec6641d0b7854b;p=collectd.git diff --git a/src/grpc.cc b/src/grpc.cc index 9523fc25..ca3314ec 100644 --- a/src/grpc.cc +++ b/src/grpc.cc @@ -1,6 +1,6 @@ /** * collectd - src/grpc.cc - * Copyright (C) 2015 Sebastian Harl + * Copyright (C) 2015-2016 Sebastian Harl * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -27,70 +27,192 @@ #include #include +#include +#include +#include + #include "collectd.grpc.pb.h" extern "C" { +#include #include -#include #include "collectd.h" #include "common.h" #include "configfile.h" #include "plugin.h" - typedef struct { - char *addr; - char *port; - } listener_t; - - static listener_t *listeners; - static size_t listeners_num; +#include "daemon/utils_cache.h" } +using collectd::Collectd; +using collectd::Dispatch; + +using collectd::DispatchValuesRequest; +using collectd::DispatchValuesReply; +using collectd::QueryValuesRequest; +using collectd::QueryValuesReply; + using google::protobuf::util::TimeUtil; /* - * proto conversion + * private types */ -static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl) +struct Listener { + grpc::string addr; + grpc::string port; + + grpc::SslServerCredentialsOptions *ssl; +}; +static std::vector listeners; +static grpc::string default_addr("0.0.0.0:50051"); + +/* + * helper functions + */ + +static bool ident_matches(const value_list_t *vl, const value_list_t *matcher) { - vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time())); - vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval())); + if (fnmatch(matcher->host, vl->host, 0)) + return false; + + if (fnmatch(matcher->plugin, vl->plugin, 0)) + return false; + if (fnmatch(matcher->plugin_instance, vl->plugin_instance, 0)) + return false; + + if (fnmatch(matcher->type, vl->type, 0)) + return false; + if (fnmatch(matcher->type_instance, vl->type_instance, 0)) + return false; + return true; +} /* ident_matches */ + +static grpc::string read_file(const char *filename) +{ + std::ifstream f; + grpc::string s, content; + + f.open(filename); + if (!f.is_open()) { + ERROR("grpc: Failed to open '%s'", filename); + return ""; + } + + while (std::getline(f, s)) { + content += s; + content.push_back('\n'); + } + f.close(); + return content; +} /* read_file */ + +/* + * proto conversion + */ + +static void marshal_ident(const value_list_t *vl, collectd::types::Identifier *msg) +{ + msg->set_host(vl->host); + msg->set_plugin(vl->plugin); + if (vl->plugin_instance[0] != '\0') + msg->set_plugin_instance(vl->plugin_instance); + msg->set_type(vl->type); + if (vl->type_instance[0] != '\0') + msg->set_type_instance(vl->type_instance); +} /* marshal_ident */ + +static grpc::Status unmarshal_ident(const collectd::types::Identifier &msg, value_list_t *vl, + bool require_fields) +{ std::string s; s = msg.host(); - if (!s.length()) + if (!s.length() && require_fields) return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, grpc::string("missing host name")); sstrncpy(vl->host, s.c_str(), sizeof(vl->host)); s = msg.plugin(); - if (!s.length()) + if (!s.length() && require_fields) return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, grpc::string("missing plugin name")); sstrncpy(vl->plugin, s.c_str(), sizeof(vl->plugin)); s = msg.type(); - if (!s.length()) + if (!s.length() && require_fields) return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, grpc::string("missing type name")); sstrncpy(vl->type, s.c_str(), sizeof(vl->type)); s = msg.plugin_instance(); - if (s.length()) - sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance)); + sstrncpy(vl->plugin_instance, s.c_str(), sizeof(vl->plugin_instance)); s = msg.type_instance(); - if (s.length()) - sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance)); + sstrncpy(vl->type_instance, s.c_str(), sizeof(vl->type_instance)); + + return grpc::Status::OK; +} /* unmarshal_ident() */ + +static grpc::Status marshal_value_list(const value_list_t *vl, collectd::types::ValueList *msg) +{ + auto id = msg->mutable_identifier(); + marshal_ident(vl, id); + + auto ds = plugin_get_ds(vl->type); + if ((ds == NULL) || (ds->ds_num != vl->values_len)) { + return grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("failed to retrieve data-set for values")); + } + + auto t = TimeUtil::NanosecondsToTimestamp(CDTIME_T_TO_NS(vl->time)); + auto d = TimeUtil::NanosecondsToDuration(CDTIME_T_TO_NS(vl->interval)); + msg->set_allocated_time(new google::protobuf::Timestamp(t)); + msg->set_allocated_interval(new google::protobuf::Duration(d)); + + for (size_t i = 0; i < vl->values_len; ++i) { + auto v = msg->add_values(); + switch (ds->ds[i].type) { + case DS_TYPE_COUNTER: + v->set_counter(vl->values[i].counter); + break; + case DS_TYPE_GAUGE: + v->set_gauge(vl->values[i].gauge); + break; + case DS_TYPE_DERIVE: + v->set_derive(vl->values[i].derive); + break; + case DS_TYPE_ABSOLUTE: + v->set_absolute(vl->values[i].absolute); + break; + default: + return grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("unknown value type")); + } + + auto name = msg->add_ds_names(); + name->assign(ds->ds[i].name); + } + + return grpc::Status::OK; +} /* marshal_value_list */ + +static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, value_list_t *vl) +{ + vl->time = NS_TO_CDTIME_T(TimeUtil::TimestampToNanoseconds(msg.time())); + vl->interval = NS_TO_CDTIME_T(TimeUtil::DurationToNanoseconds(msg.interval())); + + auto status = unmarshal_ident(msg.identifier(), vl, true); + if (!status.ok()) + return status; value_t *values = NULL; size_t values_len = 0; - auto status = grpc::Status::OK; - for (auto v : msg.value()) { + status = grpc::Status::OK; + for (auto v : msg.values()) { value_t *val = (value_t *)realloc(values, (values_len + 1) * sizeof(*values)); if (!val) { status = grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED, @@ -117,7 +239,7 @@ static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, break; default: status = grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, - grpc::string("unkown value type")); + grpc::string("unknown value type")); break; } @@ -136,130 +258,231 @@ static grpc::Status unmarshal_value_list(const collectd::types::ValueList &msg, } /* unmarshal_value_list() */ /* - * request call objects + * request call-backs and call objects */ +static grpc::Status DispatchValue(grpc::ServerContext *ctx, DispatchValuesRequest request, DispatchValuesReply *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")); -class Call + reply->Clear(); + return status; +} /* grpc::Status DispatchValue */ + +static grpc::Status QueryValues(grpc::ServerContext *ctx, QueryValuesRequest req, QueryValuesReply *res) { -public: - Call(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq) - : service_(service), cq_(cq), status_(CREATE) - { } + uc_iter_t *iter; + char *name = NULL; - virtual ~Call() - { } + value_list_t matcher; + auto status = unmarshal_ident(req.identifier(), &matcher, false); + if (!status.ok()) + return status; - void Handle() - { - if (status_ == CREATE) { - Create(); - status_ = PROCESS; + 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; + while (uc_iterator_next(iter, &name) == 0) { + value_list_t vl; + if (parse_identifier_vl(name, &vl) != 0) { + status = grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("failed to parse identifier")); + break; + } + + if (!ident_matches(&vl, &matcher)) + continue; + + if (uc_iterator_get_time(iter, &vl.time) < 0) { + status = grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("failed to retrieve value timestamp")); + break; } - else if (status_ == PROCESS) { - Process(); - status_ = FINISH; + if (uc_iterator_get_interval(iter, &vl.interval) < 0) { + status = grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("failed to retrieve value interval")); + break; } - else { - GPR_ASSERT(status_ == FINISH); - Finish(); + if (uc_iterator_get_values(iter, &vl.values, &vl.values_len) < 0) { + status = grpc::Status(grpc::StatusCode::INTERNAL, + grpc::string("failed to retrieve values")); + break; } - } /* Handle() */ -protected: - virtual void Create() = 0; - virtual void Process() = 0; - virtual void Finish() = 0; + auto pb_vl = res->add_value_lists(); + status = marshal_value_list(&vl, pb_vl); + free(vl.values); + if (!status.ok()) + break; + } - collectd::Collectd::AsyncService *service_; - grpc::ServerCompletionQueue *cq_; - grpc::ServerContext ctx_; + uc_iterator_destroy(iter); -private: - enum CallStatus { CREATE, PROCESS, FINISH }; - CallStatus status_; -}; /* class Call */ + return status; +} /* grpc::Status QueryValues */ -class DispatchValuesCall : public Call -{ +// CallData is the abstract base class for asynchronous calls. +class CallData { public: - DispatchValuesCall(collectd::Collectd::AsyncService *service, grpc::ServerCompletionQueue *cq) - : Call(service, cq), responder_(&ctx_) - { - Handle(); - } /* DispatchValuesCall() */ + virtual ~CallData() {} + virtual void process(bool ok) = 0; - virtual ~DispatchValuesCall() - { } +protected: + CallData() {} private: - void Create() - { - service_->RequestDispatchValues(&ctx_, &request_, &responder_, cq_, cq_, this); - } /* Create() */ + CallData(const CallData&) = delete; + CallData& operator=(const CallData&) = delete; +}; - void Process() - { - // Add a new request object to the queue. - new DispatchValuesCall(service_, cq_); - - value_list_t vl = VALUE_LIST_INIT; - auto status = unmarshal_value_list(request_.values(), &vl); - if (!status.ok()) { - responder_.Finish(reply_, status, this); - return; - } +/* + * Collectd service + */ +// 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_) { + // As part of the initialization, we *request* that the system start + // processing QueryValues requests. In this request, "this" acts as + // the tag uniquely identifying the request (so that different + // QueryValuesCallData instances can serve different requests + // concurrently), in this case the memory address of this + // QueryValuesCallData instance. + service->RequestQueryValues(&context_, &request_, &writer_, cq_, cq_, this); + } - if (plugin_dispatch_values(&vl)) - status = grpc::Status(grpc::StatusCode::INTERNAL, - grpc::string("failed to enqueue values for writing")); + void process(bool ok) final { + if (done_) { + delete this; + } else { + // Spawn a new QueryValuesCallData instance to serve new clients + // while we process the one for this QueryValuesCallData. The + // instance will deallocate itself as part of its FINISH state. + new QueryValuesCallData(service_, cq_); + + auto status = QueryValues(&context_, request_, &response_); + if (!status.ok()) { + writer_.FinishWithError(status, this); + } else { + writer_.Finish(response_, grpc::Status::OK, this); + } - responder_.Finish(reply_, status, this); - } /* Process() */ + done_ = true; + } + } - void Finish() - { - delete this; - } /* Finish() */ +private: + bool done_ = false; + grpc::ServerContext context_; + grpc::ServerCompletionQueue* cq_; + Collectd::AsyncService* service_; + QueryValuesRequest request_; + QueryValuesReply response_; + grpc::ServerAsyncResponseWriter writer_; +}; - collectd::DispatchValuesRequest request_; - collectd::DispatchValuesReply reply_; +/* + * 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"); + } + } - grpc::ServerAsyncResponseWriter responder_; +private: + enum class Status { + INIT, + CALL, + READ, + DONE, + }; + Status status = Status::INIT; + + grpc::ServerContext context_; + grpc::ServerCompletionQueue* cq_; + Dispatch::AsyncService* service_; + + DispatchValuesRequest request_; + DispatchValuesReply response_; + grpc::ServerAsyncReader reader_; }; /* * gRPC server implementation */ - class CollectdServer final { public: void Start() { - // TODO: make configurable auto auth = grpc::InsecureServerCredentials(); grpc::ServerBuilder builder; - if (!listeners_num) { - std::string default_addr("0.0.0.0:50051"); + if (listeners.empty()) { builder.AddListeningPort(default_addr, auth); INFO("grpc: Listening on %s", default_addr.c_str()); } else { - size_t i; - for (i = 0; i < listeners_num; i++) { - auto l = listeners[i]; - std::string addr(l.addr); - addr += std::string(":") + std::string(l.port); - builder.AddListeningPort(addr, auth); - INFO("grpc: Listening on %s", addr.c_str()); + for (auto l : listeners) { + grpc::string addr = l.addr + ":" + l.port; + + auto use_ssl = grpc::string(""); + auto a = auth; + if (l.ssl != nullptr) { + use_ssl = grpc::string(" (SSL enabled)"); + a = grpc::SslServerCredentials(*l.ssl); + } + + builder.AddListeningPort(addr, a); + INFO("grpc: Listening on %s%s", addr.c_str(), use_ssl.c_str()); } } - builder.RegisterAsyncService(&service_); 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() @@ -270,26 +493,23 @@ public: void Mainloop() { - // Register request types. - new DispatchValuesCall(&service_, cq_.get()); - while (true) { - void *req = NULL; + void *tag = NULL; bool ok = false; - if (!cq_->Next(&req, &ok)) + // 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. - if (!ok) { - ERROR("grpc: Failed to read from queue"); - break; - } - static_cast(req)->Handle(); + static_cast(tag)->process(ok); } } /* Mainloop() */ private: - collectd::Collectd::AsyncService service_; + Collectd::AsyncService collectd_service_; + Dispatch::AsyncService dispatch_service_; std::unique_ptr server_; std::unique_ptr cq_; @@ -300,7 +520,6 @@ static CollectdServer *server = nullptr; /* * collectd plugin interface */ - extern "C" { static pthread_t *workers; static size_t workers_num = 5; @@ -314,9 +533,6 @@ extern "C" { static int c_grpc_config_listen(oconfig_item_t *ci) { - listener_t *listener; - int i; - if ((ci->values_num != 2) || (ci->values[0].type != OCONFIG_TYPE_STRING) || (ci->values[1].type != OCONFIG_TYPE_STRING)) { @@ -325,25 +541,65 @@ extern "C" { return -1; } - listener = (listener_t *)realloc(listeners, - (listeners_num + 1) * sizeof(*listeners)); - if (!listener) { - ERROR("grpc: Failed to allocate listeners"); - return -1; - } - listeners = listener; - listener = listeners + listeners_num; - listeners_num++; + auto listener = Listener(); + listener.addr = grpc::string(ci->values[0].value.string); + listener.port = grpc::string(ci->values[1].value.string); + listener.ssl = nullptr; - listener->addr = strdup(ci->values[0].value.string); - listener->port = strdup(ci->values[1].value.string); + auto ssl_opts = new(grpc::SslServerCredentialsOptions); + grpc::SslServerCredentialsOptions::PemKeyCertPair pkcp = {}; + bool use_ssl = false; - for (i = 0; i < ci->children_num; i++) { + for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; - WARNING("grpc: Option `%s` not allowed in <%s> block.", - child->key, ci->key); + + if (!strcasecmp("EnableSSL", child->key)) { + if (cf_util_get_boolean(child, &use_ssl)) { + ERROR("grpc: Option `%s` expects a boolean value", + child->key); + return -1; + } + } + else if (!strcasecmp("SSLRootCerts", child->key)) { + char *certs = NULL; + if (cf_util_get_string(child, &certs)) { + ERROR("grpc: Option `%s` expects a string value", + child->key); + return -1; + } + ssl_opts->pem_root_certs = read_file(certs); + } + else if (!strcasecmp("SSLServerKey", child->key)) { + char *key = NULL; + if (cf_util_get_string(child, &key)) { + ERROR("grpc: Option `%s` expects a string value", + child->key); + return -1; + } + pkcp.private_key = read_file(key); + } + else if (!strcasecmp("SSLServerCert", child->key)) { + char *cert = NULL; + if (cf_util_get_string(child, &cert)) { + ERROR("grpc: Option `%s` expects a string value", + child->key); + return -1; + } + pkcp.cert_chain = read_file(cert); + } + else { + WARNING("grpc: Option `%s` not allowed in <%s> block.", + child->key, ci->key); + } } + ssl_opts->pem_key_cert_pairs.push_back(pkcp); + if (use_ssl) + listener.ssl = ssl_opts; + else + delete(ssl_opts); + + listeners.push_back(listener); return 0; } /* c_grpc_config_listen() */ @@ -393,7 +649,7 @@ extern "C" { server->Start(); for (i = 0; i < workers_num; i++) { - pthread_create(&workers[i], /* attr = */ NULL, + plugin_thread_create(&workers[i], /* attr = */ NULL, worker_thread, server); } INFO("grpc: Started %zu workers", workers_num);