2 * collectd - src/write_stackdriver.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_stackdriver.h"
29 #include "utils_gce.h"
30 #include "utils_oauth.h"
32 #include <curl/curl.h>
34 #include <yajl/yajl_tree.h>
40 #define GCM_API_URL "https://monitoring.googleapis.com/v3"
43 #ifndef MONITORING_SCOPE
44 #define MONITORING_SCOPE "https://www.googleapis.com/auth/monitoring"
47 struct wg_callback_s {
52 sd_resource_t *resource;
56 sd_output_t *formatter;
58 char curl_errbuf[CURL_ERROR_SIZE];
60 size_t timeseries_count;
61 cdtime_t send_buffer_init_time;
65 typedef struct wg_callback_s wg_callback_t;
71 typedef struct wg_memory_s wg_memory_t;
73 static size_t wg_write_memory_cb(void *contents, size_t size,
74 size_t nmemb, /* {{{ */
76 size_t realsize = size * nmemb;
77 wg_memory_t *mem = (wg_memory_t *)userp;
79 if (0x7FFFFFF0 < mem->size || 0x7FFFFFF0 - mem->size < realsize) {
80 ERROR("integer overflow");
84 mem->memory = (char *)realloc((void *)mem->memory, mem->size + realsize + 1);
85 if (mem->memory == NULL) {
87 ERROR("wg_write_memory_cb: not enough memory (realloc returned NULL)");
91 memcpy(&(mem->memory[mem->size]), contents, realsize);
92 mem->size += realsize;
93 mem->memory[mem->size] = 0;
95 } /* }}} size_t wg_write_memory_cb */
97 static char *wg_get_authorization_header(wg_callback_t *cb) { /* {{{ */
99 char access_token[256];
100 char authorization_header[256];
102 assert((cb->auth != NULL) || gce_check());
103 if (cb->auth != NULL)
104 status = oauth_access_token(cb->auth, access_token, sizeof(access_token));
106 status = gce_access_token(cb->email, access_token, sizeof(access_token));
108 ERROR("write_stackdriver plugin: Failed to get access token");
112 status = snprintf(authorization_header, sizeof(authorization_header),
113 "Authorization: Bearer %s", access_token);
114 if ((status < 1) || ((size_t)status >= sizeof(authorization_header)))
117 return strdup(authorization_header);
118 } /* }}} char *wg_get_authorization_header */
125 static api_error_t *parse_api_error(char const *body) {
127 yajl_val root = yajl_tree_parse(body, errbuf, sizeof(errbuf));
129 ERROR("write_stackdriver plugin: yajl_tree_parse failed: %s", errbuf);
133 api_error_t *err = calloc(1, sizeof(*err));
135 ERROR("write_stackdriver plugin: calloc failed");
136 yajl_tree_free(root);
140 yajl_val code = yajl_tree_get(root, (char const *[]){"error", "code", NULL},
142 if (YAJL_IS_INTEGER(code)) {
143 err->code = YAJL_GET_INTEGER(code);
146 yajl_val message = yajl_tree_get(
147 root, (char const *[]){"error", "message", NULL}, yajl_t_string);
148 if (YAJL_IS_STRING(message)) {
149 char const *m = YAJL_GET_STRING(message);
151 err->message = strdup(m);
158 static char *api_error_string(api_error_t *err, char *buffer,
159 size_t buffer_size) {
161 strncpy(buffer, "Unknown error (API error is NULL)", buffer_size);
162 } else if (err->message == NULL) {
163 snprintf(buffer, buffer_size, "API error %d", err->code);
165 snprintf(buffer, buffer_size, "API error %d: %s", err->code, err->message);
170 #define API_ERROR_STRING(err) api_error_string(err, (char[1024]){""}, 1024)
172 // do_post does a HTTP POST request, assuming a JSON payload and using OAuth
173 // authentication. Returns -1 on error and the HTTP status code otherwise.
174 // ret_content, if not NULL, will contain the server's response.
175 // If ret_content is provided and the server responds with a 4xx or 5xx error,
176 // an appropriate message will be logged.
177 static int do_post(wg_callback_t *cb, char const *url, void const *payload,
178 wg_memory_t *ret_content) {
179 if (cb->curl == NULL) {
180 cb->curl = curl_easy_init();
181 if (cb->curl == NULL) {
182 ERROR("write_stackdriver plugin: curl_easy_init() failed");
186 curl_easy_setopt(cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
187 curl_easy_setopt(cb->curl, CURLOPT_NOSIGNAL, 1L);
190 curl_easy_setopt(cb->curl, CURLOPT_POST, 1L);
191 curl_easy_setopt(cb->curl, CURLOPT_URL, url);
193 long timeout_ms = 2 * CDTIME_T_TO_MS(plugin_get_interval());
194 if (timeout_ms < 10000) {
197 curl_easy_setopt(cb->curl, CURLOPT_TIMEOUT_MS, timeout_ms);
200 char *auth_header = wg_get_authorization_header(cb);
201 if (auth_header == NULL) {
202 ERROR("write_stackdriver plugin: getting access token failed with");
206 struct curl_slist *headers =
207 curl_slist_append(NULL, "Content-Type: application/json");
208 headers = curl_slist_append(headers, auth_header);
209 curl_easy_setopt(cb->curl, CURLOPT_HTTPHEADER, headers);
211 curl_easy_setopt(cb->curl, CURLOPT_POSTFIELDS, payload);
213 curl_easy_setopt(cb->curl, CURLOPT_WRITEFUNCTION,
214 ret_content ? wg_write_memory_cb : NULL);
215 curl_easy_setopt(cb->curl, CURLOPT_WRITEDATA, ret_content);
217 int status = curl_easy_perform(cb->curl);
219 /* clean up that has to happen in any case */
220 curl_slist_free_all(headers);
222 curl_easy_setopt(cb->curl, CURLOPT_HTTPHEADER, NULL);
223 curl_easy_setopt(cb->curl, CURLOPT_WRITEFUNCTION, NULL);
224 curl_easy_setopt(cb->curl, CURLOPT_WRITEDATA, NULL);
226 if (status != CURLE_OK) {
227 ERROR("write_stackdriver plugin: POST %s failed: %s", url, cb->curl_errbuf);
228 if (ret_content != NULL) {
229 sfree(ret_content->memory);
230 ret_content->size = 0;
236 curl_easy_getinfo(cb->curl, CURLINFO_RESPONSE_CODE, &http_code);
238 if (ret_content != NULL) {
239 if ((http_code >= 400) && (http_code < 500)) {
240 ERROR("write_stackdriver plugin: POST %s: %s", url,
241 API_ERROR_STRING(parse_api_error(ret_content->memory)));
242 } else if (http_code >= 500) {
243 WARNING("write_stackdriver plugin: POST %s: %s", url,
244 ret_content->memory);
248 return (int)http_code;
251 static int wg_call_metricdescriptor_create(wg_callback_t *cb,
252 char const *payload) {
254 snprintf(url, sizeof(url), "%s/projects/%s/metricDescriptors", cb->url,
256 wg_memory_t response = {0};
258 int status = do_post(cb, url, payload, &response);
260 ERROR("write_stackdriver plugin: POST %s failed", url);
263 sfree(response.memory);
266 ERROR("write_stackdriver plugin: POST %s: unexpected response code: got "
272 } /* int wg_call_metricdescriptor_create */
274 static int wg_call_timeseries_write(wg_callback_t *cb, char const *payload) {
276 snprintf(url, sizeof(url), "%s/projects/%s/timeSeries", cb->url, cb->project);
277 wg_memory_t response = {0};
279 int status = do_post(cb, url, payload, &response);
281 ERROR("write_stackdriver plugin: POST %s failed", url);
284 sfree(response.memory);
287 ERROR("write_stackdriver plugin: POST %s: unexpected response code: got "
293 } /* int wg_call_timeseries_write */
295 static void wg_reset_buffer(wg_callback_t *cb) /* {{{ */
297 cb->timeseries_count = 0;
298 cb->send_buffer_init_time = cdtime();
299 } /* }}} wg_reset_buffer */
301 static int wg_callback_init(wg_callback_t *cb) /* {{{ */
303 if (cb->curl != NULL)
306 cb->formatter = sd_output_create(cb->resource);
307 if (cb->formatter == NULL) {
308 ERROR("write_stackdriver plugin: sd_output_create failed.");
312 cb->curl = curl_easy_init();
313 if (cb->curl == NULL) {
314 ERROR("write_stackdriver plugin: curl_easy_init failed.");
318 curl_easy_setopt(cb->curl, CURLOPT_NOSIGNAL, 1L);
319 curl_easy_setopt(cb->curl, CURLOPT_USERAGENT,
320 PACKAGE_NAME "/" PACKAGE_VERSION);
321 curl_easy_setopt(cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
325 } /* }}} int wg_callback_init */
327 static int wg_flush_nolock(cdtime_t timeout, wg_callback_t *cb) /* {{{ */
329 if (cb->timeseries_count == 0) {
330 cb->send_buffer_init_time = cdtime();
334 /* timeout == 0 => flush unconditionally */
336 cdtime_t now = cdtime();
338 if ((cb->send_buffer_init_time + timeout) > now)
342 char *payload = sd_output_reset(cb->formatter);
343 int status = wg_call_timeseries_write(cb, payload);
346 } /* }}} wg_flush_nolock */
348 static int wg_flush(cdtime_t timeout, /* {{{ */
349 const char *identifier __attribute__((unused)),
350 user_data_t *user_data) {
354 if (user_data == NULL)
357 cb = user_data->data;
359 pthread_mutex_lock(&cb->lock);
361 if (cb->curl == NULL) {
362 status = wg_callback_init(cb);
364 ERROR("write_stackdriver plugin: wg_callback_init failed.");
365 pthread_mutex_unlock(&cb->lock);
370 status = wg_flush_nolock(timeout, cb);
371 pthread_mutex_unlock(&cb->lock);
374 } /* }}} int wg_flush */
376 static void wg_callback_free(void *data) /* {{{ */
378 wg_callback_t *cb = data;
382 sd_output_destroy(cb->formatter);
383 cb->formatter = NULL;
389 oauth_destroy(cb->auth);
391 curl_easy_cleanup(cb->curl);
395 } /* }}} void wg_callback_free */
397 static int wg_metric_descriptors_create(wg_callback_t *cb, const data_set_t *ds,
398 const value_list_t *vl) {
400 for (size_t i = 0; i < ds->ds_num; i++) {
403 int status = sd_format_metric_descriptor(buffer, sizeof(buffer), ds, vl, i);
405 ERROR("write_stackdriver plugin: sd_format_metric_descriptor failed "
412 status = wg_call_metricdescriptor_create(cb, buffer);
414 ERROR("write_stackdriver plugin: wg_call_metricdescriptor_create failed "
422 return sd_output_register_metric(cb->formatter, ds, vl);
423 } /* }}} int wg_metric_descriptors_create */
425 static int wg_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
426 user_data_t *user_data) {
427 wg_callback_t *cb = user_data->data;
431 pthread_mutex_lock(&cb->lock);
433 if (cb->curl == NULL) {
434 int status = wg_callback_init(cb);
436 ERROR("write_stackdriver plugin: wg_callback_init failed.");
437 pthread_mutex_unlock(&cb->lock);
444 status = sd_output_add(cb->formatter, ds, vl);
445 if (status == 0) { /* success */
447 } else if (status == ENOBUFS) { /* success, flush */
448 wg_flush_nolock(0, cb);
451 } else if (status == EEXIST) {
452 /* metric already in the buffer; flush and retry */
453 wg_flush_nolock(0, cb);
455 } else if (status == ENOENT) {
456 /* new metric, create metric descriptor first */
457 status = wg_metric_descriptors_create(cb, ds, vl);
468 cb->timeseries_count++;
471 pthread_mutex_unlock(&cb->lock);
473 } /* }}} int wg_write */
475 static void wg_check_scope(char const *email) /* {{{ */
477 char *scope = gce_scope(email);
479 WARNING("write_stackdriver plugin: Unable to determine scope of this "
484 if (strstr(scope, MONITORING_SCOPE) == NULL) {
487 /* Strip trailing newline characers for printing. */
488 scope_len = strlen(scope);
489 while ((scope_len > 0) && (iscntrl((int)scope[scope_len - 1])))
490 scope[--scope_len] = 0;
492 WARNING("write_stackdriver plugin: The determined scope of this instance "
493 "(\"%s\") does not contain the monitoring scope (\"%s\"). You need "
494 "to add this scope to the list of scopes passed to gcutil with "
495 "--service_account_scopes when creating the instance. "
496 "Alternatively, to use this plugin on an instance which does not "
497 "have this scope, use a Service Account.",
498 scope, MONITORING_SCOPE);
502 } /* }}} void wg_check_scope */
504 static int wg_config_resource(oconfig_item_t *ci, wg_callback_t *cb) /* {{{ */
506 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
507 ERROR("write_stackdriver plugin: The \"%s\" option requires exactly one "
513 char *resource_type = ci->values[0].value.string;
515 if (cb->resource != NULL) {
516 sd_resource_destroy(cb->resource);
519 cb->resource = sd_resource_create(resource_type);
520 if (cb->resource == NULL) {
521 ERROR("write_stackdriver plugin: sd_resource_create(\"%s\") failed.",
526 for (int i = 0; i < ci->children_num; i++) {
527 oconfig_item_t *child = ci->children + i;
529 if (strcasecmp("Label", child->key) == 0) {
530 if ((child->values_num != 2) ||
531 (child->values[0].type != OCONFIG_TYPE_STRING) ||
532 (child->values[1].type != OCONFIG_TYPE_STRING)) {
533 ERROR("write_stackdriver plugin: The \"Label\" option needs exactly "
534 "two string arguments.");
538 sd_resource_add_label(cb->resource, child->values[0].value.string,
539 child->values[1].value.string);
544 } /* }}} int wg_config_resource */
546 static int wg_config(oconfig_item_t *ci) /* {{{ */
552 wg_callback_t *cb = calloc(1, sizeof(*cb));
554 ERROR("write_stackdriver plugin: calloc failed.");
557 cb->url = strdup(GCM_API_URL);
558 pthread_mutex_init(&cb->lock, /* attr = */ NULL);
560 char *credential_file = NULL;
562 for (int i = 0; i < ci->children_num; i++) {
563 oconfig_item_t *child = ci->children + i;
564 if (strcasecmp("Project", child->key) == 0)
565 cf_util_get_string(child, &cb->project);
566 else if (strcasecmp("Email", child->key) == 0)
567 cf_util_get_string(child, &cb->email);
568 else if (strcasecmp("Url", child->key) == 0)
569 cf_util_get_string(child, &cb->url);
570 else if (strcasecmp("CredentialFile", child->key) == 0)
571 cf_util_get_string(child, &credential_file);
572 else if (strcasecmp("Resource", child->key) == 0)
573 wg_config_resource(child, cb);
575 ERROR("write_stackdriver plugin: Invalid configuration option: %s.",
577 wg_callback_free(cb);
582 /* Set up authentication */
583 /* Option 1: Credentials file given => use service account */
584 if (credential_file != NULL) {
586 oauth_create_google_file(credential_file, MONITORING_SCOPE);
587 if (cfg.oauth == NULL) {
588 ERROR("write_stackdriver plugin: oauth_create_google_file failed");
589 wg_callback_free(cb);
592 cb->auth = cfg.oauth;
594 if (cb->project == NULL) {
595 cb->project = cfg.project_id;
596 INFO("write_stackdriver plugin: Automatically detected project ID: "
600 sfree(cfg.project_id);
603 /* Option 2: Look for credentials in well-known places */
604 if (cb->auth == NULL) {
605 oauth_google_t cfg = oauth_create_google_default(MONITORING_SCOPE);
606 cb->auth = cfg.oauth;
608 if (cb->project == NULL) {
609 cb->project = cfg.project_id;
610 INFO("write_stackdriver plugin: Automatically detected project ID: "
614 sfree(cfg.project_id);
618 if ((cb->auth != NULL) && (cb->email != NULL)) {
619 NOTICE("write_stackdriver plugin: A service account email was configured "
621 "not used for authentication because %s used instead.",
622 (credential_file != NULL) ? "a credential file was"
623 : "application default credentials were");
626 /* Option 3: Running on GCE => use metadata service */
627 if ((cb->auth == NULL) && gce_check()) {
628 wg_check_scope(cb->email);
629 } else if (cb->auth == NULL) {
630 ERROR("write_stackdriver plugin: Unable to determine credentials. Please "
632 "specify the \"Credentials\" option or set up Application Default "
634 wg_callback_free(cb);
638 if ((cb->project == NULL) && gce_check()) {
639 cb->project = gce_project_id();
641 if (cb->project == NULL) {
642 ERROR("write_stackdriver plugin: Unable to determine the project number. "
643 "Please specify the \"Project\" option manually.");
644 wg_callback_free(cb);
648 if ((cb->resource == NULL) && gce_check()) {
649 /* TODO(octo): add error handling */
650 cb->resource = sd_resource_create("gce_instance");
651 sd_resource_add_label(cb->resource, "project_id", gce_project_id());
652 sd_resource_add_label(cb->resource, "instance_id", gce_instance_id());
653 sd_resource_add_label(cb->resource, "zone", gce_zone());
655 if (cb->resource == NULL) {
656 /* TODO(octo): add error handling */
657 cb->resource = sd_resource_create("global");
658 sd_resource_add_label(cb->resource, "project_id", cb->project);
661 DEBUG("write_stackdriver plugin: Registering write callback with URL %s",
663 assert((cb->auth != NULL) || gce_check());
665 user_data_t user_data = {
668 plugin_register_flush("write_stackdriver", wg_flush, &user_data);
670 user_data.free_func = wg_callback_free;
671 plugin_register_write("write_stackdriver", wg_write, &user_data);
674 } /* }}} int wg_config */
676 static int wg_init(void) {
678 /* Call this while collectd is still single-threaded to avoid
679 * initialization issues in libgcrypt. */
680 curl_global_init(CURL_GLOBAL_SSL);
683 } /* }}} int wg_init */
685 void module_register(void) /* {{{ */
687 plugin_register_complex_config("write_stackdriver", wg_config);
688 plugin_register_init("write_stackdriver", wg_init);
689 } /* }}} void module_register */