aclk_rx_msgs.c 17 KB

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