-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfluxdbWriter.cpp
More file actions
67 lines (61 loc) · 1.92 KB
/
InfluxdbWriter.cpp
File metadata and controls
67 lines (61 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "InfluxdbWriter.h"
namespace PowerMonitor
{
InfluxdbWriter::InfluxdbWriter(const std::string& host, const std::string& db, const std::string& user, const std::string& password) :
_running(0)
{
CURLcode ret;
struct curl_slist *list = NULL;
ret = curl_global_init(CURL_GLOBAL_ALL);
if (ret)
{
throw std::runtime_error("Could not initialize curl: "
+ std::string(curl_easy_strerror(ret)));
}
_handle = curl_easy_init();
if (!_handle)
{
curl_global_cleanup();
throw std::runtime_error("Unable to obtain curl handle.");
}
_multihandle = curl_multi_init();
if (!_multihandle)
{
curl_easy_cleanup(_handle);
curl_global_cleanup();
throw std::runtime_error("Unable to obtain curl multi handle.");
}
std::stringstream url;
url << host << "/write?db=" << db;
curl_easy_setopt(_handle, CURLOPT_URL, url.str().c_str());
curl_easy_setopt(_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(_handle, CURLOPT_USERNAME, user.c_str());
curl_easy_setopt(_handle, CURLOPT_PASSWORD, password.c_str());
list = curl_slist_append(list, "Expect:");
curl_easy_setopt(_handle, CURLOPT_HTTPHEADER, list);
}
InfluxdbWriter::~InfluxdbWriter()
{
curl_multi_remove_handle(_multihandle, _handle);
curl_easy_cleanup(_handle);
curl_multi_cleanup(_multihandle);
curl_global_cleanup();
}
void InfluxdbWriter::_doSend()
{
curl_multi_perform(_multihandle, &_running);
if (!_running)
{
std::stringstream payload;
for (auto&& line : _buffer)
{
payload << line << "\n";
}
_buffer.clear();
curl_multi_remove_handle(_multihandle, _handle);
curl_easy_setopt(_handle, CURLOPT_COPYPOSTFIELDS, payload.str().c_str());
curl_multi_add_handle(_multihandle, _handle);
curl_multi_perform(_multihandle, &_running);
}
}
}