dictionary.c 138 KB

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