2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2006 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
37 /* query cache structs */
40 typedef struct Query_s {
41 Filter* filter; /* Search Filter */
42 struct berval base; /* Search Base */
43 int scope; /* Search scope */
46 struct query_template_s;
48 /* struct representing a cached query */
49 typedef struct cached_query_s {
50 Query query; /* LDAP query */
51 struct berval q_uuid; /* query identifier */
52 struct query_template_s *qtemp; /* template of the query */
53 time_t expiry_time; /* time till the query is considered valid */
54 struct cached_query_s *next; /* next query in the template */
55 struct cached_query_s *prev; /* previous query in the template */
56 struct cached_query_s *lru_up; /* previous query in the LRU list */
57 struct cached_query_s *lru_down; /* next query in the LRU list */
61 * Represents a set of projected attributes.
65 struct query_template_s *templates;
66 AttributeName* attrs; /* specifies the set */
68 #define PC_CONFIGURED (0x1)
69 #define PC_REFERENCED (0x2)
70 #define PC_GOT_OC (0x4)
71 int count; /* number of attributes */
74 /* struct representing a query template
75 * e.g. template string = &(cn=)(mail=)
77 typedef struct query_template_s {
78 struct query_template_s *qtnext;
79 struct query_template_s *qmnext;
81 CachedQuery* query; /* most recent query cached for the template */
82 CachedQuery* query_last; /* oldest query cached for the template */
83 ldap_pvt_thread_rdwr_t *t_rwlock; /* Rd/wr lock for accessing queries in the template */
84 struct berval querystr; /* Filter string corresponding to the QT */
86 int attr_set_index; /* determines the projected attributes */
87 int no_of_queries; /* Total number of queries in the template */
88 time_t ttl; /* TTL for the queries of this template */
89 time_t negttl; /* TTL for negative results */
90 struct attr_set t_attrs; /* filter attrs + attr_set */
93 struct query_manager_s;
95 /* prototypes for functions for 1) query containment
96 * 2) query addition, 3) cache replacement
98 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
99 typedef void (AddQueryfunc)(struct query_manager_s*, Query*, QueryTemplate*, struct berval*);
100 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
102 /* LDAP query cache */
103 typedef struct query_manager_s {
104 struct attr_set* attr_sets; /* possible sets of projected attributes */
105 QueryTemplate* templates; /* cacheable templates */
107 CachedQuery* lru_top; /* top and bottom of LRU list */
108 CachedQuery* lru_bottom;
110 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
112 /* Query cache methods */
113 QCfunc *qcfunc; /* Query containment*/
114 CRfunc *crfunc; /* cache replacement */
115 AddQueryfunc *addfunc; /* add query */
118 /* LDAP query cache manager */
119 typedef struct cache_manager_s {
120 BackendDB db; /* underlying database */
121 unsigned long num_cached_queries; /* total number of cached queries */
122 unsigned long max_queries; /* upper bound on # of cached queries */
123 int numattrsets; /* number of attribute sets */
124 int cur_entries; /* current number of entries cached */
125 int max_entries; /* max number of entries cached */
126 int num_entries_limit; /* max # of entries in a cacheable query */
128 char response_cb; /* install the response callback
129 * at the tail of the callback list */
130 #define PCACHE_RESPONSE_CB_HEAD 0
131 #define PCACHE_RESPONSE_CB_TAIL 1
133 time_t cc_period; /* interval between successive consistency checks (sec) */
137 ldap_pvt_thread_mutex_t cache_mutex;
139 query_manager* qm; /* query cache managed by the cache manager */
142 static int pcache_debug;
144 static AttributeDescription *ad_queryid;
145 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
146 "DESC 'list of queries the entry belongs to' "
147 "EQUALITY octetStringMatch "
148 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
149 "NO-USER-MODIFICATION USAGE directoryOperation )";
151 /* Return 1 for an added entry, else 0 */
156 struct berval* query_uuid )
159 Modifications* modlist = NULL;
160 const char* text = NULL;
162 char textbuf[SLAP_TEXT_BUFLEN];
163 size_t textlen = sizeof(textbuf);
165 SlapReply sreply = {REP_RESULT};
167 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
172 /* add queryid attribute */
173 attr_merge_one( e, ad_queryid, query_uuid, NULL );
175 /* append the attribute list from the fetched entry */
176 e->e_attrs->a_next = attr;
178 op->o_tag = LDAP_REQ_ADD;
179 op->o_protocol = LDAP_VERSION3;
180 op->o_callback = &cb;
181 op->o_time = slap_get_time();
182 op->o_do_not_cache = 1;
185 op->o_req_dn = e->e_name;
186 op->o_req_ndn = e->e_nname;
187 rc = op->o_bd->be_add( op, &sreply );
189 if ( rc != LDAP_SUCCESS ) {
190 if ( rc == LDAP_ALREADY_EXISTS ) {
191 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
192 modlist->sml_op = LDAP_MOD_ADD;
193 op->o_tag = LDAP_REQ_MODIFY;
194 op->orm_modlist = modlist;
195 op->o_bd->be_modify( op, &sreply );
196 slap_mods_free( modlist, 1 );
197 } else if ( rc == LDAP_REFERRAL ||
198 rc == LDAP_NO_SUCH_OBJECT ) {
199 syncrepl_add_glue( op, e );
208 be_entry_release_w( op, e );
215 /* compare base and scope of incoming and cached queries */
216 static int base_scope_compare(
217 struct berval* ndn_stored,
218 struct berval* ndn_incoming,
222 struct berval pdn_incoming = BER_BVNULL;
224 if (scope_stored < scope_incoming)
227 if ( !dnIsSuffix(ndn_incoming, ndn_stored))
230 switch(scope_stored) {
231 case LDAP_SCOPE_BASE:
232 return (ndn_incoming->bv_len == ndn_stored->bv_len);
234 case LDAP_SCOPE_ONELEVEL:
235 switch(scope_incoming){
236 case LDAP_SCOPE_BASE:
237 dnParent(ndn_incoming, &pdn_incoming);
238 return (pdn_incoming.bv_len == ndn_stored->bv_len);
240 case LDAP_SCOPE_ONELEVEL:
241 return (ndn_incoming->bv_len == ndn_stored->bv_len);
246 case LDAP_SCOPE_SUBTREE:
255 /* add query on top of LRU list */
257 add_query_on_top (query_manager* qm, CachedQuery* qc)
259 CachedQuery* top = qm->lru_top;
260 Query* q = (Query*)qc;
271 Debug( pcache_debug, "Base of added query = %s\n",
272 q->base.bv_val, 0, 0 );
275 /* remove_query from LRU list */
278 remove_query (query_manager* qm, CachedQuery* qc)
301 qc->lru_up = qc->lru_down = NULL;
304 /* find and remove string2 from string1
305 * from start if position = 1,
306 * from end if position = 3,
307 * from anywhere if position = 2
308 * string1 is overwritten if position = 2.
312 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
323 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
324 ber2->bv_val, ber2->bv_len )) {
326 ber1->bv_val += ber2->bv_len;
327 ber1->bv_len -= ber2->bv_len;
332 ber1->bv_val[ber1->bv_len] = '\0';
333 temp = strstr( ber1->bv_val, ber2->bv_val );
335 strcpy( temp, temp+ber2->bv_len );
336 ber1->bv_len -= ber2->bv_len;
342 if ( ber1->bv_len >= ber2->bv_len &&
343 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
346 ber1->bv_len -= ber2->bv_len;
354 static struct berval*
355 merge_init_final(Operation *op, struct berval* init, struct berval* any,
356 struct berval* final)
358 struct berval* merged, *temp;
359 int i, any_count, count;
361 for (any_count=0; any && any[any_count].bv_val; any_count++)
371 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
376 ber_dupbv_x( temp, init, op->o_tmpmemctx );
380 for (i=0; i<any_count; i++) {
381 ber_dupbv_x( temp, any, op->o_tmpmemctx );
386 ber_dupbv_x( temp, final, op->o_tmpmemctx );
393 /* Each element in stored must be found in incoming. Incoming is overwritten.
396 strings_containment(struct berval* stored, struct berval* incoming)
398 struct berval* element;
402 for ( element=stored; element->bv_val != NULL; element++ ) {
403 for (j = k; incoming[j].bv_val != NULL; j++) {
404 if (find_and_remove(&(incoming[j]), element, 2)) {
421 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
425 struct berval init_incoming;
426 struct berval final_incoming;
427 struct berval *remaining_incoming = NULL;
429 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
430 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
433 init_incoming = incoming->f_sub_initial;
434 final_incoming = incoming->f_sub_final;
436 if (find_and_remove(&init_incoming,
437 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
438 &(stored->f_sub_final), 3))
440 if (stored->f_sub_any == NULL) {
444 remaining_incoming = merge_init_final(op, &init_incoming,
445 incoming->f_sub_any, &final_incoming);
446 rc = strings_containment(stored->f_sub_any, remaining_incoming);
447 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
454 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
456 struct berval incoming_val[2];
459 incoming_val[1] = incoming->f_av_value;
461 if (find_and_remove(incoming_val+1,
462 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
463 &(stored->f_sub_final), 3)) {
464 if (stored->f_sub_any == NULL){
468 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
469 BER_BVZERO( incoming_val+1 );
470 rc = strings_containment(stored->f_sub_any, incoming_val);
471 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
477 /* check whether query is contained in any of
478 * the cached queries in template
481 query_containment(Operation *op, query_manager *qm,
483 QueryTemplate *templa)
487 Filter* inputf = query->filter;
488 struct berval* base = &(query->base);
489 int scope = query->scope;
496 MatchingRule* mrule = NULL;
497 if (inputf != NULL) {
498 Debug( pcache_debug, "Lock QC index = %p\n",
500 ldap_pvt_thread_rdwr_rlock(templa->t_rwlock);
501 for(qc=templa->query; qc != NULL; qc= qc->next) {
503 if(base_scope_compare(&(q->base), base, q->scope, scope)) {
508 switch (fs->f_choice) {
509 case LDAP_FILTER_EQUALITY:
510 if (fi->f_choice == LDAP_FILTER_EQUALITY)
511 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
517 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
523 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
524 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
525 &(fi->f_ava->aa_value),
526 &(fs->f_ava->aa_value), &text);
527 if (rc != LDAP_SUCCESS) {
528 ldap_pvt_thread_rdwr_runlock(templa->t_rwlock);
530 "Unlock: Exiting QC index=%p\n",
535 switch (fs->f_choice) {
537 case LDAP_FILTER_AND:
542 case LDAP_FILTER_SUBSTRINGS:
543 /* check if the equality query can be
544 * answered with cached substring query */
545 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
546 && substr_containment_equality( op,
549 /* check if the substring query can be
550 * answered with cached substring query */
551 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
552 ) && substr_containment_substr( op,
558 case LDAP_FILTER_PRESENT:
563 case LDAP_FILTER_EQUALITY:
570 if (mrule && ret >= 0)
576 if (mrule && ret <= 0)
581 case LDAP_FILTER_NOT:
587 } while((res) && (fi != NULL) && (fs != NULL));
590 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
591 if (qm->lru_top != qc) {
592 remove_query(qm, qc);
593 add_query_on_top(qm, qc);
595 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
601 "Not answerable: Unlock QC index=%p\n",
603 ldap_pvt_thread_rdwr_runlock(templa->t_rwlock);
609 free_query (CachedQuery* qc)
611 Query* q = (Query*)qc;
613 free(qc->q_uuid.bv_val);
614 filter_free(q->filter);
615 free (q->base.bv_val);
620 /* Add query to query cache */
621 static void add_query(
624 QueryTemplate *templ,
627 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
629 new_cached_query->qtemp = templ;
631 new_cached_query->q_uuid = *uuid;
632 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
634 BER_BVZERO( &new_cached_query->q_uuid );
635 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
637 new_cached_query->lru_up = NULL;
638 new_cached_query->lru_down = NULL;
639 Debug( pcache_debug, "Added query expires at %ld\n",
640 (long) new_cached_query->expiry_time, 0, 0 );
641 new_query = (Query*)new_cached_query;
643 ber_dupbv(&new_query->base, &query->base);
644 new_query->scope = query->scope;
645 new_query->filter = query->filter;
648 Debug( pcache_debug, "Lock AQ index = %p\n",
650 ldap_pvt_thread_rdwr_wlock(templ->t_rwlock);
651 if (templ->query == NULL)
652 templ->query_last = new_cached_query;
654 templ->query->prev = new_cached_query;
655 new_cached_query->next = templ->query;
656 new_cached_query->prev = NULL;
657 templ->query = new_cached_query;
658 templ->no_of_queries++;
659 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
660 templ, templ->no_of_queries, 0 );
662 Debug( pcache_debug, "Unlock AQ index = %p \n",
664 ldap_pvt_thread_rdwr_wunlock(templ->t_rwlock);
666 /* Adding on top of LRU list */
667 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
668 add_query_on_top(qm, new_cached_query);
669 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
673 remove_from_template (CachedQuery* qc, QueryTemplate* template)
675 if (!qc->prev && !qc->next) {
676 template->query_last = template->query = NULL;
677 } else if (qc->prev == NULL) {
678 qc->next->prev = NULL;
679 template->query = qc->next;
680 } else if (qc->next == NULL) {
681 qc->prev->next = NULL;
682 template->query_last = qc->prev;
684 qc->next->prev = qc->prev;
685 qc->prev->next = qc->next;
688 template->no_of_queries--;
691 /* remove bottom query of LRU list from the query cache */
692 static void cache_replacement(query_manager* qm, struct berval *result)
697 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
698 bottom = qm->lru_bottom;
700 result->bv_val = NULL;
704 Debug ( pcache_debug,
705 "Cache replacement invoked without "
706 "any query in LRU list\n", 0, 0, 0 );
707 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
711 temp = bottom->qtemp;
712 remove_query(qm, bottom);
713 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
715 *result = bottom->q_uuid;
716 bottom->q_uuid.bv_val = NULL;
718 Debug( pcache_debug, "Lock CR index = %p\n", temp, 0, 0 );
719 ldap_pvt_thread_rdwr_wlock(temp->t_rwlock);
720 remove_from_template(bottom, temp);
721 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
722 temp, temp->no_of_queries, 0 );
723 Debug( pcache_debug, "Unlock CR index = %p\n", temp, 0, 0 );
724 ldap_pvt_thread_rdwr_wunlock(temp->t_rwlock);
729 struct query_info *next;
741 struct query_info *qi;
744 if ( rs->sr_type != REP_SEARCH ) return 0;
746 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
747 if (attr->a_desc == ad_queryid) {
748 for (count=0; attr->a_vals[count].bv_val; count++)
753 if ( count == 0 ) return 0;
754 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
755 qi->next = op->o_callback->sc_private;
756 op->o_callback->sc_private = qi;
757 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
758 qi->del = ( count == 1 );
767 struct berval* query_uuid)
769 struct query_info *qi, *qnext;
771 #ifdef LDAP_COMP_MATCH
772 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
774 AttributeAssertion ava = { NULL, BER_BVNULL };
776 Filter filter = {LDAP_FILTER_EQUALITY};
777 SlapReply sreply = {REP_RESULT};
778 slap_callback cb = { NULL, remove_func, NULL, NULL };
781 sreply.sr_entry = NULL;
782 sreply.sr_nentries = 0;
783 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
784 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
786 filter.f_av_desc = ad_queryid;
787 filter.f_av_value = *query_uuid;
789 op->o_tag = LDAP_REQ_SEARCH;
790 op->o_protocol = LDAP_VERSION3;
791 op->o_callback = &cb;
792 op->o_time = slap_get_time();
793 op->o_do_not_cache = 1;
795 op->o_req_dn = op->o_bd->be_suffix[0];
796 op->o_req_ndn = op->o_bd->be_nsuffix[0];
797 op->ors_scope = LDAP_SCOPE_SUBTREE;
798 op->ors_deref = LDAP_DEREF_NEVER;
799 op->ors_slimit = SLAP_NO_LIMIT;
800 op->ors_tlimit = SLAP_NO_LIMIT;
801 op->ors_filter = &filter;
802 op->ors_filterstr.bv_val = filter_str;
803 op->ors_filterstr.bv_len = strlen(filter_str);
804 op->ors_attrs = NULL;
805 op->ors_attrsonly = 0;
807 op->o_bd->be_search( op, &sreply );
809 for ( qi=cb.sc_private; qi; qi=qnext ) {
812 op->o_req_dn = qi->xdn;
813 op->o_req_ndn = qi->xdn;
816 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
817 query_uuid->bv_val, 0, 0 );
819 op->o_tag = LDAP_REQ_DELETE;
821 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
826 struct berval vals[2];
828 vals[0] = *query_uuid;
829 vals[1].bv_val = NULL;
831 mod.sml_op = LDAP_MOD_DELETE;
833 mod.sml_desc = ad_queryid;
834 mod.sml_type = ad_queryid->ad_cname;
835 mod.sml_values = vals;
836 mod.sml_nvalues = NULL;
839 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
840 query_uuid->bv_val, 0, 0 );
842 op->orm_modlist = &mod;
844 op->o_bd->be_modify( op, &sreply );
846 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
847 op->o_tmpfree( qi, op->o_tmpmemctx );
854 AttributeName* attrs,
864 AttributeName** filter_attrs,
868 AttributeDescription *ad;
870 switch ( f->f_choice ) {
871 case LDAP_FILTER_EQUALITY:
873 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
874 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
879 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
880 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
885 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
886 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
889 case LDAP_FILTER_APPROX:
891 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
892 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
895 case LDAP_FILTER_SUBSTRINGS:
897 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
898 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
901 case LDAP_FILTER_PRESENT:
903 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
904 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
907 case LDAP_FILTER_AND:
909 case LDAP_FILTER_NOT: {
911 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
912 f->f_choice == LDAP_FILTER_AND ? '&' :
913 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
914 fstr->bv_len += sizeof("(%") - 1;
916 for ( f = f->f_list; f != NULL; f = f->f_next ) {
917 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
921 sprintf( fstr->bv_val+fstr->bv_len, ")" );
922 fstr->bv_len += sizeof(")") - 1;
928 strcpy( fstr->bv_val, "(?=?)" );
929 fstr->bv_len += sizeof("(?=?)")-1;
933 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
934 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
936 (*filter_attrs)[*filter_cnt].an_desc = ad;
937 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
938 (*filter_attrs)[*filter_cnt].an_oc = NULL;
939 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
940 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
942 if ( ad == slap_schema.si_ad_objectClass )
950 QueryTemplate *qtemp;
951 AttributeName* save_attrs; /* original attributes, saved for response */
962 struct berval *query_uuid)
964 struct search_info *si = op->o_callback->sc_private;
965 slap_overinst *on = si->on;
966 cache_manager *cm = on->on_bi.bi_private;
967 query_manager* qm = cm->qm;
970 struct berval crp_uuid;
971 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
972 Operation op_tmp = *op;
974 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
975 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
977 op_tmp.o_bd = &cm->db;
978 op_tmp.o_dn = cm->db.be_rootdn;
979 op_tmp.o_ndn = cm->db.be_rootndn;
981 Debug( pcache_debug, "UUID for query being added = %s\n",
984 for ( e=si->head; e; e=si->head ) {
985 si->head = e->e_private;
987 while ( cm->cur_entries > (cm->max_entries) ) {
988 qm->crfunc(qm, &crp_uuid);
989 if (crp_uuid.bv_val) {
991 "Removing query UUID %s\n",
992 crp_uuid.bv_val, 0, 0 );
993 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
995 "QUERY REMOVED, SIZE=%d\n",
997 ldap_pvt_thread_mutex_lock(
999 cm->cur_entries -= return_val;
1000 cm->num_cached_queries--;
1001 Debug( pcache_debug,
1002 "STORED QUERIES = %lu\n",
1003 cm->num_cached_queries, 0, 0 );
1004 ldap_pvt_thread_mutex_unlock(
1006 Debug( pcache_debug,
1007 "QUERY REMOVED, CACHE ="
1009 cm->cur_entries, 0, 0 );
1013 return_val = merge_entry(&op_tmp, e, query_uuid);
1014 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1015 cm->cur_entries += return_val;
1016 Debug( pcache_debug,
1017 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1018 cm->cur_entries, 0, 0 );
1020 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1031 struct search_info *si = op->o_callback->sc_private;
1032 slap_overinst *on = si->on;
1033 cache_manager *cm = on->on_bi.bi_private;
1034 query_manager* qm = cm->qm;
1037 if ( si->save_attrs != NULL ) {
1038 rs->sr_attrs = si->save_attrs;
1039 op->ors_attrs = si->save_attrs;
1040 si->save_attrs = NULL;
1043 if ( rs->sr_type == REP_SEARCH ) {
1045 /* If we haven't exceeded the limit for this query,
1046 * build a chain of answers to store. If we hit the
1047 * limit, empty the chain and ignore the rest.
1050 if ( si->count < si->max ) {
1052 e = entry_dup( rs->sr_entry );
1053 if ( !si->head ) si->head = e;
1054 if ( si->tail ) si->tail->e_private = e;
1059 for (;si->head; si->head=e) {
1060 e = si->head->e_private;
1061 si->head->e_private = NULL;
1062 entry_free(si->head);
1068 } else if ( rs->sr_type == REP_RESULT ) {
1069 QueryTemplate* templ = si->qtemp;
1070 if (( si->count && cache_entries( op, rs, &uuid ) == 0 ) ||
1071 ( templ->negttl && !si->count && !si->over &&
1072 rs->sr_err == LDAP_SUCCESS )) {
1073 qm->addfunc(qm, &si->query, si->qtemp,
1074 si->count ? &uuid : NULL);
1076 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1077 cm->num_cached_queries++;
1078 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1079 cm->num_cached_queries, 0, 0 );
1080 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1082 /* If the consistency checker suspended itself,
1085 if ( cm->cc_paused ) {
1086 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1087 if ( cm->cc_paused ) {
1089 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1091 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1094 filter_free( si->query.filter );
1098 op->o_callback->sc_cleanup = slap_freeself_cb;
1100 return SLAP_CB_CONTINUE;
1106 AttributeName** new_attrs,
1107 struct attr_set *attrs,
1108 AttributeName* filter_attrs,
1118 /* duplicate attrs */
1119 count = attrs->count + fattr_cnt;
1120 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1125 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1126 sizeof(AttributeName));
1127 for (i=0; i<attrs->count; i++) {
1128 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1129 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1131 BER_BVZERO( &(*new_attrs)[i].an_name );
1132 alluser = an_find(*new_attrs, &AllUser);
1133 allop = an_find(*new_attrs, &AllOper);
1136 for ( i=0; i<fattr_cnt; i++ ) {
1137 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1139 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1144 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1145 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1146 (*new_attrs)[j].an_oc = NULL;
1147 (*new_attrs)[j].an_oc_exclude = 0;
1151 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1152 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1153 (*new_attrs)[j].an_oc = NULL;
1154 (*new_attrs)[j].an_oc_exclude = 0;
1157 BER_BVZERO( &(*new_attrs)[j].an_name );
1160 /* NOTE: this is a quick workaround to let pcache minimally interact
1161 * with pagedResults. A more articulated solutions would be to
1162 * perform the remote query without control and cache all results,
1163 * performing the pagedResults search only within the client
1164 * and the proxy. This requires pcache to understand pagedResults. */
1166 pcache_chk_controls(
1170 const char *non = "";
1171 const char *stripped = "";
1173 switch( op->o_pagedresults ) {
1174 case SLAP_CONTROL_NONCRITICAL:
1176 stripped = "; stripped";
1179 case SLAP_CONTROL_CRITICAL:
1180 Debug( pcache_debug, "%s: "
1181 "%scritical pagedResults control "
1182 "disabled with proxy cache%s.\n",
1183 op->o_log_prefix, non, stripped );
1185 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1189 rs->sr_err = SLAP_CB_CONTINUE;
1201 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1202 cache_manager *cm = on->on_bi.bi_private;
1203 query_manager* qm = cm->qm;
1207 AttributeName *filter_attrs = NULL;
1210 QueryTemplate *qtemp = NULL;
1213 CachedQuery *answerable = NULL;
1216 int fattr_got_oc = 0;
1218 struct berval tempstr;
1220 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1222 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1223 &fattr_cnt, &fattr_got_oc )) {
1224 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1225 return SLAP_CB_CONTINUE;
1228 Debug( pcache_debug, "query template of incoming query = %s\n",
1229 tempstr.bv_val, 0, 0 );
1231 /* FIXME: cannot cache/answer requests with pagedResults control */
1234 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1236 query.filter = op->ors_filter;
1237 query.base = op->o_req_ndn;
1238 query.scope = op->ors_scope;
1240 /* check for query containment */
1241 if (attr_set > -1) {
1242 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1243 for (; qt; qt = qt->qtnext ) {
1244 /* find if template i can potentially answer tempstr */
1245 if (qt->querystr.bv_len != tempstr.bv_len ||
1246 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1250 Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1251 op->ors_filterstr.bv_val, 0, 0 );
1252 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1258 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1261 /* Need to clear the callbacks of the original operation,
1262 * in case there are other overlays */
1263 BackendDB *save_bd = op->o_bd;
1264 slap_callback *save_cb = op->o_callback;
1266 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1267 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1268 ldap_pvt_thread_rdwr_runlock(qtemp->t_rwlock);
1269 if ( BER_BVISNULL( &answerable->q_uuid )) {
1270 /* No entries cached, just an empty result set */
1272 send_ldap_result( op, rs );
1275 op->o_callback = NULL;
1276 i = cm->db.bd_info->bi_op_search( op, rs );
1279 op->o_callback = save_cb;
1283 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1285 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1286 if (cm->num_cached_queries >= cm->max_queries) {
1289 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1291 if (op->ors_attrsonly)
1296 struct search_info *si;
1298 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1299 query.filter = filter_dup(op->ors_filter, NULL);
1300 ldap_pvt_thread_rdwr_wlock(qtemp->t_rwlock);
1301 if ( !qtemp->t_attrs.count ) {
1302 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1303 &qm->attr_sets[attr_set],
1304 filter_attrs, fattr_cnt, fattr_got_oc);
1306 ldap_pvt_thread_rdwr_wunlock(qtemp->t_rwlock);
1308 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1309 cb->sc_response = pcache_response;
1310 cb->sc_cleanup = NULL;
1311 cb->sc_private = (cb+1);
1312 si = cb->sc_private;
1316 si->max = cm->num_entries_limit ;
1321 si->save_attrs = op->ors_attrs;
1323 op->ors_attrs = qtemp->t_attrs.attrs;
1325 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1326 cb->sc_next = op->o_callback;
1327 op->o_callback = cb;
1330 slap_callback **pcb;
1332 /* need to move the callback at the end, in case other
1333 * overlays are present, so that the final entry is
1334 * actually cached */
1336 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1341 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1345 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1347 return SLAP_CB_CONTINUE;
1352 AttributeName* attrs,
1360 for ( ; attrs[count].an_name.bv_val; count++ );
1363 for (i=0; i<num; i++) {
1367 if ( count > qm->attr_sets[i].count )
1370 if ( !qm->attr_sets[i].count )
1374 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1375 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1393 struct re_s *rtask = arg;
1394 slap_overinst *on = rtask->arg;
1395 cache_manager *cm = on->on_bi.bi_private;
1396 query_manager *qm = cm->qm;
1397 Connection conn = {0};
1398 OperationBuffer opbuf;
1401 SlapReply rs = {REP_RESULT};
1402 CachedQuery* query, *query_prev;
1403 int i, return_val, pause = 1;
1404 QueryTemplate* templ;
1406 op = (Operation *) &opbuf;
1407 connection_fake_init( &conn, op, ctx );
1410 op->o_dn = cm->db.be_rootdn;
1411 op->o_ndn = cm->db.be_rootndn;
1415 for (templ = qm->templates; templ; templ=templ->qmnext) {
1416 query = templ->query_last;
1417 if ( query ) pause = 0;
1418 op->o_time = slap_get_time();
1419 while (query && (query->expiry_time < op->o_time)) {
1420 Debug( pcache_debug, "Lock CR index = %d\n",
1422 ldap_pvt_thread_rdwr_wlock(templ->t_rwlock);
1423 remove_from_template(query, templ);
1424 Debug( pcache_debug, "TEMPLATE %d QUERIES-- %d\n",
1425 i, templ->no_of_queries, 0 );
1426 Debug( pcache_debug, "Unlock CR index = %d\n",
1428 ldap_pvt_thread_rdwr_wunlock(templ->t_rwlock);
1429 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1430 remove_query(qm, query);
1431 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1432 if ( BER_BVISNULL( &query->q_uuid ))
1435 return_val = remove_query_data(op, &rs, &query->q_uuid);
1436 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1438 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1439 cm->cur_entries -= return_val;
1440 cm->num_cached_queries--;
1441 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1442 cm->num_cached_queries, 0, 0 );
1443 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1444 Debug( pcache_debug,
1445 "STALE QUERY REMOVED, CACHE ="
1447 cm->cur_entries, 0, 0 );
1449 query = query->prev;
1450 free_query(query_prev);
1453 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1454 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1455 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1457 /* If there were no queries, defer processing for a while */
1458 cm->cc_paused = pause;
1459 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1461 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1466 #define MAX_ATTR_SETS 500
1476 static ConfigDriver pc_cf_gen;
1477 static ConfigLDAPadd pc_ldadd;
1478 static ConfigCfAdd pc_cfadd;
1480 static ConfigTable pccfg[] = {
1481 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1483 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1484 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1485 "DESC 'ProxyCache basic parameters' "
1486 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1487 { "proxyattrset", "index> <attributes...",
1488 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1489 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1490 "DESC 'A set of attributes to cache' "
1491 "SYNTAX OMsDirectoryString )", NULL, NULL },
1492 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1493 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1494 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1495 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1496 "SYNTAX OMsDirectoryString )", NULL, NULL },
1497 { "response-callback", "head|tail(default)",
1498 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1499 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1500 "DESC 'Response callback position in overlay stack' "
1501 "SYNTAX OMsDirectoryString )", NULL, NULL },
1502 { "proxyCacheQueries", "queries",
1503 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1504 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1505 "DESC 'Maximum number of queries to cache' "
1506 "SYNTAX OMsInteger )", NULL, NULL },
1508 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1511 static ConfigOCs pcocs[] = {
1512 { "( OLcfgOvOc:2.1 "
1513 "NAME 'olcPcacheConfig' "
1514 "DESC 'ProxyCache configuration' "
1515 "SUP olcOverlayConfig "
1516 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1517 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1518 { "( OLcfgOvOc:2.2 "
1519 "NAME 'olcPcacheDatabase' "
1520 "DESC 'Cache database configuration' "
1521 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1526 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1531 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1532 p->ce_bi->bi_cf_ocs != pcocs )
1533 return LDAP_CONSTRAINT_VIOLATION;
1535 on = (slap_overinst *)p->ce_bi;
1536 cm = on->on_bi.bi_private;
1538 return LDAP_SUCCESS;
1542 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1544 CfEntryInfo *pe = p->e_private;
1545 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1546 cache_manager *cm = on->on_bi.bi_private;
1549 /* FIXME: should not hardcode "olcDatabase" here */
1550 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1551 bv.bv_val = ca->msg;
1554 /* We can only create this entry if the database is table-driven
1556 if ( cm->db.bd_info->bi_cf_ocs )
1557 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1564 pc_cf_gen( ConfigArgs *c )
1566 slap_overinst *on = (slap_overinst *)c->bi;
1567 cache_manager* cm = on->on_bi.bi_private;
1568 query_manager* qm = cm->qm;
1569 QueryTemplate* temp;
1570 AttributeName* attr_name;
1571 AttributeName* attrarray;
1572 const char* text=NULL;
1577 if ( c->op == SLAP_CONFIG_EMIT ) {
1581 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1582 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1583 cm->num_entries_limit, cm->cc_period );
1585 value_add_one( &c->rvalue_vals, &bv );
1588 for (i=0; i<cm->numattrsets; i++) {
1589 if ( !qm->attr_sets[i].count ) continue;
1591 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1593 /* count the attr length */
1594 for ( attr_name = qm->attr_sets[i].attrs;
1595 attr_name->an_name.bv_val; attr_name++ )
1596 bv.bv_len += attr_name->an_name.bv_len + 1;
1598 bv.bv_val = ch_malloc( bv.bv_len+1 );
1599 ptr = lutil_strcopy( bv.bv_val, c->msg );
1600 for ( attr_name = qm->attr_sets[i].attrs;
1601 attr_name->an_name.bv_val; attr_name++ ) {
1603 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1605 ber_bvarray_add( &c->rvalue_vals, &bv );
1607 if ( !c->rvalue_vals )
1611 for (temp=qm->templates; temp; temp=temp->qmnext) {
1612 if ( temp->negttl ) {
1613 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1615 temp->attr_set_index,
1619 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1620 temp->attr_set_index,
1623 bv.bv_len += temp->querystr.bv_len + 2;
1624 bv.bv_val = ch_malloc( bv.bv_len+1 );
1627 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1629 strcpy( ptr, c->msg );
1630 ber_bvarray_add( &c->rvalue_vals, &bv );
1632 if ( !c->rvalue_vals )
1636 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1637 BER_BVSTR( &bv, "head" );
1639 BER_BVSTR( &bv, "tail" );
1641 value_add_one( &c->rvalue_vals, &bv );
1644 c->value_int = cm->max_queries;
1648 } else if ( c->op == LDAP_MOD_DELETE ) {
1649 return 1; /* FIXME */
1661 if ( cm->numattrsets > 0 ) {
1662 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1663 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1667 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1668 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1670 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1673 if ( cm->numattrsets <= 0 ) {
1674 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1675 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1678 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1679 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1680 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1684 if ( !backend_db_init( c->argv[1], &cm->db )) {
1685 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1686 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1690 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1691 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1693 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1696 if ( cm->max_entries <= 0 ) {
1697 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1698 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1702 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1703 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1705 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1708 if ( cm->num_entries_limit <= 0 ) {
1709 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1710 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1713 if ( cm->num_entries_limit > cm->max_entries ) {
1714 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1715 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1719 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1720 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1722 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1725 cm->cc_period = (time_t)t;
1726 Debug( pcache_debug,
1727 "Total # of attribute sets to be cached = %d.\n",
1728 cm->numattrsets, 0, 0 );
1729 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1730 sizeof( struct attr_set ) );
1733 if ( cm->numattrsets == 0 ) {
1734 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1735 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1738 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1739 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1741 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1745 if ( num < 0 || num >= cm->numattrsets ) {
1746 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1747 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1748 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1751 qm->attr_sets[num].flags |= PC_CONFIGURED;
1752 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1753 qm->attr_sets[num].count = c->argc - 2;
1754 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
1755 (c->argc-1) * sizeof( AttributeName ));
1756 attr_name = qm->attr_sets[num].attrs;
1757 for ( i = 2; i < c->argc; i++ ) {
1758 attr_name->an_desc = NULL;
1759 if ( slap_str2ad( c->argv[i],
1760 &attr_name->an_desc, &text ) )
1762 strcpy( c->msg, text );
1763 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1764 ch_free( qm->attr_sets[num].attrs );
1765 qm->attr_sets[num].attrs = NULL;
1766 qm->attr_sets[num].count = 0;
1769 attr_name->an_name = attr_name->an_desc->ad_cname;
1770 attr_name->an_oc = NULL;
1771 attr_name->an_oc_exclude = 0;
1772 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
1773 qm->attr_sets[num].flags |= PC_GOT_OC;
1775 BER_BVZERO( &attr_name->an_name );
1780 if ( cm->numattrsets == 0 ) {
1781 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1782 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1785 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
1786 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
1788 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1792 if ( i < 0 || i >= cm->numattrsets ||
1793 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
1794 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
1795 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1796 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1799 temp = ch_calloc( 1, sizeof( QueryTemplate ));
1800 temp->qmnext = qm->templates;
1801 qm->templates = temp;
1802 temp->t_rwlock = ch_malloc( sizeof( ldap_pvt_thread_rdwr_t ) );
1803 ldap_pvt_thread_rdwr_init( temp->t_rwlock );
1804 temp->query = temp->query_last = NULL;
1805 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
1806 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
1808 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1811 temp->ttl = (time_t)t;
1812 if ( c->argc == 5 ) {
1813 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
1814 snprintf( c->msg, sizeof( c->msg ),
1815 "unable to parse template negttl=\"%s\"",
1817 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1820 temp->negttl = (time_t)t;
1825 temp->no_of_queries = 0;
1827 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
1828 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
1829 Debug( pcache_debug, " query template: %s\n",
1830 temp->querystr.bv_val, 0, 0 );
1831 temp->attr_set_index = i;
1832 qm->attr_sets[i].flags |= PC_REFERENCED;
1833 temp->qtnext = qm->attr_sets[i].templates;
1834 qm->attr_sets[i].templates = temp;
1835 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
1836 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1837 for ( i=0; attrarray[i].an_name.bv_val; i++ )
1838 Debug( pcache_debug, "\t%s\n",
1839 attrarray[i].an_name.bv_val, 0, 0 );
1842 temp->querystr.bv_val = NULL;
1845 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
1846 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
1848 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
1849 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1852 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
1853 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1858 if ( c->value_int <= 0 ) {
1859 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
1860 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1863 cm->max_queries = c->value_int;
1878 slap_overinst *on = (slap_overinst *)be->bd_info;
1879 cache_manager* cm = on->on_bi.bi_private;
1881 /* Something for the cache database? */
1882 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
1883 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
1885 return SLAP_CONF_UNKNOWN;
1893 slap_overinst *on = (slap_overinst *)be->bd_info;
1897 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
1898 on->on_bi.bi_private = cm;
1900 qm = (query_manager*)ch_malloc(sizeof(query_manager));
1903 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
1904 cm->db.be_private = NULL;
1905 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
1907 cm->numattrsets = 0;
1908 cm->num_entries_limit = 5;
1909 cm->num_cached_queries = 0;
1910 cm->max_entries = 0;
1911 cm->cur_entries = 0;
1912 cm->max_queries = 10000;
1913 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1914 cm->cc_period = 1000;
1917 qm->attr_sets = NULL;
1918 qm->templates = NULL;
1920 qm->lru_bottom = NULL;
1922 qm->qcfunc = query_containment;
1923 qm->crfunc = cache_replacement;
1924 qm->addfunc = add_query;
1925 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
1927 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
1936 slap_overinst *on = (slap_overinst *)be->bd_info;
1937 cache_manager *cm = on->on_bi.bi_private;
1938 query_manager* qm = cm->qm;
1939 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
1941 /* check attr sets */
1942 for ( i = 0; i < cm->numattrsets; i++) {
1943 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
1944 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
1945 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
1949 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
1953 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
1954 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
1959 if ( ncf || rf || nrf ) {
1960 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
1961 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
1962 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
1969 /* need to inherit something from the original database... */
1970 cm->db.be_def_limit = be->be_def_limit;
1971 cm->db.be_limits = be->be_limits;
1972 cm->db.be_acl = be->be_acl;
1973 cm->db.be_dfltaccess = be->be_dfltaccess;
1975 rc = backend_startup_one( &cm->db );
1977 /* There is no runqueue in TOOL mode */
1978 if ( slapMode & SLAP_SERVER_MODE ) {
1979 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1980 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
1981 consistency_check, on,
1982 "pcache_consistency", be->be_suffix[0].bv_val );
1983 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1985 /* Cached database must have the rootdn */
1986 if ( BER_BVISNULL( &cm->db.be_rootndn )
1987 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
1989 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
1990 "underlying database of type \"%s\"\n"
1991 " serving naming context \"%s\"\n"
1992 " has no \"rootdn\", required by \"proxycache\".\n",
1993 on->on_info->oi_orig->bi_type,
1994 cm->db.be_suffix[0].bv_val, 0 );
2007 slap_overinst *on = (slap_overinst *)be->bd_info;
2008 cache_manager *cm = on->on_bi.bi_private;
2009 query_manager *qm = cm->qm;
2013 /* cleanup stuff inherited from the original database... */
2014 cm->db.be_limits = NULL;
2015 cm->db.be_acl = NULL;
2017 if ( cm->db.bd_info->bi_db_close ) {
2018 rc = cm->db.bd_info->bi_db_close( &cm->db );
2020 while ( tm = qm->templates ) {
2021 CachedQuery *qc, *qn;
2022 qm->templates = tm->qmnext;
2023 for ( qc = tm->query; qc; qc = qn ) {
2027 free( tm->querystr.bv_val );
2028 ldap_pvt_thread_rdwr_destroy( tm->t_rwlock );
2029 ch_free( tm->t_rwlock );
2030 free( tm->t_attrs.attrs );
2034 for ( i=0; i<cm->numattrsets; i++ ) {
2035 free( qm->attr_sets[i].attrs );
2037 free( qm->attr_sets );
2038 qm->attr_sets = NULL;
2048 slap_overinst *on = (slap_overinst *)be->bd_info;
2049 cache_manager *cm = on->on_bi.bi_private;
2050 query_manager *qm = cm->qm;
2052 /* cleanup stuff inherited from the original database... */
2053 cm->db.be_suffix = NULL;
2054 cm->db.be_nsuffix = NULL;
2055 BER_BVZERO( &cm->db.be_rootdn );
2056 BER_BVZERO( &cm->db.be_rootndn );
2057 BER_BVZERO( &cm->db.be_rootpw );
2058 /* FIXME: there might be more... */
2060 if ( cm->db.be_private != NULL ) {
2061 backend_destroy_one( &cm->db, 0 );
2064 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2065 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2072 static slap_overinst pcache;
2074 static char *obsolete_names[] = {
2079 int pcache_initialize()
2081 LDAPAttributeType *at;
2084 struct berval debugbv = BER_BVC("pcache");
2086 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2089 at = ldap_str2attributetype( queryid_schema, &code, &err,
2090 LDAP_SCHEMA_ALLOW_ALL );
2092 Debug( LDAP_DEBUG_ANY,
2093 "pcache_initialize: ldap_str2attributetype failed %s %s\n",
2094 ldap_scherr2str(code), err, 0 );
2097 code = at_add( at, 0, NULL, &err );
2099 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2103 Debug( LDAP_DEBUG_ANY,
2104 "pcache_initialize: at_add failed %s %s\n",
2105 scherr2str(code), err, 0 );
2109 pcache.on_bi.bi_type = "pcache";
2110 pcache.on_bi.bi_obsolete_names = obsolete_names;
2111 pcache.on_bi.bi_db_init = pcache_db_init;
2112 pcache.on_bi.bi_db_config = pcache_db_config;
2113 pcache.on_bi.bi_db_open = pcache_db_open;
2114 pcache.on_bi.bi_db_close = pcache_db_close;
2115 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2117 pcache.on_bi.bi_op_search = pcache_op_search;
2119 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2121 pcache.on_bi.bi_cf_ocs = pcocs;
2123 code = config_register_schema( pccfg, pcocs );
2124 if ( code ) return code;
2126 return overlay_register( &pcache );
2129 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2130 int init_module(int argc, char *argv[]) {
2131 return pcache_initialize();
2135 #endif /* defined(SLAPD_OVER_PROXYCACHE) */