-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.cpp
More file actions
82 lines (67 loc) · 2.35 KB
/
code.cpp
File metadata and controls
82 lines (67 loc) · 2.35 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <cstdlib>
#include <iostream>
#include <string>
#include <curl/curl.h>
bool send_alert(const std::string& message,
const std::string& severity,
const std::string& source,
const std::string& type,
int confidence,
const std::string& data_json = "{}") {
const char* token = std::getenv("INTERNAL_ALERT_TOKEN");
const char* url = std::getenv("RTCT_INTERNAL_ALERT_URL");
if (!token) {
std::cerr << "INTERNAL_ALERT_TOKEN not set\n";
return false;
}
std::string endpoint = url ? url : "http://api:4000/internal/alert";
std::string payload =
"{"
"\"message\":\"" + message + "\","
"\"severity\":\"" + severity + "\","
"\"source\":\"" + source + "\","
"\"type\":\"" + type + "\","
"\"confidence\":" + std::to_string(confidence) + ","
"\"data\":" + data_json +
"}";
CURL* curl = curl_easy_init();
if (!curl) {
std::cerr << "Failed to init curl\n";
return false;
}
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
std::string token_header = std::string("x-internal-token: ") + token;
headers = curl_slist_append(headers, token_header.c_str());
curl_easy_setopt(curl, CURLOPT_URL, endpoint.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);
CURLcode res = curl_easy_perform(curl);
long status_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
std::cerr << "curl error: " << curl_easy_strerror(res) << "\n";
return false;
}
if (status_code < 200 || status_code >= 300) {
std::cerr << "HTTP error: " << status_code << "\n";
return false;
}
return true;
}
int main() {
bool ok = send_alert(
"Example alert from C++ pod",
"medium",
"pablo-cpp-detector",
"metrics",
84,
R"({"cpu":92.5,"mem":71.2,"temp":63.9})"
);
std::cout << (ok ? "Alert sent\n" : "Failed to send alert\n");
return ok ? 0 : 1;
}