dictionary.c 86 KB

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