2 * collectd - src/write_gcm.c
5 * Copyright (C) 2017 Florian Forster
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 * Florian Forster <octo at collectd.org>
26 #include "configfile.h"
28 #include "utils_format_gcm.h"
29 #include "utils_gce.h"
30 #include "utils_oauth.h"
32 #include <curl/curl.h>
39 #define GCM_API_URL "https://monitoring.googleapis.com/v3"
42 #ifndef MONITORING_SCOPE
43 #define MONITORING_SCOPE "https://www.googleapis.com/auth/monitoring"
46 struct wg_callback_s {
51 gcm_resource_t *resource;
55 gcm_output_t *formatter;
57 char curl_errbuf[CURL_ERROR_SIZE];
59 size_t timeseries_count;
60 cdtime_t send_buffer_init_time;
64 typedef struct wg_callback_s wg_callback_t;
70 typedef struct wg_memory_s wg_memory_t;
72 static size_t wg_write_memory_cb(void *contents, size_t size,
73 size_t nmemb, /* {{{ */
75 size_t realsize = size * nmemb;
76 wg_memory_t *mem = (wg_memory_t *)userp;
78 if (0x7FFFFFF0 < mem->size || 0x7FFFFFF0 - mem->size < realsize) {
79 ERROR("integer overflow");
83 mem->memory = (char *)realloc((void *)mem->memory, mem->size + realsize + 1);
84 if (mem->memory == NULL) {
86 ERROR("wg_write_memory_cb: not enough memory (realloc returned NULL)");
90 memcpy(&(mem->memory[mem->size]), contents, realsize);
91 mem->size += realsize;
92 mem->memory[mem->size] = 0;
94 } /* }}} size_t wg_write_memory_cb */
96 static char *wg_get_authorization_header(wg_callback_t *cb) { /* {{{ */
98 char access_token[256];
99 char authorization_header[256];
101 assert((cb->auth != NULL) || gce_check());
102 if (cb->auth != NULL)
103 status = oauth_access_token(cb->auth, access_token, sizeof(access_token));
105 status = gce_access_token(cb->email, access_token, sizeof(access_token));
107 ERROR("write_gcm plugin: Failed to get access token");
111 status = snprintf(authorization_header, sizeof(authorization_header),
112 "Authorization: Bearer %s", access_token);
113 if ((status < 1) || ((size_t)status >= sizeof(authorization_header)))
116 return strdup(authorization_header);
117 } /* }}} char *wg_get_authorization_header */
119 static int wg_call_metricdescriptor_create(wg_callback_t *cb,
120 char const *payload) {
122 char final_url[1024];
124 snprintf(final_url, sizeof(final_url), "%s/projects/%s/metricDescriptors",
125 cb->url, cb->project);
126 if ((status < 1) || ((size_t)status >= sizeof(final_url)))
129 char *authorization_header = wg_get_authorization_header(cb);
130 if (authorization_header == NULL)
133 struct curl_slist *headers = NULL;
134 headers = curl_slist_append(headers, "Content-Type: application/json");
135 headers = curl_slist_append(headers, authorization_header);
137 CURL *curl = curl_easy_init();
139 ERROR("write_gcm plugin: curl_easy_init failed.");
140 curl_slist_free_all(headers);
141 sfree(authorization_header);
145 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
146 curl_easy_setopt(cb->curl, CURLOPT_USERAGENT,
147 PACKAGE_NAME "/" PACKAGE_VERSION);
148 char curl_errbuf[CURL_ERROR_SIZE];
149 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errbuf);
150 curl_easy_setopt(curl, CURLOPT_URL, final_url);
151 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
152 curl_easy_setopt(curl, CURLOPT_POST, 1L);
153 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
156 .memory = NULL, .size = 0,
158 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wg_write_memory_cb);
159 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &res);
161 status = curl_easy_perform(curl);
162 if (status != CURLE_OK) {
163 ERROR("write_gcm plugin: curl_easy_perform failed with status %d: %s",
164 status, curl_errbuf);
166 curl_easy_cleanup(curl);
167 curl_slist_free_all(headers);
168 sfree(authorization_header);
173 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
174 if ((http_code < 200) || (http_code >= 300)) {
175 ERROR("write_gcm plugin: POST request to %s failed: HTTP error %ld",
176 final_url, http_code);
177 INFO("write_gcm plugin: Server replied: %s", res.memory);
179 curl_easy_cleanup(curl);
180 curl_slist_free_all(headers);
181 sfree(authorization_header);
186 curl_easy_cleanup(curl);
187 curl_slist_free_all(headers);
188 sfree(authorization_header);
190 } /* }}} int wg_call_metricdescriptor_create */
192 static void wg_reset_buffer(wg_callback_t *cb) /* {{{ */
194 cb->timeseries_count = 0;
195 cb->send_buffer_init_time = cdtime();
196 } /* }}} wg_reset_buffer */
198 static int wg_call_timeseries_write(wg_callback_t *cb,
199 char const *payload) /* {{{ */
201 char final_url[1024];
202 int status = snprintf(final_url, sizeof(final_url),
203 "%s/projects/%s/timeSeries", cb->url, cb->project);
204 if ((status < 1) || ((size_t)status >= sizeof(final_url)))
207 char *authorization_header = wg_get_authorization_header(cb);
208 if (authorization_header == NULL)
211 struct curl_slist *headers = NULL;
212 headers = curl_slist_append(headers, authorization_header);
213 headers = curl_slist_append(headers, "Content-Type: application/json");
215 curl_easy_setopt(cb->curl, CURLOPT_URL, final_url);
216 curl_easy_setopt(cb->curl, CURLOPT_HTTPHEADER, headers);
217 curl_easy_setopt(cb->curl, CURLOPT_POST, 1L);
218 curl_easy_setopt(cb->curl, CURLOPT_POSTFIELDS, payload);
221 .memory = NULL, .size = 0,
223 curl_easy_setopt(cb->curl, CURLOPT_WRITEFUNCTION, wg_write_memory_cb);
224 curl_easy_setopt(cb->curl, CURLOPT_WRITEDATA, &res);
226 status = curl_easy_perform(cb->curl);
227 if (status != CURLE_OK) {
228 ERROR("write_gcm plugin: curl_easy_perform failed with status %d: %s",
229 status, cb->curl_errbuf);
231 curl_slist_free_all(headers);
232 sfree(authorization_header);
237 curl_easy_getinfo(cb->curl, CURLINFO_RESPONSE_CODE, &http_code);
238 if ((http_code < 200) || (http_code >= 300)) {
239 ERROR("write_gcm plugin: POST request to %s failed: HTTP error %ld",
240 final_url, http_code);
241 INFO("write_gcm plugin: Server replied: %s", res.memory);
243 curl_slist_free_all(headers);
244 sfree(authorization_header);
249 curl_slist_free_all(headers);
250 sfree(authorization_header);
252 } /* }}} wg_call_timeseries_write */
254 static int wg_callback_init(wg_callback_t *cb) /* {{{ */
256 if (cb->curl != NULL)
259 cb->formatter = gcm_output_create(cb->resource);
260 if (cb->formatter == NULL) {
261 ERROR("write_gcm plugin: gcm_output_create failed.");
265 cb->curl = curl_easy_init();
266 if (cb->curl == NULL) {
267 ERROR("write_gcm plugin: curl_easy_init failed.");
271 curl_easy_setopt(cb->curl, CURLOPT_NOSIGNAL, 1L);
272 curl_easy_setopt(cb->curl, CURLOPT_USERAGENT,
273 PACKAGE_NAME "/" PACKAGE_VERSION);
274 curl_easy_setopt(cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
278 } /* }}} int wg_callback_init */
280 static int wg_flush_nolock(cdtime_t timeout, wg_callback_t *cb) /* {{{ */
282 if (cb->timeseries_count == 0) {
283 cb->send_buffer_init_time = cdtime();
287 /* timeout == 0 => flush unconditionally */
289 cdtime_t now = cdtime();
291 if ((cb->send_buffer_init_time + timeout) > now)
295 char *payload = gcm_output_reset(cb->formatter);
296 int status = wg_call_timeseries_write(cb, payload);
298 ERROR("write_gcm plugin: Sending buffer failed with status %d.", status);
303 } /* }}} wg_flush_nolock */
305 static int wg_flush(cdtime_t timeout, /* {{{ */
306 const char *identifier __attribute__((unused)),
307 user_data_t *user_data) {
311 if (user_data == NULL)
314 cb = user_data->data;
316 pthread_mutex_lock(&cb->lock);
318 if (cb->curl == NULL) {
319 status = wg_callback_init(cb);
321 ERROR("write_gcm plugin: wg_callback_init failed.");
322 pthread_mutex_unlock(&cb->lock);
327 status = wg_flush_nolock(timeout, cb);
328 pthread_mutex_unlock(&cb->lock);
331 } /* }}} int wg_flush */
333 static void wg_callback_free(void *data) /* {{{ */
335 wg_callback_t *cb = data;
339 gcm_output_destroy(cb->formatter);
340 cb->formatter = NULL;
346 oauth_destroy(cb->auth);
348 curl_easy_cleanup(cb->curl);
352 } /* }}} void wg_callback_free */
354 static int wg_metric_descriptors_create(wg_callback_t *cb, const data_set_t *ds,
355 const value_list_t *vl) {
357 for (size_t i = 0; i < ds->ds_num; i++) {
361 gcm_format_metric_descriptor(buffer, sizeof(buffer), ds, vl, i);
363 ERROR("write_gcm plugin: gcm_format_metric_descriptor failed with status "
369 status = wg_call_metricdescriptor_create(cb, buffer);
371 ERROR("write_gcm plugin: wg_call_metricdescriptor_create failed with "
378 return gcm_output_register_metric(cb->formatter, ds, vl);
379 } /* }}} int wg_metric_descriptors_create */
381 static int wg_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
382 user_data_t *user_data) {
383 wg_callback_t *cb = user_data->data;
387 pthread_mutex_lock(&cb->lock);
389 if (cb->curl == NULL) {
390 int status = wg_callback_init(cb);
392 ERROR("write_gcm plugin: wg_callback_init failed.");
393 pthread_mutex_unlock(&cb->lock);
400 status = gcm_output_add(cb->formatter, ds, vl);
401 if (status == 0) { /* success */
403 } else if (status == ENOBUFS) { /* success, flush */
404 wg_flush_nolock(0, cb);
407 } else if (status == EEXIST) {
408 /* metric already in the buffer; flush and retry */
409 wg_flush_nolock(0, cb);
411 } else if (status == ENOENT) {
412 /* new metric, create metric descriptor first */
413 status = wg_metric_descriptors_create(cb, ds, vl);
424 cb->timeseries_count++;
427 pthread_mutex_unlock(&cb->lock);
429 } /* }}} int wg_write */
431 static void wg_check_scope(char const *email) /* {{{ */
433 char *scope = gce_scope(email);
435 WARNING("write_gcm plugin: Unable to determine scope of this instance.");
439 if (strstr(scope, MONITORING_SCOPE) == NULL) {
442 /* Strip trailing newline characers for printing. */
443 scope_len = strlen(scope);
444 while ((scope_len > 0) && (iscntrl((int)scope[scope_len - 1])))
445 scope[--scope_len] = 0;
447 WARNING("write_gcm plugin: The determined scope of this instance "
448 "(\"%s\") does not contain the monitoring scope (\"%s\"). You need "
449 "to add this scope to the list of scopes passed to gcutil with "
450 "--service_account_scopes when creating the instance. "
451 "Alternatively, to use this plugin on an instance which does not "
452 "have this scope, use a Service Account.",
453 scope, MONITORING_SCOPE);
457 } /* }}} void wg_check_scope */
459 static int wg_config_resource(oconfig_item_t *ci, wg_callback_t *cb) /* {{{ */
461 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
462 ERROR("write_gcm plugin: The \"%s\" option requires exactly one string "
467 char *resource_type = ci->values[0].value.string;
469 if (cb->resource != NULL) {
470 gcm_resource_destroy(cb->resource);
473 cb->resource = gcm_resource_create(resource_type);
474 if (cb->resource == NULL) {
475 ERROR("write_gcm plugin: gcm_resource_create(\"%s\") failed.",
480 for (int i = 0; i < ci->children_num; i++) {
481 oconfig_item_t *child = ci->children + i;
483 if ((child->values_num != 1) ||
484 (child->values[0].type != OCONFIG_TYPE_STRING)) {
485 ERROR("write_gcm plugin: Resource labels must have exactly one string "
486 "value. Ignoring label \"%s\".",
491 gcm_resource_add_label(cb->resource, child->key,
492 child->values[0].value.string);
496 } /* }}} int wg_config_resource */
498 static int wg_config(oconfig_item_t *ci) /* {{{ */
504 wg_callback_t *cb = calloc(1, sizeof(*cb));
506 ERROR("write_gcm plugin: calloc failed.");
509 cb->url = strdup(GCM_API_URL);
510 pthread_mutex_init(&cb->lock, /* attr = */ NULL);
512 char *credential_file = NULL;
514 for (int i = 0; i < ci->children_num; i++) {
515 oconfig_item_t *child = ci->children + i;
516 if (strcasecmp("Project", child->key) == 0)
517 cf_util_get_string(child, &cb->project);
518 else if (strcasecmp("Email", child->key) == 0)
519 cf_util_get_string(child, &cb->email);
520 else if (strcasecmp("Url", child->key) == 0)
521 cf_util_get_string(child, &cb->url);
522 else if (strcasecmp("CredentialFile", child->key) == 0)
523 cf_util_get_string(child, &credential_file);
524 else if (strcasecmp("Resource", child->key) == 0)
525 wg_config_resource(child, cb);
527 ERROR("write_gcm plugin: Invalid configuration option: %s.", child->key);
528 wg_callback_free(cb);
533 /* Set up authentication */
534 /* Option 1: Credentials file given => use service account */
535 if (credential_file != NULL) {
537 oauth_create_google_file(credential_file, MONITORING_SCOPE);
538 if (cfg.oauth == NULL) {
539 ERROR("write_gcm plugin: oauth_create_google_file failed");
540 wg_callback_free(cb);
543 cb->auth = cfg.oauth;
545 if (cb->project == NULL) {
546 cb->project = cfg.project_id;
547 INFO("write_gcm plugin: Automatically detected project ID: \"%s\"",
550 sfree(cfg.project_id);
553 /* Option 2: Look for credentials in well-known places */
554 if (cb->auth == NULL) {
555 oauth_google_t cfg = oauth_create_google_default(MONITORING_SCOPE);
556 cb->auth = cfg.oauth;
558 if (cb->project == NULL) {
559 cb->project = cfg.project_id;
560 INFO("write_gcm plugin: Automatically detected project ID: \"%s\"",
563 sfree(cfg.project_id);
567 if ((cb->auth != NULL) && (cb->email != NULL)) {
568 NOTICE("write_gcm plugin: A service account email was configured but is "
569 "not used for authentication because %s used instead.",
570 (credential_file != NULL) ? "a credential file was"
571 : "application default credentials were");
574 /* Option 3: Running on GCE => use metadata service */
575 if ((cb->auth == NULL) && gce_check()) {
576 wg_check_scope(cb->email);
577 } else if (cb->auth == NULL) {
578 ERROR("write_gcm plugin: Unable to determine credentials. Please either "
579 "specify the \"Credentials\" option or set up Application Default "
581 wg_callback_free(cb);
585 if ((cb->project == NULL) && gce_check()) {
586 cb->project = gce_project_id();
588 if (cb->project == NULL) {
589 ERROR("write_gcm plugin: Unable to determine the project number. "
590 "Please specify the \"Project\" option manually.");
591 wg_callback_free(cb);
595 if ((cb->resource == NULL) && gce_check()) {
596 /* TODO(octo): add error handling */
597 cb->resource = gcm_resource_create("gce_instance");
598 gcm_resource_add_label(cb->resource, "project_id", gce_project_id());
599 gcm_resource_add_label(cb->resource, "instance_id", gce_instance_id());
600 gcm_resource_add_label(cb->resource, "zone", gce_zone());
602 if (cb->resource == NULL) {
603 /* TODO(octo): add error handling */
604 cb->resource = gcm_resource_create("global");
605 gcm_resource_add_label(cb->resource, "project_id", cb->project);
608 DEBUG("write_gcm plugin: Registering write callback with URL %s", cb->url);
609 assert((cb->auth != NULL) || gce_check());
611 user_data_t user_data = {
614 plugin_register_flush("write_gcm", wg_flush, &user_data);
616 user_data.free_func = wg_callback_free;
617 plugin_register_write("write_gcm", wg_write, &user_data);
620 } /* }}} int wg_config */
622 static int wg_init(void) {
624 /* Call this while collectd is still single-threaded to avoid
625 * initialization issues in libgcrypt. */
626 curl_global_init(CURL_GLOBAL_SSL);
629 } /* }}} int wg_init */
631 void module_register(void) /* {{{ */
633 plugin_register_complex_config("write_gcm", wg_config);
634 plugin_register_init("write_gcm", wg_init);
635 } /* }}} void module_register */
637 /* vim: set sw=2 sts=2 et fdm=marker : */