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>
38 /* query cache structs */
41 typedef struct Query_s {
42 Filter* filter; /* Search Filter */
43 struct berval base; /* Search Base */
44 int scope; /* Search scope */
47 struct query_template_s;
49 typedef struct Qbase_s {
50 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
54 /* struct representing a cached query */
55 typedef struct cached_query_s {
60 struct berval q_uuid; /* query identifier */
61 struct query_template_s *qtemp; /* template of the query */
62 time_t expiry_time; /* time till the query is considered valid */
63 struct cached_query_s *next; /* next query in the template */
64 struct cached_query_s *prev; /* previous query in the template */
65 struct cached_query_s *lru_up; /* previous query in the LRU list */
66 struct cached_query_s *lru_down; /* next query in the LRU list */
70 * Represents a set of projected attributes.
74 struct query_template_s *templates;
75 AttributeName* attrs; /* specifies the set */
77 #define PC_CONFIGURED (0x1)
78 #define PC_REFERENCED (0x2)
79 #define PC_GOT_OC (0x4)
80 int count; /* number of attributes */
83 /* struct representing a query template
84 * e.g. template string = &(cn=)(mail=)
86 typedef struct query_template_s {
87 struct query_template_s *qtnext;
88 struct query_template_s *qmnext;
91 CachedQuery* query; /* most recent query cached for the template */
92 CachedQuery* query_last; /* oldest query cached for the template */
93 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
94 struct berval querystr; /* Filter string corresponding to the QT */
96 int attr_set_index; /* determines the projected attributes */
97 int no_of_queries; /* Total number of queries in the template */
98 time_t ttl; /* TTL for the queries of this template */
99 time_t negttl; /* TTL for negative results */
100 struct attr_set t_attrs; /* filter attrs + attr_set */
103 struct query_manager_s;
105 /* prototypes for functions for 1) query containment
106 * 2) query addition, 3) cache replacement
108 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
109 typedef void (AddQueryfunc)(struct query_manager_s*, Query*, QueryTemplate*, struct berval*);
110 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
112 /* LDAP query cache */
113 typedef struct query_manager_s {
114 struct attr_set* attr_sets; /* possible sets of projected attributes */
115 QueryTemplate* templates; /* cacheable templates */
117 CachedQuery* lru_top; /* top and bottom of LRU list */
118 CachedQuery* lru_bottom;
120 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
122 /* Query cache methods */
123 QCfunc *qcfunc; /* Query containment*/
124 CRfunc *crfunc; /* cache replacement */
125 AddQueryfunc *addfunc; /* add query */
128 /* LDAP query cache manager */
129 typedef struct cache_manager_s {
130 BackendDB db; /* underlying database */
131 unsigned long num_cached_queries; /* total number of cached queries */
132 unsigned long max_queries; /* upper bound on # of cached queries */
133 int numattrsets; /* number of attribute sets */
134 int cur_entries; /* current number of entries cached */
135 int max_entries; /* max number of entries cached */
136 int num_entries_limit; /* max # of entries in a cacheable query */
138 char response_cb; /* install the response callback
139 * at the tail of the callback list */
140 #define PCACHE_RESPONSE_CB_HEAD 0
141 #define PCACHE_RESPONSE_CB_TAIL 1
143 time_t cc_period; /* interval between successive consistency checks (sec) */
147 ldap_pvt_thread_mutex_t cache_mutex;
149 query_manager* qm; /* query cache managed by the cache manager */
152 static int pcache_debug;
154 static AttributeDescription *ad_queryid;
155 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
156 "DESC 'list of queries the entry belongs to' "
157 "EQUALITY octetStringMatch "
158 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
159 "NO-USER-MODIFICATION USAGE directoryOperation )";
161 /* Return 1 for an added entry, else 0 */
166 struct berval* query_uuid )
169 Modifications* modlist = NULL;
170 const char* text = NULL;
172 char textbuf[SLAP_TEXT_BUFLEN];
173 size_t textlen = sizeof(textbuf);
175 SlapReply sreply = {REP_RESULT};
177 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
182 /* add queryid attribute */
183 attr_merge_one( e, ad_queryid, query_uuid, NULL );
185 /* append the attribute list from the fetched entry */
186 e->e_attrs->a_next = attr;
188 op->o_tag = LDAP_REQ_ADD;
189 op->o_protocol = LDAP_VERSION3;
190 op->o_callback = &cb;
191 op->o_time = slap_get_time();
192 op->o_do_not_cache = 1;
195 op->o_req_dn = e->e_name;
196 op->o_req_ndn = e->e_nname;
197 rc = op->o_bd->be_add( op, &sreply );
199 if ( rc != LDAP_SUCCESS ) {
200 if ( rc == LDAP_ALREADY_EXISTS ) {
201 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
202 modlist->sml_op = LDAP_MOD_ADD;
203 op->o_tag = LDAP_REQ_MODIFY;
204 op->orm_modlist = modlist;
205 op->o_bd->be_modify( op, &sreply );
206 slap_mods_free( modlist, 1 );
207 } else if ( rc == LDAP_REFERRAL ||
208 rc == LDAP_NO_SUCH_OBJECT ) {
209 syncrepl_add_glue( op, e );
218 be_entry_release_w( op, e );
225 /* Length-ordered sort on normalized DNs */
226 static int pcache_dn_cmp( const void *v1, const void *v2 )
228 const Qbase *q1 = v1, *q2 = v2;
230 int rc = q1->base.bv_len - q2->base.bv_len;
232 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
236 /* compare the first value in each filter */
237 static int pcache_filter_cmp( const void *v1, const void *v2 )
239 const CachedQuery *q1 = v1, *q2 =v2;
240 int rc, weight1, weight2;
242 switch( q1->first->f_choice ) {
243 case LDAP_FILTER_PRESENT:
246 case LDAP_FILTER_EQUALITY:
254 switch( q2->first->f_choice ) {
255 case LDAP_FILTER_PRESENT:
258 case LDAP_FILTER_EQUALITY:
266 rc = weight1 - weight2;
271 rc = ber_bvcmp( &q1->first->f_ava->aa_value,
272 &q2->first->f_ava->aa_value );
275 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
277 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
278 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
279 rc = ber_bvcmp( &q1->first->f_sub_initial,
280 &q2->first->f_sub_initial );
284 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
288 if ( q1->first->f_sub_any ) {
289 if ( q2->first->f_sub_any ) {
290 rc = ber_bvcmp( q1->first->f_sub_any,
291 q2->first->f_sub_any );
295 } else if ( q2->first->f_sub_any ) {
299 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
300 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
301 rc = ber_bvcmp( &q1->first->f_sub_final,
302 &q2->first->f_sub_final );
306 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
310 rc = ber_bvcmp( &q1->first->f_mr_value,
311 &q2->first->f_mr_value );
320 /* add query on top of LRU list */
322 add_query_on_top (query_manager* qm, CachedQuery* qc)
324 CachedQuery* top = qm->lru_top;
325 Query* q = (Query*)qc;
336 Debug( pcache_debug, "Base of added query = %s\n",
337 q->base.bv_val, 0, 0 );
340 /* remove_query from LRU list */
343 remove_query (query_manager* qm, CachedQuery* qc)
366 qc->lru_up = qc->lru_down = NULL;
369 /* find and remove string2 from string1
370 * from start if position = 1,
371 * from end if position = 3,
372 * from anywhere if position = 2
373 * string1 is overwritten if position = 2.
377 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
388 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
389 ber2->bv_val, ber2->bv_len )) {
391 ber1->bv_val += ber2->bv_len;
392 ber1->bv_len -= ber2->bv_len;
397 ber1->bv_val[ber1->bv_len] = '\0';
398 temp = strstr( ber1->bv_val, ber2->bv_val );
400 strcpy( temp, temp+ber2->bv_len );
401 ber1->bv_len -= ber2->bv_len;
407 if ( ber1->bv_len >= ber2->bv_len &&
408 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
411 ber1->bv_len -= ber2->bv_len;
419 static struct berval*
420 merge_init_final(Operation *op, struct berval* init, struct berval* any,
421 struct berval* final)
423 struct berval* merged, *temp;
424 int i, any_count, count;
426 for (any_count=0; any && any[any_count].bv_val; any_count++)
436 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
441 ber_dupbv_x( temp, init, op->o_tmpmemctx );
445 for (i=0; i<any_count; i++) {
446 ber_dupbv_x( temp, any, op->o_tmpmemctx );
451 ber_dupbv_x( temp, final, op->o_tmpmemctx );
458 /* Each element in stored must be found in incoming. Incoming is overwritten.
461 strings_containment(struct berval* stored, struct berval* incoming)
463 struct berval* element;
467 for ( element=stored; element->bv_val != NULL; element++ ) {
468 for (j = k; incoming[j].bv_val != NULL; j++) {
469 if (find_and_remove(&(incoming[j]), element, 2)) {
486 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
490 struct berval init_incoming;
491 struct berval final_incoming;
492 struct berval *remaining_incoming = NULL;
494 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
495 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
498 init_incoming = incoming->f_sub_initial;
499 final_incoming = incoming->f_sub_final;
501 if (find_and_remove(&init_incoming,
502 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
503 &(stored->f_sub_final), 3))
505 if (stored->f_sub_any == NULL) {
509 remaining_incoming = merge_init_final(op, &init_incoming,
510 incoming->f_sub_any, &final_incoming);
511 rc = strings_containment(stored->f_sub_any, remaining_incoming);
512 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
519 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
521 struct berval incoming_val[2];
524 incoming_val[1] = incoming->f_av_value;
526 if (find_and_remove(incoming_val+1,
527 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
528 &(stored->f_sub_final), 3)) {
529 if (stored->f_sub_any == NULL){
533 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
534 BER_BVZERO( incoming_val+1 );
535 rc = strings_containment(stored->f_sub_any, incoming_val);
536 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
543 filter_first( Filter *f )
545 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
552 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
557 MatchingRule* mrule = NULL;
566 /* substring matches sort to the end, and we just have to
567 * walk the entire list.
569 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
570 ptr = tavl_end( root, 1 );
573 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
574 dir = (first->f_choice == LDAP_FILTER_LE) ? TAVL_DIR_LEFT :
584 switch (fs->f_choice) {
585 case LDAP_FILTER_EQUALITY:
586 if (fi->f_choice == LDAP_FILTER_EQUALITY)
587 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
593 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
600 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
601 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
602 &(fi->f_ava->aa_value),
603 &(fs->f_ava->aa_value), &text);
604 if (rc != LDAP_SUCCESS) {
608 switch (fs->f_choice) {
610 case LDAP_FILTER_AND:
615 case LDAP_FILTER_SUBSTRINGS:
616 /* check if the equality query can be
617 * answered with cached substring query */
618 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
619 && substr_containment_equality( op,
622 /* check if the substring query can be
623 * answered with cached substring query */
624 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
625 ) && substr_containment_substr( op,
631 case LDAP_FILTER_PRESENT:
636 case LDAP_FILTER_EQUALITY:
643 if (mrule && ret >= 0)
649 if (mrule && ret <= 0)
654 case LDAP_FILTER_NOT:
660 } while((res) && (fi != NULL) && (fs != NULL));
664 ptr = tavl_next( ptr, dir );
669 /* check whether query is contained in any of
670 * the cached queries in template
673 query_containment(Operation *op, query_manager *qm,
675 QueryTemplate *templa)
678 int depth = 0, tscope;
679 Qbase qbase, *qbptr = NULL;
682 if (query->filter != NULL) {
685 Debug( pcache_debug, "Lock QC index = %p\n",
687 qbase.base = query->base;
689 first = filter_first( query->filter );
691 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
694 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
696 tscope = query->scope;
697 /* Find a matching scope:
698 * match at depth 0 OK
701 * subord at depth > 0 OK
702 * subtree at any depth OK
704 * subtree or subord at any depth OK
706 * subtree or subord at any depth OK
708 * subord at depth > 0 OK
709 * subtree at any depth OK
711 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
712 switch ( query->scope ) {
713 case LDAP_SCOPE_BASE:
714 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
715 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
716 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
719 if ( tscope == LDAP_SCOPE_BASE )
720 tscope = LDAP_SCOPE_ONE;
721 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
723 if ( tscope < LDAP_SCOPE_SUBTREE )
724 tscope = LDAP_SCOPE_SUBTREE;
726 case LDAP_SCOPE_SUBTREE:
727 if ( tscope < LDAP_SCOPE_SUBTREE )
728 tscope = LDAP_SCOPE_SUBTREE;
729 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
731 case LDAP_SCOPE_CHILDREN:
732 if ( tscope < LDAP_SCOPE_SUBTREE )
733 tscope = LDAP_SCOPE_SUBTREE;
736 if ( !qbptr->scopes[tscope] ) continue;
739 qc = find_filter( op, qbptr->scopes[tscope],
740 query->filter, first );
742 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
743 if (qm->lru_top != qc) {
744 remove_query(qm, qc);
745 add_query_on_top(qm, qc);
747 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
752 if ( be_issuffix( op->o_bd, &qbase.base ))
755 dnParent( &qbase.base, &pdn );
761 "Not answerable: Unlock QC index=%p\n",
763 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
769 free_query (CachedQuery* qc)
771 free(qc->q_uuid.bv_val);
772 filter_free(qc->filter);
777 /* Add query to query cache */
778 static void add_query(
781 QueryTemplate *templ,
784 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
787 new_cached_query->qtemp = templ;
789 new_cached_query->q_uuid = *uuid;
790 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
792 BER_BVZERO( &new_cached_query->q_uuid );
793 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
795 new_cached_query->lru_up = NULL;
796 new_cached_query->lru_down = NULL;
797 Debug( pcache_debug, "Added query expires at %ld\n",
798 (long) new_cached_query->expiry_time, 0, 0 );
800 new_cached_query->scope = query->scope;
801 new_cached_query->filter = query->filter;
802 new_cached_query->first = filter_first( query->filter );
804 qb.base = query->base;
807 Debug( pcache_debug, "Lock AQ index = %p\n",
809 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
810 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
812 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
813 qbase->base.bv_len =qb.base.bv_len;
814 qbase->base.bv_val = (char *)(qbase+1);
815 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
816 qbase->base.bv_val[qbase->base.bv_len] = '\0';
817 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
819 if (templ->query == NULL)
820 templ->query_last = new_cached_query;
822 templ->query->prev = new_cached_query;
823 new_cached_query->next = templ->query;
824 new_cached_query->prev = NULL;
825 new_cached_query->qbase = qbase;
826 tavl_insert( &qbase->scopes[query->scope], new_cached_query,
827 pcache_filter_cmp, avl_dup_ok );
828 templ->query = new_cached_query;
829 templ->no_of_queries++;
830 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
831 templ, templ->no_of_queries, 0 );
833 Debug( pcache_debug, "Unlock AQ index = %p \n",
835 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
837 /* Adding on top of LRU list */
838 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
839 add_query_on_top(qm, new_cached_query);
840 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
844 remove_from_template (CachedQuery* qc, QueryTemplate* template)
846 if (!qc->prev && !qc->next) {
847 template->query_last = template->query = NULL;
848 } else if (qc->prev == NULL) {
849 qc->next->prev = NULL;
850 template->query = qc->next;
851 } else if (qc->next == NULL) {
852 qc->prev->next = NULL;
853 template->query_last = qc->prev;
855 qc->next->prev = qc->prev;
856 qc->prev->next = qc->next;
858 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
859 if ( qc->qbase->scopes[0] == NULL &&
860 qc->qbase->scopes[1] == NULL &&
861 qc->qbase->scopes[2] == NULL &&
862 qc->qbase->scopes[3] == NULL ) {
863 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
864 ch_free( qc->qbase );
868 template->no_of_queries--;
871 /* remove bottom query of LRU list from the query cache */
872 static void cache_replacement(query_manager* qm, struct berval *result)
877 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
878 bottom = qm->lru_bottom;
880 result->bv_val = NULL;
884 Debug ( pcache_debug,
885 "Cache replacement invoked without "
886 "any query in LRU list\n", 0, 0, 0 );
887 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
891 temp = bottom->qtemp;
892 remove_query(qm, bottom);
893 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
895 *result = bottom->q_uuid;
896 bottom->q_uuid.bv_val = NULL;
898 Debug( pcache_debug, "Lock CR index = %p\n", temp, 0, 0 );
899 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
900 remove_from_template(bottom, temp);
901 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
902 temp, temp->no_of_queries, 0 );
903 Debug( pcache_debug, "Unlock CR index = %p\n", temp, 0, 0 );
904 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
909 struct query_info *next;
921 struct query_info *qi;
924 if ( rs->sr_type != REP_SEARCH ) return 0;
926 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
927 if (attr->a_desc == ad_queryid) {
928 for (count=0; attr->a_vals[count].bv_val; count++)
933 if ( count == 0 ) return 0;
934 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
935 qi->next = op->o_callback->sc_private;
936 op->o_callback->sc_private = qi;
937 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
938 qi->del = ( count == 1 );
947 struct berval* query_uuid)
949 struct query_info *qi, *qnext;
951 #ifdef LDAP_COMP_MATCH
952 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
954 AttributeAssertion ava = { NULL, BER_BVNULL };
956 Filter filter = {LDAP_FILTER_EQUALITY};
957 SlapReply sreply = {REP_RESULT};
958 slap_callback cb = { NULL, remove_func, NULL, NULL };
961 sreply.sr_entry = NULL;
962 sreply.sr_nentries = 0;
963 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
964 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
966 filter.f_av_desc = ad_queryid;
967 filter.f_av_value = *query_uuid;
969 op->o_tag = LDAP_REQ_SEARCH;
970 op->o_protocol = LDAP_VERSION3;
971 op->o_callback = &cb;
972 op->o_time = slap_get_time();
973 op->o_do_not_cache = 1;
975 op->o_req_dn = op->o_bd->be_suffix[0];
976 op->o_req_ndn = op->o_bd->be_nsuffix[0];
977 op->ors_scope = LDAP_SCOPE_SUBTREE;
978 op->ors_deref = LDAP_DEREF_NEVER;
979 op->ors_slimit = SLAP_NO_LIMIT;
980 op->ors_tlimit = SLAP_NO_LIMIT;
981 op->ors_filter = &filter;
982 op->ors_filterstr.bv_val = filter_str;
983 op->ors_filterstr.bv_len = strlen(filter_str);
984 op->ors_attrs = NULL;
985 op->ors_attrsonly = 0;
987 op->o_bd->be_search( op, &sreply );
989 for ( qi=cb.sc_private; qi; qi=qnext ) {
992 op->o_req_dn = qi->xdn;
993 op->o_req_ndn = qi->xdn;
996 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
997 query_uuid->bv_val, 0, 0 );
999 op->o_tag = LDAP_REQ_DELETE;
1001 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1006 struct berval vals[2];
1008 vals[0] = *query_uuid;
1009 vals[1].bv_val = NULL;
1011 mod.sml_op = LDAP_MOD_DELETE;
1013 mod.sml_desc = ad_queryid;
1014 mod.sml_type = ad_queryid->ad_cname;
1015 mod.sml_values = vals;
1016 mod.sml_nvalues = NULL;
1017 mod.sml_next = NULL;
1018 Debug( pcache_debug,
1019 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1020 query_uuid->bv_val, 0, 0 );
1022 op->orm_modlist = &mod;
1024 op->o_bd->be_modify( op, &sreply );
1026 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1027 op->o_tmpfree( qi, op->o_tmpmemctx );
1034 AttributeName* attrs,
1043 struct berval *fstr,
1044 AttributeName** filter_attrs,
1046 int* filter_got_oc )
1048 AttributeDescription *ad;
1050 switch ( f->f_choice ) {
1051 case LDAP_FILTER_EQUALITY:
1053 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1054 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1057 case LDAP_FILTER_GE:
1059 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1060 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1063 case LDAP_FILTER_LE:
1065 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1066 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1069 case LDAP_FILTER_APPROX:
1071 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1072 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1075 case LDAP_FILTER_SUBSTRINGS:
1077 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1078 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1081 case LDAP_FILTER_PRESENT:
1083 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1084 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1087 case LDAP_FILTER_AND:
1088 case LDAP_FILTER_OR:
1089 case LDAP_FILTER_NOT: {
1091 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1092 f->f_choice == LDAP_FILTER_AND ? '&' :
1093 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1094 fstr->bv_len += sizeof("(%") - 1;
1096 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1097 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1101 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1102 fstr->bv_len += sizeof(")") - 1;
1108 strcpy( fstr->bv_val, "(?=?)" );
1109 fstr->bv_len += sizeof("(?=?)")-1;
1113 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1114 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1116 (*filter_attrs)[*filter_cnt].an_desc = ad;
1117 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1118 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1119 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1120 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1122 if ( ad == slap_schema.si_ad_objectClass )
1127 struct search_info {
1130 QueryTemplate *qtemp;
1131 AttributeName* save_attrs; /* original attributes, saved for response */
1142 struct berval *query_uuid)
1144 struct search_info *si = op->o_callback->sc_private;
1145 slap_overinst *on = si->on;
1146 cache_manager *cm = on->on_bi.bi_private;
1147 query_manager* qm = cm->qm;
1150 struct berval crp_uuid;
1151 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1152 Operation op_tmp = *op;
1154 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1155 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1157 op_tmp.o_bd = &cm->db;
1158 op_tmp.o_dn = cm->db.be_rootdn;
1159 op_tmp.o_ndn = cm->db.be_rootndn;
1161 Debug( pcache_debug, "UUID for query being added = %s\n",
1164 for ( e=si->head; e; e=si->head ) {
1165 si->head = e->e_private;
1166 e->e_private = NULL;
1167 while ( cm->cur_entries > (cm->max_entries) ) {
1168 qm->crfunc(qm, &crp_uuid);
1169 if (crp_uuid.bv_val) {
1170 Debug( pcache_debug,
1171 "Removing query UUID %s\n",
1172 crp_uuid.bv_val, 0, 0 );
1173 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1174 Debug( pcache_debug,
1175 "QUERY REMOVED, SIZE=%d\n",
1177 ldap_pvt_thread_mutex_lock(
1179 cm->cur_entries -= return_val;
1180 cm->num_cached_queries--;
1181 Debug( pcache_debug,
1182 "STORED QUERIES = %lu\n",
1183 cm->num_cached_queries, 0, 0 );
1184 ldap_pvt_thread_mutex_unlock(
1186 Debug( pcache_debug,
1187 "QUERY REMOVED, CACHE ="
1189 cm->cur_entries, 0, 0 );
1193 return_val = merge_entry(&op_tmp, e, query_uuid);
1194 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1195 cm->cur_entries += return_val;
1196 Debug( pcache_debug,
1197 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1198 cm->cur_entries, 0, 0 );
1200 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1211 struct search_info *si = op->o_callback->sc_private;
1212 slap_overinst *on = si->on;
1213 cache_manager *cm = on->on_bi.bi_private;
1214 query_manager* qm = cm->qm;
1217 if ( si->save_attrs != NULL ) {
1218 rs->sr_attrs = si->save_attrs;
1219 op->ors_attrs = si->save_attrs;
1220 si->save_attrs = NULL;
1223 if ( rs->sr_type == REP_SEARCH ) {
1225 /* If we haven't exceeded the limit for this query,
1226 * build a chain of answers to store. If we hit the
1227 * limit, empty the chain and ignore the rest.
1230 if ( si->count < si->max ) {
1232 e = entry_dup( rs->sr_entry );
1233 if ( !si->head ) si->head = e;
1234 if ( si->tail ) si->tail->e_private = e;
1239 for (;si->head; si->head=e) {
1240 e = si->head->e_private;
1241 si->head->e_private = NULL;
1242 entry_free(si->head);
1248 } else if ( rs->sr_type == REP_RESULT ) {
1249 QueryTemplate* templ = si->qtemp;
1250 if (( si->count && cache_entries( op, rs, &uuid ) == 0 ) ||
1251 ( templ->negttl && !si->count && !si->over &&
1252 rs->sr_err == LDAP_SUCCESS )) {
1253 qm->addfunc(qm, &si->query, si->qtemp,
1254 si->count ? &uuid : NULL);
1256 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1257 cm->num_cached_queries++;
1258 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1259 cm->num_cached_queries, 0, 0 );
1260 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1262 /* If the consistency checker suspended itself,
1265 if ( cm->cc_paused ) {
1266 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1267 if ( cm->cc_paused ) {
1269 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1271 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1274 filter_free( si->query.filter );
1278 op->o_callback->sc_cleanup = slap_freeself_cb;
1280 return SLAP_CB_CONTINUE;
1286 AttributeName** new_attrs,
1287 struct attr_set *attrs,
1288 AttributeName* filter_attrs,
1298 /* duplicate attrs */
1299 count = attrs->count + fattr_cnt;
1300 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1305 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1306 sizeof(AttributeName));
1307 for (i=0; i<attrs->count; i++) {
1308 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1309 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1311 BER_BVZERO( &(*new_attrs)[i].an_name );
1312 alluser = an_find(*new_attrs, &AllUser);
1313 allop = an_find(*new_attrs, &AllOper);
1316 for ( i=0; i<fattr_cnt; i++ ) {
1317 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1319 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1324 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1325 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1326 (*new_attrs)[j].an_oc = NULL;
1327 (*new_attrs)[j].an_oc_exclude = 0;
1331 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1332 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1333 (*new_attrs)[j].an_oc = NULL;
1334 (*new_attrs)[j].an_oc_exclude = 0;
1337 BER_BVZERO( &(*new_attrs)[j].an_name );
1340 /* NOTE: this is a quick workaround to let pcache minimally interact
1341 * with pagedResults. A more articulated solutions would be to
1342 * perform the remote query without control and cache all results,
1343 * performing the pagedResults search only within the client
1344 * and the proxy. This requires pcache to understand pagedResults. */
1346 pcache_chk_controls(
1350 const char *non = "";
1351 const char *stripped = "";
1353 switch( op->o_pagedresults ) {
1354 case SLAP_CONTROL_NONCRITICAL:
1356 stripped = "; stripped";
1359 case SLAP_CONTROL_CRITICAL:
1360 Debug( pcache_debug, "%s: "
1361 "%scritical pagedResults control "
1362 "disabled with proxy cache%s.\n",
1363 op->o_log_prefix, non, stripped );
1365 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1369 rs->sr_err = SLAP_CB_CONTINUE;
1381 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1382 cache_manager *cm = on->on_bi.bi_private;
1383 query_manager* qm = cm->qm;
1387 AttributeName *filter_attrs = NULL;
1390 QueryTemplate *qtemp = NULL;
1393 CachedQuery *answerable = NULL;
1396 int fattr_got_oc = 0;
1398 struct berval tempstr;
1400 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1402 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1403 &fattr_cnt, &fattr_got_oc )) {
1404 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1405 return SLAP_CB_CONTINUE;
1408 Debug( pcache_debug, "query template of incoming query = %s\n",
1409 tempstr.bv_val, 0, 0 );
1411 /* FIXME: cannot cache/answer requests with pagedResults control */
1414 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1416 query.filter = op->ors_filter;
1417 query.base = op->o_req_ndn;
1418 query.scope = op->ors_scope;
1420 /* check for query containment */
1421 if (attr_set > -1) {
1422 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1423 for (; qt; qt = qt->qtnext ) {
1424 /* find if template i can potentially answer tempstr */
1425 if (qt->querystr.bv_len != tempstr.bv_len ||
1426 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1430 Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1431 op->ors_filterstr.bv_val, 0, 0 );
1432 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1438 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1441 /* Need to clear the callbacks of the original operation,
1442 * in case there are other overlays */
1443 BackendDB *save_bd = op->o_bd;
1444 slap_callback *save_cb = op->o_callback;
1446 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1447 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1448 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1449 if ( BER_BVISNULL( &answerable->q_uuid )) {
1450 /* No entries cached, just an empty result set */
1452 send_ldap_result( op, rs );
1455 op->o_callback = NULL;
1456 i = cm->db.bd_info->bi_op_search( op, rs );
1459 op->o_callback = save_cb;
1463 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1465 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1466 if (cm->num_cached_queries >= cm->max_queries) {
1469 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1471 if (op->ors_attrsonly)
1476 struct search_info *si;
1478 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1479 query.filter = filter_dup(op->ors_filter, NULL);
1480 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1481 if ( !qtemp->t_attrs.count ) {
1482 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1483 &qm->attr_sets[attr_set],
1484 filter_attrs, fattr_cnt, fattr_got_oc);
1486 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1488 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1489 cb->sc_response = pcache_response;
1490 cb->sc_cleanup = NULL;
1491 cb->sc_private = (cb+1);
1492 si = cb->sc_private;
1496 si->max = cm->num_entries_limit ;
1501 si->save_attrs = op->ors_attrs;
1503 op->ors_attrs = qtemp->t_attrs.attrs;
1505 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1506 cb->sc_next = op->o_callback;
1507 op->o_callback = cb;
1510 slap_callback **pcb;
1512 /* need to move the callback at the end, in case other
1513 * overlays are present, so that the final entry is
1514 * actually cached */
1516 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1521 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1525 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1527 return SLAP_CB_CONTINUE;
1532 AttributeName* attrs,
1540 for ( ; attrs[count].an_name.bv_val; count++ );
1543 for (i=0; i<num; i++) {
1547 if ( count > qm->attr_sets[i].count )
1550 if ( !qm->attr_sets[i].count )
1554 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1555 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1573 struct re_s *rtask = arg;
1574 slap_overinst *on = rtask->arg;
1575 cache_manager *cm = on->on_bi.bi_private;
1576 query_manager *qm = cm->qm;
1577 Connection conn = {0};
1578 OperationBuffer opbuf;
1581 SlapReply rs = {REP_RESULT};
1582 CachedQuery* query, *query_prev;
1583 int return_val, pause = 1;
1584 QueryTemplate* templ;
1586 op = (Operation *) &opbuf;
1587 connection_fake_init( &conn, op, ctx );
1590 op->o_dn = cm->db.be_rootdn;
1591 op->o_ndn = cm->db.be_rootndn;
1595 for (templ = qm->templates; templ; templ=templ->qmnext) {
1596 query = templ->query_last;
1597 if ( query ) pause = 0;
1598 op->o_time = slap_get_time();
1599 while (query && (query->expiry_time < op->o_time)) {
1600 Debug( pcache_debug, "Lock CR index = %p\n",
1602 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1603 remove_from_template(query, templ);
1604 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1605 templ, templ->no_of_queries, 0 );
1606 Debug( pcache_debug, "Unlock CR index = %p\n",
1608 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1609 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1610 remove_query(qm, query);
1611 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1612 if ( BER_BVISNULL( &query->q_uuid ))
1615 return_val = remove_query_data(op, &rs, &query->q_uuid);
1616 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1618 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1619 cm->cur_entries -= return_val;
1620 cm->num_cached_queries--;
1621 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1622 cm->num_cached_queries, 0, 0 );
1623 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1624 Debug( pcache_debug,
1625 "STALE QUERY REMOVED, CACHE ="
1627 cm->cur_entries, 0, 0 );
1629 query = query->prev;
1630 free_query(query_prev);
1633 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1634 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1635 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1637 /* If there were no queries, defer processing for a while */
1638 cm->cc_paused = pause;
1639 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1641 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1646 #define MAX_ATTR_SETS 500
1656 static ConfigDriver pc_cf_gen;
1657 static ConfigLDAPadd pc_ldadd;
1658 static ConfigCfAdd pc_cfadd;
1660 static ConfigTable pccfg[] = {
1661 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1663 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1664 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1665 "DESC 'ProxyCache basic parameters' "
1666 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1667 { "proxyattrset", "index> <attributes...",
1668 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1669 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1670 "DESC 'A set of attributes to cache' "
1671 "SYNTAX OMsDirectoryString )", NULL, NULL },
1672 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1673 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1674 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1675 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1676 "SYNTAX OMsDirectoryString )", NULL, NULL },
1677 { "response-callback", "head|tail(default)",
1678 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1679 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1680 "DESC 'Response callback position in overlay stack' "
1681 "SYNTAX OMsDirectoryString )", NULL, NULL },
1682 { "proxyCacheQueries", "queries",
1683 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1684 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1685 "DESC 'Maximum number of queries to cache' "
1686 "SYNTAX OMsInteger )", NULL, NULL },
1688 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1691 static ConfigOCs pcocs[] = {
1692 { "( OLcfgOvOc:2.1 "
1693 "NAME 'olcPcacheConfig' "
1694 "DESC 'ProxyCache configuration' "
1695 "SUP olcOverlayConfig "
1696 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1697 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1698 { "( OLcfgOvOc:2.2 "
1699 "NAME 'olcPcacheDatabase' "
1700 "DESC 'Cache database configuration' "
1701 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1706 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1711 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1712 p->ce_bi->bi_cf_ocs != pcocs )
1713 return LDAP_CONSTRAINT_VIOLATION;
1715 on = (slap_overinst *)p->ce_bi;
1716 cm = on->on_bi.bi_private;
1718 return LDAP_SUCCESS;
1722 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1724 CfEntryInfo *pe = p->e_private;
1725 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1726 cache_manager *cm = on->on_bi.bi_private;
1729 /* FIXME: should not hardcode "olcDatabase" here */
1730 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1731 bv.bv_val = ca->msg;
1734 /* We can only create this entry if the database is table-driven
1736 if ( cm->db.bd_info->bi_cf_ocs )
1737 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1744 pc_cf_gen( ConfigArgs *c )
1746 slap_overinst *on = (slap_overinst *)c->bi;
1747 cache_manager* cm = on->on_bi.bi_private;
1748 query_manager* qm = cm->qm;
1749 QueryTemplate* temp;
1750 AttributeName* attr_name;
1751 AttributeName* attrarray;
1752 const char* text=NULL;
1757 if ( c->op == SLAP_CONFIG_EMIT ) {
1761 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1762 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1763 cm->num_entries_limit, cm->cc_period );
1765 value_add_one( &c->rvalue_vals, &bv );
1768 for (i=0; i<cm->numattrsets; i++) {
1769 if ( !qm->attr_sets[i].count ) continue;
1771 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1773 /* count the attr length */
1774 for ( attr_name = qm->attr_sets[i].attrs;
1775 attr_name->an_name.bv_val; attr_name++ )
1776 bv.bv_len += attr_name->an_name.bv_len + 1;
1778 bv.bv_val = ch_malloc( bv.bv_len+1 );
1779 ptr = lutil_strcopy( bv.bv_val, c->msg );
1780 for ( attr_name = qm->attr_sets[i].attrs;
1781 attr_name->an_name.bv_val; attr_name++ ) {
1783 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1785 ber_bvarray_add( &c->rvalue_vals, &bv );
1787 if ( !c->rvalue_vals )
1791 for (temp=qm->templates; temp; temp=temp->qmnext) {
1792 if ( temp->negttl ) {
1793 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1795 temp->attr_set_index,
1799 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1800 temp->attr_set_index,
1803 bv.bv_len += temp->querystr.bv_len + 2;
1804 bv.bv_val = ch_malloc( bv.bv_len+1 );
1807 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1809 strcpy( ptr, c->msg );
1810 ber_bvarray_add( &c->rvalue_vals, &bv );
1812 if ( !c->rvalue_vals )
1816 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1817 BER_BVSTR( &bv, "head" );
1819 BER_BVSTR( &bv, "tail" );
1821 value_add_one( &c->rvalue_vals, &bv );
1824 c->value_int = cm->max_queries;
1828 } else if ( c->op == LDAP_MOD_DELETE ) {
1829 return 1; /* FIXME */
1841 if ( cm->numattrsets > 0 ) {
1842 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1843 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1847 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1848 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1850 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1853 if ( cm->numattrsets <= 0 ) {
1854 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1855 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1858 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1859 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1860 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1864 if ( !backend_db_init( c->argv[1], &cm->db )) {
1865 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1866 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1870 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1871 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1873 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1876 if ( cm->max_entries <= 0 ) {
1877 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1878 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1882 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1883 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1885 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1888 if ( cm->num_entries_limit <= 0 ) {
1889 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1890 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1893 if ( cm->num_entries_limit > cm->max_entries ) {
1894 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1895 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1899 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1900 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1902 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1905 cm->cc_period = (time_t)t;
1906 Debug( pcache_debug,
1907 "Total # of attribute sets to be cached = %d.\n",
1908 cm->numattrsets, 0, 0 );
1909 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1910 sizeof( struct attr_set ) );
1913 if ( cm->numattrsets == 0 ) {
1914 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1915 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1918 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1919 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1921 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1925 if ( num < 0 || num >= cm->numattrsets ) {
1926 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1927 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1928 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1931 qm->attr_sets[num].flags |= PC_CONFIGURED;
1932 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1933 qm->attr_sets[num].count = c->argc - 2;
1934 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
1935 (c->argc-1) * sizeof( AttributeName ));
1936 attr_name = qm->attr_sets[num].attrs;
1937 for ( i = 2; i < c->argc; i++ ) {
1938 attr_name->an_desc = NULL;
1939 if ( slap_str2ad( c->argv[i],
1940 &attr_name->an_desc, &text ) )
1942 strcpy( c->msg, text );
1943 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1944 ch_free( qm->attr_sets[num].attrs );
1945 qm->attr_sets[num].attrs = NULL;
1946 qm->attr_sets[num].count = 0;
1949 attr_name->an_name = attr_name->an_desc->ad_cname;
1950 attr_name->an_oc = NULL;
1951 attr_name->an_oc_exclude = 0;
1952 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
1953 qm->attr_sets[num].flags |= PC_GOT_OC;
1955 BER_BVZERO( &attr_name->an_name );
1960 if ( cm->numattrsets == 0 ) {
1961 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1962 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1965 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
1966 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
1968 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1972 if ( i < 0 || i >= cm->numattrsets ||
1973 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
1974 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
1975 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1976 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1979 temp = ch_calloc( 1, sizeof( QueryTemplate ));
1980 temp->qmnext = qm->templates;
1981 qm->templates = temp;
1982 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
1983 temp->query = temp->query_last = NULL;
1984 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
1985 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
1987 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1990 temp->ttl = (time_t)t;
1991 if ( c->argc == 5 ) {
1992 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
1993 snprintf( c->msg, sizeof( c->msg ),
1994 "unable to parse template negttl=\"%s\"",
1996 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1999 temp->negttl = (time_t)t;
2004 temp->no_of_queries = 0;
2006 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2007 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2008 Debug( pcache_debug, " query template: %s\n",
2009 temp->querystr.bv_val, 0, 0 );
2010 temp->attr_set_index = i;
2011 qm->attr_sets[i].flags |= PC_REFERENCED;
2012 temp->qtnext = qm->attr_sets[i].templates;
2013 qm->attr_sets[i].templates = temp;
2014 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2015 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2016 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2017 Debug( pcache_debug, "\t%s\n",
2018 attrarray[i].an_name.bv_val, 0, 0 );
2021 temp->querystr.bv_val = NULL;
2024 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2025 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2027 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2028 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2031 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
2032 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2037 if ( c->value_int <= 0 ) {
2038 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
2039 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2042 cm->max_queries = c->value_int;
2057 slap_overinst *on = (slap_overinst *)be->bd_info;
2058 cache_manager* cm = on->on_bi.bi_private;
2060 /* Something for the cache database? */
2061 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2062 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2064 return SLAP_CONF_UNKNOWN;
2072 slap_overinst *on = (slap_overinst *)be->bd_info;
2076 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2077 on->on_bi.bi_private = cm;
2079 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2082 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2083 cm->db.be_private = NULL;
2084 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2086 cm->numattrsets = 0;
2087 cm->num_entries_limit = 5;
2088 cm->num_cached_queries = 0;
2089 cm->max_entries = 0;
2090 cm->cur_entries = 0;
2091 cm->max_queries = 10000;
2092 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2093 cm->cc_period = 1000;
2096 qm->attr_sets = NULL;
2097 qm->templates = NULL;
2099 qm->lru_bottom = NULL;
2101 qm->qcfunc = query_containment;
2102 qm->crfunc = cache_replacement;
2103 qm->addfunc = add_query;
2104 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2106 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2115 slap_overinst *on = (slap_overinst *)be->bd_info;
2116 cache_manager *cm = on->on_bi.bi_private;
2117 query_manager* qm = cm->qm;
2118 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2120 /* check attr sets */
2121 for ( i = 0; i < cm->numattrsets; i++) {
2122 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2123 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2124 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2128 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2132 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2133 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2138 if ( ncf || rf || nrf ) {
2139 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2140 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2141 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2148 /* need to inherit something from the original database... */
2149 cm->db.be_def_limit = be->be_def_limit;
2150 cm->db.be_limits = be->be_limits;
2151 cm->db.be_acl = be->be_acl;
2152 cm->db.be_dfltaccess = be->be_dfltaccess;
2154 rc = backend_startup_one( &cm->db );
2156 /* There is no runqueue in TOOL mode */
2157 if ( slapMode & SLAP_SERVER_MODE ) {
2158 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2159 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2160 consistency_check, on,
2161 "pcache_consistency", be->be_suffix[0].bv_val );
2162 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2164 /* Cached database must have the rootdn */
2165 if ( BER_BVISNULL( &cm->db.be_rootndn )
2166 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2168 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2169 "underlying database of type \"%s\"\n"
2170 " serving naming context \"%s\"\n"
2171 " has no \"rootdn\", required by \"proxycache\".\n",
2172 on->on_info->oi_orig->bi_type,
2173 cm->db.be_suffix[0].bv_val, 0 );
2182 pcache_free_qbase( void *v )
2188 tavl_free( qb->scopes[i], NULL );
2197 slap_overinst *on = (slap_overinst *)be->bd_info;
2198 cache_manager *cm = on->on_bi.bi_private;
2199 query_manager *qm = cm->qm;
2203 /* cleanup stuff inherited from the original database... */
2204 cm->db.be_limits = NULL;
2205 cm->db.be_acl = NULL;
2207 if ( cm->db.bd_info->bi_db_close ) {
2208 rc = cm->db.bd_info->bi_db_close( &cm->db );
2210 while ( tm = qm->templates ) {
2211 CachedQuery *qc, *qn;
2212 qm->templates = tm->qmnext;
2213 for ( qc = tm->query; qc; qc = qn ) {
2217 avl_free( tm->qbase, pcache_free_qbase );
2218 free( tm->querystr.bv_val );
2219 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2220 free( tm->t_attrs.attrs );
2224 for ( i=0; i<cm->numattrsets; i++ ) {
2225 free( qm->attr_sets[i].attrs );
2227 free( qm->attr_sets );
2228 qm->attr_sets = NULL;
2238 slap_overinst *on = (slap_overinst *)be->bd_info;
2239 cache_manager *cm = on->on_bi.bi_private;
2240 query_manager *qm = cm->qm;
2242 /* cleanup stuff inherited from the original database... */
2243 cm->db.be_suffix = NULL;
2244 cm->db.be_nsuffix = NULL;
2245 BER_BVZERO( &cm->db.be_rootdn );
2246 BER_BVZERO( &cm->db.be_rootndn );
2247 BER_BVZERO( &cm->db.be_rootpw );
2248 /* FIXME: there might be more... */
2250 if ( cm->db.be_private != NULL ) {
2251 backend_destroy_one( &cm->db, 0 );
2254 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2255 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2262 static slap_overinst pcache;
2264 static char *obsolete_names[] = {
2269 int pcache_initialize()
2271 LDAPAttributeType *at;
2274 struct berval debugbv = BER_BVC("pcache");
2276 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2279 at = ldap_str2attributetype( queryid_schema, &code, &err,
2280 LDAP_SCHEMA_ALLOW_ALL );
2282 Debug( LDAP_DEBUG_ANY,
2283 "pcache_initialize: ldap_str2attributetype failed %s %s\n",
2284 ldap_scherr2str(code), err, 0 );
2287 code = at_add( at, 0, NULL, &err );
2289 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2293 Debug( LDAP_DEBUG_ANY,
2294 "pcache_initialize: at_add failed %s %s\n",
2295 scherr2str(code), err, 0 );
2299 pcache.on_bi.bi_type = "pcache";
2300 pcache.on_bi.bi_obsolete_names = obsolete_names;
2301 pcache.on_bi.bi_db_init = pcache_db_init;
2302 pcache.on_bi.bi_db_config = pcache_db_config;
2303 pcache.on_bi.bi_db_open = pcache_db_open;
2304 pcache.on_bi.bi_db_close = pcache_db_close;
2305 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2307 pcache.on_bi.bi_op_search = pcache_op_search;
2309 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2311 pcache.on_bi.bi_cf_ocs = pcocs;
2313 code = config_register_schema( pccfg, pcocs );
2314 if ( code ) return code;
2316 return overlay_register( &pcache );
2319 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2320 int init_module(int argc, char *argv[]) {
2321 return pcache_initialize();
2325 #endif /* defined(SLAPD_OVER_PROXYCACHE) */