rrdpush.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. #include "parser/parser.h"
  4. /*
  5. * rrdpush
  6. *
  7. * 3 threads are involved for all stream operations
  8. *
  9. * 1. a random data collection thread, calling rrdset_done_push()
  10. * this is called for each chart.
  11. *
  12. * the output of this work is kept in a thread BUFFER
  13. * the sender thread is signalled via a pipe (in RRDHOST)
  14. *
  15. * 2. a sender thread running at the sending netdata
  16. * this is spawned automatically on the first chart to be pushed
  17. *
  18. * It tries to push the metrics to the remote netdata, as fast
  19. * as possible (i.e. immediately after they are collected).
  20. *
  21. * 3. a receiver thread, running at the receiving netdata
  22. * this is spawned automatically when the sender connects to
  23. * the receiver.
  24. *
  25. */
  26. struct config stream_config = {
  27. .first_section = NULL,
  28. .last_section = NULL,
  29. .mutex = NETDATA_MUTEX_INITIALIZER,
  30. .index = {
  31. .avl_tree = {
  32. .root = NULL,
  33. .compar = appconfig_section_compare
  34. },
  35. .rwlock = AVL_LOCK_INITIALIZER
  36. }
  37. };
  38. unsigned int default_rrdpush_enabled = 0;
  39. #ifdef ENABLE_COMPRESSION
  40. unsigned int default_compression_enabled = 1;
  41. #endif
  42. char *default_rrdpush_destination = NULL;
  43. char *default_rrdpush_api_key = NULL;
  44. char *default_rrdpush_send_charts_matching = NULL;
  45. bool default_rrdpush_enable_replication = true;
  46. time_t default_rrdpush_seconds_to_replicate = 86400;
  47. time_t default_rrdpush_replication_step = 600;
  48. #ifdef ENABLE_HTTPS
  49. int netdata_use_ssl_on_stream = NETDATA_SSL_OPTIONAL;
  50. char *netdata_ssl_ca_path = NULL;
  51. char *netdata_ssl_ca_file = NULL;
  52. #endif
  53. static void load_stream_conf() {
  54. errno = 0;
  55. char *filename = strdupz_path_subpath(netdata_configured_user_config_dir, "stream.conf");
  56. if(!appconfig_load(&stream_config, filename, 0, NULL)) {
  57. info("CONFIG: cannot load user config '%s'. Will try stock config.", filename);
  58. freez(filename);
  59. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "stream.conf");
  60. if(!appconfig_load(&stream_config, filename, 0, NULL))
  61. info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  62. }
  63. freez(filename);
  64. }
  65. bool rrdpush_receiver_needs_dbengine() {
  66. struct section *co;
  67. for(co = stream_config.first_section; co; co = co->next) {
  68. if(strcmp(co->name, "stream") == 0)
  69. continue; // the first section is not relevant
  70. char *s;
  71. s = appconfig_get_by_section(co, "enabled", NULL);
  72. if(!s || !appconfig_test_boolean_value(s))
  73. continue;
  74. s = appconfig_get_by_section(co, "default memory mode", NULL);
  75. if(s && strcmp(s, "dbengine") == 0)
  76. return true;
  77. s = appconfig_get_by_section(co, "memory mode", NULL);
  78. if(s && strcmp(s, "dbengine") == 0)
  79. return true;
  80. }
  81. return false;
  82. }
  83. int rrdpush_init() {
  84. // --------------------------------------------------------------------
  85. // load stream.conf
  86. load_stream_conf();
  87. default_rrdpush_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
  88. default_rrdpush_destination = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "destination", "");
  89. default_rrdpush_api_key = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "api key", "");
  90. default_rrdpush_send_charts_matching = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "send charts matching", "*");
  91. default_rrdpush_enable_replication = config_get_boolean(CONFIG_SECTION_DB, "enable replication", default_rrdpush_enable_replication);
  92. default_rrdpush_seconds_to_replicate = config_get_number(CONFIG_SECTION_DB, "seconds to replicate", default_rrdpush_seconds_to_replicate);
  93. default_rrdpush_replication_step = config_get_number(CONFIG_SECTION_DB, "seconds per replication step", default_rrdpush_replication_step);
  94. rrdhost_free_orphan_time_s = config_get_number(CONFIG_SECTION_DB, "cleanup orphan hosts after secs", rrdhost_free_orphan_time_s);
  95. #ifdef ENABLE_COMPRESSION
  96. default_compression_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM,
  97. "enable compression", default_compression_enabled);
  98. #endif
  99. if(default_rrdpush_enabled && (!default_rrdpush_destination || !*default_rrdpush_destination || !default_rrdpush_api_key || !*default_rrdpush_api_key)) {
  100. error("STREAM [send]: cannot enable sending thread - information is missing.");
  101. default_rrdpush_enabled = 0;
  102. }
  103. #ifdef ENABLE_HTTPS
  104. if (netdata_use_ssl_on_stream == NETDATA_SSL_OPTIONAL) {
  105. if (default_rrdpush_destination){
  106. char *test = strstr(default_rrdpush_destination,":SSL");
  107. if(test){
  108. *test = 0X00;
  109. netdata_use_ssl_on_stream = NETDATA_SSL_FORCE;
  110. }
  111. }
  112. }
  113. bool invalid_certificate = appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "ssl skip certificate verification", CONFIG_BOOLEAN_NO);
  114. if(invalid_certificate == CONFIG_BOOLEAN_YES){
  115. if(netdata_ssl_validate_server == NETDATA_SSL_VALID_CERTIFICATE){
  116. info("Netdata is configured to accept invalid SSL certificate.");
  117. netdata_ssl_validate_server = NETDATA_SSL_INVALID_CERTIFICATE;
  118. }
  119. }
  120. netdata_ssl_ca_path = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CApath", NULL);
  121. netdata_ssl_ca_file = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CAfile", NULL);
  122. #endif
  123. return default_rrdpush_enabled;
  124. }
  125. // data collection happens from multiple threads
  126. // each of these threads calls rrdset_done()
  127. // which in turn calls rrdset_done_push()
  128. // which uses this pipe to notify the streaming thread
  129. // that there are more data ready to be sent
  130. #define PIPE_READ 0
  131. #define PIPE_WRITE 1
  132. // to have the remote netdata re-sync the charts
  133. // to its current clock, we send for this many
  134. // iterations a BEGIN line without microseconds
  135. // this is for the first iterations of each chart
  136. unsigned int remote_clock_resync_iterations = 60;
  137. static inline bool should_send_chart_matching(RRDSET *st, RRDSET_FLAGS flags) {
  138. if(!(flags & RRDSET_FLAG_RECEIVER_REPLICATION_FINISHED))
  139. return false;
  140. if(unlikely(!(flags & (RRDSET_FLAG_UPSTREAM_SEND | RRDSET_FLAG_UPSTREAM_IGNORE)))) {
  141. RRDHOST *host = st->rrdhost;
  142. if (flags & RRDSET_FLAG_ANOMALY_DETECTION) {
  143. if(ml_streaming_enabled())
  144. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  145. else
  146. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  147. }
  148. else if(simple_pattern_matches(host->rrdpush_send_charts_matching, rrdset_id(st)) ||
  149. simple_pattern_matches(host->rrdpush_send_charts_matching, rrdset_name(st)))
  150. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  151. else
  152. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  153. // get the flags again, to know how to respond
  154. flags = rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND|RRDSET_FLAG_UPSTREAM_IGNORE);
  155. }
  156. return flags & RRDSET_FLAG_UPSTREAM_SEND;
  157. }
  158. int configured_as_parent() {
  159. struct section *section = NULL;
  160. int is_parent = 0;
  161. appconfig_wrlock(&stream_config);
  162. for (section = stream_config.first_section; section; section = section->next) {
  163. uuid_t uuid;
  164. if (uuid_parse(section->name, uuid) != -1 &&
  165. appconfig_get_boolean_by_section(section, "enabled", 0)) {
  166. is_parent = 1;
  167. break;
  168. }
  169. }
  170. appconfig_unlock(&stream_config);
  171. return is_parent;
  172. }
  173. // chart labels
  174. static int send_clabels_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  175. BUFFER *wb = (BUFFER *)data;
  176. buffer_sprintf(wb, "CLABEL \"%s\" \"%s\" %d\n", name, value, ls);
  177. return 1;
  178. }
  179. static void rrdpush_send_clabels(BUFFER *wb, RRDSET *st) {
  180. if (st->rrdlabels) {
  181. if(rrdlabels_walkthrough_read(st->rrdlabels, send_clabels_callback, wb) > 0)
  182. buffer_sprintf(wb, "CLABEL_COMMIT\n");
  183. }
  184. }
  185. // Send the current chart definition.
  186. // Assumes that collector thread has already called sender_start for mutex / buffer state.
  187. static inline bool rrdpush_send_chart_definition(BUFFER *wb, RRDSET *st) {
  188. bool replication_progress = false;
  189. RRDHOST *host = st->rrdhost;
  190. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  191. // properly set the name for the remote end to parse it
  192. char *name = "";
  193. if(likely(st->name)) {
  194. if(unlikely(st->id != st->name)) {
  195. // they differ
  196. name = strchr(rrdset_name(st), '.');
  197. if(name)
  198. name++;
  199. else
  200. name = "";
  201. }
  202. }
  203. // send the chart
  204. buffer_sprintf(
  205. wb
  206. , "CHART \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" %ld %d \"%s %s %s %s\" \"%s\" \"%s\"\n"
  207. , rrdset_id(st)
  208. , name
  209. , rrdset_title(st)
  210. , rrdset_units(st)
  211. , rrdset_family(st)
  212. , rrdset_context(st)
  213. , rrdset_type_name(st->chart_type)
  214. , st->priority
  215. , st->update_every
  216. , rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)?"obsolete":""
  217. , rrdset_flag_check(st, RRDSET_FLAG_DETAIL)?"detail":""
  218. , rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)?"store_first":""
  219. , rrdset_flag_check(st, RRDSET_FLAG_HIDDEN)?"hidden":""
  220. , rrdset_plugin_name(st)
  221. , rrdset_module_name(st)
  222. );
  223. // send the chart labels
  224. if (stream_has_capability(host->sender, STREAM_CAP_CLABELS))
  225. rrdpush_send_clabels(wb, st);
  226. // send the dimensions
  227. RRDDIM *rd;
  228. rrddim_foreach_read(rd, st) {
  229. buffer_sprintf(
  230. wb
  231. , "DIMENSION \"%s\" \"%s\" \"%s\" " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " \"%s %s %s\"\n"
  232. , rrddim_id(rd)
  233. , rrddim_name(rd)
  234. , rrd_algorithm_name(rd->algorithm)
  235. , rd->multiplier
  236. , rd->divisor
  237. , rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)?"obsolete":""
  238. , rrddim_option_check(rd, RRDDIM_OPTION_HIDDEN)?"hidden":""
  239. , rrddim_option_check(rd, RRDDIM_OPTION_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
  240. );
  241. rd->exposed = 1;
  242. }
  243. rrddim_foreach_done(rd);
  244. // send the chart functions
  245. if(stream_has_capability(host->sender, STREAM_CAP_FUNCTIONS))
  246. rrd_functions_expose_rrdpush(st, wb);
  247. // send the chart local custom variables
  248. rrdsetvar_print_to_streaming_custom_chart_variables(st, wb);
  249. if (stream_has_capability(host->sender, STREAM_CAP_REPLICATION)) {
  250. time_t db_first_time_t, db_last_time_t;
  251. time_t now = now_realtime_sec();
  252. rrdset_get_retention_of_tier_for_collected_chart(st, &db_first_time_t, &db_last_time_t, now, 0);
  253. buffer_sprintf(wb, PLUGINSD_KEYWORD_CHART_DEFINITION_END " %llu %llu %llu\n",
  254. (unsigned long long)db_first_time_t,
  255. (unsigned long long)db_last_time_t,
  256. (unsigned long long)now);
  257. rrdset_flag_set(st, RRDSET_FLAG_SENDER_REPLICATION_IN_PROGRESS);
  258. rrdset_flag_clear(st, RRDSET_FLAG_SENDER_REPLICATION_FINISHED);
  259. rrdhost_sender_replicating_charts_plus_one(st->rrdhost);
  260. replication_progress = true;
  261. #ifdef NETDATA_LOG_REPLICATION_REQUESTS
  262. internal_error(true, "REPLAY: 'host:%s/chart:%s' replication starts",
  263. rrdhost_hostname(st->rrdhost), rrdset_id(st));
  264. #endif
  265. }
  266. st->upstream_resync_time_s = st->last_collected_time.tv_sec + (remote_clock_resync_iterations * st->update_every);
  267. return replication_progress;
  268. }
  269. // sends the current chart dimensions
  270. static void rrdpush_send_chart_metrics(BUFFER *wb, RRDSET *st, struct sender_state *s __maybe_unused, RRDSET_FLAGS flags) {
  271. buffer_fast_strcat(wb, "BEGIN \"", 7);
  272. buffer_fast_strcat(wb, rrdset_id(st), string_strlen(st->id));
  273. buffer_fast_strcat(wb, "\" ", 2);
  274. if(st->last_collected_time.tv_sec > st->upstream_resync_time_s)
  275. buffer_print_llu(wb, st->usec_since_last_update);
  276. else
  277. buffer_fast_strcat(wb, "0", 1);
  278. buffer_fast_strcat(wb, "\n", 1);
  279. RRDDIM *rd;
  280. rrddim_foreach_read(rd, st) {
  281. if(unlikely(!rd->updated))
  282. continue;
  283. if(likely(rd->exposed)) {
  284. buffer_fast_strcat(wb, "SET \"", 5);
  285. buffer_fast_strcat(wb, rrddim_id(rd), string_strlen(rd->id));
  286. buffer_fast_strcat(wb, "\" = ", 4);
  287. buffer_print_ll(wb, rd->collected_value);
  288. buffer_fast_strcat(wb, "\n", 1);
  289. }
  290. else {
  291. internal_error(true, "STREAM: 'host:%s/chart:%s/dim:%s' flag 'exposed' is updated but not exposed",
  292. rrdhost_hostname(st->rrdhost), rrdset_id(st), rrddim_id(rd));
  293. // we will include it in the next iteration
  294. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  295. }
  296. }
  297. rrddim_foreach_done(rd);
  298. if(unlikely(flags & RRDSET_FLAG_UPSTREAM_SEND_VARIABLES))
  299. rrdsetvar_print_to_streaming_custom_chart_variables(st, wb);
  300. buffer_fast_strcat(wb, "END\n", 4);
  301. }
  302. static void rrdpush_sender_thread_spawn(RRDHOST *host);
  303. // Called from the internal collectors to mark a chart obsolete.
  304. bool rrdset_push_chart_definition_now(RRDSET *st) {
  305. RRDHOST *host = st->rrdhost;
  306. if(unlikely(!rrdhost_can_send_definitions_to_parent(host)
  307. || !should_send_chart_matching(st, __atomic_load_n(&st->flags, __ATOMIC_SEQ_CST))))
  308. return false;
  309. BUFFER *wb = sender_start(host->sender);
  310. rrdpush_send_chart_definition(wb, st);
  311. sender_commit(host->sender, wb);
  312. sender_thread_buffer_free();
  313. return true;
  314. }
  315. void rrdset_done_push(RRDSET *st) {
  316. RRDHOST *host = st->rrdhost;
  317. // fetch the flags we need to check with one atomic operation
  318. RRDHOST_FLAGS host_flags = __atomic_load_n(&host->flags, __ATOMIC_SEQ_CST);
  319. // check if we are not connected
  320. if(unlikely(!(host_flags & RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS))) {
  321. if(unlikely(!(host_flags & (RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN | RRDHOST_FLAG_RRDPUSH_RECEIVER_DISCONNECTED))))
  322. rrdpush_sender_thread_spawn(host);
  323. if(unlikely(!(host_flags & RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS))) {
  324. rrdhost_flag_set(host, RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS);
  325. error("STREAM %s [send]: not ready - collected metrics are not sent to parent.", rrdhost_hostname(host));
  326. }
  327. return;
  328. }
  329. else if(unlikely(host_flags & RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS)) {
  330. info("STREAM %s [send]: sending metrics to parent...", rrdhost_hostname(host));
  331. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS);
  332. }
  333. RRDSET_FLAGS rrdset_flags = __atomic_load_n(&st->flags, __ATOMIC_SEQ_CST);
  334. bool exposed_upstream = (rrdset_flags & RRDSET_FLAG_UPSTREAM_EXPOSED);
  335. bool replication_in_progress = !(rrdset_flags & RRDSET_FLAG_SENDER_REPLICATION_FINISHED);
  336. if(unlikely((exposed_upstream && replication_in_progress) ||
  337. !should_send_chart_matching(st, rrdset_flags)))
  338. return;
  339. BUFFER *wb = sender_start(host->sender);
  340. if(unlikely(!exposed_upstream))
  341. replication_in_progress = rrdpush_send_chart_definition(wb, st);
  342. if (likely(!replication_in_progress))
  343. rrdpush_send_chart_metrics(wb, st, host->sender, rrdset_flags);
  344. sender_commit(host->sender, wb);
  345. }
  346. // labels
  347. static int send_labels_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  348. BUFFER *wb = (BUFFER *)data;
  349. buffer_sprintf(wb, "LABEL \"%s\" = %d \"%s\"\n", name, ls, value);
  350. return 1;
  351. }
  352. void rrdpush_send_host_labels(RRDHOST *host) {
  353. if(unlikely(!rrdhost_can_send_definitions_to_parent(host)
  354. || !stream_has_capability(host->sender, STREAM_CAP_HLABELS)))
  355. return;
  356. BUFFER *wb = sender_start(host->sender);
  357. rrdlabels_walkthrough_read(host->rrdlabels, send_labels_callback, wb);
  358. buffer_sprintf(wb, "OVERWRITE %s\n", "labels");
  359. sender_commit(host->sender, wb);
  360. sender_thread_buffer_free();
  361. }
  362. void rrdpush_claimed_id(RRDHOST *host)
  363. {
  364. if(!stream_has_capability(host->sender, STREAM_CAP_CLAIM))
  365. return;
  366. if(unlikely(!rrdhost_can_send_definitions_to_parent(host)))
  367. return;
  368. BUFFER *wb = sender_start(host->sender);
  369. rrdhost_aclk_state_lock(host);
  370. buffer_sprintf(wb, "CLAIMED_ID %s %s\n", host->machine_guid, (host->aclk_state.claimed_id ? host->aclk_state.claimed_id : "NULL") );
  371. rrdhost_aclk_state_unlock(host);
  372. sender_commit(host->sender, wb);
  373. sender_thread_buffer_free();
  374. }
  375. int connect_to_one_of_destinations(
  376. RRDHOST *host,
  377. int default_port,
  378. struct timeval *timeout,
  379. size_t *reconnects_counter,
  380. char *connected_to,
  381. size_t connected_to_size,
  382. struct rrdpush_destinations **destination)
  383. {
  384. int sock = -1;
  385. for (struct rrdpush_destinations *d = host->destinations; d; d = d->next) {
  386. time_t now = now_realtime_sec();
  387. if(d->postpone_reconnection_until > now)
  388. continue;
  389. info(
  390. "STREAM %s: connecting to '%s' (default port: %d)...",
  391. rrdhost_hostname(host),
  392. string2str(d->destination),
  393. default_port);
  394. if (reconnects_counter)
  395. *reconnects_counter += 1;
  396. sock = connect_to_this(string2str(d->destination), default_port, timeout);
  397. if (sock != -1) {
  398. if (connected_to && connected_to_size)
  399. strncpyz(connected_to, string2str(d->destination), connected_to_size);
  400. *destination = d;
  401. // move the current item to the end of the list
  402. // without this, this destination will break the loop again and again
  403. // not advancing the destinations to find one that may work
  404. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(host->destinations, d, prev, next);
  405. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(host->destinations, d, prev, next);
  406. break;
  407. }
  408. }
  409. return sock;
  410. }
  411. struct destinations_init_tmp {
  412. RRDHOST *host;
  413. struct rrdpush_destinations *list;
  414. int count;
  415. };
  416. bool destinations_init_add_one(char *entry, void *data) {
  417. struct destinations_init_tmp *t = data;
  418. struct rrdpush_destinations *d = callocz(1, sizeof(struct rrdpush_destinations));
  419. d->destination = string_strdupz(entry);
  420. __atomic_add_fetch(&netdata_buffers_statistics.rrdhost_senders, sizeof(struct rrdpush_destinations), __ATOMIC_RELAXED);
  421. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(t->list, d, prev, next);
  422. t->count++;
  423. info("STREAM: added streaming destination No %d: '%s' to host '%s'", t->count, string2str(d->destination), rrdhost_hostname(t->host));
  424. return false; // we return false, so that we will get all defined destinations
  425. }
  426. void rrdpush_destinations_init(RRDHOST *host) {
  427. if(!host->rrdpush_send_destination) return;
  428. rrdpush_destinations_free(host);
  429. struct destinations_init_tmp t = {
  430. .host = host,
  431. .list = NULL,
  432. .count = 0,
  433. };
  434. foreach_entry_in_connection_string(host->rrdpush_send_destination, destinations_init_add_one, &t);
  435. host->destinations = t.list;
  436. }
  437. void rrdpush_destinations_free(RRDHOST *host) {
  438. while (host->destinations) {
  439. struct rrdpush_destinations *tmp = host->destinations;
  440. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(host->destinations, tmp, prev, next);
  441. string_freez(tmp->destination);
  442. freez(tmp);
  443. __atomic_sub_fetch(&netdata_buffers_statistics.rrdhost_senders, sizeof(struct rrdpush_destinations), __ATOMIC_RELAXED);
  444. }
  445. host->destinations = NULL;
  446. }
  447. // ----------------------------------------------------------------------------
  448. // rrdpush sender thread
  449. // Either the receiver lost the connection or the host is being destroyed.
  450. // The sender mutex guards thread creation, any spurious data is wiped on reconnection.
  451. void rrdpush_sender_thread_stop(RRDHOST *host, const char *reason, bool wait) {
  452. if (!host->sender)
  453. return;
  454. netdata_mutex_lock(&host->sender->mutex);
  455. if(rrdhost_flag_check(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN)) {
  456. host->sender->exit.shutdown = true;
  457. host->sender->exit.reason = reason;
  458. // signal it to cancel
  459. netdata_thread_cancel(host->rrdpush_sender_thread);
  460. }
  461. netdata_mutex_unlock(&host->sender->mutex);
  462. if(wait) {
  463. netdata_mutex_lock(&host->sender->mutex);
  464. while(host->sender->tid) {
  465. netdata_mutex_unlock(&host->sender->mutex);
  466. sleep_usec(10 * USEC_PER_MS);
  467. netdata_mutex_lock(&host->sender->mutex);
  468. }
  469. netdata_mutex_unlock(&host->sender->mutex);
  470. }
  471. }
  472. // ----------------------------------------------------------------------------
  473. // rrdpush receiver thread
  474. void log_stream_connection(const char *client_ip, const char *client_port, const char *api_key, const char *machine_guid, const char *host, const char *msg) {
  475. log_access("STREAM: %d '[%s]:%s' '%s' host '%s' api key '%s' machine guid '%s'", gettid(), client_ip, client_port, msg, host, api_key, machine_guid);
  476. }
  477. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  478. netdata_mutex_lock(&host->sender->mutex);
  479. if(!rrdhost_flag_check(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN)) {
  480. char tag[NETDATA_THREAD_TAG_MAX + 1];
  481. snprintfz(tag, NETDATA_THREAD_TAG_MAX, THREAD_TAG_STREAM_SENDER "[%s]", rrdhost_hostname(host));
  482. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_sender_thread, (void *) host->sender))
  483. error("STREAM %s [send]: failed to create new thread for client.", rrdhost_hostname(host));
  484. else
  485. rrdhost_flag_set(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN);
  486. }
  487. netdata_mutex_unlock(&host->sender->mutex);
  488. }
  489. int rrdpush_receiver_permission_denied(struct web_client *w) {
  490. // we always respond with the same message and error code
  491. // to prevent an attacker from gaining info about the error
  492. buffer_flush(w->response.data);
  493. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  494. return HTTP_RESP_UNAUTHORIZED;
  495. }
  496. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  497. // we always respond with the same message and error code
  498. // to prevent an attacker from gaining info about the error
  499. buffer_flush(w->response.data);
  500. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  501. return HTTP_RESP_SERVICE_UNAVAILABLE;
  502. }
  503. void *rrdpush_receiver_thread(void *ptr);
  504. int rrdpush_receiver_thread_spawn(struct web_client *w, char *url) {
  505. if(!service_running(ABILITY_STREAMING_CONNECTIONS))
  506. return rrdpush_receiver_too_busy_now(w);
  507. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  508. rpt->last_msg_t = now_realtime_sec();
  509. rpt->capabilities = STREAM_CAP_INVALID;
  510. rpt->hops = 1;
  511. __atomic_add_fetch(&netdata_buffers_statistics.rrdhost_receivers, sizeof(*rpt), __ATOMIC_RELAXED);
  512. __atomic_add_fetch(&netdata_buffers_statistics.rrdhost_allocations_size, sizeof(struct rrdhost_system_info), __ATOMIC_RELAXED);
  513. rpt->system_info = callocz(1, sizeof(struct rrdhost_system_info));
  514. rpt->system_info->hops = rpt->hops;
  515. rpt->fd = w->ifd;
  516. rpt->client_ip = strdupz(w->client_ip);
  517. rpt->client_port = strdupz(w->client_port);
  518. rpt->config.update_every = default_rrd_update_every;
  519. #ifdef ENABLE_HTTPS
  520. rpt->ssl.conn = w->ssl.conn;
  521. rpt->ssl.flags = w->ssl.flags;
  522. w->ssl.conn = NULL;
  523. w->ssl.flags = NETDATA_SSL_START;
  524. #endif
  525. // parse the parameters and fill rpt and rpt->system_info
  526. while(url) {
  527. char *value = mystrsep(&url, "&");
  528. if(!value || !*value) continue;
  529. char *name = mystrsep(&value, "=");
  530. if(!name || !*name) continue;
  531. if(!value || !*value) continue;
  532. if(!strcmp(name, "key") && !rpt->key)
  533. rpt->key = strdupz(value);
  534. else if(!strcmp(name, "hostname") && !rpt->hostname)
  535. rpt->hostname = strdupz(value);
  536. else if(!strcmp(name, "registry_hostname") && !rpt->registry_hostname)
  537. rpt->registry_hostname = strdupz(value);
  538. else if(!strcmp(name, "machine_guid") && !rpt->machine_guid)
  539. rpt->machine_guid = strdupz(value);
  540. else if(!strcmp(name, "update_every"))
  541. rpt->config.update_every = (int)strtoul(value, NULL, 0);
  542. else if(!strcmp(name, "os") && !rpt->os)
  543. rpt->os = strdupz(value);
  544. else if(!strcmp(name, "timezone") && !rpt->timezone)
  545. rpt->timezone = strdupz(value);
  546. else if(!strcmp(name, "abbrev_timezone") && !rpt->abbrev_timezone)
  547. rpt->abbrev_timezone = strdupz(value);
  548. else if(!strcmp(name, "utc_offset"))
  549. rpt->utc_offset = (int32_t)strtol(value, NULL, 0);
  550. else if(!strcmp(name, "hops"))
  551. rpt->hops = rpt->system_info->hops = (uint16_t) strtoul(value, NULL, 0);
  552. else if(!strcmp(name, "ml_capable"))
  553. rpt->system_info->ml_capable = strtoul(value, NULL, 0);
  554. else if(!strcmp(name, "ml_enabled"))
  555. rpt->system_info->ml_enabled = strtoul(value, NULL, 0);
  556. else if(!strcmp(name, "mc_version"))
  557. rpt->system_info->mc_version = strtoul(value, NULL, 0);
  558. else if(!strcmp(name, "tags") && !rpt->tags)
  559. rpt->tags = strdupz(value);
  560. else if(!strcmp(name, "ver") && (rpt->capabilities & STREAM_CAP_INVALID))
  561. rpt->capabilities = convert_stream_version_to_capabilities(strtoul(value, NULL, 0));
  562. else {
  563. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  564. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  565. name = "NETDATA_HOST_OS_NAME";
  566. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  567. name = "NETDATA_HOST_OS_ID";
  568. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  569. name = "NETDATA_HOST_OS_ID_LIKE";
  570. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  571. name = "NETDATA_HOST_OS_VERSION";
  572. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  573. name = "NETDATA_HOST_OS_VERSION_ID";
  574. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  575. name = "NETDATA_HOST_OS_DETECTION";
  576. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && (rpt->capabilities & STREAM_CAP_INVALID))
  577. rpt->capabilities = convert_stream_version_to_capabilities(1);
  578. if (unlikely(rrdhost_set_system_info_variable(rpt->system_info, name, value))) {
  579. info("STREAM '%s' [receive from [%s]:%s]: "
  580. "request has parameter '%s' = '%s', which is not used."
  581. , (rpt->hostname && *rpt->hostname) ? rpt->hostname : "-"
  582. , rpt->client_ip, rpt->client_port
  583. , name, value);
  584. }
  585. }
  586. }
  587. if (rpt->capabilities & STREAM_CAP_INVALID)
  588. // no version is supplied, assume version 0;
  589. rpt->capabilities = convert_stream_version_to_capabilities(0);
  590. // find the program name and version
  591. if(w->user_agent && w->user_agent[0]) {
  592. char *t = strchr(w->user_agent, '/');
  593. if(t && *t) {
  594. *t = '\0';
  595. t++;
  596. }
  597. rpt->program_name = strdupz(w->user_agent);
  598. if(t && *t) rpt->program_version = strdupz(t);
  599. }
  600. // check if we should accept this connection
  601. if(!rpt->key || !*rpt->key) {
  602. rrdpush_receive_log_status(
  603. rpt,
  604. "request without an API key",
  605. "NO API KEY PERMISSION DENIED");
  606. receiver_state_free(rpt);
  607. return rrdpush_receiver_permission_denied(w);
  608. }
  609. if(!rpt->hostname || !*rpt->hostname) {
  610. rrdpush_receive_log_status(
  611. rpt,
  612. "request without a hostname",
  613. "NO HOSTNAME PERMISSION DENIED");
  614. receiver_state_free(rpt);
  615. return rrdpush_receiver_permission_denied(w);
  616. }
  617. if(!rpt->registry_hostname)
  618. rpt->registry_hostname = strdupz(rpt->hostname);
  619. if(!rpt->machine_guid || !*rpt->machine_guid) {
  620. rrdpush_receive_log_status(
  621. rpt,
  622. "request without a machine GUID",
  623. "NO MACHINE GUID PERMISSION DENIED");
  624. receiver_state_free(rpt);
  625. return rrdpush_receiver_permission_denied(w);
  626. }
  627. {
  628. char buf[GUID_LEN + 1];
  629. if (regenerate_guid(rpt->key, buf) == -1) {
  630. rrdpush_receive_log_status(
  631. rpt,
  632. "API key is not a valid UUID (use the command uuidgen to generate one)",
  633. "INVALID API KEY PERMISSION DENIED");
  634. receiver_state_free(rpt);
  635. return rrdpush_receiver_permission_denied(w);
  636. }
  637. if (regenerate_guid(rpt->machine_guid, buf) == -1) {
  638. rrdpush_receive_log_status(
  639. rpt,
  640. "machine GUID is not a valid UUID",
  641. "INVALID MACHINE GUID PERMISSION DENIED");
  642. receiver_state_free(rpt);
  643. return rrdpush_receiver_permission_denied(w);
  644. }
  645. }
  646. const char *api_key_type = appconfig_get(&stream_config, rpt->key, "type", "api");
  647. if(!api_key_type || !*api_key_type) api_key_type = "unknown";
  648. if(strcmp(api_key_type, "api") != 0) {
  649. rrdpush_receive_log_status(
  650. rpt,
  651. "API key is a machine GUID",
  652. "INVALID API KEY PERMISSION DENIED");
  653. receiver_state_free(rpt);
  654. return rrdpush_receiver_permission_denied(w);
  655. }
  656. if(!appconfig_get_boolean(&stream_config, rpt->key, "enabled", 0)) {
  657. rrdpush_receive_log_status(
  658. rpt,
  659. "API key is not enabled",
  660. "API KEY DISABLED PERMISSION DENIED");
  661. receiver_state_free(rpt);
  662. return rrdpush_receiver_permission_denied(w);
  663. }
  664. {
  665. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(
  666. appconfig_get(&stream_config, rpt->key, "allow from", "*"),
  667. NULL, SIMPLE_PATTERN_EXACT);
  668. if(key_allow_from) {
  669. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  670. simple_pattern_free(key_allow_from);
  671. rrdpush_receive_log_status(
  672. rpt,
  673. "API key is not allowed from this IP",
  674. "NOT ALLOWED IP PERMISSION DENIED");
  675. receiver_state_free(rpt);
  676. return rrdpush_receiver_permission_denied(w);
  677. }
  678. simple_pattern_free(key_allow_from);
  679. }
  680. }
  681. {
  682. const char *machine_guid_type = appconfig_get(&stream_config, rpt->machine_guid, "type", "machine");
  683. if (!machine_guid_type || !*machine_guid_type) machine_guid_type = "unknown";
  684. if (strcmp(machine_guid_type, "machine") != 0) {
  685. rrdpush_receive_log_status(
  686. rpt,
  687. "machine GUID is an API key",
  688. "INVALID MACHINE GUID PERMISSION DENIED");
  689. receiver_state_free(rpt);
  690. return rrdpush_receiver_permission_denied(w);
  691. }
  692. }
  693. if(!appconfig_get_boolean(&stream_config, rpt->machine_guid, "enabled", 1)) {
  694. rrdpush_receive_log_status(
  695. rpt,
  696. "machine GUID is not enabled",
  697. "MACHINE GUID DISABLED PERMISSION DENIED");
  698. receiver_state_free(rpt);
  699. return rrdpush_receiver_permission_denied(w);
  700. }
  701. {
  702. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(
  703. appconfig_get(&stream_config, rpt->machine_guid, "allow from", "*"),
  704. NULL, SIMPLE_PATTERN_EXACT);
  705. if(machine_allow_from) {
  706. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  707. simple_pattern_free(machine_allow_from);
  708. rrdpush_receive_log_status(
  709. rpt,
  710. "machine GUID is not allowed from this IP",
  711. "NOT ALLOWED IP PERMISSION DENIED");
  712. receiver_state_free(rpt);
  713. return rrdpush_receiver_permission_denied(w);
  714. }
  715. simple_pattern_free(machine_allow_from);
  716. }
  717. }
  718. if (strcmp(rpt->machine_guid, localhost->machine_guid) == 0) {
  719. rrdpush_receive_log_status(
  720. rpt,
  721. "machine GUID is my own",
  722. "LOCALHOST PERMISSION DENIED");
  723. char initial_response[HTTP_HEADER_SIZE + 1];
  724. snprintfz(initial_response, HTTP_HEADER_SIZE, "%s", START_STREAMING_ERROR_SAME_LOCALHOST);
  725. if(send_timeout(
  726. #ifdef ENABLE_HTTPS
  727. &rpt->ssl,
  728. #endif
  729. rpt->fd, initial_response, strlen(initial_response), 0, 60) != (ssize_t)strlen(initial_response)) {
  730. error("STREAM '%s' [receive from [%s]:%s]: "
  731. "failed to reply."
  732. , rpt->hostname
  733. , rpt->client_ip, rpt->client_port
  734. );
  735. }
  736. close(rpt->fd);
  737. receiver_state_free(rpt);
  738. return web_client_socket_is_now_used_for_streaming(w);
  739. }
  740. if(unlikely(web_client_streaming_rate_t > 0)) {
  741. static SPINLOCK spinlock = NETDATA_SPINLOCK_INITIALIZER;
  742. static time_t last_stream_accepted_t = 0;
  743. time_t now = now_realtime_sec();
  744. netdata_spinlock_lock(&spinlock);
  745. if(unlikely(last_stream_accepted_t == 0))
  746. last_stream_accepted_t = now;
  747. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  748. netdata_spinlock_unlock(&spinlock);
  749. char msg[100 + 1];
  750. snprintfz(msg, 100,
  751. "rate limit, will accept new connection in %ld secs",
  752. (long)(web_client_streaming_rate_t - (now - last_stream_accepted_t)));
  753. rrdpush_receive_log_status(
  754. rpt,
  755. msg,
  756. "RATE LIMIT TRY LATER");
  757. receiver_state_free(rpt);
  758. return rrdpush_receiver_too_busy_now(w);
  759. }
  760. last_stream_accepted_t = now;
  761. netdata_spinlock_unlock(&spinlock);
  762. }
  763. /*
  764. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  765. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  766. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  767. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  768. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  769. * lookup to the now-attached structure).
  770. */
  771. {
  772. time_t age = 0;
  773. bool receiver_stale = false;
  774. bool receiver_working = false;
  775. rrd_rdlock();
  776. RRDHOST *host = rrdhost_find_by_guid(rpt->machine_guid);
  777. if (unlikely(host && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) /* Ignore archived hosts. */
  778. host = NULL;
  779. if (host) {
  780. netdata_mutex_lock(&host->receiver_lock);
  781. if (host->receiver) {
  782. age = now_realtime_sec() - host->receiver->last_msg_t;
  783. if (age < 30)
  784. receiver_working = true;
  785. else
  786. receiver_stale = true;
  787. }
  788. netdata_mutex_unlock(&host->receiver_lock);
  789. }
  790. rrd_unlock();
  791. if (receiver_stale && stop_streaming_receiver(host, "STALE RECEIVER")) {
  792. // we stopped the receiver
  793. // we can proceed with this connection
  794. receiver_stale = false;
  795. info("STREAM '%s' [receive from [%s]:%s]: "
  796. "stopped previous stale receiver to accept this one."
  797. , rpt->hostname
  798. , rpt->client_ip, rpt->client_port
  799. );
  800. }
  801. if (receiver_working || receiver_stale) {
  802. // another receiver is already connected
  803. // try again later
  804. char msg[200 + 1];
  805. snprintfz(msg, 200,
  806. "multiple connections for same host, "
  807. "old connection was used %ld secs ago%s",
  808. age, receiver_stale ? " (signaled old receiver to stop)" : " (new connection not accepted)");
  809. rrdpush_receive_log_status(
  810. rpt,
  811. msg,
  812. "ALREADY CONNECTED");
  813. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  814. buffer_flush(w->response.data);
  815. buffer_strcat(w->response.data, "This GUID is already streaming to this server");
  816. receiver_state_free(rpt);
  817. return HTTP_RESP_CONFLICT;
  818. }
  819. }
  820. debug(D_SYSTEM, "starting STREAM receive thread.");
  821. char tag[FILENAME_MAX + 1];
  822. snprintfz(tag, FILENAME_MAX, THREAD_TAG_STREAM_RECEIVER "[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  823. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt)) {
  824. rrdpush_receive_log_status(
  825. rpt,
  826. "can't create receiver thread",
  827. "INTERNAL SERVER ERROR");
  828. buffer_flush(w->response.data);
  829. buffer_strcat(w->response.data, "Can't handle this request");
  830. receiver_state_free(rpt);
  831. return HTTP_RESP_INTERNAL_SERVER_ERROR;
  832. }
  833. // prevent the caller from closing the streaming socket
  834. return web_client_socket_is_now_used_for_streaming(w);
  835. }
  836. static void stream_capabilities_to_string(BUFFER *wb, STREAM_CAPABILITIES caps) {
  837. if(caps & STREAM_CAP_V1) buffer_strcat(wb, "V1 ");
  838. if(caps & STREAM_CAP_V2) buffer_strcat(wb, "V2 ");
  839. if(caps & STREAM_CAP_VN) buffer_strcat(wb, "VN ");
  840. if(caps & STREAM_CAP_VCAPS) buffer_strcat(wb, "VCAPS ");
  841. if(caps & STREAM_CAP_HLABELS) buffer_strcat(wb, "HLABELS ");
  842. if(caps & STREAM_CAP_CLAIM) buffer_strcat(wb, "CLAIM ");
  843. if(caps & STREAM_CAP_CLABELS) buffer_strcat(wb, "CLABELS ");
  844. if(caps & STREAM_CAP_COMPRESSION) buffer_strcat(wb, "COMPRESSION ");
  845. if(caps & STREAM_CAP_FUNCTIONS) buffer_strcat(wb, "FUNCTIONS ");
  846. if(caps & STREAM_CAP_REPLICATION) buffer_strcat(wb, "REPLICATION ");
  847. if(caps & STREAM_CAP_BINARY) buffer_strcat(wb, "BINARY ");
  848. }
  849. void log_receiver_capabilities(struct receiver_state *rpt) {
  850. BUFFER *wb = buffer_create(100, NULL);
  851. stream_capabilities_to_string(wb, rpt->capabilities);
  852. info("STREAM %s [receive from [%s]:%s]: established link with negotiated capabilities: %s",
  853. rrdhost_hostname(rpt->host), rpt->client_ip, rpt->client_port, buffer_tostring(wb));
  854. buffer_free(wb);
  855. }
  856. void log_sender_capabilities(struct sender_state *s) {
  857. BUFFER *wb = buffer_create(100, NULL);
  858. stream_capabilities_to_string(wb, s->capabilities);
  859. info("STREAM %s [send to %s]: established link with negotiated capabilities: %s",
  860. rrdhost_hostname(s->host), s->connected_to, buffer_tostring(wb));
  861. buffer_free(wb);
  862. }
  863. STREAM_CAPABILITIES convert_stream_version_to_capabilities(int32_t version) {
  864. STREAM_CAPABILITIES caps = 0;
  865. if(version <= 1) caps = STREAM_CAP_V1;
  866. else if(version < STREAM_OLD_VERSION_CLAIM) caps = STREAM_CAP_V2 | STREAM_CAP_HLABELS;
  867. else if(version <= STREAM_OLD_VERSION_CLAIM) caps = STREAM_CAP_VN | STREAM_CAP_HLABELS | STREAM_CAP_CLAIM;
  868. else if(version <= STREAM_OLD_VERSION_CLABELS) caps = STREAM_CAP_VN | STREAM_CAP_HLABELS | STREAM_CAP_CLAIM | STREAM_CAP_CLABELS;
  869. else if(version <= STREAM_OLD_VERSION_COMPRESSION) caps = STREAM_CAP_VN | STREAM_CAP_HLABELS | STREAM_CAP_CLAIM | STREAM_CAP_CLABELS | STREAM_HAS_COMPRESSION;
  870. else caps = version;
  871. if(caps & STREAM_CAP_VCAPS)
  872. caps &= ~(STREAM_CAP_V1|STREAM_CAP_V2|STREAM_CAP_VN);
  873. if(caps & STREAM_CAP_VN)
  874. caps &= ~(STREAM_CAP_V1|STREAM_CAP_V2);
  875. if(caps & STREAM_CAP_V2)
  876. caps &= ~(STREAM_CAP_V1);
  877. return caps & STREAM_OUR_CAPABILITIES;
  878. }
  879. int32_t stream_capabilities_to_vn(uint32_t caps) {
  880. if(caps & STREAM_CAP_COMPRESSION) return STREAM_OLD_VERSION_COMPRESSION;
  881. if(caps & STREAM_CAP_CLABELS) return STREAM_OLD_VERSION_CLABELS;
  882. return STREAM_OLD_VERSION_CLAIM; // if(caps & STREAM_CAP_CLAIM)
  883. }