dictionary.c 142 KB

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