dictionary.c 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. // NOT TO BE USED BY USERS
  3. #define DICTIONARY_FLAG_EXCLUSIVE_ACCESS (1 << 29) // there is only one thread accessing the dictionary
  4. #define DICTIONARY_FLAG_DESTROYED (1 << 30) // this dictionary has been destroyed
  5. #define DICTIONARY_FLAG_DEFER_ALL_DELETIONS (1 << 31) // defer all deletions of items in the dictionary
  6. // our reserved flags that cannot be set by users
  7. #define DICTIONARY_FLAGS_RESERVED (DICTIONARY_FLAG_EXCLUSIVE_ACCESS|DICTIONARY_FLAG_DESTROYED|DICTIONARY_FLAG_DEFER_ALL_DELETIONS)
  8. typedef struct dictionary DICTIONARY;
  9. #define DICTIONARY_INTERNALS
  10. #include "../libnetdata.h"
  11. #ifndef ENABLE_DBENGINE
  12. #define DICTIONARY_WITH_AVL
  13. #warning Compiling DICTIONARY with an AVL index
  14. #else
  15. #define DICTIONARY_WITH_JUDYHS
  16. #endif
  17. #ifdef DICTIONARY_WITH_JUDYHS
  18. #include <Judy.h>
  19. #endif
  20. typedef enum name_value_flags {
  21. NAME_VALUE_FLAG_NONE = 0,
  22. NAME_VALUE_FLAG_NAME_IS_ALLOCATED = (1 << 0), // the name pointer is a STRING
  23. NAME_VALUE_FLAG_DELETED = (1 << 1), // this item is deleted, so it is not available for traversal
  24. NAME_VALUE_FLAG_NEW_OR_UPDATED = (1 << 2), // this item is new or just updated (used by the react callback)
  25. // IMPORTANT: IF YOU ADD ANOTHER FLAG, YOU NEED TO ALLOCATE ANOTHER BIT TO FLAGS IN NAME_VALUE !!!
  26. } NAME_VALUE_FLAGS;
  27. /*
  28. * Every item in the dictionary has the following structure.
  29. */
  30. typedef struct name_value {
  31. #ifdef DICTIONARY_WITH_AVL
  32. avl_t avl_node;
  33. #endif
  34. #ifdef NETDATA_INTERNAL_CHECKS
  35. DICTIONARY *dict;
  36. #endif
  37. struct name_value *next; // a double linked list to allow fast insertions and deletions
  38. struct name_value *prev;
  39. uint32_t refcount; // the reference counter
  40. uint32_t value_len:29; // the size of the value (assumed binary)
  41. uint8_t flags:3; // the flags for this item
  42. void *value; // the value of the dictionary item
  43. union {
  44. STRING *string_name; // the name of the dictionary item
  45. char *caller_name; // the user supplied string pointer
  46. };
  47. } NAME_VALUE;
  48. struct dictionary {
  49. #ifdef NETDATA_INTERNAL_CHECKS
  50. const char *creation_function;
  51. const char *creation_file;
  52. size_t creation_line;
  53. #endif
  54. DICTIONARY_FLAGS flags; // the flags of the dictionary
  55. NAME_VALUE *first_item; // the double linked list base pointers
  56. NAME_VALUE *last_item;
  57. #ifdef DICTIONARY_WITH_AVL
  58. avl_tree_type values_index;
  59. NAME_VALUE *hash_base;
  60. void *(*get_thread_static_name_value)(const char *name);
  61. #endif
  62. #ifdef DICTIONARY_WITH_JUDYHS
  63. Pvoid_t JudyHSArray; // the hash table
  64. #endif
  65. netdata_rwlock_t rwlock; // the r/w lock when DICTIONARY_FLAG_SINGLE_THREADED is not set
  66. void (*ins_callback)(const char *name, void *value, void *data);
  67. void *ins_callback_data;
  68. void (*react_callback)(const char *name, void *value, void *data);
  69. void *react_callback_data;
  70. void (*del_callback)(const char *name, void *value, void *data);
  71. void *del_callback_data;
  72. void (*conflict_callback)(const char *name, void *old_value, void *new_value, void *data);
  73. void *conflict_callback_data;
  74. size_t version; // the current version of the dictionary
  75. size_t inserts; // how many index insertions have been performed
  76. size_t deletes; // how many index deletions have been performed
  77. size_t searches; // how many index searches have been performed
  78. size_t resets; // how many times items have reset their values
  79. size_t walkthroughs; // how many walkthroughs have been done
  80. long int memory; // how much memory the dictionary has currently allocated
  81. long int entries; // how many items are currently in the index (the linked list may have more)
  82. long int referenced_items; // how many items of the dictionary are currently being used by 3rd parties
  83. long int pending_deletion_items; // how many items of the dictionary have been deleted, but have not been removed yet
  84. int readers; // how many readers are currently using the dictionary
  85. int writers; // how many writers are currently using the dictionary
  86. size_t scratchpad_size; // the size of the scratchpad in bytes
  87. uint8_t scratchpad[]; // variable size scratchpad requested by the caller
  88. };
  89. static inline void linkedlist_namevalue_unlink_unsafe(DICTIONARY *dict, NAME_VALUE *nv);
  90. static size_t namevalue_destroy_unsafe(DICTIONARY *dict, NAME_VALUE *nv);
  91. static inline const char *namevalue_get_name(NAME_VALUE *nv);
  92. // ----------------------------------------------------------------------------
  93. // callbacks registration
  94. void dictionary_register_insert_callback(DICTIONARY *dict, void (*ins_callback)(const char *name, void *value, void *data), void *data) {
  95. dict->ins_callback = ins_callback;
  96. dict->ins_callback_data = data;
  97. }
  98. void dictionary_register_delete_callback(DICTIONARY *dict, void (*del_callback)(const char *name, void *value, void *data), void *data) {
  99. dict->del_callback = del_callback;
  100. dict->del_callback_data = data;
  101. }
  102. void dictionary_register_conflict_callback(DICTIONARY *dict, void (*conflict_callback)(const char *name, void *old_value, void *new_value, void *data), void *data) {
  103. dict->conflict_callback = conflict_callback;
  104. dict->conflict_callback_data = data;
  105. }
  106. void dictionary_register_react_callback(DICTIONARY *dict, void (*react_callback)(const char *name, void *value, void *data), void *data) {
  107. dict->react_callback = react_callback;
  108. dict->react_callback_data = data;
  109. }
  110. // ----------------------------------------------------------------------------
  111. // dictionary statistics maintenance
  112. long int dictionary_stats_allocated_memory(DICTIONARY *dict) {
  113. return dict->memory;
  114. }
  115. long int dictionary_stats_entries(DICTIONARY *dict) {
  116. return dict->entries;
  117. }
  118. size_t dictionary_stats_version(DICTIONARY *dict) {
  119. return dict->version;
  120. }
  121. size_t dictionary_stats_searches(DICTIONARY *dict) {
  122. return dict->searches;
  123. }
  124. size_t dictionary_stats_inserts(DICTIONARY *dict) {
  125. return dict->inserts;
  126. }
  127. size_t dictionary_stats_deletes(DICTIONARY *dict) {
  128. return dict->deletes;
  129. }
  130. size_t dictionary_stats_resets(DICTIONARY *dict) {
  131. return dict->resets;
  132. }
  133. size_t dictionary_stats_walkthroughs(DICTIONARY *dict) {
  134. return dict->walkthroughs;
  135. }
  136. size_t dictionary_stats_referenced_items(DICTIONARY *dict) {
  137. return __atomic_load_n(&dict->referenced_items, __ATOMIC_SEQ_CST);
  138. }
  139. static inline void DICTIONARY_STATS_SEARCHES_PLUS1(DICTIONARY *dict) {
  140. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  141. dict->searches++;
  142. }
  143. else {
  144. __atomic_fetch_add(&dict->searches, 1, __ATOMIC_RELAXED);
  145. }
  146. }
  147. static inline void DICTIONARY_STATS_ENTRIES_PLUS1(DICTIONARY *dict, size_t size) {
  148. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  149. dict->version++;
  150. dict->inserts++;
  151. dict->entries++;
  152. dict->memory += (long)size;
  153. }
  154. else {
  155. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  156. __atomic_fetch_add(&dict->inserts, 1, __ATOMIC_RELAXED);
  157. __atomic_fetch_add(&dict->entries, 1, __ATOMIC_RELAXED);
  158. __atomic_fetch_add(&dict->memory, (long)size, __ATOMIC_RELAXED);
  159. }
  160. }
  161. static inline void DICTIONARY_STATS_ENTRIES_MINUS1(DICTIONARY *dict) {
  162. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  163. dict->version++;
  164. dict->deletes++;
  165. dict->entries--;
  166. }
  167. else {
  168. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  169. __atomic_fetch_add(&dict->deletes, 1, __ATOMIC_RELAXED);
  170. __atomic_fetch_sub(&dict->entries, 1, __ATOMIC_RELAXED);
  171. }
  172. }
  173. static inline void DICTIONARY_STATS_ENTRIES_MINUS_MEMORY(DICTIONARY *dict, size_t size) {
  174. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  175. dict->memory -= (long)size;
  176. }
  177. else {
  178. __atomic_fetch_sub(&dict->memory, (long)size, __ATOMIC_RELAXED);
  179. }
  180. }
  181. static inline void DICTIONARY_STATS_VALUE_RESETS_PLUS1(DICTIONARY *dict, size_t oldsize, size_t newsize) {
  182. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  183. dict->version++;
  184. dict->resets++;
  185. dict->memory += (long)newsize;
  186. dict->memory -= (long)oldsize;
  187. }
  188. else {
  189. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  190. __atomic_fetch_add(&dict->resets, 1, __ATOMIC_RELAXED);
  191. __atomic_fetch_add(&dict->memory, (long)newsize, __ATOMIC_RELAXED);
  192. __atomic_fetch_sub(&dict->memory, (long)oldsize, __ATOMIC_RELAXED);
  193. }
  194. }
  195. static inline void DICTIONARY_STATS_WALKTHROUGHS_PLUS1(DICTIONARY *dict) {
  196. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  197. dict->walkthroughs++;
  198. }
  199. else {
  200. __atomic_fetch_add(&dict->walkthroughs, 1, __ATOMIC_RELAXED);
  201. }
  202. }
  203. static inline size_t DICTIONARY_STATS_REFERENCED_ITEMS_PLUS1(DICTIONARY *dict) {
  204. return __atomic_add_fetch(&dict->referenced_items, 1, __ATOMIC_SEQ_CST);
  205. }
  206. static inline size_t DICTIONARY_STATS_REFERENCED_ITEMS_MINUS1(DICTIONARY *dict) {
  207. return __atomic_sub_fetch(&dict->referenced_items, 1, __ATOMIC_SEQ_CST);
  208. }
  209. static inline size_t DICTIONARY_STATS_PENDING_DELETES_PLUS1(DICTIONARY *dict) {
  210. return __atomic_add_fetch(&dict->pending_deletion_items, 1, __ATOMIC_SEQ_CST);
  211. }
  212. static inline size_t DICTIONARY_STATS_PENDING_DELETES_MINUS1(DICTIONARY *dict) {
  213. return __atomic_sub_fetch(&dict->pending_deletion_items, 1, __ATOMIC_SEQ_CST);
  214. }
  215. static inline size_t DICTIONARY_STATS_PENDING_DELETES_GET(DICTIONARY *dict) {
  216. return __atomic_load_n(&dict->pending_deletion_items, __ATOMIC_SEQ_CST);
  217. }
  218. static inline int DICTIONARY_NAME_VALUE_REFCOUNT_GET(NAME_VALUE *nv) {
  219. return __atomic_load_n(&nv->refcount, __ATOMIC_SEQ_CST);
  220. }
  221. // ----------------------------------------------------------------------------
  222. // garbage collector
  223. // it is called every time someone gets a write lock to the dictionary
  224. static void garbage_collect_pending_deletes_unsafe(DICTIONARY *dict) {
  225. if(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS)) return;
  226. if(likely(!DICTIONARY_STATS_PENDING_DELETES_GET(dict))) return;
  227. NAME_VALUE *nv = dict->first_item;
  228. while(nv) {
  229. if((nv->flags & NAME_VALUE_FLAG_DELETED) && DICTIONARY_NAME_VALUE_REFCOUNT_GET(nv) == 0) {
  230. NAME_VALUE *nv_next = nv->next;
  231. linkedlist_namevalue_unlink_unsafe(dict, nv);
  232. namevalue_destroy_unsafe(dict, nv);
  233. size_t pending = DICTIONARY_STATS_PENDING_DELETES_MINUS1(dict);
  234. if(!pending) break;
  235. nv = nv_next;
  236. }
  237. else
  238. nv = nv->next;
  239. }
  240. }
  241. // ----------------------------------------------------------------------------
  242. // dictionary locks
  243. static inline size_t dictionary_lock_init(DICTIONARY *dict) {
  244. if(likely(!(dict->flags & DICTIONARY_FLAG_SINGLE_THREADED))) {
  245. netdata_rwlock_init(&dict->rwlock);
  246. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS)
  247. dict->flags &= ~DICTIONARY_FLAG_EXCLUSIVE_ACCESS;
  248. return 0;
  249. }
  250. // we are single threaded
  251. dict->flags |= DICTIONARY_FLAG_EXCLUSIVE_ACCESS;
  252. return 0;
  253. }
  254. static inline size_t dictionary_lock_free(DICTIONARY *dict) {
  255. if(likely(!(dict->flags & DICTIONARY_FLAG_SINGLE_THREADED))) {
  256. netdata_rwlock_destroy(&dict->rwlock);
  257. return 0;
  258. }
  259. return 0;
  260. }
  261. static void dictionary_lock(DICTIONARY *dict, char rw) {
  262. if(rw == 'u' || rw == 'U') return;
  263. if(rw == 'r' || rw == 'R') {
  264. // read lock
  265. __atomic_add_fetch(&dict->readers, 1, __ATOMIC_RELAXED);
  266. }
  267. else {
  268. // write lock
  269. __atomic_add_fetch(&dict->writers, 1, __ATOMIC_RELAXED);
  270. }
  271. if(likely(dict->flags & DICTIONARY_FLAG_SINGLE_THREADED))
  272. return;
  273. if(rw == 'r' || rw == 'R') {
  274. // read lock
  275. netdata_rwlock_rdlock(&dict->rwlock);
  276. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS) {
  277. internal_error(true, "DICTIONARY: left-over exclusive access to dictionary created by %s (%zu@%s) found", dict->creation_function, dict->creation_line, dict->creation_file);
  278. dict->flags &= ~DICTIONARY_FLAG_EXCLUSIVE_ACCESS;
  279. }
  280. }
  281. else {
  282. // write lock
  283. netdata_rwlock_wrlock(&dict->rwlock);
  284. dict->flags |= DICTIONARY_FLAG_EXCLUSIVE_ACCESS;
  285. }
  286. }
  287. static void dictionary_unlock(DICTIONARY *dict, char rw) {
  288. if(rw == 'u' || rw == 'U') return;
  289. if(rw == 'r' || rw == 'R') {
  290. // read unlock
  291. __atomic_sub_fetch(&dict->readers, 1, __ATOMIC_RELAXED);
  292. }
  293. else {
  294. // write unlock
  295. garbage_collect_pending_deletes_unsafe(dict);
  296. __atomic_sub_fetch(&dict->writers, 1, __ATOMIC_RELAXED);
  297. }
  298. if(likely(dict->flags & DICTIONARY_FLAG_SINGLE_THREADED))
  299. return;
  300. if(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS)
  301. dict->flags &= ~DICTIONARY_FLAG_EXCLUSIVE_ACCESS;
  302. netdata_rwlock_unlock(&dict->rwlock);
  303. }
  304. // ----------------------------------------------------------------------------
  305. // deferred deletions
  306. void dictionary_defer_all_deletions_unsafe(DICTIONARY *dict, char rw) {
  307. if(rw == 'r' || rw == 'R') {
  308. // read locked - no need to defer deletions
  309. ;
  310. }
  311. else {
  312. // write locked - defer deletions
  313. dict->flags |= DICTIONARY_FLAG_DEFER_ALL_DELETIONS;
  314. }
  315. }
  316. void dictionary_restore_all_deletions_unsafe(DICTIONARY *dict, char rw) {
  317. if(rw == 'r' || rw == 'R') {
  318. // read locked - no need to defer deletions
  319. internal_error(dict->flags & DICTIONARY_FLAG_DEFER_ALL_DELETIONS, "DICTIONARY: deletions are deferred on a read lock");
  320. }
  321. else {
  322. // write locked - defer deletions
  323. if(dict->flags & DICTIONARY_FLAG_DEFER_ALL_DELETIONS)
  324. dict->flags &= ~DICTIONARY_FLAG_DEFER_ALL_DELETIONS;
  325. }
  326. }
  327. // ----------------------------------------------------------------------------
  328. // reference counters
  329. static inline size_t reference_counter_init(DICTIONARY *dict) {
  330. (void)dict;
  331. // allocate memory required for reference counters
  332. // return number of bytes
  333. return 0;
  334. }
  335. static inline size_t reference_counter_free(DICTIONARY *dict) {
  336. (void)dict;
  337. // free memory required for reference counters
  338. // return number of bytes
  339. return 0;
  340. }
  341. static int reference_counter_increase(NAME_VALUE *nv) {
  342. int refcount = __atomic_add_fetch(&nv->refcount, 1, __ATOMIC_SEQ_CST);
  343. if(refcount == 1)
  344. fatal("DICTIONARY: request to dup item '%s' but its reference counter was zero", namevalue_get_name(nv));
  345. return refcount;
  346. }
  347. static int reference_counter_acquire(DICTIONARY *dict, NAME_VALUE *nv) {
  348. int refcount;
  349. if(likely(dict->flags & DICTIONARY_FLAG_SINGLE_THREADED))
  350. refcount = ++nv->refcount;
  351. else
  352. refcount = __atomic_add_fetch(&nv->refcount, 1, __ATOMIC_SEQ_CST);
  353. if(refcount == 1) {
  354. // referenced items counts number of unique items referenced
  355. // so, we increase it only when refcount == 1
  356. DICTIONARY_STATS_REFERENCED_ITEMS_PLUS1(dict);
  357. // if this is a deleted item, but the counter increased to 1
  358. // we need to remove it from the pending items to delete
  359. if (nv->flags & NAME_VALUE_FLAG_DELETED)
  360. DICTIONARY_STATS_PENDING_DELETES_MINUS1(dict);
  361. }
  362. return refcount;
  363. }
  364. static uint32_t reference_counter_release(DICTIONARY *dict, NAME_VALUE *nv, bool can_get_write_lock) {
  365. // this function may be called without any lock on the dictionary
  366. // or even when someone else has a write lock on the dictionary
  367. // so, we cannot check for EXCLUSIVE ACCESS
  368. uint32_t refcount;
  369. if(likely(dict->flags & DICTIONARY_FLAG_SINGLE_THREADED))
  370. refcount = nv->refcount--;
  371. else
  372. refcount = __atomic_fetch_sub(&nv->refcount, 1, __ATOMIC_SEQ_CST);
  373. if(refcount == 0) {
  374. internal_error(true, "DICTIONARY: attempted to release item without references: '%s' on dictionary created by %s() (%zu@%s)", namevalue_get_name(nv), dict->creation_function, dict->creation_line, dict->creation_file);
  375. fatal("DICTIONARY: attempted to release item without references: '%s'", namevalue_get_name(nv));
  376. }
  377. if(refcount == 1) {
  378. if((nv->flags & NAME_VALUE_FLAG_DELETED))
  379. DICTIONARY_STATS_PENDING_DELETES_PLUS1(dict);
  380. // referenced items counts number of unique items referenced
  381. // so, we decrease it only when refcount == 0
  382. DICTIONARY_STATS_REFERENCED_ITEMS_MINUS1(dict);
  383. }
  384. if(can_get_write_lock && DICTIONARY_STATS_PENDING_DELETES_GET(dict)) {
  385. // we can garbage collect now
  386. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  387. garbage_collect_pending_deletes_unsafe(dict);
  388. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  389. }
  390. return refcount;
  391. }
  392. // ----------------------------------------------------------------------------
  393. // hash table
  394. #ifdef DICTIONARY_WITH_AVL
  395. static inline const char *namevalue_get_name(NAME_VALUE *nv);
  396. static int name_value_compare(void* a, void* b) {
  397. return strcmp(namevalue_get_name((NAME_VALUE *)a), namevalue_get_name((NAME_VALUE *)b));
  398. }
  399. static void *get_thread_static_name_value(const char *name) {
  400. static __thread NAME_VALUE tmp = { 0 };
  401. tmp.flags = NAME_VALUE_FLAG_NONE;
  402. tmp.caller_name = (char *)name;
  403. return &tmp;
  404. }
  405. static void hashtable_init_unsafe(DICTIONARY *dict) {
  406. avl_init(&dict->values_index, name_value_compare);
  407. dict->get_thread_static_name_value = get_thread_static_name_value;
  408. }
  409. static size_t hashtable_destroy_unsafe(DICTIONARY *dict) {
  410. (void)dict;
  411. return 0;
  412. }
  413. static inline int hashtable_delete_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *nv) {
  414. (void)name;
  415. (void)name_len;
  416. if(unlikely(avl_remove(&(dict->values_index), (avl_t *)(nv)) != (avl_t *)nv))
  417. return 0;
  418. return 1;
  419. }
  420. static inline NAME_VALUE *hashtable_get_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  421. (void)name_len;
  422. void *tmp = dict->get_thread_static_name_value(name);
  423. return (NAME_VALUE *)avl_search(&(dict->values_index), (avl_t *)tmp);
  424. }
  425. static inline NAME_VALUE **hashtable_insert_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  426. // AVL needs a NAME_VALUE to insert into the dictionary but we don't have it yet.
  427. // So, the only thing we can do, is return an existing one if it is already there.
  428. // Returning NULL will make the caller thing we added it, will allocate one
  429. // and will call hashtable_inserted_name_value_unsafe(), at which we will do
  430. // the actual indexing.
  431. dict->hash_base = hashtable_get_unsafe(dict, name, name_len);
  432. return &dict->hash_base;
  433. }
  434. static inline void hashtable_inserted_name_value_unsafe(DICTIONARY *dict, void *nv) {
  435. // we have our new NAME_VALUE object.
  436. // Let's index it.
  437. if(unlikely(avl_insert(&((dict)->values_index), (avl_t *)(nv)) != (avl_t *)nv))
  438. error("dictionary: INTERNAL ERROR: duplicate insertion to dictionary.");
  439. }
  440. #endif
  441. #ifdef DICTIONARY_WITH_JUDYHS
  442. static void hashtable_init_unsafe(DICTIONARY *dict) {
  443. dict->JudyHSArray = NULL;
  444. }
  445. static size_t hashtable_destroy_unsafe(DICTIONARY *dict) {
  446. if(unlikely(!dict->JudyHSArray)) return 0;
  447. JError_t J_Error;
  448. Word_t ret = JudyHSFreeArray(&dict->JudyHSArray, &J_Error);
  449. if(unlikely(ret == (Word_t) JERR)) {
  450. error("DICTIONARY: Cannot destroy JudyHS, JU_ERRNO_* == %u, ID == %d",
  451. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  452. }
  453. debug(D_DICTIONARY, "Dictionary: hash table freed %lu bytes", ret);
  454. dict->JudyHSArray = NULL;
  455. return (size_t)ret;
  456. }
  457. static inline NAME_VALUE **hashtable_insert_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  458. internal_error(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS), "DICTIONARY: inserting item from the index without exclusive access to the dictionary created by %s() (%zu@%s)", dict->creation_function, dict->creation_line, dict->creation_file);
  459. JError_t J_Error;
  460. Pvoid_t *Rc = JudyHSIns(&dict->JudyHSArray, (void *)name, name_len, &J_Error);
  461. if (unlikely(Rc == PJERR)) {
  462. fatal("DICTIONARY: Cannot insert entry with name '%s' to JudyHS, JU_ERRNO_* == %u, ID == %d",
  463. name, JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  464. }
  465. // if *Rc == 0, new item added to the array
  466. // otherwise the existing item value is returned in *Rc
  467. // we return a pointer to a pointer, so that the caller can
  468. // put anything needed at the value of the index.
  469. // The pointer to pointer we return has to be used before
  470. // any other operation that may change the index (insert/delete).
  471. return (NAME_VALUE **)Rc;
  472. }
  473. static inline int hashtable_delete_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *nv) {
  474. internal_error(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS), "DICTIONARY: deleting item from the index without exclusive access to the dictionary created by %s() (%zu@%s)", dict->creation_function, dict->creation_line, dict->creation_file);
  475. (void)nv;
  476. if(unlikely(!dict->JudyHSArray)) return 0;
  477. JError_t J_Error;
  478. int ret = JudyHSDel(&dict->JudyHSArray, (void *)name, name_len, &J_Error);
  479. if(unlikely(ret == JERR)) {
  480. error("DICTIONARY: Cannot delete entry with name '%s' from JudyHS, JU_ERRNO_* == %u, ID == %d", name,
  481. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  482. return 0;
  483. }
  484. // Hey, this is problematic! We need the value back, not just an int with a status!
  485. // https://sourceforge.net/p/judy/feature-requests/23/
  486. if(unlikely(ret == 0)) {
  487. // not found in the dictionary
  488. return 0;
  489. }
  490. else {
  491. // found and deleted from the dictionary
  492. return 1;
  493. }
  494. }
  495. static inline NAME_VALUE *hashtable_get_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  496. if(unlikely(!dict->JudyHSArray)) return NULL;
  497. DICTIONARY_STATS_SEARCHES_PLUS1(dict);
  498. Pvoid_t *Rc;
  499. Rc = JudyHSGet(dict->JudyHSArray, (void *)name, name_len);
  500. if(likely(Rc)) {
  501. // found in the hash table
  502. return (NAME_VALUE *)*Rc;
  503. }
  504. else {
  505. // not found in the hash table
  506. return NULL;
  507. }
  508. }
  509. static inline void hashtable_inserted_name_value_unsafe(DICTIONARY *dict, void *nv) {
  510. (void)dict;
  511. (void)nv;
  512. ;
  513. }
  514. #endif // DICTIONARY_WITH_JUDYHS
  515. // ----------------------------------------------------------------------------
  516. // linked list management
  517. static inline void linkedlist_namevalue_link_unsafe(DICTIONARY *dict, NAME_VALUE *nv) {
  518. internal_error(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS), "DICTIONARY: adding item to the linked-list without exclusive access to the dictionary created by %s() (%zu@%s)", dict->creation_function, dict->creation_line, dict->creation_file);
  519. if (unlikely(!dict->first_item)) {
  520. // we are the only ones here
  521. nv->next = NULL;
  522. nv->prev = NULL;
  523. dict->first_item = dict->last_item = nv;
  524. return;
  525. }
  526. if(dict->flags & DICTIONARY_FLAG_ADD_IN_FRONT) {
  527. // add it at the beginning
  528. nv->prev = NULL;
  529. nv->next = dict->first_item;
  530. if (likely(nv->next)) nv->next->prev = nv;
  531. dict->first_item = nv;
  532. }
  533. else {
  534. // add it at the end
  535. nv->next = NULL;
  536. nv->prev = dict->last_item;
  537. if (likely(nv->prev)) nv->prev->next = nv;
  538. dict->last_item = nv;
  539. }
  540. }
  541. static inline void linkedlist_namevalue_unlink_unsafe(DICTIONARY *dict, NAME_VALUE *nv) {
  542. internal_error(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS), "DICTIONARY: removing item from the linked-list without exclusive access to the dictionary created by %s() (%zu@%s)", dict->creation_function, dict->creation_line, dict->creation_file);
  543. if(nv->next) nv->next->prev = nv->prev;
  544. if(nv->prev) nv->prev->next = nv->next;
  545. if(dict->first_item == nv) dict->first_item = nv->next;
  546. if(dict->last_item == nv) dict->last_item = nv->prev;
  547. }
  548. // ----------------------------------------------------------------------------
  549. // NAME_VALUE methods
  550. static inline size_t namevalue_set_name(DICTIONARY *dict, NAME_VALUE *nv, const char *name, size_t name_len) {
  551. if(likely(dict->flags & DICTIONARY_FLAG_NAME_LINK_DONT_CLONE)) {
  552. nv->caller_name = (char *)name;
  553. return 0;
  554. }
  555. nv->string_name = string_strdupz(name);
  556. nv->flags |= NAME_VALUE_FLAG_NAME_IS_ALLOCATED;
  557. return name_len;
  558. }
  559. static inline size_t namevalue_free_name(DICTIONARY *dict, NAME_VALUE *nv) {
  560. if(unlikely(!(dict->flags & DICTIONARY_FLAG_NAME_LINK_DONT_CLONE)))
  561. string_freez(nv->string_name);
  562. return 0;
  563. }
  564. static inline const char *namevalue_get_name(NAME_VALUE *nv) {
  565. if(nv->flags & NAME_VALUE_FLAG_NAME_IS_ALLOCATED)
  566. return string2str(nv->string_name);
  567. else
  568. return nv->caller_name;
  569. }
  570. static NAME_VALUE *namevalue_create_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *value, size_t value_len) {
  571. debug(D_DICTIONARY, "Creating name value entry for name '%s'.", name);
  572. size_t size = sizeof(NAME_VALUE);
  573. NAME_VALUE *nv = mallocz(size);
  574. size_t allocated = size;
  575. #ifdef NETDATA_INTERNAL_CHECKS
  576. nv->dict = dict;
  577. #endif
  578. nv->refcount = 0;
  579. nv->flags = NAME_VALUE_FLAG_NONE;
  580. nv->value_len = value_len;
  581. allocated += namevalue_set_name(dict, nv, name, name_len);
  582. if(likely(dict->flags & DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE))
  583. nv->value = value;
  584. else {
  585. if(likely(value_len)) {
  586. if (value) {
  587. // a value has been supplied
  588. // copy it
  589. nv->value = mallocz(value_len);
  590. memcpy(nv->value, value, value_len);
  591. }
  592. else {
  593. // no value has been supplied
  594. // allocate a clear memory block
  595. nv->value = callocz(1, value_len);
  596. }
  597. }
  598. else {
  599. // the caller wants an item without any value
  600. nv->value = NULL;
  601. }
  602. allocated += value_len;
  603. }
  604. DICTIONARY_STATS_ENTRIES_PLUS1(dict, allocated);
  605. if(dict->ins_callback)
  606. dict->ins_callback(namevalue_get_name(nv), nv->value, dict->ins_callback_data);
  607. return nv;
  608. }
  609. static void namevalue_reset_unsafe(DICTIONARY *dict, NAME_VALUE *nv, void *value, size_t value_len) {
  610. debug(D_DICTIONARY, "Dictionary entry with name '%s' found. Changing its value.", namevalue_get_name(nv));
  611. DICTIONARY_STATS_VALUE_RESETS_PLUS1(dict, nv->value_len, value_len);
  612. if(dict->del_callback)
  613. dict->del_callback(namevalue_get_name(nv), nv->value, dict->del_callback_data);
  614. if(likely(dict->flags & DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE)) {
  615. debug(D_DICTIONARY, "Dictionary: linking value to '%s'", namevalue_get_name(nv));
  616. nv->value = value;
  617. nv->value_len = value_len;
  618. }
  619. else {
  620. debug(D_DICTIONARY, "Dictionary: cloning value to '%s'", namevalue_get_name(nv));
  621. void *oldvalue = nv->value;
  622. void *newvalue = NULL;
  623. if(value_len) {
  624. newvalue = mallocz(value_len);
  625. if(value) memcpy(newvalue, value, value_len);
  626. else memset(newvalue, 0, value_len);
  627. }
  628. nv->value = newvalue;
  629. nv->value_len = value_len;
  630. debug(D_DICTIONARY, "Dictionary: freeing old value of '%s'", namevalue_get_name(nv));
  631. freez(oldvalue);
  632. }
  633. if(dict->ins_callback)
  634. dict->ins_callback(namevalue_get_name(nv), nv->value, dict->ins_callback_data);
  635. }
  636. static size_t namevalue_destroy_unsafe(DICTIONARY *dict, NAME_VALUE *nv) {
  637. debug(D_DICTIONARY, "Destroying name value entry for name '%s'.", namevalue_get_name(nv));
  638. if(dict->del_callback)
  639. dict->del_callback(namevalue_get_name(nv), nv->value, dict->del_callback_data);
  640. size_t freed = 0;
  641. if(unlikely(!(dict->flags & DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE))) {
  642. debug(D_DICTIONARY, "Dictionary freeing value of '%s'", namevalue_get_name(nv));
  643. freez(nv->value);
  644. freed += nv->value_len;
  645. }
  646. if(unlikely(!(dict->flags & DICTIONARY_FLAG_NAME_LINK_DONT_CLONE))) {
  647. debug(D_DICTIONARY, "Dictionary freeing name '%s'", namevalue_get_name(nv));
  648. freed += namevalue_free_name(dict, nv);
  649. }
  650. freez(nv);
  651. freed += sizeof(NAME_VALUE);
  652. DICTIONARY_STATS_ENTRIES_MINUS_MEMORY(dict, freed);
  653. return freed;
  654. }
  655. // if a dictionary item can be deleted, return true, otherwise return false
  656. static bool name_value_can_be_deleted(DICTIONARY *dict, NAME_VALUE *nv) {
  657. if(unlikely(dict->flags & DICTIONARY_FLAG_DEFER_ALL_DELETIONS))
  658. return false;
  659. if(unlikely(DICTIONARY_NAME_VALUE_REFCOUNT_GET(nv) > 0))
  660. return false;
  661. return true;
  662. }
  663. // ----------------------------------------------------------------------------
  664. // API - dictionary management
  665. #ifdef NETDATA_INTERNAL_CHECKS
  666. DICTIONARY *dictionary_create_advanced_with_trace(DICTIONARY_FLAGS flags, size_t scratchpad_size, const char *function, size_t line, const char *file) {
  667. #else
  668. DICTIONARY *dictionary_create_advanced(DICTIONARY_FLAGS flags, size_t scratchpad_size) {
  669. #endif
  670. debug(D_DICTIONARY, "Creating dictionary.");
  671. if(unlikely(flags & DICTIONARY_FLAGS_RESERVED))
  672. flags &= ~DICTIONARY_FLAGS_RESERVED;
  673. DICTIONARY *dict = callocz(1, sizeof(DICTIONARY) + scratchpad_size);
  674. size_t allocated = sizeof(DICTIONARY) + scratchpad_size;
  675. dict->scratchpad_size = scratchpad_size;
  676. dict->flags = flags;
  677. dict->first_item = dict->last_item = NULL;
  678. allocated += dictionary_lock_init(dict);
  679. allocated += reference_counter_init(dict);
  680. dict->memory = (long)allocated;
  681. hashtable_init_unsafe(dict);
  682. #ifdef NETDATA_INTERNAL_CHECKS
  683. dict->creation_function = function;
  684. dict->creation_file = file;
  685. dict->creation_line = line;
  686. #endif
  687. return (DICTIONARY *)dict;
  688. }
  689. void *dictionary_scratchpad(DICTIONARY *dict) {
  690. return &dict->scratchpad;
  691. }
  692. size_t dictionary_destroy(DICTIONARY *dict) {
  693. if(!dict) return 0;
  694. NAME_VALUE *nv;
  695. debug(D_DICTIONARY, "Destroying dictionary.");
  696. long referenced_items = 0;
  697. size_t retries = 0;
  698. do {
  699. referenced_items = __atomic_load_n(&dict->referenced_items, __ATOMIC_SEQ_CST);
  700. if (referenced_items) {
  701. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  702. // there are referenced items
  703. // delete all items individually, so that only the referenced will remain
  704. NAME_VALUE *nv_next;
  705. for (nv = dict->first_item; nv; nv = nv_next) {
  706. nv_next = nv->next;
  707. size_t refcount = DICTIONARY_NAME_VALUE_REFCOUNT_GET(nv);
  708. if (!refcount && !(nv->flags & NAME_VALUE_FLAG_DELETED))
  709. dictionary_del_unsafe(dict, namevalue_get_name(nv));
  710. }
  711. internal_error(
  712. retries == 0,
  713. "DICTIONARY: waiting (try %zu) for destruction of dictionary created from %s() %zu@%s, because it has %ld referenced items in it (%ld total).",
  714. retries + 1,
  715. dict->creation_function,
  716. dict->creation_line,
  717. dict->creation_file,
  718. referenced_items,
  719. dict->entries);
  720. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  721. sleep_usec(10000);
  722. }
  723. } while(referenced_items > 0 && ++retries < 10);
  724. if(referenced_items) {
  725. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  726. dict->flags |= DICTIONARY_FLAG_DESTROYED;
  727. internal_error(
  728. true,
  729. "DICTIONARY: delaying destruction of dictionary created from %s() %zu@%s after %zu retries, because it has %ld referenced items in it (%ld total).",
  730. dict->creation_function,
  731. dict->creation_line,
  732. dict->creation_file,
  733. retries,
  734. referenced_items,
  735. dict->entries);
  736. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  737. return 0;
  738. }
  739. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  740. size_t freed = 0;
  741. nv = dict->first_item;
  742. while (nv) {
  743. // cache nv->next
  744. // because we are going to free nv
  745. NAME_VALUE *nv_next = nv->next;
  746. freed += namevalue_destroy_unsafe(dict, nv);
  747. nv = nv_next;
  748. // to speed up destruction, we don't
  749. // unlink nv from the linked-list here
  750. }
  751. dict->first_item = NULL;
  752. dict->last_item = NULL;
  753. // destroy the dictionary
  754. freed += hashtable_destroy_unsafe(dict);
  755. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  756. freed += dictionary_lock_free(dict);
  757. freed += reference_counter_free(dict);
  758. freed += sizeof(DICTIONARY) + dict->scratchpad_size;
  759. freez(dict);
  760. return freed;
  761. }
  762. // ----------------------------------------------------------------------------
  763. // helpers
  764. static NAME_VALUE *dictionary_set_name_value_unsafe(DICTIONARY *dict, const char *name, void *value, size_t value_len) {
  765. if(unlikely(!name)) {
  766. internal_error(true, "DICTIONARY: attempted to dictionary_set() a dictionary item without a name");
  767. return NULL;
  768. }
  769. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  770. internal_error(true, "DICTIONARY: attempted to dictionary_set() on a destroyed dictionary");
  771. return NULL;
  772. }
  773. internal_error(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS), "DICTIONARY: inserting dictionary item '%s' without exclusive access to dictionary", name);
  774. size_t name_len = strlen(name) + 1; // we need the terminating null too
  775. debug(D_DICTIONARY, "SET dictionary entry with name '%s'.", name);
  776. // DISCUSSION:
  777. // Is it better to gain a read-lock and do a hashtable_get_unsafe()
  778. // before we write lock to do hashtable_insert_unsafe()?
  779. //
  780. // Probably this depends on the use case.
  781. // For statsd for example that does dictionary_set() to update received values,
  782. // it could be beneficial to do a get() before we insert().
  783. //
  784. // But the caller has the option to do this on his/her own.
  785. // So, let's do the fastest here and let the caller decide the flow of calls.
  786. NAME_VALUE *nv, **pnv = hashtable_insert_unsafe(dict, name, name_len);
  787. if(likely(*pnv == 0)) {
  788. // a new item added to the index
  789. nv = *pnv = namevalue_create_unsafe(dict, name, name_len, value, value_len);
  790. hashtable_inserted_name_value_unsafe(dict, nv);
  791. linkedlist_namevalue_link_unsafe(dict, nv);
  792. nv->flags |= NAME_VALUE_FLAG_NEW_OR_UPDATED;
  793. }
  794. else {
  795. // the item is already in the index
  796. // so, either we will return the old one
  797. // or overwrite the value, depending on dictionary flags
  798. nv = *pnv;
  799. if(!(dict->flags & DICTIONARY_FLAG_DONT_OVERWRITE_VALUE)) {
  800. namevalue_reset_unsafe(dict, nv, value, value_len);
  801. nv->flags |= NAME_VALUE_FLAG_NEW_OR_UPDATED;
  802. }
  803. else if(dict->conflict_callback) {
  804. dict->conflict_callback(namevalue_get_name(nv), nv->value, value, dict->conflict_callback_data);
  805. nv->flags |= NAME_VALUE_FLAG_NEW_OR_UPDATED;
  806. }
  807. else {
  808. // make sure this flag is not set
  809. nv->flags &= ~NAME_VALUE_FLAG_NEW_OR_UPDATED;
  810. }
  811. }
  812. return nv;
  813. }
  814. static NAME_VALUE *dictionary_get_name_value_unsafe(DICTIONARY *dict, const char *name) {
  815. if(unlikely(!name)) {
  816. internal_error(true, "attempted to dictionary_get() without a name");
  817. return NULL;
  818. }
  819. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  820. internal_error(true, "DICTIONARY: attempted to dictionary_get() on a destroyed dictionary");
  821. return NULL;
  822. }
  823. size_t name_len = strlen(name) + 1; // we need the terminating null too
  824. debug(D_DICTIONARY, "GET dictionary entry with name '%s'.", name);
  825. NAME_VALUE *nv = hashtable_get_unsafe(dict, name, name_len);
  826. if(unlikely(!nv)) {
  827. debug(D_DICTIONARY, "Not found dictionary entry with name '%s'.", name);
  828. return NULL;
  829. }
  830. debug(D_DICTIONARY, "Found dictionary entry with name '%s'.", name);
  831. return nv;
  832. }
  833. // ----------------------------------------------------------------------------
  834. // API - items management
  835. void *dictionary_set_unsafe(DICTIONARY *dict, const char *name, void *value, size_t value_len) {
  836. NAME_VALUE *nv = dictionary_set_name_value_unsafe(dict, name, value, value_len);
  837. if(unlikely(dict->react_callback && nv && (nv->flags & NAME_VALUE_FLAG_NEW_OR_UPDATED))) {
  838. // we need to call the react callback with a reference counter on nv
  839. reference_counter_acquire(dict, nv);
  840. dict->react_callback(namevalue_get_name(nv), nv->value, dict->react_callback_data);
  841. reference_counter_release(dict, nv, false);
  842. }
  843. return nv ? nv->value : NULL;
  844. }
  845. void *dictionary_set(DICTIONARY *dict, const char *name, void *value, size_t value_len) {
  846. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  847. NAME_VALUE *nv = dictionary_set_name_value_unsafe(dict, name, value, value_len);
  848. // we need to get a reference counter for the react callback
  849. // before we unlock the dictionary
  850. if(unlikely(dict->react_callback && nv && (nv->flags & NAME_VALUE_FLAG_NEW_OR_UPDATED)))
  851. reference_counter_acquire(dict, nv);
  852. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  853. if(unlikely(dict->react_callback && nv && (nv->flags & NAME_VALUE_FLAG_NEW_OR_UPDATED))) {
  854. // we got the reference counter we need, above
  855. dict->react_callback(namevalue_get_name(nv), nv->value, dict->react_callback_data);
  856. reference_counter_release(dict, nv, false);
  857. }
  858. return nv ? nv->value : NULL;
  859. }
  860. DICTIONARY_ITEM *dictionary_set_and_acquire_item_unsafe(DICTIONARY *dict, const char *name, void *value, size_t value_len) {
  861. NAME_VALUE *nv = dictionary_set_name_value_unsafe(dict, name, value, value_len);
  862. if(unlikely(!nv))
  863. return NULL;
  864. reference_counter_acquire(dict, nv);
  865. if(unlikely(dict->react_callback && (nv->flags & NAME_VALUE_FLAG_NEW_OR_UPDATED))) {
  866. dict->react_callback(namevalue_get_name(nv), nv->value, dict->react_callback_data);
  867. }
  868. return (DICTIONARY_ITEM *)nv;
  869. }
  870. DICTIONARY_ITEM *dictionary_set_and_acquire_item(DICTIONARY *dict, const char *name, void *value, size_t value_len) {
  871. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  872. NAME_VALUE *nv = dictionary_set_name_value_unsafe(dict, name, value, value_len);
  873. // we need to get the reference counter before we unlock
  874. if(nv) reference_counter_acquire(dict, nv);
  875. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  876. if(unlikely(dict->react_callback && nv && (nv->flags & NAME_VALUE_FLAG_NEW_OR_UPDATED))) {
  877. // we already have a reference counter, for the caller, no need for another one
  878. dict->react_callback(namevalue_get_name(nv), nv->value, dict->react_callback_data);
  879. }
  880. return (DICTIONARY_ITEM *)nv;
  881. }
  882. void *dictionary_get_unsafe(DICTIONARY *dict, const char *name) {
  883. NAME_VALUE *nv = dictionary_get_name_value_unsafe(dict, name);
  884. if(unlikely(!nv))
  885. return NULL;
  886. return nv->value;
  887. }
  888. void *dictionary_get(DICTIONARY *dict, const char *name) {
  889. dictionary_lock(dict, DICTIONARY_LOCK_READ);
  890. void *ret = dictionary_get_unsafe(dict, name);
  891. dictionary_unlock(dict, DICTIONARY_LOCK_READ);
  892. return ret;
  893. }
  894. DICTIONARY_ITEM *dictionary_get_and_acquire_item_unsafe(DICTIONARY *dict, const char *name) {
  895. NAME_VALUE *nv = dictionary_get_name_value_unsafe(dict, name);
  896. if(unlikely(!nv))
  897. return NULL;
  898. reference_counter_acquire(dict, nv);
  899. return (DICTIONARY_ITEM *)nv;
  900. }
  901. DICTIONARY_ITEM *dictionary_get_and_acquire_item(DICTIONARY *dict, const char *name) {
  902. dictionary_lock(dict, DICTIONARY_LOCK_READ);
  903. void *ret = dictionary_get_and_acquire_item_unsafe(dict, name);
  904. dictionary_unlock(dict, DICTIONARY_LOCK_READ);
  905. return ret;
  906. }
  907. DICTIONARY_ITEM *dictionary_acquired_item_dup(DICTIONARY_ITEM *item) {
  908. if(unlikely(!item)) return NULL;
  909. reference_counter_increase((NAME_VALUE *)item);
  910. return item;
  911. }
  912. const char *dictionary_acquired_item_name(DICTIONARY_ITEM *item) {
  913. if(unlikely(!item)) return NULL;
  914. return namevalue_get_name((NAME_VALUE *)item);
  915. }
  916. void *dictionary_acquired_item_value(DICTIONARY_ITEM *item) {
  917. if(unlikely(!item)) return NULL;
  918. return ((NAME_VALUE *)item)->value;
  919. }
  920. void dictionary_acquired_item_release_unsafe(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  921. if(unlikely(!item)) return;
  922. #ifdef NETDATA_INTERNAL_CHECKS
  923. if(((NAME_VALUE *)item)->dict != dict)
  924. fatal("DICTIONARY: %s(): name_value item with name '%s' does not belong to this dictionary", __FUNCTION__, namevalue_get_name((NAME_VALUE *)item));
  925. #endif
  926. reference_counter_release(dict, (NAME_VALUE *)item, false);
  927. }
  928. void dictionary_acquired_item_release(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  929. if(unlikely(!item)) return;
  930. #ifdef NETDATA_INTERNAL_CHECKS
  931. if(((NAME_VALUE *)item)->dict != dict)
  932. fatal("DICTIONARY: %s(): name_value item with name '%s' does not belong to this dictionary", __FUNCTION__, namevalue_get_name((NAME_VALUE *)item));
  933. #endif
  934. // no need to get a lock here
  935. // we pass the last parameter to reference_counter_release() as true
  936. // so that the release may get a write-lock if required to clean up
  937. reference_counter_release(dict, (NAME_VALUE *)item, true);
  938. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED))
  939. dictionary_destroy(dict);
  940. }
  941. int dictionary_del_unsafe(DICTIONARY *dict, const char *name) {
  942. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  943. internal_error(true, "DICTIONARY: attempted to dictionary_del() on a destroyed dictionary");
  944. return -1;
  945. }
  946. if(unlikely(!name || !*name)) {
  947. internal_error(true, "DICTIONARY: attempted to dictionary_del() without a name");
  948. return -1;
  949. }
  950. internal_error(!(dict->flags & DICTIONARY_FLAG_EXCLUSIVE_ACCESS), "DICTIONARY: INTERNAL ERROR: deleting dictionary item '%s' without exclusive access to dictionary", name);
  951. size_t name_len = strlen(name) + 1; // we need the terminating null too
  952. debug(D_DICTIONARY, "DEL dictionary entry with name '%s'.", name);
  953. // Unfortunately, the JudyHSDel() does not return the value of the
  954. // item that was deleted, so we have to find it before we delete it,
  955. // since we need to release our structures too.
  956. int ret;
  957. NAME_VALUE *nv = hashtable_get_unsafe(dict, name, name_len);
  958. if(unlikely(!nv)) {
  959. debug(D_DICTIONARY, "Not found dictionary entry with name '%s'.", name);
  960. ret = -1;
  961. }
  962. else {
  963. debug(D_DICTIONARY, "Found dictionary entry with name '%s'.", name);
  964. if(hashtable_delete_unsafe(dict, name, name_len, nv) == 0)
  965. error("DICTIONARY: INTERNAL ERROR: tried to delete item with name '%s' that is not in the index", name);
  966. if(name_value_can_be_deleted(dict, nv)) {
  967. linkedlist_namevalue_unlink_unsafe(dict, nv);
  968. namevalue_destroy_unsafe(dict, nv);
  969. }
  970. else
  971. nv->flags |= NAME_VALUE_FLAG_DELETED;
  972. ret = 0;
  973. DICTIONARY_STATS_ENTRIES_MINUS1(dict);
  974. }
  975. return ret;
  976. }
  977. int dictionary_del(DICTIONARY *dict, const char *name) {
  978. dictionary_lock(dict, DICTIONARY_LOCK_WRITE);
  979. int ret = dictionary_del_unsafe(dict, name);
  980. dictionary_unlock(dict, DICTIONARY_LOCK_WRITE);
  981. return ret;
  982. }
  983. // ----------------------------------------------------------------------------
  984. // traversal with loop
  985. void *dictionary_foreach_start_rw(DICTFE *dfe, DICTIONARY *dict, char rw) {
  986. if(unlikely(!dfe || !dict)) return NULL;
  987. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  988. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_start_rw() on a destroyed dictionary");
  989. dfe->last_item = NULL;
  990. dfe->name = NULL;
  991. dfe->value = NULL;
  992. return NULL;
  993. }
  994. dfe->dict = dict;
  995. dfe->rw = rw;
  996. dfe->started_ut = now_realtime_usec();
  997. dictionary_lock(dict, dfe->rw);
  998. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  999. // get the first item from the list
  1000. NAME_VALUE *nv = dict->first_item;
  1001. // skip all the deleted items
  1002. while(nv && (nv->flags & NAME_VALUE_FLAG_DELETED))
  1003. nv = nv->next;
  1004. if(likely(nv)) {
  1005. dfe->last_item = nv;
  1006. dfe->name = (char *)namevalue_get_name(nv);
  1007. dfe->value = nv->value;
  1008. reference_counter_acquire(dict, nv);
  1009. }
  1010. else {
  1011. dfe->last_item = NULL;
  1012. dfe->name = NULL;
  1013. dfe->value = NULL;
  1014. }
  1015. return dfe->value;
  1016. }
  1017. void *dictionary_foreach_next(DICTFE *dfe) {
  1018. if(unlikely(!dfe || !dfe->dict)) return NULL;
  1019. if(unlikely(dfe->dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  1020. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_next() on a destroyed dictionary");
  1021. dfe->last_item = NULL;
  1022. dfe->name = NULL;
  1023. dfe->value = NULL;
  1024. return NULL;
  1025. }
  1026. // the item we just did
  1027. NAME_VALUE *nv = (NAME_VALUE *)dfe->last_item;
  1028. // get the next item from the list
  1029. NAME_VALUE *nv_next = (nv) ? nv->next : NULL;
  1030. // skip all the deleted items
  1031. while(nv_next && (nv_next->flags & NAME_VALUE_FLAG_DELETED))
  1032. nv_next = nv_next->next;
  1033. // release the old, so that it can possibly be deleted
  1034. if(likely(nv))
  1035. reference_counter_release(dfe->dict, nv, false);
  1036. if(likely(nv = nv_next)) {
  1037. dfe->last_item = nv;
  1038. dfe->name = (char *)namevalue_get_name(nv);
  1039. dfe->value = nv->value;
  1040. reference_counter_acquire(dfe->dict, nv);
  1041. }
  1042. else {
  1043. dfe->last_item = NULL;
  1044. dfe->name = NULL;
  1045. dfe->value = NULL;
  1046. }
  1047. return dfe->value;
  1048. }
  1049. usec_t dictionary_foreach_done(DICTFE *dfe) {
  1050. if(unlikely(!dfe || !dfe->dict)) return 0;
  1051. if(unlikely(dfe->dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  1052. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_next() on a destroyed dictionary");
  1053. return 0;
  1054. }
  1055. // the item we just did
  1056. NAME_VALUE *nv = (NAME_VALUE *)dfe->last_item;
  1057. // release it, so that it can possibly be deleted
  1058. if(likely(nv))
  1059. reference_counter_release(dfe->dict, nv, false);
  1060. dictionary_unlock(dfe->dict, dfe->rw);
  1061. dfe->dict = NULL;
  1062. dfe->last_item = NULL;
  1063. dfe->name = NULL;
  1064. dfe->value = NULL;
  1065. usec_t usec = now_realtime_usec() - dfe->started_ut;
  1066. dfe->started_ut = 0;
  1067. return usec;
  1068. }
  1069. // ----------------------------------------------------------------------------
  1070. // API - walk through the dictionary
  1071. // the dictionary is locked for reading while this happens
  1072. // do not use other dictionary calls while walking the dictionary - deadlock!
  1073. int dictionary_walkthrough_rw(DICTIONARY *dict, char rw, int (*callback)(const char *name, void *entry, void *data), void *data) {
  1074. if(unlikely(!dict)) return 0;
  1075. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  1076. internal_error(true, "DICTIONARY: attempted to dictionary_walkthrough_rw() on a destroyed dictionary");
  1077. return 0;
  1078. }
  1079. dictionary_lock(dict, rw);
  1080. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  1081. // written in such a way, that the callback can delete the active element
  1082. int ret = 0;
  1083. NAME_VALUE *nv = dict->first_item, *nv_next;
  1084. while(nv) {
  1085. // skip the deleted items
  1086. if(unlikely(nv->flags & NAME_VALUE_FLAG_DELETED)) {
  1087. nv = nv->next;
  1088. continue;
  1089. }
  1090. // get a reference counter, so that our item will not be deleted
  1091. // while we are using it
  1092. reference_counter_acquire(dict, nv);
  1093. int r = callback(namevalue_get_name(nv), nv->value, data);
  1094. // since we have a reference counter, this item cannot be deleted
  1095. // until we release the reference counter, so the pointers are there
  1096. nv_next = nv->next;
  1097. reference_counter_release(dict, nv, false);
  1098. if(unlikely(r < 0)) {
  1099. ret = r;
  1100. break;
  1101. }
  1102. ret += r;
  1103. nv = nv_next;
  1104. }
  1105. dictionary_unlock(dict, rw);
  1106. return ret;
  1107. }
  1108. // ----------------------------------------------------------------------------
  1109. // sorted walkthrough
  1110. static int dictionary_sort_compar(const void *nv1, const void *nv2) {
  1111. return strcmp(namevalue_get_name((*(NAME_VALUE **)nv1)), namevalue_get_name((*(NAME_VALUE **)nv2)));
  1112. }
  1113. int dictionary_sorted_walkthrough_rw(DICTIONARY *dict, char rw, int (*callback)(const char *name, void *entry, void *data), void *data) {
  1114. if(unlikely(!dict || !dict->entries)) return 0;
  1115. if(unlikely(dict->flags & DICTIONARY_FLAG_DESTROYED)) {
  1116. internal_error(true, "DICTIONARY: attempted to dictionary_sorted_walkthrough_rw() on a destroyed dictionary");
  1117. return 0;
  1118. }
  1119. dictionary_lock(dict, rw);
  1120. dictionary_defer_all_deletions_unsafe(dict, rw);
  1121. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  1122. size_t count = dict->entries;
  1123. NAME_VALUE **array = mallocz(sizeof(NAME_VALUE *) * count);
  1124. size_t i;
  1125. NAME_VALUE *nv;
  1126. for(nv = dict->first_item, i = 0; nv && i < count ;nv = nv->next) {
  1127. if(likely(!(nv->flags & NAME_VALUE_FLAG_DELETED)))
  1128. array[i++] = nv;
  1129. }
  1130. internal_error(nv != NULL, "DICTIONARY: during sorting expected to have %zu items in dictionary, but there are more. Sorted results may be incomplete. Dictionary fails to maintain an accurate number of the number of entries it has.", count);
  1131. if(unlikely(i != count)) {
  1132. internal_error(true, "DICTIONARY: during sorting expected to have %zu items in dictionary, but there are %zu. Sorted results may be incomplete. Dictionary fails to maintain an accurate number of the number of entries it has.", count, i);
  1133. count = i;
  1134. }
  1135. qsort(array, count, sizeof(NAME_VALUE *), dictionary_sort_compar);
  1136. int ret = 0;
  1137. for(i = 0; i < count ;i++) {
  1138. nv = array[i];
  1139. if(likely(!(nv->flags & NAME_VALUE_FLAG_DELETED))) {
  1140. reference_counter_acquire(dict, nv);
  1141. int r = callback(namevalue_get_name(nv), nv->value, data);
  1142. reference_counter_release(dict, nv, false);
  1143. if (r < 0) {
  1144. ret = r;
  1145. break;
  1146. }
  1147. ret += r;
  1148. }
  1149. }
  1150. dictionary_restore_all_deletions_unsafe(dict, rw);
  1151. dictionary_unlock(dict, rw);
  1152. freez(array);
  1153. return ret;
  1154. }
  1155. // ----------------------------------------------------------------------------
  1156. // STRING implementation - dedup all STRINGs
  1157. typedef struct string_entry {
  1158. #ifdef DICTIONARY_WITH_AVL
  1159. avl_t avl_node;
  1160. #endif
  1161. uint32_t length; // the string length with the terminating '\0'
  1162. uint32_t refcount; // how many times this string is used
  1163. const char str[]; // the string itself
  1164. } STRING_ENTRY;
  1165. #ifdef DICTIONARY_WITH_AVL
  1166. static int string_entry_compare(void* a, void* b) {
  1167. return strcmp(((STRING_ENTRY *)a)->str, ((STRING_ENTRY *)b)->str);
  1168. }
  1169. static void *get_thread_static_string_entry(const char *name) {
  1170. static __thread size_t _length = 0;
  1171. static __thread STRING_ENTRY *_tmp = NULL;
  1172. size_t size = sizeof(STRING_ENTRY) + strlen(name) + 1;
  1173. if(likely(_tmp && _length < size)) {
  1174. freez(_tmp);
  1175. _tmp = NULL;
  1176. _length = 0;
  1177. }
  1178. if(unlikely(!_tmp)) {
  1179. _tmp = callocz(1, size);
  1180. _length = size;
  1181. }
  1182. strcpy((char *)&_tmp->str[0], name);
  1183. return _tmp;
  1184. }
  1185. #endif
  1186. DICTIONARY string_dictionary = {
  1187. #ifdef DICTIONARY_WITH_AVL
  1188. .values_index = {
  1189. .root = NULL,
  1190. .compar = string_entry_compare
  1191. },
  1192. .get_thread_static_name_value = get_thread_static_string_entry,
  1193. #endif
  1194. .flags = DICTIONARY_FLAG_EXCLUSIVE_ACCESS,
  1195. .rwlock = NETDATA_RWLOCK_INITIALIZER
  1196. };
  1197. static netdata_mutex_t string_mutex = NETDATA_MUTEX_INITIALIZER;
  1198. STRING *string_dup(STRING *string) {
  1199. if(unlikely(!string)) return NULL;
  1200. STRING_ENTRY *se = (STRING_ENTRY *)string;
  1201. netdata_mutex_lock(&string_mutex);
  1202. se->refcount++;
  1203. netdata_mutex_unlock(&string_mutex);
  1204. return string;
  1205. }
  1206. STRING *string_strdupz(const char *str) {
  1207. if(unlikely(!str || !*str)) return NULL;
  1208. netdata_mutex_lock(&string_mutex);
  1209. size_t length = strlen(str) + 1;
  1210. STRING_ENTRY *se;
  1211. STRING_ENTRY **ptr = (STRING_ENTRY **)hashtable_insert_unsafe(&string_dictionary, str, length);
  1212. if(unlikely(*ptr == 0)) {
  1213. // a new item added to the index
  1214. size_t mem_size = sizeof(STRING_ENTRY) + length;
  1215. se = mallocz(mem_size);
  1216. strcpy((char *)se->str, str);
  1217. se->length = length;
  1218. se->refcount = 1;
  1219. *ptr = se;
  1220. hashtable_inserted_name_value_unsafe(&string_dictionary, se);
  1221. string_dictionary.version++;
  1222. string_dictionary.inserts++;
  1223. string_dictionary.entries++;
  1224. string_dictionary.memory += (long)mem_size;
  1225. }
  1226. else {
  1227. // the item is already in the index
  1228. se = *ptr;
  1229. se->refcount++;
  1230. string_dictionary.searches++;
  1231. }
  1232. netdata_mutex_unlock(&string_mutex);
  1233. return (STRING *)se;
  1234. }
  1235. void string_freez(STRING *string) {
  1236. if(unlikely(!string)) return;
  1237. netdata_mutex_lock(&string_mutex);
  1238. STRING_ENTRY *se = (STRING_ENTRY *)string;
  1239. if(se->refcount == 0)
  1240. fatal("STRING: tried to free string that has zero references.");
  1241. se->refcount--;
  1242. if(unlikely(se->refcount == 0)) {
  1243. if(hashtable_delete_unsafe(&string_dictionary, se->str, se->length, se) == 0)
  1244. error("STRING: INTERNAL ERROR: tried to delete '%s' that is not in the index", se->str);
  1245. size_t mem_size = sizeof(STRING_ENTRY) + se->length;
  1246. freez(se);
  1247. string_dictionary.version++;
  1248. string_dictionary.deletes++;
  1249. string_dictionary.entries--;
  1250. string_dictionary.memory -= (long)mem_size;
  1251. }
  1252. netdata_mutex_unlock(&string_mutex);
  1253. }
  1254. size_t string_length(STRING *string) {
  1255. if(unlikely(!string)) return 0;
  1256. return ((STRING_ENTRY *)string)->length - 1;
  1257. }
  1258. const char *string2str(STRING *string) {
  1259. if(unlikely(!string)) return "";
  1260. return ((STRING_ENTRY *)string)->str;
  1261. }
  1262. STRING *string_2way_merge(STRING *a, STRING *b) {
  1263. static STRING *X = NULL;
  1264. if(unlikely(!X)) {
  1265. X = string_strdupz("[x]");
  1266. }
  1267. if(unlikely(a == b)) return string_dup(a);
  1268. if(unlikely(a == X)) return string_dup(a);
  1269. if(unlikely(b == X)) return string_dup(b);
  1270. if(unlikely(!a)) return string_dup(X);
  1271. if(unlikely(!b)) return string_dup(X);
  1272. size_t alen = string_length(a);
  1273. size_t blen = string_length(b);
  1274. size_t length = alen + blen + string_length(X) + 1;
  1275. char buf1[length + 1], buf2[length + 1], *dst1;
  1276. const char *s1, *s2;
  1277. s1 = string2str(a);
  1278. s2 = string2str(b);
  1279. dst1 = buf1;
  1280. for( ; *s1 && *s2 && *s1 == *s2 ;s1++, s2++)
  1281. *dst1++ = *s1;
  1282. *dst1 = '\0';
  1283. if(*s1 != '\0' || *s2 != '\0') {
  1284. *dst1++ = '[';
  1285. *dst1++ = 'x';
  1286. *dst1++ = ']';
  1287. s1 = &(string2str(a))[alen - 1];
  1288. s2 = &(string2str(b))[blen - 1];
  1289. char *dst2 = &buf2[length];
  1290. *dst2 = '\0';
  1291. for (; *s1 && *s2 && *s1 == *s2; s1--, s2--)
  1292. *(--dst2) = *s1;
  1293. strcpy(dst1, dst2);
  1294. }
  1295. return string_strdupz(buf1);
  1296. }
  1297. // ----------------------------------------------------------------------------
  1298. // unit test
  1299. static void dictionary_unittest_free_char_pp(char **pp, size_t entries) {
  1300. for(size_t i = 0; i < entries ;i++)
  1301. freez(pp[i]);
  1302. freez(pp);
  1303. }
  1304. static char **dictionary_unittest_generate_names(size_t entries) {
  1305. char **names = mallocz(sizeof(char *) * entries);
  1306. for(size_t i = 0; i < entries ;i++) {
  1307. char buf[25 + 1] = "";
  1308. snprintfz(buf, 25, "name.%zu.0123456789.%zu \t !@#$%%^&*(),./[]{}\\|~`", i, entries / 2 + i);
  1309. names[i] = strdupz(buf);
  1310. }
  1311. return names;
  1312. }
  1313. static char **dictionary_unittest_generate_values(size_t entries) {
  1314. char **values = mallocz(sizeof(char *) * entries);
  1315. for(size_t i = 0; i < entries ;i++) {
  1316. char buf[25 + 1] = "";
  1317. snprintfz(buf, 25, "value-%zu-0987654321.%zu%%^&*(),. \t !@#$/[]{}\\|~`", i, entries / 2 + i);
  1318. values[i] = strdupz(buf);
  1319. }
  1320. return values;
  1321. }
  1322. static size_t dictionary_unittest_set_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1323. size_t errors = 0;
  1324. for(size_t i = 0; i < entries ;i++) {
  1325. size_t vallen = strlen(values[i]) + 1;
  1326. char *val = (char *)dictionary_set(dict, names[i], values[i], vallen);
  1327. if(val == values[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  1328. if(!val || memcmp(val, values[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  1329. }
  1330. return errors;
  1331. }
  1332. static size_t dictionary_unittest_set_null(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1333. (void)values;
  1334. size_t errors = 0;
  1335. long i = 0;
  1336. for(; i < (long)entries ;i++) {
  1337. void *val = dictionary_set(dict, names[i], NULL, 0);
  1338. if(val != NULL) { fprintf(stderr, ">>> %s() returns a non NULL value\n", __FUNCTION__); errors++; }
  1339. }
  1340. if(dictionary_stats_entries(dict) != i) {
  1341. fprintf(stderr, ">>> %s() dictionary items do not match\n", __FUNCTION__);
  1342. errors++;
  1343. }
  1344. return errors;
  1345. }
  1346. static size_t dictionary_unittest_set_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1347. size_t errors = 0;
  1348. for(size_t i = 0; i < entries ;i++) {
  1349. size_t vallen = strlen(values[i]) + 1;
  1350. char *val = (char *)dictionary_set(dict, names[i], values[i], vallen);
  1351. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  1352. }
  1353. return errors;
  1354. }
  1355. static size_t dictionary_unittest_get_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1356. size_t errors = 0;
  1357. for(size_t i = 0; i < entries ;i++) {
  1358. size_t vallen = strlen(values[i]) + 1;
  1359. char *val = (char *)dictionary_get(dict, names[i]);
  1360. if(val == values[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  1361. if(!val || memcmp(val, values[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  1362. }
  1363. return errors;
  1364. }
  1365. static size_t dictionary_unittest_get_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1366. size_t errors = 0;
  1367. for(size_t i = 0; i < entries ;i++) {
  1368. char *val = (char *)dictionary_get(dict, names[i]);
  1369. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  1370. }
  1371. return errors;
  1372. }
  1373. static size_t dictionary_unittest_get_nonexisting(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1374. (void)names;
  1375. size_t errors = 0;
  1376. for(size_t i = 0; i < entries ;i++) {
  1377. char *val = (char *)dictionary_get(dict, values[i]);
  1378. if(val) { fprintf(stderr, ">>> %s() returns non-existing item\n", __FUNCTION__); errors++; }
  1379. }
  1380. return errors;
  1381. }
  1382. static size_t dictionary_unittest_del_nonexisting(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1383. (void)names;
  1384. size_t errors = 0;
  1385. for(size_t i = 0; i < entries ;i++) {
  1386. int ret = dictionary_del(dict, values[i]);
  1387. if(ret != -1) { fprintf(stderr, ">>> %s() deleted non-existing item\n", __FUNCTION__); errors++; }
  1388. }
  1389. return errors;
  1390. }
  1391. static size_t dictionary_unittest_del_existing(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1392. (void)values;
  1393. size_t errors = 0;
  1394. size_t forward_from = 0, forward_to = entries / 3;
  1395. size_t middle_from = forward_to, middle_to = entries * 2 / 3;
  1396. size_t backward_from = middle_to, backward_to = entries;
  1397. for(size_t i = forward_from; i < forward_to ;i++) {
  1398. int ret = dictionary_del(dict, names[i]);
  1399. if(ret == -1) { fprintf(stderr, ">>> %s() didn't delete (forward) existing item\n", __FUNCTION__); errors++; }
  1400. }
  1401. for(size_t i = middle_to - 1; i >= middle_from ;i--) {
  1402. int ret = dictionary_del(dict, names[i]);
  1403. if(ret == -1) { fprintf(stderr, ">>> %s() didn't delete (middle) existing item\n", __FUNCTION__); errors++; }
  1404. }
  1405. for(size_t i = backward_to - 1; i >= backward_from ;i--) {
  1406. int ret = dictionary_del(dict, names[i]);
  1407. if(ret == -1) { fprintf(stderr, ">>> %s() didn't delete (backward) existing item\n", __FUNCTION__); errors++; }
  1408. }
  1409. return errors;
  1410. }
  1411. static size_t dictionary_unittest_reset_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1412. (void)values;
  1413. // set the name as value too
  1414. size_t errors = 0;
  1415. for(size_t i = 0; i < entries ;i++) {
  1416. size_t vallen = strlen(names[i]) + 1;
  1417. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  1418. if(val == names[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  1419. if(!val || memcmp(val, names[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  1420. }
  1421. return errors;
  1422. }
  1423. static size_t dictionary_unittest_reset_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1424. (void)values;
  1425. // set the name as value too
  1426. size_t errors = 0;
  1427. for(size_t i = 0; i < entries ;i++) {
  1428. size_t vallen = strlen(names[i]) + 1;
  1429. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  1430. if(val != names[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  1431. if(!val) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  1432. }
  1433. return errors;
  1434. }
  1435. static size_t dictionary_unittest_reset_dont_overwrite_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1436. // set the name as value too
  1437. size_t errors = 0;
  1438. for(size_t i = 0; i < entries ;i++) {
  1439. size_t vallen = strlen(names[i]) + 1;
  1440. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  1441. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  1442. }
  1443. return errors;
  1444. }
  1445. static int dictionary_unittest_walkthrough_callback(const char *name, void *value, void *data) {
  1446. (void)name;
  1447. (void)value;
  1448. (void)data;
  1449. return 1;
  1450. }
  1451. static size_t dictionary_unittest_walkthrough(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1452. (void)names;
  1453. (void)values;
  1454. int sum = dictionary_walkthrough_read(dict, dictionary_unittest_walkthrough_callback, NULL);
  1455. if(sum < (int)entries) return entries - sum;
  1456. else return sum - entries;
  1457. }
  1458. static int dictionary_unittest_walkthrough_delete_this_callback(const char *name, void *value, void *data) {
  1459. (void)value;
  1460. if(dictionary_del_having_write_lock((DICTIONARY *)data, name) == -1)
  1461. return 0;
  1462. return 1;
  1463. }
  1464. static size_t dictionary_unittest_walkthrough_delete_this(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1465. (void)names;
  1466. (void)values;
  1467. int sum = dictionary_walkthrough_write(dict, dictionary_unittest_walkthrough_delete_this_callback, dict);
  1468. if(sum < (int)entries) return entries - sum;
  1469. else return sum - entries;
  1470. }
  1471. static int dictionary_unittest_walkthrough_stop_callback(const char *name, void *value, void *data) {
  1472. (void)name;
  1473. (void)value;
  1474. (void)data;
  1475. return -1;
  1476. }
  1477. static size_t dictionary_unittest_walkthrough_stop(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1478. (void)names;
  1479. (void)values;
  1480. (void)entries;
  1481. int sum = dictionary_walkthrough_read(dict, dictionary_unittest_walkthrough_stop_callback, NULL);
  1482. if(sum != -1) return 1;
  1483. return 0;
  1484. }
  1485. static size_t dictionary_unittest_foreach(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1486. (void)names;
  1487. (void)values;
  1488. (void)entries;
  1489. size_t count = 0;
  1490. char *item;
  1491. dfe_start_read(dict, item)
  1492. count++;
  1493. dfe_done(item);
  1494. if(count > entries) return count - entries;
  1495. return entries - count;
  1496. }
  1497. static size_t dictionary_unittest_foreach_delete_this(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1498. (void)names;
  1499. (void)values;
  1500. (void)entries;
  1501. size_t count = 0;
  1502. char *item;
  1503. dfe_start_write(dict, item)
  1504. if(dictionary_del_having_write_lock(dict, item_name) != -1) count++;
  1505. dfe_done(item);
  1506. if(count > entries) return count - entries;
  1507. return entries - count;
  1508. }
  1509. static size_t dictionary_unittest_destroy(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1510. (void)names;
  1511. (void)values;
  1512. (void)entries;
  1513. size_t bytes = dictionary_destroy(dict);
  1514. fprintf(stderr, " %s() freed %zu bytes,", __FUNCTION__, bytes);
  1515. return 0;
  1516. }
  1517. static usec_t dictionary_unittest_run_and_measure_time(DICTIONARY *dict, char *message, char **names, char **values, size_t entries, size_t *errors, size_t (*callback)(DICTIONARY *dict, char **names, char **values, size_t entries)) {
  1518. fprintf(stderr, "%40s ... ", message);
  1519. usec_t started = now_realtime_usec();
  1520. size_t errs = callback(dict, names, values, entries);
  1521. usec_t ended = now_realtime_usec();
  1522. usec_t dt = ended - started;
  1523. if(callback == dictionary_unittest_destroy) dict = NULL;
  1524. fprintf(stderr, " %zu errors, %ld items in dictionary, %llu usec \n", errs, dict? dictionary_stats_entries(dict):0, dt);
  1525. *errors += errs;
  1526. return dt;
  1527. }
  1528. static void dictionary_unittest_clone(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  1529. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_clone);
  1530. dictionary_unittest_run_and_measure_time(dict, "getting entries", names, values, entries, errors, dictionary_unittest_get_clone);
  1531. dictionary_unittest_run_and_measure_time(dict, "getting non-existing entries", names, values, entries, errors, dictionary_unittest_get_nonexisting);
  1532. dictionary_unittest_run_and_measure_time(dict, "resetting entries", names, values, entries, errors, dictionary_unittest_reset_clone);
  1533. dictionary_unittest_run_and_measure_time(dict, "deleting non-existing entries", names, values, entries, errors, dictionary_unittest_del_nonexisting);
  1534. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  1535. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, errors, dictionary_unittest_walkthrough);
  1536. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, errors, dictionary_unittest_walkthrough_stop);
  1537. dictionary_unittest_run_and_measure_time(dict, "deleting existing entries", names, values, entries, errors, dictionary_unittest_del_existing);
  1538. dictionary_unittest_run_and_measure_time(dict, "walking through empty", names, values, 0, errors, dictionary_unittest_walkthrough);
  1539. dictionary_unittest_run_and_measure_time(dict, "traverse foreach empty", names, values, 0, errors, dictionary_unittest_foreach);
  1540. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, errors, dictionary_unittest_destroy);
  1541. }
  1542. static void dictionary_unittest_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  1543. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_nonclone);
  1544. dictionary_unittest_run_and_measure_time(dict, "getting entries", names, values, entries, errors, dictionary_unittest_get_nonclone);
  1545. dictionary_unittest_run_and_measure_time(dict, "getting non-existing entries", names, values, entries, errors, dictionary_unittest_get_nonexisting);
  1546. dictionary_unittest_run_and_measure_time(dict, "resetting entries", names, values, entries, errors, dictionary_unittest_reset_nonclone);
  1547. dictionary_unittest_run_and_measure_time(dict, "deleting non-existing entries", names, values, entries, errors, dictionary_unittest_del_nonexisting);
  1548. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  1549. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, errors, dictionary_unittest_walkthrough);
  1550. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, errors, dictionary_unittest_walkthrough_stop);
  1551. dictionary_unittest_run_and_measure_time(dict, "deleting existing entries", names, values, entries, errors, dictionary_unittest_del_existing);
  1552. dictionary_unittest_run_and_measure_time(dict, "walking through empty", names, values, 0, errors, dictionary_unittest_walkthrough);
  1553. dictionary_unittest_run_and_measure_time(dict, "traverse foreach empty", names, values, 0, errors, dictionary_unittest_foreach);
  1554. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, errors, dictionary_unittest_destroy);
  1555. }
  1556. struct dictionary_unittest_sorting {
  1557. const char *oldname;
  1558. const char *oldvalue;
  1559. size_t count;
  1560. };
  1561. static int dictionary_unittest_sorting_callback(const char *name, void *value, void *data) {
  1562. struct dictionary_unittest_sorting *t = (struct dictionary_unittest_sorting *)data;
  1563. const char *v = (const char *)value;
  1564. int ret = 0;
  1565. if(t->oldname && strcmp(t->oldname, name) > 0) {
  1566. fprintf(stderr, "name '%s' should be after '%s'\n", t->oldname, name);
  1567. ret = 1;
  1568. }
  1569. t->count++;
  1570. t->oldname = name;
  1571. t->oldvalue = v;
  1572. return ret;
  1573. }
  1574. static size_t dictionary_unittest_sorted_walkthrough(DICTIONARY *dict, char **names, char **values, size_t entries) {
  1575. (void)names;
  1576. (void)values;
  1577. struct dictionary_unittest_sorting tmp = { .oldname = NULL, .oldvalue = NULL, .count = 0 };
  1578. size_t errors;
  1579. errors = dictionary_sorted_walkthrough_read(dict, dictionary_unittest_sorting_callback, &tmp);
  1580. if(tmp.count != entries) {
  1581. fprintf(stderr, "Expected %zu entries, counted %zu\n", entries, tmp.count);
  1582. errors++;
  1583. }
  1584. return errors;
  1585. }
  1586. static void dictionary_unittest_sorting(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  1587. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_clone);
  1588. dictionary_unittest_run_and_measure_time(dict, "sorted walkthrough", names, values, entries, errors, dictionary_unittest_sorted_walkthrough);
  1589. }
  1590. static void dictionary_unittest_null_dfe(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  1591. dictionary_unittest_run_and_measure_time(dict, "adding null value entries", names, values, entries, errors, dictionary_unittest_set_null);
  1592. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  1593. }
  1594. static int check_dictionary_callback(const char *name, void *value, void *data) {
  1595. (void)name;
  1596. (void)value;
  1597. (void)data;
  1598. return 1;
  1599. }
  1600. static size_t check_dictionary(DICTIONARY *dict, size_t entries, size_t linked_list_members) {
  1601. size_t errors = 0;
  1602. fprintf(stderr, "dictionary entries %ld, expected %zu...\t\t\t\t\t", dictionary_stats_entries(dict), entries);
  1603. if (dictionary_stats_entries(dict) != (long)entries) {
  1604. fprintf(stderr, "FAILED\n");
  1605. errors++;
  1606. }
  1607. else
  1608. fprintf(stderr, "OK\n");
  1609. size_t ll = 0;
  1610. void *t;
  1611. dfe_start_read(dict, t)
  1612. ll++;
  1613. dfe_done(t);
  1614. fprintf(stderr, "dictionary foreach entries %zu, expected %zu...\t\t\t\t", ll, entries);
  1615. if(ll != entries) {
  1616. fprintf(stderr, "FAILED\n");
  1617. errors++;
  1618. }
  1619. else
  1620. fprintf(stderr, "OK\n");
  1621. ll = dictionary_walkthrough_read(dict, check_dictionary_callback, NULL);
  1622. fprintf(stderr, "dictionary walkthrough entries %zu, expected %zu...\t\t\t\t", ll, entries);
  1623. if(ll != entries) {
  1624. fprintf(stderr, "FAILED\n");
  1625. errors++;
  1626. }
  1627. else
  1628. fprintf(stderr, "OK\n");
  1629. ll = dictionary_sorted_walkthrough_read(dict, check_dictionary_callback, NULL);
  1630. fprintf(stderr, "dictionary sorted walkthrough entries %zu, expected %zu...\t\t\t", ll, entries);
  1631. if(ll != entries) {
  1632. fprintf(stderr, "FAILED\n");
  1633. errors++;
  1634. }
  1635. else
  1636. fprintf(stderr, "OK\n");
  1637. NAME_VALUE *nv;
  1638. for(ll = 0, nv = dict->first_item; nv ;nv = nv->next)
  1639. ll++;
  1640. fprintf(stderr, "dictionary linked list entries %zu, expected %zu...\t\t\t\t", ll, linked_list_members);
  1641. if(ll != linked_list_members) {
  1642. fprintf(stderr, "FAILED\n");
  1643. errors++;
  1644. }
  1645. else
  1646. fprintf(stderr, "OK\n");
  1647. return errors;
  1648. }
  1649. static int check_name_value_callback(const char *name, void *value, void *data) {
  1650. (void)name;
  1651. return value == data;
  1652. }
  1653. static size_t check_name_value_deleted_flag(DICTIONARY *dict, NAME_VALUE *nv, const char *name, const char *value, unsigned refcount, NAME_VALUE_FLAGS deleted_flags, bool searchable, bool browsable, bool linked) {
  1654. size_t errors = 0;
  1655. fprintf(stderr, "NAME_VALUE name is '%s', expected '%s'...\t\t\t\t", namevalue_get_name(nv), name);
  1656. if(strcmp(namevalue_get_name(nv), name) != 0) {
  1657. fprintf(stderr, "FAILED\n");
  1658. errors++;
  1659. }
  1660. else
  1661. fprintf(stderr, "OK\n");
  1662. fprintf(stderr, "NAME_VALUE value is '%s', expected '%s'...\t\t\t", (const char *)nv->value, value);
  1663. if(strcmp((const char *)nv->value, value) != 0) {
  1664. fprintf(stderr, "FAILED\n");
  1665. errors++;
  1666. }
  1667. else
  1668. fprintf(stderr, "OK\n");
  1669. fprintf(stderr, "NAME_VALUE refcount is %u, expected %u...\t\t\t\t\t", nv->refcount, refcount);
  1670. if (nv->refcount != refcount) {
  1671. fprintf(stderr, "FAILED\n");
  1672. errors++;
  1673. }
  1674. else
  1675. fprintf(stderr, "OK\n");
  1676. fprintf(stderr, "NAME_VALUE deleted flag is %s, expected %s...\t\t\t", (nv->flags & NAME_VALUE_FLAG_DELETED)?"TRUE":"FALSE", (deleted_flags & NAME_VALUE_FLAG_DELETED)?"TRUE":"FALSE");
  1677. if ((nv->flags & NAME_VALUE_FLAG_DELETED) != (deleted_flags & NAME_VALUE_FLAG_DELETED)) {
  1678. fprintf(stderr, "FAILED\n");
  1679. errors++;
  1680. }
  1681. else
  1682. fprintf(stderr, "OK\n");
  1683. void *v = dictionary_get(dict, name);
  1684. bool found = v == nv->value;
  1685. fprintf(stderr, "NAME_VALUE searchable %5s, expected %5s...\t\t\t\t", found?"true":"false", searchable?"true":"false");
  1686. if(found != searchable) {
  1687. fprintf(stderr, "FAILED\n");
  1688. errors++;
  1689. }
  1690. else
  1691. fprintf(stderr, "OK\n");
  1692. found = false;
  1693. void *t;
  1694. dfe_start_read(dict, t) {
  1695. if(t == nv->value) found = true;
  1696. }
  1697. dfe_done(t);
  1698. fprintf(stderr, "NAME_VALUE dfe browsable %5s, expected %5s...\t\t\t", found?"true":"false", browsable?"true":"false");
  1699. if(found != browsable) {
  1700. fprintf(stderr, "FAILED\n");
  1701. errors++;
  1702. }
  1703. else
  1704. fprintf(stderr, "OK\n");
  1705. found = dictionary_walkthrough_read(dict, check_name_value_callback, nv->value);
  1706. fprintf(stderr, "NAME_VALUE walkthrough browsable %5s, expected %5s...\t\t", found?"true":"false", browsable?"true":"false");
  1707. if(found != browsable) {
  1708. fprintf(stderr, "FAILED\n");
  1709. errors++;
  1710. }
  1711. else
  1712. fprintf(stderr, "OK\n");
  1713. found = dictionary_sorted_walkthrough_read(dict, check_name_value_callback, nv->value);
  1714. fprintf(stderr, "NAME_VALUE sorted walkthrough browsable %5s, expected %5s...\t", found?"true":"false", browsable?"true":"false");
  1715. if(found != browsable) {
  1716. fprintf(stderr, "FAILED\n");
  1717. errors++;
  1718. }
  1719. else
  1720. fprintf(stderr, "OK\n");
  1721. found = false;
  1722. NAME_VALUE *n;
  1723. for(n = dict->first_item; n ;n = n->next)
  1724. if(n == nv) found = true;
  1725. fprintf(stderr, "NAME_VALUE linked %5s, expected %5s...\t\t\t\t", found?"true":"false", linked?"true":"false");
  1726. if(found != linked) {
  1727. fprintf(stderr, "FAILED\n");
  1728. errors++;
  1729. }
  1730. else
  1731. fprintf(stderr, "OK\n");
  1732. return errors;
  1733. }
  1734. int dictionary_unittest(size_t entries) {
  1735. if(entries < 10) entries = 10;
  1736. DICTIONARY *dict;
  1737. size_t errors = 0;
  1738. fprintf(stderr, "Generating %zu names and values...\n", entries);
  1739. char **names = dictionary_unittest_generate_names(entries);
  1740. char **values = dictionary_unittest_generate_values(entries);
  1741. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  1742. dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED);
  1743. dictionary_unittest_clone(dict, names, values, entries, &errors);
  1744. fprintf(stderr, "\nCreating dictionary multi threaded, clone, %zu items\n", entries);
  1745. dict = dictionary_create(DICTIONARY_FLAG_NONE);
  1746. dictionary_unittest_clone(dict, names, values, entries, &errors);
  1747. fprintf(stderr, "\nCreating dictionary single threaded, non-clone, add-in-front options, %zu items\n", entries);
  1748. dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED|DICTIONARY_FLAG_NAME_LINK_DONT_CLONE|DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE|DICTIONARY_FLAG_ADD_IN_FRONT);
  1749. dictionary_unittest_nonclone(dict, names, values, entries, &errors);
  1750. fprintf(stderr, "\nCreating dictionary multi threaded, non-clone, add-in-front options, %zu items\n", entries);
  1751. dict = dictionary_create(DICTIONARY_FLAG_NAME_LINK_DONT_CLONE|DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE|DICTIONARY_FLAG_ADD_IN_FRONT);
  1752. dictionary_unittest_nonclone(dict, names, values, entries, &errors);
  1753. fprintf(stderr, "\nCreating dictionary single-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  1754. dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED|DICTIONARY_FLAG_NAME_LINK_DONT_CLONE|DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE|DICTIONARY_FLAG_DONT_OVERWRITE_VALUE);
  1755. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  1756. dictionary_unittest_run_and_measure_time(dict, "resetting non-overwrite entries", names, values, entries, &errors, dictionary_unittest_reset_dont_overwrite_nonclone);
  1757. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, &errors, dictionary_unittest_foreach);
  1758. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, &errors, dictionary_unittest_walkthrough);
  1759. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, &errors, dictionary_unittest_walkthrough_stop);
  1760. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  1761. fprintf(stderr, "\nCreating dictionary multi-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  1762. dict = dictionary_create(DICTIONARY_FLAG_NAME_LINK_DONT_CLONE|DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE|DICTIONARY_FLAG_DONT_OVERWRITE_VALUE);
  1763. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  1764. dictionary_unittest_run_and_measure_time(dict, "walkthrough write delete this", names, values, entries, &errors, dictionary_unittest_walkthrough_delete_this);
  1765. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  1766. fprintf(stderr, "\nCreating dictionary multi-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  1767. dict = dictionary_create(DICTIONARY_FLAG_NAME_LINK_DONT_CLONE|DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE|DICTIONARY_FLAG_DONT_OVERWRITE_VALUE);
  1768. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  1769. dictionary_unittest_run_and_measure_time(dict, "foreach write delete this", names, values, entries, &errors, dictionary_unittest_foreach_delete_this);
  1770. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop empty", names, values, 0, &errors, dictionary_unittest_foreach);
  1771. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback empty", names, values, 0, &errors, dictionary_unittest_walkthrough);
  1772. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  1773. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  1774. dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED);
  1775. dictionary_unittest_sorting(dict, names, values, entries, &errors);
  1776. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  1777. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  1778. dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED);
  1779. dictionary_unittest_null_dfe(dict, names, values, entries, &errors);
  1780. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  1781. fprintf(stderr, "\nCreating dictionary single threaded, noclone, %zu items\n", entries);
  1782. dict = dictionary_create(DICTIONARY_FLAG_SINGLE_THREADED|DICTIONARY_FLAG_VALUE_LINK_DONT_CLONE);
  1783. dictionary_unittest_null_dfe(dict, names, values, entries, &errors);
  1784. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  1785. // check reference counters
  1786. {
  1787. fprintf(stderr, "\nTesting reference counters:\n");
  1788. dict = dictionary_create(DICTIONARY_FLAG_NONE|DICTIONARY_FLAG_NAME_LINK_DONT_CLONE);
  1789. errors += check_dictionary(dict, 0, 0);
  1790. fprintf(stderr, "\nAdding test item to dictionary and acquiring it\n");
  1791. dictionary_set(dict, "test", "ITEM1", 6);
  1792. NAME_VALUE *nv = (NAME_VALUE *)dictionary_get_and_acquire_item(dict, "test");
  1793. errors += check_dictionary(dict, 1, 1);
  1794. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_NONE, true, true, true);
  1795. fprintf(stderr, "\nChecking that reference counters are increased:\n");
  1796. void *t;
  1797. dfe_start_read(dict, t) {
  1798. errors += check_dictionary(dict, 1, 1);
  1799. errors +=
  1800. check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 2, NAME_VALUE_FLAG_NONE, true, true, true);
  1801. }
  1802. dfe_done(t);
  1803. fprintf(stderr, "\nChecking that reference counters are decreased:\n");
  1804. errors += check_dictionary(dict, 1, 1);
  1805. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_NONE, true, true, true);
  1806. fprintf(stderr, "\nDeleting the item we have acquired:\n");
  1807. dictionary_del(dict, "test");
  1808. errors += check_dictionary(dict, 0, 1);
  1809. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_DELETED, false, false, true);
  1810. fprintf(stderr, "\nAdding another item with the same name of the item we deleted, while being acquired:\n");
  1811. dictionary_set(dict, "test", "ITEM2", 6);
  1812. errors += check_dictionary(dict, 1, 2);
  1813. fprintf(stderr, "\nAcquiring the second item:\n");
  1814. NAME_VALUE *nv2 = (NAME_VALUE *)dictionary_get_and_acquire_item(dict, "test");
  1815. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_DELETED, false, false, true);
  1816. errors += check_name_value_deleted_flag(dict, nv2, "test", "ITEM2", 1, NAME_VALUE_FLAG_NONE, true, true, true);
  1817. fprintf(stderr, "\nReleasing the second item (the first is still acquired):\n");
  1818. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)nv2);
  1819. errors += check_dictionary(dict, 1, 2);
  1820. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_DELETED, false, false, true);
  1821. errors += check_name_value_deleted_flag(dict, nv2, "test", "ITEM2", 0, NAME_VALUE_FLAG_NONE, true, true, true);
  1822. fprintf(stderr, "\nDeleting the second item (the first is still acquired):\n");
  1823. dictionary_del(dict, "test");
  1824. errors += check_dictionary(dict, 0, 1);
  1825. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_DELETED, false, false, true);
  1826. fprintf(stderr, "\nReleasing the first item (which we have already deleted):\n");
  1827. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)nv);
  1828. errors += check_dictionary(dict, 0, 0);
  1829. fprintf(stderr, "\nAdding again the test item to dictionary and acquiring it\n");
  1830. dictionary_set(dict, "test", "ITEM1", 6);
  1831. nv = (NAME_VALUE *)dictionary_get_and_acquire_item(dict, "test");
  1832. errors += check_dictionary(dict, 1, 1);
  1833. errors += check_name_value_deleted_flag(dict, nv, "test", "ITEM1", 1, NAME_VALUE_FLAG_NONE, true, true, true);
  1834. fprintf(stderr, "\nDestroying the dictionary while we have acquired an item\n");
  1835. dictionary_destroy(dict);
  1836. fprintf(stderr, "Releasing the item (on a destroyed dictionary)\n");
  1837. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)nv);
  1838. nv = NULL;
  1839. dict = NULL;
  1840. }
  1841. // check string
  1842. {
  1843. long string_entries_starting = dictionary_stats_entries(&string_dictionary);
  1844. fprintf(stderr, "\nChecking strings...\n");
  1845. STRING *s1 = string_strdupz("hello unittest");
  1846. STRING *s2 = string_strdupz("hello unittest");
  1847. if(s1 != s2) {
  1848. errors++;
  1849. fprintf(stderr, "ERROR: duplicating strings are not deduplicated\n");
  1850. }
  1851. else
  1852. fprintf(stderr, "OK: duplicating string are deduplicated\n");
  1853. STRING *s3 = string_dup(s1);
  1854. if(s3 != s1) {
  1855. errors++;
  1856. fprintf(stderr, "ERROR: cloning strings are not deduplicated\n");
  1857. }
  1858. else
  1859. fprintf(stderr, "OK: cloning string are deduplicated\n");
  1860. STRING_ENTRY *se = (STRING_ENTRY *)s1;
  1861. if(se->refcount != 3) {
  1862. errors++;
  1863. fprintf(stderr, "ERROR: string refcount is not 3\n");
  1864. }
  1865. else
  1866. fprintf(stderr, "OK: string refcount is 3\n");
  1867. STRING *s4 = string_strdupz("world unittest");
  1868. if(s4 == s1) {
  1869. errors++;
  1870. fprintf(stderr, "ERROR: string is sharing pointers on different strings\n");
  1871. }
  1872. else
  1873. fprintf(stderr, "OK: string is properly handling different strings\n");
  1874. usec_t start_ut, end_ut;
  1875. STRING **strings = mallocz(entries * sizeof(STRING *));
  1876. start_ut = now_realtime_usec();
  1877. for(size_t i = 0; i < entries ;i++) {
  1878. strings[i] = string_strdupz(names[i]);
  1879. }
  1880. end_ut = now_realtime_usec();
  1881. fprintf(stderr, "Created %zu strings in %llu usecs\n", entries, end_ut - start_ut);
  1882. start_ut = now_realtime_usec();
  1883. for(size_t i = 0; i < entries ;i++) {
  1884. strings[i] = string_dup(strings[i]);
  1885. }
  1886. end_ut = now_realtime_usec();
  1887. fprintf(stderr, "Cloned %zu strings in %llu usecs\n", entries, end_ut - start_ut);
  1888. start_ut = now_realtime_usec();
  1889. for(size_t i = 0; i < entries ;i++) {
  1890. string_freez(strings[i]);
  1891. string_freez(strings[i]);
  1892. }
  1893. end_ut = now_realtime_usec();
  1894. fprintf(stderr, "Freed %zu strings in %llu usecs\n", entries, end_ut - start_ut);
  1895. freez(strings);
  1896. if(dictionary_stats_entries(&string_dictionary) != string_entries_starting + 2) {
  1897. errors++;
  1898. fprintf(stderr, "ERROR: strings dictionary should have %ld items but it has %ld\n", string_entries_starting + 2, dictionary_stats_entries(&string_dictionary));
  1899. }
  1900. else
  1901. fprintf(stderr, "OK: strings dictionary has 2 items\n");
  1902. }
  1903. // check 2-way merge
  1904. {
  1905. struct testcase {
  1906. char *src1; char *src2; char *expected;
  1907. } tests[] = {
  1908. { "", "", ""},
  1909. { "a", "", "[x]"},
  1910. { "", "a", "[x]"},
  1911. { "a", "a", "a"},
  1912. { "abcd", "abcd", "abcd"},
  1913. { "foo_cs", "bar_cs", "[x]_cs"},
  1914. { "cp_UNIQUE_INFIX_cs", "cp_unique_infix_cs", "cp_[x]_cs"},
  1915. { "cp_UNIQUE_INFIX_ci_unique_infix_cs", "cp_unique_infix_ci_UNIQUE_INFIX_cs", "cp_[x]_cs"},
  1916. { "foo[1234]", "foo[4321]", "foo[[x]]"},
  1917. { NULL, NULL, NULL },
  1918. };
  1919. for (struct testcase *tc = &tests[0]; tc->expected != NULL; tc++) {
  1920. STRING *src1 = string_strdupz(tc->src1);
  1921. STRING *src2 = string_strdupz(tc->src2);
  1922. STRING *expected = string_strdupz(tc->expected);
  1923. STRING *result = string_2way_merge(src1, src2);
  1924. if (string_cmp(result, expected) != 0) {
  1925. fprintf(stderr, "string_2way_merge(\"%s\", \"%s\") -> \"%s\" (expected=\"%s\")\n",
  1926. string2str(src1),
  1927. string2str(src2),
  1928. string2str(result),
  1929. string2str(expected));
  1930. errors++;
  1931. }
  1932. string_freez(src1);
  1933. string_freez(src2);
  1934. string_freez(expected);
  1935. string_freez(result);
  1936. }
  1937. }
  1938. dictionary_unittest_free_char_pp(names, entries);
  1939. dictionary_unittest_free_char_pp(values, entries);
  1940. fprintf(stderr, "\n%zu errors found\n", errors);
  1941. return errors ? 1 : 0;
  1942. }