api.c 1.45 KB
Newer Older
Julian Rother's avatar
Julian Rother committed
1
2
3
#include <curl/curl.h>
#include <stdio.h>
#include <stdarg.h>
Julian Rother's avatar
Julian Rother committed
4
#include <stdlib.h>
Julian Rother's avatar
Julian Rother committed
5
6
7
8
9
10
11
12
#include <unistd.h>
#include <string.h>

#include "../util.h"
#include "../config.h"

static size_t curl_write_cb(char *ptr, size_t size, size_t nmemb, void *user)
{
Julian Rother's avatar
Julian Rother committed
13
	return size*nmemb;
Julian Rother's avatar
Julian Rother committed
14
15
16
17
18
19
20
}

int ping_job(int id, char *state, char *status, ...)
{
	int ret;
	CURL *curl;
	va_list ap;
Julian Rother's avatar
Julian Rother committed
21
22
	char *p, *url, *e_host, *e_status, *e_apikey, *e_state;
	char hostbuf[HOST_NAME_MAX+1];
Julian Rother's avatar
Julian Rother committed
23
24
25
26
27
	if (!(curl = curl_easy_init()))
		return -1;
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_cb);
	e_apikey = curl_easy_escape(curl, CONFIG_APIKEY, 0);
	e_state = curl_easy_escape(curl, state, 0);
Julian Rother's avatar
Julian Rother committed
28
29
30
	if (gethostname(BL(hostbuf)))
		strcpy(hostbuf, "localhost");
	e_host = curl_easy_escape(curl, hostbuf, 0);
Julian Rother's avatar
Julian Rother committed
31
32
33
	if (status)
	{
		va_start(ap, status);
Julian Rother's avatar
Julian Rother committed
34
		p = vmprintf(status, ap);
Julian Rother's avatar
Julian Rother committed
35
36
37
		va_end(ap);
	}
	else
Julian Rother's avatar
Julian Rother committed
38
39
40
41
42
		p = strdup("{}");
	e_status = curl_easy_escape(curl, p, 0);
	free(p);
	p = mprintf("apikey=%s&state=%s&host=%s&status=%s", e_apikey, e_state,
			e_host, e_status);
Julian Rother's avatar
Julian Rother committed
43
44
45
46
	curl_free(e_apikey);
	curl_free(e_state);
	curl_free(e_host);
	curl_free(e_status);
Julian Rother's avatar
Julian Rother committed
47
48
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, p);
	url = mprintf("%s/internal/jobs/api/job/%i/ping", CONFIG_APIBASE, id);
Julian Rother's avatar
Julian Rother committed
49
50
	curl_easy_setopt(curl, CURLOPT_URL, url);
	ret = curl_easy_perform(curl);
Julian Rother's avatar
Julian Rother committed
51
52
	free(p);
	free(url);
Julian Rother's avatar
Julian Rother committed
53
54
	curl_easy_cleanup(curl);
	if (ret)
Julian Rother's avatar
Julian Rother committed
55
56
	{
		fprintf(stderr, "API call to \"%s\" failed: %s\n", url, curl_easy_strerror(ret));
Julian Rother's avatar
Julian Rother committed
57
		return -1;
Julian Rother's avatar
Julian Rother committed
58
	}
Julian Rother's avatar
Julian Rother committed
59
60
61
	else
		return 0;
}