dictionary.c 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define DICTIONARY_INTERNALS
  3. #include "../libnetdata.h"
  4. // runtime flags of the dictionary - must be checked with atomics
  5. typedef enum __attribute__ ((__packed__)) {
  6. DICT_FLAG_NONE = 0,
  7. DICT_FLAG_DESTROYED = (1 << 0), // this dictionary has been destroyed
  8. } DICT_FLAGS;
  9. #define dict_flag_check(dict, flag) (__atomic_load_n(&((dict)->flags), __ATOMIC_SEQ_CST) & (flag))
  10. #define dict_flag_set(dict, flag) __atomic_or_fetch(&((dict)->flags), flag, __ATOMIC_SEQ_CST)
  11. #define dict_flag_clear(dict, flag) __atomic_and_fetch(&((dict)->flags), ~(flag), __ATOMIC_SEQ_CST)
  12. // flags macros
  13. #define is_dictionary_destroyed(dict) dict_flag_check(dict, DICT_FLAG_DESTROYED)
  14. // configuration options macros
  15. #define is_dictionary_single_threaded(dict) ((dict)->options & DICT_OPTION_SINGLE_THREADED)
  16. #define is_view_dictionary(dict) ((dict)->master)
  17. #define is_master_dictionary(dict) (!is_view_dictionary(dict))
  18. typedef enum __attribute__ ((__packed__)) item_options {
  19. ITEM_OPTION_NONE = 0,
  20. ITEM_OPTION_ALLOCATED_NAME = (1 << 0), // the name pointer is a STRING
  21. // IMPORTANT: This is 1-bit - to add more change ITEM_OPTIONS_BITS
  22. } ITEM_OPTIONS;
  23. typedef enum __attribute__ ((__packed__)) item_flags {
  24. ITEM_FLAG_NONE = 0,
  25. ITEM_FLAG_DELETED = (1 << 0), // this item is marked deleted, so it is not available for traversal (deleted from the index too)
  26. ITEM_FLAG_BEING_CREATED = (1 << 1), // this item is currently being created - this flag is removed when construction finishes
  27. // IMPORTANT: This is 8-bit
  28. } ITEM_FLAGS;
  29. #define item_flag_check(item, flag) (__atomic_load_n(&((item)->flags), __ATOMIC_SEQ_CST) & (flag))
  30. #define item_flag_set(item, flag) __atomic_or_fetch(&((item)->flags), flag, __ATOMIC_SEQ_CST)
  31. #define item_flag_clear(item, flag) __atomic_and_fetch(&((item)->flags), ~(flag), __ATOMIC_SEQ_CST)
  32. #define item_shared_flag_check(item, flag) (__atomic_load_n(&((item)->shared->flags), __ATOMIC_SEQ_CST) & (flag))
  33. #define item_shared_flag_set(item, flag) __atomic_or_fetch(&((item)->shared->flags), flag, __ATOMIC_SEQ_CST)
  34. #define item_shared_flag_clear(item, flag) __atomic_and_fetch(&((item)->shared->flags), ~(flag), __ATOMIC_SEQ_CST)
  35. #define REFCOUNT_DELETING (-100)
  36. #define ITEM_FLAGS_TYPE uint8_t
  37. #define KEY_LEN_TYPE uint32_t
  38. #define VALUE_LEN_TYPE uint32_t
  39. #define ITEM_OPTIONS_BITS 1
  40. #define KEY_LEN_BITS ((sizeof(KEY_LEN_TYPE) * 8) - (sizeof(ITEM_FLAGS_TYPE) * 8) - ITEM_OPTIONS_BITS)
  41. #define KEY_LEN_MAX ((1 << KEY_LEN_BITS) - 1)
  42. #define VALUE_LEN_BITS ((sizeof(VALUE_LEN_TYPE) * 8) - (sizeof(ITEM_FLAGS_TYPE) * 8))
  43. #define VALUE_LEN_MAX ((1 << VALUE_LEN_BITS) - 1)
  44. /*
  45. * Every item in the dictionary has the following structure.
  46. */
  47. typedef int32_t REFCOUNT;
  48. typedef struct dictionary_item_shared {
  49. void *value; // the value of the dictionary item
  50. // the order of the following items is important!
  51. // The total of their storage should be 64-bits
  52. REFCOUNT links; // how many links this item has
  53. VALUE_LEN_TYPE value_len:VALUE_LEN_BITS; // the size of the value
  54. ITEM_FLAGS_TYPE flags; // shared flags
  55. } DICTIONARY_ITEM_SHARED;
  56. struct dictionary_item {
  57. #ifdef NETDATA_INTERNAL_CHECKS
  58. DICTIONARY *dict;
  59. pid_t creator_pid;
  60. pid_t deleter_pid;
  61. pid_t ll_adder_pid;
  62. pid_t ll_remover_pid;
  63. #endif
  64. DICTIONARY_ITEM_SHARED *shared;
  65. struct dictionary_item *next; // a double linked list to allow fast insertions and deletions
  66. struct dictionary_item *prev;
  67. union {
  68. STRING *string_name; // the name of the dictionary item
  69. char *caller_name; // the user supplied string pointer
  70. // void *key_ptr; // binary key pointer
  71. };
  72. // the order of the following items is important!
  73. // The total of their storage should be 64-bits
  74. REFCOUNT refcount; // the private reference counter
  75. KEY_LEN_TYPE key_len:KEY_LEN_BITS; // the size of key indexed (for strings, including the null terminator)
  76. // this is (2^23 - 1) = 8.388.607 bytes max key length.
  77. ITEM_OPTIONS options:ITEM_OPTIONS_BITS; // permanent configuration options
  78. // (no atomic operations on this - they never change)
  79. ITEM_FLAGS_TYPE flags; // runtime changing flags for this item (atomic operations on this)
  80. // cannot be a bit field because of atomics.
  81. };
  82. struct dictionary_hooks {
  83. REFCOUNT links;
  84. usec_t last_master_deletion_us;
  85. void (*ins_callback)(const DICTIONARY_ITEM *item, void *value, void *data);
  86. void *ins_callback_data;
  87. bool (*conflict_callback)(const DICTIONARY_ITEM *item, void *old_value, void *new_value, void *data);
  88. void *conflict_callback_data;
  89. void (*react_callback)(const DICTIONARY_ITEM *item, void *value, void *data);
  90. void *react_callback_data;
  91. void (*del_callback)(const DICTIONARY_ITEM *item, void *value, void *data);
  92. void *del_callback_data;
  93. };
  94. struct dictionary_stats dictionary_stats_category_other = {
  95. .name = "other",
  96. };
  97. struct dictionary {
  98. #ifdef NETDATA_INTERNAL_CHECKS
  99. const char *creation_function;
  100. const char *creation_file;
  101. size_t creation_line;
  102. #endif
  103. usec_t last_gc_run_us;
  104. DICT_OPTIONS options; // the configuration flags of the dictionary (they never change - no atomics)
  105. DICT_FLAGS flags; // run time flags for the dictionary (they change all the time - atomics needed)
  106. ARAL *value_aral;
  107. struct { // support for multiple indexing engines
  108. Pvoid_t JudyHSArray; // the hash table
  109. netdata_rwlock_t rwlock; // protect the index
  110. } index;
  111. struct {
  112. DICTIONARY_ITEM *list; // the double linked list of all items in the dictionary
  113. netdata_rwlock_t rwlock; // protect the linked-list
  114. pid_t writer_pid; // the gettid() of the writer
  115. size_t writer_depth; // nesting of write locks
  116. } items;
  117. struct dictionary_hooks *hooks; // pointer to external function callbacks to be called at certain points
  118. struct dictionary_stats *stats; // statistics data, when DICT_OPTION_STATS is set
  119. DICTIONARY *master; // the master dictionary
  120. DICTIONARY *next; // linked list for delayed destruction (garbage collection of whole dictionaries)
  121. size_t version; // the current version of the dictionary
  122. // it is incremented when:
  123. // - item added
  124. // - item removed
  125. // - item value reset
  126. // - conflict callback returns true
  127. // - function dictionary_version_increment() is called
  128. long int entries; // how many items are currently in the index (the linked list may have more)
  129. long int referenced_items; // how many items of the dictionary are currently being used by 3rd parties
  130. long int pending_deletion_items; // how many items of the dictionary have been deleted, but have not been removed yet
  131. #ifdef NETDATA_INTERNAL_CHECKS
  132. netdata_mutex_t global_pointer_registry_mutex;
  133. Pvoid_t global_pointer_registry;
  134. #endif
  135. };
  136. // ----------------------------------------------------------------------------
  137. // forward definitions of functions used in reverse order in the code
  138. static void garbage_collect_pending_deletes(DICTIONARY *dict);
  139. static inline void item_linked_list_remove(DICTIONARY *dict, DICTIONARY_ITEM *item);
  140. static size_t dict_item_free_with_hooks(DICTIONARY *dict, DICTIONARY_ITEM *item);
  141. static inline const char *item_get_name(const DICTIONARY_ITEM *item);
  142. static inline int hashtable_delete_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *item);
  143. static void item_release(DICTIONARY *dict, DICTIONARY_ITEM *item);
  144. static bool dict_item_set_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item);
  145. #define RC_ITEM_OK ( 0)
  146. #define RC_ITEM_MARKED_FOR_DELETION (-1) // the item is marked for deletion
  147. #define RC_ITEM_IS_CURRENTLY_BEING_DELETED (-2) // the item is currently being deleted
  148. #define RC_ITEM_IS_CURRENTLY_BEING_CREATED (-3) // the item is currently being deleted
  149. #define RC_ITEM_IS_REFERENCED (-4) // the item is currently referenced
  150. #define item_check_and_acquire(dict, item) (item_check_and_acquire_advanced(dict, item, false) == RC_ITEM_OK)
  151. static int item_check_and_acquire_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item, bool having_index_lock);
  152. #define item_is_not_referenced_and_can_be_removed(dict, item) (item_is_not_referenced_and_can_be_removed_advanced(dict, item) == RC_ITEM_OK)
  153. static inline int item_is_not_referenced_and_can_be_removed_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item);
  154. // ----------------------------------------------------------------------------
  155. // validate each pointer is indexed once - internal checks only
  156. static inline void pointer_index_init(DICTIONARY *dict __maybe_unused) {
  157. #ifdef NETDATA_INTERNAL_CHECKS
  158. netdata_mutex_init(&dict->global_pointer_registry_mutex);
  159. #else
  160. ;
  161. #endif
  162. }
  163. static inline void pointer_destroy_index(DICTIONARY *dict __maybe_unused) {
  164. #ifdef NETDATA_INTERNAL_CHECKS
  165. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  166. JudyHSFreeArray(&dict->global_pointer_registry, PJE0);
  167. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  168. #else
  169. ;
  170. #endif
  171. }
  172. static inline void pointer_add(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item __maybe_unused) {
  173. #ifdef NETDATA_INTERNAL_CHECKS
  174. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  175. Pvoid_t *PValue = JudyHSIns(&dict->global_pointer_registry, &item, sizeof(void *), PJE0);
  176. if(*PValue != NULL)
  177. fatal("pointer already exists in registry");
  178. *PValue = item;
  179. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  180. #else
  181. ;
  182. #endif
  183. }
  184. static inline void pointer_check(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item __maybe_unused) {
  185. #ifdef NETDATA_INTERNAL_CHECKS
  186. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  187. Pvoid_t *PValue = JudyHSGet(dict->global_pointer_registry, &item, sizeof(void *));
  188. if(PValue == NULL)
  189. fatal("pointer is not found in registry");
  190. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  191. #else
  192. ;
  193. #endif
  194. }
  195. static inline void pointer_del(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item __maybe_unused) {
  196. #ifdef NETDATA_INTERNAL_CHECKS
  197. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  198. int ret = JudyHSDel(&dict->global_pointer_registry, &item, sizeof(void *), PJE0);
  199. if(!ret)
  200. fatal("pointer to be deleted does not exist in registry");
  201. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  202. #else
  203. ;
  204. #endif
  205. }
  206. // ----------------------------------------------------------------------------
  207. // memory statistics
  208. static inline void DICTIONARY_STATS_PLUS_MEMORY(DICTIONARY *dict, size_t key_size, size_t item_size, size_t value_size) {
  209. if(key_size)
  210. __atomic_fetch_add(&dict->stats->memory.index, (long)JUDYHS_INDEX_SIZE_ESTIMATE(key_size), __ATOMIC_RELAXED);
  211. if(item_size)
  212. __atomic_fetch_add(&dict->stats->memory.dict, (long)item_size, __ATOMIC_RELAXED);
  213. if(value_size)
  214. __atomic_fetch_add(&dict->stats->memory.values, (long)value_size, __ATOMIC_RELAXED);
  215. }
  216. static inline void DICTIONARY_STATS_MINUS_MEMORY(DICTIONARY *dict, size_t key_size, size_t item_size, size_t value_size) {
  217. if(key_size)
  218. __atomic_fetch_sub(&dict->stats->memory.index, (long)JUDYHS_INDEX_SIZE_ESTIMATE(key_size), __ATOMIC_RELAXED);
  219. if(item_size)
  220. __atomic_fetch_sub(&dict->stats->memory.dict, (long)item_size, __ATOMIC_RELAXED);
  221. if(value_size)
  222. __atomic_fetch_sub(&dict->stats->memory.values, (long)value_size, __ATOMIC_RELAXED);
  223. }
  224. // ----------------------------------------------------------------------------
  225. // callbacks registration
  226. static inline void dictionary_hooks_allocate(DICTIONARY *dict) {
  227. if(dict->hooks) return;
  228. dict->hooks = callocz(1, sizeof(struct dictionary_hooks));
  229. dict->hooks->links = 1;
  230. DICTIONARY_STATS_PLUS_MEMORY(dict, 0, sizeof(struct dictionary_hooks), 0);
  231. }
  232. static inline size_t dictionary_hooks_free(DICTIONARY *dict) {
  233. if(!dict->hooks) return 0;
  234. REFCOUNT links = __atomic_sub_fetch(&dict->hooks->links, 1, __ATOMIC_SEQ_CST);
  235. if(links == 0) {
  236. freez(dict->hooks);
  237. dict->hooks = NULL;
  238. DICTIONARY_STATS_MINUS_MEMORY(dict, 0, sizeof(struct dictionary_hooks), 0);
  239. return sizeof(struct dictionary_hooks);
  240. }
  241. return 0;
  242. }
  243. void dictionary_register_insert_callback(DICTIONARY *dict, void (*ins_callback)(const DICTIONARY_ITEM *item, void *value, void *data), void *data) {
  244. if(unlikely(is_view_dictionary(dict)))
  245. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  246. dictionary_hooks_allocate(dict);
  247. dict->hooks->ins_callback = ins_callback;
  248. dict->hooks->ins_callback_data = data;
  249. }
  250. void dictionary_register_conflict_callback(DICTIONARY *dict, bool (*conflict_callback)(const DICTIONARY_ITEM *item, void *old_value, void *new_value, void *data), void *data) {
  251. if(unlikely(is_view_dictionary(dict)))
  252. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  253. internal_error(!(dict->options & DICT_OPTION_DONT_OVERWRITE_VALUE), "DICTIONARY: registering conflict callback without DICT_OPTION_DONT_OVERWRITE_VALUE");
  254. dict->options |= DICT_OPTION_DONT_OVERWRITE_VALUE;
  255. dictionary_hooks_allocate(dict);
  256. dict->hooks->conflict_callback = conflict_callback;
  257. dict->hooks->conflict_callback_data = data;
  258. }
  259. void dictionary_register_react_callback(DICTIONARY *dict, void (*react_callback)(const DICTIONARY_ITEM *item, void *value, void *data), void *data) {
  260. if(unlikely(is_view_dictionary(dict)))
  261. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  262. dictionary_hooks_allocate(dict);
  263. dict->hooks->react_callback = react_callback;
  264. dict->hooks->react_callback_data = data;
  265. }
  266. void dictionary_register_delete_callback(DICTIONARY *dict, void (*del_callback)(const DICTIONARY_ITEM *item, void *value, void *data), void *data) {
  267. if(unlikely(is_view_dictionary(dict)))
  268. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  269. dictionary_hooks_allocate(dict);
  270. dict->hooks->del_callback = del_callback;
  271. dict->hooks->del_callback_data = data;
  272. }
  273. // ----------------------------------------------------------------------------
  274. // dictionary statistics API
  275. size_t dictionary_version(DICTIONARY *dict) {
  276. if(unlikely(!dict)) return 0;
  277. // this is required for views to return the right number
  278. garbage_collect_pending_deletes(dict);
  279. return __atomic_load_n(&dict->version, __ATOMIC_SEQ_CST);
  280. }
  281. size_t dictionary_entries(DICTIONARY *dict) {
  282. if(unlikely(!dict)) return 0;
  283. // this is required for views to return the right number
  284. garbage_collect_pending_deletes(dict);
  285. long int entries = __atomic_load_n(&dict->entries, __ATOMIC_SEQ_CST);
  286. if(entries < 0)
  287. fatal("DICTIONARY: entries is negative: %ld", entries);
  288. return entries;
  289. }
  290. size_t dictionary_referenced_items(DICTIONARY *dict) {
  291. if(unlikely(!dict)) return 0;
  292. long int referenced_items = __atomic_load_n(&dict->referenced_items, __ATOMIC_SEQ_CST);
  293. if(referenced_items < 0)
  294. fatal("DICTIONARY: referenced items is negative: %ld", referenced_items);
  295. return referenced_items;
  296. }
  297. long int dictionary_stats_for_registry(DICTIONARY *dict) {
  298. if(unlikely(!dict)) return 0;
  299. return (dict->stats->memory.index + dict->stats->memory.dict);
  300. }
  301. void dictionary_version_increment(DICTIONARY *dict) {
  302. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  303. }
  304. // ----------------------------------------------------------------------------
  305. // internal statistics API
  306. static inline void DICTIONARY_STATS_SEARCHES_PLUS1(DICTIONARY *dict) {
  307. __atomic_fetch_add(&dict->stats->ops.searches, 1, __ATOMIC_RELAXED);
  308. }
  309. static inline void DICTIONARY_ENTRIES_PLUS1(DICTIONARY *dict) {
  310. // statistics
  311. __atomic_fetch_add(&dict->stats->items.entries, 1, __ATOMIC_RELAXED);
  312. __atomic_fetch_add(&dict->stats->items.referenced, 1, __ATOMIC_RELAXED);
  313. __atomic_fetch_add(&dict->stats->ops.inserts, 1, __ATOMIC_RELAXED);
  314. if(unlikely(is_dictionary_single_threaded(dict))) {
  315. dict->version++;
  316. dict->entries++;
  317. dict->referenced_items++;
  318. }
  319. else {
  320. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  321. __atomic_fetch_add(&dict->entries, 1, __ATOMIC_SEQ_CST);
  322. __atomic_fetch_add(&dict->referenced_items, 1, __ATOMIC_SEQ_CST);
  323. }
  324. }
  325. static inline void DICTIONARY_ENTRIES_MINUS1(DICTIONARY *dict) {
  326. // statistics
  327. __atomic_fetch_add(&dict->stats->ops.deletes, 1, __ATOMIC_RELAXED);
  328. __atomic_fetch_sub(&dict->stats->items.entries, 1, __ATOMIC_RELAXED);
  329. size_t entries; (void)entries;
  330. if(unlikely(is_dictionary_single_threaded(dict))) {
  331. dict->version++;
  332. entries = dict->entries++;
  333. }
  334. else {
  335. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  336. entries = __atomic_fetch_sub(&dict->entries, 1, __ATOMIC_SEQ_CST);
  337. }
  338. #ifdef NETDATA_INTERNAL_CHECKS
  339. if(unlikely(entries == 0))
  340. fatal("DICT: negative number of entries in dictionary created from %s() (%zu@%s)",
  341. dict->creation_function,
  342. dict->creation_line,
  343. dict->creation_file);
  344. #endif
  345. }
  346. static inline void DICTIONARY_VALUE_RESETS_PLUS1(DICTIONARY *dict) {
  347. __atomic_fetch_add(&dict->stats->ops.resets, 1, __ATOMIC_RELAXED);
  348. if(unlikely(is_dictionary_single_threaded(dict)))
  349. dict->version++;
  350. else
  351. __atomic_fetch_add(&dict->version, 1, __ATOMIC_SEQ_CST);
  352. }
  353. static inline void DICTIONARY_STATS_TRAVERSALS_PLUS1(DICTIONARY *dict) {
  354. __atomic_fetch_add(&dict->stats->ops.traversals, 1, __ATOMIC_RELAXED);
  355. }
  356. static inline void DICTIONARY_STATS_WALKTHROUGHS_PLUS1(DICTIONARY *dict) {
  357. __atomic_fetch_add(&dict->stats->ops.walkthroughs, 1, __ATOMIC_RELAXED);
  358. }
  359. static inline void DICTIONARY_STATS_CHECK_SPINS_PLUS(DICTIONARY *dict, size_t count) {
  360. __atomic_fetch_add(&dict->stats->spin_locks.use_spins, count, __ATOMIC_RELAXED);
  361. }
  362. static inline void DICTIONARY_STATS_INSERT_SPINS_PLUS(DICTIONARY *dict, size_t count) {
  363. __atomic_fetch_add(&dict->stats->spin_locks.insert_spins, count, __ATOMIC_RELAXED);
  364. }
  365. static inline void DICTIONARY_STATS_DELETE_SPINS_PLUS(DICTIONARY *dict, size_t count) {
  366. __atomic_fetch_add(&dict->stats->spin_locks.delete_spins, count, __ATOMIC_RELAXED);
  367. }
  368. static inline void DICTIONARY_STATS_SEARCH_IGNORES_PLUS1(DICTIONARY *dict) {
  369. __atomic_fetch_add(&dict->stats->spin_locks.search_spins, 1, __ATOMIC_RELAXED);
  370. }
  371. static inline void DICTIONARY_STATS_CALLBACK_INSERTS_PLUS1(DICTIONARY *dict) {
  372. __atomic_fetch_add(&dict->stats->callbacks.inserts, 1, __ATOMIC_RELAXED);
  373. }
  374. static inline void DICTIONARY_STATS_CALLBACK_CONFLICTS_PLUS1(DICTIONARY *dict) {
  375. __atomic_fetch_add(&dict->stats->callbacks.conflicts, 1, __ATOMIC_RELAXED);
  376. }
  377. static inline void DICTIONARY_STATS_CALLBACK_REACTS_PLUS1(DICTIONARY *dict) {
  378. __atomic_fetch_add(&dict->stats->callbacks.reacts, 1, __ATOMIC_RELAXED);
  379. }
  380. static inline void DICTIONARY_STATS_CALLBACK_DELETES_PLUS1(DICTIONARY *dict) {
  381. __atomic_fetch_add(&dict->stats->callbacks.deletes, 1, __ATOMIC_RELAXED);
  382. }
  383. static inline void DICTIONARY_STATS_GARBAGE_COLLECTIONS_PLUS1(DICTIONARY *dict) {
  384. __atomic_fetch_add(&dict->stats->ops.garbage_collections, 1, __ATOMIC_RELAXED);
  385. }
  386. static inline void DICTIONARY_STATS_DICT_CREATIONS_PLUS1(DICTIONARY *dict) {
  387. __atomic_fetch_add(&dict->stats->dictionaries.active, 1, __ATOMIC_RELAXED);
  388. __atomic_fetch_add(&dict->stats->ops.creations, 1, __ATOMIC_RELAXED);
  389. }
  390. static inline void DICTIONARY_STATS_DICT_DESTRUCTIONS_PLUS1(DICTIONARY *dict) {
  391. __atomic_fetch_sub(&dict->stats->dictionaries.active, 1, __ATOMIC_RELAXED);
  392. __atomic_fetch_add(&dict->stats->ops.destructions, 1, __ATOMIC_RELAXED);
  393. }
  394. static inline void DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(DICTIONARY *dict) {
  395. __atomic_fetch_add(&dict->stats->dictionaries.deleted, 1, __ATOMIC_RELAXED);
  396. }
  397. static inline void DICTIONARY_STATS_DICT_DESTROY_QUEUED_MINUS1(DICTIONARY *dict) {
  398. __atomic_fetch_sub(&dict->stats->dictionaries.deleted, 1, __ATOMIC_RELAXED);
  399. }
  400. static inline void DICTIONARY_STATS_DICT_FLUSHES_PLUS1(DICTIONARY *dict) {
  401. __atomic_fetch_add(&dict->stats->ops.flushes, 1, __ATOMIC_RELAXED);
  402. }
  403. static inline long int DICTIONARY_REFERENCED_ITEMS_PLUS1(DICTIONARY *dict) {
  404. __atomic_fetch_add(&dict->stats->items.referenced, 1, __ATOMIC_RELAXED);
  405. if(unlikely(is_dictionary_single_threaded(dict)))
  406. return ++dict->referenced_items;
  407. else
  408. return __atomic_add_fetch(&dict->referenced_items, 1, __ATOMIC_SEQ_CST);
  409. }
  410. static inline long int DICTIONARY_REFERENCED_ITEMS_MINUS1(DICTIONARY *dict) {
  411. __atomic_fetch_sub(&dict->stats->items.referenced, 1, __ATOMIC_RELAXED);
  412. long int referenced_items;
  413. if(unlikely(is_dictionary_single_threaded(dict)))
  414. referenced_items = --dict->referenced_items;
  415. else
  416. referenced_items = __atomic_sub_fetch(&dict->referenced_items, 1, __ATOMIC_SEQ_CST);
  417. #ifdef NETDATA_INTERNAL_CHECKS
  418. if(unlikely(referenced_items < 0))
  419. fatal("DICT: negative number of referenced items (%ld) in dictionary created from %s() (%zu@%s)",
  420. referenced_items,
  421. dict->creation_function,
  422. dict->creation_line,
  423. dict->creation_file);
  424. #endif
  425. return referenced_items;
  426. }
  427. static inline long int DICTIONARY_PENDING_DELETES_PLUS1(DICTIONARY *dict) {
  428. __atomic_fetch_add(&dict->stats->items.pending_deletion, 1, __ATOMIC_RELAXED);
  429. if(unlikely(is_dictionary_single_threaded(dict)))
  430. return ++dict->pending_deletion_items;
  431. else
  432. return __atomic_add_fetch(&dict->pending_deletion_items, 1, __ATOMIC_SEQ_CST);
  433. }
  434. static inline long int DICTIONARY_PENDING_DELETES_MINUS1(DICTIONARY *dict) {
  435. __atomic_fetch_sub(&dict->stats->items.pending_deletion, 1, __ATOMIC_RELAXED);
  436. if(unlikely(is_dictionary_single_threaded(dict)))
  437. return --dict->pending_deletion_items;
  438. else
  439. return __atomic_sub_fetch(&dict->pending_deletion_items, 1, __ATOMIC_SEQ_CST);
  440. }
  441. static inline long int DICTIONARY_PENDING_DELETES_GET(DICTIONARY *dict) {
  442. if(unlikely(is_dictionary_single_threaded(dict)))
  443. return dict->pending_deletion_items;
  444. else
  445. return __atomic_load_n(&dict->pending_deletion_items, __ATOMIC_SEQ_CST);
  446. }
  447. static inline REFCOUNT DICTIONARY_ITEM_REFCOUNT_GET(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  448. if(unlikely(dict && is_dictionary_single_threaded(dict))) // this is an exception, dict can be null
  449. return item->refcount;
  450. else
  451. return (REFCOUNT)__atomic_load_n(&item->refcount, __ATOMIC_SEQ_CST);
  452. }
  453. static inline REFCOUNT DICTIONARY_ITEM_REFCOUNT_GET_SOLE(DICTIONARY_ITEM *item) {
  454. return (REFCOUNT)__atomic_load_n(&item->refcount, __ATOMIC_SEQ_CST);
  455. }
  456. // ----------------------------------------------------------------------------
  457. // callbacks execution
  458. static void dictionary_execute_insert_callback(DICTIONARY *dict, DICTIONARY_ITEM *item, void *constructor_data) {
  459. if(likely(!dict->hooks || !dict->hooks->ins_callback))
  460. return;
  461. if(unlikely(is_view_dictionary(dict)))
  462. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  463. internal_error(false,
  464. "DICTIONARY: Running insert callback on item '%s' of dictionary created from %s() %zu@%s.",
  465. item_get_name(item),
  466. dict->creation_function,
  467. dict->creation_line,
  468. dict->creation_file);
  469. DICTIONARY_STATS_CALLBACK_INSERTS_PLUS1(dict);
  470. dict->hooks->ins_callback(item, item->shared->value, constructor_data?constructor_data:dict->hooks->ins_callback_data);
  471. }
  472. static bool dictionary_execute_conflict_callback(DICTIONARY *dict, DICTIONARY_ITEM *item, void *new_value, void *constructor_data) {
  473. if(likely(!dict->hooks || !dict->hooks->conflict_callback))
  474. return false;
  475. if(unlikely(is_view_dictionary(dict)))
  476. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  477. internal_error(false,
  478. "DICTIONARY: Running conflict callback on item '%s' of dictionary created from %s() %zu@%s.",
  479. item_get_name(item),
  480. dict->creation_function,
  481. dict->creation_line,
  482. dict->creation_file);
  483. DICTIONARY_STATS_CALLBACK_CONFLICTS_PLUS1(dict);
  484. return dict->hooks->conflict_callback(
  485. item, item->shared->value, new_value,
  486. constructor_data ? constructor_data : dict->hooks->conflict_callback_data);
  487. }
  488. static void dictionary_execute_react_callback(DICTIONARY *dict, DICTIONARY_ITEM *item, void *constructor_data) {
  489. if(likely(!dict->hooks || !dict->hooks->react_callback))
  490. return;
  491. if(unlikely(is_view_dictionary(dict)))
  492. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  493. internal_error(false,
  494. "DICTIONARY: Running react callback on item '%s' of dictionary created from %s() %zu@%s.",
  495. item_get_name(item),
  496. dict->creation_function,
  497. dict->creation_line,
  498. dict->creation_file);
  499. DICTIONARY_STATS_CALLBACK_REACTS_PLUS1(dict);
  500. dict->hooks->react_callback(item, item->shared->value,
  501. constructor_data?constructor_data:dict->hooks->react_callback_data);
  502. }
  503. static void dictionary_execute_delete_callback(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  504. if(likely(!dict->hooks || !dict->hooks->del_callback))
  505. return;
  506. // We may execute delete callback on items deleted from a view,
  507. // because we may have references to it, after the master is gone
  508. // so, the shared structure will remain until the last reference is released.
  509. internal_error(false,
  510. "DICTIONARY: Running delete callback on item '%s' of dictionary created from %s() %zu@%s.",
  511. item_get_name(item),
  512. dict->creation_function,
  513. dict->creation_line,
  514. dict->creation_file);
  515. DICTIONARY_STATS_CALLBACK_DELETES_PLUS1(dict);
  516. dict->hooks->del_callback(item, item->shared->value, dict->hooks->del_callback_data);
  517. }
  518. // ----------------------------------------------------------------------------
  519. // dictionary locks
  520. static inline size_t dictionary_locks_init(DICTIONARY *dict) {
  521. if(likely(!is_dictionary_single_threaded(dict))) {
  522. netdata_rwlock_init(&dict->index.rwlock);
  523. netdata_rwlock_init(&dict->items.rwlock);
  524. return 0;
  525. }
  526. return 0;
  527. }
  528. static inline size_t dictionary_locks_destroy(DICTIONARY *dict) {
  529. if(likely(!is_dictionary_single_threaded(dict))) {
  530. netdata_rwlock_destroy(&dict->index.rwlock);
  531. netdata_rwlock_destroy(&dict->items.rwlock);
  532. return 0;
  533. }
  534. return 0;
  535. }
  536. static inline void ll_recursive_lock_set_thread_as_writer(DICTIONARY *dict) {
  537. pid_t expected = 0, desired = gettid();
  538. if(!__atomic_compare_exchange_n(&dict->items.writer_pid, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
  539. fatal("DICTIONARY: Cannot set thread %d as exclusive writer, expected %d, desired %d, found %d.", gettid(), expected, desired, __atomic_load_n(&dict->items.writer_pid, __ATOMIC_SEQ_CST));
  540. }
  541. static inline void ll_recursive_unlock_unset_thread_writer(DICTIONARY *dict) {
  542. pid_t expected = gettid(), desired = 0;
  543. if(!__atomic_compare_exchange_n(&dict->items.writer_pid, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
  544. fatal("DICTIONARY: Cannot unset thread %d as exclusive writer, expected %d, desired %d, found %d.", gettid(), expected, desired, __atomic_load_n(&dict->items.writer_pid, __ATOMIC_SEQ_CST));
  545. }
  546. static inline bool ll_recursive_lock_is_thread_the_writer(DICTIONARY *dict) {
  547. pid_t tid = gettid();
  548. return tid > 0 && tid == __atomic_load_n(&dict->items.writer_pid, __ATOMIC_SEQ_CST);
  549. }
  550. static void ll_recursive_lock(DICTIONARY *dict, char rw) {
  551. if(unlikely(is_dictionary_single_threaded(dict)))
  552. return;
  553. if(ll_recursive_lock_is_thread_the_writer(dict)) {
  554. dict->items.writer_depth++;
  555. return;
  556. }
  557. if(rw == DICTIONARY_LOCK_READ || rw == DICTIONARY_LOCK_REENTRANT || rw == 'R') {
  558. // read lock
  559. netdata_rwlock_rdlock(&dict->items.rwlock);
  560. }
  561. else {
  562. // write lock
  563. netdata_rwlock_wrlock(&dict->items.rwlock);
  564. ll_recursive_lock_set_thread_as_writer(dict);
  565. }
  566. }
  567. static void ll_recursive_unlock(DICTIONARY *dict, char rw) {
  568. if(unlikely(is_dictionary_single_threaded(dict)))
  569. return;
  570. if(ll_recursive_lock_is_thread_the_writer(dict) && dict->items.writer_depth > 0) {
  571. dict->items.writer_depth--;
  572. return;
  573. }
  574. if(rw == DICTIONARY_LOCK_READ || rw == DICTIONARY_LOCK_REENTRANT || rw == 'R') {
  575. // read unlock
  576. netdata_rwlock_unlock(&dict->items.rwlock);
  577. }
  578. else {
  579. // write unlock
  580. ll_recursive_unlock_unset_thread_writer(dict);
  581. netdata_rwlock_unlock(&dict->items.rwlock);
  582. }
  583. }
  584. void dictionary_write_lock(DICTIONARY *dict) {
  585. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  586. }
  587. void dictionary_write_unlock(DICTIONARY *dict) {
  588. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  589. }
  590. static inline void dictionary_index_lock_rdlock(DICTIONARY *dict) {
  591. if(unlikely(is_dictionary_single_threaded(dict)))
  592. return;
  593. netdata_rwlock_rdlock(&dict->index.rwlock);
  594. }
  595. static inline void dictionary_index_rdlock_unlock(DICTIONARY *dict) {
  596. if(unlikely(is_dictionary_single_threaded(dict)))
  597. return;
  598. netdata_rwlock_unlock(&dict->index.rwlock);
  599. }
  600. static inline void dictionary_index_lock_wrlock(DICTIONARY *dict) {
  601. if(unlikely(is_dictionary_single_threaded(dict)))
  602. return;
  603. netdata_rwlock_wrlock(&dict->index.rwlock);
  604. }
  605. static inline void dictionary_index_wrlock_unlock(DICTIONARY *dict) {
  606. if(unlikely(is_dictionary_single_threaded(dict)))
  607. return;
  608. netdata_rwlock_unlock(&dict->index.rwlock);
  609. }
  610. // ----------------------------------------------------------------------------
  611. // items garbage collector
  612. static void garbage_collect_pending_deletes(DICTIONARY *dict) {
  613. usec_t last_master_deletion_us = dict->hooks?__atomic_load_n(&dict->hooks->last_master_deletion_us, __ATOMIC_SEQ_CST):0;
  614. usec_t last_gc_run_us = __atomic_load_n(&dict->last_gc_run_us, __ATOMIC_SEQ_CST);
  615. bool is_view = is_view_dictionary(dict);
  616. if(likely(!(
  617. DICTIONARY_PENDING_DELETES_GET(dict) > 0 ||
  618. (is_view && last_master_deletion_us > last_gc_run_us)
  619. )))
  620. return;
  621. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  622. __atomic_store_n(&dict->last_gc_run_us, now_realtime_usec(), __ATOMIC_SEQ_CST);
  623. if(is_view)
  624. dictionary_index_lock_wrlock(dict);
  625. DICTIONARY_STATS_GARBAGE_COLLECTIONS_PLUS1(dict);
  626. size_t deleted = 0, pending = 0, examined = 0;
  627. DICTIONARY_ITEM *item = dict->items.list, *item_next;
  628. while(item) {
  629. examined++;
  630. // this will clean up
  631. item_next = item->next;
  632. int rc = item_check_and_acquire_advanced(dict, item, is_view);
  633. if(rc == RC_ITEM_MARKED_FOR_DELETION) {
  634. // we didn't get a reference
  635. if(item_is_not_referenced_and_can_be_removed(dict, item)) {
  636. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(dict->items.list, item, prev, next);
  637. dict_item_free_with_hooks(dict, item);
  638. deleted++;
  639. pending = DICTIONARY_PENDING_DELETES_MINUS1(dict);
  640. if (!pending)
  641. break;
  642. }
  643. }
  644. else if(rc == RC_ITEM_IS_CURRENTLY_BEING_DELETED)
  645. ; // do not touch this item (we didn't get a reference)
  646. else if(rc == RC_ITEM_OK)
  647. item_release(dict, item);
  648. item = item_next;
  649. }
  650. if(is_view)
  651. dictionary_index_wrlock_unlock(dict);
  652. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  653. (void)deleted;
  654. (void)examined;
  655. internal_error(false, "DICTIONARY: garbage collected dictionary created by %s (%zu@%s), examined %zu items, deleted %zu items, still pending %zu items",
  656. dict->creation_function, dict->creation_line, dict->creation_file, examined, deleted, pending);
  657. }
  658. // ----------------------------------------------------------------------------
  659. // reference counters
  660. static inline size_t reference_counter_init(DICTIONARY *dict) {
  661. (void)dict;
  662. // allocate memory required for reference counters
  663. // return number of bytes
  664. return 0;
  665. }
  666. static inline size_t reference_counter_free(DICTIONARY *dict) {
  667. (void)dict;
  668. // free memory required for reference counters
  669. // return number of bytes
  670. return 0;
  671. }
  672. static void item_acquire(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  673. REFCOUNT refcount;
  674. if(unlikely(is_dictionary_single_threaded(dict))) {
  675. refcount = ++item->refcount;
  676. }
  677. else {
  678. // increment the refcount
  679. refcount = __atomic_add_fetch(&item->refcount, 1, __ATOMIC_SEQ_CST);
  680. }
  681. if(refcount <= 0) {
  682. internal_error(
  683. true,
  684. "DICTIONARY: attempted to acquire item which is deleted (refcount = %d): "
  685. "'%s' on dictionary created by %s() (%zu@%s)",
  686. refcount - 1,
  687. item_get_name(item),
  688. dict->creation_function,
  689. dict->creation_line,
  690. dict->creation_file);
  691. fatal(
  692. "DICTIONARY: request to acquire item '%s', which is deleted (refcount = %d)!",
  693. item_get_name(item),
  694. refcount - 1);
  695. }
  696. if(refcount == 1) {
  697. // referenced items counts number of unique items referenced
  698. // so, we increase it only when refcount == 1
  699. DICTIONARY_REFERENCED_ITEMS_PLUS1(dict);
  700. // if this is a deleted item, but the counter increased to 1
  701. // we need to remove it from the pending items to delete
  702. if(item_flag_check(item, ITEM_FLAG_DELETED))
  703. DICTIONARY_PENDING_DELETES_MINUS1(dict);
  704. }
  705. }
  706. static void item_release(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  707. // this function may be called without any lock on the dictionary
  708. // or even when someone else has 'write' lock on the dictionary
  709. bool is_deleted;
  710. REFCOUNT refcount;
  711. if(unlikely(is_dictionary_single_threaded(dict))) {
  712. is_deleted = item->flags & ITEM_FLAG_DELETED;
  713. refcount = --item->refcount;
  714. }
  715. else {
  716. // get the flags before decrementing any reference counters
  717. // (the other way around may lead to use-after-free)
  718. is_deleted = item_flag_check(item, ITEM_FLAG_DELETED);
  719. // decrement the refcount
  720. refcount = __atomic_sub_fetch(&item->refcount, 1, __ATOMIC_SEQ_CST);
  721. }
  722. if(refcount < 0) {
  723. internal_error(
  724. true,
  725. "DICTIONARY: attempted to release item without references (refcount = %d): "
  726. "'%s' on dictionary created by %s() (%zu@%s)",
  727. refcount + 1,
  728. item_get_name(item),
  729. dict->creation_function,
  730. dict->creation_line,
  731. dict->creation_file);
  732. fatal(
  733. "DICTIONARY: attempted to release item '%s' without references (refcount = %d)",
  734. item_get_name(item),
  735. refcount + 1);
  736. }
  737. if(refcount == 0) {
  738. if(is_deleted)
  739. DICTIONARY_PENDING_DELETES_PLUS1(dict);
  740. // referenced items counts number of unique items referenced
  741. // so, we decrease it only when refcount == 0
  742. DICTIONARY_REFERENCED_ITEMS_MINUS1(dict);
  743. }
  744. }
  745. static int item_check_and_acquire_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item, bool having_index_lock) {
  746. size_t spins = 0;
  747. REFCOUNT refcount, desired;
  748. int ret = RC_ITEM_OK;
  749. refcount = DICTIONARY_ITEM_REFCOUNT_GET(dict, item);
  750. do {
  751. spins++;
  752. if(refcount < 0) {
  753. // we can't use this item
  754. ret = RC_ITEM_IS_CURRENTLY_BEING_DELETED;
  755. break;
  756. }
  757. if(item_flag_check(item, ITEM_FLAG_DELETED)) {
  758. // we can't use this item
  759. ret = RC_ITEM_MARKED_FOR_DELETION;
  760. break;
  761. }
  762. desired = refcount + 1;
  763. } while(!__atomic_compare_exchange_n(&item->refcount, &refcount, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST));
  764. // if ret == ITEM_OK, we acquired the item
  765. if(ret == RC_ITEM_OK) {
  766. if (is_view_dictionary(dict) &&
  767. item_shared_flag_check(item, ITEM_FLAG_DELETED) &&
  768. !item_flag_check(item, ITEM_FLAG_DELETED)) {
  769. // but, we can't use this item
  770. if (having_index_lock) {
  771. // delete it from the hashtable
  772. if(hashtable_delete_unsafe(dict, item_get_name(item), item->key_len, item) == 0)
  773. error("DICTIONARY: INTERNAL ERROR VIEW: tried to delete item with name '%s', name_len %u that is not in the index", item_get_name(item), (KEY_LEN_TYPE)(item->key_len - 1));
  774. else
  775. pointer_del(dict, item);
  776. // mark it in our dictionary as deleted too,
  777. // this is safe to be done here, because we have got
  778. // a reference counter on item
  779. dict_item_set_deleted(dict, item);
  780. // decrement the refcount we incremented above
  781. if (__atomic_sub_fetch(&item->refcount, 1, __ATOMIC_SEQ_CST) == 0) {
  782. // this is a deleted item, and we are the last one
  783. DICTIONARY_PENDING_DELETES_PLUS1(dict);
  784. }
  785. // do not touch the item below this point
  786. } else {
  787. // this is traversal / walkthrough
  788. // decrement the refcount we incremented above
  789. __atomic_sub_fetch(&item->refcount, 1, __ATOMIC_SEQ_CST);
  790. }
  791. return RC_ITEM_MARKED_FOR_DELETION;
  792. }
  793. if(desired == 1)
  794. DICTIONARY_REFERENCED_ITEMS_PLUS1(dict);
  795. }
  796. if(unlikely(spins > 1 && dict->stats))
  797. DICTIONARY_STATS_CHECK_SPINS_PLUS(dict, spins - 1);
  798. return ret;
  799. }
  800. // if a dictionary item can be deleted, return true, otherwise return false
  801. // we use the private reference counter
  802. static inline int item_is_not_referenced_and_can_be_removed_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  803. // if we can set refcount to REFCOUNT_DELETING, we can delete this item
  804. size_t spins = 0;
  805. REFCOUNT refcount, desired = REFCOUNT_DELETING;
  806. int ret = RC_ITEM_OK;
  807. refcount = DICTIONARY_ITEM_REFCOUNT_GET(dict, item);
  808. do {
  809. spins++;
  810. if(refcount < 0) {
  811. // we can't use this item
  812. ret = RC_ITEM_IS_CURRENTLY_BEING_DELETED;
  813. break;
  814. }
  815. if(refcount > 0) {
  816. // we can't delete this
  817. ret = RC_ITEM_IS_REFERENCED;
  818. break;
  819. }
  820. if(item_flag_check(item, ITEM_FLAG_BEING_CREATED)) {
  821. // we can't use this item
  822. ret = RC_ITEM_IS_CURRENTLY_BEING_CREATED;
  823. break;
  824. }
  825. } while(!__atomic_compare_exchange_n(&item->refcount, &refcount, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST));
  826. #ifdef NETDATA_INTERNAL_CHECKS
  827. if(ret == RC_ITEM_OK)
  828. item->deleter_pid = gettid();
  829. #endif
  830. if(unlikely(spins > 1 && dict->stats))
  831. DICTIONARY_STATS_DELETE_SPINS_PLUS(dict, spins - 1);
  832. return ret;
  833. }
  834. // if a dictionary item can be freed, return true, otherwise return false
  835. // we use the shared reference counter
  836. static inline bool item_shared_release_and_check_if_it_can_be_freed(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item) {
  837. // if we can set refcount to REFCOUNT_DELETING, we can delete this item
  838. REFCOUNT links = __atomic_sub_fetch(&item->shared->links, 1, __ATOMIC_SEQ_CST);
  839. if(links == 0 && __atomic_compare_exchange_n(&item->shared->links, &links, REFCOUNT_DELETING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
  840. // we can delete it
  841. return true;
  842. }
  843. // we can't delete it
  844. return false;
  845. }
  846. // ----------------------------------------------------------------------------
  847. // hash table operations
  848. static size_t hashtable_init_unsafe(DICTIONARY *dict) {
  849. dict->index.JudyHSArray = NULL;
  850. return 0;
  851. }
  852. static size_t hashtable_destroy_unsafe(DICTIONARY *dict) {
  853. if(unlikely(!dict->index.JudyHSArray)) return 0;
  854. pointer_destroy_index(dict);
  855. JError_t J_Error;
  856. Word_t ret = JudyHSFreeArray(&dict->index.JudyHSArray, &J_Error);
  857. if(unlikely(ret == (Word_t) JERR)) {
  858. error("DICTIONARY: Cannot destroy JudyHS, JU_ERRNO_* == %u, ID == %d",
  859. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  860. }
  861. debug(D_DICTIONARY, "Dictionary: hash table freed %lu bytes", ret);
  862. dict->index.JudyHSArray = NULL;
  863. return (size_t)ret;
  864. }
  865. static inline void **hashtable_insert_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  866. JError_t J_Error;
  867. Pvoid_t *Rc = JudyHSIns(&dict->index.JudyHSArray, (void *)name, name_len, &J_Error);
  868. if (unlikely(Rc == PJERR)) {
  869. error("DICTIONARY: Cannot insert entry with name '%s' to JudyHS, JU_ERRNO_* == %u, ID == %d",
  870. name, JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  871. }
  872. // if *Rc == 0, new item added to the array
  873. // otherwise the existing item value is returned in *Rc
  874. // we return a pointer to a pointer, so that the caller can
  875. // put anything needed at the value of the index.
  876. // The pointer to pointer we return has to be used before
  877. // any other operation that may change the index (insert/delete).
  878. return Rc;
  879. }
  880. static inline int hashtable_delete_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *item) {
  881. (void)item;
  882. if(unlikely(!dict->index.JudyHSArray)) return 0;
  883. JError_t J_Error;
  884. int ret = JudyHSDel(&dict->index.JudyHSArray, (void *)name, name_len, &J_Error);
  885. if(unlikely(ret == JERR)) {
  886. error("DICTIONARY: Cannot delete entry with name '%s' from JudyHS, JU_ERRNO_* == %u, ID == %d", name,
  887. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  888. return 0;
  889. }
  890. // Hey, this is problematic! We need the value back, not just an int with a status!
  891. // https://sourceforge.net/p/judy/feature-requests/23/
  892. if(unlikely(ret == 0)) {
  893. // not found in the dictionary
  894. return 0;
  895. }
  896. else {
  897. // found and deleted from the dictionary
  898. return 1;
  899. }
  900. }
  901. static inline DICTIONARY_ITEM *hashtable_get_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  902. if(unlikely(!dict->index.JudyHSArray)) return NULL;
  903. DICTIONARY_STATS_SEARCHES_PLUS1(dict);
  904. Pvoid_t *Rc;
  905. Rc = JudyHSGet(dict->index.JudyHSArray, (void *)name, name_len);
  906. if(likely(Rc)) {
  907. // found in the hash table
  908. pointer_check(dict, (DICTIONARY_ITEM *)*Rc);
  909. return (DICTIONARY_ITEM *)*Rc;
  910. }
  911. else {
  912. // not found in the hash table
  913. return NULL;
  914. }
  915. }
  916. static inline void hashtable_inserted_item_unsafe(DICTIONARY *dict, void *item) {
  917. (void)dict;
  918. (void)item;
  919. // this is called just after an item is successfully inserted to the hashtable
  920. // we don't need this for judy, but we may need it if we integrate more hash tables
  921. ;
  922. }
  923. // ----------------------------------------------------------------------------
  924. // linked list management
  925. static inline void item_linked_list_add(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  926. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  927. if(dict->options & DICT_OPTION_ADD_IN_FRONT)
  928. DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(dict->items.list, item, prev, next);
  929. else
  930. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(dict->items.list, item, prev, next);
  931. #ifdef NETDATA_INTERNAL_CHECKS
  932. item->ll_adder_pid = gettid();
  933. #endif
  934. // clear the BEING created flag,
  935. // after it has been inserted into the linked list
  936. item_flag_clear(item, ITEM_FLAG_BEING_CREATED);
  937. garbage_collect_pending_deletes(dict);
  938. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  939. }
  940. static inline void item_linked_list_remove(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  941. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  942. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(dict->items.list, item, prev, next);
  943. #ifdef NETDATA_INTERNAL_CHECKS
  944. item->ll_remover_pid = gettid();
  945. #endif
  946. garbage_collect_pending_deletes(dict);
  947. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  948. }
  949. // ----------------------------------------------------------------------------
  950. // ITEM initialization and updates
  951. static inline size_t item_set_name(DICTIONARY *dict, DICTIONARY_ITEM *item, const char *name, size_t name_len) {
  952. if(likely(dict->options & DICT_OPTION_NAME_LINK_DONT_CLONE)) {
  953. item->caller_name = (char *)name;
  954. item->key_len = name_len;
  955. }
  956. else {
  957. item->string_name = string_strdupz(name);
  958. item->key_len = string_strlen(item->string_name) + 1;
  959. item->options |= ITEM_OPTION_ALLOCATED_NAME;
  960. }
  961. return item->key_len;
  962. }
  963. static inline size_t item_free_name(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  964. if(likely(!(dict->options & DICT_OPTION_NAME_LINK_DONT_CLONE)))
  965. string_freez(item->string_name);
  966. return item->key_len;
  967. }
  968. static inline const char *item_get_name(const DICTIONARY_ITEM *item) {
  969. if(item->options & ITEM_OPTION_ALLOCATED_NAME)
  970. return string2str(item->string_name);
  971. else
  972. return item->caller_name;
  973. }
  974. static inline size_t item_get_name_len(const DICTIONARY_ITEM *item) {
  975. if(item->options & ITEM_OPTION_ALLOCATED_NAME)
  976. return string_strlen(item->string_name);
  977. else
  978. return strlen(item->caller_name);
  979. }
  980. static ARAL *dict_items_aral = NULL;
  981. static ARAL *dict_shared_items_aral = NULL;
  982. void dictionary_static_items_aral_init(void) {
  983. static SPINLOCK spinlock;
  984. if(unlikely(!dict_items_aral || !dict_shared_items_aral)) {
  985. netdata_spinlock_lock(&spinlock);
  986. // we have to check again
  987. if(!dict_items_aral)
  988. dict_items_aral = aral_create(
  989. "dict-items",
  990. sizeof(DICTIONARY_ITEM),
  991. 0,
  992. 65536,
  993. aral_by_size_statistics(),
  994. NULL, NULL, false, false);
  995. // we have to check again
  996. if(!dict_shared_items_aral)
  997. dict_shared_items_aral = aral_create(
  998. "dict-shared-items",
  999. sizeof(DICTIONARY_ITEM_SHARED),
  1000. 0,
  1001. 65536,
  1002. aral_by_size_statistics(),
  1003. NULL, NULL, false, false);
  1004. netdata_spinlock_unlock(&spinlock);
  1005. }
  1006. }
  1007. static DICTIONARY_ITEM *dict_item_create(DICTIONARY *dict __maybe_unused, size_t *allocated_bytes, DICTIONARY_ITEM *master_item) {
  1008. DICTIONARY_ITEM *item;
  1009. size_t size = sizeof(DICTIONARY_ITEM);
  1010. item = aral_mallocz(dict_items_aral);
  1011. memset(item, 0, sizeof(DICTIONARY_ITEM));
  1012. #ifdef NETDATA_INTERNAL_CHECKS
  1013. item->creator_pid = gettid();
  1014. #endif
  1015. item->refcount = 1;
  1016. item->flags = ITEM_FLAG_BEING_CREATED;
  1017. *allocated_bytes += size;
  1018. if(master_item) {
  1019. item->shared = master_item->shared;
  1020. if(unlikely(__atomic_add_fetch(&item->shared->links, 1, __ATOMIC_SEQ_CST) <= 1))
  1021. fatal("DICTIONARY: attempted to link to a shared item structure that had zero references");
  1022. }
  1023. else {
  1024. size = sizeof(DICTIONARY_ITEM_SHARED);
  1025. item->shared = aral_mallocz(dict_shared_items_aral);
  1026. memset(item->shared, 0, sizeof(DICTIONARY_ITEM_SHARED));
  1027. item->shared->links = 1;
  1028. *allocated_bytes += size;
  1029. }
  1030. #ifdef NETDATA_INTERNAL_CHECKS
  1031. item->dict = dict;
  1032. #endif
  1033. return item;
  1034. }
  1035. static inline void *dict_item_value_mallocz(DICTIONARY *dict, size_t value_len) {
  1036. if(dict->value_aral) {
  1037. internal_fatal(aral_element_size(dict->value_aral) != value_len,
  1038. "DICTIONARY: item value size %zu does not match the configured fixed one %zu",
  1039. value_len, aral_element_size(dict->value_aral));
  1040. return aral_mallocz(dict->value_aral);
  1041. }
  1042. else
  1043. return mallocz(value_len);
  1044. }
  1045. static inline void dict_item_value_freez(DICTIONARY *dict, void *ptr) {
  1046. if(dict->value_aral)
  1047. aral_freez(dict->value_aral, ptr);
  1048. else
  1049. freez(ptr);
  1050. }
  1051. static void *dict_item_value_create(DICTIONARY *dict, void *value, size_t value_len) {
  1052. void *ptr = NULL;
  1053. if(likely(value_len)) {
  1054. if (likely(value)) {
  1055. // a value has been supplied
  1056. // copy it
  1057. ptr = dict_item_value_mallocz(dict, value_len);
  1058. memcpy(ptr, value, value_len);
  1059. }
  1060. else {
  1061. // no value has been supplied
  1062. // allocate a clear memory block
  1063. ptr = dict_item_value_mallocz(dict, value_len);
  1064. memset(ptr, 0, value_len);
  1065. }
  1066. }
  1067. // else
  1068. // the caller wants an item without any value
  1069. return ptr;
  1070. }
  1071. static DICTIONARY_ITEM *dict_item_create_with_hooks(DICTIONARY *dict, const char *name, size_t name_len, void *value, size_t value_len, void *constructor_data, DICTIONARY_ITEM *master_item) {
  1072. #ifdef NETDATA_INTERNAL_CHECKS
  1073. if(unlikely(name_len > KEY_LEN_MAX))
  1074. fatal("DICTIONARY: tried to index a key of size %zu, but the maximum acceptable is %zu", name_len, (size_t)KEY_LEN_MAX);
  1075. if(unlikely(value_len > VALUE_LEN_MAX))
  1076. fatal("DICTIONARY: tried to add an item of size %zu, but the maximum acceptable is %zu", value_len, (size_t)VALUE_LEN_MAX);
  1077. #endif
  1078. size_t item_size = 0, key_size = 0, value_size = 0;
  1079. DICTIONARY_ITEM *item = dict_item_create(dict, &item_size, master_item);
  1080. key_size += item_set_name(dict, item, name, name_len);
  1081. if(unlikely(is_view_dictionary(dict))) {
  1082. // we are on a view dictionary
  1083. // do not touch the value
  1084. ;
  1085. #ifdef NETDATA_INTERNAL_CHECKS
  1086. if(unlikely(!master_item))
  1087. fatal("DICTIONARY: cannot add an item to a view without a master item.");
  1088. #endif
  1089. }
  1090. else {
  1091. // we are on the master dictionary
  1092. if(unlikely(dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE))
  1093. item->shared->value = value;
  1094. else
  1095. item->shared->value = dict_item_value_create(dict, value, value_len);
  1096. item->shared->value_len = value_len;
  1097. value_size += value_len;
  1098. dictionary_execute_insert_callback(dict, item, constructor_data);
  1099. }
  1100. DICTIONARY_ENTRIES_PLUS1(dict);
  1101. DICTIONARY_STATS_PLUS_MEMORY(dict, key_size, item_size, value_size);
  1102. return item;
  1103. }
  1104. static void dict_item_reset_value_with_hooks(DICTIONARY *dict, DICTIONARY_ITEM *item, void *value, size_t value_len, void *constructor_data) {
  1105. if(unlikely(is_view_dictionary(dict)))
  1106. fatal("DICTIONARY: %s() should never be called on views.", __FUNCTION__ );
  1107. debug(D_DICTIONARY, "Dictionary entry with name '%s' found. Changing its value.", item_get_name(item));
  1108. DICTIONARY_VALUE_RESETS_PLUS1(dict);
  1109. if(item->shared->value_len != value_len) {
  1110. DICTIONARY_STATS_PLUS_MEMORY(dict, 0, 0, value_len);
  1111. DICTIONARY_STATS_MINUS_MEMORY(dict, 0, 0, item->shared->value_len);
  1112. }
  1113. dictionary_execute_delete_callback(dict, item);
  1114. if(likely(dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE)) {
  1115. debug(D_DICTIONARY, "Dictionary: linking value to '%s'", item_get_name(item));
  1116. item->shared->value = value;
  1117. item->shared->value_len = value_len;
  1118. }
  1119. else {
  1120. debug(D_DICTIONARY, "Dictionary: cloning value to '%s'", item_get_name(item));
  1121. void *old_value = item->shared->value;
  1122. void *new_value = NULL;
  1123. if(value_len) {
  1124. new_value = dict_item_value_mallocz(dict, value_len);
  1125. if(value) memcpy(new_value, value, value_len);
  1126. else memset(new_value, 0, value_len);
  1127. }
  1128. item->shared->value = new_value;
  1129. item->shared->value_len = value_len;
  1130. debug(D_DICTIONARY, "Dictionary: freeing old value of '%s'", item_get_name(item));
  1131. dict_item_value_freez(dict, old_value);
  1132. }
  1133. dictionary_execute_insert_callback(dict, item, constructor_data);
  1134. }
  1135. static size_t dict_item_free_with_hooks(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1136. debug(D_DICTIONARY, "Destroying name value entry for name '%s'.", item_get_name(item));
  1137. if(!item_flag_check(item, ITEM_FLAG_DELETED))
  1138. DICTIONARY_ENTRIES_MINUS1(dict);
  1139. size_t item_size = 0, key_size = 0, value_size = 0;
  1140. key_size += item->key_len;
  1141. if(unlikely(!(dict->options & DICT_OPTION_NAME_LINK_DONT_CLONE)))
  1142. item_free_name(dict, item);
  1143. if(item_shared_release_and_check_if_it_can_be_freed(dict, item)) {
  1144. dictionary_execute_delete_callback(dict, item);
  1145. if(unlikely(!(dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE))) {
  1146. debug(D_DICTIONARY, "Dictionary freeing value of '%s'", item_get_name(item));
  1147. dict_item_value_freez(dict, item->shared->value);
  1148. item->shared->value = NULL;
  1149. }
  1150. value_size += item->shared->value_len;
  1151. aral_freez(dict_shared_items_aral, item->shared);
  1152. item->shared = NULL;
  1153. item_size += sizeof(DICTIONARY_ITEM_SHARED);
  1154. }
  1155. aral_freez(dict_items_aral, item);
  1156. item_size += sizeof(DICTIONARY_ITEM);
  1157. DICTIONARY_STATS_MINUS_MEMORY(dict, key_size, item_size, value_size);
  1158. // we return the memory we actually freed
  1159. return item_size + ((dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE) ? 0 : value_size);
  1160. }
  1161. // ----------------------------------------------------------------------------
  1162. // item operations
  1163. static void dict_item_shared_set_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1164. if(is_master_dictionary(dict)) {
  1165. item_shared_flag_set(item, ITEM_FLAG_DELETED);
  1166. if(dict->hooks)
  1167. __atomic_store_n(&dict->hooks->last_master_deletion_us, now_realtime_usec(), __ATOMIC_SEQ_CST);
  1168. }
  1169. }
  1170. // returns true if we set the deleted flag on this item
  1171. static bool dict_item_set_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1172. ITEM_FLAGS expected, desired;
  1173. expected = __atomic_load_n(&item->flags, __ATOMIC_SEQ_CST);
  1174. do {
  1175. if (expected & ITEM_FLAG_DELETED)
  1176. return false;
  1177. desired = expected | ITEM_FLAG_DELETED;
  1178. } while(!__atomic_compare_exchange_n(&item->flags, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST));
  1179. DICTIONARY_ENTRIES_MINUS1(dict);
  1180. return true;
  1181. }
  1182. static inline void dict_item_free_or_mark_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1183. int rc = item_is_not_referenced_and_can_be_removed_advanced(dict, item);
  1184. switch(rc) {
  1185. case RC_ITEM_OK:
  1186. // the item is ours, refcount set to -100
  1187. dict_item_shared_set_deleted(dict, item);
  1188. item_linked_list_remove(dict, item);
  1189. dict_item_free_with_hooks(dict, item);
  1190. break;
  1191. case RC_ITEM_IS_REFERENCED:
  1192. case RC_ITEM_IS_CURRENTLY_BEING_CREATED:
  1193. // the item is currently referenced by others
  1194. dict_item_shared_set_deleted(dict, item);
  1195. dict_item_set_deleted(dict, item);
  1196. // after this point do not touch the item
  1197. break;
  1198. case RC_ITEM_IS_CURRENTLY_BEING_DELETED:
  1199. // an item that is currently being deleted by someone else - don't touch it
  1200. break;
  1201. default:
  1202. internal_error(true, "Hey dev! You forgot to add the new condition here!");
  1203. break;
  1204. }
  1205. }
  1206. // this is used by traversal functions to remove the current item
  1207. // if it is deleted, and it has zero references. This will eliminate
  1208. // the need for the garbage collector to kick-in later.
  1209. // Most deletions happen during traversal, so this is a nice hack
  1210. // to speed up everything!
  1211. static inline void dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(DICTIONARY *dict, DICTIONARY_ITEM *item, char rw) {
  1212. if(rw == DICTIONARY_LOCK_WRITE) {
  1213. bool should_be_deleted = item_flag_check(item, ITEM_FLAG_DELETED);
  1214. item_release(dict, item);
  1215. if(should_be_deleted && item_is_not_referenced_and_can_be_removed(dict, item)) {
  1216. // this has to be before removing from the linked list,
  1217. // otherwise the garbage collector will also kick in!
  1218. DICTIONARY_PENDING_DELETES_MINUS1(dict);
  1219. item_linked_list_remove(dict, item);
  1220. dict_item_free_with_hooks(dict, item);
  1221. }
  1222. }
  1223. else {
  1224. // we can't do anything under this mode
  1225. item_release(dict, item);
  1226. }
  1227. }
  1228. static bool dict_item_del(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1229. if(unlikely(!name || !*name)) {
  1230. internal_error(
  1231. true,
  1232. "DICTIONARY: attempted to %s() without a name on a dictionary created from %s() %zu@%s.",
  1233. __FUNCTION__,
  1234. dict->creation_function,
  1235. dict->creation_line,
  1236. dict->creation_file);
  1237. return false;
  1238. }
  1239. if(unlikely(is_dictionary_destroyed(dict))) {
  1240. internal_error(true, "DICTIONARY: attempted to dictionary_del() on a destroyed dictionary");
  1241. return false;
  1242. }
  1243. if(name_len == -1)
  1244. name_len = (ssize_t)strlen(name) + 1; // we need the terminating null too
  1245. debug(D_DICTIONARY, "DEL dictionary entry with name '%s'.", name);
  1246. // Unfortunately, the JudyHSDel() does not return the value of the
  1247. // item that was deleted, so we have to find it before we delete it,
  1248. // since we need to release our structures too.
  1249. dictionary_index_lock_wrlock(dict);
  1250. int ret;
  1251. DICTIONARY_ITEM *item = hashtable_get_unsafe(dict, name, name_len);
  1252. if(unlikely(!item)) {
  1253. dictionary_index_wrlock_unlock(dict);
  1254. ret = false;
  1255. }
  1256. else {
  1257. if(hashtable_delete_unsafe(dict, name, name_len, item) == 0)
  1258. error("DICTIONARY: INTERNAL ERROR: tried to delete item with name '%s', name_len %zd that is not in the index", name, name_len - 1);
  1259. else
  1260. pointer_del(dict, item);
  1261. dictionary_index_wrlock_unlock(dict);
  1262. dict_item_free_or_mark_deleted(dict, item);
  1263. ret = true;
  1264. }
  1265. return ret;
  1266. }
  1267. static DICTIONARY_ITEM *dict_item_add_or_reset_value_and_acquire(DICTIONARY *dict, const char *name, ssize_t name_len, void *value, size_t value_len, void *constructor_data, DICTIONARY_ITEM *master_item) {
  1268. if(unlikely(!name || !*name)) {
  1269. internal_error(
  1270. true,
  1271. "DICTIONARY: attempted to %s() without a name on a dictionary created from %s() %zu@%s.",
  1272. __FUNCTION__,
  1273. dict->creation_function,
  1274. dict->creation_line,
  1275. dict->creation_file);
  1276. return NULL;
  1277. }
  1278. if(unlikely(is_dictionary_destroyed(dict))) {
  1279. internal_error(true, "DICTIONARY: attempted to dictionary_set() on a destroyed dictionary");
  1280. return NULL;
  1281. }
  1282. if(name_len == -1)
  1283. name_len = (ssize_t)strlen(name) + 1; // we need the terminating null too
  1284. debug(D_DICTIONARY, "SET dictionary entry with name '%s'.", name);
  1285. // DISCUSSION:
  1286. // Is it better to gain a read-lock and do a hashtable_get_unsafe()
  1287. // before we write lock to do hashtable_insert_unsafe()?
  1288. //
  1289. // Probably this depends on the use case.
  1290. // For statsd for example that does dictionary_set() to update received values,
  1291. // it could be beneficial to do a get() before we insert().
  1292. //
  1293. // But the caller has the option to do this on his/her own.
  1294. // So, let's do the fastest here and let the caller decide the flow of calls.
  1295. dictionary_index_lock_wrlock(dict);
  1296. bool added_or_updated = false;
  1297. size_t spins = 0;
  1298. DICTIONARY_ITEM *item = NULL;
  1299. do {
  1300. DICTIONARY_ITEM **item_pptr = (DICTIONARY_ITEM **)hashtable_insert_unsafe(dict, name, name_len);
  1301. if (likely(*item_pptr == NULL)) {
  1302. // a new item added to the index
  1303. // create the dictionary item
  1304. item = *item_pptr =
  1305. dict_item_create_with_hooks(dict, name, name_len, value, value_len, constructor_data, master_item);
  1306. pointer_add(dict, item);
  1307. // call the hashtable react
  1308. hashtable_inserted_item_unsafe(dict, item);
  1309. // unlock the index lock, before we add it to the linked list
  1310. // DON'T DO IT THE OTHER WAY AROUND - DO NOT CROSS THE LOCKS!
  1311. dictionary_index_wrlock_unlock(dict);
  1312. item_linked_list_add(dict, item);
  1313. added_or_updated = true;
  1314. }
  1315. else {
  1316. pointer_check(dict, *item_pptr);
  1317. if(item_check_and_acquire_advanced(dict, *item_pptr, true) != RC_ITEM_OK) {
  1318. spins++;
  1319. continue;
  1320. }
  1321. // the item is already in the index
  1322. // so, either we will return the old one
  1323. // or overwrite the value, depending on dictionary flags
  1324. // We should not compare the values here!
  1325. // even if they are the same, we have to do the whole job
  1326. // so that the callbacks will be called.
  1327. item = *item_pptr;
  1328. if(is_view_dictionary(dict)) {
  1329. // view dictionary
  1330. // the item is already there and can be used
  1331. if(item->shared != master_item->shared)
  1332. error("DICTIONARY: changing the master item on a view is not supported. The previous item will remain. To change the key of an item in a view, delete it and add it again.");
  1333. }
  1334. else {
  1335. // master dictionary
  1336. // the user wants to reset its value
  1337. if (!(dict->options & DICT_OPTION_DONT_OVERWRITE_VALUE)) {
  1338. dict_item_reset_value_with_hooks(dict, item, value, value_len, constructor_data);
  1339. added_or_updated = true;
  1340. }
  1341. else if (dictionary_execute_conflict_callback(dict, item, value, constructor_data)) {
  1342. dictionary_version_increment(dict);
  1343. added_or_updated = true;
  1344. }
  1345. else {
  1346. // conflict callback returned false
  1347. // we did really nothing!
  1348. ;
  1349. }
  1350. }
  1351. dictionary_index_wrlock_unlock(dict);
  1352. }
  1353. } while(!item);
  1354. if(unlikely(spins > 0 && dict->stats))
  1355. DICTIONARY_STATS_INSERT_SPINS_PLUS(dict, spins);
  1356. if(is_master_dictionary(dict) && added_or_updated)
  1357. dictionary_execute_react_callback(dict, item, constructor_data);
  1358. return item;
  1359. }
  1360. static DICTIONARY_ITEM *dict_item_find_and_acquire(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1361. if(unlikely(!name || !*name)) {
  1362. internal_error(
  1363. true,
  1364. "DICTIONARY: attempted to %s() without a name on a dictionary created from %s() %zu@%s.",
  1365. __FUNCTION__,
  1366. dict->creation_function,
  1367. dict->creation_line,
  1368. dict->creation_file);
  1369. return NULL;
  1370. }
  1371. if(unlikely(is_dictionary_destroyed(dict))) {
  1372. internal_error(true, "DICTIONARY: attempted to dictionary_get() on a destroyed dictionary");
  1373. return NULL;
  1374. }
  1375. if(name_len == -1)
  1376. name_len = (ssize_t)strlen(name) + 1; // we need the terminating null too
  1377. debug(D_DICTIONARY, "GET dictionary entry with name '%s'.", name);
  1378. dictionary_index_lock_rdlock(dict);
  1379. DICTIONARY_ITEM *item = hashtable_get_unsafe(dict, name, name_len);
  1380. if(unlikely(item && !item_check_and_acquire(dict, item))) {
  1381. item = NULL;
  1382. DICTIONARY_STATS_SEARCH_IGNORES_PLUS1(dict);
  1383. }
  1384. dictionary_index_rdlock_unlock(dict);
  1385. return item;
  1386. }
  1387. // ----------------------------------------------------------------------------
  1388. // delayed destruction of dictionaries
  1389. static bool dictionary_free_all_resources(DICTIONARY *dict, size_t *mem, bool force) {
  1390. if(mem)
  1391. *mem = 0;
  1392. if(!force && dictionary_referenced_items(dict))
  1393. return false;
  1394. size_t dict_size = 0, counted_items = 0, item_size = 0, index_size = 0;
  1395. (void)counted_items;
  1396. #ifdef NETDATA_INTERNAL_CHECKS
  1397. long int entries = dict->entries;
  1398. long int referenced_items = dict->referenced_items;
  1399. long int pending_deletion_items = dict->pending_deletion_items;
  1400. const char *creation_function = dict->creation_function;
  1401. const char *creation_file = dict->creation_file;
  1402. size_t creation_line = dict->creation_line;
  1403. #endif
  1404. // destroy the index
  1405. dictionary_index_lock_wrlock(dict);
  1406. index_size += hashtable_destroy_unsafe(dict);
  1407. dictionary_index_wrlock_unlock(dict);
  1408. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  1409. DICTIONARY_ITEM *item = dict->items.list;
  1410. while (item) {
  1411. // cache item->next
  1412. // because we are going to free item
  1413. DICTIONARY_ITEM *item_next = item->next;
  1414. item_size += dict_item_free_with_hooks(dict, item);
  1415. item = item_next;
  1416. // to speed up destruction, we don't
  1417. // unlink item from the linked-list here
  1418. counted_items++;
  1419. }
  1420. dict->items.list = NULL;
  1421. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1422. dict_size += dictionary_locks_destroy(dict);
  1423. dict_size += reference_counter_free(dict);
  1424. dict_size += dictionary_hooks_free(dict);
  1425. dict_size += sizeof(DICTIONARY);
  1426. DICTIONARY_STATS_MINUS_MEMORY(dict, 0, sizeof(DICTIONARY), 0);
  1427. if(dict->value_aral)
  1428. aral_by_size_release(dict->value_aral);
  1429. freez(dict);
  1430. internal_error(
  1431. false,
  1432. "DICTIONARY: Freed dictionary created from %s() %zu@%s, having %ld (counted %zu) entries, %ld referenced, %ld pending deletion, total freed memory: %zu bytes (sizeof(dict) = %zu, sizeof(item) = %zu).",
  1433. creation_function,
  1434. creation_line,
  1435. creation_file,
  1436. entries, counted_items, referenced_items, pending_deletion_items,
  1437. dict_size + item_size, sizeof(DICTIONARY), sizeof(DICTIONARY_ITEM) + sizeof(DICTIONARY_ITEM_SHARED));
  1438. if(mem)
  1439. *mem = dict_size + item_size + index_size;
  1440. return true;
  1441. }
  1442. netdata_mutex_t dictionaries_waiting_to_be_destroyed_mutex = NETDATA_MUTEX_INITIALIZER;
  1443. static DICTIONARY *dictionaries_waiting_to_be_destroyed = NULL;
  1444. void dictionary_queue_for_destruction(DICTIONARY *dict) {
  1445. if(is_dictionary_destroyed(dict))
  1446. return;
  1447. DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(dict);
  1448. dict_flag_set(dict, DICT_FLAG_DESTROYED);
  1449. netdata_mutex_lock(&dictionaries_waiting_to_be_destroyed_mutex);
  1450. dict->next = dictionaries_waiting_to_be_destroyed;
  1451. dictionaries_waiting_to_be_destroyed = dict;
  1452. netdata_mutex_unlock(&dictionaries_waiting_to_be_destroyed_mutex);
  1453. }
  1454. void cleanup_destroyed_dictionaries(void) {
  1455. if(!dictionaries_waiting_to_be_destroyed)
  1456. return;
  1457. netdata_mutex_lock(&dictionaries_waiting_to_be_destroyed_mutex);
  1458. DICTIONARY *dict, *last = NULL, *next = NULL;
  1459. for(dict = dictionaries_waiting_to_be_destroyed; dict ; dict = next) {
  1460. next = dict->next;
  1461. #ifdef NETDATA_INTERNAL_CHECKS
  1462. size_t line = dict->creation_line;
  1463. const char *file = dict->creation_file;
  1464. const char *function = dict->creation_function;
  1465. #endif
  1466. DICTIONARY_STATS_DICT_DESTROY_QUEUED_MINUS1(dict);
  1467. if(dictionary_free_all_resources(dict, NULL, false)) {
  1468. internal_error(
  1469. true,
  1470. "DICTIONARY: freed dictionary with delayed destruction, created from %s() %zu@%s.",
  1471. function, line, file);
  1472. if(last) last->next = next;
  1473. else dictionaries_waiting_to_be_destroyed = next;
  1474. }
  1475. else {
  1476. DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(dict);
  1477. last = dict;
  1478. }
  1479. }
  1480. netdata_mutex_unlock(&dictionaries_waiting_to_be_destroyed_mutex);
  1481. }
  1482. // ----------------------------------------------------------------------------
  1483. // API internal checks
  1484. #ifdef NETDATA_INTERNAL_CHECKS
  1485. #define api_internal_check(dict, item, allow_null_dict, allow_null_item) api_internal_check_with_trace(dict, item, __FUNCTION__, allow_null_dict, allow_null_item)
  1486. static inline void api_internal_check_with_trace(DICTIONARY *dict, DICTIONARY_ITEM *item, const char *function, bool allow_null_dict, bool allow_null_item) {
  1487. if(!allow_null_dict && !dict) {
  1488. internal_error(
  1489. item,
  1490. "DICTIONARY: attempted to %s() with a NULL dictionary, passing an item created from %s() %zu@%s.",
  1491. function,
  1492. item->dict->creation_function,
  1493. item->dict->creation_line,
  1494. item->dict->creation_file);
  1495. fatal("DICTIONARY: attempted to %s() but dict is NULL", function);
  1496. }
  1497. if(!allow_null_item && !item) {
  1498. internal_error(
  1499. true,
  1500. "DICTIONARY: attempted to %s() without an item on a dictionary created from %s() %zu@%s.",
  1501. function,
  1502. dict?dict->creation_function:"unknown",
  1503. dict?dict->creation_line:0,
  1504. dict?dict->creation_file:"unknown");
  1505. fatal("DICTIONARY: attempted to %s() but item is NULL", function);
  1506. }
  1507. if(dict && item && dict != item->dict) {
  1508. internal_error(
  1509. true,
  1510. "DICTIONARY: attempted to %s() an item on a dictionary created from %s() %zu@%s, but the item belongs to the dictionary created from %s() %zu@%s.",
  1511. function,
  1512. dict->creation_function,
  1513. dict->creation_line,
  1514. dict->creation_file,
  1515. item->dict->creation_function,
  1516. item->dict->creation_line,
  1517. item->dict->creation_file
  1518. );
  1519. fatal("DICTIONARY: %s(): item does not belong to this dictionary.", function);
  1520. }
  1521. if(item) {
  1522. REFCOUNT refcount = DICTIONARY_ITEM_REFCOUNT_GET(dict, item);
  1523. if (unlikely(refcount <= 0)) {
  1524. internal_error(
  1525. true,
  1526. "DICTIONARY: attempted to %s() of an item with reference counter = %d on a dictionary created from %s() %zu@%s",
  1527. function,
  1528. refcount,
  1529. item->dict->creation_function,
  1530. item->dict->creation_line,
  1531. item->dict->creation_file);
  1532. fatal("DICTIONARY: attempted to %s but item is having refcount = %d", function, refcount);
  1533. }
  1534. }
  1535. }
  1536. #else
  1537. #define api_internal_check(dict, item, allow_null_dict, allow_null_item) debug_dummy()
  1538. #endif
  1539. #define api_is_name_good(dict, name, name_len) api_is_name_good_with_trace(dict, name, name_len, __FUNCTION__)
  1540. static bool api_is_name_good_with_trace(DICTIONARY *dict __maybe_unused, const char *name, ssize_t name_len __maybe_unused, const char *function __maybe_unused) {
  1541. if(unlikely(!name)) {
  1542. internal_error(
  1543. true,
  1544. "DICTIONARY: attempted to %s() with name = NULL on a dictionary created from %s() %zu@%s.",
  1545. function,
  1546. dict?dict->creation_function:"unknown",
  1547. dict?dict->creation_line:0,
  1548. dict?dict->creation_file:"unknown");
  1549. return false;
  1550. }
  1551. if(unlikely(!*name)) {
  1552. internal_error(
  1553. true,
  1554. "DICTIONARY: attempted to %s() with empty name on a dictionary created from %s() %zu@%s.",
  1555. function,
  1556. dict?dict->creation_function:"unknown",
  1557. dict?dict->creation_line:0,
  1558. dict?dict->creation_file:"unknown");
  1559. return false;
  1560. }
  1561. internal_error(
  1562. name_len > 0 && name_len != (ssize_t)(strlen(name) + 1),
  1563. "DICTIONARY: attempted to %s() with a name of '%s', having length of %zu (incl. '\\0'), but the supplied name_len = %ld, on a dictionary created from %s() %zu@%s.",
  1564. function,
  1565. name,
  1566. strlen(name) + 1,
  1567. (long int) name_len,
  1568. dict?dict->creation_function:"unknown",
  1569. dict?dict->creation_line:0,
  1570. dict?dict->creation_file:"unknown");
  1571. internal_error(
  1572. name_len <= 0 && name_len != -1,
  1573. "DICTIONARY: attempted to %s() with a name of '%s', having length of %zu (incl. '\\0'), but the supplied name_len = %ld, on a dictionary created from %s() %zu@%s.",
  1574. function,
  1575. name,
  1576. strlen(name) + 1,
  1577. (long int) name_len,
  1578. dict?dict->creation_function:"unknown",
  1579. dict?dict->creation_line:0,
  1580. dict?dict->creation_file:"unknown");
  1581. return true;
  1582. }
  1583. // ----------------------------------------------------------------------------
  1584. // API - dictionary management
  1585. static DICTIONARY *dictionary_create_internal(DICT_OPTIONS options, struct dictionary_stats *stats, size_t fixed_size) {
  1586. cleanup_destroyed_dictionaries();
  1587. DICTIONARY *dict = callocz(1, sizeof(DICTIONARY));
  1588. dict->options = options;
  1589. dict->stats = stats;
  1590. if((dict->options & DICT_OPTION_FIXED_SIZE) && !fixed_size) {
  1591. dict->options &= ~DICT_OPTION_FIXED_SIZE;
  1592. internal_fatal(true, "DICTIONARY: requested fixed size dictionary, without setting the size");
  1593. }
  1594. if(!(dict->options & DICT_OPTION_FIXED_SIZE) && fixed_size) {
  1595. dict->options |= DICT_OPTION_FIXED_SIZE;
  1596. internal_fatal(true, "DICTIONARY: set a fixed size for the items, without setting DICT_OPTION_FIXED_SIZE flag");
  1597. }
  1598. if(dict->options & DICT_OPTION_FIXED_SIZE)
  1599. dict->value_aral = aral_by_size_acquire(fixed_size);
  1600. else
  1601. dict->value_aral = NULL;
  1602. size_t dict_size = 0;
  1603. dict_size += sizeof(DICTIONARY);
  1604. dict_size += dictionary_locks_init(dict);
  1605. dict_size += reference_counter_init(dict);
  1606. dict_size += hashtable_init_unsafe(dict);
  1607. dictionary_static_items_aral_init();
  1608. pointer_index_init(dict);
  1609. DICTIONARY_STATS_PLUS_MEMORY(dict, 0, dict_size, 0);
  1610. return dict;
  1611. }
  1612. #ifdef NETDATA_INTERNAL_CHECKS
  1613. DICTIONARY *dictionary_create_advanced_with_trace(DICT_OPTIONS options, struct dictionary_stats *stats, size_t fixed_size, const char *function, size_t line, const char *file) {
  1614. #else
  1615. DICTIONARY *dictionary_create_advanced(DICT_OPTIONS options, struct dictionary_stats *stats, size_t fixed_size) {
  1616. #endif
  1617. DICTIONARY *dict = dictionary_create_internal(options, stats?stats:&dictionary_stats_category_other, fixed_size);
  1618. #ifdef NETDATA_INTERNAL_CHECKS
  1619. dict->creation_function = function;
  1620. dict->creation_file = file;
  1621. dict->creation_line = line;
  1622. #endif
  1623. DICTIONARY_STATS_DICT_CREATIONS_PLUS1(dict);
  1624. return dict;
  1625. }
  1626. #ifdef NETDATA_INTERNAL_CHECKS
  1627. DICTIONARY *dictionary_create_view_with_trace(DICTIONARY *master, const char *function, size_t line, const char *file) {
  1628. #else
  1629. DICTIONARY *dictionary_create_view(DICTIONARY *master) {
  1630. #endif
  1631. DICTIONARY *dict = dictionary_create_internal(master->options, master->stats,
  1632. master->value_aral ? aral_element_size(master->value_aral) : 0);
  1633. dict->master = master;
  1634. dictionary_hooks_allocate(master);
  1635. if(unlikely(__atomic_load_n(&master->hooks->links, __ATOMIC_SEQ_CST)) < 1)
  1636. fatal("DICTIONARY: attempted to create a view that has %d links", master->hooks->links);
  1637. dict->hooks = master->hooks;
  1638. __atomic_add_fetch(&master->hooks->links, 1, __ATOMIC_SEQ_CST);
  1639. #ifdef NETDATA_INTERNAL_CHECKS
  1640. dict->creation_function = function;
  1641. dict->creation_file = file;
  1642. dict->creation_line = line;
  1643. #endif
  1644. DICTIONARY_STATS_DICT_CREATIONS_PLUS1(dict);
  1645. return dict;
  1646. }
  1647. void dictionary_flush(DICTIONARY *dict) {
  1648. if(unlikely(!dict))
  1649. return;
  1650. void *value;
  1651. dfe_start_write(dict, value) {
  1652. dictionary_del_advanced(dict, item_get_name(value_dfe.item), (ssize_t)item_get_name_len(value_dfe.item) + 1);
  1653. }
  1654. dfe_done(value);
  1655. DICTIONARY_STATS_DICT_FLUSHES_PLUS1(dict);
  1656. }
  1657. size_t dictionary_destroy(DICTIONARY *dict) {
  1658. cleanup_destroyed_dictionaries();
  1659. if(!dict) return 0;
  1660. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  1661. dict_flag_set(dict, DICT_FLAG_DESTROYED);
  1662. DICTIONARY_STATS_DICT_DESTRUCTIONS_PLUS1(dict);
  1663. size_t referenced_items = dictionary_referenced_items(dict);
  1664. if(referenced_items) {
  1665. dictionary_flush(dict);
  1666. dictionary_queue_for_destruction(dict);
  1667. internal_error(
  1668. true,
  1669. "DICTIONARY: delaying destruction of dictionary created from %s() %zu@%s, because it has %ld referenced items in it (%ld total).",
  1670. dict->creation_function,
  1671. dict->creation_line,
  1672. dict->creation_file,
  1673. dict->referenced_items,
  1674. dict->entries);
  1675. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1676. return 0;
  1677. }
  1678. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1679. size_t freed;
  1680. dictionary_free_all_resources(dict, &freed, true);
  1681. return freed;
  1682. }
  1683. // ----------------------------------------------------------------------------
  1684. // SET an item to the dictionary
  1685. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_set_and_acquire_item_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, void *value, size_t value_len, void *constructor_data) {
  1686. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1687. return NULL;
  1688. api_internal_check(dict, NULL, false, true);
  1689. if(unlikely(is_view_dictionary(dict)))
  1690. fatal("DICTIONARY: this dictionary is a view, you cannot add items other than the ones from the master dictionary.");
  1691. DICTIONARY_ITEM *item =
  1692. dict_item_add_or_reset_value_and_acquire(dict, name, name_len, value, value_len, constructor_data, NULL);
  1693. api_internal_check(dict, item, false, false);
  1694. return item;
  1695. }
  1696. void *dictionary_set_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, void *value, size_t value_len, void *constructor_data) {
  1697. DICTIONARY_ITEM *item = dictionary_set_and_acquire_item_advanced(dict, name, name_len, value, value_len, constructor_data);
  1698. if(likely(item)) {
  1699. void *v = item->shared->value;
  1700. item_release(dict, item);
  1701. return v;
  1702. }
  1703. return NULL;
  1704. }
  1705. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_view_set_and_acquire_item_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, DICTIONARY_ITEM *master_item) {
  1706. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1707. return NULL;
  1708. api_internal_check(dict, NULL, false, true);
  1709. if(unlikely(is_master_dictionary(dict)))
  1710. fatal("DICTIONARY: this dictionary is a master, you cannot add items from other dictionaries.");
  1711. dictionary_acquired_item_dup(dict->master, master_item);
  1712. DICTIONARY_ITEM *item = dict_item_add_or_reset_value_and_acquire(dict, name, name_len, NULL, 0, NULL, master_item);
  1713. dictionary_acquired_item_release(dict->master, master_item);
  1714. api_internal_check(dict, item, false, false);
  1715. return item;
  1716. }
  1717. void *dictionary_view_set_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, DICTIONARY_ITEM *master_item) {
  1718. DICTIONARY_ITEM *item = dictionary_view_set_and_acquire_item_advanced(dict, name, name_len, master_item);
  1719. if(likely(item)) {
  1720. void *v = item->shared->value;
  1721. item_release(dict, item);
  1722. return v;
  1723. }
  1724. return NULL;
  1725. }
  1726. // ----------------------------------------------------------------------------
  1727. // GET an item from the dictionary
  1728. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_get_and_acquire_item_advanced(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1729. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1730. return NULL;
  1731. api_internal_check(dict, NULL, false, true);
  1732. DICTIONARY_ITEM *item = dict_item_find_and_acquire(dict, name, name_len);
  1733. api_internal_check(dict, item, false, true);
  1734. return item;
  1735. }
  1736. void *dictionary_get_advanced(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1737. DICTIONARY_ITEM *item = dictionary_get_and_acquire_item_advanced(dict, name, name_len);
  1738. if(likely(item)) {
  1739. void *v = item->shared->value;
  1740. item_release(dict, item);
  1741. return v;
  1742. }
  1743. return NULL;
  1744. }
  1745. // ----------------------------------------------------------------------------
  1746. // DUP/REL an item (increase/decrease its reference counter)
  1747. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_acquired_item_dup(DICTIONARY *dict, DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1748. // we allow the item to be NULL here
  1749. api_internal_check(dict, item, false, true);
  1750. if(likely(item)) {
  1751. item_acquire(dict, item);
  1752. api_internal_check(dict, item, false, false);
  1753. }
  1754. return item;
  1755. }
  1756. void dictionary_acquired_item_release(DICTIONARY *dict, DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1757. // we allow the item to be NULL here
  1758. api_internal_check(dict, item, false, true);
  1759. // no need to get a lock here
  1760. // we pass the last parameter to reference_counter_release() as true
  1761. // so that the release may get a write-lock if required to clean up
  1762. if(likely(item))
  1763. item_release(dict, item);
  1764. }
  1765. // ----------------------------------------------------------------------------
  1766. // get the name/value of an item
  1767. const char *dictionary_acquired_item_name(DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1768. return item_get_name(item);
  1769. }
  1770. void *dictionary_acquired_item_value(DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1771. if(likely(item))
  1772. return item->shared->value;
  1773. return NULL;
  1774. }
  1775. size_t dictionary_acquired_item_references(DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1776. if(likely(item))
  1777. return DICTIONARY_ITEM_REFCOUNT_GET_SOLE(item);
  1778. return 0;
  1779. }
  1780. // ----------------------------------------------------------------------------
  1781. // DEL an item
  1782. bool dictionary_del_advanced(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1783. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1784. return false;
  1785. api_internal_check(dict, NULL, false, true);
  1786. return dict_item_del(dict, name, name_len);
  1787. }
  1788. // ----------------------------------------------------------------------------
  1789. // traversal with loop
  1790. void *dictionary_foreach_start_rw(DICTFE *dfe, DICTIONARY *dict, char rw) {
  1791. if(unlikely(!dfe || !dict)) return NULL;
  1792. if(unlikely(is_dictionary_destroyed(dict))) {
  1793. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_start_rw() on a destroyed dictionary");
  1794. dfe->counter = 0;
  1795. dfe->item = NULL;
  1796. dfe->name = NULL;
  1797. dfe->value = NULL;
  1798. return NULL;
  1799. }
  1800. dfe->counter = 0;
  1801. dfe->dict = dict;
  1802. dfe->rw = rw;
  1803. ll_recursive_lock(dict, dfe->rw);
  1804. DICTIONARY_STATS_TRAVERSALS_PLUS1(dict);
  1805. // get the first item from the list
  1806. DICTIONARY_ITEM *item = dict->items.list;
  1807. // skip all the deleted items
  1808. while(item && !item_check_and_acquire(dict, item))
  1809. item = item->next;
  1810. if(likely(item)) {
  1811. dfe->item = item;
  1812. dfe->name = (char *)item_get_name(item);
  1813. dfe->value = item->shared->value;
  1814. }
  1815. else {
  1816. dfe->item = NULL;
  1817. dfe->name = NULL;
  1818. dfe->value = NULL;
  1819. }
  1820. if(unlikely(dfe->rw == DICTIONARY_LOCK_REENTRANT))
  1821. ll_recursive_unlock(dfe->dict, dfe->rw);
  1822. return dfe->value;
  1823. }
  1824. void *dictionary_foreach_next(DICTFE *dfe) {
  1825. if(unlikely(!dfe || !dfe->dict)) return NULL;
  1826. if(unlikely(is_dictionary_destroyed(dfe->dict))) {
  1827. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_next() on a destroyed dictionary");
  1828. dfe->item = NULL;
  1829. dfe->name = NULL;
  1830. dfe->value = NULL;
  1831. return NULL;
  1832. }
  1833. if(unlikely(dfe->rw == DICTIONARY_LOCK_REENTRANT))
  1834. ll_recursive_lock(dfe->dict, dfe->rw);
  1835. // the item we just did
  1836. DICTIONARY_ITEM *item = dfe->item;
  1837. // get the next item from the list
  1838. DICTIONARY_ITEM *item_next = (item) ? item->next : NULL;
  1839. // skip all the deleted items until one that can be acquired is found
  1840. while(item_next && !item_check_and_acquire(dfe->dict, item_next))
  1841. item_next = item_next->next;
  1842. if(likely(item)) {
  1843. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dfe->dict, item, dfe->rw);
  1844. // item_release(dfe->dict, item);
  1845. }
  1846. item = item_next;
  1847. if(likely(item)) {
  1848. dfe->item = item;
  1849. dfe->name = (char *)item_get_name(item);
  1850. dfe->value = item->shared->value;
  1851. dfe->counter++;
  1852. }
  1853. else {
  1854. dfe->item = NULL;
  1855. dfe->name = NULL;
  1856. dfe->value = NULL;
  1857. }
  1858. if(unlikely(dfe->rw == DICTIONARY_LOCK_REENTRANT))
  1859. ll_recursive_unlock(dfe->dict, dfe->rw);
  1860. return dfe->value;
  1861. }
  1862. void dictionary_foreach_done(DICTFE *dfe) {
  1863. if(unlikely(!dfe || !dfe->dict)) return;
  1864. if(unlikely(is_dictionary_destroyed(dfe->dict))) {
  1865. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_next() on a destroyed dictionary");
  1866. return;
  1867. }
  1868. // the item we just did
  1869. DICTIONARY_ITEM *item = dfe->item;
  1870. // release it, so that it can possibly be deleted
  1871. if(likely(item)) {
  1872. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dfe->dict, item, dfe->rw);
  1873. // item_release(dfe->dict, item);
  1874. }
  1875. if(likely(dfe->rw != DICTIONARY_LOCK_REENTRANT))
  1876. ll_recursive_unlock(dfe->dict, dfe->rw);
  1877. dfe->dict = NULL;
  1878. dfe->item = NULL;
  1879. dfe->name = NULL;
  1880. dfe->value = NULL;
  1881. dfe->counter = 0;
  1882. }
  1883. // ----------------------------------------------------------------------------
  1884. // API - walk through the dictionary.
  1885. // The dictionary is locked for reading while this happens
  1886. // do not use other dictionary calls while walking the dictionary - deadlock!
  1887. int dictionary_walkthrough_rw(DICTIONARY *dict, char rw, int (*callback)(const DICTIONARY_ITEM *item, void *entry, void *data), void *data) {
  1888. if(unlikely(!dict || !callback)) return 0;
  1889. if(unlikely(is_dictionary_destroyed(dict))) {
  1890. internal_error(true, "DICTIONARY: attempted to dictionary_walkthrough_rw() on a destroyed dictionary");
  1891. return 0;
  1892. }
  1893. ll_recursive_lock(dict, rw);
  1894. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  1895. // written in such a way, that the callback can delete the active element
  1896. int ret = 0;
  1897. DICTIONARY_ITEM *item = dict->items.list, *item_next;
  1898. while(item) {
  1899. // skip the deleted items
  1900. if(unlikely(!item_check_and_acquire(dict, item))) {
  1901. item = item->next;
  1902. continue;
  1903. }
  1904. if(unlikely(rw == DICTIONARY_LOCK_REENTRANT))
  1905. ll_recursive_unlock(dict, rw);
  1906. int r = callback(item, item->shared->value, data);
  1907. if(unlikely(rw == DICTIONARY_LOCK_REENTRANT))
  1908. ll_recursive_lock(dict, rw);
  1909. // since we have a reference counter, this item cannot be deleted
  1910. // until we release the reference counter, so the pointers are there
  1911. item_next = item->next;
  1912. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dict, item, rw);
  1913. // item_release(dict, item);
  1914. if(unlikely(r < 0)) {
  1915. ret = r;
  1916. break;
  1917. }
  1918. ret += r;
  1919. item = item_next;
  1920. }
  1921. ll_recursive_unlock(dict, rw);
  1922. return ret;
  1923. }
  1924. // ----------------------------------------------------------------------------
  1925. // sorted walkthrough
  1926. typedef int (*qsort_compar)(const void *item1, const void *item2);
  1927. static int dictionary_sort_compar(const void *item1, const void *item2) {
  1928. return strcmp(item_get_name((*(DICTIONARY_ITEM **)item1)), item_get_name((*(DICTIONARY_ITEM **)item2)));
  1929. }
  1930. int dictionary_sorted_walkthrough_rw(DICTIONARY *dict, char rw, int (*callback)(const DICTIONARY_ITEM *item, void *entry, void *data), void *data, dictionary_sorted_compar compar) {
  1931. if(unlikely(!dict || !callback)) return 0;
  1932. if(unlikely(is_dictionary_destroyed(dict))) {
  1933. internal_error(true, "DICTIONARY: attempted to dictionary_sorted_walkthrough_rw() on a destroyed dictionary");
  1934. return 0;
  1935. }
  1936. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  1937. ll_recursive_lock(dict, rw);
  1938. size_t entries = __atomic_load_n(&dict->entries, __ATOMIC_SEQ_CST);
  1939. DICTIONARY_ITEM **array = mallocz(sizeof(DICTIONARY_ITEM *) * entries);
  1940. size_t i;
  1941. DICTIONARY_ITEM *item;
  1942. for(item = dict->items.list, i = 0; item && i < entries; item = item->next) {
  1943. if(likely(item_check_and_acquire(dict, item)))
  1944. array[i++] = item;
  1945. }
  1946. ll_recursive_unlock(dict, rw);
  1947. if(unlikely(i != entries))
  1948. entries = i;
  1949. if(compar)
  1950. qsort(array, entries, sizeof(DICTIONARY_ITEM *), (qsort_compar)compar);
  1951. else
  1952. qsort(array, entries, sizeof(DICTIONARY_ITEM *), dictionary_sort_compar);
  1953. bool callit = true;
  1954. int ret = 0, r;
  1955. for(i = 0; i < entries ;i++) {
  1956. item = array[i];
  1957. if(callit)
  1958. r = callback(item, item->shared->value, data);
  1959. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dict, item, rw);
  1960. // item_release(dict, item);
  1961. if(r < 0) {
  1962. ret = r;
  1963. r = 0;
  1964. // stop calling the callback,
  1965. // but we have to continue, to release all the reference counters
  1966. callit = false;
  1967. }
  1968. else
  1969. ret += r;
  1970. }
  1971. freez(array);
  1972. return ret;
  1973. }
  1974. // ----------------------------------------------------------------------------
  1975. // THREAD_CACHE
  1976. static __thread Pvoid_t thread_cache_judy_array = NULL;
  1977. void *thread_cache_entry_get_or_set(void *key,
  1978. ssize_t key_length,
  1979. void *value,
  1980. void *(*transform_the_value_before_insert)(void *key, size_t key_length, void *value)
  1981. ) {
  1982. if(unlikely(!key || !key_length)) return NULL;
  1983. if(key_length == -1)
  1984. key_length = (ssize_t)strlen((char *)key) + 1;
  1985. JError_t J_Error;
  1986. Pvoid_t *Rc = JudyHSIns(&thread_cache_judy_array, key, key_length, &J_Error);
  1987. if (unlikely(Rc == PJERR)) {
  1988. fatal("THREAD_CACHE: Cannot insert entry to JudyHS, JU_ERRNO_* == %u, ID == %d",
  1989. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  1990. }
  1991. if(*Rc == 0) {
  1992. // new item added
  1993. *Rc = (transform_the_value_before_insert) ? transform_the_value_before_insert(key, key_length, value) : value;
  1994. }
  1995. return *Rc;
  1996. }
  1997. void thread_cache_destroy(void) {
  1998. if(unlikely(!thread_cache_judy_array)) return;
  1999. JError_t J_Error;
  2000. Word_t ret = JudyHSFreeArray(&thread_cache_judy_array, &J_Error);
  2001. if(unlikely(ret == (Word_t) JERR)) {
  2002. error("THREAD_CACHE: Cannot destroy JudyHS, JU_ERRNO_* == %u, ID == %d",
  2003. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  2004. }
  2005. internal_error(true, "THREAD_CACHE: hash table freed %lu bytes", ret);
  2006. thread_cache_judy_array = NULL;
  2007. }
  2008. // ----------------------------------------------------------------------------
  2009. // unit test
  2010. static void dictionary_unittest_free_char_pp(char **pp, size_t entries) {
  2011. for(size_t i = 0; i < entries ;i++)
  2012. freez(pp[i]);
  2013. freez(pp);
  2014. }
  2015. static char **dictionary_unittest_generate_names(size_t entries) {
  2016. char **names = mallocz(sizeof(char *) * entries);
  2017. for(size_t i = 0; i < entries ;i++) {
  2018. char buf[25 + 1] = "";
  2019. snprintfz(buf, 25, "name.%zu.0123456789.%zu!@#$%%^&*(),./[]{}\\|~`", i, entries / 2 + i);
  2020. names[i] = strdupz(buf);
  2021. }
  2022. return names;
  2023. }
  2024. static char **dictionary_unittest_generate_values(size_t entries) {
  2025. char **values = mallocz(sizeof(char *) * entries);
  2026. for(size_t i = 0; i < entries ;i++) {
  2027. char buf[25 + 1] = "";
  2028. snprintfz(buf, 25, "value-%zu-0987654321.%zu%%^&*(),. \t !@#$/[]{}\\|~`", i, entries / 2 + i);
  2029. values[i] = strdupz(buf);
  2030. }
  2031. return values;
  2032. }
  2033. static size_t dictionary_unittest_set_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2034. size_t errors = 0;
  2035. for(size_t i = 0; i < entries ;i++) {
  2036. size_t vallen = strlen(values[i]) + 1;
  2037. char *val = (char *)dictionary_set(dict, names[i], values[i], vallen);
  2038. if(val == values[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  2039. if(!val || memcmp(val, values[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2040. }
  2041. return errors;
  2042. }
  2043. static size_t dictionary_unittest_set_null(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2044. (void)values;
  2045. size_t errors = 0;
  2046. size_t i = 0;
  2047. for(; i < entries ;i++) {
  2048. void *val = dictionary_set(dict, names[i], NULL, 0);
  2049. if(val != NULL) { fprintf(stderr, ">>> %s() returns a non NULL value\n", __FUNCTION__); errors++; }
  2050. }
  2051. if(dictionary_entries(dict) != i) {
  2052. fprintf(stderr, ">>> %s() dictionary items do not match\n", __FUNCTION__);
  2053. errors++;
  2054. }
  2055. return errors;
  2056. }
  2057. static size_t dictionary_unittest_set_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2058. size_t errors = 0;
  2059. for(size_t i = 0; i < entries ;i++) {
  2060. size_t vallen = strlen(values[i]) + 1;
  2061. char *val = (char *)dictionary_set(dict, names[i], values[i], vallen);
  2062. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2063. }
  2064. return errors;
  2065. }
  2066. static size_t dictionary_unittest_get_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2067. size_t errors = 0;
  2068. for(size_t i = 0; i < entries ;i++) {
  2069. size_t vallen = strlen(values[i]) + 1;
  2070. char *val = (char *)dictionary_get(dict, names[i]);
  2071. if(val == values[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  2072. if(!val || memcmp(val, values[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2073. }
  2074. return errors;
  2075. }
  2076. static size_t dictionary_unittest_get_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2077. size_t errors = 0;
  2078. for(size_t i = 0; i < entries ;i++) {
  2079. char *val = (char *)dictionary_get(dict, names[i]);
  2080. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2081. }
  2082. return errors;
  2083. }
  2084. static size_t dictionary_unittest_get_nonexisting(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2085. (void)names;
  2086. size_t errors = 0;
  2087. for(size_t i = 0; i < entries ;i++) {
  2088. char *val = (char *)dictionary_get(dict, values[i]);
  2089. if(val) { fprintf(stderr, ">>> %s() returns non-existing item\n", __FUNCTION__); errors++; }
  2090. }
  2091. return errors;
  2092. }
  2093. static size_t dictionary_unittest_del_nonexisting(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2094. (void)names;
  2095. size_t errors = 0;
  2096. for(size_t i = 0; i < entries ;i++) {
  2097. bool ret = dictionary_del(dict, values[i]);
  2098. if(ret) { fprintf(stderr, ">>> %s() deleted non-existing item\n", __FUNCTION__); errors++; }
  2099. }
  2100. return errors;
  2101. }
  2102. static size_t dictionary_unittest_del_existing(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2103. (void)values;
  2104. size_t errors = 0;
  2105. size_t forward_from = 0, forward_to = entries / 3;
  2106. size_t middle_from = forward_to, middle_to = entries * 2 / 3;
  2107. size_t backward_from = middle_to, backward_to = entries;
  2108. for(size_t i = forward_from; i < forward_to ;i++) {
  2109. bool ret = dictionary_del(dict, names[i]);
  2110. if(!ret) { fprintf(stderr, ">>> %s() didn't delete (forward) existing item\n", __FUNCTION__); errors++; }
  2111. }
  2112. for(size_t i = middle_to - 1; i >= middle_from ;i--) {
  2113. bool ret = dictionary_del(dict, names[i]);
  2114. if(!ret) { fprintf(stderr, ">>> %s() didn't delete (middle) existing item\n", __FUNCTION__); errors++; }
  2115. }
  2116. for(size_t i = backward_to - 1; i >= backward_from ;i--) {
  2117. bool ret = dictionary_del(dict, names[i]);
  2118. if(!ret) { fprintf(stderr, ">>> %s() didn't delete (backward) existing item\n", __FUNCTION__); errors++; }
  2119. }
  2120. return errors;
  2121. }
  2122. static size_t dictionary_unittest_reset_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2123. (void)values;
  2124. // set the name as value too
  2125. size_t errors = 0;
  2126. for(size_t i = 0; i < entries ;i++) {
  2127. size_t vallen = strlen(names[i]) + 1;
  2128. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  2129. if(val == names[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  2130. if(!val || memcmp(val, names[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2131. }
  2132. return errors;
  2133. }
  2134. static size_t dictionary_unittest_reset_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2135. (void)values;
  2136. // set the name as value too
  2137. size_t errors = 0;
  2138. for(size_t i = 0; i < entries ;i++) {
  2139. size_t vallen = strlen(names[i]) + 1;
  2140. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  2141. if(val != names[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2142. if(!val) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2143. }
  2144. return errors;
  2145. }
  2146. static size_t dictionary_unittest_reset_dont_overwrite_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2147. // set the name as value too
  2148. size_t errors = 0;
  2149. for(size_t i = 0; i < entries ;i++) {
  2150. size_t vallen = strlen(names[i]) + 1;
  2151. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  2152. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2153. }
  2154. return errors;
  2155. }
  2156. static int dictionary_unittest_walkthrough_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value __maybe_unused, void *data __maybe_unused) {
  2157. return 1;
  2158. }
  2159. static size_t dictionary_unittest_walkthrough(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2160. (void)names;
  2161. (void)values;
  2162. int sum = dictionary_walkthrough_read(dict, dictionary_unittest_walkthrough_callback, NULL);
  2163. if(sum < (int)entries) return entries - sum;
  2164. else return sum - entries;
  2165. }
  2166. static int dictionary_unittest_walkthrough_delete_this_callback(const DICTIONARY_ITEM *item, void *value __maybe_unused, void *data) {
  2167. const char *name = dictionary_acquired_item_name((DICTIONARY_ITEM *)item);
  2168. if(!dictionary_del((DICTIONARY *)data, name))
  2169. return 0;
  2170. return 1;
  2171. }
  2172. static size_t dictionary_unittest_walkthrough_delete_this(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2173. (void)names;
  2174. (void)values;
  2175. int sum = dictionary_walkthrough_write(dict, dictionary_unittest_walkthrough_delete_this_callback, dict);
  2176. if(sum < (int)entries) return entries - sum;
  2177. else return sum - entries;
  2178. }
  2179. static int dictionary_unittest_walkthrough_stop_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value __maybe_unused, void *data __maybe_unused) {
  2180. return -1;
  2181. }
  2182. static size_t dictionary_unittest_walkthrough_stop(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2183. (void)names;
  2184. (void)values;
  2185. (void)entries;
  2186. int sum = dictionary_walkthrough_read(dict, dictionary_unittest_walkthrough_stop_callback, NULL);
  2187. if(sum != -1) return 1;
  2188. return 0;
  2189. }
  2190. static size_t dictionary_unittest_foreach(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2191. (void)names;
  2192. (void)values;
  2193. (void)entries;
  2194. size_t count = 0;
  2195. char *item;
  2196. dfe_start_read(dict, item)
  2197. count++;
  2198. dfe_done(item);
  2199. if(count > entries) return count - entries;
  2200. return entries - count;
  2201. }
  2202. static size_t dictionary_unittest_foreach_delete_this(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2203. (void)names;
  2204. (void)values;
  2205. (void)entries;
  2206. size_t count = 0;
  2207. char *item;
  2208. dfe_start_write(dict, item)
  2209. if(dictionary_del(dict, item_dfe.name)) count++;
  2210. dfe_done(item);
  2211. if(count > entries) return count - entries;
  2212. return entries - count;
  2213. }
  2214. static size_t dictionary_unittest_destroy(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2215. (void)names;
  2216. (void)values;
  2217. (void)entries;
  2218. size_t bytes = dictionary_destroy(dict);
  2219. fprintf(stderr, " %s() freed %zu bytes,", __FUNCTION__, bytes);
  2220. return 0;
  2221. }
  2222. 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)) {
  2223. fprintf(stderr, "%40s ... ", message);
  2224. usec_t started = now_realtime_usec();
  2225. size_t errs = callback(dict, names, values, entries);
  2226. usec_t ended = now_realtime_usec();
  2227. usec_t dt = ended - started;
  2228. if(callback == dictionary_unittest_destroy) dict = NULL;
  2229. long int found_ok = 0, found_deleted = 0, found_referenced = 0;
  2230. if(dict) {
  2231. DICTIONARY_ITEM *item;
  2232. DOUBLE_LINKED_LIST_FOREACH_FORWARD(dict->items.list, item, prev, next) {
  2233. if(item->refcount >= 0 && !(item ->flags & ITEM_FLAG_DELETED))
  2234. found_ok++;
  2235. else
  2236. found_deleted++;
  2237. if(item->refcount > 0)
  2238. found_referenced++;
  2239. }
  2240. }
  2241. fprintf(stderr, " %zu errors, %ld (found %ld) items in dictionary, %ld (found %ld) referenced, %ld (found %ld) deleted, %llu usec \n",
  2242. errs, dict?dict->entries:0, found_ok, dict?dict->referenced_items:0, found_referenced, dict?dict->pending_deletion_items:0, found_deleted, dt);
  2243. *errors += errs;
  2244. return dt;
  2245. }
  2246. static void dictionary_unittest_clone(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2247. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_clone);
  2248. dictionary_unittest_run_and_measure_time(dict, "getting entries", names, values, entries, errors, dictionary_unittest_get_clone);
  2249. dictionary_unittest_run_and_measure_time(dict, "getting non-existing entries", names, values, entries, errors, dictionary_unittest_get_nonexisting);
  2250. dictionary_unittest_run_and_measure_time(dict, "resetting entries", names, values, entries, errors, dictionary_unittest_reset_clone);
  2251. dictionary_unittest_run_and_measure_time(dict, "deleting non-existing entries", names, values, entries, errors, dictionary_unittest_del_nonexisting);
  2252. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  2253. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, errors, dictionary_unittest_walkthrough);
  2254. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, errors, dictionary_unittest_walkthrough_stop);
  2255. dictionary_unittest_run_and_measure_time(dict, "deleting existing entries", names, values, entries, errors, dictionary_unittest_del_existing);
  2256. dictionary_unittest_run_and_measure_time(dict, "walking through empty", names, values, 0, errors, dictionary_unittest_walkthrough);
  2257. dictionary_unittest_run_and_measure_time(dict, "traverse foreach empty", names, values, 0, errors, dictionary_unittest_foreach);
  2258. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, errors, dictionary_unittest_destroy);
  2259. }
  2260. static void dictionary_unittest_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2261. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_nonclone);
  2262. dictionary_unittest_run_and_measure_time(dict, "getting entries", names, values, entries, errors, dictionary_unittest_get_nonclone);
  2263. dictionary_unittest_run_and_measure_time(dict, "getting non-existing entries", names, values, entries, errors, dictionary_unittest_get_nonexisting);
  2264. dictionary_unittest_run_and_measure_time(dict, "resetting entries", names, values, entries, errors, dictionary_unittest_reset_nonclone);
  2265. dictionary_unittest_run_and_measure_time(dict, "deleting non-existing entries", names, values, entries, errors, dictionary_unittest_del_nonexisting);
  2266. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  2267. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, errors, dictionary_unittest_walkthrough);
  2268. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, errors, dictionary_unittest_walkthrough_stop);
  2269. dictionary_unittest_run_and_measure_time(dict, "deleting existing entries", names, values, entries, errors, dictionary_unittest_del_existing);
  2270. dictionary_unittest_run_and_measure_time(dict, "walking through empty", names, values, 0, errors, dictionary_unittest_walkthrough);
  2271. dictionary_unittest_run_and_measure_time(dict, "traverse foreach empty", names, values, 0, errors, dictionary_unittest_foreach);
  2272. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, errors, dictionary_unittest_destroy);
  2273. }
  2274. struct dictionary_unittest_sorting {
  2275. const char *old_name;
  2276. const char *old_value;
  2277. size_t count;
  2278. };
  2279. static int dictionary_unittest_sorting_callback(const DICTIONARY_ITEM *item, void *value, void *data) {
  2280. const char *name = dictionary_acquired_item_name((DICTIONARY_ITEM *)item);
  2281. struct dictionary_unittest_sorting *t = (struct dictionary_unittest_sorting *)data;
  2282. const char *v = (const char *)value;
  2283. int ret = 0;
  2284. if(t->old_name && strcmp(t->old_name, name) > 0) {
  2285. fprintf(stderr, "name '%s' should be after '%s'\n", t->old_name, name);
  2286. ret = 1;
  2287. }
  2288. t->count++;
  2289. t->old_name = name;
  2290. t->old_value = v;
  2291. return ret;
  2292. }
  2293. static size_t dictionary_unittest_sorted_walkthrough(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2294. (void)names;
  2295. (void)values;
  2296. struct dictionary_unittest_sorting tmp = { .old_name = NULL, .old_value = NULL, .count = 0 };
  2297. size_t errors;
  2298. errors = dictionary_sorted_walkthrough_read(dict, dictionary_unittest_sorting_callback, &tmp);
  2299. if(tmp.count != entries) {
  2300. fprintf(stderr, "Expected %zu entries, counted %zu\n", entries, tmp.count);
  2301. errors++;
  2302. }
  2303. return errors;
  2304. }
  2305. static void dictionary_unittest_sorting(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2306. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_clone);
  2307. dictionary_unittest_run_and_measure_time(dict, "sorted walkthrough", names, values, entries, errors, dictionary_unittest_sorted_walkthrough);
  2308. }
  2309. static void dictionary_unittest_null_dfe(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2310. dictionary_unittest_run_and_measure_time(dict, "adding null value entries", names, values, entries, errors, dictionary_unittest_set_null);
  2311. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  2312. }
  2313. static int unittest_check_dictionary_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value __maybe_unused, void *data __maybe_unused) {
  2314. return 1;
  2315. }
  2316. static size_t unittest_check_dictionary(const char *label, DICTIONARY *dict, size_t traversable, size_t active_items, size_t deleted_items, size_t referenced_items, size_t pending_deletion) {
  2317. size_t errors = 0;
  2318. size_t ll = 0;
  2319. void *t;
  2320. dfe_start_read(dict, t)
  2321. ll++;
  2322. dfe_done(t);
  2323. fprintf(stderr, "DICT %-20s: dictionary foreach entries %zu, expected %zu...\t\t\t\t\t",
  2324. label, ll, traversable);
  2325. if(ll != traversable) {
  2326. fprintf(stderr, "FAILED\n");
  2327. errors++;
  2328. }
  2329. else
  2330. fprintf(stderr, "OK\n");
  2331. ll = dictionary_walkthrough_read(dict, unittest_check_dictionary_callback, NULL);
  2332. fprintf(stderr, "DICT %-20s: dictionary walkthrough entries %zu, expected %zu...\t\t\t\t",
  2333. label, ll, traversable);
  2334. if(ll != traversable) {
  2335. fprintf(stderr, "FAILED\n");
  2336. errors++;
  2337. }
  2338. else
  2339. fprintf(stderr, "OK\n");
  2340. ll = dictionary_sorted_walkthrough_read(dict, unittest_check_dictionary_callback, NULL);
  2341. fprintf(stderr, "DICT %-20s: dictionary sorted walkthrough entries %zu, expected %zu...\t\t\t",
  2342. label, ll, traversable);
  2343. if(ll != traversable) {
  2344. fprintf(stderr, "FAILED\n");
  2345. errors++;
  2346. }
  2347. else
  2348. fprintf(stderr, "OK\n");
  2349. DICTIONARY_ITEM *item;
  2350. size_t active = 0, deleted = 0, referenced = 0, pending = 0;
  2351. for(item = dict->items.list; item; item = item->next) {
  2352. if(!(item->flags & ITEM_FLAG_DELETED) && !(item->shared->flags & ITEM_FLAG_DELETED))
  2353. active++;
  2354. else {
  2355. deleted++;
  2356. if(item->refcount == 0)
  2357. pending++;
  2358. }
  2359. if(item->refcount > 0)
  2360. referenced++;
  2361. }
  2362. fprintf(stderr, "DICT %-20s: dictionary active items reported %ld, counted %zu, expected %zu...\t\t\t",
  2363. label, dict->entries, active, active_items);
  2364. if(active != active_items || active != (size_t)dict->entries) {
  2365. fprintf(stderr, "FAILED\n");
  2366. errors++;
  2367. }
  2368. else
  2369. fprintf(stderr, "OK\n");
  2370. fprintf(stderr, "DICT %-20s: dictionary deleted items counted %zu, expected %zu...\t\t\t\t",
  2371. label, deleted, deleted_items);
  2372. if(deleted != deleted_items) {
  2373. fprintf(stderr, "FAILED\n");
  2374. errors++;
  2375. }
  2376. else
  2377. fprintf(stderr, "OK\n");
  2378. fprintf(stderr, "DICT %-20s: dictionary referenced items reported %ld, counted %zu, expected %zu...\t\t",
  2379. label, dict->referenced_items, referenced, referenced_items);
  2380. if(referenced != referenced_items || dict->referenced_items != (long int)referenced) {
  2381. fprintf(stderr, "FAILED\n");
  2382. errors++;
  2383. }
  2384. else
  2385. fprintf(stderr, "OK\n");
  2386. fprintf(stderr, "DICT %-20s: dictionary pending deletion items reported %ld, counted %zu, expected %zu...\t",
  2387. label, dict->pending_deletion_items, pending, pending_deletion);
  2388. if(pending != pending_deletion || pending != (size_t)dict->pending_deletion_items) {
  2389. fprintf(stderr, "FAILED\n");
  2390. errors++;
  2391. }
  2392. else
  2393. fprintf(stderr, "OK\n");
  2394. return errors;
  2395. }
  2396. static int check_item_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value, void *data) {
  2397. return value == data;
  2398. }
  2399. static size_t unittest_check_item(const char *label, DICTIONARY *dict,
  2400. DICTIONARY_ITEM *item, const char *name, const char *value, int refcount,
  2401. ITEM_FLAGS deleted_flags, bool searchable, bool browsable, bool linked) {
  2402. size_t errors = 0;
  2403. fprintf(stderr, "ITEM %-20s: name is '%s', expected '%s'...\t\t\t\t\t\t", label, item_get_name(item), name);
  2404. if(strcmp(item_get_name(item), name) != 0) {
  2405. fprintf(stderr, "FAILED\n");
  2406. errors++;
  2407. }
  2408. else
  2409. fprintf(stderr, "OK\n");
  2410. fprintf(stderr, "ITEM %-20s: value is '%s', expected '%s'...\t\t\t\t\t", label, (const char *)item->shared->value, value);
  2411. if(strcmp((const char *)item->shared->value, value) != 0) {
  2412. fprintf(stderr, "FAILED\n");
  2413. errors++;
  2414. }
  2415. else
  2416. fprintf(stderr, "OK\n");
  2417. fprintf(stderr, "ITEM %-20s: refcount is %d, expected %d...\t\t\t\t\t\t\t", label, item->refcount, refcount);
  2418. if (item->refcount != refcount) {
  2419. fprintf(stderr, "FAILED\n");
  2420. errors++;
  2421. }
  2422. else
  2423. fprintf(stderr, "OK\n");
  2424. fprintf(stderr, "ITEM %-20s: deleted flag is %s, expected %s...\t\t\t\t\t", label,
  2425. (item->flags & ITEM_FLAG_DELETED || item->shared->flags & ITEM_FLAG_DELETED)?"true":"false",
  2426. (deleted_flags & ITEM_FLAG_DELETED)?"true":"false");
  2427. if ((item->flags & ITEM_FLAG_DELETED || item->shared->flags & ITEM_FLAG_DELETED) != (deleted_flags & ITEM_FLAG_DELETED)) {
  2428. fprintf(stderr, "FAILED\n");
  2429. errors++;
  2430. }
  2431. else
  2432. fprintf(stderr, "OK\n");
  2433. void *v = dictionary_get(dict, name);
  2434. bool found = v == item->shared->value;
  2435. fprintf(stderr, "ITEM %-20s: searchable %5s, expected %5s...\t\t\t\t\t\t", label,
  2436. found?"true":"false", searchable?"true":"false");
  2437. if(found != searchable) {
  2438. fprintf(stderr, "FAILED\n");
  2439. errors++;
  2440. }
  2441. else
  2442. fprintf(stderr, "OK\n");
  2443. found = false;
  2444. void *t;
  2445. dfe_start_read(dict, t) {
  2446. if(t == item->shared->value) found = true;
  2447. }
  2448. dfe_done(t);
  2449. fprintf(stderr, "ITEM %-20s: dfe browsable %5s, expected %5s...\t\t\t\t\t", label,
  2450. found?"true":"false", browsable?"true":"false");
  2451. if(found != browsable) {
  2452. fprintf(stderr, "FAILED\n");
  2453. errors++;
  2454. }
  2455. else
  2456. fprintf(stderr, "OK\n");
  2457. found = dictionary_walkthrough_read(dict, check_item_callback, item->shared->value);
  2458. fprintf(stderr, "ITEM %-20s: walkthrough browsable %5s, expected %5s...\t\t\t\t", label,
  2459. found?"true":"false", browsable?"true":"false");
  2460. if(found != browsable) {
  2461. fprintf(stderr, "FAILED\n");
  2462. errors++;
  2463. }
  2464. else
  2465. fprintf(stderr, "OK\n");
  2466. found = dictionary_sorted_walkthrough_read(dict, check_item_callback, item->shared->value);
  2467. fprintf(stderr, "ITEM %-20s: sorted walkthrough browsable %5s, expected %5s...\t\t\t", label,
  2468. found?"true":"false", browsable?"true":"false");
  2469. if(found != browsable) {
  2470. fprintf(stderr, "FAILED\n");
  2471. errors++;
  2472. }
  2473. else
  2474. fprintf(stderr, "OK\n");
  2475. found = false;
  2476. DICTIONARY_ITEM *n;
  2477. for(n = dict->items.list; n ;n = n->next)
  2478. if(n == item) found = true;
  2479. fprintf(stderr, "ITEM %-20s: linked %5s, expected %5s...\t\t\t\t\t\t", label,
  2480. found?"true":"false", linked?"true":"false");
  2481. if(found != linked) {
  2482. fprintf(stderr, "FAILED\n");
  2483. errors++;
  2484. }
  2485. else
  2486. fprintf(stderr, "OK\n");
  2487. return errors;
  2488. }
  2489. struct thread_unittest {
  2490. int join;
  2491. DICTIONARY *dict;
  2492. int dups;
  2493. };
  2494. static void *unittest_dict_thread(void *arg) {
  2495. struct thread_unittest *tu = arg;
  2496. for(; 1 ;) {
  2497. if(__atomic_load_n(&tu->join, __ATOMIC_RELAXED))
  2498. break;
  2499. DICT_ITEM_CONST DICTIONARY_ITEM *item =
  2500. dictionary_set_and_acquire_item_advanced(tu->dict, "dict thread checking 1234567890",
  2501. -1, NULL, 0, NULL);
  2502. dictionary_get(tu->dict, dictionary_acquired_item_name(item));
  2503. void *t1;
  2504. dfe_start_write(tu->dict, t1) {
  2505. // this should delete the referenced item
  2506. dictionary_del(tu->dict, t1_dfe.name);
  2507. void *t2;
  2508. dfe_start_write(tu->dict, t2) {
  2509. // this should add another
  2510. dictionary_set(tu->dict, t2_dfe.name, NULL, 0);
  2511. dictionary_get(tu->dict, dictionary_acquired_item_name(item));
  2512. // and this should delete it again
  2513. dictionary_del(tu->dict, t2_dfe.name);
  2514. }
  2515. dfe_done(t2);
  2516. // this should fail to add it
  2517. dictionary_set(tu->dict, t1_dfe.name, NULL, 0);
  2518. dictionary_del(tu->dict, t1_dfe.name);
  2519. }
  2520. dfe_done(t1);
  2521. for(int i = 0; i < tu->dups ; i++) {
  2522. dictionary_acquired_item_dup(tu->dict, item);
  2523. dictionary_get(tu->dict, dictionary_acquired_item_name(item));
  2524. }
  2525. for(int i = 0; i < tu->dups ; i++) {
  2526. dictionary_acquired_item_release(tu->dict, item);
  2527. dictionary_del(tu->dict, dictionary_acquired_item_name(item));
  2528. }
  2529. dictionary_acquired_item_release(tu->dict, item);
  2530. dictionary_del(tu->dict, "dict thread checking 1234567890");
  2531. // test concurrent deletions and flushes
  2532. {
  2533. if(gettid() % 2) {
  2534. char buf [256 + 1];
  2535. for (int i = 0; i < 1000; i++) {
  2536. snprintfz(buf, 256, "del/flush test %d", i);
  2537. dictionary_set(tu->dict, buf, NULL, 0);
  2538. }
  2539. for (int i = 0; i < 1000; i++) {
  2540. snprintfz(buf, 256, "del/flush test %d", i);
  2541. dictionary_del(tu->dict, buf);
  2542. }
  2543. }
  2544. else {
  2545. for (int i = 0; i < 10; i++) {
  2546. dictionary_flush(tu->dict);
  2547. }
  2548. }
  2549. }
  2550. }
  2551. return arg;
  2552. }
  2553. static int dictionary_unittest_threads() {
  2554. struct thread_unittest tu = {
  2555. .join = 0,
  2556. .dict = NULL,
  2557. .dups = 1,
  2558. };
  2559. // threads testing of dictionary
  2560. tu.dict = dictionary_create(DICT_OPTION_DONT_OVERWRITE_VALUE);
  2561. time_t seconds_to_run = 5;
  2562. int threads_to_create = 2;
  2563. fprintf(
  2564. stderr,
  2565. "\nChecking dictionary concurrency with %d threads for %lld seconds...\n",
  2566. threads_to_create,
  2567. (long long)seconds_to_run);
  2568. netdata_thread_t threads[threads_to_create];
  2569. tu.join = 0;
  2570. for (int i = 0; i < threads_to_create; i++) {
  2571. char buf[100 + 1];
  2572. snprintf(buf, 100, "dict%d", i);
  2573. netdata_thread_create(
  2574. &threads[i],
  2575. buf,
  2576. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  2577. unittest_dict_thread,
  2578. &tu);
  2579. }
  2580. sleep_usec(seconds_to_run * USEC_PER_SEC);
  2581. __atomic_store_n(&tu.join, 1, __ATOMIC_RELAXED);
  2582. for (int i = 0; i < threads_to_create; i++) {
  2583. void *retval;
  2584. netdata_thread_join(threads[i], &retval);
  2585. }
  2586. fprintf(stderr,
  2587. "inserts %zu"
  2588. ", deletes %zu"
  2589. ", searches %zu"
  2590. ", resets %zu"
  2591. ", flushes %zu"
  2592. ", entries %ld"
  2593. ", referenced_items %ld"
  2594. ", pending deletions %ld"
  2595. ", check spins %zu"
  2596. ", insert spins %zu"
  2597. ", delete spins %zu"
  2598. ", search ignores %zu"
  2599. "\n",
  2600. tu.dict->stats->ops.inserts,
  2601. tu.dict->stats->ops.deletes,
  2602. tu.dict->stats->ops.searches,
  2603. tu.dict->stats->ops.resets,
  2604. tu.dict->stats->ops.flushes,
  2605. tu.dict->entries,
  2606. tu.dict->referenced_items,
  2607. tu.dict->pending_deletion_items,
  2608. tu.dict->stats->spin_locks.use_spins,
  2609. tu.dict->stats->spin_locks.insert_spins,
  2610. tu.dict->stats->spin_locks.delete_spins,
  2611. tu.dict->stats->spin_locks.search_spins
  2612. );
  2613. dictionary_destroy(tu.dict);
  2614. tu.dict = NULL;
  2615. return 0;
  2616. }
  2617. struct thread_view_unittest {
  2618. int join;
  2619. DICTIONARY *master;
  2620. DICTIONARY *view;
  2621. DICTIONARY_ITEM *item_master;
  2622. int dups;
  2623. };
  2624. static void *unittest_dict_master_thread(void *arg) {
  2625. struct thread_view_unittest *tv = arg;
  2626. DICTIONARY_ITEM *item = NULL;
  2627. int loops = 0;
  2628. while(!__atomic_load_n(&tv->join, __ATOMIC_SEQ_CST)) {
  2629. if(!item)
  2630. item = dictionary_set_and_acquire_item(tv->master, "ITEM1", "123", strlen("123") + 1);
  2631. if(__atomic_load_n(&tv->item_master, __ATOMIC_SEQ_CST) != NULL) {
  2632. dictionary_acquired_item_release(tv->master, item);
  2633. dictionary_del(tv->master, "ITEM1");
  2634. item = NULL;
  2635. loops++;
  2636. continue;
  2637. }
  2638. dictionary_acquired_item_dup(tv->master, item); // for the view thread
  2639. __atomic_store_n(&tv->item_master, item, __ATOMIC_SEQ_CST);
  2640. dictionary_del(tv->master, "ITEM1");
  2641. for(int i = 0; i < tv->dups + loops ; i++) {
  2642. dictionary_acquired_item_dup(tv->master, item);
  2643. }
  2644. for(int i = 0; i < tv->dups + loops ; i++) {
  2645. dictionary_acquired_item_release(tv->master, item);
  2646. }
  2647. dictionary_acquired_item_release(tv->master, item);
  2648. item = NULL;
  2649. loops = 0;
  2650. }
  2651. return arg;
  2652. }
  2653. static void *unittest_dict_view_thread(void *arg) {
  2654. struct thread_view_unittest *tv = arg;
  2655. DICTIONARY_ITEM *m_item = NULL;
  2656. while(!__atomic_load_n(&tv->join, __ATOMIC_SEQ_CST)) {
  2657. if(!(m_item = __atomic_load_n(&tv->item_master, __ATOMIC_SEQ_CST)))
  2658. continue;
  2659. DICTIONARY_ITEM *v_item = dictionary_view_set_and_acquire_item(tv->view, "ITEM2", m_item);
  2660. dictionary_acquired_item_release(tv->master, m_item);
  2661. __atomic_store_n(&tv->item_master, NULL, __ATOMIC_SEQ_CST);
  2662. for(int i = 0; i < tv->dups ; i++) {
  2663. dictionary_acquired_item_dup(tv->view, v_item);
  2664. }
  2665. for(int i = 0; i < tv->dups ; i++) {
  2666. dictionary_acquired_item_release(tv->view, v_item);
  2667. }
  2668. dictionary_del(tv->view, "ITEM2");
  2669. while(!__atomic_load_n(&tv->join, __ATOMIC_SEQ_CST) && !(m_item = __atomic_load_n(&tv->item_master, __ATOMIC_SEQ_CST))) {
  2670. dictionary_acquired_item_dup(tv->view, v_item);
  2671. dictionary_acquired_item_release(tv->view, v_item);
  2672. }
  2673. dictionary_acquired_item_release(tv->view, v_item);
  2674. }
  2675. return arg;
  2676. }
  2677. static int dictionary_unittest_view_threads() {
  2678. struct thread_view_unittest tv = {
  2679. .join = 0,
  2680. .master = NULL,
  2681. .view = NULL,
  2682. .item_master = NULL,
  2683. .dups = 1,
  2684. };
  2685. // threads testing of dictionary
  2686. struct dictionary_stats stats_master = {};
  2687. struct dictionary_stats stats_view = {};
  2688. tv.master = dictionary_create_advanced(DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE, &stats_master, 0);
  2689. tv.view = dictionary_create_view(tv.master);
  2690. tv.view->stats = &stats_view;
  2691. time_t seconds_to_run = 5;
  2692. fprintf(
  2693. stderr,
  2694. "\nChecking dictionary concurrency with 1 master and 1 view threads for %lld seconds...\n",
  2695. (long long)seconds_to_run);
  2696. netdata_thread_t master_thread, view_thread;
  2697. tv.join = 0;
  2698. netdata_thread_create(
  2699. &master_thread,
  2700. "master",
  2701. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  2702. unittest_dict_master_thread,
  2703. &tv);
  2704. netdata_thread_create(
  2705. &view_thread,
  2706. "view",
  2707. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  2708. unittest_dict_view_thread,
  2709. &tv);
  2710. sleep_usec(seconds_to_run * USEC_PER_SEC);
  2711. __atomic_store_n(&tv.join, 1, __ATOMIC_RELAXED);
  2712. void *retval;
  2713. netdata_thread_join(view_thread, &retval);
  2714. netdata_thread_join(master_thread, &retval);
  2715. fprintf(stderr,
  2716. "MASTER: inserts %zu"
  2717. ", deletes %zu"
  2718. ", searches %zu"
  2719. ", resets %zu"
  2720. ", entries %ld"
  2721. ", referenced_items %ld"
  2722. ", pending deletions %ld"
  2723. ", check spins %zu"
  2724. ", insert spins %zu"
  2725. ", delete spins %zu"
  2726. ", search ignores %zu"
  2727. "\n",
  2728. stats_master.ops.inserts,
  2729. stats_master.ops.deletes,
  2730. stats_master.ops.searches,
  2731. stats_master.ops.resets,
  2732. tv.master->entries,
  2733. tv.master->referenced_items,
  2734. tv.master->pending_deletion_items,
  2735. stats_master.spin_locks.use_spins,
  2736. stats_master.spin_locks.insert_spins,
  2737. stats_master.spin_locks.delete_spins,
  2738. stats_master.spin_locks.search_spins
  2739. );
  2740. fprintf(stderr,
  2741. "VIEW : inserts %zu"
  2742. ", deletes %zu"
  2743. ", searches %zu"
  2744. ", resets %zu"
  2745. ", entries %ld"
  2746. ", referenced_items %ld"
  2747. ", pending deletions %ld"
  2748. ", check spins %zu"
  2749. ", insert spins %zu"
  2750. ", delete spins %zu"
  2751. ", search ignores %zu"
  2752. "\n",
  2753. stats_view.ops.inserts,
  2754. stats_view.ops.deletes,
  2755. stats_view.ops.searches,
  2756. stats_view.ops.resets,
  2757. tv.view->entries,
  2758. tv.view->referenced_items,
  2759. tv.view->pending_deletion_items,
  2760. stats_view.spin_locks.use_spins,
  2761. stats_view.spin_locks.insert_spins,
  2762. stats_view.spin_locks.delete_spins,
  2763. stats_view.spin_locks.search_spins
  2764. );
  2765. dictionary_destroy(tv.master);
  2766. dictionary_destroy(tv.view);
  2767. return 0;
  2768. }
  2769. size_t dictionary_unittest_views(void) {
  2770. size_t errors = 0;
  2771. struct dictionary_stats stats = {};
  2772. DICTIONARY *master = dictionary_create_advanced(DICT_OPTION_NONE, &stats, 0);
  2773. DICTIONARY *view = dictionary_create_view(master);
  2774. fprintf(stderr, "\n\nChecking dictionary views...\n");
  2775. // Add an item to both master and view, then remove the view first and the master second
  2776. fprintf(stderr, "\nPASS 1: Adding 1 item to master:\n");
  2777. DICTIONARY_ITEM *item1_on_master = dictionary_set_and_acquire_item(master, "KEY 1", "VALUE1", strlen("VALUE1") + 1);
  2778. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2779. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2780. fprintf(stderr, "\nPASS 1: Adding master item to view:\n");
  2781. DICTIONARY_ITEM *item1_on_view = dictionary_view_set_and_acquire_item(view, "KEY 1 ON VIEW", item1_on_master);
  2782. errors += unittest_check_dictionary("view", view, 1, 1, 0, 1, 0);
  2783. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2784. fprintf(stderr, "\nPASS 1: Deleting view item:\n");
  2785. dictionary_del(view, "KEY 1 ON VIEW");
  2786. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2787. errors += unittest_check_dictionary("view", view, 0, 0, 1, 1, 0);
  2788. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2789. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2790. fprintf(stderr, "\nPASS 1: Releasing the deleted view item:\n");
  2791. dictionary_acquired_item_release(view, item1_on_view);
  2792. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2793. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2794. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2795. fprintf(stderr, "\nPASS 1: Releasing the acquired master item:\n");
  2796. dictionary_acquired_item_release(master, item1_on_master);
  2797. errors += unittest_check_dictionary("master", master, 1, 1, 0, 0, 0);
  2798. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2799. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 0, ITEM_FLAG_NONE, true, true, true);
  2800. fprintf(stderr, "\nPASS 1: Deleting the released master item:\n");
  2801. dictionary_del(master, "KEY 1");
  2802. errors += unittest_check_dictionary("master", master, 0, 0, 0, 0, 0);
  2803. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2804. // The other way now:
  2805. // Add an item to both master and view, then remove the master first and verify it is deleted on the view also
  2806. fprintf(stderr, "\nPASS 2: Adding 1 item to master:\n");
  2807. item1_on_master = dictionary_set_and_acquire_item(master, "KEY 1", "VALUE1", strlen("VALUE1") + 1);
  2808. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2809. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2810. fprintf(stderr, "\nPASS 2: Adding master item to view:\n");
  2811. item1_on_view = dictionary_view_set_and_acquire_item(view, "KEY 1 ON VIEW", item1_on_master);
  2812. errors += unittest_check_dictionary("view", view, 1, 1, 0, 1, 0);
  2813. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2814. fprintf(stderr, "\nPASS 2: Deleting master item:\n");
  2815. dictionary_del(master, "KEY 1");
  2816. dictionary_version(view);
  2817. errors += unittest_check_dictionary("master", master, 0, 0, 1, 1, 0);
  2818. errors += unittest_check_dictionary("view", view, 0, 0, 1, 1, 0);
  2819. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2820. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2821. fprintf(stderr, "\nPASS 2: Releasing the acquired master item:\n");
  2822. dictionary_acquired_item_release(master, item1_on_master);
  2823. errors += unittest_check_dictionary("master", master, 0, 0, 1, 0, 1);
  2824. errors += unittest_check_dictionary("view", view, 0, 0, 1, 1, 0);
  2825. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2826. fprintf(stderr, "\nPASS 2: Releasing the deleted view item:\n");
  2827. dictionary_acquired_item_release(view, item1_on_view);
  2828. errors += unittest_check_dictionary("master", master, 0, 0, 1, 0, 1);
  2829. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2830. dictionary_destroy(master);
  2831. dictionary_destroy(view);
  2832. return errors;
  2833. }
  2834. int dictionary_unittest(size_t entries) {
  2835. if(entries < 10) entries = 10;
  2836. DICTIONARY *dict;
  2837. size_t errors = 0;
  2838. fprintf(stderr, "Generating %zu names and values...\n", entries);
  2839. char **names = dictionary_unittest_generate_names(entries);
  2840. char **values = dictionary_unittest_generate_values(entries);
  2841. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  2842. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  2843. dictionary_unittest_clone(dict, names, values, entries, &errors);
  2844. fprintf(stderr, "\nCreating dictionary multi threaded, clone, %zu items\n", entries);
  2845. dict = dictionary_create(DICT_OPTION_NONE);
  2846. dictionary_unittest_clone(dict, names, values, entries, &errors);
  2847. fprintf(stderr, "\nCreating dictionary single threaded, non-clone, add-in-front options, %zu items\n", entries);
  2848. dict = dictionary_create(
  2849. DICT_OPTION_SINGLE_THREADED | DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE |
  2850. DICT_OPTION_ADD_IN_FRONT);
  2851. dictionary_unittest_nonclone(dict, names, values, entries, &errors);
  2852. fprintf(stderr, "\nCreating dictionary multi threaded, non-clone, add-in-front options, %zu items\n", entries);
  2853. dict = dictionary_create(
  2854. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_ADD_IN_FRONT);
  2855. dictionary_unittest_nonclone(dict, names, values, entries, &errors);
  2856. fprintf(stderr, "\nCreating dictionary single-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  2857. dict = dictionary_create(
  2858. DICT_OPTION_SINGLE_THREADED | DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE |
  2859. DICT_OPTION_DONT_OVERWRITE_VALUE);
  2860. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  2861. dictionary_unittest_run_and_measure_time(dict, "resetting non-overwrite entries", names, values, entries, &errors, dictionary_unittest_reset_dont_overwrite_nonclone);
  2862. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, &errors, dictionary_unittest_foreach);
  2863. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, &errors, dictionary_unittest_walkthrough);
  2864. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, &errors, dictionary_unittest_walkthrough_stop);
  2865. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2866. fprintf(stderr, "\nCreating dictionary multi-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  2867. dict = dictionary_create(
  2868. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE);
  2869. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  2870. dictionary_unittest_run_and_measure_time(dict, "walkthrough write delete this", names, values, entries, &errors, dictionary_unittest_walkthrough_delete_this);
  2871. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2872. fprintf(stderr, "\nCreating dictionary multi-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  2873. dict = dictionary_create(
  2874. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE);
  2875. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  2876. dictionary_unittest_run_and_measure_time(dict, "foreach write delete this", names, values, entries, &errors, dictionary_unittest_foreach_delete_this);
  2877. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop empty", names, values, 0, &errors, dictionary_unittest_foreach);
  2878. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback empty", names, values, 0, &errors, dictionary_unittest_walkthrough);
  2879. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2880. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  2881. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  2882. dictionary_unittest_sorting(dict, names, values, entries, &errors);
  2883. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2884. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  2885. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  2886. dictionary_unittest_null_dfe(dict, names, values, entries, &errors);
  2887. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2888. fprintf(stderr, "\nCreating dictionary single threaded, noclone, %zu items\n", entries);
  2889. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED | DICT_OPTION_VALUE_LINK_DONT_CLONE);
  2890. dictionary_unittest_null_dfe(dict, names, values, entries, &errors);
  2891. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2892. // check reference counters
  2893. {
  2894. fprintf(stderr, "\nTesting reference counters:\n");
  2895. dict = dictionary_create(DICT_OPTION_NONE | DICT_OPTION_NAME_LINK_DONT_CLONE);
  2896. errors += unittest_check_dictionary("", dict, 0, 0, 0, 0, 0);
  2897. fprintf(stderr, "\nAdding test item to dictionary and acquiring it\n");
  2898. dictionary_set(dict, "test", "ITEM1", 6);
  2899. DICTIONARY_ITEM *item = (DICTIONARY_ITEM *)dictionary_get_and_acquire_item(dict, "test");
  2900. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2901. errors += unittest_check_item("ACQUIRED", dict, item, "test", "ITEM1", 1, ITEM_FLAG_NONE, true, true, true);
  2902. fprintf(stderr, "\nChecking that reference counters are increased:\n");
  2903. void *t;
  2904. dfe_start_read(dict, t) {
  2905. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2906. errors += unittest_check_item("ACQUIRED TRAVERSAL", dict, item, "test", "ITEM1", 2, ITEM_FLAG_NONE, true, true, true);
  2907. }
  2908. dfe_done(t);
  2909. fprintf(stderr, "\nChecking that reference counters are decreased:\n");
  2910. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2911. errors += unittest_check_item("ACQUIRED TRAVERSAL 2", dict, item, "test", "ITEM1", 1, ITEM_FLAG_NONE, true, true, true);
  2912. fprintf(stderr, "\nDeleting the item we have acquired:\n");
  2913. dictionary_del(dict, "test");
  2914. errors += unittest_check_dictionary("", dict, 0, 0, 1, 1, 0);
  2915. errors += unittest_check_item("DELETED", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  2916. fprintf(stderr, "\nAdding another item with the same name of the item we deleted, while being acquired:\n");
  2917. dictionary_set(dict, "test", "ITEM2", 6);
  2918. errors += unittest_check_dictionary("", dict, 1, 1, 1, 1, 0);
  2919. fprintf(stderr, "\nAcquiring the second item:\n");
  2920. DICTIONARY_ITEM *item2 = (DICTIONARY_ITEM *)dictionary_get_and_acquire_item(dict, "test");
  2921. errors += unittest_check_item("FIRST", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  2922. errors += unittest_check_item("SECOND", dict, item2, "test", "ITEM2", 1, ITEM_FLAG_NONE, true, true, true);
  2923. errors += unittest_check_dictionary("", dict, 1, 1, 1, 2, 0);
  2924. fprintf(stderr, "\nReleasing the second item (the first is still acquired):\n");
  2925. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)item2);
  2926. errors += unittest_check_dictionary("", dict, 1, 1, 1, 1, 0);
  2927. errors += unittest_check_item("FIRST", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  2928. errors += unittest_check_item("SECOND RELEASED", dict, item2, "test", "ITEM2", 0, ITEM_FLAG_NONE, true, true, true);
  2929. fprintf(stderr, "\nDeleting the second item (the first is still acquired):\n");
  2930. dictionary_del(dict, "test");
  2931. errors += unittest_check_dictionary("", dict, 0, 0, 1, 1, 0);
  2932. errors += unittest_check_item("ACQUIRED DELETED", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  2933. fprintf(stderr, "\nReleasing the first item (which we have already deleted):\n");
  2934. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)item);
  2935. dfe_start_write(dict, item) ; dfe_done(item);
  2936. errors += unittest_check_dictionary("", dict, 0, 0, 1, 0, 1);
  2937. fprintf(stderr, "\nAdding again the test item to dictionary and acquiring it\n");
  2938. dictionary_set(dict, "test", "ITEM1", 6);
  2939. item = (DICTIONARY_ITEM *)dictionary_get_and_acquire_item(dict, "test");
  2940. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2941. errors += unittest_check_item("RE-ADDITION", dict, item, "test", "ITEM1", 1, ITEM_FLAG_NONE, true, true, true);
  2942. fprintf(stderr, "\nDestroying the dictionary while we have acquired an item\n");
  2943. dictionary_destroy(dict);
  2944. fprintf(stderr, "Releasing the item (on a destroyed dictionary)\n");
  2945. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)item);
  2946. item = NULL;
  2947. dict = NULL;
  2948. }
  2949. dictionary_unittest_free_char_pp(names, entries);
  2950. dictionary_unittest_free_char_pp(values, entries);
  2951. errors += dictionary_unittest_views();
  2952. errors += dictionary_unittest_threads();
  2953. errors += dictionary_unittest_view_threads();
  2954. fprintf(stderr, "\n%zu errors found\n", errors);
  2955. return errors ? 1 : 0;
  2956. }