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 AttributeName* attrs; /* Projected attributes */
43 AttributeName* save_attrs; /* original attributes, saved for response */
44 struct berval base; /* Search Base */
45 int scope; /* Search scope */
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 int template_id; /* 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 */
60 /* struct representing a query template
61 * e.g. template string = &(cn=)(mail=)
63 typedef struct query_template_s {
64 struct berval querystr; /* Filter string corresponding to the QT */
65 int attr_set_index; /* determines the projected attributes */
67 CachedQuery* query; /* most recent query cached for the template */
68 CachedQuery* query_last; /* oldest query cached for the template */
70 int no_of_queries; /* Total number of queries in the template */
71 time_t ttl; /* TTL for the queries of this template */
72 time_t negttl; /* TTL for negative results */
73 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
77 * Represents a set of projected attributes.
82 #define PC_CONFIGURED (0x1)
83 #define PC_REFERENCED (0x2)
84 #define PC_GOT_OC (0x4)
85 AttributeName* attrs; /* specifies the set */
86 int count; /* number of attributes */
89 struct query_manager_s;
91 /* prototypes for functions for 1) query containment
92 * 2) query addition, 3) cache replacement
94 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, int );
95 typedef void (AddQueryfunc)(struct query_manager_s*, Query*, int, struct berval*);
96 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
98 /* LDAP query cache */
99 typedef struct query_manager_s {
100 struct attr_set* attr_sets; /* possible sets of projected attributes */
101 QueryTemplate* templates; /* cacheable templates */
103 CachedQuery* lru_top; /* top and bottom of LRU list */
104 CachedQuery* lru_bottom;
106 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
108 /* Query cache methods */
109 QCfunc *qcfunc; /* Query containment*/
110 CRfunc *crfunc; /* cache replacement */
111 AddQueryfunc *addfunc; /* add query */
114 /* LDAP query cache manager */
115 typedef struct cache_manager_s {
116 BackendDB db; /* underlying database */
117 unsigned long num_cached_queries; /* total number of cached queries */
118 unsigned long max_queries; /* upper bound on # of cached queries */
119 int numattrsets; /* number of attribute sets */
120 int numtemplates; /* number of cacheable templates */
121 int cur_entries; /* current number of entries cached */
122 int max_entries; /* max number of entries cached */
123 int num_entries_limit; /* max # of entries in a cacheable query */
125 char response_cb; /* install the response callback
126 * at the tail of the callback list */
127 #define PCACHE_RESPONSE_CB_HEAD 0
128 #define PCACHE_RESPONSE_CB_TAIL 1
130 time_t cc_period; /* interval between successive consistency checks (sec) */
134 ldap_pvt_thread_mutex_t cache_mutex;
136 query_manager* qm; /* query cache managed by the cache manager */
139 static int pcache_debug;
141 static AttributeDescription *ad_queryid;
142 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
143 "DESC 'list of queries the entry belongs to' "
144 "EQUALITY octetStringMatch "
145 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
146 "NO-USER-MODIFICATION USAGE directoryOperation )";
148 /* Return 1 for an added entry, else 0 */
153 struct berval* query_uuid )
156 Modifications* modlist = NULL;
157 const char* text = NULL;
159 char textbuf[SLAP_TEXT_BUFLEN];
160 size_t textlen = sizeof(textbuf);
162 SlapReply sreply = {REP_RESULT};
164 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
169 /* add queryid attribute */
170 attr_merge_one( e, ad_queryid, query_uuid, NULL );
172 /* append the attribute list from the fetched entry */
173 e->e_attrs->a_next = attr;
175 op->o_tag = LDAP_REQ_ADD;
176 op->o_protocol = LDAP_VERSION3;
177 op->o_callback = &cb;
178 op->o_time = slap_get_time();
179 op->o_do_not_cache = 1;
182 op->o_req_dn = e->e_name;
183 op->o_req_ndn = e->e_nname;
184 rc = op->o_bd->be_add( op, &sreply );
186 if ( rc != LDAP_SUCCESS ) {
187 if ( rc == LDAP_ALREADY_EXISTS ) {
188 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
189 modlist->sml_op = LDAP_MOD_ADD;
190 op->o_tag = LDAP_REQ_MODIFY;
191 op->orm_modlist = modlist;
192 op->o_bd->be_modify( op, &sreply );
193 slap_mods_free( modlist, 1 );
194 } else if ( rc == LDAP_REFERRAL ||
195 rc == LDAP_NO_SUCH_OBJECT ) {
196 syncrepl_add_glue( op, e );
205 be_entry_release_w( op, e );
212 /* compare base and scope of incoming and cached queries */
213 static int base_scope_compare(
214 struct berval* ndn_stored,
215 struct berval* ndn_incoming,
219 struct berval pdn_incoming = BER_BVNULL;
221 if (scope_stored < scope_incoming)
224 if ( !dnIsSuffix(ndn_incoming, ndn_stored))
227 switch(scope_stored) {
228 case LDAP_SCOPE_BASE:
229 return (ndn_incoming->bv_len == ndn_stored->bv_len);
231 case LDAP_SCOPE_ONELEVEL:
232 switch(scope_incoming){
233 case LDAP_SCOPE_BASE:
234 dnParent(ndn_incoming, &pdn_incoming);
235 return (pdn_incoming.bv_len == ndn_stored->bv_len);
237 case LDAP_SCOPE_ONELEVEL:
238 return (ndn_incoming->bv_len == ndn_stored->bv_len);
243 case LDAP_SCOPE_SUBTREE:
252 /* add query on top of LRU list */
254 add_query_on_top (query_manager* qm, CachedQuery* qc)
256 CachedQuery* top = qm->lru_top;
257 Query* q = (Query*)qc;
268 Debug( pcache_debug, "Base of added query = %s\n",
269 q->base.bv_val, 0, 0 );
272 /* remove_query from LRU list */
275 remove_query (query_manager* qm, CachedQuery* qc)
298 qc->lru_up = qc->lru_down = NULL;
301 /* find and remove string2 from string1
302 * from start if position = 1,
303 * from end if position = 3,
304 * from anywhere if position = 2
305 * string1 is overwritten if position = 2.
309 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
320 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
321 ber2->bv_val, ber2->bv_len )) {
323 ber1->bv_val += ber2->bv_len;
324 ber1->bv_len -= ber2->bv_len;
329 ber1->bv_val[ber1->bv_len] = '\0';
330 temp = strstr( ber1->bv_val, ber2->bv_val );
332 strcpy( temp, temp+ber2->bv_len );
333 ber1->bv_len -= ber2->bv_len;
339 if ( ber1->bv_len >= ber2->bv_len &&
340 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
343 ber1->bv_len -= ber2->bv_len;
351 static struct berval*
352 merge_init_final(Operation *op, struct berval* init, struct berval* any,
353 struct berval* final)
355 struct berval* merged, *temp;
356 int i, any_count, count;
358 for (any_count=0; any && any[any_count].bv_val; any_count++)
368 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
373 ber_dupbv_x( temp, init, op->o_tmpmemctx );
377 for (i=0; i<any_count; i++) {
378 ber_dupbv_x( temp, any, op->o_tmpmemctx );
383 ber_dupbv_x( temp, final, op->o_tmpmemctx );
390 /* Each element in stored must be found in incoming. Incoming is overwritten.
393 strings_containment(struct berval* stored, struct berval* incoming)
395 struct berval* element;
399 for ( element=stored; element->bv_val != NULL; element++ ) {
400 for (j = k; incoming[j].bv_val != NULL; j++) {
401 if (find_and_remove(&(incoming[j]), element, 2)) {
418 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
423 struct berval init_incoming;
424 struct berval final_incoming;
425 struct berval *remaining_incoming = NULL;
427 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
428 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
431 init_incoming = incoming->f_sub_initial;
432 final_incoming = incoming->f_sub_final;
434 if (find_and_remove(&init_incoming,
435 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
436 &(stored->f_sub_final), 3))
438 if (stored->f_sub_any == NULL) {
442 remaining_incoming = merge_init_final(op, &init_incoming,
443 incoming->f_sub_any, &final_incoming);
444 rc = strings_containment(stored->f_sub_any, remaining_incoming);
445 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
452 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
454 struct berval incoming_val[2];
457 incoming_val[1] = incoming->f_av_value;
459 if (find_and_remove(incoming_val+1,
460 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
461 &(stored->f_sub_final), 3)) {
462 if (stored->f_sub_any == NULL){
466 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
467 BER_BVZERO( incoming_val+1 );
468 rc = strings_containment(stored->f_sub_any, incoming_val);
469 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
475 /* check whether query is contained in any of
476 * the cached queries in template template_index
479 query_containment(Operation *op, query_manager *qm,
483 QueryTemplate* templa= qm->templates;
486 Filter* inputf = query->filter;
487 struct berval* base = &(query->base);
488 int scope = query->scope;
495 MatchingRule* mrule = NULL;
496 if (inputf != NULL) {
497 Debug( pcache_debug, "Lock QC index = %d\n",
498 template_index, 0, 0 );
499 ldap_pvt_thread_rdwr_rlock(&(templa[template_index].t_rwlock));
500 for(qc=templa[template_index].query; qc != NULL; qc= qc->next) {
502 if(base_scope_compare(&(q->base), base, q->scope, scope)) {
507 switch (fs->f_choice) {
508 case LDAP_FILTER_EQUALITY:
509 if (fi->f_choice == LDAP_FILTER_EQUALITY)
510 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
516 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
522 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
523 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
524 &(fi->f_ava->aa_value),
525 &(fs->f_ava->aa_value), &text);
526 if (rc != LDAP_SUCCESS) {
527 ldap_pvt_thread_rdwr_runlock(&(templa[template_index].t_rwlock));
529 "Unlock: Exiting QC index=%d\n",
530 template_index, 0, 0 );
534 switch (fs->f_choice) {
536 case LDAP_FILTER_AND:
541 case LDAP_FILTER_SUBSTRINGS:
542 /* check if the equality query can be
543 * answered with cached substring query */
544 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
545 && substr_containment_equality( op,
548 /* check if the substring query can be
549 * answered with cached substring query */
550 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
551 ) && substr_containment_substr( op,
557 case LDAP_FILTER_PRESENT:
562 case LDAP_FILTER_EQUALITY:
580 case LDAP_FILTER_NOT:
586 } while((res) && (fi != NULL) && (fs != NULL));
589 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
590 if (qm->lru_top != qc) {
591 remove_query(qm, qc);
592 add_query_on_top(qm, qc);
594 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
600 "Not answerable: Unlock QC index=%d\n",
601 template_index, 0, 0 );
602 ldap_pvt_thread_rdwr_runlock(&(templa[template_index].t_rwlock));
608 free_query (CachedQuery* qc)
610 Query* q = (Query*)qc;
613 free(qc->q_uuid.bv_val);
614 filter_free(q->filter);
615 free (q->base.bv_val);
621 /* Add query to query cache */
622 static void add_query(
628 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
629 QueryTemplate* templ = (qm->templates)+template_index;
631 new_cached_query->template_id = template_index;
633 new_cached_query->q_uuid = *uuid;
634 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
636 BER_BVZERO( &new_cached_query->q_uuid );
637 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
639 new_cached_query->lru_up = NULL;
640 new_cached_query->lru_down = NULL;
641 Debug( pcache_debug, "Added query expires at %ld\n",
642 (long) new_cached_query->expiry_time, 0, 0 );
643 new_query = (Query*)new_cached_query;
645 ber_dupbv(&new_query->base, &query->base);
646 new_query->scope = query->scope;
647 new_query->filter = query->filter;
648 new_query->attrs = query->attrs;
651 Debug( pcache_debug, "Lock AQ index = %d\n",
652 template_index, 0, 0 );
653 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
654 if (templ->query == NULL)
655 templ->query_last = new_cached_query;
657 templ->query->prev = new_cached_query;
658 new_cached_query->next = templ->query;
659 new_cached_query->prev = NULL;
660 templ->query = new_cached_query;
661 templ->no_of_queries++;
662 Debug( pcache_debug, "TEMPLATE %d QUERIES++ %d\n",
663 template_index, templ->no_of_queries, 0 );
665 Debug( pcache_debug, "Unlock AQ index = %d \n",
666 template_index, 0, 0 );
667 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
669 /* Adding on top of LRU list */
670 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
671 add_query_on_top(qm, new_cached_query);
672 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
676 remove_from_template (CachedQuery* qc, QueryTemplate* template)
678 if (!qc->prev && !qc->next) {
679 template->query_last = template->query = NULL;
680 } else if (qc->prev == NULL) {
681 qc->next->prev = NULL;
682 template->query = qc->next;
683 } else if (qc->next == NULL) {
684 qc->prev->next = NULL;
685 template->query_last = qc->prev;
687 qc->next->prev = qc->prev;
688 qc->prev->next = qc->next;
691 template->no_of_queries--;
694 /* remove bottom query of LRU list from the query cache */
695 static void cache_replacement(query_manager* qm, struct berval *result)
700 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
701 bottom = qm->lru_bottom;
703 result->bv_val = NULL;
707 Debug ( pcache_debug,
708 "Cache replacement invoked without "
709 "any query in LRU list\n", 0, 0, 0 );
710 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
714 temp_id = bottom->template_id;
715 remove_query(qm, bottom);
716 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
718 *result = bottom->q_uuid;
719 bottom->q_uuid.bv_val = NULL;
721 Debug( pcache_debug, "Lock CR index = %d\n", temp_id, 0, 0 );
722 ldap_pvt_thread_rdwr_wlock(&(qm->templates[temp_id].t_rwlock));
723 remove_from_template(bottom, (qm->templates+temp_id));
724 Debug( pcache_debug, "TEMPLATE %d QUERIES-- %d\n",
725 temp_id, qm->templates[temp_id].no_of_queries, 0 );
726 Debug( pcache_debug, "Unlock CR index = %d\n", temp_id, 0, 0 );
727 ldap_pvt_thread_rdwr_wunlock(&(qm->templates[temp_id].t_rwlock));
732 struct query_info *next;
744 struct query_info *qi;
747 if ( rs->sr_type != REP_SEARCH ) return 0;
749 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
750 if (attr->a_desc == ad_queryid) {
751 for (count=0; attr->a_vals[count].bv_val; count++)
756 if ( count == 0 ) return 0;
757 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
758 qi->next = op->o_callback->sc_private;
759 op->o_callback->sc_private = qi;
760 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
761 qi->del = ( count == 1 );
770 struct berval* query_uuid)
772 struct query_info *qi, *qnext;
774 #ifdef LDAP_COMP_MATCH
775 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
777 AttributeAssertion ava = { NULL, BER_BVNULL };
779 Filter filter = {LDAP_FILTER_EQUALITY};
780 SlapReply sreply = {REP_RESULT};
781 slap_callback cb = { NULL, remove_func, NULL, NULL };
784 sreply.sr_entry = NULL;
785 sreply.sr_nentries = 0;
786 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
787 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
789 filter.f_av_desc = ad_queryid;
790 filter.f_av_value = *query_uuid;
792 op->o_tag = LDAP_REQ_SEARCH;
793 op->o_protocol = LDAP_VERSION3;
794 op->o_callback = &cb;
795 op->o_time = slap_get_time();
796 op->o_do_not_cache = 1;
798 op->o_req_dn = op->o_bd->be_suffix[0];
799 op->o_req_ndn = op->o_bd->be_nsuffix[0];
800 op->ors_scope = LDAP_SCOPE_SUBTREE;
801 op->ors_deref = LDAP_DEREF_NEVER;
802 op->ors_slimit = SLAP_NO_LIMIT;
803 op->ors_tlimit = SLAP_NO_LIMIT;
804 op->ors_filter = &filter;
805 op->ors_filterstr.bv_val = filter_str;
806 op->ors_filterstr.bv_len = strlen(filter_str);
807 op->ors_attrs = NULL;
808 op->ors_attrsonly = 0;
810 op->o_bd->be_search( op, &sreply );
812 for ( qi=cb.sc_private; qi; qi=qnext ) {
815 op->o_req_dn = qi->xdn;
816 op->o_req_ndn = qi->xdn;
819 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
820 query_uuid->bv_val, 0, 0 );
822 op->o_tag = LDAP_REQ_DELETE;
824 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
829 struct berval vals[2];
831 vals[0] = *query_uuid;
832 vals[1].bv_val = NULL;
834 mod.sml_op = LDAP_MOD_DELETE;
836 mod.sml_desc = ad_queryid;
837 mod.sml_type = ad_queryid->ad_cname;
838 mod.sml_values = vals;
839 mod.sml_nvalues = NULL;
842 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
843 query_uuid->bv_val, 0, 0 );
845 op->orm_modlist = &mod;
847 op->o_bd->be_modify( op, &sreply );
849 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
850 op->o_tmpfree( qi, op->o_tmpmemctx );
857 AttributeName* attrs,
867 AttributeName** filter_attrs,
871 AttributeDescription *ad;
873 switch ( f->f_choice ) {
874 case LDAP_FILTER_EQUALITY:
876 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
877 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
882 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
883 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
888 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
889 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
892 case LDAP_FILTER_APPROX:
894 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
895 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
898 case LDAP_FILTER_SUBSTRINGS:
900 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
901 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
904 case LDAP_FILTER_PRESENT:
906 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
907 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
910 case LDAP_FILTER_AND:
912 case LDAP_FILTER_NOT: {
914 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
915 f->f_choice == LDAP_FILTER_AND ? '&' :
916 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
917 fstr->bv_len += sizeof("(%") - 1;
919 for ( f = f->f_list; f != NULL; f = f->f_next ) {
920 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
924 sprintf( fstr->bv_val+fstr->bv_len, ")" );
925 fstr->bv_len += sizeof(")") - 1;
931 strcpy( fstr->bv_val, "(?=?)" );
932 fstr->bv_len += sizeof("(?=?)")-1;
936 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
937 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
939 (*filter_attrs)[*filter_cnt].an_desc = ad;
940 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
941 (*filter_attrs)[*filter_cnt].an_oc = NULL;
942 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
943 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
945 if ( ad == slap_schema.si_ad_objectClass )
964 struct berval *query_uuid)
966 struct search_info *si = op->o_callback->sc_private;
967 slap_overinst *on = si->on;
968 cache_manager *cm = on->on_bi.bi_private;
969 query_manager* qm = cm->qm;
972 struct berval crp_uuid;
973 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
974 Operation op_tmp = *op;
976 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
977 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
979 op_tmp.o_bd = &cm->db;
980 op_tmp.o_dn = cm->db.be_rootdn;
981 op_tmp.o_ndn = cm->db.be_rootndn;
983 Debug( pcache_debug, "UUID for query being added = %s\n",
986 for ( e=si->head; e; e=si->head ) {
987 si->head = e->e_private;
989 while ( cm->cur_entries > (cm->max_entries) ) {
990 qm->crfunc(qm, &crp_uuid);
991 if (crp_uuid.bv_val) {
993 "Removing query UUID %s\n",
994 crp_uuid.bv_val, 0, 0 );
995 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
997 "QUERY REMOVED, SIZE=%d\n",
999 ldap_pvt_thread_mutex_lock(
1001 cm->cur_entries -= return_val;
1002 cm->num_cached_queries--;
1003 Debug( pcache_debug,
1004 "STORED QUERIES = %lu\n",
1005 cm->num_cached_queries, 0, 0 );
1006 ldap_pvt_thread_mutex_unlock(
1008 Debug( pcache_debug,
1009 "QUERY REMOVED, CACHE ="
1011 cm->cur_entries, 0, 0 );
1015 return_val = merge_entry(&op_tmp, e, query_uuid);
1016 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1017 cm->cur_entries += return_val;
1018 Debug( pcache_debug,
1019 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1020 cm->cur_entries, 0, 0 );
1022 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1033 struct search_info *si = op->o_callback->sc_private;
1034 slap_overinst *on = si->on;
1035 cache_manager *cm = on->on_bi.bi_private;
1036 query_manager* qm = cm->qm;
1039 if ( si->query.save_attrs != NULL ) {
1040 rs->sr_attrs = si->query.save_attrs;
1041 op->ors_attrs = si->query.save_attrs;
1042 si->query.save_attrs = NULL;
1045 if ( rs->sr_type == REP_SEARCH ) {
1047 /* If we haven't exceeded the limit for this query,
1048 * build a chain of answers to store. If we hit the
1049 * limit, empty the chain and ignore the rest.
1052 if ( si->count < si->max ) {
1054 e = entry_dup( rs->sr_entry );
1055 if ( !si->head ) si->head = e;
1056 if ( si->tail ) si->tail->e_private = e;
1061 for (;si->head; si->head=e) {
1062 e = si->head->e_private;
1063 si->head->e_private = NULL;
1064 entry_free(si->head);
1070 } else if ( rs->sr_type == REP_RESULT ) {
1071 QueryTemplate* templ = (qm->templates)+si->template_id;
1072 if (( si->count && cache_entries( op, rs, &uuid ) == 0 ) ||
1073 ( templ->negttl && !si->count && !si->over &&
1074 rs->sr_err == LDAP_SUCCESS )) {
1075 qm->addfunc(qm, &si->query, si->template_id,
1076 si->count ? &uuid : NULL);
1078 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1079 cm->num_cached_queries++;
1080 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1081 cm->num_cached_queries, 0, 0 );
1082 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1084 /* If the consistency checker suspended itself,
1087 if ( cm->cc_paused ) {
1088 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1089 if ( cm->cc_paused ) {
1091 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1093 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1096 free( si->query.attrs );
1097 filter_free( si->query.filter );
1101 op->o_callback->sc_cleanup = slap_freeself_cb;
1103 return SLAP_CB_CONTINUE;
1109 AttributeName** new_attrs,
1110 struct attr_set *attrs,
1111 AttributeName* filter_attrs,
1121 /* duplicate attrs */
1122 count = attrs->count + fattr_cnt;
1123 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1128 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1129 sizeof(AttributeName));
1130 for (i=0; i<attrs->count; i++) {
1131 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1132 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1134 BER_BVZERO( &(*new_attrs)[i].an_name );
1135 alluser = an_find(*new_attrs, &AllUser);
1136 allop = an_find(*new_attrs, &AllOper);
1139 for ( i=0; i<fattr_cnt; i++ ) {
1140 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1142 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1147 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1148 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1149 (*new_attrs)[j].an_oc = NULL;
1150 (*new_attrs)[j].an_oc_exclude = 0;
1154 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1155 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1156 (*new_attrs)[j].an_oc = NULL;
1157 (*new_attrs)[j].an_oc_exclude = 0;
1160 BER_BVZERO( &(*new_attrs)[j].an_name );
1163 /* NOTE: this is a quick workaround to let pcache minimally interact
1164 * with pagedResults. A more articulated solutions would be to
1165 * perform the remote query without control and cache all results,
1166 * performing the pagedResults search only within the client
1167 * and the proxy. This requires pcache to understand pagedResults. */
1169 pcache_chk_controls(
1173 const char *non = "";
1174 const char *stripped = "";
1176 switch( op->o_pagedresults ) {
1177 case SLAP_CONTROL_NONCRITICAL:
1179 stripped = "; stripped";
1182 case SLAP_CONTROL_CRITICAL:
1183 Debug( pcache_debug, "%s: "
1184 "%scritical pagedResults control "
1185 "disabled with proxy cache%s.\n",
1186 op->o_log_prefix, non, stripped );
1188 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1192 rs->sr_err = SLAP_CB_CONTINUE;
1204 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1205 cache_manager *cm = on->on_bi.bi_private;
1206 query_manager* qm = cm->qm;
1212 AttributeName *filter_attrs = NULL;
1217 int template_id = -1;
1218 CachedQuery *answerable = NULL;
1221 int fattr_got_oc = 0;
1222 int oc_attr_absent = 1;
1224 struct berval tempstr;
1226 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1228 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1229 &fattr_cnt, &fattr_got_oc )) {
1230 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1231 return SLAP_CB_CONTINUE;
1234 Debug( pcache_debug, "query template of incoming query = %s\n",
1235 tempstr.bv_val, 0, 0 );
1237 /* FIXME: cannot cache/answer requests with pagedResults control */
1241 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1243 query.filter = op->ors_filter;
1244 query.attrs = op->ors_attrs;
1245 query.save_attrs = NULL;
1246 query.base = op->o_req_ndn;
1247 query.scope = op->ors_scope;
1249 /* check for query containment */
1250 if (attr_set > -1) {
1251 QueryTemplate *qt = qm->templates;
1252 for (i=0; i<cm->numtemplates; i++, qt++) {
1253 /* find if template i can potentially answer tempstr */
1254 if ( qt->attr_set_index != attr_set ||
1255 qt->querystr.bv_len != tempstr.bv_len ||
1256 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1260 Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1261 op->ors_filterstr.bv_val, 0, 0 );
1262 answerable = (*(qm->qcfunc))(op, qm, &query, i);
1268 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1270 query.save_attrs = op->ors_attrs;
1274 /* Need to clear the callbacks of the original operation,
1275 * in case there are other overlays */
1276 BackendDB *save_bd = op->o_bd;
1277 slap_callback *save_cb = op->o_callback;
1279 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1280 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1281 ldap_pvt_thread_rdwr_runlock(&qm->templates[i].t_rwlock);
1282 if ( BER_BVISNULL( &answerable->q_uuid )) {
1283 /* No entries cached, just an empty result set */
1285 send_ldap_result( op, rs );
1288 op->o_callback = NULL;
1289 i = cm->db.bd_info->bi_op_search( op, rs );
1292 op->o_callback = save_cb;
1296 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1298 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1299 if (cm->num_cached_queries >= cm->max_queries) {
1302 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1304 if (op->ors_attrsonly)
1309 struct search_info *si;
1311 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1312 query.filter = filter_dup(op->ors_filter, NULL);
1313 add_filter_attrs(op, &query.attrs, &qm->attr_sets[attr_set],
1314 filter_attrs, fattr_cnt, fattr_got_oc);
1316 op->ors_attrs = query.attrs;
1318 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1319 cb->sc_response = pcache_response;
1320 cb->sc_cleanup = NULL;
1321 cb->sc_private = (cb+1);
1322 si = cb->sc_private;
1325 si->template_id = template_id;
1326 si->max = cm->num_entries_limit ;
1332 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1333 cb->sc_next = op->o_callback;
1334 op->o_callback = cb;
1337 slap_callback **pcb;
1339 /* need to move the callback at the end, in case other
1340 * overlays are present, so that the final entry is
1341 * actually cached */
1343 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1348 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1352 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1354 return SLAP_CB_CONTINUE;
1359 AttributeName* attrs,
1367 for ( ; attrs[count].an_name.bv_val; count++ );
1370 for (i=0; i<num; i++) {
1374 if ( count > qm->attr_sets[i].count )
1377 if ( !qm->attr_sets[i].count )
1381 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1382 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1400 struct re_s *rtask = arg;
1401 slap_overinst *on = rtask->arg;
1402 cache_manager *cm = on->on_bi.bi_private;
1403 query_manager *qm = cm->qm;
1404 Connection conn = {0};
1405 OperationBuffer opbuf;
1408 SlapReply rs = {REP_RESULT};
1409 CachedQuery* query, *query_prev;
1410 int i, return_val, pause = 1;
1411 QueryTemplate* templ;
1413 op = (Operation *) &opbuf;
1414 connection_fake_init( &conn, op, ctx );
1417 op->o_dn = cm->db.be_rootdn;
1418 op->o_ndn = cm->db.be_rootndn;
1422 for (i=0; qm->templates[i].querystr.bv_val; i++) {
1423 templ = qm->templates + i;
1424 query = templ->query_last;
1425 if ( query ) pause = 0;
1426 op->o_time = slap_get_time();
1427 while (query && (query->expiry_time < op->o_time)) {
1428 Debug( pcache_debug, "Lock CR index = %d\n",
1430 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1431 remove_from_template(query, templ);
1432 Debug( pcache_debug, "TEMPLATE %d QUERIES-- %d\n",
1433 i, templ->no_of_queries, 0 );
1434 Debug( pcache_debug, "Unlock CR index = %d\n",
1436 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1437 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1438 remove_query(qm, query);
1439 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1440 if ( BER_BVISNULL( &query->q_uuid ))
1443 return_val = remove_query_data(op, &rs, &query->q_uuid);
1444 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1446 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1447 cm->cur_entries -= return_val;
1448 cm->num_cached_queries--;
1449 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1450 cm->num_cached_queries, 0, 0 );
1451 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1452 Debug( pcache_debug,
1453 "STALE QUERY REMOVED, CACHE ="
1455 cm->cur_entries, 0, 0 );
1457 query = query->prev;
1458 free_query(query_prev);
1461 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1462 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1463 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1465 /* If there were no queries, defer processing for a while */
1466 cm->cc_paused = pause;
1467 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1469 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1474 #define MAX_ATTR_SETS 500
1484 static ConfigDriver pc_cf_gen;
1485 static ConfigLDAPadd pc_ldadd;
1486 static ConfigCfAdd pc_cfadd;
1488 static ConfigTable pccfg[] = {
1489 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1491 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1492 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1493 "DESC 'ProxyCache basic parameters' "
1494 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1495 { "proxyattrset", "index> <attributes...",
1496 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1497 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1498 "DESC 'A set of attributes to cache' "
1499 "SYNTAX OMsDirectoryString )", NULL, NULL },
1500 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1501 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1502 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1503 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1504 "SYNTAX OMsDirectoryString )", NULL, NULL },
1505 { "response-callback", "head|tail(default)",
1506 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1507 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1508 "DESC 'Response callback position in overlay stack' "
1509 "SYNTAX OMsDirectoryString )", NULL, NULL },
1510 { "proxyCacheQueries", "queries",
1511 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1512 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1513 "DESC 'Maximum number of queries to cache' "
1514 "SYNTAX OMsInteger )", NULL, NULL },
1516 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1519 static ConfigOCs pcocs[] = {
1520 { "( OLcfgOvOc:2.1 "
1521 "NAME 'olcPcacheConfig' "
1522 "DESC 'ProxyCache configuration' "
1523 "SUP olcOverlayConfig "
1524 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1525 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1526 { "( OLcfgOvOc:2.2 "
1527 "NAME 'olcPcacheDatabase' "
1528 "DESC 'Cache database configuration' "
1529 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1534 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1539 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1540 p->ce_bi->bi_cf_ocs != pcocs )
1541 return LDAP_CONSTRAINT_VIOLATION;
1543 on = (slap_overinst *)p->ce_bi;
1544 cm = on->on_bi.bi_private;
1546 return LDAP_SUCCESS;
1550 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1552 CfEntryInfo *pe = p->e_private;
1553 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1554 cache_manager *cm = on->on_bi.bi_private;
1557 /* FIXME: should not hardcode "olcDatabase" here */
1558 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1559 bv.bv_val = ca->msg;
1562 /* We can only create this entry if the database is table-driven
1564 if ( cm->db.bd_info->bi_cf_ocs )
1565 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1572 pc_cf_gen( ConfigArgs *c )
1574 slap_overinst *on = (slap_overinst *)c->bi;
1575 cache_manager* cm = on->on_bi.bi_private;
1576 query_manager* qm = cm->qm;
1577 QueryTemplate* temp;
1578 AttributeName* attr_name;
1579 AttributeName* attrarray;
1580 const char* text=NULL;
1585 if ( c->op == SLAP_CONFIG_EMIT ) {
1589 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1590 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1591 cm->num_entries_limit, cm->cc_period );
1593 value_add_one( &c->rvalue_vals, &bv );
1596 for (i=0; i<cm->numattrsets; i++) {
1597 if ( !qm->attr_sets[i].count ) continue;
1599 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1601 /* count the attr length */
1602 for ( attr_name = qm->attr_sets[i].attrs;
1603 attr_name->an_name.bv_val; attr_name++ )
1604 bv.bv_len += attr_name->an_name.bv_len + 1;
1606 bv.bv_val = ch_malloc( bv.bv_len+1 );
1607 ptr = lutil_strcopy( bv.bv_val, c->msg );
1608 for ( attr_name = qm->attr_sets[i].attrs;
1609 attr_name->an_name.bv_val; attr_name++ ) {
1611 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1613 ber_bvarray_add( &c->rvalue_vals, &bv );
1615 if ( !c->rvalue_vals )
1619 for (i=0; i<cm->numtemplates; i++) {
1620 if ( qm->templates[i].negttl ) {
1621 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1623 qm->templates[i].attr_set_index,
1624 qm->templates[i].ttl,
1625 qm->templates[i].negttl );
1627 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1628 qm->templates[i].attr_set_index,
1629 qm->templates[i].ttl );
1631 bv.bv_len += qm->templates[i].querystr.bv_len + 2;
1632 bv.bv_val = ch_malloc( bv.bv_len+1 );
1635 ptr = lutil_strcopy( ptr, qm->templates[i].querystr.bv_val );
1637 strcpy( ptr, c->msg );
1638 ber_bvarray_add( &c->rvalue_vals, &bv );
1640 if ( !c->rvalue_vals )
1644 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1645 BER_BVSTR( &bv, "head" );
1647 BER_BVSTR( &bv, "tail" );
1649 value_add_one( &c->rvalue_vals, &bv );
1652 c->value_int = cm->max_queries;
1656 } else if ( c->op == LDAP_MOD_DELETE ) {
1657 return 1; /* FIXME */
1669 if ( cm->numattrsets > 0 ) {
1670 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1671 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1675 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1676 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1678 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1681 if ( cm->numattrsets <= 0 ) {
1682 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1683 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1686 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1687 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1688 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1692 if ( !backend_db_init( c->argv[1], &cm->db )) {
1693 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1694 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1698 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1699 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1701 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1704 if ( cm->max_entries <= 0 ) {
1705 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1706 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1710 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1711 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1713 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1716 if ( cm->num_entries_limit <= 0 ) {
1717 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1718 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1721 if ( cm->num_entries_limit > cm->max_entries ) {
1722 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1723 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1727 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1728 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1730 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1733 cm->cc_period = (time_t)t;
1734 Debug( pcache_debug,
1735 "Total # of attribute sets to be cached = %d.\n",
1736 cm->numattrsets, 0, 0 );
1737 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1738 sizeof( struct attr_set ) );
1741 if ( cm->numattrsets == 0 ) {
1742 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1743 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1746 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1747 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1749 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1753 if ( num < 0 || num >= cm->numattrsets ) {
1754 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1755 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1756 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1759 qm->attr_sets[num].flags |= PC_CONFIGURED;
1760 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1761 qm->attr_sets[num].count = c->argc - 2;
1762 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
1763 (c->argc-1) * sizeof( AttributeName ));
1764 attr_name = qm->attr_sets[num].attrs;
1765 for ( i = 2; i < c->argc; i++ ) {
1766 attr_name->an_desc = NULL;
1767 if ( slap_str2ad( c->argv[i],
1768 &attr_name->an_desc, &text ) )
1770 strcpy( c->msg, text );
1771 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1772 ch_free( qm->attr_sets[num].attrs );
1773 qm->attr_sets[num].attrs = NULL;
1774 qm->attr_sets[num].count = 0;
1777 attr_name->an_name = attr_name->an_desc->ad_cname;
1778 attr_name->an_oc = NULL;
1779 attr_name->an_oc_exclude = 0;
1780 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
1781 qm->attr_sets[num].flags |= PC_GOT_OC;
1783 BER_BVZERO( &attr_name->an_name );
1788 if ( cm->numattrsets == 0 ) {
1789 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1790 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1793 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
1794 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
1796 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1800 if ( i < 0 || i >= cm->numattrsets ) {
1801 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
1802 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1803 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1806 num = cm->numtemplates;
1807 qm->templates = ( QueryTemplate* )ch_realloc( qm->templates,
1808 ( num + 2 ) * sizeof( QueryTemplate ));
1809 temp = qm->templates + num;
1810 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
1811 temp->query = temp->query_last = NULL;
1812 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
1813 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
1815 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1818 temp->ttl = (time_t)t;
1819 if ( c->argc == 5 ) {
1820 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
1821 snprintf( c->msg, sizeof( c->msg ),
1822 "unable to parse template negttl=\"%s\"",
1824 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1827 temp->negttl = (time_t)t;
1832 temp->no_of_queries = 0;
1834 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
1835 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
1836 Debug( pcache_debug, " query template: %s\n",
1837 temp->querystr.bv_val, 0, 0 );
1838 temp->attr_set_index = i;
1839 qm->attr_sets[i].flags |= PC_REFERENCED;
1840 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
1841 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
1842 for ( i=0; attrarray[i].an_name.bv_val; i++ )
1843 Debug( pcache_debug, "\t%s\n",
1844 attrarray[i].an_name.bv_val, 0, 0 );
1847 temp->querystr.bv_val = NULL;
1851 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
1852 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
1854 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
1855 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1858 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
1859 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1864 if ( c->value_int <= 0 ) {
1865 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
1866 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1869 cm->max_queries = c->value_int;
1884 slap_overinst *on = (slap_overinst *)be->bd_info;
1885 cache_manager* cm = on->on_bi.bi_private;
1887 /* Something for the cache database? */
1888 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
1889 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
1891 return SLAP_CONF_UNKNOWN;
1899 slap_overinst *on = (slap_overinst *)be->bd_info;
1903 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
1904 on->on_bi.bi_private = cm;
1906 qm = (query_manager*)ch_malloc(sizeof(query_manager));
1909 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
1910 cm->db.be_private = NULL;
1911 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
1913 cm->numattrsets = 0;
1914 cm->numtemplates = 0;
1915 cm->num_entries_limit = 5;
1916 cm->num_cached_queries = 0;
1917 cm->max_entries = 0;
1918 cm->cur_entries = 0;
1919 cm->max_queries = 10000;
1920 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
1921 cm->cc_period = 1000;
1924 qm->attr_sets = NULL;
1925 qm->templates = NULL;
1927 qm->lru_bottom = NULL;
1929 qm->qcfunc = query_containment;
1930 qm->crfunc = cache_replacement;
1931 qm->addfunc = add_query;
1932 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
1934 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
1943 slap_overinst *on = (slap_overinst *)be->bd_info;
1944 cache_manager *cm = on->on_bi.bi_private;
1945 query_manager* qm = cm->qm;
1946 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
1948 /* check attr sets */
1949 for ( i = 0; i < cm->numattrsets; i++) {
1950 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
1951 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
1952 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
1956 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
1960 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
1961 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
1966 if ( ncf || rf || nrf ) {
1967 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
1968 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
1969 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
1976 /* need to inherit something from the original database... */
1977 cm->db.be_def_limit = be->be_def_limit;
1978 cm->db.be_limits = be->be_limits;
1979 cm->db.be_acl = be->be_acl;
1980 cm->db.be_dfltaccess = be->be_dfltaccess;
1982 rc = backend_startup_one( &cm->db );
1984 /* There is no runqueue in TOOL mode */
1985 if ( slapMode & SLAP_SERVER_MODE ) {
1986 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1987 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
1988 consistency_check, on,
1989 "pcache_consistency", be->be_suffix[0].bv_val );
1990 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1992 /* Cached database must have the rootdn */
1993 if ( BER_BVISNULL( &cm->db.be_rootndn )
1994 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
1996 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
1997 "underlying database of type \"%s\"\n"
1998 " serving naming context \"%s\"\n"
1999 " has no \"rootdn\", required by \"proxycache\".\n",
2000 on->on_info->oi_orig->bi_type,
2001 cm->db.be_suffix[0].bv_val, 0 );
2014 slap_overinst *on = (slap_overinst *)be->bd_info;
2015 cache_manager *cm = on->on_bi.bi_private;
2016 query_manager *qm = cm->qm;
2019 /* cleanup stuff inherited from the original database... */
2020 cm->db.be_limits = NULL;
2021 cm->db.be_acl = NULL;
2023 if ( cm->db.bd_info->bi_db_close ) {
2024 rc = cm->db.bd_info->bi_db_close( &cm->db );
2026 for ( i=0; i<cm->numtemplates; i++ ) {
2027 CachedQuery *qc, *qn;
2028 for ( qc = qm->templates[i].query; qc; qc = qn ) {
2032 free( qm->templates[i].querystr.bv_val );
2033 ldap_pvt_thread_rdwr_destroy( &qm->templates[i].t_rwlock );
2035 free( qm->templates );
2036 qm->templates = NULL;
2038 for ( i=0; i<cm->numattrsets; i++ ) {
2039 free( qm->attr_sets[i].attrs );
2041 free( qm->attr_sets );
2042 qm->attr_sets = NULL;
2052 slap_overinst *on = (slap_overinst *)be->bd_info;
2053 cache_manager *cm = on->on_bi.bi_private;
2054 query_manager *qm = cm->qm;
2056 /* cleanup stuff inherited from the original database... */
2057 cm->db.be_suffix = NULL;
2058 cm->db.be_nsuffix = NULL;
2059 BER_BVZERO( &cm->db.be_rootdn );
2060 BER_BVZERO( &cm->db.be_rootndn );
2061 BER_BVZERO( &cm->db.be_rootpw );
2062 /* FIXME: there might be more... */
2064 if ( cm->db.be_private != NULL ) {
2065 backend_destroy_one( &cm->db, 0 );
2068 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2069 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2076 static slap_overinst pcache;
2078 int pcache_initialize()
2080 LDAPAttributeType *at;
2083 struct berval debugbv = BER_BVC("pcache");
2085 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2088 at = ldap_str2attributetype( queryid_schema, &code, &err,
2089 LDAP_SCHEMA_ALLOW_ALL );
2091 Debug( LDAP_DEBUG_ANY,
2092 "pcache_initialize: ldap_str2attributetype failed %s %s\n",
2093 ldap_scherr2str(code), err, 0 );
2096 code = at_add( at, 0, NULL, &err );
2098 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2102 Debug( LDAP_DEBUG_ANY,
2103 "pcache_initialize: at_add failed %s %s\n",
2104 scherr2str(code), err, 0 );
2108 pcache.on_bi.bi_type = "pcache";
2109 pcache.on_bi.bi_db_init = pcache_db_init;
2110 pcache.on_bi.bi_db_config = pcache_db_config;
2111 pcache.on_bi.bi_db_open = pcache_db_open;
2112 pcache.on_bi.bi_db_close = pcache_db_close;
2113 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2115 pcache.on_bi.bi_op_search = pcache_op_search;
2117 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2119 pcache.on_bi.bi_cf_ocs = pcocs;
2121 code = config_register_schema( pccfg, pcocs );
2122 if ( code ) return code;
2124 return overlay_register( &pcache );
2127 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2128 int init_module(int argc, char *argv[]) {
2129 return pcache_initialize();
2133 #endif /* defined(SLAPD_OVER_PROXYCACHE) */