res_sorcery_memory_cache.c 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2015, Digium, Inc.
  5. *
  6. * Joshua Colp <jcolp@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*!
  19. * \file
  20. *
  21. * \brief Sorcery Memory Cache Object Wizard
  22. *
  23. * \author Joshua Colp <jcolp@digium.com>
  24. */
  25. /*** MODULEINFO
  26. <support_level>core</support_level>
  27. ***/
  28. #include "asterisk.h"
  29. #include "asterisk/module.h"
  30. #include "asterisk/sorcery.h"
  31. #include "asterisk/astobj2.h"
  32. #include "asterisk/sched.h"
  33. #include "asterisk/test.h"
  34. #include "asterisk/heap.h"
  35. #include "asterisk/cli.h"
  36. #include "asterisk/manager.h"
  37. /*** DOCUMENTATION
  38. <manager name="SorceryMemoryCacheExpireObject" language="en_US">
  39. <synopsis>
  40. Expire (remove) an object from a sorcery memory cache.
  41. </synopsis>
  42. <syntax>
  43. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  44. <parameter name="Cache" required="true">
  45. <para>The name of the cache to expire the object from.</para>
  46. </parameter>
  47. <parameter name="Object" required="true">
  48. <para>The name of the object to expire.</para>
  49. </parameter>
  50. </syntax>
  51. <description>
  52. <para>Expires (removes) an object from a sorcery memory cache.</para>
  53. </description>
  54. </manager>
  55. <manager name="SorceryMemoryCacheExpire" language="en_US">
  56. <synopsis>
  57. Expire (remove) ALL objects from a sorcery memory cache.
  58. </synopsis>
  59. <syntax>
  60. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  61. <parameter name="Cache" required="true">
  62. <para>The name of the cache to expire all objects from.</para>
  63. </parameter>
  64. </syntax>
  65. <description>
  66. <para>Expires (removes) ALL objects from a sorcery memory cache.</para>
  67. </description>
  68. </manager>
  69. <manager name="SorceryMemoryCacheStaleObject" language="en_US">
  70. <synopsis>
  71. Mark an object in a sorcery memory cache as stale.
  72. </synopsis>
  73. <syntax>
  74. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  75. <parameter name="Cache" required="true">
  76. <para>The name of the cache to mark the object as stale in.</para>
  77. </parameter>
  78. <parameter name="Object" required="true">
  79. <para>The name of the object to mark as stale.</para>
  80. </parameter>
  81. <parameter name="Reload" required="false">
  82. <para>If true, then immediately reload the object from the backend cache instead of waiting for the next retrieval</para>
  83. </parameter>
  84. </syntax>
  85. <description>
  86. <para>Marks an object as stale within a sorcery memory cache.</para>
  87. </description>
  88. </manager>
  89. <manager name="SorceryMemoryCacheStale" language="en_US">
  90. <synopsis>
  91. Marks ALL objects in a sorcery memory cache as stale.
  92. </synopsis>
  93. <syntax>
  94. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  95. <parameter name="Cache" required="true">
  96. <para>The name of the cache to mark all object as stale in.</para>
  97. </parameter>
  98. </syntax>
  99. <description>
  100. <para>Marks ALL objects in a sorcery memory cache as stale.</para>
  101. </description>
  102. </manager>
  103. <manager name="SorceryMemoryCachePopulate" language="en_US">
  104. <synopsis>
  105. Expire all objects from a memory cache and populate it with all objects from the backend.
  106. </synopsis>
  107. <syntax>
  108. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  109. <parameter name="Cache" required="true">
  110. <para>The name of the cache to populate.</para>
  111. </parameter>
  112. </syntax>
  113. <description>
  114. <para>Expires all objects from a memory cache and populate it with all objects from the backend.</para>
  115. </description>
  116. </manager>
  117. ***/
  118. /*! \brief Structure for storing a memory cache */
  119. struct sorcery_memory_cache {
  120. /*! \brief The name of the memory cache */
  121. char *name;
  122. /*! \brief Objects in the cache */
  123. struct ao2_container *objects;
  124. /*! \brief The maximum number of objects permitted in the cache, 0 if no limit */
  125. unsigned int maximum_objects;
  126. /*! \brief The maximum time (in seconds) an object will stay in the cache, 0 if no limit */
  127. unsigned int object_lifetime_maximum;
  128. /*! \brief The amount of time (in seconds) before an object is marked as stale, 0 if disabled */
  129. unsigned int object_lifetime_stale;
  130. /*! \brief Whether all objects are expired when the object type is reloaded, 0 if disabled */
  131. unsigned int expire_on_reload;
  132. /*! \brief Whether this is a cache of the entire backend, 0 if disabled */
  133. unsigned int full_backend_cache;
  134. /*! \brief Heap of cached objects. Oldest object is at the top. */
  135. struct ast_heap *object_heap;
  136. /*! \brief Scheduler item for expiring oldest object. */
  137. int expire_id;
  138. /*! \brief scheduler id of stale update task */
  139. int stale_update_sched_id;
  140. /*! \brief An unreffed pointer to the sorcery instance, accessible only with lock held */
  141. const struct ast_sorcery *sorcery;
  142. /*! \brief The type of object we are caching */
  143. char *object_type;
  144. /*! TRUE if trying to stop the oldest object expiration scheduler item. */
  145. unsigned int del_expire:1;
  146. #ifdef TEST_FRAMEWORK
  147. /*! \brief Variable used to indicate we should notify a test when we reach empty */
  148. unsigned int cache_notify;
  149. /*! \brief Mutex lock used for signaling when the cache has reached empty */
  150. ast_mutex_t lock;
  151. /*! \brief Condition used for signaling when the cache has reached empty */
  152. ast_cond_t cond;
  153. /*! \brief Variable that is set when the cache has reached empty */
  154. unsigned int cache_completed;
  155. #endif
  156. };
  157. /*! \brief Structure for stored a cached object */
  158. struct sorcery_memory_cached_object {
  159. /*! \brief The cached object */
  160. void *object;
  161. /*! \brief The time at which the object was created */
  162. struct timeval created;
  163. /*! \brief index required by heap */
  164. ssize_t __heap_index;
  165. /*! \brief scheduler id of stale update task */
  166. int stale_update_sched_id;
  167. /*! \brief Cached objectset for field and regex retrieval */
  168. struct ast_variable *objectset;
  169. };
  170. /*! \brief Structure used for fields comparison */
  171. struct sorcery_memory_cache_fields_cmp_params {
  172. /*! \brief Pointer to the sorcery structure */
  173. const struct ast_sorcery *sorcery;
  174. /*! \brief The sorcery memory cache */
  175. struct sorcery_memory_cache *cache;
  176. /*! \brief Pointer to the fields to check */
  177. const struct ast_variable *fields;
  178. /*! \brief Regular expression for checking object id */
  179. regex_t *regex;
  180. /*! \brief Prefix for matching object id */
  181. const char *prefix;
  182. /*! \brief Prefix length in bytes for matching object id */
  183. const size_t prefix_len;
  184. /*! \brief Optional container to put object into */
  185. struct ao2_container *container;
  186. };
  187. static void *sorcery_memory_cache_open(const char *data);
  188. static int sorcery_memory_cache_create(const struct ast_sorcery *sorcery, void *data, void *object);
  189. static void sorcery_memory_cache_load(void *data, const struct ast_sorcery *sorcery, const char *type);
  190. static void sorcery_memory_cache_reload(void *data, const struct ast_sorcery *sorcery, const char *type);
  191. static void *sorcery_memory_cache_retrieve_id(const struct ast_sorcery *sorcery, void *data, const char *type,
  192. const char *id);
  193. static void *sorcery_memory_cache_retrieve_fields(const struct ast_sorcery *sorcery, void *data, const char *type,
  194. const struct ast_variable *fields);
  195. static void sorcery_memory_cache_retrieve_multiple(const struct ast_sorcery *sorcery, void *data, const char *type,
  196. struct ao2_container *objects, const struct ast_variable *fields);
  197. static void sorcery_memory_cache_retrieve_regex(const struct ast_sorcery *sorcery, void *data, const char *type,
  198. struct ao2_container *objects, const char *regex);
  199. static void sorcery_memory_cache_retrieve_prefix(const struct ast_sorcery *sorcery, void *data, const char *type,
  200. struct ao2_container *objects, const char *prefix, const size_t prefix_len);
  201. static int sorcery_memory_cache_delete(const struct ast_sorcery *sorcery, void *data, void *object);
  202. static void sorcery_memory_cache_close(void *data);
  203. static struct ast_sorcery_wizard memory_cache_object_wizard = {
  204. .name = "memory_cache",
  205. .open = sorcery_memory_cache_open,
  206. .create = sorcery_memory_cache_create,
  207. .update = sorcery_memory_cache_create,
  208. .delete = sorcery_memory_cache_delete,
  209. .load = sorcery_memory_cache_load,
  210. .reload = sorcery_memory_cache_reload,
  211. .retrieve_id = sorcery_memory_cache_retrieve_id,
  212. .retrieve_fields = sorcery_memory_cache_retrieve_fields,
  213. .retrieve_multiple = sorcery_memory_cache_retrieve_multiple,
  214. .retrieve_regex = sorcery_memory_cache_retrieve_regex,
  215. .retrieve_prefix = sorcery_memory_cache_retrieve_prefix,
  216. .close = sorcery_memory_cache_close,
  217. };
  218. /*! \brief The bucket size for the container of caches */
  219. #define CACHES_CONTAINER_BUCKET_SIZE 53
  220. /*! \brief The default bucket size for the container of objects in the cache */
  221. #define CACHE_CONTAINER_BUCKET_SIZE 53
  222. /*! \brief Height of heap for cache object heap. Allows 31 initial objects */
  223. #define CACHE_HEAP_INIT_HEIGHT 5
  224. /*! \brief Container of created caches */
  225. static struct ao2_container *caches;
  226. /*! \brief Scheduler for cache management */
  227. static struct ast_sched_context *sched;
  228. #define PASSTHRU_UPDATE_THREAD_ID 0x5EED1E55
  229. AST_THREADSTORAGE(passthru_update_id_storage);
  230. static int is_passthru_update(void)
  231. {
  232. uint32_t *passthru_update_thread_id;
  233. passthru_update_thread_id = ast_threadstorage_get(&passthru_update_id_storage,
  234. sizeof(*passthru_update_thread_id));
  235. if (!passthru_update_thread_id) {
  236. return 0;
  237. }
  238. return *passthru_update_thread_id == PASSTHRU_UPDATE_THREAD_ID;
  239. }
  240. static void set_passthru_update(uint32_t value)
  241. {
  242. uint32_t *passthru_update_thread_id;
  243. passthru_update_thread_id = ast_threadstorage_get(&passthru_update_id_storage,
  244. sizeof(*passthru_update_thread_id));
  245. if (!passthru_update_thread_id) {
  246. ast_log(LOG_ERROR, "Could not set passthru update ID for sorcery memory cache thread\n");
  247. return;
  248. }
  249. *passthru_update_thread_id = value;
  250. }
  251. static void start_passthru_update(void)
  252. {
  253. set_passthru_update(PASSTHRU_UPDATE_THREAD_ID);
  254. }
  255. static void end_passthru_update(void)
  256. {
  257. set_passthru_update(0);
  258. }
  259. /*!
  260. * \internal
  261. * \brief Hashing function for the container holding caches
  262. *
  263. * \param obj A sorcery memory cache or name of one
  264. * \param flags Hashing flags
  265. *
  266. * \return The hash of the memory cache name
  267. */
  268. static int sorcery_memory_cache_hash(const void *obj, int flags)
  269. {
  270. const struct sorcery_memory_cache *cache = obj;
  271. const char *name = obj;
  272. int hash;
  273. switch (flags & OBJ_SEARCH_MASK) {
  274. default:
  275. case OBJ_SEARCH_OBJECT:
  276. name = cache->name;
  277. /* Fall through */
  278. case OBJ_SEARCH_KEY:
  279. hash = ast_str_hash(name);
  280. break;
  281. case OBJ_SEARCH_PARTIAL_KEY:
  282. /* Should never happen in hash callback. */
  283. ast_assert(0);
  284. hash = 0;
  285. break;
  286. }
  287. return hash;
  288. }
  289. /*!
  290. * \internal
  291. * \brief Comparison function for the container holding caches
  292. *
  293. * \param obj A sorcery memory cache
  294. * \param arg A sorcery memory cache, or name of one
  295. * \param flags Comparison flags
  296. *
  297. * \retval CMP_MATCH if the name is the same
  298. * \retval 0 if the name does not match
  299. */
  300. static int sorcery_memory_cache_cmp(void *obj, void *arg, int flags)
  301. {
  302. const struct sorcery_memory_cache *left = obj;
  303. const struct sorcery_memory_cache *right = arg;
  304. const char *right_name = arg;
  305. int cmp;
  306. switch (flags & OBJ_SEARCH_MASK) {
  307. default:
  308. case OBJ_SEARCH_OBJECT:
  309. right_name = right->name;
  310. /* Fall through */
  311. case OBJ_SEARCH_KEY:
  312. cmp = strcmp(left->name, right_name);
  313. break;
  314. case OBJ_SEARCH_PARTIAL_KEY:
  315. cmp = strncmp(left->name, right_name, strlen(right_name));
  316. break;
  317. }
  318. return cmp ? 0 : CMP_MATCH;
  319. }
  320. /*!
  321. * \internal
  322. * \brief Hashing function for the container holding cached objects
  323. *
  324. * \param obj A cached object or id of one
  325. * \param flags Hashing flags
  326. *
  327. * \return The hash of the cached object id
  328. */
  329. static int sorcery_memory_cached_object_hash(const void *obj, int flags)
  330. {
  331. const struct sorcery_memory_cached_object *cached = obj;
  332. const char *name = obj;
  333. int hash;
  334. switch (flags & OBJ_SEARCH_MASK) {
  335. default:
  336. case OBJ_SEARCH_OBJECT:
  337. name = ast_sorcery_object_get_id(cached->object);
  338. /* Fall through */
  339. case OBJ_SEARCH_KEY:
  340. hash = ast_str_hash(name);
  341. break;
  342. case OBJ_SEARCH_PARTIAL_KEY:
  343. /* Should never happen in hash callback. */
  344. ast_assert(0);
  345. hash = 0;
  346. break;
  347. }
  348. return hash;
  349. }
  350. /*!
  351. * \internal
  352. * \brief Comparison function for the container holding cached objects
  353. *
  354. * \param obj A cached object
  355. * \param arg A cached object, or id of one
  356. * \param flags Comparison flags
  357. *
  358. * \retval CMP_MATCH if the id is the same
  359. * \retval 0 if the id does not match
  360. */
  361. static int sorcery_memory_cached_object_cmp(void *obj, void *arg, int flags)
  362. {
  363. struct sorcery_memory_cached_object *left = obj;
  364. struct sorcery_memory_cached_object *right = arg;
  365. const char *right_name = arg;
  366. int cmp;
  367. switch (flags & OBJ_SEARCH_MASK) {
  368. default:
  369. case OBJ_SEARCH_OBJECT:
  370. right_name = ast_sorcery_object_get_id(right->object);
  371. /* Fall through */
  372. case OBJ_SEARCH_KEY:
  373. cmp = strcmp(ast_sorcery_object_get_id(left->object), right_name);
  374. break;
  375. case OBJ_SEARCH_PARTIAL_KEY:
  376. cmp = strncmp(ast_sorcery_object_get_id(left->object), right_name, strlen(right_name));
  377. break;
  378. }
  379. return cmp ? 0 : CMP_MATCH;
  380. }
  381. /*!
  382. * \internal
  383. * \brief Destructor function for a sorcery memory cache
  384. *
  385. * \param obj A sorcery memory cache
  386. */
  387. static void sorcery_memory_cache_destructor(void *obj)
  388. {
  389. struct sorcery_memory_cache *cache = obj;
  390. ast_free(cache->name);
  391. if (cache->object_heap) {
  392. ast_heap_destroy(cache->object_heap);
  393. }
  394. ao2_cleanup(cache->objects);
  395. ast_free(cache->object_type);
  396. }
  397. /*!
  398. * \internal
  399. * \brief Destructor function for sorcery memory cached objects
  400. *
  401. * \param obj A sorcery memory cached object
  402. */
  403. static void sorcery_memory_cached_object_destructor(void *obj)
  404. {
  405. struct sorcery_memory_cached_object *cached = obj;
  406. ao2_cleanup(cached->object);
  407. ast_variables_destroy(cached->objectset);
  408. }
  409. static int schedule_cache_expiration(struct sorcery_memory_cache *cache);
  410. /*!
  411. * \internal
  412. * \brief Remove an object from the cache.
  413. *
  414. * This removes the item from both the hashtable and the heap.
  415. *
  416. * \pre cache->objects is write-locked
  417. *
  418. * \param cache The cache from which the object is being removed.
  419. * \param id The sorcery object id of the object to remove.
  420. * \param reschedule Reschedule cache expiration if this was the oldest object.
  421. *
  422. * \retval 0 Success
  423. * \retval non-zero Failure
  424. */
  425. static int remove_from_cache(struct sorcery_memory_cache *cache, const char *id, int reschedule)
  426. {
  427. struct sorcery_memory_cached_object *hash_object;
  428. struct sorcery_memory_cached_object *oldest_object;
  429. struct sorcery_memory_cached_object *heap_object;
  430. hash_object = ao2_find(cache->objects, id, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NOLOCK);
  431. if (!hash_object) {
  432. return -1;
  433. }
  434. ast_assert(!strcmp(ast_sorcery_object_get_id(hash_object->object), id));
  435. oldest_object = ast_heap_peek(cache->object_heap, 1);
  436. heap_object = ast_heap_remove(cache->object_heap, hash_object);
  437. ast_assert(heap_object == hash_object);
  438. ao2_ref(hash_object, -1);
  439. if (reschedule && (oldest_object == heap_object)) {
  440. schedule_cache_expiration(cache);
  441. }
  442. return 0;
  443. }
  444. /*!
  445. * \internal
  446. * \brief Scheduler callback invoked to expire old objects
  447. *
  448. * \param data The opaque callback data (in our case, the memory cache)
  449. */
  450. static int expire_objects_from_cache(const void *data)
  451. {
  452. struct sorcery_memory_cache *cache = (struct sorcery_memory_cache *)data;
  453. struct sorcery_memory_cached_object *cached;
  454. /*
  455. * We need to do deadlock avoidance between a non-scheduler thread
  456. * blocking when trying to delete the scheduled entry for this
  457. * callback because the scheduler thread is running this callback
  458. * and this callback waiting for the cache->objects container lock
  459. * that the blocked non-scheduler thread already holds.
  460. */
  461. while (ao2_trywrlock(cache->objects)) {
  462. if (cache->del_expire) {
  463. cache->expire_id = -1;
  464. ao2_ref(cache, -1);
  465. return 0;
  466. }
  467. sched_yield();
  468. }
  469. cache->expire_id = -1;
  470. /* This is an optimization for objects which have been cached close to each other */
  471. while ((cached = ast_heap_peek(cache->object_heap, 1))) {
  472. int expiration;
  473. expiration = ast_tvdiff_ms(ast_tvadd(cached->created, ast_samp2tv(cache->object_lifetime_maximum, 1)), ast_tvnow());
  474. /* If the current oldest object has not yet expired stop and reschedule for it */
  475. if (expiration > 0) {
  476. break;
  477. }
  478. remove_from_cache(cache, ast_sorcery_object_get_id(cached->object), 0);
  479. }
  480. schedule_cache_expiration(cache);
  481. ao2_unlock(cache->objects);
  482. ao2_ref(cache, -1);
  483. return 0;
  484. }
  485. /*!
  486. * \internal
  487. * \brief Remove all objects from the cache.
  488. *
  489. * This removes ALL objects from both the hash table and heap.
  490. *
  491. * \pre cache->objects is write-locked
  492. *
  493. * \param cache The cache to empty.
  494. */
  495. static void remove_all_from_cache(struct sorcery_memory_cache *cache)
  496. {
  497. while (ast_heap_pop(cache->object_heap)) {
  498. }
  499. ao2_callback(cache->objects, OBJ_UNLINK | OBJ_NOLOCK | OBJ_NODATA | OBJ_MULTIPLE,
  500. NULL, NULL);
  501. cache->del_expire = 1;
  502. AST_SCHED_DEL_UNREF(sched, cache->expire_id, ao2_ref(cache, -1));
  503. cache->del_expire = 0;
  504. }
  505. /*!
  506. * \internal
  507. * \brief AO2 callback function for making an object stale immediately
  508. *
  509. * This changes the creation time of an object so it appears as though it is stale immediately.
  510. *
  511. * \param obj The cached object
  512. * \param arg The cache itself
  513. * \param flags Unused flags
  514. */
  515. static int object_stale_callback(void *obj, void *arg, int flags)
  516. {
  517. struct sorcery_memory_cached_object *cached = obj;
  518. struct sorcery_memory_cache *cache = arg;
  519. /* Since our granularity is seconds it's possible for something to retrieve us within a window
  520. * where we wouldn't be treated as stale. To ensure that doesn't happen we use the configured stale
  521. * time plus a second.
  522. */
  523. cached->created = ast_tvsub(cached->created, ast_samp2tv(cache->object_lifetime_stale + 1, 1));
  524. return CMP_MATCH;
  525. }
  526. /*!
  527. * \internal
  528. * \brief Mark an object as stale explicitly.
  529. *
  530. * This changes the creation time of an object so it appears as though it is stale immediately.
  531. *
  532. * \pre cache->objects is read-locked
  533. *
  534. * \param cache The cache the object is in
  535. * \param id The unique identifier of the object
  536. *
  537. * \retval 0 success
  538. * \retval -1 failure
  539. */
  540. static int mark_object_as_stale_in_cache(struct sorcery_memory_cache *cache, const char *id)
  541. {
  542. struct sorcery_memory_cached_object *cached;
  543. cached = ao2_find(cache->objects, id, OBJ_SEARCH_KEY | OBJ_NOLOCK);
  544. if (!cached) {
  545. return -1;
  546. }
  547. ast_assert(!strcmp(ast_sorcery_object_get_id(cached->object), id));
  548. object_stale_callback(cached, cache, 0);
  549. ao2_ref(cached, -1);
  550. return 0;
  551. }
  552. /*!
  553. * \internal
  554. * \brief Mark all objects as stale within a cache.
  555. *
  556. * This changes the creation time of ALL objects so they appear as though they are stale.
  557. *
  558. * \pre cache->objects is read-locked
  559. *
  560. * \param cache
  561. */
  562. static void mark_all_as_stale_in_cache(struct sorcery_memory_cache *cache)
  563. {
  564. ao2_callback(cache->objects, OBJ_NOLOCK | OBJ_NODATA | OBJ_MULTIPLE, object_stale_callback, cache);
  565. }
  566. /*!
  567. * \internal
  568. * \brief Schedule a callback for cached object expiration.
  569. *
  570. * \pre cache->objects is write-locked
  571. *
  572. * \param cache The cache that is having its callback scheduled.
  573. *
  574. * \retval 0 success
  575. * \retval -1 failure
  576. */
  577. static int schedule_cache_expiration(struct sorcery_memory_cache *cache)
  578. {
  579. struct sorcery_memory_cached_object *cached;
  580. int expiration = 0;
  581. if (!cache->object_lifetime_maximum) {
  582. return 0;
  583. }
  584. cache->del_expire = 1;
  585. AST_SCHED_DEL_UNREF(sched, cache->expire_id, ao2_ref(cache, -1));
  586. cache->del_expire = 0;
  587. cached = ast_heap_peek(cache->object_heap, 1);
  588. if (!cached) {
  589. #ifdef TEST_FRAMEWORK
  590. ast_mutex_lock(&cache->lock);
  591. cache->cache_completed = 1;
  592. ast_cond_signal(&cache->cond);
  593. ast_mutex_unlock(&cache->lock);
  594. #endif
  595. return 0;
  596. }
  597. expiration = MAX(ast_tvdiff_ms(ast_tvadd(cached->created, ast_samp2tv(cache->object_lifetime_maximum, 1)), ast_tvnow()),
  598. 1);
  599. cache->expire_id = ast_sched_add(sched, expiration, expire_objects_from_cache, ao2_bump(cache));
  600. if (cache->expire_id < 0) {
  601. ao2_ref(cache, -1);
  602. return -1;
  603. }
  604. return 0;
  605. }
  606. /*!
  607. * \internal
  608. * \brief Remove the oldest item from the cache.
  609. *
  610. * \pre cache->objects is write-locked
  611. *
  612. * \param cache The cache from which to remove the oldest object
  613. *
  614. * \retval 0 Success
  615. * \retval non-zero Failure
  616. */
  617. static int remove_oldest_from_cache(struct sorcery_memory_cache *cache)
  618. {
  619. struct sorcery_memory_cached_object *heap_old_object;
  620. struct sorcery_memory_cached_object *hash_old_object;
  621. heap_old_object = ast_heap_pop(cache->object_heap);
  622. if (!heap_old_object) {
  623. return -1;
  624. }
  625. hash_old_object = ao2_find(cache->objects, heap_old_object,
  626. OBJ_SEARCH_OBJECT | OBJ_UNLINK | OBJ_NOLOCK);
  627. ast_assert(heap_old_object == hash_old_object);
  628. ao2_ref(hash_old_object, -1);
  629. schedule_cache_expiration(cache);
  630. return 0;
  631. }
  632. /*!
  633. * \internal
  634. * \brief Add a new object to the cache.
  635. *
  636. * \pre cache->objects is write-locked
  637. *
  638. * \param cache The cache in which to add the new object
  639. * \param cached_object The object to add to the cache
  640. *
  641. * \retval 0 Success
  642. * \retval non-zero Failure
  643. */
  644. static int add_to_cache(struct sorcery_memory_cache *cache,
  645. struct sorcery_memory_cached_object *cached_object)
  646. {
  647. struct sorcery_memory_cached_object *front;
  648. if (!ao2_link_flags(cache->objects, cached_object, OBJ_NOLOCK)) {
  649. return -1;
  650. }
  651. if (cache->full_backend_cache && (front = ast_heap_peek(cache->object_heap, 1))) {
  652. /* For a full backend cache all objects share the same lifetime */
  653. cached_object->created = front->created;
  654. }
  655. if (ast_heap_push(cache->object_heap, cached_object)) {
  656. ao2_find(cache->objects, cached_object,
  657. OBJ_SEARCH_OBJECT | OBJ_UNLINK | OBJ_NODATA | OBJ_NOLOCK);
  658. return -1;
  659. }
  660. if (cache->expire_id == -1) {
  661. schedule_cache_expiration(cache);
  662. }
  663. return 0;
  664. }
  665. /*!
  666. * \internal
  667. * \brief Allocate a cached object for caching an object
  668. *
  669. * \param sorcery The sorcery instance
  670. * \param cache The sorcery memory cache
  671. * \param object The object to cache
  672. *
  673. * \retval non-NULL success
  674. * \retval NULL failure
  675. */
  676. static struct sorcery_memory_cached_object *sorcery_memory_cached_object_alloc(const struct ast_sorcery *sorcery,
  677. const struct sorcery_memory_cache *cache, void *object)
  678. {
  679. struct sorcery_memory_cached_object *cached;
  680. cached = ao2_alloc(sizeof(*cached), sorcery_memory_cached_object_destructor);
  681. if (!cached) {
  682. return NULL;
  683. }
  684. cached->object = ao2_bump(object);
  685. cached->created = ast_tvnow();
  686. cached->stale_update_sched_id = -1;
  687. if (cache->full_backend_cache) {
  688. /* A cached objectset allows us to easily perform all retrieval operations in a
  689. * minimal of time.
  690. */
  691. cached->objectset = ast_sorcery_objectset_create(sorcery, object);
  692. if (!cached->objectset) {
  693. ao2_ref(cached, -1);
  694. return NULL;
  695. }
  696. }
  697. return cached;
  698. }
  699. /*!
  700. * \internal
  701. * \brief Callback function to cache an object in a memory cache
  702. *
  703. * \param sorcery The sorcery instance
  704. * \param data The sorcery memory cache
  705. * \param object The object to cache
  706. *
  707. * \retval 0 success
  708. * \retval -1 failure
  709. */
  710. static int sorcery_memory_cache_create(const struct ast_sorcery *sorcery, void *data, void *object)
  711. {
  712. struct sorcery_memory_cache *cache = data;
  713. struct sorcery_memory_cached_object *cached;
  714. cached = sorcery_memory_cached_object_alloc(sorcery, cache, object);
  715. if (!cached) {
  716. return -1;
  717. }
  718. /* As there is no guarantee that this won't be called by multiple threads wanting to cache
  719. * the same object we remove any old ones, which turns this into a create/update function
  720. * in reality. As well since there's no guarantee that the object in the cache is the same
  721. * one here we remove any old objects using the object identifier.
  722. */
  723. ao2_wrlock(cache->objects);
  724. remove_from_cache(cache, ast_sorcery_object_get_id(object), 1);
  725. if (cache->maximum_objects && ao2_container_count(cache->objects) >= cache->maximum_objects) {
  726. if (remove_oldest_from_cache(cache)) {
  727. ast_log(LOG_ERROR, "Unable to make room in cache for sorcery object '%s'.\n",
  728. ast_sorcery_object_get_id(object));
  729. ao2_unlock(cache->objects);
  730. ao2_ref(cached, -1);
  731. return -1;
  732. }
  733. ast_assert(ao2_container_count(cache->objects) != cache->maximum_objects);
  734. }
  735. if (add_to_cache(cache, cached)) {
  736. ast_log(LOG_ERROR, "Unable to add object '%s' to the cache\n",
  737. ast_sorcery_object_get_id(object));
  738. ao2_unlock(cache->objects);
  739. ao2_ref(cached, -1);
  740. return -1;
  741. }
  742. ao2_unlock(cache->objects);
  743. ao2_ref(cached, -1);
  744. return 0;
  745. }
  746. /*!
  747. * \internal
  748. * \brief AO2 callback function for adding an object to a memory cache
  749. *
  750. * \param obj The cached object
  751. * \param arg The sorcery instance
  752. * \param data The cache itself
  753. * \param flags Unused flags
  754. */
  755. static int object_add_to_cache_callback(void *obj, void *arg, void *data, int flags)
  756. {
  757. struct sorcery_memory_cache *cache = data;
  758. struct sorcery_memory_cached_object *cached;
  759. cached = sorcery_memory_cached_object_alloc(arg, cache, obj);
  760. if (!cached) {
  761. return CMP_STOP;
  762. }
  763. add_to_cache(cache, cached);
  764. ao2_ref(cached, -1);
  765. return 0;
  766. }
  767. struct stale_cache_update_task_data {
  768. struct ast_sorcery *sorcery;
  769. struct sorcery_memory_cache *cache;
  770. char *type;
  771. };
  772. static void stale_cache_update_task_data_destructor(void *obj)
  773. {
  774. struct stale_cache_update_task_data *task_data = obj;
  775. ao2_cleanup(task_data->cache);
  776. ast_sorcery_unref(task_data->sorcery);
  777. ast_free(task_data->type);
  778. }
  779. static struct stale_cache_update_task_data *stale_cache_update_task_data_alloc(struct ast_sorcery *sorcery,
  780. struct sorcery_memory_cache *cache, const char *type)
  781. {
  782. struct stale_cache_update_task_data *task_data;
  783. task_data = ao2_alloc_options(sizeof(*task_data), stale_cache_update_task_data_destructor,
  784. AO2_ALLOC_OPT_LOCK_NOLOCK);
  785. if (!task_data) {
  786. return NULL;
  787. }
  788. task_data->sorcery = ao2_bump(sorcery);
  789. task_data->cache = ao2_bump(cache);
  790. task_data->type = ast_strdup(type);
  791. if (!task_data->type) {
  792. ao2_ref(task_data, -1);
  793. return NULL;
  794. }
  795. return task_data;
  796. }
  797. static int stale_cache_update(const void *data)
  798. {
  799. struct stale_cache_update_task_data *task_data = (struct stale_cache_update_task_data *) data;
  800. struct ao2_container *backend_objects;
  801. start_passthru_update();
  802. backend_objects = ast_sorcery_retrieve_by_fields(task_data->sorcery, task_data->type,
  803. AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  804. end_passthru_update();
  805. if (!backend_objects) {
  806. task_data->cache->stale_update_sched_id = -1;
  807. ao2_ref(task_data, -1);
  808. return 0;
  809. }
  810. if (task_data->cache->maximum_objects && ao2_container_count(backend_objects) >= task_data->cache->maximum_objects) {
  811. ast_log(LOG_ERROR, "The backend contains %d objects while the sorcery memory cache '%s' is explicitly configured to only allow %d\n",
  812. ao2_container_count(backend_objects), task_data->cache->name, task_data->cache->maximum_objects);
  813. task_data->cache->stale_update_sched_id = -1;
  814. ao2_ref(task_data, -1);
  815. return 0;
  816. }
  817. ao2_wrlock(task_data->cache->objects);
  818. remove_all_from_cache(task_data->cache);
  819. ao2_callback_data(backend_objects, OBJ_NOLOCK | OBJ_NODATA | OBJ_MULTIPLE, object_add_to_cache_callback,
  820. task_data->sorcery, task_data->cache);
  821. /* If the number of cached objects does not match the number of backend objects we encountered a memory allocation
  822. * failure and the cache is incomplete, so drop everything and fall back to querying the backend directly
  823. * as it may be able to provide what is wanted.
  824. */
  825. if (ao2_container_count(task_data->cache->objects) != ao2_container_count(backend_objects)) {
  826. ast_log(LOG_WARNING, "The backend contains %d objects while only %d could be added to sorcery memory cache '%s'\n",
  827. ao2_container_count(backend_objects), ao2_container_count(task_data->cache->objects), task_data->cache->name);
  828. remove_all_from_cache(task_data->cache);
  829. }
  830. ao2_unlock(task_data->cache->objects);
  831. ao2_ref(backend_objects, -1);
  832. task_data->cache->stale_update_sched_id = -1;
  833. ao2_ref(task_data, -1);
  834. return 0;
  835. }
  836. struct stale_update_task_data {
  837. struct ast_sorcery *sorcery;
  838. struct sorcery_memory_cache *cache;
  839. void *object;
  840. };
  841. static void stale_update_task_data_destructor(void *obj)
  842. {
  843. struct stale_update_task_data *task_data = obj;
  844. ao2_cleanup(task_data->cache);
  845. ao2_cleanup(task_data->object);
  846. ast_sorcery_unref(task_data->sorcery);
  847. }
  848. static struct stale_update_task_data *stale_update_task_data_alloc(struct ast_sorcery *sorcery,
  849. struct sorcery_memory_cache *cache, const char *type, void *object)
  850. {
  851. struct stale_update_task_data *task_data;
  852. task_data = ao2_alloc_options(sizeof(*task_data), stale_update_task_data_destructor,
  853. AO2_ALLOC_OPT_LOCK_NOLOCK);
  854. if (!task_data) {
  855. return NULL;
  856. }
  857. task_data->sorcery = ao2_bump(sorcery);
  858. task_data->cache = ao2_bump(cache);
  859. task_data->object = ao2_bump(object);
  860. return task_data;
  861. }
  862. static int stale_item_update(const void *data)
  863. {
  864. struct stale_update_task_data *task_data = (struct stale_update_task_data *) data;
  865. void *object;
  866. start_passthru_update();
  867. object = ast_sorcery_retrieve_by_id(task_data->sorcery,
  868. ast_sorcery_object_get_type(task_data->object),
  869. ast_sorcery_object_get_id(task_data->object));
  870. if (!object) {
  871. ast_debug(1, "Backend no longer has object type '%s' ID '%s'. Removing from cache\n",
  872. ast_sorcery_object_get_type(task_data->object),
  873. ast_sorcery_object_get_id(task_data->object));
  874. sorcery_memory_cache_delete(task_data->sorcery, task_data->cache,
  875. task_data->object);
  876. } else {
  877. ast_debug(1, "Refreshing stale cache object type '%s' ID '%s'\n",
  878. ast_sorcery_object_get_type(task_data->object),
  879. ast_sorcery_object_get_id(task_data->object));
  880. sorcery_memory_cache_create(task_data->sorcery, task_data->cache,
  881. object);
  882. }
  883. ast_test_suite_event_notify("SORCERY_MEMORY_CACHE_REFRESHED", "Cache: %s\r\nType: %s\r\nName: %s\r\n",
  884. task_data->cache->name, ast_sorcery_object_get_type(task_data->object),
  885. ast_sorcery_object_get_id(task_data->object));
  886. ao2_ref(task_data, -1);
  887. end_passthru_update();
  888. return 0;
  889. }
  890. /*!
  891. * \internal
  892. * \brief Populate the cache with all objects from the backend
  893. *
  894. * \pre cache->objects is write-locked
  895. *
  896. * \param sorcery The sorcery instance
  897. * \param type The type of object
  898. * \param cache The sorcery memory cache
  899. */
  900. static void memory_cache_populate(const struct ast_sorcery *sorcery, const char *type, struct sorcery_memory_cache *cache)
  901. {
  902. struct ao2_container *backend_objects;
  903. start_passthru_update();
  904. backend_objects = ast_sorcery_retrieve_by_fields(sorcery, type, AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  905. end_passthru_update();
  906. if (!backend_objects) {
  907. /* This will occur in off-nominal memory allocation failure scenarios */
  908. return;
  909. }
  910. if (cache->maximum_objects && ao2_container_count(backend_objects) >= cache->maximum_objects) {
  911. ast_log(LOG_ERROR, "The backend contains %d objects while the sorcery memory cache '%s' is explicitly configured to only allow %d\n",
  912. ao2_container_count(backend_objects), cache->name, cache->maximum_objects);
  913. return;
  914. }
  915. ao2_callback_data(backend_objects, OBJ_NOLOCK | OBJ_NODATA | OBJ_MULTIPLE, object_add_to_cache_callback,
  916. (struct ast_sorcery*)sorcery, cache);
  917. /* If the number of cached objects does not match the number of backend objects we encountered a memory allocation
  918. * failure and the cache is incomplete, so drop everything and fall back to querying the backend directly
  919. * as it may be able to provide what is wanted.
  920. */
  921. if (ao2_container_count(cache->objects) != ao2_container_count(backend_objects)) {
  922. ast_log(LOG_WARNING, "The backend contains %d objects while only %d could be added to sorcery memory cache '%s'\n",
  923. ao2_container_count(backend_objects), ao2_container_count(cache->objects), cache->name);
  924. remove_all_from_cache(cache);
  925. }
  926. ao2_ref(backend_objects, -1);
  927. }
  928. /*!
  929. * \internal
  930. * \brief Determine if a full backend cache update is needed and do it
  931. *
  932. * \param sorcery The sorcery instance
  933. * \param type The type of object
  934. * \param cache The sorcery memory cache
  935. */
  936. static void memory_cache_full_update(const struct ast_sorcery *sorcery, const char *type, struct sorcery_memory_cache *cache)
  937. {
  938. if (!cache->full_backend_cache) {
  939. return;
  940. }
  941. ao2_wrlock(cache->objects);
  942. if (!ao2_container_count(cache->objects)) {
  943. memory_cache_populate(sorcery, type, cache);
  944. }
  945. ao2_unlock(cache->objects);
  946. }
  947. /*!
  948. * \internal
  949. * \brief Queue a full cache update
  950. *
  951. * \param sorcery The sorcery instance
  952. * \param cache The sorcery memory cache
  953. * \param type The type of object
  954. */
  955. static void memory_cache_stale_update_full(const struct ast_sorcery *sorcery, struct sorcery_memory_cache *cache,
  956. const char *type)
  957. {
  958. ao2_wrlock(cache->objects);
  959. if (cache->stale_update_sched_id == -1) {
  960. struct stale_cache_update_task_data *task_data;
  961. task_data = stale_cache_update_task_data_alloc((struct ast_sorcery *) sorcery,
  962. cache, type);
  963. if (task_data) {
  964. cache->stale_update_sched_id = ast_sched_add(sched, 1,
  965. stale_cache_update, task_data);
  966. }
  967. if (cache->stale_update_sched_id < 0) {
  968. ao2_cleanup(task_data);
  969. }
  970. }
  971. ao2_unlock(cache->objects);
  972. }
  973. /*!
  974. * \internal
  975. * \brief Queue a stale object update
  976. *
  977. * \param sorcery The sorcery instance
  978. * \param cache The sorcery memory cache
  979. * \param cached The cached object
  980. */
  981. static void memory_cache_stale_update_object(const struct ast_sorcery *sorcery, struct sorcery_memory_cache *cache,
  982. struct sorcery_memory_cached_object *cached)
  983. {
  984. ao2_lock(cached);
  985. if (cached->stale_update_sched_id == -1) {
  986. struct stale_update_task_data *task_data;
  987. task_data = stale_update_task_data_alloc((struct ast_sorcery *) sorcery,
  988. cache, ast_sorcery_object_get_type(cached->object), cached->object);
  989. if (task_data) {
  990. ast_debug(1, "Cached sorcery object type '%s' ID '%s' is stale. Refreshing\n",
  991. ast_sorcery_object_get_type(cached->object), ast_sorcery_object_get_id(cached->object));
  992. cached->stale_update_sched_id = ast_sched_add(sched, 1,
  993. stale_item_update, task_data);
  994. }
  995. if (cached->stale_update_sched_id < 0) {
  996. ao2_cleanup(task_data);
  997. ast_log(LOG_ERROR, "Unable to update stale cached object type '%s', ID '%s'.\n",
  998. ast_sorcery_object_get_type(cached->object), ast_sorcery_object_get_id(cached->object));
  999. }
  1000. }
  1001. ao2_unlock(cached);
  1002. }
  1003. /*!
  1004. * \internal
  1005. * \brief Check whether an object (or cache) is stale and queue an update
  1006. *
  1007. * \param sorcery The sorcery instance
  1008. * \param cache The sorcery memory cache
  1009. * \param cached The cached object
  1010. */
  1011. static void memory_cache_stale_check_object(const struct ast_sorcery *sorcery, struct sorcery_memory_cache *cache,
  1012. struct sorcery_memory_cached_object *cached)
  1013. {
  1014. struct timeval elapsed;
  1015. if (!cache->object_lifetime_stale) {
  1016. return;
  1017. }
  1018. /* For a full cache as every object has the same expiration/staleness we can do the same check */
  1019. elapsed = ast_tvsub(ast_tvnow(), cached->created);
  1020. if (elapsed.tv_sec < cache->object_lifetime_stale) {
  1021. return;
  1022. }
  1023. if (cache->full_backend_cache) {
  1024. memory_cache_stale_update_full(sorcery, cache, ast_sorcery_object_get_type(cached->object));
  1025. } else {
  1026. memory_cache_stale_update_object(sorcery, cache, cached);
  1027. }
  1028. }
  1029. /*!
  1030. * \internal
  1031. * \brief Check whether the entire cache is stale or not and queue an update
  1032. *
  1033. * \param sorcery The sorcery instance
  1034. * \param cache The sorcery memory cache
  1035. *
  1036. * \note Unlike \ref memory_cache_stale_check this does not require an explicit object
  1037. */
  1038. static void memory_cache_stale_check(const struct ast_sorcery *sorcery, struct sorcery_memory_cache *cache)
  1039. {
  1040. struct sorcery_memory_cached_object *cached;
  1041. ao2_rdlock(cache->objects);
  1042. cached = ao2_bump(ast_heap_peek(cache->object_heap, 1));
  1043. ao2_unlock(cache->objects);
  1044. if (!cached) {
  1045. return;
  1046. }
  1047. memory_cache_stale_check_object(sorcery, cache, cached);
  1048. ao2_ref(cached, -1);
  1049. }
  1050. /*!
  1051. * \internal
  1052. * \brief Callback function to retrieve an object from a memory cache
  1053. *
  1054. * \param sorcery The sorcery instance
  1055. * \param data The sorcery memory cache
  1056. * \param type The type of the object to retrieve
  1057. * \param id The id of the object to retrieve
  1058. *
  1059. * \retval non-NULL success
  1060. * \retval NULL failure
  1061. */
  1062. static void *sorcery_memory_cache_retrieve_id(const struct ast_sorcery *sorcery, void *data, const char *type, const char *id)
  1063. {
  1064. struct sorcery_memory_cache *cache = data;
  1065. struct sorcery_memory_cached_object *cached;
  1066. void *object;
  1067. if (is_passthru_update()) {
  1068. return NULL;
  1069. }
  1070. memory_cache_full_update(sorcery, type, cache);
  1071. cached = ao2_find(cache->objects, id, OBJ_SEARCH_KEY);
  1072. if (!cached) {
  1073. return NULL;
  1074. }
  1075. ast_assert(!strcmp(ast_sorcery_object_get_id(cached->object), id));
  1076. memory_cache_stale_check_object(sorcery, cache, cached);
  1077. object = ao2_bump(cached->object);
  1078. ao2_ref(cached, -1);
  1079. return object;
  1080. }
  1081. /*!
  1082. * \internal
  1083. * \brief AO2 callback function for comparing a retrieval request and finding applicable objects
  1084. *
  1085. * \param obj The cached object
  1086. * \param arg The comparison parameters
  1087. * \param flags Unused flags
  1088. */
  1089. static int sorcery_memory_cache_fields_cmp(void *obj, void *arg, int flags)
  1090. {
  1091. struct sorcery_memory_cached_object *cached = obj;
  1092. const struct sorcery_memory_cache_fields_cmp_params *params = arg;
  1093. RAII_VAR(struct ast_variable *, diff, NULL, ast_variables_destroy);
  1094. if (params->regex) {
  1095. /* If a regular expression has been provided see if it matches, otherwise move on */
  1096. if (!regexec(params->regex, ast_sorcery_object_get_id(cached->object), 0, NULL, 0)) {
  1097. ao2_link(params->container, cached->object);
  1098. }
  1099. return 0;
  1100. } else if (params->prefix) {
  1101. if (!strncmp(params->prefix, ast_sorcery_object_get_id(cached->object), params->prefix_len)) {
  1102. ao2_link(params->container, cached->object);
  1103. }
  1104. return 0;
  1105. } else if (params->fields &&
  1106. (!ast_variable_lists_match(cached->objectset, params->fields, 0))) {
  1107. /* If we can't turn the object into an object set OR if differences exist between the fields
  1108. * passed in and what are present on the object they are not a match.
  1109. */
  1110. return 0;
  1111. }
  1112. if (params->container) {
  1113. ao2_link(params->container, cached->object);
  1114. /* As multiple objects are being returned keep going */
  1115. return 0;
  1116. } else {
  1117. /* Immediately stop and return, we only want a single object */
  1118. return CMP_MATCH | CMP_STOP;
  1119. }
  1120. }
  1121. /*!
  1122. * \internal
  1123. * \brief Callback function to retrieve a single object based on fields
  1124. *
  1125. * \param sorcery The sorcery instance
  1126. * \param data The sorcery memory cache
  1127. * \param type The type of the object to retrieve
  1128. * \param fields Any explicit fields to search for
  1129. */
  1130. static void *sorcery_memory_cache_retrieve_fields(const struct ast_sorcery *sorcery, void *data, const char *type,
  1131. const struct ast_variable *fields)
  1132. {
  1133. struct sorcery_memory_cache *cache = data;
  1134. struct sorcery_memory_cache_fields_cmp_params params = {
  1135. .sorcery = sorcery,
  1136. .cache = cache,
  1137. .fields = fields,
  1138. };
  1139. struct sorcery_memory_cached_object *cached;
  1140. void *object = NULL;
  1141. if (is_passthru_update() || !cache->full_backend_cache || !fields) {
  1142. return NULL;
  1143. }
  1144. cached = ao2_callback(cache->objects, 0, sorcery_memory_cache_fields_cmp, &params);
  1145. if (cached) {
  1146. memory_cache_stale_check_object(sorcery, cache, cached);
  1147. object = ao2_bump(cached->object);
  1148. ao2_ref(cached, -1);
  1149. }
  1150. return object;
  1151. }
  1152. /*!
  1153. * \internal
  1154. * \brief Callback function to retrieve multiple objects from a memory cache
  1155. *
  1156. * \param sorcery The sorcery instance
  1157. * \param data The sorcery memory cache
  1158. * \param type The type of the object to retrieve
  1159. * \param objects Container to place the objects into
  1160. * \param fields Any explicit fields to search for
  1161. */
  1162. static void sorcery_memory_cache_retrieve_multiple(const struct ast_sorcery *sorcery, void *data, const char *type,
  1163. struct ao2_container *objects, const struct ast_variable *fields)
  1164. {
  1165. struct sorcery_memory_cache *cache = data;
  1166. struct sorcery_memory_cache_fields_cmp_params params = {
  1167. .sorcery = sorcery,
  1168. .cache = cache,
  1169. .fields = fields,
  1170. .container = objects,
  1171. };
  1172. if (is_passthru_update() || !cache->full_backend_cache) {
  1173. return;
  1174. }
  1175. memory_cache_full_update(sorcery, type, cache);
  1176. ao2_callback(cache->objects, 0, sorcery_memory_cache_fields_cmp, &params);
  1177. if (ao2_container_count(objects)) {
  1178. memory_cache_stale_check(sorcery, cache);
  1179. }
  1180. }
  1181. /*!
  1182. * \internal
  1183. * \brief Callback function to retrieve multiple objects using a regex on the object id
  1184. *
  1185. * \param sorcery The sorcery instance
  1186. * \param data The sorcery memory cache
  1187. * \param type The type of the object to retrieve
  1188. * \param objects Container to place the objects into
  1189. * \param regex Regular expression to apply to the object id
  1190. */
  1191. static void sorcery_memory_cache_retrieve_regex(const struct ast_sorcery *sorcery, void *data, const char *type,
  1192. struct ao2_container *objects, const char *regex)
  1193. {
  1194. struct sorcery_memory_cache *cache = data;
  1195. regex_t expression;
  1196. struct sorcery_memory_cache_fields_cmp_params params = {
  1197. .sorcery = sorcery,
  1198. .cache = cache,
  1199. .container = objects,
  1200. .regex = &expression,
  1201. };
  1202. if (is_passthru_update() || !cache->full_backend_cache || regcomp(&expression, regex, REG_EXTENDED | REG_NOSUB)) {
  1203. return;
  1204. }
  1205. memory_cache_full_update(sorcery, type, cache);
  1206. ao2_callback(cache->objects, 0, sorcery_memory_cache_fields_cmp, &params);
  1207. regfree(&expression);
  1208. if (ao2_container_count(objects)) {
  1209. memory_cache_stale_check(sorcery, cache);
  1210. }
  1211. }
  1212. /*!
  1213. * \internal
  1214. * \brief Callback function to retrieve multiple objects whose id matches a prefix
  1215. *
  1216. * \param sorcery The sorcery instance
  1217. * \param data The sorcery memory cache
  1218. * \param type The type of the object to retrieve
  1219. * \param objects Container to place the objects into
  1220. * \param prefix Prefix to match against the object id
  1221. */
  1222. static void sorcery_memory_cache_retrieve_prefix(const struct ast_sorcery *sorcery, void *data, const char *type,
  1223. struct ao2_container *objects, const char *prefix, const size_t prefix_len)
  1224. {
  1225. struct sorcery_memory_cache *cache = data;
  1226. struct sorcery_memory_cache_fields_cmp_params params = {
  1227. .sorcery = sorcery,
  1228. .cache = cache,
  1229. .container = objects,
  1230. .prefix = prefix,
  1231. .prefix_len = prefix_len,
  1232. };
  1233. if (is_passthru_update() || !cache->full_backend_cache) {
  1234. return;
  1235. }
  1236. memory_cache_full_update(sorcery, type, cache);
  1237. ao2_callback(cache->objects, 0, sorcery_memory_cache_fields_cmp, &params);
  1238. if (ao2_container_count(objects)) {
  1239. memory_cache_stale_check(sorcery, cache);
  1240. }
  1241. }
  1242. /*!
  1243. * \internal
  1244. * \brief Callback function to finish configuring the memory cache
  1245. *
  1246. * \param data The sorcery memory cache
  1247. * \param sorcery The sorcery instance
  1248. * \param type The type of object being loaded
  1249. */
  1250. static void sorcery_memory_cache_load(void *data, const struct ast_sorcery *sorcery, const char *type)
  1251. {
  1252. struct sorcery_memory_cache *cache = data;
  1253. /* If no name was explicitly specified generate one given the sorcery instance and object type */
  1254. if (ast_strlen_zero(cache->name)) {
  1255. ast_asprintf(&cache->name, "%s/%s", ast_sorcery_get_module(sorcery), type);
  1256. }
  1257. ao2_link(caches, cache);
  1258. ast_debug(1, "Memory cache '%s' associated with sorcery instance '%p' of module '%s' with object type '%s'\n",
  1259. cache->name, sorcery, ast_sorcery_get_module(sorcery), type);
  1260. cache->sorcery = sorcery;
  1261. cache->object_type = ast_strdup(type);
  1262. }
  1263. /*!
  1264. * \internal
  1265. * \brief Callback function to expire objects from the memory cache on reload (if configured)
  1266. *
  1267. * \param data The sorcery memory cache
  1268. * \param sorcery The sorcery instance
  1269. * \param type The type of object being reloaded
  1270. */
  1271. static void sorcery_memory_cache_reload(void *data, const struct ast_sorcery *sorcery, const char *type)
  1272. {
  1273. struct sorcery_memory_cache *cache = data;
  1274. if (!cache->expire_on_reload) {
  1275. return;
  1276. }
  1277. ao2_wrlock(cache->objects);
  1278. remove_all_from_cache(cache);
  1279. ao2_unlock(cache->objects);
  1280. }
  1281. /*!
  1282. * \internal
  1283. * \brief Function used to take an unsigned integer based configuration option and parse it
  1284. *
  1285. * \param value The string value of the configuration option
  1286. * \param result The unsigned integer to place the result in
  1287. *
  1288. * \retval 0 failure
  1289. * \retval 1 success
  1290. */
  1291. static int configuration_parse_unsigned_integer(const char *value, unsigned int *result)
  1292. {
  1293. if (ast_strlen_zero(value) || !strncmp(value, "-", 1)) {
  1294. return 0;
  1295. }
  1296. return sscanf(value, "%30u", result);
  1297. }
  1298. static int age_cmp(void *a, void *b)
  1299. {
  1300. return ast_tvcmp(((struct sorcery_memory_cached_object *) b)->created,
  1301. ((struct sorcery_memory_cached_object *) a)->created);
  1302. }
  1303. /*!
  1304. * \internal
  1305. * \brief Callback function to create a new sorcery memory cache using provided configuration
  1306. *
  1307. * \param data A stringified configuration for the memory cache
  1308. *
  1309. * \retval non-NULL success
  1310. * \retval NULL failure
  1311. */
  1312. static void *sorcery_memory_cache_open(const char *data)
  1313. {
  1314. char *options = ast_strdup(data), *option;
  1315. RAII_VAR(struct sorcery_memory_cache *, cache, NULL, ao2_cleanup);
  1316. cache = ao2_alloc_options(sizeof(*cache), sorcery_memory_cache_destructor, AO2_ALLOC_OPT_LOCK_NOLOCK);
  1317. if (!cache) {
  1318. return NULL;
  1319. }
  1320. cache->expire_id = -1;
  1321. cache->stale_update_sched_id = -1;
  1322. /* If no configuration options have been provided this memory cache will operate in a default
  1323. * configuration.
  1324. */
  1325. while (!ast_strlen_zero(options) && (option = strsep(&options, ","))) {
  1326. char *name = strsep(&option, "="), *value = option;
  1327. if (!strcasecmp(name, "name")) {
  1328. if (ast_strlen_zero(value)) {
  1329. ast_log(LOG_ERROR, "A name must be specified for the memory cache\n");
  1330. return NULL;
  1331. }
  1332. ast_free(cache->name);
  1333. cache->name = ast_strdup(value);
  1334. } else if (!strcasecmp(name, "maximum_objects")) {
  1335. if (configuration_parse_unsigned_integer(value, &cache->maximum_objects) != 1) {
  1336. ast_log(LOG_ERROR, "Unsupported maximum objects value of '%s' used for memory cache\n",
  1337. value);
  1338. return NULL;
  1339. }
  1340. } else if (!strcasecmp(name, "object_lifetime_maximum")) {
  1341. if (configuration_parse_unsigned_integer(value, &cache->object_lifetime_maximum) != 1) {
  1342. ast_log(LOG_ERROR, "Unsupported object maximum lifetime value of '%s' used for memory cache\n",
  1343. value);
  1344. return NULL;
  1345. }
  1346. } else if (!strcasecmp(name, "object_lifetime_stale")) {
  1347. if (configuration_parse_unsigned_integer(value, &cache->object_lifetime_stale) != 1) {
  1348. ast_log(LOG_ERROR, "Unsupported object stale lifetime value of '%s' used for memory cache\n",
  1349. value);
  1350. return NULL;
  1351. }
  1352. } else if (!strcasecmp(name, "expire_on_reload")) {
  1353. cache->expire_on_reload = ast_true(value);
  1354. } else if (!strcasecmp(name, "full_backend_cache")) {
  1355. cache->full_backend_cache = ast_true(value);
  1356. } else {
  1357. ast_log(LOG_ERROR, "Unsupported option '%s' used for memory cache\n", name);
  1358. return NULL;
  1359. }
  1360. }
  1361. cache->objects = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK, 0,
  1362. cache->maximum_objects ? cache->maximum_objects : CACHE_CONTAINER_BUCKET_SIZE,
  1363. sorcery_memory_cached_object_hash, NULL, sorcery_memory_cached_object_cmp);
  1364. if (!cache->objects) {
  1365. ast_log(LOG_ERROR, "Could not create a container to hold cached objects for memory cache\n");
  1366. return NULL;
  1367. }
  1368. cache->object_heap = ast_heap_create(CACHE_HEAP_INIT_HEIGHT, age_cmp,
  1369. offsetof(struct sorcery_memory_cached_object, __heap_index));
  1370. if (!cache->object_heap) {
  1371. ast_log(LOG_ERROR, "Could not create heap to hold cached objects\n");
  1372. return NULL;
  1373. }
  1374. /* The memory cache is not linked to the caches container until the load callback is invoked.
  1375. * Linking occurs there so an intelligent cache name can be constructed using the module of
  1376. * the sorcery instance and the specific object type if no cache name was specified as part
  1377. * of the configuration.
  1378. */
  1379. /* This is done as RAII_VAR will drop the reference */
  1380. return ao2_bump(cache);
  1381. }
  1382. /*!
  1383. * \internal
  1384. * \brief Callback function to delete an object from a memory cache
  1385. *
  1386. * \param sorcery The sorcery instance
  1387. * \param data The sorcery memory cache
  1388. * \param object The object to cache
  1389. *
  1390. * \retval 0 success
  1391. * \retval -1 failure
  1392. */
  1393. static int sorcery_memory_cache_delete(const struct ast_sorcery *sorcery, void *data, void *object)
  1394. {
  1395. struct sorcery_memory_cache *cache = data;
  1396. int res;
  1397. ao2_wrlock(cache->objects);
  1398. res = remove_from_cache(cache, ast_sorcery_object_get_id(object), 1);
  1399. ao2_unlock(cache->objects);
  1400. if (res) {
  1401. ast_debug(1, "Unable to delete object '%s' from sorcery cache\n", ast_sorcery_object_get_id(object));
  1402. }
  1403. return res;
  1404. }
  1405. /*!
  1406. * \internal
  1407. * \brief Callback function to terminate a memory cache
  1408. *
  1409. * \param data The sorcery memory cache
  1410. */
  1411. static void sorcery_memory_cache_close(void *data)
  1412. {
  1413. struct sorcery_memory_cache *cache = data;
  1414. /* This can occur if a cache is created but never loaded */
  1415. if (!ast_strlen_zero(cache->name)) {
  1416. ao2_unlink(caches, cache);
  1417. }
  1418. if (cache->object_lifetime_maximum) {
  1419. /* If object lifetime support is enabled we need to explicitly drop all cached objects here
  1420. * and stop the scheduled task. Failure to do so could potentially keep the cache around for
  1421. * a prolonged period of time.
  1422. */
  1423. ao2_wrlock(cache->objects);
  1424. remove_all_from_cache(cache);
  1425. ao2_unlock(cache->objects);
  1426. }
  1427. if (cache->full_backend_cache) {
  1428. ao2_wrlock(cache->objects);
  1429. cache->sorcery = NULL;
  1430. ao2_unlock(cache->objects);
  1431. }
  1432. ao2_ref(cache, -1);
  1433. }
  1434. /*!
  1435. * \internal
  1436. * \brief CLI tab completion for cache names
  1437. */
  1438. static char *sorcery_memory_cache_complete_name(const char *word, int state)
  1439. {
  1440. struct sorcery_memory_cache *cache;
  1441. struct ao2_iterator it_caches;
  1442. int wordlen = strlen(word);
  1443. int which = 0;
  1444. char *result = NULL;
  1445. it_caches = ao2_iterator_init(caches, 0);
  1446. while ((cache = ao2_iterator_next(&it_caches))) {
  1447. if (!strncasecmp(word, cache->name, wordlen)
  1448. && ++which > state) {
  1449. result = ast_strdup(cache->name);
  1450. }
  1451. ao2_ref(cache, -1);
  1452. if (result) {
  1453. break;
  1454. }
  1455. }
  1456. ao2_iterator_destroy(&it_caches);
  1457. return result;
  1458. }
  1459. /*!
  1460. * \internal
  1461. * \brief CLI command implementation for 'sorcery memory cache show'
  1462. */
  1463. static char *sorcery_memory_cache_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1464. {
  1465. struct sorcery_memory_cache *cache;
  1466. switch (cmd) {
  1467. case CLI_INIT:
  1468. e->command = "sorcery memory cache show";
  1469. e->usage =
  1470. "Usage: sorcery memory cache show <name>\n"
  1471. " Show sorcery memory cache configuration and statistics.\n";
  1472. return NULL;
  1473. case CLI_GENERATE:
  1474. if (a->pos == 4) {
  1475. return sorcery_memory_cache_complete_name(a->word, a->n);
  1476. } else {
  1477. return NULL;
  1478. }
  1479. }
  1480. if (a->argc != 5) {
  1481. return CLI_SHOWUSAGE;
  1482. }
  1483. cache = ao2_find(caches, a->argv[4], OBJ_SEARCH_KEY);
  1484. if (!cache) {
  1485. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not exist\n", a->argv[4]);
  1486. return CLI_FAILURE;
  1487. }
  1488. ast_cli(a->fd, "Sorcery memory cache: %s\n", cache->name);
  1489. ast_cli(a->fd, "Number of objects within cache: %d\n", ao2_container_count(cache->objects));
  1490. if (cache->maximum_objects) {
  1491. ast_cli(a->fd, "Maximum allowed objects: %d\n", cache->maximum_objects);
  1492. } else {
  1493. ast_cli(a->fd, "There is no limit on the maximum number of objects in the cache\n");
  1494. }
  1495. if (cache->object_lifetime_maximum) {
  1496. ast_cli(a->fd, "Number of seconds before object expires: %d\n", cache->object_lifetime_maximum);
  1497. } else {
  1498. ast_cli(a->fd, "Object expiration is not enabled - cached objects will not expire\n");
  1499. }
  1500. if (cache->object_lifetime_stale) {
  1501. ast_cli(a->fd, "Number of seconds before object becomes stale: %d\n", cache->object_lifetime_stale);
  1502. } else {
  1503. ast_cli(a->fd, "Object staleness is not enabled - cached objects will not go stale\n");
  1504. }
  1505. ast_cli(a->fd, "Expire all objects on reload: %s\n", AST_CLI_ONOFF(cache->expire_on_reload));
  1506. ao2_ref(cache, -1);
  1507. return CLI_SUCCESS;
  1508. }
  1509. /*! \brief Structure used to pass data for printing cached object information */
  1510. struct print_object_details {
  1511. /*! \brief The sorcery memory cache */
  1512. struct sorcery_memory_cache *cache;
  1513. /*! \brief The CLI arguments */
  1514. struct ast_cli_args *a;
  1515. };
  1516. /*!
  1517. * \internal
  1518. * \brief Callback function for displaying object within the cache
  1519. */
  1520. static int sorcery_memory_cache_print_object(void *obj, void *arg, int flags)
  1521. {
  1522. #define FORMAT "%-25.25s %-15u %-15u \n"
  1523. struct sorcery_memory_cached_object *cached = obj;
  1524. struct print_object_details *details = arg;
  1525. int seconds_until_expire = 0, seconds_until_stale = 0;
  1526. if (details->cache->object_lifetime_maximum) {
  1527. seconds_until_expire = ast_tvdiff_ms(ast_tvadd(cached->created, ast_samp2tv(details->cache->object_lifetime_maximum, 1)), ast_tvnow()) / 1000;
  1528. }
  1529. if (details->cache->object_lifetime_stale) {
  1530. seconds_until_stale = ast_tvdiff_ms(ast_tvadd(cached->created, ast_samp2tv(details->cache->object_lifetime_stale, 1)), ast_tvnow()) / 1000;
  1531. }
  1532. ast_cli(details->a->fd, FORMAT, ast_sorcery_object_get_id(cached->object), MAX(seconds_until_stale, 0), MAX(seconds_until_expire, 0));
  1533. return CMP_MATCH;
  1534. #undef FORMAT
  1535. }
  1536. /*!
  1537. * \internal
  1538. * \brief CLI command implementation for 'sorcery memory cache dump'
  1539. */
  1540. static char *sorcery_memory_cache_dump(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1541. {
  1542. #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
  1543. struct sorcery_memory_cache *cache;
  1544. struct print_object_details details;
  1545. switch (cmd) {
  1546. case CLI_INIT:
  1547. e->command = "sorcery memory cache dump";
  1548. e->usage =
  1549. "Usage: sorcery memory cache dump <name>\n"
  1550. " Dump a list of the objects within the cache, listed by object identifier.\n";
  1551. return NULL;
  1552. case CLI_GENERATE:
  1553. if (a->pos == 4) {
  1554. return sorcery_memory_cache_complete_name(a->word, a->n);
  1555. } else {
  1556. return NULL;
  1557. }
  1558. }
  1559. if (a->argc != 5) {
  1560. return CLI_SHOWUSAGE;
  1561. }
  1562. cache = ao2_find(caches, a->argv[4], OBJ_SEARCH_KEY);
  1563. if (!cache) {
  1564. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not exist\n", a->argv[4]);
  1565. return CLI_FAILURE;
  1566. }
  1567. details.cache = cache;
  1568. details.a = a;
  1569. ast_cli(a->fd, "Dumping sorcery memory cache '%s':\n", cache->name);
  1570. if (!cache->object_lifetime_stale) {
  1571. ast_cli(a->fd, " * Staleness is not enabled - objects will not go stale\n");
  1572. }
  1573. if (!cache->object_lifetime_maximum) {
  1574. ast_cli(a->fd, " * Object lifetime is not enabled - objects will not expire\n");
  1575. }
  1576. ast_cli(a->fd, FORMAT, "Object Name", "Stale In", "Expires In");
  1577. ast_cli(a->fd, FORMAT, "-------------------------", "---------------", "---------------");
  1578. ao2_callback(cache->objects, OBJ_NODATA | OBJ_MULTIPLE, sorcery_memory_cache_print_object, &details);
  1579. ast_cli(a->fd, FORMAT, "-------------------------", "---------------", "---------------");
  1580. ast_cli(a->fd, "Total number of objects cached: %d\n", ao2_container_count(cache->objects));
  1581. ao2_ref(cache, -1);
  1582. return CLI_SUCCESS;
  1583. #undef FORMAT
  1584. }
  1585. /*!
  1586. * \internal
  1587. * \brief CLI tab completion for cached object names
  1588. */
  1589. static char *sorcery_memory_cache_complete_object_name(const char *cache_name, const char *word, int state)
  1590. {
  1591. struct sorcery_memory_cache *cache;
  1592. struct sorcery_memory_cached_object *cached;
  1593. struct ao2_iterator it_cached;
  1594. int wordlen = strlen(word);
  1595. int which = 0;
  1596. char *result = NULL;
  1597. cache = ao2_find(caches, cache_name, OBJ_SEARCH_KEY);
  1598. if (!cache) {
  1599. return NULL;
  1600. }
  1601. it_cached = ao2_iterator_init(cache->objects, 0);
  1602. while ((cached = ao2_iterator_next(&it_cached))) {
  1603. if (!strncasecmp(word, ast_sorcery_object_get_id(cached->object), wordlen)
  1604. && ++which > state) {
  1605. result = ast_strdup(ast_sorcery_object_get_id(cached->object));
  1606. }
  1607. ao2_ref(cached, -1);
  1608. if (result) {
  1609. break;
  1610. }
  1611. }
  1612. ao2_iterator_destroy(&it_cached);
  1613. ao2_ref(cache, -1);
  1614. return result;
  1615. }
  1616. /*!
  1617. * \internal
  1618. * \brief CLI command implementation for 'sorcery memory cache expire'
  1619. */
  1620. static char *sorcery_memory_cache_expire(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1621. {
  1622. struct sorcery_memory_cache *cache;
  1623. switch (cmd) {
  1624. case CLI_INIT:
  1625. e->command = "sorcery memory cache expire";
  1626. e->usage =
  1627. "Usage: sorcery memory cache expire <cache name> [object name]\n"
  1628. " Expire a specific object or ALL objects within a sorcery memory cache.\n";
  1629. return NULL;
  1630. case CLI_GENERATE:
  1631. if (a->pos == 4) {
  1632. return sorcery_memory_cache_complete_name(a->word, a->n);
  1633. } else if (a->pos == 5) {
  1634. return sorcery_memory_cache_complete_object_name(a->argv[4], a->word, a->n);
  1635. } else {
  1636. return NULL;
  1637. }
  1638. }
  1639. if (a->argc < 5 || a->argc > 6) {
  1640. return CLI_SHOWUSAGE;
  1641. }
  1642. cache = ao2_find(caches, a->argv[4], OBJ_SEARCH_KEY);
  1643. if (!cache) {
  1644. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not exist\n", a->argv[4]);
  1645. return CLI_FAILURE;
  1646. }
  1647. ao2_wrlock(cache->objects);
  1648. if (a->argc == 5) {
  1649. remove_all_from_cache(cache);
  1650. ast_cli(a->fd, "All objects have been removed from cache '%s'\n", a->argv[4]);
  1651. } else {
  1652. if (!remove_from_cache(cache, a->argv[5], 1)) {
  1653. ast_cli(a->fd, "Successfully expired object '%s' from cache '%s'\n", a->argv[5], a->argv[4]);
  1654. } else {
  1655. ast_cli(a->fd, "Object '%s' was not expired from cache '%s' as it was not found\n", a->argv[5],
  1656. a->argv[4]);
  1657. }
  1658. }
  1659. ao2_unlock(cache->objects);
  1660. ao2_ref(cache, -1);
  1661. return CLI_SUCCESS;
  1662. }
  1663. /*!
  1664. * \internal
  1665. * \brief CLI command implementation for 'sorcery memory cache stale'
  1666. */
  1667. static char *sorcery_memory_cache_stale(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1668. {
  1669. struct sorcery_memory_cache *cache;
  1670. int reload = 0;
  1671. switch (cmd) {
  1672. case CLI_INIT:
  1673. e->command = "sorcery memory cache stale";
  1674. e->usage =
  1675. "Usage: sorcery memory cache stale <cache name> [object name [reload]]\n"
  1676. " Mark a specific object or ALL objects as stale in a sorcery memory cache.\n"
  1677. " If \"reload\" is specified, then the object is marked stale and immediately\n"
  1678. " retrieved from backend storage to repopulate the cache\n";
  1679. return NULL;
  1680. case CLI_GENERATE:
  1681. if (a->pos == 4) {
  1682. return sorcery_memory_cache_complete_name(a->word, a->n);
  1683. } else if (a->pos == 5) {
  1684. return sorcery_memory_cache_complete_object_name(a->argv[4], a->word, a->n);
  1685. } else if (a->pos == 6) {
  1686. static const char * const completions[] = { "reload", NULL };
  1687. return ast_cli_complete(a->word, completions, a->n);
  1688. } else {
  1689. return NULL;
  1690. }
  1691. }
  1692. if (a->argc < 5 || a->argc > 7) {
  1693. return CLI_SHOWUSAGE;
  1694. }
  1695. if (a->argc == 7) {
  1696. if (!strcasecmp(a->argv[6], "reload")) {
  1697. reload = 1;
  1698. } else {
  1699. return CLI_SHOWUSAGE;
  1700. }
  1701. }
  1702. cache = ao2_find(caches, a->argv[4], OBJ_SEARCH_KEY);
  1703. if (!cache) {
  1704. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not exist\n", a->argv[4]);
  1705. return CLI_FAILURE;
  1706. }
  1707. if (!cache->object_lifetime_stale) {
  1708. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not have staleness enabled\n", a->argv[4]);
  1709. ao2_ref(cache, -1);
  1710. return CLI_FAILURE;
  1711. }
  1712. ao2_rdlock(cache->objects);
  1713. if (a->argc == 5) {
  1714. mark_all_as_stale_in_cache(cache);
  1715. ast_cli(a->fd, "Marked all objects in sorcery memory cache '%s' as stale\n", a->argv[4]);
  1716. } else {
  1717. if (!mark_object_as_stale_in_cache(cache, a->argv[5])) {
  1718. ast_cli(a->fd, "Successfully marked object '%s' in memory cache '%s' as stale\n",
  1719. a->argv[5], a->argv[4]);
  1720. if (reload) {
  1721. struct sorcery_memory_cached_object *cached;
  1722. cached = ao2_find(cache->objects, a->argv[5], OBJ_SEARCH_KEY | OBJ_NOLOCK);
  1723. if (cached) {
  1724. memory_cache_stale_update_object(cache->sorcery, cache, cached);
  1725. ao2_ref(cached, -1);
  1726. }
  1727. }
  1728. } else {
  1729. ast_cli(a->fd, "Object '%s' in sorcery memory cache '%s' could not be marked as stale as it was not found\n",
  1730. a->argv[5], a->argv[4]);
  1731. }
  1732. }
  1733. ao2_unlock(cache->objects);
  1734. ao2_ref(cache, -1);
  1735. return CLI_SUCCESS;
  1736. }
  1737. /*!
  1738. * \internal
  1739. * \brief CLI command implementation for 'sorcery memory cache populate'
  1740. */
  1741. static char *sorcery_memory_cache_populate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1742. {
  1743. struct sorcery_memory_cache *cache;
  1744. switch (cmd) {
  1745. case CLI_INIT:
  1746. e->command = "sorcery memory cache populate";
  1747. e->usage =
  1748. "Usage: sorcery memory cache populate <cache name>\n"
  1749. " Expire all objects in the cache and populate it with ALL objects from backend.\n";
  1750. return NULL;
  1751. case CLI_GENERATE:
  1752. if (a->pos == 4) {
  1753. return sorcery_memory_cache_complete_name(a->word, a->n);
  1754. } else {
  1755. return NULL;
  1756. }
  1757. }
  1758. if (a->argc != 5) {
  1759. return CLI_SHOWUSAGE;
  1760. }
  1761. cache = ao2_find(caches, a->argv[4], OBJ_SEARCH_KEY);
  1762. if (!cache) {
  1763. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not exist\n", a->argv[4]);
  1764. return CLI_FAILURE;
  1765. }
  1766. if (!cache->full_backend_cache) {
  1767. ast_cli(a->fd, "Specified sorcery memory cache '%s' does not have full backend caching enabled\n", a->argv[4]);
  1768. ao2_ref(cache, -1);
  1769. return CLI_FAILURE;
  1770. }
  1771. ao2_wrlock(cache->objects);
  1772. if (!cache->sorcery) {
  1773. ast_cli(a->fd, "Specified sorcery memory cache '%s' is no longer active\n", a->argv[4]);
  1774. ao2_unlock(cache->objects);
  1775. ao2_ref(cache, -1);
  1776. return CLI_FAILURE;
  1777. }
  1778. remove_all_from_cache(cache);
  1779. memory_cache_populate(cache->sorcery, cache->object_type, cache);
  1780. ast_cli(a->fd, "Specified sorcery memory cache '%s' has been populated with '%d' objects from the backend\n",
  1781. a->argv[4], ao2_container_count(cache->objects));
  1782. ao2_unlock(cache->objects);
  1783. ao2_ref(cache, -1);
  1784. return CLI_SUCCESS;
  1785. }
  1786. static struct ast_cli_entry cli_memory_cache[] = {
  1787. AST_CLI_DEFINE(sorcery_memory_cache_show, "Show sorcery memory cache information"),
  1788. AST_CLI_DEFINE(sorcery_memory_cache_dump, "Dump all objects within a sorcery memory cache"),
  1789. AST_CLI_DEFINE(sorcery_memory_cache_expire, "Expire a specific object or ALL objects within a sorcery memory cache"),
  1790. AST_CLI_DEFINE(sorcery_memory_cache_stale, "Mark a specific object or ALL objects as stale within a sorcery memory cache"),
  1791. AST_CLI_DEFINE(sorcery_memory_cache_populate, "Clear and populate the sorcery memory cache with objects from the backend"),
  1792. };
  1793. /*!
  1794. * \internal
  1795. * \brief AMI command implementation for 'SorceryMemoryCacheExpireObject'
  1796. */
  1797. static int sorcery_memory_cache_ami_expire_object(struct mansession *s, const struct message *m)
  1798. {
  1799. const char *cache_name = astman_get_header(m, "Cache");
  1800. const char *object_name = astman_get_header(m, "Object");
  1801. struct sorcery_memory_cache *cache;
  1802. int res;
  1803. if (ast_strlen_zero(cache_name)) {
  1804. astman_send_error(s, m, "SorceryMemoryCacheExpireObject requires that a cache name be provided.\n");
  1805. return 0;
  1806. } else if (ast_strlen_zero(object_name)) {
  1807. astman_send_error(s, m, "SorceryMemoryCacheExpireObject requires that an object name be provided\n");
  1808. return 0;
  1809. }
  1810. cache = ao2_find(caches, cache_name, OBJ_SEARCH_KEY);
  1811. if (!cache) {
  1812. astman_send_error(s, m, "The provided cache does not exist\n");
  1813. return 0;
  1814. }
  1815. ao2_wrlock(cache->objects);
  1816. res = remove_from_cache(cache, object_name, 1);
  1817. ao2_unlock(cache->objects);
  1818. ao2_ref(cache, -1);
  1819. if (!res) {
  1820. astman_send_ack(s, m, "The provided object was expired from the cache\n");
  1821. } else {
  1822. astman_send_error(s, m, "The provided object could not be expired from the cache\n");
  1823. }
  1824. return 0;
  1825. }
  1826. /*!
  1827. * \internal
  1828. * \brief AMI command implementation for 'SorceryMemoryCacheExpire'
  1829. */
  1830. static int sorcery_memory_cache_ami_expire(struct mansession *s, const struct message *m)
  1831. {
  1832. const char *cache_name = astman_get_header(m, "Cache");
  1833. struct sorcery_memory_cache *cache;
  1834. if (ast_strlen_zero(cache_name)) {
  1835. astman_send_error(s, m, "SorceryMemoryCacheExpire requires that a cache name be provided.\n");
  1836. return 0;
  1837. }
  1838. cache = ao2_find(caches, cache_name, OBJ_SEARCH_KEY);
  1839. if (!cache) {
  1840. astman_send_error(s, m, "The provided cache does not exist\n");
  1841. return 0;
  1842. }
  1843. ao2_wrlock(cache->objects);
  1844. remove_all_from_cache(cache);
  1845. ao2_unlock(cache->objects);
  1846. ao2_ref(cache, -1);
  1847. astman_send_ack(s, m, "All objects were expired from the cache\n");
  1848. return 0;
  1849. }
  1850. /*!
  1851. * \internal
  1852. * \brief AMI command implementation for 'SorceryMemoryCacheStaleObject'
  1853. */
  1854. static int sorcery_memory_cache_ami_stale_object(struct mansession *s, const struct message *m)
  1855. {
  1856. const char *cache_name = astman_get_header(m, "Cache");
  1857. const char *object_name = astman_get_header(m, "Object");
  1858. const char *reload = astman_get_header(m, "Reload");
  1859. struct sorcery_memory_cache *cache;
  1860. int res;
  1861. if (ast_strlen_zero(cache_name)) {
  1862. astman_send_error(s, m, "SorceryMemoryCacheStaleObject requires that a cache name be provided.\n");
  1863. return 0;
  1864. } else if (ast_strlen_zero(object_name)) {
  1865. astman_send_error(s, m, "SorceryMemoryCacheStaleObject requires that an object name be provided\n");
  1866. return 0;
  1867. }
  1868. cache = ao2_find(caches, cache_name, OBJ_SEARCH_KEY);
  1869. if (!cache) {
  1870. astman_send_error(s, m, "The provided cache does not exist\n");
  1871. return 0;
  1872. }
  1873. ao2_rdlock(cache->objects);
  1874. res = mark_object_as_stale_in_cache(cache, object_name);
  1875. if (ast_true(reload)) {
  1876. struct sorcery_memory_cached_object *cached;
  1877. cached = ao2_find(cache->objects, object_name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
  1878. if (cached) {
  1879. memory_cache_stale_update_object(cache->sorcery, cache, cached);
  1880. ao2_ref(cached, -1);
  1881. }
  1882. }
  1883. ao2_unlock(cache->objects);
  1884. ao2_ref(cache, -1);
  1885. if (!res) {
  1886. astman_send_ack(s, m, "The provided object was marked as stale in the cache\n");
  1887. } else {
  1888. astman_send_error(s, m, "The provided object could not be marked as stale in the cache\n");
  1889. }
  1890. return 0;
  1891. }
  1892. /*!
  1893. * \internal
  1894. * \brief AMI command implementation for 'SorceryMemoryCacheStale'
  1895. */
  1896. static int sorcery_memory_cache_ami_stale(struct mansession *s, const struct message *m)
  1897. {
  1898. const char *cache_name = astman_get_header(m, "Cache");
  1899. struct sorcery_memory_cache *cache;
  1900. if (ast_strlen_zero(cache_name)) {
  1901. astman_send_error(s, m, "SorceryMemoryCacheStale requires that a cache name be provided.\n");
  1902. return 0;
  1903. }
  1904. cache = ao2_find(caches, cache_name, OBJ_SEARCH_KEY);
  1905. if (!cache) {
  1906. astman_send_error(s, m, "The provided cache does not exist\n");
  1907. return 0;
  1908. }
  1909. ao2_rdlock(cache->objects);
  1910. mark_all_as_stale_in_cache(cache);
  1911. ao2_unlock(cache->objects);
  1912. ao2_ref(cache, -1);
  1913. astman_send_ack(s, m, "All objects were marked as stale in the cache\n");
  1914. return 0;
  1915. }
  1916. /*!
  1917. * \internal
  1918. * \brief AMI command implementation for 'SorceryMemoryCachePopulate'
  1919. */
  1920. static int sorcery_memory_cache_ami_populate(struct mansession *s, const struct message *m)
  1921. {
  1922. const char *cache_name = astman_get_header(m, "Cache");
  1923. struct sorcery_memory_cache *cache;
  1924. if (ast_strlen_zero(cache_name)) {
  1925. astman_send_error(s, m, "SorceryMemoryCachePopulate requires that a cache name be provided.\n");
  1926. return 0;
  1927. }
  1928. cache = ao2_find(caches, cache_name, OBJ_SEARCH_KEY);
  1929. if (!cache) {
  1930. astman_send_error(s, m, "The provided cache does not exist\n");
  1931. return 0;
  1932. }
  1933. if (!cache->full_backend_cache) {
  1934. astman_send_error(s, m, "The provided cache does not have full backend caching enabled\n");
  1935. ao2_ref(cache, -1);
  1936. return 0;
  1937. }
  1938. ao2_wrlock(cache->objects);
  1939. if (!cache->sorcery) {
  1940. astman_send_error(s, m, "The provided cache is no longer active\n");
  1941. ao2_unlock(cache->objects);
  1942. ao2_ref(cache, -1);
  1943. return 0;
  1944. }
  1945. remove_all_from_cache(cache);
  1946. memory_cache_populate(cache->sorcery, cache->object_type, cache);
  1947. ao2_unlock(cache->objects);
  1948. ao2_ref(cache, -1);
  1949. astman_send_ack(s, m, "Cache has been expired and populated\n");
  1950. return 0;
  1951. }
  1952. #ifdef TEST_FRAMEWORK
  1953. /*! \brief Dummy sorcery object */
  1954. struct test_sorcery_object {
  1955. SORCERY_OBJECT(details);
  1956. };
  1957. /*!
  1958. * \internal
  1959. * \brief Allocator for test object
  1960. *
  1961. * \param id The identifier for the object
  1962. *
  1963. * \retval non-NULL success
  1964. * \retval NULL failure
  1965. */
  1966. static void *test_sorcery_object_alloc(const char *id)
  1967. {
  1968. return ast_sorcery_generic_alloc(sizeof(struct test_sorcery_object), NULL);
  1969. }
  1970. /*!
  1971. * \internal
  1972. * \brief Allocator for test sorcery instance
  1973. *
  1974. * \retval non-NULL success
  1975. * \retval NULL failure
  1976. */
  1977. static struct ast_sorcery *alloc_and_initialize_sorcery(void)
  1978. {
  1979. struct ast_sorcery *sorcery;
  1980. if (!(sorcery = ast_sorcery_open())) {
  1981. return NULL;
  1982. }
  1983. if ((ast_sorcery_apply_default(sorcery, "test", "memory", NULL) != AST_SORCERY_APPLY_SUCCESS) ||
  1984. ast_sorcery_internal_object_register(sorcery, "test", test_sorcery_object_alloc, NULL, NULL)) {
  1985. ast_sorcery_unref(sorcery);
  1986. return NULL;
  1987. }
  1988. return sorcery;
  1989. }
  1990. AST_TEST_DEFINE(open_with_valid_options)
  1991. {
  1992. int res = AST_TEST_PASS;
  1993. struct sorcery_memory_cache *cache;
  1994. switch (cmd) {
  1995. case TEST_INIT:
  1996. info->name = "open_with_valid_options";
  1997. info->category = "/res/res_sorcery_memory_cache/";
  1998. info->summary = "Attempt to create sorcery memory caches using valid options";
  1999. info->description = "This test performs the following:\n"
  2000. "\t* Creates a memory cache with default configuration\n"
  2001. "\t* Creates a memory cache with a maximum object count of 10 and verifies it\n"
  2002. "\t* Creates a memory cache with a maximum object lifetime of 60 and verifies it\n"
  2003. "\t* Creates a memory cache with a stale object lifetime of 90 and verifies it";
  2004. return AST_TEST_NOT_RUN;
  2005. case TEST_EXECUTE:
  2006. break;
  2007. }
  2008. cache = sorcery_memory_cache_open("");
  2009. if (!cache) {
  2010. ast_test_status_update(test, "Failed to create a sorcery memory cache using default configuration\n");
  2011. res = AST_TEST_FAIL;
  2012. } else {
  2013. sorcery_memory_cache_close(cache);
  2014. }
  2015. cache = sorcery_memory_cache_open("maximum_objects=10");
  2016. if (!cache) {
  2017. ast_test_status_update(test, "Failed to create a sorcery memory cache with a maximum object count of 10\n");
  2018. res = AST_TEST_FAIL;
  2019. } else {
  2020. if (cache->maximum_objects != 10) {
  2021. ast_test_status_update(test, "Created a sorcery memory cache with a maximum object count of 10 but it has '%u'\n",
  2022. cache->maximum_objects);
  2023. }
  2024. sorcery_memory_cache_close(cache);
  2025. }
  2026. cache = sorcery_memory_cache_open("object_lifetime_maximum=60");
  2027. if (!cache) {
  2028. ast_test_status_update(test, "Failed to create a sorcery memory cache with a maximum object lifetime of 60\n");
  2029. res = AST_TEST_FAIL;
  2030. } else {
  2031. if (cache->object_lifetime_maximum != 60) {
  2032. ast_test_status_update(test, "Created a sorcery memory cache with a maximum object lifetime of 60 but it has '%u'\n",
  2033. cache->object_lifetime_maximum);
  2034. }
  2035. sorcery_memory_cache_close(cache);
  2036. }
  2037. cache = sorcery_memory_cache_open("object_lifetime_stale=90");
  2038. if (!cache) {
  2039. ast_test_status_update(test, "Failed to create a sorcery memory cache with a stale object lifetime of 90\n");
  2040. res = AST_TEST_FAIL;
  2041. } else {
  2042. if (cache->object_lifetime_stale != 90) {
  2043. ast_test_status_update(test, "Created a sorcery memory cache with a stale object lifetime of 90 but it has '%u'\n",
  2044. cache->object_lifetime_stale);
  2045. }
  2046. sorcery_memory_cache_close(cache);
  2047. }
  2048. return res;
  2049. }
  2050. AST_TEST_DEFINE(open_with_invalid_options)
  2051. {
  2052. int res = AST_TEST_PASS;
  2053. struct sorcery_memory_cache *cache;
  2054. switch (cmd) {
  2055. case TEST_INIT:
  2056. info->name = "open_with_invalid_options";
  2057. info->category = "/res/res_sorcery_memory_cache/";
  2058. info->summary = "Attempt to create sorcery memory caches using invalid options";
  2059. info->description = "This test attempts to perform the following:\n"
  2060. "\t* Create a memory cache with an empty name\n"
  2061. "\t* Create a memory cache with a maximum object count of -1\n"
  2062. "\t* Create a memory cache with a maximum object count of toast\n"
  2063. "\t* Create a memory cache with a maximum object lifetime of -1\n"
  2064. "\t* Create a memory cache with a maximum object lifetime of toast\n"
  2065. "\t* Create a memory cache with a stale object lifetime of -1\n"
  2066. "\t* Create a memory cache with a stale object lifetime of toast";
  2067. return AST_TEST_NOT_RUN;
  2068. case TEST_EXECUTE:
  2069. break;
  2070. }
  2071. cache = sorcery_memory_cache_open("name=");
  2072. if (cache) {
  2073. ast_test_status_update(test, "Created a sorcery memory cache with an empty name\n");
  2074. sorcery_memory_cache_close(cache);
  2075. res = AST_TEST_FAIL;
  2076. }
  2077. cache = sorcery_memory_cache_open("maximum_objects=-1");
  2078. if (cache) {
  2079. ast_test_status_update(test, "Created a sorcery memory cache with a maximum object count of -1\n");
  2080. sorcery_memory_cache_close(cache);
  2081. res = AST_TEST_FAIL;
  2082. }
  2083. cache = sorcery_memory_cache_open("maximum_objects=toast");
  2084. if (cache) {
  2085. ast_test_status_update(test, "Created a sorcery memory cache with a maximum object count of toast\n");
  2086. sorcery_memory_cache_close(cache);
  2087. res = AST_TEST_FAIL;
  2088. }
  2089. cache = sorcery_memory_cache_open("object_lifetime_maximum=-1");
  2090. if (cache) {
  2091. ast_test_status_update(test, "Created a sorcery memory cache with an object lifetime maximum of -1\n");
  2092. sorcery_memory_cache_close(cache);
  2093. res = AST_TEST_FAIL;
  2094. }
  2095. cache = sorcery_memory_cache_open("object_lifetime_maximum=toast");
  2096. if (cache) {
  2097. ast_test_status_update(test, "Created a sorcery memory cache with an object lifetime maximum of toast\n");
  2098. sorcery_memory_cache_close(cache);
  2099. res = AST_TEST_FAIL;
  2100. }
  2101. cache = sorcery_memory_cache_open("object_lifetime_stale=-1");
  2102. if (cache) {
  2103. ast_test_status_update(test, "Created a sorcery memory cache with a stale object lifetime of -1\n");
  2104. sorcery_memory_cache_close(cache);
  2105. res = AST_TEST_FAIL;
  2106. }
  2107. cache = sorcery_memory_cache_open("object_lifetime_stale=toast");
  2108. if (cache) {
  2109. ast_test_status_update(test, "Created a sorcery memory cache with a stale object lifetime of toast\n");
  2110. sorcery_memory_cache_close(cache);
  2111. res = AST_TEST_FAIL;
  2112. }
  2113. cache = sorcery_memory_cache_open("tacos");
  2114. if (cache) {
  2115. ast_test_status_update(test, "Created a sorcery memory cache with an invalid configuration option 'tacos'\n");
  2116. sorcery_memory_cache_close(cache);
  2117. res = AST_TEST_FAIL;
  2118. }
  2119. return res;
  2120. }
  2121. AST_TEST_DEFINE(create_and_retrieve)
  2122. {
  2123. int res = AST_TEST_FAIL;
  2124. struct ast_sorcery *sorcery = NULL;
  2125. struct sorcery_memory_cache *cache = NULL;
  2126. RAII_VAR(void *, object, NULL, ao2_cleanup);
  2127. RAII_VAR(void *, cached_object, NULL, ao2_cleanup);
  2128. switch (cmd) {
  2129. case TEST_INIT:
  2130. info->name = "create";
  2131. info->category = "/res/res_sorcery_memory_cache/";
  2132. info->summary = "Attempt to create an object in the cache";
  2133. info->description = "This test performs the following:\n"
  2134. "\t* Creates a memory cache with default options\n"
  2135. "\t* Creates a sorcery instance with a test object\n"
  2136. "\t* Creates a test object with an id of test\n"
  2137. "\t* Pushes the test object into the memory cache\n"
  2138. "\t* Confirms that the test object is in the cache";
  2139. return AST_TEST_NOT_RUN;
  2140. case TEST_EXECUTE:
  2141. break;
  2142. }
  2143. cache = sorcery_memory_cache_open("");
  2144. if (!cache) {
  2145. ast_test_status_update(test, "Failed to create a sorcery memory cache using default options\n");
  2146. goto cleanup;
  2147. }
  2148. if (ao2_container_count(cache->objects)) {
  2149. ast_test_status_update(test, "Memory cache contains cached objects before we added one\n");
  2150. goto cleanup;
  2151. }
  2152. sorcery = alloc_and_initialize_sorcery();
  2153. if (!sorcery) {
  2154. ast_test_status_update(test, "Failed to create a test sorcery instance\n");
  2155. goto cleanup;
  2156. }
  2157. object = ast_sorcery_alloc(sorcery, "test", "test");
  2158. if (!object) {
  2159. ast_test_status_update(test, "Failed to allocate a test object\n");
  2160. goto cleanup;
  2161. }
  2162. sorcery_memory_cache_create(sorcery, cache, object);
  2163. if (!ao2_container_count(cache->objects)) {
  2164. ast_test_status_update(test, "Added test object to memory cache but cache remains empty\n");
  2165. goto cleanup;
  2166. }
  2167. cached_object = sorcery_memory_cache_retrieve_id(sorcery, cache, "test", "test");
  2168. if (!cached_object) {
  2169. ast_test_status_update(test, "Object placed into memory cache could not be retrieved\n");
  2170. goto cleanup;
  2171. }
  2172. if (cached_object != object) {
  2173. ast_test_status_update(test, "Object retrieved from memory cached is not the one we cached\n");
  2174. goto cleanup;
  2175. }
  2176. res = AST_TEST_PASS;
  2177. cleanup:
  2178. if (cache) {
  2179. sorcery_memory_cache_close(cache);
  2180. }
  2181. if (sorcery) {
  2182. ast_sorcery_unref(sorcery);
  2183. }
  2184. return res;
  2185. }
  2186. AST_TEST_DEFINE(update)
  2187. {
  2188. int res = AST_TEST_FAIL;
  2189. struct ast_sorcery *sorcery = NULL;
  2190. struct sorcery_memory_cache *cache = NULL;
  2191. RAII_VAR(void *, original_object, NULL, ao2_cleanup);
  2192. RAII_VAR(void *, updated_object, NULL, ao2_cleanup);
  2193. RAII_VAR(void *, cached_object, NULL, ao2_cleanup);
  2194. switch (cmd) {
  2195. case TEST_INIT:
  2196. info->name = "create";
  2197. info->category = "/res/res_sorcery_memory_cache/";
  2198. info->summary = "Attempt to create and then update an object in the cache";
  2199. info->description = "This test performs the following:\n"
  2200. "\t* Creates a memory cache with default options\n"
  2201. "\t* Creates a sorcery instance with a test object\n"
  2202. "\t* Creates a test object with an id of test\n"
  2203. "\t* Pushes the test object into the memory cache\n"
  2204. "\t* Confirms that the test object is in the cache\n"
  2205. "\t* Creates a new test object with the same id of test\n"
  2206. "\t* Pushes the new test object into the memory cache\n"
  2207. "\t* Confirms that the new test object has replaced the old one";
  2208. return AST_TEST_NOT_RUN;
  2209. case TEST_EXECUTE:
  2210. break;
  2211. }
  2212. cache = sorcery_memory_cache_open("");
  2213. if (!cache) {
  2214. ast_test_status_update(test, "Failed to create a sorcery memory cache using default options\n");
  2215. goto cleanup;
  2216. }
  2217. if (ao2_container_count(cache->objects)) {
  2218. ast_test_status_update(test, "Memory cache contains cached objects before we added one\n");
  2219. goto cleanup;
  2220. }
  2221. sorcery = alloc_and_initialize_sorcery();
  2222. if (!sorcery) {
  2223. ast_test_status_update(test, "Failed to create a test sorcery instance\n");
  2224. goto cleanup;
  2225. }
  2226. original_object = ast_sorcery_alloc(sorcery, "test", "test");
  2227. if (!original_object) {
  2228. ast_test_status_update(test, "Failed to allocate a test object\n");
  2229. goto cleanup;
  2230. }
  2231. sorcery_memory_cache_create(sorcery, cache, original_object);
  2232. updated_object = ast_sorcery_alloc(sorcery, "test", "test");
  2233. if (!updated_object) {
  2234. ast_test_status_update(test, "Failed to allocate an updated test object\n");
  2235. goto cleanup;
  2236. }
  2237. sorcery_memory_cache_create(sorcery, cache, updated_object);
  2238. if (ao2_container_count(cache->objects) != 1) {
  2239. ast_test_status_update(test, "Added updated test object to memory cache but cache now contains %d objects instead of 1\n",
  2240. ao2_container_count(cache->objects));
  2241. goto cleanup;
  2242. }
  2243. cached_object = sorcery_memory_cache_retrieve_id(sorcery, cache, "test", "test");
  2244. if (!cached_object) {
  2245. ast_test_status_update(test, "Updated object placed into memory cache could not be retrieved\n");
  2246. goto cleanup;
  2247. }
  2248. if (cached_object == original_object) {
  2249. ast_test_status_update(test, "Updated object placed into memory cache but old one is being retrieved\n");
  2250. goto cleanup;
  2251. } else if (cached_object != updated_object) {
  2252. ast_test_status_update(test, "Updated object placed into memory cache but different one is being retrieved\n");
  2253. goto cleanup;
  2254. }
  2255. res = AST_TEST_PASS;
  2256. cleanup:
  2257. if (cache) {
  2258. sorcery_memory_cache_close(cache);
  2259. }
  2260. if (sorcery) {
  2261. ast_sorcery_unref(sorcery);
  2262. }
  2263. return res;
  2264. }
  2265. AST_TEST_DEFINE(delete)
  2266. {
  2267. int res = AST_TEST_FAIL;
  2268. struct ast_sorcery *sorcery = NULL;
  2269. struct sorcery_memory_cache *cache = NULL;
  2270. RAII_VAR(void *, object, NULL, ao2_cleanup);
  2271. RAII_VAR(void *, cached_object, NULL, ao2_cleanup);
  2272. switch (cmd) {
  2273. case TEST_INIT:
  2274. info->name = "delete";
  2275. info->category = "/res/res_sorcery_memory_cache/";
  2276. info->summary = "Attempt to create and then delete an object in the cache";
  2277. info->description = "This test performs the following:\n"
  2278. "\t* Creates a memory cache with default options\n"
  2279. "\t* Creates a sorcery instance with a test object\n"
  2280. "\t* Creates a test object with an id of test\n"
  2281. "\t* Pushes the test object into the memory cache\n"
  2282. "\t* Confirms that the test object is in the cache\n"
  2283. "\t* Deletes the test object from the cache\n"
  2284. "\t* Confirms that the test object is no longer in the cache";
  2285. return AST_TEST_NOT_RUN;
  2286. case TEST_EXECUTE:
  2287. break;
  2288. }
  2289. cache = sorcery_memory_cache_open("");
  2290. if (!cache) {
  2291. ast_test_status_update(test, "Failed to create a sorcery memory cache using default options\n");
  2292. goto cleanup;
  2293. }
  2294. if (ao2_container_count(cache->objects)) {
  2295. ast_test_status_update(test, "Memory cache contains cached objects before we added one\n");
  2296. goto cleanup;
  2297. }
  2298. sorcery = alloc_and_initialize_sorcery();
  2299. if (!sorcery) {
  2300. ast_test_status_update(test, "Failed to create a test sorcery instance\n");
  2301. goto cleanup;
  2302. }
  2303. object = ast_sorcery_alloc(sorcery, "test", "test");
  2304. if (!object) {
  2305. ast_test_status_update(test, "Failed to allocate a test object\n");
  2306. goto cleanup;
  2307. }
  2308. sorcery_memory_cache_create(sorcery, cache, object);
  2309. if (!ao2_container_count(cache->objects)) {
  2310. ast_test_status_update(test, "Added test object to memory cache but cache contains no objects\n");
  2311. goto cleanup;
  2312. }
  2313. cached_object = sorcery_memory_cache_retrieve_id(sorcery, cache, "test", "test");
  2314. if (!cached_object) {
  2315. ast_test_status_update(test, "Test object placed into memory cache could not be retrieved\n");
  2316. goto cleanup;
  2317. }
  2318. ao2_ref(cached_object, -1);
  2319. cached_object = NULL;
  2320. sorcery_memory_cache_delete(sorcery, cache, object);
  2321. cached_object = sorcery_memory_cache_retrieve_id(sorcery, cache, "test", "test");
  2322. if (cached_object) {
  2323. ast_test_status_update(test, "Test object deleted from memory cache can still be retrieved\n");
  2324. goto cleanup;
  2325. }
  2326. res = AST_TEST_PASS;
  2327. cleanup:
  2328. if (cache) {
  2329. sorcery_memory_cache_close(cache);
  2330. }
  2331. if (sorcery) {
  2332. ast_sorcery_unref(sorcery);
  2333. }
  2334. return res;
  2335. }
  2336. static int check_cache_content(struct ast_test *test, struct ast_sorcery *sorcery, struct sorcery_memory_cache *cache,
  2337. const char **in_cache, size_t num_in_cache, const char **not_in_cache, size_t num_not_in_cache)
  2338. {
  2339. int i;
  2340. int res = 0;
  2341. RAII_VAR(void *, cached_object, NULL, ao2_cleanup);
  2342. for (i = 0; i < num_in_cache; ++i) {
  2343. cached_object = sorcery_memory_cache_retrieve_id(sorcery, cache, "test", in_cache[i]);
  2344. if (!cached_object) {
  2345. ast_test_status_update(test, "Failed to retrieve '%s' object from the cache\n",
  2346. in_cache[i]);
  2347. res = -1;
  2348. }
  2349. ao2_ref(cached_object, -1);
  2350. }
  2351. for (i = 0; i < num_not_in_cache; ++i) {
  2352. cached_object = sorcery_memory_cache_retrieve_id(sorcery, cache, "test", not_in_cache[i]);
  2353. if (cached_object) {
  2354. ast_test_status_update(test, "Retrieved '%s' object from the cache unexpectedly\n",
  2355. not_in_cache[i]);
  2356. ao2_ref(cached_object, -1);
  2357. res = -1;
  2358. }
  2359. }
  2360. return res;
  2361. }
  2362. AST_TEST_DEFINE(maximum_objects)
  2363. {
  2364. int res = AST_TEST_FAIL;
  2365. struct ast_sorcery *sorcery = NULL;
  2366. struct sorcery_memory_cache *cache = NULL;
  2367. RAII_VAR(void *, alice, NULL, ao2_cleanup);
  2368. RAII_VAR(void *, bob, NULL, ao2_cleanup);
  2369. RAII_VAR(void *, charlie, NULL, ao2_cleanup);
  2370. RAII_VAR(void *, cached_object, NULL, ao2_cleanup);
  2371. const char *in_cache[2];
  2372. const char *not_in_cache[2];
  2373. switch (cmd) {
  2374. case TEST_INIT:
  2375. info->name = "maximum_objects";
  2376. info->category = "/res/res_sorcery_memory_cache/";
  2377. info->summary = "Ensure that the 'maximum_objects' option works as expected";
  2378. info->description = "This test performs the following:\n"
  2379. "\t* Creates a memory cache with maximum_objects=2\n"
  2380. "\t* Creates a sorcery instance\n"
  2381. "\t* Creates a three test objects: alice, bob, charlie, and david\n"
  2382. "\t* Pushes alice and bob into the memory cache\n"
  2383. "\t* Confirms that alice and bob are in the memory cache\n"
  2384. "\t* Pushes charlie into the memory cache\n"
  2385. "\t* Confirms that bob and charlie are in the memory cache\n"
  2386. "\t* Deletes charlie from the memory cache\n"
  2387. "\t* Confirms that only bob is in the memory cache\n"
  2388. "\t* Pushes alice into the memory cache\n"
  2389. "\t* Confirms that bob and alice are in the memory cache";
  2390. return AST_TEST_NOT_RUN;
  2391. case TEST_EXECUTE:
  2392. break;
  2393. }
  2394. cache = sorcery_memory_cache_open("maximum_objects=2");
  2395. if (!cache) {
  2396. ast_test_status_update(test, "Failed to create a sorcery memory cache with maximum_objects=2\n");
  2397. goto cleanup;
  2398. }
  2399. if (ao2_container_count(cache->objects)) {
  2400. ast_test_status_update(test, "Memory cache contains cached objects before we added one\n");
  2401. goto cleanup;
  2402. }
  2403. sorcery = alloc_and_initialize_sorcery();
  2404. if (!sorcery) {
  2405. ast_test_status_update(test, "Failed to create a test sorcery instance\n");
  2406. goto cleanup;
  2407. }
  2408. alice = ast_sorcery_alloc(sorcery, "test", "alice");
  2409. bob = ast_sorcery_alloc(sorcery, "test", "bob");
  2410. charlie = ast_sorcery_alloc(sorcery, "test", "charlie");
  2411. if (!alice || !bob || !charlie) {
  2412. ast_test_status_update(test, "Failed to allocate sorcery object(s)\n");
  2413. goto cleanup;
  2414. }
  2415. sorcery_memory_cache_create(sorcery, cache, alice);
  2416. in_cache[0] = "alice";
  2417. in_cache[1] = NULL;
  2418. not_in_cache[0] = "bob";
  2419. not_in_cache[1] = "charlie";
  2420. if (check_cache_content(test, sorcery, cache, in_cache, 1, not_in_cache, 2)) {
  2421. goto cleanup;
  2422. }
  2423. /* Delays are added to ensure that we are not adding cache entries within the
  2424. * same microsecond
  2425. */
  2426. usleep(1000);
  2427. sorcery_memory_cache_create(sorcery, cache, bob);
  2428. in_cache[0] = "alice";
  2429. in_cache[1] = "bob";
  2430. not_in_cache[0] = "charlie";
  2431. not_in_cache[1] = NULL;
  2432. if (check_cache_content(test, sorcery, cache, in_cache, 2, not_in_cache, 1)) {
  2433. goto cleanup;
  2434. }
  2435. usleep(1000);
  2436. sorcery_memory_cache_create(sorcery, cache, charlie);
  2437. in_cache[0] = "bob";
  2438. in_cache[1] = "charlie";
  2439. not_in_cache[0] = "alice";
  2440. not_in_cache[1] = NULL;
  2441. if (check_cache_content(test, sorcery, cache, in_cache, 2, not_in_cache, 1)) {
  2442. goto cleanup;
  2443. }
  2444. usleep(1000);
  2445. sorcery_memory_cache_delete(sorcery, cache, charlie);
  2446. in_cache[0] = "bob";
  2447. in_cache[1] = NULL;
  2448. not_in_cache[0] = "alice";
  2449. not_in_cache[1] = "charlie";
  2450. if (check_cache_content(test, sorcery, cache, in_cache, 1, not_in_cache, 2)) {
  2451. goto cleanup;
  2452. }
  2453. usleep(1000);
  2454. sorcery_memory_cache_create(sorcery, cache, alice);
  2455. in_cache[0] = "bob";
  2456. in_cache[1] = "alice";
  2457. not_in_cache[0] = "charlie";
  2458. not_in_cache[1] = NULL;
  2459. if (check_cache_content(test, sorcery, cache, in_cache, 2, not_in_cache, 1)) {
  2460. goto cleanup;
  2461. }
  2462. res = AST_TEST_PASS;
  2463. cleanup:
  2464. if (cache) {
  2465. sorcery_memory_cache_close(cache);
  2466. }
  2467. if (sorcery) {
  2468. ast_sorcery_unref(sorcery);
  2469. }
  2470. return res;
  2471. }
  2472. AST_TEST_DEFINE(expiration)
  2473. {
  2474. int res = AST_TEST_FAIL;
  2475. struct ast_sorcery *sorcery = NULL;
  2476. struct sorcery_memory_cache *cache = NULL;
  2477. int i;
  2478. switch (cmd) {
  2479. case TEST_INIT:
  2480. info->name = "expiration";
  2481. info->category = "/res/res_sorcery_memory_cache/";
  2482. info->summary = "Add objects to a cache configured with maximum lifetime, confirm they are removed";
  2483. info->description = "This test performs the following:\n"
  2484. "\t* Creates a memory cache with a maximum object lifetime of 5 seconds\n"
  2485. "\t* Pushes 10 objects into the memory cache\n"
  2486. "\t* Waits (up to) 10 seconds for expiration to occur\n"
  2487. "\t* Confirms that the objects have been removed from the cache";
  2488. return AST_TEST_NOT_RUN;
  2489. case TEST_EXECUTE:
  2490. break;
  2491. }
  2492. cache = sorcery_memory_cache_open("object_lifetime_maximum=5");
  2493. if (!cache) {
  2494. ast_test_status_update(test, "Failed to create a sorcery memory cache using default options\n");
  2495. goto cleanup;
  2496. }
  2497. sorcery = alloc_and_initialize_sorcery();
  2498. if (!sorcery) {
  2499. ast_test_status_update(test, "Failed to create a test sorcery instance\n");
  2500. goto cleanup;
  2501. }
  2502. cache->cache_notify = 1;
  2503. ast_mutex_init(&cache->lock);
  2504. ast_cond_init(&cache->cond, NULL);
  2505. for (i = 0; i < 5; ++i) {
  2506. char uuid[AST_UUID_STR_LEN];
  2507. void *object;
  2508. object = ast_sorcery_alloc(sorcery, "test", ast_uuid_generate_str(uuid, sizeof(uuid)));
  2509. if (!object) {
  2510. ast_test_status_update(test, "Failed to allocate test object for expiration\n");
  2511. goto cleanup;
  2512. }
  2513. sorcery_memory_cache_create(sorcery, cache, object);
  2514. ao2_ref(object, -1);
  2515. }
  2516. ast_mutex_lock(&cache->lock);
  2517. while (!cache->cache_completed) {
  2518. struct timeval start = ast_tvnow();
  2519. struct timespec end = {
  2520. .tv_sec = start.tv_sec + 10,
  2521. .tv_nsec = start.tv_usec * 1000,
  2522. };
  2523. if (ast_cond_timedwait(&cache->cond, &cache->lock, &end) == ETIMEDOUT) {
  2524. break;
  2525. }
  2526. }
  2527. ast_mutex_unlock(&cache->lock);
  2528. if (ao2_container_count(cache->objects)) {
  2529. ast_test_status_update(test, "Objects placed into the memory cache did not expire and get removed\n");
  2530. goto cleanup;
  2531. }
  2532. res = AST_TEST_PASS;
  2533. cleanup:
  2534. if (cache) {
  2535. if (cache->cache_notify) {
  2536. ast_cond_destroy(&cache->cond);
  2537. ast_mutex_destroy(&cache->lock);
  2538. }
  2539. sorcery_memory_cache_close(cache);
  2540. }
  2541. if (sorcery) {
  2542. ast_sorcery_unref(sorcery);
  2543. }
  2544. return res;
  2545. }
  2546. /*!
  2547. * \brief Backend data that the mock sorcery wizard uses to create objects
  2548. */
  2549. static struct backend_data {
  2550. /*! An arbitrary data field */
  2551. int salt;
  2552. /*! Another arbitrary data field */
  2553. int pepper;
  2554. /*! Indicates whether the backend has data */
  2555. int exists;
  2556. } *real_backend_data;
  2557. /*!
  2558. * \brief Sorcery object created based on backend data
  2559. */
  2560. struct test_data {
  2561. SORCERY_OBJECT(details);
  2562. /*! Mirrors the backend data's salt field */
  2563. int salt;
  2564. /*! Mirrors the backend data's pepper field */
  2565. int pepper;
  2566. };
  2567. /*!
  2568. * \brief Allocation callback for test_data sorcery object
  2569. */
  2570. static void *test_data_alloc(const char *id) {
  2571. return ast_sorcery_generic_alloc(sizeof(struct test_data), NULL);
  2572. }
  2573. /*!
  2574. * \brief Callback for retrieving sorcery object by ID
  2575. *
  2576. * The mock wizard uses the \ref real_backend_data in order to construct
  2577. * objects. If the backend data is "nonexisent" then no object is returned.
  2578. * Otherwise, an object is created that has the backend data's salt and
  2579. * pepper values copied.
  2580. *
  2581. * \param sorcery The sorcery instance
  2582. * \param data Unused
  2583. * \param type The object type. Will always be "test".
  2584. * \param id The object id. Will always be "test".
  2585. *
  2586. * \retval NULL Backend data does not exist
  2587. * \retval non-NULL An object representing the backend data
  2588. */
  2589. static void *mock_retrieve_id(const struct ast_sorcery *sorcery, void *data,
  2590. const char *type, const char *id)
  2591. {
  2592. struct test_data *b_data;
  2593. if (!real_backend_data->exists) {
  2594. return NULL;
  2595. }
  2596. b_data = ast_sorcery_alloc(sorcery, type, id);
  2597. if (!b_data) {
  2598. return NULL;
  2599. }
  2600. b_data->salt = real_backend_data->salt;
  2601. b_data->pepper = real_backend_data->pepper;
  2602. return b_data;
  2603. }
  2604. /*!
  2605. * \brief Callback for retrieving multiple sorcery objects
  2606. *
  2607. * The mock wizard uses the \ref real_backend_data in order to construct
  2608. * objects. If the backend data is "nonexisent" then no object is returned.
  2609. * Otherwise, the number of objects matching the exists value will be returned.
  2610. *
  2611. * \param sorcery The sorcery instance
  2612. * \param data Unused
  2613. * \param type The object type. Will always be "test".
  2614. * \param objects Container to place objects into.
  2615. * \param fields Fields to search for.
  2616. */
  2617. static void mock_retrieve_multiple(const struct ast_sorcery *sorcery, void *data,
  2618. const char *type, struct ao2_container *objects, const struct ast_variable *fields)
  2619. {
  2620. int i;
  2621. if (fields) {
  2622. return;
  2623. }
  2624. for (i = 0; i < real_backend_data->exists; ++i) {
  2625. char uuid[AST_UUID_STR_LEN];
  2626. struct test_data *b_data;
  2627. b_data = ast_sorcery_alloc(sorcery, type, ast_uuid_generate_str(uuid, sizeof(uuid)));
  2628. if (!b_data) {
  2629. continue;
  2630. }
  2631. b_data->salt = real_backend_data->salt;
  2632. b_data->pepper = real_backend_data->pepper;
  2633. ao2_link(objects, b_data);
  2634. ao2_ref(b_data, -1);
  2635. }
  2636. }
  2637. /*!
  2638. * \brief A mock sorcery wizard used for the stale test
  2639. */
  2640. static struct ast_sorcery_wizard mock_wizard = {
  2641. .name = "mock",
  2642. .retrieve_id = mock_retrieve_id,
  2643. .retrieve_multiple = mock_retrieve_multiple,
  2644. };
  2645. /*!
  2646. * \brief Wait for the cache to be updated after a stale object is retrieved.
  2647. *
  2648. * Since the cache does not know what type of objects it is dealing with, and
  2649. * since we do not have the internals of the cache, the only way to make this
  2650. * determination is to continuously retrieve an object from the cache until
  2651. * we retrieve a different object than we had previously retrieved.
  2652. *
  2653. * \param sorcery The sorcery instance
  2654. * \param previous_object The object we had previously retrieved from the cache
  2655. * \param[out] new_object The new object we retrieve from the cache
  2656. *
  2657. * \retval 0 Successfully retrieved a new object from the cache
  2658. * \retval non-zero Failed to retrieve a new object from the cache
  2659. */
  2660. static int wait_for_cache_update(const struct ast_sorcery *sorcery,
  2661. void *previous_object, struct test_data **new_object)
  2662. {
  2663. struct timeval start = ast_tvnow();
  2664. while (ast_remaining_ms(start, 5000) > 0) {
  2665. void *object;
  2666. object = ast_sorcery_retrieve_by_id(sorcery, "test", "test");
  2667. if (object != previous_object) {
  2668. *new_object = object;
  2669. return 0;
  2670. }
  2671. ao2_cleanup(object);
  2672. }
  2673. return -1;
  2674. }
  2675. AST_TEST_DEFINE(stale)
  2676. {
  2677. int res = AST_TEST_FAIL;
  2678. struct ast_sorcery *sorcery = NULL;
  2679. struct test_data *backend_object;
  2680. struct backend_data iterations[] = {
  2681. { .salt = 1, .pepper = 2, .exists = 1 },
  2682. { .salt = 568729, .pepper = -234123, .exists = 1 },
  2683. { .salt = 0, .pepper = 0, .exists = 0 },
  2684. };
  2685. struct backend_data initial = {
  2686. .salt = 0,
  2687. .pepper = 0,
  2688. .exists = 1,
  2689. };
  2690. int i;
  2691. switch (cmd) {
  2692. case TEST_INIT:
  2693. info->name = "stale";
  2694. info->category = "/res/res_sorcery_memory_cache/";
  2695. info->summary = "Ensure that stale objects are replaced with updated objects";
  2696. info->description = "This test performs the following:\n"
  2697. "\t* Create a sorcery instance with two wizards"
  2698. "\t\t* The first is a memory cache that marks items stale after 3 seconds\n"
  2699. "\t\t* The second is a mock of a back-end\n"
  2700. "\t* Pre-populates the cache by retrieving some initial data from the backend.\n"
  2701. "\t* Performs iterations of the following:\n"
  2702. "\t\t* Update backend data with new values\n"
  2703. "\t\t* Retrieve item from the cache\n"
  2704. "\t\t* Ensure the retrieved item does not have the new backend values\n"
  2705. "\t\t* Wait for cached object to become stale\n"
  2706. "\t\t* Retrieve the stale cached object\n"
  2707. "\t\t* Ensure that the stale object retrieved is the same as the fresh one from earlier\n"
  2708. "\t\t* Wait for the cache to update with new data\n"
  2709. "\t\t* Ensure that new data in the cache matches backend data";
  2710. return AST_TEST_NOT_RUN;
  2711. case TEST_EXECUTE:
  2712. break;
  2713. }
  2714. ast_sorcery_wizard_register(&mock_wizard);
  2715. sorcery = ast_sorcery_open();
  2716. if (!sorcery) {
  2717. ast_test_status_update(test, "Failed to create sorcery instance\n");
  2718. goto cleanup;
  2719. }
  2720. ast_sorcery_apply_wizard_mapping(sorcery, "test", "memory_cache",
  2721. "object_lifetime_stale=3", 1);
  2722. ast_sorcery_apply_wizard_mapping(sorcery, "test", "mock", NULL, 0);
  2723. ast_sorcery_internal_object_register(sorcery, "test", test_data_alloc, NULL, NULL);
  2724. /* Prepopulate the cache */
  2725. real_backend_data = &initial;
  2726. backend_object = ast_sorcery_retrieve_by_id(sorcery, "test", "test");
  2727. if (!backend_object) {
  2728. ast_test_status_update(test, "Unable to retrieve backend data and populate the cache\n");
  2729. goto cleanup;
  2730. }
  2731. ao2_ref(backend_object, -1);
  2732. for (i = 0; i < ARRAY_LEN(iterations); ++i) {
  2733. RAII_VAR(struct test_data *, cache_fresh, NULL, ao2_cleanup);
  2734. RAII_VAR(struct test_data *, cache_stale, NULL, ao2_cleanup);
  2735. RAII_VAR(struct test_data *, cache_new, NULL, ao2_cleanup);
  2736. real_backend_data = &iterations[i];
  2737. ast_test_status_update(test, "Begininning iteration %d\n", i);
  2738. cache_fresh = ast_sorcery_retrieve_by_id(sorcery, "test", "test");
  2739. if (!cache_fresh) {
  2740. ast_test_status_update(test, "Unable to retrieve fresh cached object\n");
  2741. goto cleanup;
  2742. }
  2743. if (cache_fresh->salt == iterations[i].salt || cache_fresh->pepper == iterations[i].pepper) {
  2744. ast_test_status_update(test, "Fresh cached object has unexpected values. Did we hit the backend?\n");
  2745. goto cleanup;
  2746. }
  2747. sleep(5);
  2748. cache_stale = ast_sorcery_retrieve_by_id(sorcery, "test", "test");
  2749. if (!cache_stale) {
  2750. ast_test_status_update(test, "Unable to retrieve stale cached object\n");
  2751. goto cleanup;
  2752. }
  2753. if (cache_stale != cache_fresh) {
  2754. ast_test_status_update(test, "Stale cache hit retrieved different object than fresh cache hit\n");
  2755. goto cleanup;
  2756. }
  2757. if (wait_for_cache_update(sorcery, cache_stale, &cache_new)) {
  2758. ast_test_status_update(test, "Cache was not updated\n");
  2759. goto cleanup;
  2760. }
  2761. if (iterations[i].exists) {
  2762. if (!cache_new) {
  2763. ast_test_status_update(test, "Failed to retrieve item from cache when there should be one present\n");
  2764. goto cleanup;
  2765. } else if (cache_new->salt != iterations[i].salt ||
  2766. cache_new->pepper != iterations[i].pepper) {
  2767. ast_test_status_update(test, "New cached item has unexpected values\n");
  2768. goto cleanup;
  2769. }
  2770. } else if (cache_new) {
  2771. ast_test_status_update(test, "Retrieved a cached item when there should not have been one present\n");
  2772. goto cleanup;
  2773. }
  2774. }
  2775. res = AST_TEST_PASS;
  2776. cleanup:
  2777. if (sorcery) {
  2778. ast_sorcery_unref(sorcery);
  2779. }
  2780. ast_sorcery_wizard_unregister(&mock_wizard);
  2781. return res;
  2782. }
  2783. AST_TEST_DEFINE(full_backend_cache_expiration)
  2784. {
  2785. int res = AST_TEST_FAIL;
  2786. struct ast_sorcery *sorcery = NULL;
  2787. struct backend_data initial = {
  2788. .salt = 0,
  2789. .pepper = 0,
  2790. .exists = 4,
  2791. };
  2792. struct ao2_container *objects;
  2793. ast_mutex_t lock;
  2794. ast_cond_t cond;
  2795. struct timeval start;
  2796. struct timespec end;
  2797. switch (cmd) {
  2798. case TEST_INIT:
  2799. info->name = "full_backend_cache_expiration";
  2800. info->category = "/res/res_sorcery_memory_cache/";
  2801. info->summary = "Ensure that the full backend cache actually caches the backend";
  2802. info->description = "This test performs the following:\n"
  2803. "\t* Create a sorcery instance with two wizards"
  2804. "\t\t* The first is a memory cache that expires objects after 3 seconds and does full backend caching\n"
  2805. "\t\t* The second is a mock of a back-end\n"
  2806. "\t* Populates the cache by requesting all objects which returns 4.\n"
  2807. "\t* Updates the backend to contain a different number of objects, 8.\n"
  2808. "\t* Requests all objects and confirms the number returned is only 4.\n"
  2809. "\t* Wait for cached objects to expire.\n"
  2810. "\t* Requests all objects and confirms the number returned is 8.";
  2811. return AST_TEST_NOT_RUN;
  2812. case TEST_EXECUTE:
  2813. break;
  2814. }
  2815. ast_sorcery_wizard_register(&mock_wizard);
  2816. sorcery = ast_sorcery_open();
  2817. if (!sorcery) {
  2818. ast_test_status_update(test, "Failed to create sorcery instance\n");
  2819. goto cleanup;
  2820. }
  2821. ast_sorcery_apply_wizard_mapping(sorcery, "test", "memory_cache",
  2822. "object_lifetime_maximum=3,full_backend_cache=yes", 1);
  2823. ast_sorcery_apply_wizard_mapping(sorcery, "test", "mock", NULL, 0);
  2824. ast_sorcery_internal_object_register(sorcery, "test", test_data_alloc, NULL, NULL);
  2825. ast_sorcery_object_field_register_nodoc(sorcery, "test", "salt", "0", OPT_UINT_T, 0, FLDSET(struct test_data, salt));
  2826. ast_sorcery_object_field_register_nodoc(sorcery, "test", "pepper", "0", OPT_UINT_T, 0, FLDSET(struct test_data, pepper));
  2827. /* Prepopulate the cache */
  2828. real_backend_data = &initial;
  2829. /* Get all current objects in the backend */
  2830. objects = ast_sorcery_retrieve_by_fields(sorcery, "test", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  2831. if (!objects) {
  2832. ast_test_status_update(test, "Unable to retrieve all objects in backend and populate cache\n");
  2833. goto cleanup;
  2834. }
  2835. ao2_ref(objects, -1);
  2836. /* Update the backend to have a different number of objects */
  2837. initial.exists = 8;
  2838. /* Get all current objects in the backend */
  2839. objects = ast_sorcery_retrieve_by_fields(sorcery, "test", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  2840. if (!objects) {
  2841. ast_test_status_update(test, "Unable to retrieve all objects in backend and populate cache\n");
  2842. goto cleanup;
  2843. }
  2844. if (ao2_container_count(objects) == initial.exists) {
  2845. ast_test_status_update(test, "Number of objects returned is of the current backend and not the cache\n");
  2846. ao2_ref(objects, -1);
  2847. goto cleanup;
  2848. }
  2849. ao2_ref(objects, -1);
  2850. ast_mutex_init(&lock);
  2851. ast_cond_init(&cond, NULL);
  2852. start = ast_tvnow();
  2853. end.tv_sec = start.tv_sec + 5;
  2854. end.tv_nsec = start.tv_usec * 1000;
  2855. ast_mutex_lock(&lock);
  2856. while (ast_cond_timedwait(&cond, &lock, &end) != ETIMEDOUT) {
  2857. }
  2858. ast_mutex_unlock(&lock);
  2859. ast_mutex_destroy(&lock);
  2860. ast_cond_destroy(&cond);
  2861. /* Get all current objects in the backend */
  2862. objects = ast_sorcery_retrieve_by_fields(sorcery, "test", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  2863. if (!objects) {
  2864. ast_test_status_update(test, "Unable to retrieve all objects in backend and populate cache\n");
  2865. goto cleanup;
  2866. }
  2867. if (ao2_container_count(objects) != initial.exists) {
  2868. ast_test_status_update(test, "Number of objects returned is NOT of the current backend when it should be\n");
  2869. ao2_ref(objects, -1);
  2870. goto cleanup;
  2871. }
  2872. ao2_ref(objects, -1);
  2873. res = AST_TEST_PASS;
  2874. cleanup:
  2875. if (sorcery) {
  2876. ast_sorcery_unref(sorcery);
  2877. }
  2878. ast_sorcery_wizard_unregister(&mock_wizard);
  2879. return res;
  2880. }
  2881. AST_TEST_DEFINE(full_backend_cache_stale)
  2882. {
  2883. int res = AST_TEST_FAIL;
  2884. struct ast_sorcery *sorcery = NULL;
  2885. struct backend_data initial = {
  2886. .salt = 0,
  2887. .pepper = 0,
  2888. .exists = 4,
  2889. };
  2890. struct ao2_container *objects;
  2891. ast_mutex_t lock;
  2892. ast_cond_t cond;
  2893. struct timeval start;
  2894. struct timespec end;
  2895. switch (cmd) {
  2896. case TEST_INIT:
  2897. info->name = "full_backend_cache_stale";
  2898. info->category = "/res/res_sorcery_memory_cache/";
  2899. info->summary = "Ensure that the full backend cache works with staleness";
  2900. info->description = "This test performs the following:\n"
  2901. "\t* Create a sorcery instance with two wizards"
  2902. "\t\t* The first is a memory cache that stales objects after 1 second and does full backend caching\n"
  2903. "\t\t* The second is a mock of a back-end\n"
  2904. "\t* Populates the cache by requesting all objects which returns 4.\n"
  2905. "\t* Wait for objects to go stale.\n"
  2906. "\t* Updates the backend to contain a different number of objects, 8.\""
  2907. "\t* Requests all objects and confirms the number returned is only 4.\n"
  2908. "\t* Wait for objects to be refreshed from backend.\n"
  2909. "\t* Requests all objects and confirms the number returned is 8.";
  2910. return AST_TEST_NOT_RUN;
  2911. case TEST_EXECUTE:
  2912. break;
  2913. }
  2914. ast_sorcery_wizard_register(&mock_wizard);
  2915. ast_mutex_init(&lock);
  2916. ast_cond_init(&cond, NULL);
  2917. sorcery = ast_sorcery_open();
  2918. if (!sorcery) {
  2919. ast_test_status_update(test, "Failed to create sorcery instance\n");
  2920. goto cleanup;
  2921. }
  2922. ast_sorcery_apply_wizard_mapping(sorcery, "test", "memory_cache",
  2923. "object_lifetime_stale=1,full_backend_cache=yes", 1);
  2924. ast_sorcery_apply_wizard_mapping(sorcery, "test", "mock", NULL, 0);
  2925. ast_sorcery_internal_object_register(sorcery, "test", test_data_alloc, NULL, NULL);
  2926. ast_sorcery_object_field_register_nodoc(sorcery, "test", "salt", "0", OPT_UINT_T, 0, FLDSET(struct test_data, salt));
  2927. ast_sorcery_object_field_register_nodoc(sorcery, "test", "pepper", "0", OPT_UINT_T, 0, FLDSET(struct test_data, pepper));
  2928. /* Prepopulate the cache */
  2929. real_backend_data = &initial;
  2930. /* Get all current objects in the backend */
  2931. objects = ast_sorcery_retrieve_by_fields(sorcery, "test", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  2932. if (!objects) {
  2933. ast_test_status_update(test, "Unable to retrieve all objects in backend and populate cache\n");
  2934. goto cleanup;
  2935. }
  2936. ao2_ref(objects, -1);
  2937. start = ast_tvnow();
  2938. end.tv_sec = start.tv_sec + 5;
  2939. end.tv_nsec = start.tv_usec * 1000;
  2940. ast_mutex_lock(&lock);
  2941. while (ast_cond_timedwait(&cond, &lock, &end) != ETIMEDOUT) {
  2942. }
  2943. ast_mutex_unlock(&lock);
  2944. initial.exists = 8;
  2945. /* Get all current objects in the backend */
  2946. objects = ast_sorcery_retrieve_by_fields(sorcery, "test", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  2947. if (!objects) {
  2948. ast_test_status_update(test, "Unable to retrieve all objects in backend and populate cache\n");
  2949. goto cleanup;
  2950. }
  2951. if (ao2_container_count(objects) == initial.exists) {
  2952. ast_test_status_update(test, "Number of objects returned is of the backend and not the cache\n");
  2953. ao2_ref(objects, -1);
  2954. goto cleanup;
  2955. }
  2956. ao2_ref(objects, -1);
  2957. start = ast_tvnow();
  2958. end.tv_sec = start.tv_sec + 5;
  2959. end.tv_nsec = start.tv_usec * 1000;
  2960. ast_mutex_lock(&lock);
  2961. while (ast_cond_timedwait(&cond, &lock, &end) != ETIMEDOUT) {
  2962. }
  2963. ast_mutex_unlock(&lock);
  2964. /* Get all current objects in the backend */
  2965. objects = ast_sorcery_retrieve_by_fields(sorcery, "test", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  2966. if (!objects) {
  2967. ast_test_status_update(test, "Unable to retrieve all objects in backend and populate cache\n");
  2968. goto cleanup;
  2969. }
  2970. if (ao2_container_count(objects) != initial.exists) {
  2971. ast_test_status_update(test, "Number of objects returned is not of backend\n");
  2972. ao2_ref(objects, -1);
  2973. goto cleanup;
  2974. }
  2975. ao2_ref(objects, -1);
  2976. start = ast_tvnow();
  2977. end.tv_sec = start.tv_sec + 5;
  2978. end.tv_nsec = start.tv_usec * 1000;
  2979. ast_mutex_lock(&lock);
  2980. while (ast_cond_timedwait(&cond, &lock, &end) != ETIMEDOUT) {
  2981. }
  2982. ast_mutex_unlock(&lock);
  2983. res = AST_TEST_PASS;
  2984. cleanup:
  2985. if (sorcery) {
  2986. ast_sorcery_unref(sorcery);
  2987. }
  2988. ast_sorcery_wizard_unregister(&mock_wizard);
  2989. ast_mutex_destroy(&lock);
  2990. ast_cond_destroy(&cond);
  2991. return res;
  2992. }
  2993. #endif
  2994. static int unload_module(void)
  2995. {
  2996. AST_TEST_UNREGISTER(open_with_valid_options);
  2997. AST_TEST_UNREGISTER(open_with_invalid_options);
  2998. AST_TEST_UNREGISTER(create_and_retrieve);
  2999. AST_TEST_UNREGISTER(update);
  3000. AST_TEST_UNREGISTER(delete);
  3001. AST_TEST_UNREGISTER(maximum_objects);
  3002. AST_TEST_UNREGISTER(expiration);
  3003. AST_TEST_UNREGISTER(stale);
  3004. AST_TEST_UNREGISTER(full_backend_cache_expiration);
  3005. AST_TEST_UNREGISTER(full_backend_cache_stale);
  3006. ast_manager_unregister("SorceryMemoryCacheExpireObject");
  3007. ast_manager_unregister("SorceryMemoryCacheExpire");
  3008. ast_manager_unregister("SorceryMemoryCacheStaleObject");
  3009. ast_manager_unregister("SorceryMemoryCacheStale");
  3010. ast_manager_unregister("SorceryMemoryCachePopulate");
  3011. ast_cli_unregister_multiple(cli_memory_cache, ARRAY_LEN(cli_memory_cache));
  3012. ast_sorcery_wizard_unregister(&memory_cache_object_wizard);
  3013. /*
  3014. * XXX There is the potential to leak memory if there are pending
  3015. * next-cache-expiration and stale-cache-update tasks in the scheduler.
  3016. */
  3017. if (sched) {
  3018. ast_sched_context_destroy(sched);
  3019. sched = NULL;
  3020. }
  3021. ao2_cleanup(caches);
  3022. caches = NULL;
  3023. return 0;
  3024. }
  3025. static int load_module(void)
  3026. {
  3027. int res;
  3028. caches = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
  3029. CACHES_CONTAINER_BUCKET_SIZE, sorcery_memory_cache_hash, NULL,
  3030. sorcery_memory_cache_cmp);
  3031. if (!caches) {
  3032. ast_log(LOG_ERROR, "Failed to create container for configured caches\n");
  3033. unload_module();
  3034. return AST_MODULE_LOAD_DECLINE;
  3035. }
  3036. sched = ast_sched_context_create();
  3037. if (!sched) {
  3038. ast_log(LOG_ERROR, "Failed to create scheduler for cache management\n");
  3039. unload_module();
  3040. return AST_MODULE_LOAD_DECLINE;
  3041. }
  3042. if (ast_sched_start_thread(sched)) {
  3043. ast_log(LOG_ERROR, "Failed to create scheduler thread for cache management\n");
  3044. unload_module();
  3045. return AST_MODULE_LOAD_DECLINE;
  3046. }
  3047. if (ast_sorcery_wizard_register(&memory_cache_object_wizard)) {
  3048. unload_module();
  3049. return AST_MODULE_LOAD_DECLINE;
  3050. }
  3051. res = ast_cli_register_multiple(cli_memory_cache, ARRAY_LEN(cli_memory_cache));
  3052. res |= ast_manager_register_xml("SorceryMemoryCacheExpireObject", EVENT_FLAG_SYSTEM, sorcery_memory_cache_ami_expire_object);
  3053. res |= ast_manager_register_xml("SorceryMemoryCacheExpire", EVENT_FLAG_SYSTEM, sorcery_memory_cache_ami_expire);
  3054. res |= ast_manager_register_xml("SorceryMemoryCacheStaleObject", EVENT_FLAG_SYSTEM, sorcery_memory_cache_ami_stale_object);
  3055. res |= ast_manager_register_xml("SorceryMemoryCacheStale", EVENT_FLAG_SYSTEM, sorcery_memory_cache_ami_stale);
  3056. res |= ast_manager_register_xml("SorceryMemoryCachePopulate", EVENT_FLAG_SYSTEM, sorcery_memory_cache_ami_populate);
  3057. if (res) {
  3058. unload_module();
  3059. return AST_MODULE_LOAD_DECLINE;
  3060. }
  3061. /* This causes the stale unit test to execute last, so if a sorcery instance persists
  3062. * longer than expected subsequent unit tests don't fail when setting it up.
  3063. */
  3064. AST_TEST_REGISTER(stale);
  3065. AST_TEST_REGISTER(open_with_valid_options);
  3066. AST_TEST_REGISTER(open_with_invalid_options);
  3067. AST_TEST_REGISTER(create_and_retrieve);
  3068. AST_TEST_REGISTER(update);
  3069. AST_TEST_REGISTER(delete);
  3070. AST_TEST_REGISTER(maximum_objects);
  3071. AST_TEST_REGISTER(expiration);
  3072. AST_TEST_REGISTER(full_backend_cache_expiration);
  3073. AST_TEST_REGISTER(full_backend_cache_stale);
  3074. return AST_MODULE_LOAD_SUCCESS;
  3075. }
  3076. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Sorcery Memory Cache Object Wizard",
  3077. .support_level = AST_MODULE_SUPPORT_CORE,
  3078. .load = load_module,
  3079. .unload = unload_module,
  3080. .load_pri = AST_MODPRI_REALTIME_DRIVER,
  3081. );