aclk_rx_msgs.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "aclk_rx_msgs.h"
  3. #include "aclk_stats.h"
  4. #include "aclk_query_queue.h"
  5. #include "aclk.h"
  6. #include "aclk_capas.h"
  7. #include "aclk_query.h"
  8. #include "schema-wrappers/proto_2_json.h"
  9. #define ACLK_V2_PAYLOAD_SEPARATOR "\x0D\x0A\x0D\x0A"
  10. #define ACLK_CLOUD_REQ_V2_PREFIX "GET /"
  11. #define ACLK_V_COMPRESSION 2
  12. struct aclk_request {
  13. char *type_id;
  14. char *msg_id;
  15. char *callback_topic;
  16. char *payload;
  17. int version;
  18. int timeout;
  19. int min_version;
  20. int max_version;
  21. };
  22. static int cloud_to_agent_parse(JSON_ENTRY *e)
  23. {
  24. struct aclk_request *data = e->callback_data;
  25. switch (e->type) {
  26. case JSON_OBJECT:
  27. case JSON_ARRAY:
  28. break;
  29. case JSON_STRING:
  30. if (!strcmp(e->name, "msg-id")) {
  31. data->msg_id = strdupz(e->data.string);
  32. break;
  33. }
  34. if (!strcmp(e->name, "type")) {
  35. data->type_id = strdupz(e->data.string);
  36. break;
  37. }
  38. if (!strcmp(e->name, "callback-topic")) {
  39. data->callback_topic = strdupz(e->data.string);
  40. break;
  41. }
  42. if (!strcmp(e->name, "payload")) {
  43. if (likely(e->data.string)) {
  44. size_t len = strlen(e->data.string);
  45. data->payload = mallocz(len+1);
  46. if (!url_decode_r(data->payload, e->data.string, len + 1))
  47. strcpy(data->payload, e->data.string);
  48. }
  49. break;
  50. }
  51. break;
  52. case JSON_NUMBER:
  53. if (!strcmp(e->name, "version")) {
  54. data->version = (int)e->data.number;
  55. break;
  56. }
  57. if (!strcmp(e->name, "timeout")) {
  58. data->timeout = (int)e->data.number;
  59. break;
  60. }
  61. if (!strcmp(e->name, "min-version")) {
  62. data->min_version = (int)e->data.number;
  63. break;
  64. }
  65. if (!strcmp(e->name, "max-version")) {
  66. data->max_version = (int)e->data.number;
  67. break;
  68. }
  69. break;
  70. case JSON_BOOLEAN:
  71. break;
  72. case JSON_NULL:
  73. break;
  74. }
  75. return 0;
  76. }
  77. static inline int aclk_extract_v2_data(char *payload, char **data)
  78. {
  79. char* ptr = strstr(payload, ACLK_V2_PAYLOAD_SEPARATOR);
  80. if(!ptr)
  81. return 1;
  82. ptr += strlen(ACLK_V2_PAYLOAD_SEPARATOR);
  83. *data = strdupz(ptr);
  84. return 0;
  85. }
  86. static inline int aclk_v2_payload_get_query(const char *payload, char **query_url)
  87. {
  88. const char *start, *end;
  89. // TODO better check of URL
  90. if(strncmp(payload, ACLK_CLOUD_REQ_V2_PREFIX, strlen(ACLK_CLOUD_REQ_V2_PREFIX))) {
  91. errno = 0;
  92. netdata_log_error("Only accepting requests that start with \"%s\" from CLOUD.", ACLK_CLOUD_REQ_V2_PREFIX);
  93. return 1;
  94. }
  95. start = payload + 4;
  96. if(!(end = strstr(payload, HTTP_1_1 HTTP_ENDL))) {
  97. errno = 0;
  98. netdata_log_error("Doesn't look like HTTP GET request.");
  99. return 1;
  100. }
  101. *query_url = mallocz((end - start) + 1);
  102. strncpyz(*query_url, start, end - start);
  103. return 0;
  104. }
  105. static int aclk_handle_cloud_http_request_v2(struct aclk_request *cloud_to_agent, char *raw_payload)
  106. {
  107. aclk_query_t query;
  108. errno = 0;
  109. if (cloud_to_agent->version < ACLK_V_COMPRESSION) {
  110. netdata_log_error(
  111. "This handler cannot reply to request with version older than %d, received %d.",
  112. ACLK_V_COMPRESSION,
  113. cloud_to_agent->version);
  114. return 1;
  115. }
  116. query = aclk_query_new(HTTP_API_V2);
  117. if (unlikely(aclk_extract_v2_data(raw_payload, &query->data.http_api_v2.payload))) {
  118. netdata_log_error("Error extracting payload expected after the JSON dictionary.");
  119. goto error;
  120. }
  121. if (unlikely(aclk_v2_payload_get_query(query->data.http_api_v2.payload, &query->dedup_id))) {
  122. netdata_log_error("Could not extract payload from query");
  123. goto error;
  124. }
  125. if (unlikely(!cloud_to_agent->callback_topic)) {
  126. netdata_log_error("Missing callback_topic");
  127. goto error;
  128. }
  129. if (unlikely(!cloud_to_agent->msg_id)) {
  130. netdata_log_error("Missing msg_id");
  131. goto error;
  132. }
  133. // aclk_queue_query takes ownership of data pointer
  134. query->callback_topic = cloud_to_agent->callback_topic;
  135. query->timeout = cloud_to_agent->timeout;
  136. // for clarity and code readability as when we process the request
  137. // it would be strange to get URL from `dedup_id`
  138. query->data.http_api_v2.query = query->dedup_id;
  139. query->msg_id = cloud_to_agent->msg_id;
  140. aclk_queue_query(query);
  141. return 0;
  142. error:
  143. aclk_query_free(query);
  144. return 1;
  145. }
  146. int aclk_handle_cloud_cmd_message(char *payload)
  147. {
  148. struct aclk_request cloud_to_agent;
  149. memset(&cloud_to_agent, 0, sizeof(struct aclk_request));
  150. if (unlikely(!payload)) {
  151. error_report("ACLK incoming 'cmd' message is empty");
  152. return 1;
  153. }
  154. netdata_log_debug(D_ACLK, "ACLK incoming 'cmd' message (%s)", payload);
  155. int rc = json_parse(payload, &cloud_to_agent, cloud_to_agent_parse);
  156. if (unlikely(rc != JSON_OK)) {
  157. error_report("Malformed json request (%s)", payload);
  158. goto err_cleanup;
  159. }
  160. if (!cloud_to_agent.type_id) {
  161. error_report("Cloud message is missing compulsory key \"type\"");
  162. goto err_cleanup;
  163. }
  164. // Originally we were expecting to have multiple types of 'cmd' message,
  165. // but after the new protocol was designed we will ever only have 'http'
  166. if (strcmp(cloud_to_agent.type_id, "http")) {
  167. error_report("Only 'http' cmd message is supported");
  168. goto err_cleanup;
  169. }
  170. if (likely(!aclk_handle_cloud_http_request_v2(&cloud_to_agent, payload))) {
  171. // aclk_handle_cloud_request takes ownership of the pointers
  172. // (to avoid copying) in case of success
  173. freez(cloud_to_agent.type_id);
  174. return 0;
  175. }
  176. err_cleanup:
  177. if (cloud_to_agent.payload)
  178. freez(cloud_to_agent.payload);
  179. if (cloud_to_agent.type_id)
  180. freez(cloud_to_agent.type_id);
  181. if (cloud_to_agent.msg_id)
  182. freez(cloud_to_agent.msg_id);
  183. if (cloud_to_agent.callback_topic)
  184. freez(cloud_to_agent.callback_topic);
  185. return 1;
  186. }
  187. typedef uint32_t simple_hash_t;
  188. typedef int(*rx_msg_handler)(const char *msg, size_t msg_len);
  189. int handle_old_proto_cmd(const char *msg, size_t msg_len)
  190. {
  191. // msg is binary payload in all other cases
  192. // however in this message from old legacy cloud
  193. // we have to convert it to C string
  194. char *str = mallocz(msg_len+1);
  195. memcpy(str, msg, msg_len);
  196. str[msg_len] = 0;
  197. if (aclk_handle_cloud_cmd_message(str)) {
  198. freez(str);
  199. return 1;
  200. }
  201. freez(str);
  202. return 0;
  203. }
  204. int create_node_instance_result(const char *msg, size_t msg_len)
  205. {
  206. node_instance_creation_result_t res = parse_create_node_instance_result(msg, msg_len);
  207. if (!res.machine_guid || !res.node_id) {
  208. error_report("Error parsing CreateNodeInstanceResult");
  209. freez(res.machine_guid);
  210. freez(res.node_id);
  211. return 1;
  212. }
  213. netdata_log_debug(D_ACLK, "CreateNodeInstanceResult: guid:%s nodeid:%s", res.machine_guid, res.node_id);
  214. uuid_t host_id, node_id;
  215. if (uuid_parse(res.machine_guid, host_id)) {
  216. netdata_log_error("Error parsing machine_guid provided by CreateNodeInstanceResult");
  217. freez(res.machine_guid);
  218. freez(res.node_id);
  219. return 1;
  220. }
  221. if (uuid_parse(res.node_id, node_id)) {
  222. netdata_log_error("Error parsing node_id provided by CreateNodeInstanceResult");
  223. freez(res.machine_guid);
  224. freez(res.node_id);
  225. return 1;
  226. }
  227. update_node_id(&host_id, &node_id);
  228. aclk_query_t query = aclk_query_new(NODE_STATE_UPDATE);
  229. node_instance_connection_t node_state_update = {
  230. .hops = 1,
  231. .live = 0,
  232. .queryable = 1,
  233. .session_id = aclk_session_newarch,
  234. .node_id = res.node_id,
  235. .capabilities = NULL
  236. };
  237. RRDHOST *host = rrdhost_find_by_guid(res.machine_guid);
  238. if (likely(host)) {
  239. if (host == localhost) {
  240. node_state_update.live = 1;
  241. node_state_update.hops = 0;
  242. } else {
  243. node_state_update.live = (!rrdhost_flag_check(host, RRDHOST_FLAG_ORPHAN));
  244. node_state_update.hops = host->system_info->hops;
  245. }
  246. node_state_update.capabilities = aclk_get_node_instance_capas(host);
  247. }
  248. rrdhost_aclk_state_lock(localhost);
  249. node_state_update.claim_id = localhost->aclk_state.claimed_id;
  250. query->data.bin_payload.payload = generate_node_instance_connection(&query->data.bin_payload.size, &node_state_update);
  251. rrdhost_aclk_state_unlock(localhost);
  252. freez((void *)node_state_update.capabilities);
  253. query->data.bin_payload.msg_name = "UpdateNodeInstanceConnection";
  254. query->data.bin_payload.topic = ACLK_TOPICID_NODE_CONN;
  255. aclk_queue_query(query);
  256. freez(res.node_id);
  257. freez(res.machine_guid);
  258. return 0;
  259. }
  260. int send_node_instances(const char *msg, size_t msg_len)
  261. {
  262. UNUSED(msg);
  263. UNUSED(msg_len);
  264. aclk_send_node_instances();
  265. return 0;
  266. }
  267. int stream_charts_and_dimensions(const char *msg, size_t msg_len)
  268. {
  269. UNUSED(msg);
  270. UNUSED(msg_len);
  271. error_report("Received obsolete StreamChartsAndDimensions msg");
  272. return 0;
  273. }
  274. int charts_and_dimensions_ack(const char *msg, size_t msg_len)
  275. {
  276. UNUSED(msg);
  277. UNUSED(msg_len);
  278. error_report("Received obsolete StreamChartsAndDimensionsAck msg");
  279. return 0;
  280. }
  281. int update_chart_configs(const char *msg, size_t msg_len)
  282. {
  283. UNUSED(msg);
  284. UNUSED(msg_len);
  285. error_report("Received obsolete UpdateChartConfigs msg");
  286. return 0;
  287. }
  288. int start_alarm_streaming(const char *msg, size_t msg_len)
  289. {
  290. struct start_alarm_streaming res = parse_start_alarm_streaming(msg, msg_len);
  291. if (!res.node_id) {
  292. netdata_log_error("Error parsing StartAlarmStreaming");
  293. return 1;
  294. }
  295. aclk_start_alert_streaming(res.node_id, res.resets);
  296. freez(res.node_id);
  297. return 0;
  298. }
  299. int send_alarm_checkpoint(const char *msg, size_t msg_len)
  300. {
  301. struct send_alarm_checkpoint sac = parse_send_alarm_checkpoint(msg, msg_len);
  302. if (!sac.node_id || !sac.claim_id) {
  303. netdata_log_error("Error parsing SendAlarmCheckpoint");
  304. freez(sac.node_id);
  305. freez(sac.claim_id);
  306. return 1;
  307. }
  308. aclk_send_alarm_checkpoint(sac.node_id, sac.claim_id);
  309. freez(sac.node_id);
  310. freez(sac.claim_id);
  311. return 0;
  312. }
  313. int send_alarm_configuration(const char *msg, size_t msg_len)
  314. {
  315. char *config_hash = parse_send_alarm_configuration(msg, msg_len);
  316. if (!config_hash || !*config_hash) {
  317. netdata_log_error("Error parsing SendAlarmConfiguration");
  318. freez(config_hash);
  319. return 1;
  320. }
  321. aclk_send_alarm_configuration(config_hash);
  322. freez(config_hash);
  323. return 0;
  324. }
  325. int send_alarm_snapshot(const char *msg, size_t msg_len)
  326. {
  327. struct send_alarm_snapshot *sas = parse_send_alarm_snapshot(msg, msg_len);
  328. if (!sas->node_id || !sas->claim_id || !sas->snapshot_uuid) {
  329. netdata_log_error("Error parsing SendAlarmSnapshot");
  330. destroy_send_alarm_snapshot(sas);
  331. return 1;
  332. }
  333. aclk_process_send_alarm_snapshot(sas->node_id, sas->claim_id, sas->snapshot_uuid);
  334. destroy_send_alarm_snapshot(sas);
  335. return 0;
  336. }
  337. int handle_disconnect_req(const char *msg, size_t msg_len)
  338. {
  339. struct disconnect_cmd *cmd = parse_disconnect_cmd(msg, msg_len);
  340. if (!cmd)
  341. return 1;
  342. if (cmd->permaban) {
  343. netdata_log_error("Cloud Banned This Agent!");
  344. aclk_disable_runtime = 1;
  345. }
  346. netdata_log_info("Cloud requested disconnect (EC=%u, \"%s\")", (unsigned int)cmd->error_code, cmd->error_description);
  347. if (cmd->reconnect_after_s > 0) {
  348. aclk_block_until = now_monotonic_sec() + cmd->reconnect_after_s;
  349. netdata_log_info(
  350. "Cloud asks not to reconnect for %u seconds. We shall honor that request",
  351. (unsigned int)cmd->reconnect_after_s);
  352. }
  353. disconnect_req = 1;
  354. freez(cmd->error_description);
  355. freez(cmd);
  356. return 0;
  357. }
  358. int contexts_checkpoint(const char *msg, size_t msg_len)
  359. {
  360. aclk_ctx_based = 1;
  361. struct ctxs_checkpoint *cmd = parse_ctxs_checkpoint(msg, msg_len);
  362. if (!cmd)
  363. return 1;
  364. rrdcontext_hub_checkpoint_command(cmd);
  365. freez(cmd->claim_id);
  366. freez(cmd->node_id);
  367. freez(cmd);
  368. return 0;
  369. }
  370. int stop_streaming_contexts(const char *msg, size_t msg_len)
  371. {
  372. if (!aclk_ctx_based) {
  373. error_report("Received StopStreamingContexts message but context based communication was not enabled (Cloud violated the protocol). Ignoring message");
  374. return 1;
  375. }
  376. struct stop_streaming_ctxs *cmd = parse_stop_streaming_ctxs(msg, msg_len);
  377. if (!cmd)
  378. return 1;
  379. rrdcontext_hub_stop_streaming_command(cmd);
  380. freez(cmd->claim_id);
  381. freez(cmd->node_id);
  382. freez(cmd);
  383. return 0;
  384. }
  385. int cancel_pending_req(const char *msg, size_t msg_len)
  386. {
  387. struct aclk_cancel_pending_req cmd = {.request_id = NULL, .trace_id = NULL};
  388. if(parse_cancel_pending_req(msg, msg_len, &cmd)) {
  389. error_report("Error parsing CancelPendingReq");
  390. return 1;
  391. }
  392. nd_log(NDLS_ACCESS, NDLP_NOTICE, "ACLK CancelPendingRequest REQ: %s, cloud trace-id: %s", cmd.request_id, cmd.trace_id);
  393. if (mark_pending_req_cancelled(cmd.request_id))
  394. error_report("CancelPending Request for %s failed. No such pending request.", cmd.request_id);
  395. free_cancel_pending_req(&cmd);
  396. return 0;
  397. }
  398. typedef struct {
  399. const char *name;
  400. simple_hash_t name_hash;
  401. rx_msg_handler fnc;
  402. } new_cloud_rx_msg_t;
  403. new_cloud_rx_msg_t rx_msgs[] = {
  404. { .name = "cmd", .name_hash = 0, .fnc = handle_old_proto_cmd },
  405. { .name = "CreateNodeInstanceResult", .name_hash = 0, .fnc = create_node_instance_result },
  406. { .name = "SendNodeInstances", .name_hash = 0, .fnc = send_node_instances },
  407. { .name = "StreamChartsAndDimensions", .name_hash = 0, .fnc = stream_charts_and_dimensions },
  408. { .name = "ChartsAndDimensionsAck", .name_hash = 0, .fnc = charts_and_dimensions_ack },
  409. { .name = "UpdateChartConfigs", .name_hash = 0, .fnc = update_chart_configs },
  410. { .name = "StartAlarmStreaming", .name_hash = 0, .fnc = start_alarm_streaming },
  411. { .name = "SendAlarmCheckpoint", .name_hash = 0, .fnc = send_alarm_checkpoint },
  412. { .name = "SendAlarmConfiguration", .name_hash = 0, .fnc = send_alarm_configuration },
  413. { .name = "SendAlarmSnapshot", .name_hash = 0, .fnc = send_alarm_snapshot },
  414. { .name = "DisconnectReq", .name_hash = 0, .fnc = handle_disconnect_req },
  415. { .name = "ContextsCheckpoint", .name_hash = 0, .fnc = contexts_checkpoint },
  416. { .name = "StopStreamingContexts", .name_hash = 0, .fnc = stop_streaming_contexts },
  417. { .name = "CancelPendingRequest", .name_hash = 0, .fnc = cancel_pending_req },
  418. { .name = NULL, .name_hash = 0, .fnc = NULL },
  419. };
  420. new_cloud_rx_msg_t *find_rx_handler_by_hash(simple_hash_t hash)
  421. {
  422. // we can afford to not compare strings after hash match
  423. // because we check for collisions at initialization in
  424. // aclk_init_rx_msg_handlers()
  425. for (int i = 0; rx_msgs[i].fnc; i++) {
  426. if (rx_msgs[i].name_hash == hash)
  427. return &rx_msgs[i];
  428. }
  429. return NULL;
  430. }
  431. const char *rx_handler_get_name(size_t i)
  432. {
  433. return rx_msgs[i].name;
  434. }
  435. unsigned int aclk_init_rx_msg_handlers(void)
  436. {
  437. int i;
  438. for (i = 0; rx_msgs[i].fnc; i++) {
  439. simple_hash_t hash = simple_hash(rx_msgs[i].name);
  440. new_cloud_rx_msg_t *hdl = find_rx_handler_by_hash(hash);
  441. if (unlikely(hdl)) {
  442. // the list of message names changes only by changing
  443. // the source code, therefore fatal is appropriate
  444. fatal("Hash collision. Choose better hash. Added '%s' clashes with existing '%s'", rx_msgs[i].name, hdl->name);
  445. }
  446. rx_msgs[i].name_hash = hash;
  447. }
  448. return i;
  449. }
  450. void aclk_handle_new_cloud_msg(const char *message_type, const char *msg, size_t msg_len, const char *topic __maybe_unused)
  451. {
  452. if (aclk_stats_enabled) {
  453. ACLK_STATS_LOCK;
  454. aclk_metrics_per_sample.cloud_req_recvd++;
  455. ACLK_STATS_UNLOCK;
  456. }
  457. new_cloud_rx_msg_t *msg_descriptor = find_rx_handler_by_hash(simple_hash(message_type));
  458. netdata_log_debug(D_ACLK, "Got message named '%s' from cloud", message_type);
  459. if (unlikely(!msg_descriptor)) {
  460. netdata_log_error("Do not know how to handle message of type '%s'. Ignoring", message_type);
  461. if (aclk_stats_enabled) {
  462. ACLK_STATS_LOCK;
  463. aclk_metrics_per_sample.cloud_req_err++;
  464. ACLK_STATS_UNLOCK;
  465. }
  466. return;
  467. }
  468. if (aclklog_enabled) {
  469. if (!strncmp(message_type, "cmd", strlen("cmd"))) {
  470. log_aclk_message_bin(msg, msg_len, 0, topic, msg_descriptor->name);
  471. } else {
  472. char *json = protomsg_to_json(msg, msg_len, msg_descriptor->name);
  473. log_aclk_message_bin(json, strlen(json), 0, topic, msg_descriptor->name);
  474. freez(json);
  475. }
  476. }
  477. if (aclk_stats_enabled) {
  478. ACLK_STATS_LOCK;
  479. aclk_proto_rx_msgs_sample[msg_descriptor-rx_msgs]++;
  480. ACLK_STATS_UNLOCK;
  481. }
  482. if (msg_descriptor->fnc(msg, msg_len)) {
  483. netdata_log_error("Error processing message of type '%s'", message_type);
  484. if (aclk_stats_enabled) {
  485. ACLK_STATS_LOCK;
  486. aclk_metrics_per_sample.cloud_req_err++;
  487. ACLK_STATS_UNLOCK;
  488. }
  489. return;
  490. }
  491. }