mqtt.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include <libnetdata/json/json.h>
  3. #include "../daemon/common.h"
  4. #include "mqtt.h"
  5. #include "aclk_lws_wss_client.h"
  6. #include "aclk_stats.h"
  7. extern usec_t aclk_session_us;
  8. extern time_t aclk_session_sec;
  9. inline const char *_link_strerror(int rc)
  10. {
  11. return mosquitto_strerror(rc);
  12. }
  13. #ifdef NETDATA_INTERNAL_CHECKS
  14. static struct timeval sendTimes[1024];
  15. #endif
  16. static struct mosquitto *mosq = NULL;
  17. void mqtt_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
  18. {
  19. UNUSED(mosq);
  20. UNUSED(obj);
  21. aclk_handle_cloud_request(msg->payload);
  22. }
  23. void publish_callback(struct mosquitto *mosq, void *obj, int rc)
  24. {
  25. UNUSED(mosq);
  26. UNUSED(obj);
  27. UNUSED(rc);
  28. #ifdef NETDATA_INTERNAL_CHECKS
  29. struct timeval now, *orig;
  30. now_realtime_timeval(&now);
  31. orig = &sendTimes[ rc & 0x3ff ];
  32. int64_t diff = (now.tv_sec - orig->tv_sec) * USEC_PER_SEC + (now.tv_usec - orig->tv_usec);
  33. diff /= 1000;
  34. info("Publish_callback: mid=%d latency=%" PRId64 "ms", rc, diff);
  35. if (aclk_stats_enabled) {
  36. ACLK_STATS_LOCK;
  37. if (aclk_metrics_per_sample.latency_max < diff)
  38. aclk_metrics_per_sample.latency_max = diff;
  39. aclk_metrics_per_sample.latency_total += diff;
  40. aclk_metrics_per_sample.latency_count++;
  41. ACLK_STATS_UNLOCK;
  42. }
  43. #endif
  44. return;
  45. }
  46. void connect_callback(struct mosquitto *mosq, void *obj, int rc)
  47. {
  48. UNUSED(mosq);
  49. UNUSED(obj);
  50. UNUSED(rc);
  51. info("Connection to cloud estabilished");
  52. aclk_connect();
  53. return;
  54. }
  55. void disconnect_callback(struct mosquitto *mosq, void *obj, int rc)
  56. {
  57. UNUSED(mosq);
  58. UNUSED(obj);
  59. UNUSED(rc);
  60. if (netdata_exit)
  61. info("Connection to cloud terminated due to agent shutdown");
  62. else {
  63. errno = 0;
  64. error("Connection to cloud failed");
  65. }
  66. aclk_disconnect();
  67. aclk_lws_wss_mqtt_layer_disconect_notif();
  68. return;
  69. }
  70. void _show_mqtt_info()
  71. {
  72. int libmosq_major, libmosq_minor, libmosq_revision, libmosq_version;
  73. libmosq_version = mosquitto_lib_version(&libmosq_major, &libmosq_minor, &libmosq_revision);
  74. info(
  75. "Detected libmosquitto library version %d, %d.%d.%d", libmosq_version, libmosq_major, libmosq_minor,
  76. libmosq_revision);
  77. }
  78. size_t _mqtt_external_write_hook(void *buf, size_t count)
  79. {
  80. return aclk_lws_wss_client_write(buf, count);
  81. }
  82. size_t _mqtt_external_read_hook(void *buf, size_t count)
  83. {
  84. return aclk_lws_wss_client_read(buf, count);
  85. }
  86. int _mqtt_lib_init()
  87. {
  88. int rc;
  89. //int libmosq_major, libmosq_minor, libmosq_revision, libmosq_version;
  90. /* Commenting out now as it is unused - do not delete, this is needed for the on-prem version.
  91. char *ca_crt;
  92. char *server_crt;
  93. char *server_key;
  94. // show library info so can have it in the logfile
  95. //libmosq_version = mosquitto_lib_version(&libmosq_major, &libmosq_minor, &libmosq_revision);
  96. ca_crt = config_get(CONFIG_SECTION_CLOUD, "link cert", "*");
  97. server_crt = config_get(CONFIG_SECTION_CLOUD, "link server cert", "*");
  98. server_key = config_get(CONFIG_SECTION_CLOUD, "link server key", "*");
  99. if (ca_crt[0] == '*') {
  100. freez(ca_crt);
  101. ca_crt = NULL;
  102. }
  103. if (server_crt[0] == '*') {
  104. freez(server_crt);
  105. server_crt = NULL;
  106. }
  107. if (server_key[0] == '*') {
  108. freez(server_key);
  109. server_key = NULL;
  110. }
  111. */
  112. // info(
  113. // "Detected libmosquitto library version %d, %d.%d.%d", libmosq_version, libmosq_major, libmosq_minor,
  114. // libmosq_revision);
  115. rc = mosquitto_lib_init();
  116. if (unlikely(rc != MOSQ_ERR_SUCCESS)) {
  117. error("Failed to initialize MQTT (libmosquitto library)");
  118. return 1;
  119. }
  120. return 0;
  121. }
  122. static int _mqtt_create_connection(char *username, char *password)
  123. {
  124. if (mosq != NULL)
  125. mosquitto_destroy(mosq);
  126. mosq = mosquitto_new(username, true, NULL);
  127. if (unlikely(!mosq)) {
  128. mosquitto_lib_cleanup();
  129. error("MQTT new structure -- %s", mosquitto_strerror(errno));
  130. return MOSQ_ERR_UNKNOWN;
  131. }
  132. // Record the session start time to allow a nominal LWT timestamp
  133. usec_t now = now_realtime_usec();
  134. aclk_session_sec = now / USEC_PER_SEC;
  135. aclk_session_us = now % USEC_PER_SEC;
  136. _link_set_lwt("outbound/meta", 2);
  137. mosquitto_connect_callback_set(mosq, connect_callback);
  138. mosquitto_disconnect_callback_set(mosq, disconnect_callback);
  139. mosquitto_publish_callback_set(mosq, publish_callback);
  140. info("Using challenge-response: %s / %s", username, password);
  141. mosquitto_username_pw_set(mosq, username, password);
  142. int rc = mosquitto_threaded_set(mosq, 1);
  143. if (unlikely(rc != MOSQ_ERR_SUCCESS))
  144. error("Failed to tune the thread model for libmoquitto (%s)", mosquitto_strerror(rc));
  145. #if defined(LIBMOSQUITTO_VERSION_NUMBER) >= 1006000
  146. rc = mosquitto_int_option(mosq, MQTT_PROTOCOL_V311, 0);
  147. if (unlikely(rc != MOSQ_ERR_SUCCESS))
  148. error("MQTT protocol specification rc = %d (%s)", rc, mosquitto_strerror(rc));
  149. rc = mosquitto_int_option(mosq, MOSQ_OPT_SEND_MAXIMUM, 1);
  150. info("MQTT in flight messages set to 1 -- %s", mosquitto_strerror(rc));
  151. #endif
  152. return rc;
  153. }
  154. static int _link_mqtt_connect(char *aclk_hostname, int aclk_port)
  155. {
  156. int rc;
  157. rc = mosquitto_connect_async(mosq, aclk_hostname, aclk_port, ACLK_PING_INTERVAL);
  158. if (unlikely(rc != MOSQ_ERR_SUCCESS))
  159. error(
  160. "Failed to establish link to [%s:%d] MQTT status = %d (%s)", aclk_hostname, aclk_port, rc,
  161. mosquitto_strerror(rc));
  162. else
  163. info("Establishing MQTT link to [%s:%d]", aclk_hostname, aclk_port);
  164. return rc;
  165. }
  166. static inline void _link_mosquitto_write()
  167. {
  168. int rc;
  169. if (unlikely(!mosq)) {
  170. return;
  171. }
  172. rc = mosquitto_loop_misc(mosq);
  173. if (unlikely(rc != MOSQ_ERR_SUCCESS))
  174. debug(D_ACLK, "ACLK: failure during mosquitto_loop_misc %s", mosquitto_strerror(rc));
  175. if (likely(mosquitto_want_write(mosq))) {
  176. rc = mosquitto_loop_write(mosq, 1);
  177. if (rc != MOSQ_ERR_SUCCESS)
  178. debug(D_ACLK, "ACLK: failure during mosquitto_loop_write %s", mosquitto_strerror(rc));
  179. }
  180. }
  181. void aclk_lws_connection_established(char *hostname, int port)
  182. {
  183. _link_mqtt_connect(hostname, port); // Parameters only used for logging, lower layer connected.
  184. _link_mosquitto_write();
  185. }
  186. void aclk_lws_connection_data_received()
  187. {
  188. int rc = mosquitto_loop_read(mosq, 1);
  189. if (rc != MOSQ_ERR_SUCCESS)
  190. debug(D_ACLK, "ACLK: failure during mosquitto_loop_read %s", mosquitto_strerror(rc));
  191. }
  192. void aclk_lws_connection_closed()
  193. {
  194. aclk_disconnect();
  195. }
  196. int mqtt_attempt_connection(char *aclk_hostname, int aclk_port, char *username, char *password)
  197. {
  198. if(aclk_lws_wss_connect(aclk_hostname, aclk_port))
  199. return MOSQ_ERR_UNKNOWN;
  200. aclk_lws_wss_service_loop();
  201. int rc = _mqtt_create_connection(username, password);
  202. if (rc!= MOSQ_ERR_SUCCESS)
  203. return rc;
  204. mosquitto_external_callbacks_set(mosq, _mqtt_external_write_hook, _mqtt_external_read_hook);
  205. return rc;
  206. }
  207. inline int _link_event_loop()
  208. {
  209. // TODO: Check if we need to flush undelivered messages from libmosquitto on new connection attempts (QoS=1).
  210. _link_mosquitto_write();
  211. aclk_lws_wss_service_loop();
  212. // this is because if use LWS we don't want
  213. // mqtt to reconnect by itself
  214. return MOSQ_ERR_SUCCESS;
  215. }
  216. void _link_shutdown()
  217. {
  218. int rc;
  219. if (likely(!mosq))
  220. return;
  221. rc = mosquitto_disconnect(mosq);
  222. switch (rc) {
  223. case MOSQ_ERR_SUCCESS:
  224. info("MQTT disconnected from broker");
  225. break;
  226. default:
  227. info("MQTT invalid structure");
  228. break;
  229. };
  230. }
  231. int _link_set_lwt(char *sub_topic, int qos)
  232. {
  233. int rc;
  234. char topic[ACLK_MAX_TOPIC + 1];
  235. char *final_topic;
  236. final_topic = get_topic(sub_topic, topic, ACLK_MAX_TOPIC);
  237. if (unlikely(!final_topic)) {
  238. errno = 0;
  239. error("Unable to build outgoing topic; truncated?");
  240. return 1;
  241. }
  242. usec_t lwt_time = aclk_session_sec * USEC_PER_SEC + aclk_session_us + 1;
  243. BUFFER *b = buffer_create(512);
  244. aclk_create_header(b, "disconnect", NULL, lwt_time / USEC_PER_SEC, lwt_time % USEC_PER_SEC);
  245. buffer_strcat(b, ", \"payload\": \"unexpected\" }");
  246. rc = mosquitto_will_set(mosq, topic, buffer_strlen(b), buffer_tostring(b), qos, 0);
  247. buffer_free(b);
  248. return rc;
  249. }
  250. int _link_subscribe(char *topic, int qos)
  251. {
  252. int rc;
  253. if (unlikely(!mosq))
  254. return 1;
  255. mosquitto_message_callback_set(mosq, mqtt_message_callback);
  256. rc = mosquitto_subscribe(mosq, NULL, topic, qos);
  257. if (unlikely(rc)) {
  258. errno = 0;
  259. error("Failed to register subscription %d (%s)", rc, mosquitto_strerror(rc));
  260. return 1;
  261. }
  262. _link_mosquitto_write();
  263. return 0;
  264. }
  265. /*
  266. * Send a message to the cloud to specific topic
  267. *
  268. */
  269. int _link_send_message(char *topic, unsigned char *message, int *mid)
  270. {
  271. int rc;
  272. size_t write_q, write_q_bytes, read_q;
  273. rc = mosquitto_pub_topic_check(topic);
  274. if (unlikely(rc != MOSQ_ERR_SUCCESS))
  275. return rc;
  276. int msg_len = strlen((char*)message);
  277. lws_wss_check_queues(&write_q, &write_q_bytes, &read_q);
  278. rc = mosquitto_publish(mosq, mid, topic, msg_len, message, ACLK_QOS, 0);
  279. #ifdef NETDATA_INTERNAL_CHECKS
  280. char msg_head[64];
  281. memset(msg_head, 0, sizeof(msg_head));
  282. strncpy(msg_head, (char*)message, 60);
  283. for (size_t i = 0; i < sizeof(msg_head); i++)
  284. if(msg_head[i] == '\n') msg_head[i] = ' ';
  285. info("Sending MQTT len=%d mid=%d wq=%zu (%zu-bytes) readq=%zu: %s", msg_len,
  286. *mid, write_q, write_q_bytes, read_q, msg_head);
  287. now_realtime_timeval(&sendTimes[ *mid & 0x3ff ]);
  288. #endif
  289. // TODO: Add better handling -- error will flood the logfile here
  290. if (unlikely(rc != MOSQ_ERR_SUCCESS)) {
  291. errno = 0;
  292. error("MQTT message failed : %s", mosquitto_strerror(rc));
  293. }
  294. _link_mosquitto_write();
  295. return rc;
  296. }