2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2007 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 */
55 /* struct representing a cached query */
56 typedef struct cached_query_s {
61 struct berval q_uuid; /* query identifier */
62 struct query_template_s *qtemp; /* template of the query */
63 time_t expiry_time; /* time till the query is considered valid */
64 struct cached_query_s *next; /* next query in the template */
65 struct cached_query_s *prev; /* previous query in the template */
66 struct cached_query_s *lru_up; /* previous query in the LRU list */
67 struct cached_query_s *lru_down; /* next query in the LRU list */
71 * Represents a set of projected attributes.
75 struct query_template_s *templates;
76 AttributeName* attrs; /* specifies the set */
78 #define PC_CONFIGURED (0x1)
79 #define PC_REFERENCED (0x2)
80 #define PC_GOT_OC (0x4)
81 int count; /* number of attributes */
84 /* struct representing a query template
85 * e.g. template string = &(cn=)(mail=)
87 typedef struct query_template_s {
88 struct query_template_s *qtnext;
89 struct query_template_s *qmnext;
92 CachedQuery* query; /* most recent query cached for the template */
93 CachedQuery* query_last; /* oldest query cached for the template */
94 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
95 struct berval querystr; /* Filter string corresponding to the QT */
97 int attr_set_index; /* determines the projected attributes */
98 int no_of_queries; /* Total number of queries in the template */
99 time_t ttl; /* TTL for the queries of this template */
100 time_t negttl; /* TTL for negative results */
101 struct attr_set t_attrs; /* filter attrs + attr_set */
104 struct query_manager_s;
106 /* prototypes for functions for 1) query containment
107 * 2) query addition, 3) cache replacement
109 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
110 typedef CachedQuery * (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
111 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
113 /* LDAP query cache */
114 typedef struct query_manager_s {
115 struct attr_set* attr_sets; /* possible sets of projected attributes */
116 QueryTemplate* templates; /* cacheable templates */
118 CachedQuery* lru_top; /* top and bottom of LRU list */
119 CachedQuery* lru_bottom;
121 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
123 /* Query cache methods */
124 QCfunc *qcfunc; /* Query containment*/
125 CRfunc *crfunc; /* cache replacement */
126 AddQueryfunc *addfunc; /* add query */
129 /* LDAP query cache manager */
130 typedef struct cache_manager_s {
131 BackendDB db; /* underlying database */
132 unsigned long num_cached_queries; /* total number of cached queries */
133 unsigned long max_queries; /* upper bound on # of cached queries */
134 int numattrsets; /* number of attribute sets */
135 int cur_entries; /* current number of entries cached */
136 int max_entries; /* max number of entries cached */
137 int num_entries_limit; /* max # of entries in a cacheable query */
139 char response_cb; /* install the response callback
140 * at the tail of the callback list */
141 #define PCACHE_RESPONSE_CB_HEAD 0
142 #define PCACHE_RESPONSE_CB_TAIL 1
144 time_t cc_period; /* interval between successive consistency checks (sec) */
148 ldap_pvt_thread_mutex_t cache_mutex;
150 query_manager* qm; /* query cache managed by the cache manager */
153 static int pcache_debug;
155 static AttributeDescription *ad_queryid;
156 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
157 "DESC 'list of queries the entry belongs to' "
158 "EQUALITY octetStringMatch "
159 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
160 "NO-USER-MODIFICATION USAGE directoryOperation )";
162 /* Return 1 for an added entry, else 0 */
167 struct berval* query_uuid )
170 Modifications* modlist = NULL;
171 const char* text = NULL;
173 char textbuf[SLAP_TEXT_BUFLEN];
174 size_t textlen = sizeof(textbuf);
176 SlapReply sreply = {REP_RESULT};
178 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
183 /* add queryid attribute */
184 attr_merge_one( e, ad_queryid, query_uuid, NULL );
186 /* append the attribute list from the fetched entry */
187 e->e_attrs->a_next = attr;
189 op->o_tag = LDAP_REQ_ADD;
190 op->o_protocol = LDAP_VERSION3;
191 op->o_callback = &cb;
192 op->o_time = slap_get_time();
193 op->o_do_not_cache = 1;
196 op->o_req_dn = e->e_name;
197 op->o_req_ndn = e->e_nname;
198 rc = op->o_bd->be_add( op, &sreply );
200 if ( rc != LDAP_SUCCESS ) {
201 if ( rc == LDAP_ALREADY_EXISTS ) {
202 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
203 modlist->sml_op = LDAP_MOD_ADD;
204 op->o_tag = LDAP_REQ_MODIFY;
205 op->orm_modlist = modlist;
206 op->o_bd->be_modify( op, &sreply );
207 slap_mods_free( modlist, 1 );
208 } else if ( rc == LDAP_REFERRAL ||
209 rc == LDAP_NO_SUCH_OBJECT ) {
210 syncrepl_add_glue( op, e );
219 if ( op->ora_e == e )
220 be_entry_release_w( op, e );
227 /* Length-ordered sort on normalized DNs */
228 static int pcache_dn_cmp( const void *v1, const void *v2 )
230 const Qbase *q1 = v1, *q2 = v2;
232 int rc = q1->base.bv_len - q2->base.bv_len;
234 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
238 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
241 dif = bv1->bv_len - bv2->bv_len;
243 if ( dif > 0 ) len -= dif;
244 len = memcmp( bv1->bv_val, bv2->bv_val, len );
250 /* compare the first value in each filter */
251 static int pcache_filter_cmp( const void *v1, const void *v2 )
253 const CachedQuery *q1 = v1, *q2 =v2;
254 int rc, weight1, weight2;
256 switch( q1->first->f_choice ) {
257 case LDAP_FILTER_PRESENT:
260 case LDAP_FILTER_EQUALITY:
268 switch( q2->first->f_choice ) {
269 case LDAP_FILTER_PRESENT:
272 case LDAP_FILTER_EQUALITY:
280 rc = weight1 - weight2;
285 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
288 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
290 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
291 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
292 rc = lex_bvcmp( &q1->first->f_sub_initial,
293 &q2->first->f_sub_initial );
297 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
301 if ( q1->first->f_sub_any ) {
302 if ( q2->first->f_sub_any ) {
303 rc = lex_bvcmp( q1->first->f_sub_any,
304 q2->first->f_sub_any );
308 } else if ( q2->first->f_sub_any ) {
312 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
313 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
314 rc = lex_bvcmp( &q1->first->f_sub_final,
315 &q2->first->f_sub_final );
319 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
323 rc = lex_bvcmp( &q1->first->f_mr_value,
324 &q2->first->f_mr_value );
333 /* add query on top of LRU list */
335 add_query_on_top (query_manager* qm, CachedQuery* qc)
337 CachedQuery* top = qm->lru_top;
348 Debug( pcache_debug, "Base of added query = %s\n",
349 qc->qbase->base.bv_val, 0, 0 );
352 /* remove_query from LRU list */
355 remove_query (query_manager* qm, CachedQuery* qc)
378 qc->lru_up = qc->lru_down = NULL;
381 /* find and remove string2 from string1
382 * from start if position = 1,
383 * from end if position = 3,
384 * from anywhere if position = 2
385 * string1 is overwritten if position = 2.
389 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
400 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
401 ber2->bv_val, ber2->bv_len )) {
403 ber1->bv_val += ber2->bv_len;
404 ber1->bv_len -= ber2->bv_len;
409 ber1->bv_val[ber1->bv_len] = '\0';
410 temp = strstr( ber1->bv_val, ber2->bv_val );
412 strcpy( temp, temp+ber2->bv_len );
413 ber1->bv_len -= ber2->bv_len;
419 if ( ber1->bv_len >= ber2->bv_len &&
420 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
423 ber1->bv_len -= ber2->bv_len;
431 static struct berval*
432 merge_init_final(Operation *op, struct berval* init, struct berval* any,
433 struct berval* final)
435 struct berval* merged, *temp;
436 int i, any_count, count;
438 for (any_count=0; any && any[any_count].bv_val; any_count++)
448 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
453 ber_dupbv_x( temp, init, op->o_tmpmemctx );
457 for (i=0; i<any_count; i++) {
458 ber_dupbv_x( temp, any, op->o_tmpmemctx );
463 ber_dupbv_x( temp, final, op->o_tmpmemctx );
470 /* Each element in stored must be found in incoming. Incoming is overwritten.
473 strings_containment(struct berval* stored, struct berval* incoming)
475 struct berval* element;
479 for ( element=stored; element->bv_val != NULL; element++ ) {
480 for (j = k; incoming[j].bv_val != NULL; j++) {
481 if (find_and_remove(&(incoming[j]), element, 2)) {
498 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
502 struct berval init_incoming;
503 struct berval final_incoming;
504 struct berval *remaining_incoming = NULL;
506 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
507 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
510 init_incoming = incoming->f_sub_initial;
511 final_incoming = incoming->f_sub_final;
513 if (find_and_remove(&init_incoming,
514 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
515 &(stored->f_sub_final), 3))
517 if (stored->f_sub_any == NULL) {
521 remaining_incoming = merge_init_final(op, &init_incoming,
522 incoming->f_sub_any, &final_incoming);
523 rc = strings_containment(stored->f_sub_any, remaining_incoming);
524 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
531 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
533 struct berval incoming_val[2];
536 incoming_val[1] = incoming->f_av_value;
538 if (find_and_remove(incoming_val+1,
539 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
540 &(stored->f_sub_final), 3)) {
541 if (stored->f_sub_any == NULL){
545 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
546 BER_BVZERO( incoming_val+1 );
547 rc = strings_containment(stored->f_sub_any, incoming_val);
548 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
555 filter_first( Filter *f )
557 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
564 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
568 MatchingRule* mrule = NULL;
569 int res=0, eqpass= 0;
577 /* substring matches sort to the end, and we just have to
578 * walk the entire list.
580 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
581 ptr = tavl_end( root, 1 );
584 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
585 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
594 /* an incoming substr query can only be satisfied by a cached
597 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
598 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
601 /* an incoming eq query can be satisfied by a cached eq or substr
604 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
606 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
607 nextpass: eqpass = 1;
608 ptr = tavl_end( root, 1 );
613 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
619 switch (fs->f_choice) {
620 case LDAP_FILTER_EQUALITY:
621 if (fi->f_choice == LDAP_FILTER_EQUALITY)
622 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
628 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
635 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
636 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
637 &(fi->f_ava->aa_value),
638 &(fs->f_ava->aa_value), &text);
639 if (rc != LDAP_SUCCESS) {
642 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
645 switch (fs->f_choice) {
647 case LDAP_FILTER_AND:
652 case LDAP_FILTER_SUBSTRINGS:
653 /* check if the equality query can be
654 * answered with cached substring query */
655 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
656 && substr_containment_equality( op,
659 /* check if the substring query can be
660 * answered with cached substring query */
661 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
662 ) && substr_containment_substr( op,
668 case LDAP_FILTER_PRESENT:
673 case LDAP_FILTER_EQUALITY:
680 if (mrule && ret >= 0)
686 if (mrule && ret <= 0)
691 case LDAP_FILTER_NOT:
697 } while((res) && (fi != NULL) && (fs != NULL));
701 ptr = tavl_next( ptr, dir );
706 /* check whether query is contained in any of
707 * the cached queries in template
710 query_containment(Operation *op, query_manager *qm,
712 QueryTemplate *templa)
715 int depth = 0, tscope;
716 Qbase qbase, *qbptr = NULL;
719 if (query->filter != NULL) {
722 Debug( pcache_debug, "Lock QC index = %p\n",
723 (void *) templa, 0, 0 );
724 qbase.base = query->base;
726 first = filter_first( query->filter );
728 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
731 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
733 tscope = query->scope;
734 /* Find a matching scope:
735 * match at depth 0 OK
738 * subord at depth > 0 OK
739 * subtree at any depth OK
741 * subtree or subord at any depth OK
743 * subtree or subord at any depth OK
745 * subord at depth > 0 OK
746 * subtree at any depth OK
748 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
749 switch ( query->scope ) {
750 case LDAP_SCOPE_BASE:
751 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
752 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
753 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
756 if ( tscope == LDAP_SCOPE_BASE )
757 tscope = LDAP_SCOPE_ONE;
758 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
760 if ( tscope < LDAP_SCOPE_SUBTREE )
761 tscope = LDAP_SCOPE_SUBTREE;
763 case LDAP_SCOPE_SUBTREE:
764 if ( tscope < LDAP_SCOPE_SUBTREE )
765 tscope = LDAP_SCOPE_SUBTREE;
766 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
768 case LDAP_SCOPE_CHILDREN:
769 if ( tscope < LDAP_SCOPE_SUBTREE )
770 tscope = LDAP_SCOPE_SUBTREE;
773 if ( !qbptr->scopes[tscope] ) continue;
776 qc = find_filter( op, qbptr->scopes[tscope],
777 query->filter, first );
779 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
780 if (qm->lru_top != qc) {
781 remove_query(qm, qc);
782 add_query_on_top(qm, qc);
784 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
789 if ( be_issuffix( op->o_bd, &qbase.base ))
792 dnParent( &qbase.base, &pdn );
798 "Not answerable: Unlock QC index=%p\n",
799 (void *) templa, 0, 0 );
800 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
806 free_query (CachedQuery* qc)
808 free(qc->q_uuid.bv_val);
809 filter_free(qc->filter);
814 /* Add query to query cache */
815 static CachedQuery * add_query(
819 QueryTemplate *templ,
822 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
827 new_cached_query->qtemp = templ;
828 BER_BVZERO( &new_cached_query->q_uuid );
830 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
832 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
834 new_cached_query->lru_up = NULL;
835 new_cached_query->lru_down = NULL;
836 Debug( pcache_debug, "Added query expires at %ld\n",
837 (long) new_cached_query->expiry_time, 0, 0 );
839 new_cached_query->scope = query->scope;
840 new_cached_query->filter = query->filter;
841 new_cached_query->first = first = filter_first( query->filter );
843 qb.base = query->base;
846 Debug( pcache_debug, "Lock AQ index = %p\n",
847 (void *) templ, 0, 0 );
848 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
849 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
851 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
852 qbase->base.bv_len =qb.base.bv_len;
853 qbase->base.bv_val = (char *)(qbase+1);
854 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
855 qbase->base.bv_val[qbase->base.bv_len] = '\0';
856 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
858 new_cached_query->next = templ->query;
859 new_cached_query->prev = NULL;
860 new_cached_query->qbase = qbase;
861 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
862 pcache_filter_cmp, avl_dup_error );
865 if (templ->query == NULL)
866 templ->query_last = new_cached_query;
868 templ->query->prev = new_cached_query;
869 templ->query = new_cached_query;
870 templ->no_of_queries++;
872 ch_free( new_cached_query );
873 new_cached_query = find_filter( op, qbase->scopes[query->scope],
874 query->filter, first );
875 filter_free( query->filter );
877 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
878 (void *) templ, templ->no_of_queries, 0 );
880 Debug( pcache_debug, "Unlock AQ index = %p \n",
881 (void *) templ, 0, 0 );
882 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
884 /* Adding on top of LRU list */
886 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
887 add_query_on_top(qm, new_cached_query);
888 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
890 return rc == 0 ? new_cached_query : NULL;
894 remove_from_template (CachedQuery* qc, QueryTemplate* template)
896 if (!qc->prev && !qc->next) {
897 template->query_last = template->query = NULL;
898 } else if (qc->prev == NULL) {
899 qc->next->prev = NULL;
900 template->query = qc->next;
901 } else if (qc->next == NULL) {
902 qc->prev->next = NULL;
903 template->query_last = qc->prev;
905 qc->next->prev = qc->prev;
906 qc->prev->next = qc->next;
908 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
909 qc->qbase->queries--;
910 if ( qc->qbase->queries == 0 ) {
911 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
912 ch_free( qc->qbase );
916 template->no_of_queries--;
919 /* remove bottom query of LRU list from the query cache */
920 static void cache_replacement(query_manager* qm, struct berval *result)
925 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
926 bottom = qm->lru_bottom;
928 result->bv_val = NULL;
932 Debug ( pcache_debug,
933 "Cache replacement invoked without "
934 "any query in LRU list\n", 0, 0, 0 );
935 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
939 temp = bottom->qtemp;
940 remove_query(qm, bottom);
941 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
943 *result = bottom->q_uuid;
944 bottom->q_uuid.bv_val = NULL;
946 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
947 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
948 remove_from_template(bottom, temp);
949 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
950 (void *) temp, temp->no_of_queries, 0 );
951 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
952 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
957 struct query_info *next;
969 struct query_info *qi;
972 if ( rs->sr_type != REP_SEARCH ) return 0;
974 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
975 if (attr->a_desc == ad_queryid) {
976 for (count=0; attr->a_vals[count].bv_val; count++)
981 if ( count == 0 ) return 0;
982 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
983 qi->next = op->o_callback->sc_private;
984 op->o_callback->sc_private = qi;
985 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
986 qi->del = ( count == 1 );
995 struct berval* query_uuid)
997 struct query_info *qi, *qnext;
999 #ifdef LDAP_COMP_MATCH
1000 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1002 AttributeAssertion ava = { NULL, BER_BVNULL };
1004 Filter filter = {LDAP_FILTER_EQUALITY};
1005 SlapReply sreply = {REP_RESULT};
1006 slap_callback cb = { NULL, remove_func, NULL, NULL };
1009 sreply.sr_entry = NULL;
1010 sreply.sr_nentries = 0;
1011 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1012 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
1013 filter.f_ava = &ava;
1014 filter.f_av_desc = ad_queryid;
1015 filter.f_av_value = *query_uuid;
1017 op->o_tag = LDAP_REQ_SEARCH;
1018 op->o_protocol = LDAP_VERSION3;
1019 op->o_callback = &cb;
1020 op->o_time = slap_get_time();
1021 op->o_do_not_cache = 1;
1023 op->o_req_dn = op->o_bd->be_suffix[0];
1024 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1025 op->ors_scope = LDAP_SCOPE_SUBTREE;
1026 op->ors_deref = LDAP_DEREF_NEVER;
1027 op->ors_slimit = SLAP_NO_LIMIT;
1028 op->ors_tlimit = SLAP_NO_LIMIT;
1029 op->ors_filter = &filter;
1030 op->ors_filterstr.bv_val = filter_str;
1031 op->ors_filterstr.bv_len = strlen(filter_str);
1032 op->ors_attrs = NULL;
1033 op->ors_attrsonly = 0;
1035 op->o_bd->be_search( op, &sreply );
1037 for ( qi=cb.sc_private; qi; qi=qnext ) {
1040 op->o_req_dn = qi->xdn;
1041 op->o_req_ndn = qi->xdn;
1044 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1045 query_uuid->bv_val, 0, 0 );
1047 op->o_tag = LDAP_REQ_DELETE;
1049 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1054 struct berval vals[2];
1056 vals[0] = *query_uuid;
1057 vals[1].bv_val = NULL;
1059 mod.sml_op = LDAP_MOD_DELETE;
1061 mod.sml_desc = ad_queryid;
1062 mod.sml_type = ad_queryid->ad_cname;
1063 mod.sml_values = vals;
1064 mod.sml_nvalues = NULL;
1065 mod.sml_next = NULL;
1066 Debug( pcache_debug,
1067 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1068 query_uuid->bv_val, 0, 0 );
1070 op->orm_modlist = &mod;
1072 op->o_bd->be_modify( op, &sreply );
1074 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1075 op->o_tmpfree( qi, op->o_tmpmemctx );
1082 AttributeName* attrs,
1091 struct berval *fstr,
1092 AttributeName** filter_attrs,
1094 int* filter_got_oc )
1096 AttributeDescription *ad;
1098 switch ( f->f_choice ) {
1099 case LDAP_FILTER_EQUALITY:
1101 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1102 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1105 case LDAP_FILTER_GE:
1107 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1108 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1111 case LDAP_FILTER_LE:
1113 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1114 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1117 case LDAP_FILTER_APPROX:
1119 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1120 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1123 case LDAP_FILTER_SUBSTRINGS:
1125 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1126 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1129 case LDAP_FILTER_PRESENT:
1131 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1132 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1135 case LDAP_FILTER_AND:
1136 case LDAP_FILTER_OR:
1137 case LDAP_FILTER_NOT: {
1139 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1140 f->f_choice == LDAP_FILTER_AND ? '&' :
1141 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1142 fstr->bv_len += sizeof("(%") - 1;
1144 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1145 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1149 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1150 fstr->bv_len += sizeof(")") - 1;
1156 strcpy( fstr->bv_val, "(?=?)" );
1157 fstr->bv_len += sizeof("(?=?)")-1;
1161 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1162 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1164 (*filter_attrs)[*filter_cnt].an_desc = ad;
1165 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1166 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1167 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1168 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1170 if ( ad == slap_schema.si_ad_objectClass )
1175 struct search_info {
1178 QueryTemplate *qtemp;
1179 AttributeName* save_attrs; /* original attributes, saved for response */
1190 struct berval *query_uuid)
1192 struct search_info *si = op->o_callback->sc_private;
1193 slap_overinst *on = si->on;
1194 cache_manager *cm = on->on_bi.bi_private;
1195 query_manager* qm = cm->qm;
1198 struct berval crp_uuid;
1199 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1200 Operation op_tmp = *op;
1202 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1203 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1205 op_tmp.o_bd = &cm->db;
1206 op_tmp.o_dn = cm->db.be_rootdn;
1207 op_tmp.o_ndn = cm->db.be_rootndn;
1209 Debug( pcache_debug, "UUID for query being added = %s\n",
1212 for ( e=si->head; e; e=si->head ) {
1213 si->head = e->e_private;
1214 e->e_private = NULL;
1215 while ( cm->cur_entries > (cm->max_entries) ) {
1216 qm->crfunc(qm, &crp_uuid);
1217 if (crp_uuid.bv_val) {
1218 Debug( pcache_debug,
1219 "Removing query UUID %s\n",
1220 crp_uuid.bv_val, 0, 0 );
1221 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1222 Debug( pcache_debug,
1223 "QUERY REMOVED, SIZE=%d\n",
1225 ldap_pvt_thread_mutex_lock(
1227 cm->cur_entries -= return_val;
1228 cm->num_cached_queries--;
1229 Debug( pcache_debug,
1230 "STORED QUERIES = %lu\n",
1231 cm->num_cached_queries, 0, 0 );
1232 ldap_pvt_thread_mutex_unlock(
1234 Debug( pcache_debug,
1235 "QUERY REMOVED, CACHE ="
1237 cm->cur_entries, 0, 0 );
1241 return_val = merge_entry(&op_tmp, e, query_uuid);
1242 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1243 cm->cur_entries += return_val;
1244 Debug( pcache_debug,
1245 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1246 cm->cur_entries, 0, 0 );
1248 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1259 struct search_info *si = op->o_callback->sc_private;
1260 slap_overinst *on = si->on;
1261 cache_manager *cm = on->on_bi.bi_private;
1262 query_manager* qm = cm->qm;
1264 if ( si->save_attrs != NULL ) {
1265 rs->sr_attrs = si->save_attrs;
1266 op->ors_attrs = si->save_attrs;
1267 si->save_attrs = NULL;
1270 if ( rs->sr_type == REP_SEARCH ) {
1272 /* If we haven't exceeded the limit for this query,
1273 * build a chain of answers to store. If we hit the
1274 * limit, empty the chain and ignore the rest.
1277 if ( si->count < si->max ) {
1279 e = entry_dup( rs->sr_entry );
1280 if ( !si->head ) si->head = e;
1281 if ( si->tail ) si->tail->e_private = e;
1286 for (;si->head; si->head=e) {
1287 e = si->head->e_private;
1288 si->head->e_private = NULL;
1289 entry_free(si->head);
1295 } else if ( rs->sr_type == REP_RESULT ) {
1297 ( si->qtemp->negttl && !si->count && !si->over &&
1298 rs->sr_err == LDAP_SUCCESS )) {
1299 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1304 cache_entries( op, rs, &qc->q_uuid );
1305 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1306 cm->num_cached_queries++;
1307 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1308 cm->num_cached_queries, 0, 0 );
1309 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1311 /* If the consistency checker suspended itself,
1314 if ( cm->cc_paused ) {
1315 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1316 if ( cm->cc_paused ) {
1318 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1320 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1322 } else if ( si->count ) {
1323 /* duplicate query, free it */
1325 for (;si->head; si->head=e) {
1326 e = si->head->e_private;
1327 si->head->e_private = NULL;
1328 entry_free(si->head);
1332 filter_free( si->query.filter );
1336 op->o_callback->sc_cleanup = slap_freeself_cb;
1338 return SLAP_CB_CONTINUE;
1344 AttributeName** new_attrs,
1345 struct attr_set *attrs,
1346 AttributeName* filter_attrs,
1356 /* duplicate attrs */
1357 count = attrs->count + fattr_cnt;
1358 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1363 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1364 sizeof(AttributeName));
1365 for (i=0; i<attrs->count; i++) {
1366 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1367 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1369 BER_BVZERO( &(*new_attrs)[i].an_name );
1370 alluser = an_find(*new_attrs, &AllUser);
1371 allop = an_find(*new_attrs, &AllOper);
1374 for ( i=0; i<fattr_cnt; i++ ) {
1375 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1377 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1382 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1383 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1384 (*new_attrs)[j].an_oc = NULL;
1385 (*new_attrs)[j].an_oc_exclude = 0;
1389 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1390 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1391 (*new_attrs)[j].an_oc = NULL;
1392 (*new_attrs)[j].an_oc_exclude = 0;
1395 BER_BVZERO( &(*new_attrs)[j].an_name );
1398 /* NOTE: this is a quick workaround to let pcache minimally interact
1399 * with pagedResults. A more articulated solutions would be to
1400 * perform the remote query without control and cache all results,
1401 * performing the pagedResults search only within the client
1402 * and the proxy. This requires pcache to understand pagedResults. */
1404 pcache_chk_controls(
1408 const char *non = "";
1409 const char *stripped = "";
1411 switch( op->o_pagedresults ) {
1412 case SLAP_CONTROL_NONCRITICAL:
1414 stripped = "; stripped";
1417 case SLAP_CONTROL_CRITICAL:
1418 Debug( pcache_debug, "%s: "
1419 "%scritical pagedResults control "
1420 "disabled with proxy cache%s.\n",
1421 op->o_log_prefix, non, stripped );
1423 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1427 rs->sr_err = SLAP_CB_CONTINUE;
1439 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1440 cache_manager *cm = on->on_bi.bi_private;
1441 query_manager* qm = cm->qm;
1445 AttributeName *filter_attrs = NULL;
1448 QueryTemplate *qtemp = NULL;
1451 CachedQuery *answerable = NULL;
1454 int fattr_got_oc = 0;
1456 struct berval tempstr;
1458 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1460 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1461 &fattr_cnt, &fattr_got_oc )) {
1462 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1463 return SLAP_CB_CONTINUE;
1466 Debug( pcache_debug, "query template of incoming query = %s\n",
1467 tempstr.bv_val, 0, 0 );
1469 /* FIXME: cannot cache/answer requests with pagedResults control */
1472 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1474 query.filter = op->ors_filter;
1475 query.base = op->o_req_ndn;
1476 query.scope = op->ors_scope;
1478 /* check for query containment */
1479 if (attr_set > -1) {
1480 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1481 for (; qt; qt = qt->qtnext ) {
1482 /* find if template i can potentially answer tempstr */
1483 if (qt->querystr.bv_len != tempstr.bv_len ||
1484 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1488 Debug( pcache_debug, "Entering QC, querystr = %s\n",
1489 op->ors_filterstr.bv_val, 0, 0 );
1490 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1496 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1499 /* Need to clear the callbacks of the original operation,
1500 * in case there are other overlays */
1501 BackendDB *save_bd = op->o_bd;
1502 slap_callback *save_cb = op->o_callback;
1504 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1505 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1506 if ( BER_BVISNULL( &answerable->q_uuid )) {
1507 /* No entries cached, just an empty result set */
1509 send_ldap_result( op, rs );
1512 op->o_callback = NULL;
1513 i = cm->db.bd_info->bi_op_search( op, rs );
1515 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1517 op->o_callback = save_cb;
1521 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1523 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1524 if (cm->num_cached_queries >= cm->max_queries) {
1527 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1529 if (op->ors_attrsonly)
1534 struct search_info *si;
1536 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1537 query.filter = filter_dup(op->ors_filter, NULL);
1538 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1539 if ( !qtemp->t_attrs.count ) {
1540 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1541 &qm->attr_sets[attr_set],
1542 filter_attrs, fattr_cnt, fattr_got_oc);
1544 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1546 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1547 cb->sc_response = pcache_response;
1548 cb->sc_cleanup = NULL;
1549 cb->sc_private = (cb+1);
1550 si = cb->sc_private;
1554 si->max = cm->num_entries_limit ;
1559 si->save_attrs = op->ors_attrs;
1561 op->ors_attrs = qtemp->t_attrs.attrs;
1563 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1564 cb->sc_next = op->o_callback;
1565 op->o_callback = cb;
1568 slap_callback **pcb;
1570 /* need to move the callback at the end, in case other
1571 * overlays are present, so that the final entry is
1572 * actually cached */
1574 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1579 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1583 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1585 return SLAP_CB_CONTINUE;
1590 AttributeName* attrs,
1598 for ( ; attrs[count].an_name.bv_val; count++ );
1601 for (i=0; i<num; i++) {
1605 if ( count > qm->attr_sets[i].count )
1608 if ( !qm->attr_sets[i].count )
1612 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1613 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1631 struct re_s *rtask = arg;
1632 slap_overinst *on = rtask->arg;
1633 cache_manager *cm = on->on_bi.bi_private;
1634 query_manager *qm = cm->qm;
1635 Connection conn = {0};
1636 OperationBuffer opbuf;
1639 SlapReply rs = {REP_RESULT};
1641 int return_val, pause = 1;
1642 QueryTemplate* templ;
1644 op = (Operation *) &opbuf;
1645 connection_fake_init( &conn, op, ctx );
1648 op->o_dn = cm->db.be_rootdn;
1649 op->o_ndn = cm->db.be_rootndn;
1653 for (templ = qm->templates; templ; templ=templ->qmnext) {
1654 query = templ->query_last;
1655 if ( query ) pause = 0;
1656 op->o_time = slap_get_time();
1657 while (query && (query->expiry_time < op->o_time)) {
1659 Debug( pcache_debug, "Lock CR index = %p\n",
1660 (void *) templ, 0, 0 );
1661 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1662 if ( query == templ->query_last ) {
1664 remove_from_template(query, templ);
1665 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1666 (void *) templ, templ->no_of_queries, 0 );
1667 Debug( pcache_debug, "Unlock CR index = %p\n",
1668 (void *) templ, 0, 0 );
1670 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1672 query = templ->query_last;
1675 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1676 remove_query(qm, query);
1677 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1678 if ( BER_BVISNULL( &query->q_uuid ))
1681 return_val = remove_query_data(op, &rs, &query->q_uuid);
1682 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1684 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1685 cm->cur_entries -= return_val;
1686 cm->num_cached_queries--;
1687 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1688 cm->num_cached_queries, 0, 0 );
1689 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1690 Debug( pcache_debug,
1691 "STALE QUERY REMOVED, CACHE ="
1693 cm->cur_entries, 0, 0 );
1695 query = templ->query_last;
1698 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1699 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1700 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1702 /* If there were no queries, defer processing for a while */
1703 cm->cc_paused = pause;
1704 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1706 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1711 #define MAX_ATTR_SETS 500
1721 static ConfigDriver pc_cf_gen;
1722 static ConfigLDAPadd pc_ldadd;
1723 static ConfigCfAdd pc_cfadd;
1725 static ConfigTable pccfg[] = {
1726 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1728 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1729 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1730 "DESC 'ProxyCache basic parameters' "
1731 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1732 { "proxyattrset", "index> <attributes...",
1733 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1734 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1735 "DESC 'A set of attributes to cache' "
1736 "SYNTAX OMsDirectoryString )", NULL, NULL },
1737 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1738 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1739 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1740 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1741 "SYNTAX OMsDirectoryString )", NULL, NULL },
1742 { "response-callback", "head|tail(default)",
1743 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1744 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1745 "DESC 'Response callback position in overlay stack' "
1746 "SYNTAX OMsDirectoryString )", NULL, NULL },
1747 { "proxyCacheQueries", "queries",
1748 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1749 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1750 "DESC 'Maximum number of queries to cache' "
1751 "SYNTAX OMsInteger )", NULL, NULL },
1753 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1756 static ConfigOCs pcocs[] = {
1757 { "( OLcfgOvOc:2.1 "
1758 "NAME 'olcPcacheConfig' "
1759 "DESC 'ProxyCache configuration' "
1760 "SUP olcOverlayConfig "
1761 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1762 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1763 { "( OLcfgOvOc:2.2 "
1764 "NAME 'olcPcacheDatabase' "
1765 "DESC 'Cache database configuration' "
1766 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1771 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1776 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1777 p->ce_bi->bi_cf_ocs != pcocs )
1778 return LDAP_CONSTRAINT_VIOLATION;
1780 on = (slap_overinst *)p->ce_bi;
1781 cm = on->on_bi.bi_private;
1783 return LDAP_SUCCESS;
1787 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1789 CfEntryInfo *pe = p->e_private;
1790 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1791 cache_manager *cm = on->on_bi.bi_private;
1794 /* FIXME: should not hardcode "olcDatabase" here */
1795 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1796 bv.bv_val = ca->msg;
1799 /* We can only create this entry if the database is table-driven
1801 if ( cm->db.bd_info->bi_cf_ocs )
1802 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1809 pc_cf_gen( ConfigArgs *c )
1811 slap_overinst *on = (slap_overinst *)c->bi;
1812 cache_manager* cm = on->on_bi.bi_private;
1813 query_manager* qm = cm->qm;
1814 QueryTemplate* temp;
1815 AttributeName* attr_name;
1816 AttributeName* attrarray;
1817 const char* text=NULL;
1822 if ( c->op == SLAP_CONFIG_EMIT ) {
1826 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1827 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1828 cm->num_entries_limit, cm->cc_period );
1830 value_add_one( &c->rvalue_vals, &bv );
1833 for (i=0; i<cm->numattrsets; i++) {
1834 if ( !qm->attr_sets[i].count ) continue;
1836 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1838 /* count the attr length */
1839 for ( attr_name = qm->attr_sets[i].attrs;
1840 attr_name->an_name.bv_val; attr_name++ )
1841 bv.bv_len += attr_name->an_name.bv_len + 1;
1843 bv.bv_val = ch_malloc( bv.bv_len+1 );
1844 ptr = lutil_strcopy( bv.bv_val, c->msg );
1845 for ( attr_name = qm->attr_sets[i].attrs;
1846 attr_name->an_name.bv_val; attr_name++ ) {
1848 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1850 ber_bvarray_add( &c->rvalue_vals, &bv );
1852 if ( !c->rvalue_vals )
1856 for (temp=qm->templates; temp; temp=temp->qmnext) {
1857 if ( temp->negttl ) {
1858 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1860 temp->attr_set_index,
1864 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1865 temp->attr_set_index,
1868 bv.bv_len += temp->querystr.bv_len + 2;
1869 bv.bv_val = ch_malloc( bv.bv_len+1 );
1872 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1874 strcpy( ptr, c->msg );
1875 ber_bvarray_add( &c->rvalue_vals, &bv );
1877 if ( !c->rvalue_vals )
1881 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1882 BER_BVSTR( &bv, "head" );
1884 BER_BVSTR( &bv, "tail" );
1886 value_add_one( &c->rvalue_vals, &bv );
1889 c->value_int = cm->max_queries;
1893 } else if ( c->op == LDAP_MOD_DELETE ) {
1894 return 1; /* FIXME */
1906 if ( cm->numattrsets > 0 ) {
1907 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1908 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1912 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1913 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1915 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1918 if ( cm->numattrsets <= 0 ) {
1919 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1920 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1923 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1924 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1925 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1929 if ( !backend_db_init( c->argv[1], &cm->db, -1 )) {
1930 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1931 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1935 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1936 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1938 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1941 if ( cm->max_entries <= 0 ) {
1942 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1943 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1947 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1948 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1950 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1953 if ( cm->num_entries_limit <= 0 ) {
1954 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1955 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1958 if ( cm->num_entries_limit > cm->max_entries ) {
1959 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1960 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1964 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1965 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1967 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1970 cm->cc_period = (time_t)t;
1971 Debug( pcache_debug,
1972 "Total # of attribute sets to be cached = %d.\n",
1973 cm->numattrsets, 0, 0 );
1974 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1975 sizeof( struct attr_set ) );
1978 if ( cm->numattrsets == 0 ) {
1979 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1980 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1983 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1984 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1986 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1990 if ( num < 0 || num >= cm->numattrsets ) {
1991 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1992 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1993 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1996 qm->attr_sets[num].flags |= PC_CONFIGURED;
1997 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1998 qm->attr_sets[num].count = c->argc - 2;
1999 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
2000 (c->argc-1) * sizeof( AttributeName ));
2001 attr_name = qm->attr_sets[num].attrs;
2002 for ( i = 2; i < c->argc; i++ ) {
2003 attr_name->an_desc = NULL;
2004 if ( slap_str2ad( c->argv[i],
2005 &attr_name->an_desc, &text ) )
2007 strcpy( c->msg, text );
2008 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2009 ch_free( qm->attr_sets[num].attrs );
2010 qm->attr_sets[num].attrs = NULL;
2011 qm->attr_sets[num].count = 0;
2014 attr_name->an_name = attr_name->an_desc->ad_cname;
2015 attr_name->an_oc = NULL;
2016 attr_name->an_oc_exclude = 0;
2017 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2018 qm->attr_sets[num].flags |= PC_GOT_OC;
2020 BER_BVZERO( &attr_name->an_name );
2025 if ( cm->numattrsets == 0 ) {
2026 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
2027 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2030 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2031 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
2033 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2037 if ( i < 0 || i >= cm->numattrsets ||
2038 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2039 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
2040 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2041 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2044 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2045 temp->qmnext = qm->templates;
2046 qm->templates = temp;
2047 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2048 temp->query = temp->query_last = NULL;
2049 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2050 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
2052 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2055 temp->ttl = (time_t)t;
2056 if ( c->argc == 5 ) {
2057 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2058 snprintf( c->msg, sizeof( c->msg ),
2059 "unable to parse template negttl=\"%s\"",
2061 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2064 temp->negttl = (time_t)t;
2069 temp->no_of_queries = 0;
2071 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2072 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2073 Debug( pcache_debug, " query template: %s\n",
2074 temp->querystr.bv_val, 0, 0 );
2075 temp->attr_set_index = i;
2076 qm->attr_sets[i].flags |= PC_REFERENCED;
2077 temp->qtnext = qm->attr_sets[i].templates;
2078 qm->attr_sets[i].templates = temp;
2079 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2080 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2081 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2082 Debug( pcache_debug, "\t%s\n",
2083 attrarray[i].an_name.bv_val, 0, 0 );
2087 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2088 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2090 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2091 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2094 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
2095 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2100 if ( c->value_int <= 0 ) {
2101 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
2102 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2105 cm->max_queries = c->value_int;
2120 slap_overinst *on = (slap_overinst *)be->bd_info;
2121 cache_manager* cm = on->on_bi.bi_private;
2123 /* Something for the cache database? */
2124 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2125 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2127 return SLAP_CONF_UNKNOWN;
2134 slap_overinst *on = (slap_overinst *)be->bd_info;
2138 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2139 on->on_bi.bi_private = cm;
2141 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2144 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2145 cm->db.be_private = NULL;
2146 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2148 cm->numattrsets = 0;
2149 cm->num_entries_limit = 5;
2150 cm->num_cached_queries = 0;
2151 cm->max_entries = 0;
2152 cm->cur_entries = 0;
2153 cm->max_queries = 10000;
2154 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2155 cm->cc_period = 1000;
2158 qm->attr_sets = NULL;
2159 qm->templates = NULL;
2161 qm->lru_bottom = NULL;
2163 qm->qcfunc = query_containment;
2164 qm->crfunc = cache_replacement;
2165 qm->addfunc = add_query;
2166 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2168 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2176 slap_overinst *on = (slap_overinst *)be->bd_info;
2177 cache_manager *cm = on->on_bi.bi_private;
2178 query_manager* qm = cm->qm;
2179 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2181 /* check attr sets */
2182 for ( i = 0; i < cm->numattrsets; i++) {
2183 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2184 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2185 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2189 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2193 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2194 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2199 if ( ncf || rf || nrf ) {
2200 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2201 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2202 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2209 /* need to inherit something from the original database... */
2210 cm->db.be_def_limit = be->be_def_limit;
2211 cm->db.be_limits = be->be_limits;
2212 cm->db.be_acl = be->be_acl;
2213 cm->db.be_dfltaccess = be->be_dfltaccess;
2215 if ( SLAP_DBMONITORING( be ) ) {
2216 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2219 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2222 rc = backend_startup_one( &cm->db );
2224 /* There is no runqueue in TOOL mode */
2225 if ( slapMode & SLAP_SERVER_MODE ) {
2226 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2227 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2228 consistency_check, on,
2229 "pcache_consistency", be->be_suffix[0].bv_val );
2230 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2232 /* Cached database must have the rootdn */
2233 if ( BER_BVISNULL( &cm->db.be_rootndn )
2234 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2236 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2237 "underlying database of type \"%s\"\n"
2238 " serving naming context \"%s\"\n"
2239 " has no \"rootdn\", required by \"proxycache\".\n",
2240 on->on_info->oi_orig->bi_type,
2241 cm->db.be_suffix[0].bv_val, 0 );
2250 pcache_free_qbase( void *v )
2256 tavl_free( qb->scopes[i], NULL );
2265 slap_overinst *on = (slap_overinst *)be->bd_info;
2266 cache_manager *cm = on->on_bi.bi_private;
2267 query_manager *qm = cm->qm;
2271 /* cleanup stuff inherited from the original database... */
2272 cm->db.be_limits = NULL;
2273 cm->db.be_acl = NULL;
2275 if ( cm->db.bd_info->bi_db_close ) {
2276 rc = cm->db.bd_info->bi_db_close( &cm->db );
2278 while ( (tm = qm->templates) != NULL ) {
2279 CachedQuery *qc, *qn;
2280 qm->templates = tm->qmnext;
2281 for ( qc = tm->query; qc; qc = qn ) {
2285 avl_free( tm->qbase, pcache_free_qbase );
2286 free( tm->querystr.bv_val );
2287 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2288 free( tm->t_attrs.attrs );
2292 for ( i=0; i<cm->numattrsets; i++ ) {
2293 free( qm->attr_sets[i].attrs );
2295 free( qm->attr_sets );
2296 qm->attr_sets = NULL;
2306 slap_overinst *on = (slap_overinst *)be->bd_info;
2307 cache_manager *cm = on->on_bi.bi_private;
2308 query_manager *qm = cm->qm;
2310 if ( cm->db.be_private != NULL ) {
2311 backend_stopdown_one( &cm->db );
2314 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2315 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2322 static slap_overinst pcache;
2324 static char *obsolete_names[] = {
2329 int pcache_initialize()
2332 struct berval debugbv = BER_BVC("pcache");
2334 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2337 code = register_at( queryid_schema, &ad_queryid, 0 );
2339 Debug( LDAP_DEBUG_ANY,
2340 "pcache_initialize: register_at failed\n", 0, 0, 0 );
2344 pcache.on_bi.bi_type = "pcache";
2345 pcache.on_bi.bi_obsolete_names = obsolete_names;
2346 pcache.on_bi.bi_db_init = pcache_db_init;
2347 pcache.on_bi.bi_db_config = pcache_db_config;
2348 pcache.on_bi.bi_db_open = pcache_db_open;
2349 pcache.on_bi.bi_db_close = pcache_db_close;
2350 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2352 pcache.on_bi.bi_op_search = pcache_op_search;
2354 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2356 pcache.on_bi.bi_cf_ocs = pcocs;
2358 code = config_register_schema( pccfg, pcocs );
2359 if ( code ) return code;
2361 return overlay_register( &pcache );
2364 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2365 int init_module(int argc, char *argv[]) {
2366 return pcache_initialize();
2370 #endif /* defined(SLAPD_OVER_PROXYCACHE) */