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);
1255 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1256 slap_callback *cb = op->o_callback;
1257 struct search_info *si = cb->sc_private;
1258 if ( si->save_attrs != NULL ) {
1259 rs->sr_attrs = si->save_attrs;
1260 op->ors_attrs = si->save_attrs;
1262 op->o_callback = op->o_callback->sc_next;
1263 op->o_tmpfree( cb, op->o_tmpmemctx );
1264 return SLAP_CB_CONTINUE;
1272 struct search_info *si = op->o_callback->sc_private;
1273 slap_overinst *on = si->on;
1274 cache_manager *cm = on->on_bi.bi_private;
1275 query_manager* qm = cm->qm;
1277 if ( si->save_attrs != NULL ) {
1278 rs->sr_attrs = si->save_attrs;
1279 op->ors_attrs = si->save_attrs;
1282 if ( rs->sr_type == REP_SEARCH ) {
1284 /* If we haven't exceeded the limit for this query,
1285 * build a chain of answers to store. If we hit the
1286 * limit, empty the chain and ignore the rest.
1289 if ( si->count < si->max ) {
1291 e = entry_dup( rs->sr_entry );
1292 if ( !si->head ) si->head = e;
1293 if ( si->tail ) si->tail->e_private = e;
1298 for (;si->head; si->head=e) {
1299 e = si->head->e_private;
1300 si->head->e_private = NULL;
1301 entry_free(si->head);
1307 } else if ( rs->sr_type == REP_RESULT ) {
1309 ( si->qtemp->negttl && !si->count && !si->over &&
1310 rs->sr_err == LDAP_SUCCESS )) {
1311 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1316 cache_entries( op, rs, &qc->q_uuid );
1317 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1318 cm->num_cached_queries++;
1319 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1320 cm->num_cached_queries, 0, 0 );
1321 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1323 /* If the consistency checker suspended itself,
1326 if ( cm->cc_paused ) {
1327 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1328 if ( cm->cc_paused ) {
1330 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1332 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1334 } else if ( si->count ) {
1335 /* duplicate query, free it */
1337 for (;si->head; si->head=e) {
1338 e = si->head->e_private;
1339 si->head->e_private = NULL;
1340 entry_free(si->head);
1344 filter_free( si->query.filter );
1347 op->o_callback->sc_cleanup = pcache_op_cleanup;
1349 return SLAP_CB_CONTINUE;
1355 AttributeName** new_attrs,
1356 struct attr_set *attrs,
1357 AttributeName* filter_attrs,
1367 /* duplicate attrs */
1368 count = attrs->count + fattr_cnt;
1369 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1374 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1375 sizeof(AttributeName));
1376 for (i=0; i<attrs->count; i++) {
1377 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1378 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1380 BER_BVZERO( &(*new_attrs)[i].an_name );
1381 alluser = an_find(*new_attrs, &AllUser);
1382 allop = an_find(*new_attrs, &AllOper);
1385 for ( i=0; i<fattr_cnt; i++ ) {
1386 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1388 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1393 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1394 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1395 (*new_attrs)[j].an_oc = NULL;
1396 (*new_attrs)[j].an_oc_exclude = 0;
1400 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1401 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1402 (*new_attrs)[j].an_oc = NULL;
1403 (*new_attrs)[j].an_oc_exclude = 0;
1406 BER_BVZERO( &(*new_attrs)[j].an_name );
1409 /* NOTE: this is a quick workaround to let pcache minimally interact
1410 * with pagedResults. A more articulated solutions would be to
1411 * perform the remote query without control and cache all results,
1412 * performing the pagedResults search only within the client
1413 * and the proxy. This requires pcache to understand pagedResults. */
1415 pcache_chk_controls(
1419 const char *non = "";
1420 const char *stripped = "";
1422 switch( op->o_pagedresults ) {
1423 case SLAP_CONTROL_NONCRITICAL:
1425 stripped = "; stripped";
1428 case SLAP_CONTROL_CRITICAL:
1429 Debug( pcache_debug, "%s: "
1430 "%scritical pagedResults control "
1431 "disabled with proxy cache%s.\n",
1432 op->o_log_prefix, non, stripped );
1434 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1438 rs->sr_err = SLAP_CB_CONTINUE;
1450 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1451 cache_manager *cm = on->on_bi.bi_private;
1452 query_manager* qm = cm->qm;
1456 AttributeName *filter_attrs = NULL;
1459 QueryTemplate *qtemp = NULL;
1462 CachedQuery *answerable = NULL;
1465 int fattr_got_oc = 0;
1467 struct berval tempstr;
1469 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1471 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1472 &fattr_cnt, &fattr_got_oc )) {
1473 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1474 return SLAP_CB_CONTINUE;
1477 Debug( pcache_debug, "query template of incoming query = %s\n",
1478 tempstr.bv_val, 0, 0 );
1480 /* FIXME: cannot cache/answer requests with pagedResults control */
1483 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1485 query.filter = op->ors_filter;
1486 query.base = op->o_req_ndn;
1487 query.scope = op->ors_scope;
1489 /* check for query containment */
1490 if (attr_set > -1) {
1491 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1492 for (; qt; qt = qt->qtnext ) {
1493 /* find if template i can potentially answer tempstr */
1494 if (qt->querystr.bv_len != tempstr.bv_len ||
1495 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1499 Debug( pcache_debug, "Entering QC, querystr = %s\n",
1500 op->ors_filterstr.bv_val, 0, 0 );
1501 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1507 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1510 /* Need to clear the callbacks of the original operation,
1511 * in case there are other overlays */
1512 BackendDB *save_bd = op->o_bd;
1513 slap_callback *save_cb = op->o_callback;
1515 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1516 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1517 if ( BER_BVISNULL( &answerable->q_uuid )) {
1518 /* No entries cached, just an empty result set */
1520 send_ldap_result( op, rs );
1523 op->o_callback = NULL;
1524 i = cm->db.bd_info->bi_op_search( op, rs );
1526 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1528 op->o_callback = save_cb;
1532 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1534 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1535 if (cm->num_cached_queries >= cm->max_queries) {
1538 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1540 if (op->ors_attrsonly)
1545 struct search_info *si;
1547 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1548 query.filter = filter_dup(op->ors_filter, NULL);
1549 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1550 if ( !qtemp->t_attrs.count ) {
1551 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1552 &qm->attr_sets[attr_set],
1553 filter_attrs, fattr_cnt, fattr_got_oc);
1555 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1557 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1558 cb->sc_response = pcache_response;
1559 cb->sc_cleanup = NULL;
1560 cb->sc_private = (cb+1);
1561 si = cb->sc_private;
1565 si->max = cm->num_entries_limit ;
1570 si->save_attrs = op->ors_attrs;
1572 op->ors_attrs = qtemp->t_attrs.attrs;
1574 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1575 cb->sc_next = op->o_callback;
1576 op->o_callback = cb;
1579 slap_callback **pcb;
1581 /* need to move the callback at the end, in case other
1582 * overlays are present, so that the final entry is
1583 * actually cached */
1585 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1590 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1594 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1596 return SLAP_CB_CONTINUE;
1601 AttributeName* attrs,
1609 for ( ; attrs[count].an_name.bv_val; count++ );
1612 for (i=0; i<num; i++) {
1616 if ( count > qm->attr_sets[i].count )
1619 if ( !qm->attr_sets[i].count )
1623 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1624 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1642 struct re_s *rtask = arg;
1643 slap_overinst *on = rtask->arg;
1644 cache_manager *cm = on->on_bi.bi_private;
1645 query_manager *qm = cm->qm;
1646 Connection conn = {0};
1647 OperationBuffer opbuf;
1650 SlapReply rs = {REP_RESULT};
1652 int return_val, pause = 1;
1653 QueryTemplate* templ;
1655 connection_fake_init( &conn, &opbuf, ctx );
1659 op->o_dn = cm->db.be_rootdn;
1660 op->o_ndn = cm->db.be_rootndn;
1664 for (templ = qm->templates; templ; templ=templ->qmnext) {
1665 query = templ->query_last;
1666 if ( query ) pause = 0;
1667 op->o_time = slap_get_time();
1668 while (query && (query->expiry_time < op->o_time)) {
1670 Debug( pcache_debug, "Lock CR index = %p\n",
1671 (void *) templ, 0, 0 );
1672 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1673 if ( query == templ->query_last ) {
1675 remove_from_template(query, templ);
1676 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1677 (void *) templ, templ->no_of_queries, 0 );
1678 Debug( pcache_debug, "Unlock CR index = %p\n",
1679 (void *) templ, 0, 0 );
1681 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1683 query = templ->query_last;
1686 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1687 remove_query(qm, query);
1688 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1689 if ( BER_BVISNULL( &query->q_uuid ))
1692 return_val = remove_query_data(op, &rs, &query->q_uuid);
1693 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1695 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1696 cm->cur_entries -= return_val;
1697 cm->num_cached_queries--;
1698 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1699 cm->num_cached_queries, 0, 0 );
1700 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1701 Debug( pcache_debug,
1702 "STALE QUERY REMOVED, CACHE ="
1704 cm->cur_entries, 0, 0 );
1706 query = templ->query_last;
1709 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1710 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1711 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1713 /* If there were no queries, defer processing for a while */
1714 cm->cc_paused = pause;
1715 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1717 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1722 #define MAX_ATTR_SETS 500
1732 static ConfigDriver pc_cf_gen;
1733 static ConfigLDAPadd pc_ldadd;
1734 static ConfigCfAdd pc_cfadd;
1736 static ConfigTable pccfg[] = {
1737 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1739 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1740 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1741 "DESC 'ProxyCache basic parameters' "
1742 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1743 { "proxyattrset", "index> <attributes...",
1744 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1745 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1746 "DESC 'A set of attributes to cache' "
1747 "SYNTAX OMsDirectoryString )", NULL, NULL },
1748 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1749 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1750 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1751 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1752 "SYNTAX OMsDirectoryString )", NULL, NULL },
1753 { "response-callback", "head|tail(default)",
1754 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1755 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1756 "DESC 'Response callback position in overlay stack' "
1757 "SYNTAX OMsDirectoryString )", NULL, NULL },
1758 { "proxyCacheQueries", "queries",
1759 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1760 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1761 "DESC 'Maximum number of queries to cache' "
1762 "SYNTAX OMsInteger )", NULL, NULL },
1764 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1767 static ConfigOCs pcocs[] = {
1768 { "( OLcfgOvOc:2.1 "
1769 "NAME 'olcPcacheConfig' "
1770 "DESC 'ProxyCache configuration' "
1771 "SUP olcOverlayConfig "
1772 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1773 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1774 { "( OLcfgOvOc:2.2 "
1775 "NAME 'olcPcacheDatabase' "
1776 "DESC 'Cache database configuration' "
1777 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1782 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1787 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1788 p->ce_bi->bi_cf_ocs != pcocs )
1789 return LDAP_CONSTRAINT_VIOLATION;
1791 on = (slap_overinst *)p->ce_bi;
1792 cm = on->on_bi.bi_private;
1794 return LDAP_SUCCESS;
1798 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1800 CfEntryInfo *pe = p->e_private;
1801 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1802 cache_manager *cm = on->on_bi.bi_private;
1805 /* FIXME: should not hardcode "olcDatabase" here */
1806 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1807 bv.bv_val = ca->msg;
1810 /* We can only create this entry if the database is table-driven
1812 if ( cm->db.bd_info->bi_cf_ocs )
1813 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1820 pc_cf_gen( ConfigArgs *c )
1822 slap_overinst *on = (slap_overinst *)c->bi;
1823 cache_manager* cm = on->on_bi.bi_private;
1824 query_manager* qm = cm->qm;
1825 QueryTemplate* temp;
1826 AttributeName* attr_name;
1827 AttributeName* attrarray;
1828 const char* text=NULL;
1833 if ( c->op == SLAP_CONFIG_EMIT ) {
1837 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1838 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1839 cm->num_entries_limit, cm->cc_period );
1841 value_add_one( &c->rvalue_vals, &bv );
1844 for (i=0; i<cm->numattrsets; i++) {
1845 if ( !qm->attr_sets[i].count ) continue;
1847 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1849 /* count the attr length */
1850 for ( attr_name = qm->attr_sets[i].attrs;
1851 attr_name->an_name.bv_val; attr_name++ )
1852 bv.bv_len += attr_name->an_name.bv_len + 1;
1854 bv.bv_val = ch_malloc( bv.bv_len+1 );
1855 ptr = lutil_strcopy( bv.bv_val, c->msg );
1856 for ( attr_name = qm->attr_sets[i].attrs;
1857 attr_name->an_name.bv_val; attr_name++ ) {
1859 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1861 ber_bvarray_add( &c->rvalue_vals, &bv );
1863 if ( !c->rvalue_vals )
1867 for (temp=qm->templates; temp; temp=temp->qmnext) {
1868 if ( temp->negttl ) {
1869 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1871 temp->attr_set_index,
1875 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1876 temp->attr_set_index,
1879 bv.bv_len += temp->querystr.bv_len + 2;
1880 bv.bv_val = ch_malloc( bv.bv_len+1 );
1883 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1885 strcpy( ptr, c->msg );
1886 ber_bvarray_add( &c->rvalue_vals, &bv );
1888 if ( !c->rvalue_vals )
1892 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1893 BER_BVSTR( &bv, "head" );
1895 BER_BVSTR( &bv, "tail" );
1897 value_add_one( &c->rvalue_vals, &bv );
1900 c->value_int = cm->max_queries;
1904 } else if ( c->op == LDAP_MOD_DELETE ) {
1905 return 1; /* FIXME */
1917 if ( cm->numattrsets > 0 ) {
1918 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1919 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1923 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1924 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1926 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1929 if ( cm->numattrsets <= 0 ) {
1930 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1931 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1934 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1935 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1936 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1940 if ( !backend_db_init( c->argv[1], &cm->db, -1 )) {
1941 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1942 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1946 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1947 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1949 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1952 if ( cm->max_entries <= 0 ) {
1953 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1954 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1958 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1959 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1961 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1964 if ( cm->num_entries_limit <= 0 ) {
1965 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1966 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1969 if ( cm->num_entries_limit > cm->max_entries ) {
1970 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1971 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1975 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1976 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1978 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1981 cm->cc_period = (time_t)t;
1982 Debug( pcache_debug,
1983 "Total # of attribute sets to be cached = %d.\n",
1984 cm->numattrsets, 0, 0 );
1985 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1986 sizeof( struct attr_set ) );
1989 if ( cm->numattrsets == 0 ) {
1990 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1991 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1994 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1995 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1997 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2001 if ( num < 0 || num >= cm->numattrsets ) {
2002 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
2003 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2004 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2007 qm->attr_sets[num].flags |= PC_CONFIGURED;
2008 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
2009 qm->attr_sets[num].count = c->argc - 2;
2010 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
2011 (c->argc-1) * sizeof( AttributeName ));
2012 attr_name = qm->attr_sets[num].attrs;
2013 for ( i = 2; i < c->argc; i++ ) {
2014 attr_name->an_desc = NULL;
2015 if ( slap_str2ad( c->argv[i],
2016 &attr_name->an_desc, &text ) )
2018 strcpy( c->msg, text );
2019 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2020 ch_free( qm->attr_sets[num].attrs );
2021 qm->attr_sets[num].attrs = NULL;
2022 qm->attr_sets[num].count = 0;
2025 attr_name->an_name = attr_name->an_desc->ad_cname;
2026 attr_name->an_oc = NULL;
2027 attr_name->an_oc_exclude = 0;
2028 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2029 qm->attr_sets[num].flags |= PC_GOT_OC;
2031 BER_BVZERO( &attr_name->an_name );
2036 if ( cm->numattrsets == 0 ) {
2037 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
2038 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2041 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2042 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
2044 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2048 if ( i < 0 || i >= cm->numattrsets ||
2049 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2050 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
2051 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2052 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2055 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2056 temp->qmnext = qm->templates;
2057 qm->templates = temp;
2058 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2059 temp->query = temp->query_last = NULL;
2060 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2061 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
2063 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2066 temp->ttl = (time_t)t;
2067 if ( c->argc == 5 ) {
2068 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2069 snprintf( c->msg, sizeof( c->msg ),
2070 "unable to parse template negttl=\"%s\"",
2072 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2075 temp->negttl = (time_t)t;
2080 temp->no_of_queries = 0;
2082 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2083 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2084 Debug( pcache_debug, " query template: %s\n",
2085 temp->querystr.bv_val, 0, 0 );
2086 temp->attr_set_index = i;
2087 qm->attr_sets[i].flags |= PC_REFERENCED;
2088 temp->qtnext = qm->attr_sets[i].templates;
2089 qm->attr_sets[i].templates = temp;
2090 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2091 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2092 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2093 Debug( pcache_debug, "\t%s\n",
2094 attrarray[i].an_name.bv_val, 0, 0 );
2098 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2099 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2101 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2102 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2105 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
2106 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2111 if ( c->value_int <= 0 ) {
2112 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
2113 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2116 cm->max_queries = c->value_int;
2131 slap_overinst *on = (slap_overinst *)be->bd_info;
2132 cache_manager* cm = on->on_bi.bi_private;
2134 /* Something for the cache database? */
2135 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2136 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2138 return SLAP_CONF_UNKNOWN;
2145 slap_overinst *on = (slap_overinst *)be->bd_info;
2149 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2150 on->on_bi.bi_private = cm;
2152 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2155 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2156 cm->db.be_private = NULL;
2157 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2159 cm->numattrsets = 0;
2160 cm->num_entries_limit = 5;
2161 cm->num_cached_queries = 0;
2162 cm->max_entries = 0;
2163 cm->cur_entries = 0;
2164 cm->max_queries = 10000;
2165 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2166 cm->cc_period = 1000;
2169 qm->attr_sets = NULL;
2170 qm->templates = NULL;
2172 qm->lru_bottom = NULL;
2174 qm->qcfunc = query_containment;
2175 qm->crfunc = cache_replacement;
2176 qm->addfunc = add_query;
2177 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2179 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2187 slap_overinst *on = (slap_overinst *)be->bd_info;
2188 cache_manager *cm = on->on_bi.bi_private;
2189 query_manager* qm = cm->qm;
2190 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2192 /* check attr sets */
2193 for ( i = 0; i < cm->numattrsets; i++) {
2194 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2195 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2196 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2200 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2204 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2205 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2210 if ( ncf || rf || nrf ) {
2211 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2212 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2213 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2220 /* need to inherit something from the original database... */
2221 cm->db.be_def_limit = be->be_def_limit;
2222 cm->db.be_limits = be->be_limits;
2223 cm->db.be_acl = be->be_acl;
2224 cm->db.be_dfltaccess = be->be_dfltaccess;
2226 if ( SLAP_DBMONITORING( be ) ) {
2227 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2230 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2233 rc = backend_startup_one( &cm->db );
2235 /* There is no runqueue in TOOL mode */
2236 if ( slapMode & SLAP_SERVER_MODE ) {
2237 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2238 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2239 consistency_check, on,
2240 "pcache_consistency", be->be_suffix[0].bv_val );
2241 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2243 /* Cached database must have the rootdn */
2244 if ( BER_BVISNULL( &cm->db.be_rootndn )
2245 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2247 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2248 "underlying database of type \"%s\"\n"
2249 " serving naming context \"%s\"\n"
2250 " has no \"rootdn\", required by \"proxycache\".\n",
2251 on->on_info->oi_orig->bi_type,
2252 cm->db.be_suffix[0].bv_val, 0 );
2261 pcache_free_qbase( void *v )
2267 tavl_free( qb->scopes[i], NULL );
2276 slap_overinst *on = (slap_overinst *)be->bd_info;
2277 cache_manager *cm = on->on_bi.bi_private;
2278 query_manager *qm = cm->qm;
2282 /* cleanup stuff inherited from the original database... */
2283 cm->db.be_limits = NULL;
2284 cm->db.be_acl = NULL;
2286 if ( cm->db.bd_info->bi_db_close ) {
2287 rc = cm->db.bd_info->bi_db_close( &cm->db );
2289 while ( (tm = qm->templates) != NULL ) {
2290 CachedQuery *qc, *qn;
2291 qm->templates = tm->qmnext;
2292 for ( qc = tm->query; qc; qc = qn ) {
2296 avl_free( tm->qbase, pcache_free_qbase );
2297 free( tm->querystr.bv_val );
2298 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2299 free( tm->t_attrs.attrs );
2303 for ( i=0; i<cm->numattrsets; i++ ) {
2304 free( qm->attr_sets[i].attrs );
2306 free( qm->attr_sets );
2307 qm->attr_sets = NULL;
2317 slap_overinst *on = (slap_overinst *)be->bd_info;
2318 cache_manager *cm = on->on_bi.bi_private;
2319 query_manager *qm = cm->qm;
2321 if ( cm->db.be_private != NULL ) {
2322 backend_stopdown_one( &cm->db );
2325 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2326 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2333 static slap_overinst pcache;
2335 static char *obsolete_names[] = {
2340 int pcache_initialize()
2343 struct berval debugbv = BER_BVC("pcache");
2345 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2348 code = register_at( queryid_schema, &ad_queryid, 0 );
2350 Debug( LDAP_DEBUG_ANY,
2351 "pcache_initialize: register_at failed\n", 0, 0, 0 );
2355 pcache.on_bi.bi_type = "pcache";
2356 pcache.on_bi.bi_obsolete_names = obsolete_names;
2357 pcache.on_bi.bi_db_init = pcache_db_init;
2358 pcache.on_bi.bi_db_config = pcache_db_config;
2359 pcache.on_bi.bi_db_open = pcache_db_open;
2360 pcache.on_bi.bi_db_close = pcache_db_close;
2361 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2363 pcache.on_bi.bi_op_search = pcache_op_search;
2365 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2367 pcache.on_bi.bi_cf_ocs = pcocs;
2369 code = config_register_schema( pccfg, pcocs );
2370 if ( code ) return code;
2372 return overlay_register( &pcache );
2375 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2376 int init_module(int argc, char *argv[]) {
2377 return pcache_initialize();
2381 #endif /* defined(SLAPD_OVER_PROXYCACHE) */