2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2006 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
38 /* query cache structs */
41 typedef struct Query_s {
42 Filter* filter; /* Search Filter */
43 struct berval base; /* Search Base */
44 int scope; /* Search scope */
47 struct query_template_s;
49 typedef struct Qbase_s {
50 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
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 be_entry_release_w( op, e );
226 /* Length-ordered sort on normalized DNs */
227 static int pcache_dn_cmp( const void *v1, const void *v2 )
229 const Qbase *q1 = v1, *q2 = v2;
231 int rc = q1->base.bv_len - q2->base.bv_len;
233 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
237 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
240 dif = bv1->bv_len - bv2->bv_len;
242 if ( dif > 0 ) len -= dif;
243 len = memcmp( bv1->bv_val, bv2->bv_val, len );
249 /* compare the first value in each filter */
250 static int pcache_filter_cmp( const void *v1, const void *v2 )
252 const CachedQuery *q1 = v1, *q2 =v2;
253 int rc, weight1, weight2;
255 switch( q1->first->f_choice ) {
256 case LDAP_FILTER_PRESENT:
259 case LDAP_FILTER_EQUALITY:
267 switch( q2->first->f_choice ) {
268 case LDAP_FILTER_PRESENT:
271 case LDAP_FILTER_EQUALITY:
279 rc = weight1 - weight2;
284 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
287 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
289 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
290 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
291 rc = lex_bvcmp( &q1->first->f_sub_initial,
292 &q2->first->f_sub_initial );
296 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
300 if ( q1->first->f_sub_any ) {
301 if ( q2->first->f_sub_any ) {
302 rc = lex_bvcmp( q1->first->f_sub_any,
303 q2->first->f_sub_any );
307 } else if ( q2->first->f_sub_any ) {
311 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
312 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
313 rc = lex_bvcmp( &q1->first->f_sub_final,
314 &q2->first->f_sub_final );
318 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
322 rc = lex_bvcmp( &q1->first->f_mr_value,
323 &q2->first->f_mr_value );
332 /* add query on top of LRU list */
334 add_query_on_top (query_manager* qm, CachedQuery* qc)
336 CachedQuery* top = qm->lru_top;
347 Debug( pcache_debug, "Base of added query = %s\n",
348 qc->qbase->base.bv_val, 0, 0 );
351 /* remove_query from LRU list */
354 remove_query (query_manager* qm, CachedQuery* qc)
377 qc->lru_up = qc->lru_down = NULL;
380 /* find and remove string2 from string1
381 * from start if position = 1,
382 * from end if position = 3,
383 * from anywhere if position = 2
384 * string1 is overwritten if position = 2.
388 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
399 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
400 ber2->bv_val, ber2->bv_len )) {
402 ber1->bv_val += ber2->bv_len;
403 ber1->bv_len -= ber2->bv_len;
408 ber1->bv_val[ber1->bv_len] = '\0';
409 temp = strstr( ber1->bv_val, ber2->bv_val );
411 strcpy( temp, temp+ber2->bv_len );
412 ber1->bv_len -= ber2->bv_len;
418 if ( ber1->bv_len >= ber2->bv_len &&
419 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
422 ber1->bv_len -= ber2->bv_len;
430 static struct berval*
431 merge_init_final(Operation *op, struct berval* init, struct berval* any,
432 struct berval* final)
434 struct berval* merged, *temp;
435 int i, any_count, count;
437 for (any_count=0; any && any[any_count].bv_val; any_count++)
447 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
452 ber_dupbv_x( temp, init, op->o_tmpmemctx );
456 for (i=0; i<any_count; i++) {
457 ber_dupbv_x( temp, any, op->o_tmpmemctx );
462 ber_dupbv_x( temp, final, op->o_tmpmemctx );
469 /* Each element in stored must be found in incoming. Incoming is overwritten.
472 strings_containment(struct berval* stored, struct berval* incoming)
474 struct berval* element;
478 for ( element=stored; element->bv_val != NULL; element++ ) {
479 for (j = k; incoming[j].bv_val != NULL; j++) {
480 if (find_and_remove(&(incoming[j]), element, 2)) {
497 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
501 struct berval init_incoming;
502 struct berval final_incoming;
503 struct berval *remaining_incoming = NULL;
505 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
506 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
509 init_incoming = incoming->f_sub_initial;
510 final_incoming = incoming->f_sub_final;
512 if (find_and_remove(&init_incoming,
513 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
514 &(stored->f_sub_final), 3))
516 if (stored->f_sub_any == NULL) {
520 remaining_incoming = merge_init_final(op, &init_incoming,
521 incoming->f_sub_any, &final_incoming);
522 rc = strings_containment(stored->f_sub_any, remaining_incoming);
523 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
530 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
532 struct berval incoming_val[2];
535 incoming_val[1] = incoming->f_av_value;
537 if (find_and_remove(incoming_val+1,
538 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
539 &(stored->f_sub_final), 3)) {
540 if (stored->f_sub_any == NULL){
544 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
545 BER_BVZERO( incoming_val+1 );
546 rc = strings_containment(stored->f_sub_any, incoming_val);
547 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
554 filter_first( Filter *f )
556 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
563 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
567 MatchingRule* mrule = NULL;
568 int res=0, eqpass= 0;
576 /* substring matches sort to the end, and we just have to
577 * walk the entire list.
579 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
580 ptr = tavl_end( root, 1 );
583 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
584 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
593 /* an incoming substr query can only be satisfied by a cached
596 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
597 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
600 /* an incoming eq query can be satisfied by a cached eq or substr
603 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
605 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
606 nextpass: eqpass = 1;
607 ptr = tavl_end( root, 1 );
612 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
618 switch (fs->f_choice) {
619 case LDAP_FILTER_EQUALITY:
620 if (fi->f_choice == LDAP_FILTER_EQUALITY)
621 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
627 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
634 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
635 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
636 &(fi->f_ava->aa_value),
637 &(fs->f_ava->aa_value), &text);
638 if (rc != LDAP_SUCCESS) {
641 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
644 switch (fs->f_choice) {
646 case LDAP_FILTER_AND:
651 case LDAP_FILTER_SUBSTRINGS:
652 /* check if the equality query can be
653 * answered with cached substring query */
654 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
655 && substr_containment_equality( op,
658 /* check if the substring query can be
659 * answered with cached substring query */
660 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
661 ) && substr_containment_substr( op,
667 case LDAP_FILTER_PRESENT:
672 case LDAP_FILTER_EQUALITY:
679 if (mrule && ret >= 0)
685 if (mrule && ret <= 0)
690 case LDAP_FILTER_NOT:
696 } while((res) && (fi != NULL) && (fs != NULL));
700 ptr = tavl_next( ptr, dir );
705 /* check whether query is contained in any of
706 * the cached queries in template
709 query_containment(Operation *op, query_manager *qm,
711 QueryTemplate *templa)
714 int depth = 0, tscope;
715 Qbase qbase, *qbptr = NULL;
718 if (query->filter != NULL) {
721 Debug( pcache_debug, "Lock QC index = %p\n",
722 (void *) templa, 0, 0 );
723 qbase.base = query->base;
725 first = filter_first( query->filter );
727 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
730 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
732 tscope = query->scope;
733 /* Find a matching scope:
734 * match at depth 0 OK
737 * subord at depth > 0 OK
738 * subtree at any depth OK
740 * subtree or subord at any depth OK
742 * subtree or subord at any depth OK
744 * subord at depth > 0 OK
745 * subtree at any depth OK
747 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
748 switch ( query->scope ) {
749 case LDAP_SCOPE_BASE:
750 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
751 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
752 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
755 if ( tscope == LDAP_SCOPE_BASE )
756 tscope = LDAP_SCOPE_ONE;
757 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
759 if ( tscope < LDAP_SCOPE_SUBTREE )
760 tscope = LDAP_SCOPE_SUBTREE;
762 case LDAP_SCOPE_SUBTREE:
763 if ( tscope < LDAP_SCOPE_SUBTREE )
764 tscope = LDAP_SCOPE_SUBTREE;
765 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
767 case LDAP_SCOPE_CHILDREN:
768 if ( tscope < LDAP_SCOPE_SUBTREE )
769 tscope = LDAP_SCOPE_SUBTREE;
772 if ( !qbptr->scopes[tscope] ) continue;
775 qc = find_filter( op, qbptr->scopes[tscope],
776 query->filter, first );
778 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
779 if (qm->lru_top != qc) {
780 remove_query(qm, qc);
781 add_query_on_top(qm, qc);
783 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
788 if ( be_issuffix( op->o_bd, &qbase.base ))
791 dnParent( &qbase.base, &pdn );
797 "Not answerable: Unlock QC index=%p\n",
798 (void *) templa, 0, 0 );
799 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
805 free_query (CachedQuery* qc)
807 free(qc->q_uuid.bv_val);
808 filter_free(qc->filter);
813 /* Add query to query cache */
814 static CachedQuery * add_query(
818 QueryTemplate *templ,
821 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
826 new_cached_query->qtemp = templ;
827 BER_BVZERO( &new_cached_query->q_uuid );
829 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
831 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
833 new_cached_query->lru_up = NULL;
834 new_cached_query->lru_down = NULL;
835 Debug( pcache_debug, "Added query expires at %ld\n",
836 (long) new_cached_query->expiry_time, 0, 0 );
838 new_cached_query->scope = query->scope;
839 new_cached_query->filter = query->filter;
840 new_cached_query->first = first = filter_first( query->filter );
842 qb.base = query->base;
845 Debug( pcache_debug, "Lock AQ index = %p\n",
846 (void *) templ, 0, 0 );
847 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
848 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
850 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
851 qbase->base.bv_len =qb.base.bv_len;
852 qbase->base.bv_val = (char *)(qbase+1);
853 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
854 qbase->base.bv_val[qbase->base.bv_len] = '\0';
855 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
857 new_cached_query->next = templ->query;
858 new_cached_query->prev = NULL;
859 new_cached_query->qbase = qbase;
860 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
861 pcache_filter_cmp, avl_dup_error );
864 if (templ->query == NULL)
865 templ->query_last = new_cached_query;
867 templ->query->prev = new_cached_query;
868 templ->query = new_cached_query;
869 templ->no_of_queries++;
871 ch_free( new_cached_query );
872 new_cached_query = find_filter( op, qbase->scopes[query->scope],
873 query->filter, first );
874 filter_free( query->filter );
876 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
877 (void *) templ, templ->no_of_queries, 0 );
879 Debug( pcache_debug, "Unlock AQ index = %p \n",
880 (void *) templ, 0, 0 );
881 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
883 /* Adding on top of LRU list */
885 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
886 add_query_on_top(qm, new_cached_query);
887 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
889 return rc == 0 ? new_cached_query : NULL;
893 remove_from_template (CachedQuery* qc, QueryTemplate* template)
895 if (!qc->prev && !qc->next) {
896 template->query_last = template->query = NULL;
897 } else if (qc->prev == NULL) {
898 qc->next->prev = NULL;
899 template->query = qc->next;
900 } else if (qc->next == NULL) {
901 qc->prev->next = NULL;
902 template->query_last = qc->prev;
904 qc->next->prev = qc->prev;
905 qc->prev->next = qc->next;
907 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
908 qc->qbase->queries--;
909 if ( qc->qbase->queries == 0 ) {
910 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
911 ch_free( qc->qbase );
915 template->no_of_queries--;
918 /* remove bottom query of LRU list from the query cache */
919 static void cache_replacement(query_manager* qm, struct berval *result)
924 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
925 bottom = qm->lru_bottom;
927 result->bv_val = NULL;
931 Debug ( pcache_debug,
932 "Cache replacement invoked without "
933 "any query in LRU list\n", 0, 0, 0 );
934 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
938 temp = bottom->qtemp;
939 remove_query(qm, bottom);
940 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
942 *result = bottom->q_uuid;
943 bottom->q_uuid.bv_val = NULL;
945 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
946 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
947 remove_from_template(bottom, temp);
948 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
949 (void *) temp, temp->no_of_queries, 0 );
950 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
951 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
956 struct query_info *next;
968 struct query_info *qi;
971 if ( rs->sr_type != REP_SEARCH ) return 0;
973 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
974 if (attr->a_desc == ad_queryid) {
975 for (count=0; attr->a_vals[count].bv_val; count++)
980 if ( count == 0 ) return 0;
981 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
982 qi->next = op->o_callback->sc_private;
983 op->o_callback->sc_private = qi;
984 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
985 qi->del = ( count == 1 );
994 struct berval* query_uuid)
996 struct query_info *qi, *qnext;
998 #ifdef LDAP_COMP_MATCH
999 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1001 AttributeAssertion ava = { NULL, BER_BVNULL };
1003 Filter filter = {LDAP_FILTER_EQUALITY};
1004 SlapReply sreply = {REP_RESULT};
1005 slap_callback cb = { NULL, remove_func, NULL, NULL };
1008 sreply.sr_entry = NULL;
1009 sreply.sr_nentries = 0;
1010 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1011 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
1012 filter.f_ava = &ava;
1013 filter.f_av_desc = ad_queryid;
1014 filter.f_av_value = *query_uuid;
1016 op->o_tag = LDAP_REQ_SEARCH;
1017 op->o_protocol = LDAP_VERSION3;
1018 op->o_callback = &cb;
1019 op->o_time = slap_get_time();
1020 op->o_do_not_cache = 1;
1022 op->o_req_dn = op->o_bd->be_suffix[0];
1023 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1024 op->ors_scope = LDAP_SCOPE_SUBTREE;
1025 op->ors_deref = LDAP_DEREF_NEVER;
1026 op->ors_slimit = SLAP_NO_LIMIT;
1027 op->ors_tlimit = SLAP_NO_LIMIT;
1028 op->ors_filter = &filter;
1029 op->ors_filterstr.bv_val = filter_str;
1030 op->ors_filterstr.bv_len = strlen(filter_str);
1031 op->ors_attrs = NULL;
1032 op->ors_attrsonly = 0;
1034 op->o_bd->be_search( op, &sreply );
1036 for ( qi=cb.sc_private; qi; qi=qnext ) {
1039 op->o_req_dn = qi->xdn;
1040 op->o_req_ndn = qi->xdn;
1043 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1044 query_uuid->bv_val, 0, 0 );
1046 op->o_tag = LDAP_REQ_DELETE;
1048 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1053 struct berval vals[2];
1055 vals[0] = *query_uuid;
1056 vals[1].bv_val = NULL;
1058 mod.sml_op = LDAP_MOD_DELETE;
1060 mod.sml_desc = ad_queryid;
1061 mod.sml_type = ad_queryid->ad_cname;
1062 mod.sml_values = vals;
1063 mod.sml_nvalues = NULL;
1064 mod.sml_next = NULL;
1065 Debug( pcache_debug,
1066 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1067 query_uuid->bv_val, 0, 0 );
1069 op->orm_modlist = &mod;
1071 op->o_bd->be_modify( op, &sreply );
1073 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1074 op->o_tmpfree( qi, op->o_tmpmemctx );
1081 AttributeName* attrs,
1090 struct berval *fstr,
1091 AttributeName** filter_attrs,
1093 int* filter_got_oc )
1095 AttributeDescription *ad;
1097 switch ( f->f_choice ) {
1098 case LDAP_FILTER_EQUALITY:
1100 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1101 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1104 case LDAP_FILTER_GE:
1106 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1107 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1110 case LDAP_FILTER_LE:
1112 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1113 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1116 case LDAP_FILTER_APPROX:
1118 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1119 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1122 case LDAP_FILTER_SUBSTRINGS:
1124 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1125 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1128 case LDAP_FILTER_PRESENT:
1130 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1131 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1134 case LDAP_FILTER_AND:
1135 case LDAP_FILTER_OR:
1136 case LDAP_FILTER_NOT: {
1138 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1139 f->f_choice == LDAP_FILTER_AND ? '&' :
1140 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1141 fstr->bv_len += sizeof("(%") - 1;
1143 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1144 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1148 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1149 fstr->bv_len += sizeof(")") - 1;
1155 strcpy( fstr->bv_val, "(?=?)" );
1156 fstr->bv_len += sizeof("(?=?)")-1;
1160 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1161 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1163 (*filter_attrs)[*filter_cnt].an_desc = ad;
1164 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1165 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1166 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1167 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1169 if ( ad == slap_schema.si_ad_objectClass )
1174 struct search_info {
1177 QueryTemplate *qtemp;
1178 AttributeName* save_attrs; /* original attributes, saved for response */
1189 struct berval *query_uuid)
1191 struct search_info *si = op->o_callback->sc_private;
1192 slap_overinst *on = si->on;
1193 cache_manager *cm = on->on_bi.bi_private;
1194 query_manager* qm = cm->qm;
1197 struct berval crp_uuid;
1198 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1199 Operation op_tmp = *op;
1201 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1202 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1204 op_tmp.o_bd = &cm->db;
1205 op_tmp.o_dn = cm->db.be_rootdn;
1206 op_tmp.o_ndn = cm->db.be_rootndn;
1208 Debug( pcache_debug, "UUID for query being added = %s\n",
1211 for ( e=si->head; e; e=si->head ) {
1212 si->head = e->e_private;
1213 e->e_private = NULL;
1214 while ( cm->cur_entries > (cm->max_entries) ) {
1215 qm->crfunc(qm, &crp_uuid);
1216 if (crp_uuid.bv_val) {
1217 Debug( pcache_debug,
1218 "Removing query UUID %s\n",
1219 crp_uuid.bv_val, 0, 0 );
1220 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1221 Debug( pcache_debug,
1222 "QUERY REMOVED, SIZE=%d\n",
1224 ldap_pvt_thread_mutex_lock(
1226 cm->cur_entries -= return_val;
1227 cm->num_cached_queries--;
1228 Debug( pcache_debug,
1229 "STORED QUERIES = %lu\n",
1230 cm->num_cached_queries, 0, 0 );
1231 ldap_pvt_thread_mutex_unlock(
1233 Debug( pcache_debug,
1234 "QUERY REMOVED, CACHE ="
1236 cm->cur_entries, 0, 0 );
1240 return_val = merge_entry(&op_tmp, e, query_uuid);
1241 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1242 cm->cur_entries += return_val;
1243 Debug( pcache_debug,
1244 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1245 cm->cur_entries, 0, 0 );
1247 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1258 struct search_info *si = op->o_callback->sc_private;
1259 slap_overinst *on = si->on;
1260 cache_manager *cm = on->on_bi.bi_private;
1261 query_manager* qm = cm->qm;
1263 if ( si->save_attrs != NULL ) {
1264 rs->sr_attrs = si->save_attrs;
1265 op->ors_attrs = si->save_attrs;
1266 si->save_attrs = NULL;
1269 if ( rs->sr_type == REP_SEARCH ) {
1271 /* If we haven't exceeded the limit for this query,
1272 * build a chain of answers to store. If we hit the
1273 * limit, empty the chain and ignore the rest.
1276 if ( si->count < si->max ) {
1278 e = entry_dup( rs->sr_entry );
1279 if ( !si->head ) si->head = e;
1280 if ( si->tail ) si->tail->e_private = e;
1285 for (;si->head; si->head=e) {
1286 e = si->head->e_private;
1287 si->head->e_private = NULL;
1288 entry_free(si->head);
1294 } else if ( rs->sr_type == REP_RESULT ) {
1296 ( si->qtemp->negttl && !si->count && !si->over &&
1297 rs->sr_err == LDAP_SUCCESS )) {
1298 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1303 cache_entries( op, rs, &qc->q_uuid );
1304 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1305 cm->num_cached_queries++;
1306 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1307 cm->num_cached_queries, 0, 0 );
1308 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1310 /* If the consistency checker suspended itself,
1313 if ( cm->cc_paused ) {
1314 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1315 if ( cm->cc_paused ) {
1317 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1319 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1321 } else if ( si->count ) {
1322 /* duplicate query, free it */
1324 for (;si->head; si->head=e) {
1325 e = si->head->e_private;
1326 si->head->e_private = NULL;
1327 entry_free(si->head);
1331 filter_free( si->query.filter );
1335 op->o_callback->sc_cleanup = slap_freeself_cb;
1337 return SLAP_CB_CONTINUE;
1343 AttributeName** new_attrs,
1344 struct attr_set *attrs,
1345 AttributeName* filter_attrs,
1355 /* duplicate attrs */
1356 count = attrs->count + fattr_cnt;
1357 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1362 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1363 sizeof(AttributeName));
1364 for (i=0; i<attrs->count; i++) {
1365 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1366 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1368 BER_BVZERO( &(*new_attrs)[i].an_name );
1369 alluser = an_find(*new_attrs, &AllUser);
1370 allop = an_find(*new_attrs, &AllOper);
1373 for ( i=0; i<fattr_cnt; i++ ) {
1374 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1376 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1381 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1382 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1383 (*new_attrs)[j].an_oc = NULL;
1384 (*new_attrs)[j].an_oc_exclude = 0;
1388 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1389 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1390 (*new_attrs)[j].an_oc = NULL;
1391 (*new_attrs)[j].an_oc_exclude = 0;
1394 BER_BVZERO( &(*new_attrs)[j].an_name );
1397 /* NOTE: this is a quick workaround to let pcache minimally interact
1398 * with pagedResults. A more articulated solutions would be to
1399 * perform the remote query without control and cache all results,
1400 * performing the pagedResults search only within the client
1401 * and the proxy. This requires pcache to understand pagedResults. */
1403 pcache_chk_controls(
1407 const char *non = "";
1408 const char *stripped = "";
1410 switch( op->o_pagedresults ) {
1411 case SLAP_CONTROL_NONCRITICAL:
1413 stripped = "; stripped";
1416 case SLAP_CONTROL_CRITICAL:
1417 Debug( pcache_debug, "%s: "
1418 "%scritical pagedResults control "
1419 "disabled with proxy cache%s.\n",
1420 op->o_log_prefix, non, stripped );
1422 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1426 rs->sr_err = SLAP_CB_CONTINUE;
1438 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1439 cache_manager *cm = on->on_bi.bi_private;
1440 query_manager* qm = cm->qm;
1444 AttributeName *filter_attrs = NULL;
1447 QueryTemplate *qtemp = NULL;
1450 CachedQuery *answerable = NULL;
1453 int fattr_got_oc = 0;
1455 struct berval tempstr;
1457 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1459 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1460 &fattr_cnt, &fattr_got_oc )) {
1461 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1462 return SLAP_CB_CONTINUE;
1465 Debug( pcache_debug, "query template of incoming query = %s\n",
1466 tempstr.bv_val, 0, 0 );
1468 /* FIXME: cannot cache/answer requests with pagedResults control */
1471 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1473 query.filter = op->ors_filter;
1474 query.base = op->o_req_ndn;
1475 query.scope = op->ors_scope;
1477 /* check for query containment */
1478 if (attr_set > -1) {
1479 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1480 for (; qt; qt = qt->qtnext ) {
1481 /* find if template i can potentially answer tempstr */
1482 if (qt->querystr.bv_len != tempstr.bv_len ||
1483 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1487 Debug( pcache_debug, "Entering QC, querystr = %s\n",
1488 op->ors_filterstr.bv_val, 0, 0 );
1489 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1495 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1498 /* Need to clear the callbacks of the original operation,
1499 * in case there are other overlays */
1500 BackendDB *save_bd = op->o_bd;
1501 slap_callback *save_cb = op->o_callback;
1503 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1504 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1505 if ( BER_BVISNULL( &answerable->q_uuid )) {
1506 /* No entries cached, just an empty result set */
1508 send_ldap_result( op, rs );
1511 op->o_callback = NULL;
1512 i = cm->db.bd_info->bi_op_search( op, rs );
1514 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1516 op->o_callback = save_cb;
1520 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1522 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1523 if (cm->num_cached_queries >= cm->max_queries) {
1526 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1528 if (op->ors_attrsonly)
1533 struct search_info *si;
1535 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1536 query.filter = filter_dup(op->ors_filter, NULL);
1537 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1538 if ( !qtemp->t_attrs.count ) {
1539 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1540 &qm->attr_sets[attr_set],
1541 filter_attrs, fattr_cnt, fattr_got_oc);
1543 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1545 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1546 cb->sc_response = pcache_response;
1547 cb->sc_cleanup = NULL;
1548 cb->sc_private = (cb+1);
1549 si = cb->sc_private;
1553 si->max = cm->num_entries_limit ;
1558 si->save_attrs = op->ors_attrs;
1560 op->ors_attrs = qtemp->t_attrs.attrs;
1562 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1563 cb->sc_next = op->o_callback;
1564 op->o_callback = cb;
1567 slap_callback **pcb;
1569 /* need to move the callback at the end, in case other
1570 * overlays are present, so that the final entry is
1571 * actually cached */
1573 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1578 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1582 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1584 return SLAP_CB_CONTINUE;
1589 AttributeName* attrs,
1597 for ( ; attrs[count].an_name.bv_val; count++ );
1600 for (i=0; i<num; i++) {
1604 if ( count > qm->attr_sets[i].count )
1607 if ( !qm->attr_sets[i].count )
1611 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1612 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1630 struct re_s *rtask = arg;
1631 slap_overinst *on = rtask->arg;
1632 cache_manager *cm = on->on_bi.bi_private;
1633 query_manager *qm = cm->qm;
1634 Connection conn = {0};
1635 OperationBuffer opbuf;
1638 SlapReply rs = {REP_RESULT};
1640 int return_val, pause = 1;
1641 QueryTemplate* templ;
1643 op = (Operation *) &opbuf;
1644 connection_fake_init( &conn, op, ctx );
1647 op->o_dn = cm->db.be_rootdn;
1648 op->o_ndn = cm->db.be_rootndn;
1652 for (templ = qm->templates; templ; templ=templ->qmnext) {
1653 query = templ->query_last;
1654 if ( query ) pause = 0;
1655 op->o_time = slap_get_time();
1656 while (query && (query->expiry_time < op->o_time)) {
1658 Debug( pcache_debug, "Lock CR index = %p\n",
1659 (void *) templ, 0, 0 );
1660 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1661 if ( query == templ->query_last ) {
1663 remove_from_template(query, templ);
1664 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1665 (void *) templ, templ->no_of_queries, 0 );
1666 Debug( pcache_debug, "Unlock CR index = %p\n",
1667 (void *) templ, 0, 0 );
1669 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1671 query = templ->query_last;
1674 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1675 remove_query(qm, query);
1676 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1677 if ( BER_BVISNULL( &query->q_uuid ))
1680 return_val = remove_query_data(op, &rs, &query->q_uuid);
1681 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1683 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1684 cm->cur_entries -= return_val;
1685 cm->num_cached_queries--;
1686 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1687 cm->num_cached_queries, 0, 0 );
1688 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1689 Debug( pcache_debug,
1690 "STALE QUERY REMOVED, CACHE ="
1692 cm->cur_entries, 0, 0 );
1694 query = templ->query_last;
1697 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1698 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1699 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1701 /* If there were no queries, defer processing for a while */
1702 cm->cc_paused = pause;
1703 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1705 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1710 #define MAX_ATTR_SETS 500
1720 static ConfigDriver pc_cf_gen;
1721 static ConfigLDAPadd pc_ldadd;
1722 static ConfigCfAdd pc_cfadd;
1724 static ConfigTable pccfg[] = {
1725 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1727 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1728 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1729 "DESC 'ProxyCache basic parameters' "
1730 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1731 { "proxyattrset", "index> <attributes...",
1732 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1733 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1734 "DESC 'A set of attributes to cache' "
1735 "SYNTAX OMsDirectoryString )", NULL, NULL },
1736 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1737 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1738 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1739 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1740 "SYNTAX OMsDirectoryString )", NULL, NULL },
1741 { "response-callback", "head|tail(default)",
1742 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1743 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1744 "DESC 'Response callback position in overlay stack' "
1745 "SYNTAX OMsDirectoryString )", NULL, NULL },
1746 { "proxyCacheQueries", "queries",
1747 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1748 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1749 "DESC 'Maximum number of queries to cache' "
1750 "SYNTAX OMsInteger )", NULL, NULL },
1752 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1755 static ConfigOCs pcocs[] = {
1756 { "( OLcfgOvOc:2.1 "
1757 "NAME 'olcPcacheConfig' "
1758 "DESC 'ProxyCache configuration' "
1759 "SUP olcOverlayConfig "
1760 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1761 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1762 { "( OLcfgOvOc:2.2 "
1763 "NAME 'olcPcacheDatabase' "
1764 "DESC 'Cache database configuration' "
1765 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1770 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1775 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1776 p->ce_bi->bi_cf_ocs != pcocs )
1777 return LDAP_CONSTRAINT_VIOLATION;
1779 on = (slap_overinst *)p->ce_bi;
1780 cm = on->on_bi.bi_private;
1782 return LDAP_SUCCESS;
1786 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1788 CfEntryInfo *pe = p->e_private;
1789 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1790 cache_manager *cm = on->on_bi.bi_private;
1793 /* FIXME: should not hardcode "olcDatabase" here */
1794 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1795 bv.bv_val = ca->msg;
1798 /* We can only create this entry if the database is table-driven
1800 if ( cm->db.bd_info->bi_cf_ocs )
1801 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1808 pc_cf_gen( ConfigArgs *c )
1810 slap_overinst *on = (slap_overinst *)c->bi;
1811 cache_manager* cm = on->on_bi.bi_private;
1812 query_manager* qm = cm->qm;
1813 QueryTemplate* temp;
1814 AttributeName* attr_name;
1815 AttributeName* attrarray;
1816 const char* text=NULL;
1821 if ( c->op == SLAP_CONFIG_EMIT ) {
1825 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1826 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1827 cm->num_entries_limit, cm->cc_period );
1829 value_add_one( &c->rvalue_vals, &bv );
1832 for (i=0; i<cm->numattrsets; i++) {
1833 if ( !qm->attr_sets[i].count ) continue;
1835 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1837 /* count the attr length */
1838 for ( attr_name = qm->attr_sets[i].attrs;
1839 attr_name->an_name.bv_val; attr_name++ )
1840 bv.bv_len += attr_name->an_name.bv_len + 1;
1842 bv.bv_val = ch_malloc( bv.bv_len+1 );
1843 ptr = lutil_strcopy( bv.bv_val, c->msg );
1844 for ( attr_name = qm->attr_sets[i].attrs;
1845 attr_name->an_name.bv_val; attr_name++ ) {
1847 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1849 ber_bvarray_add( &c->rvalue_vals, &bv );
1851 if ( !c->rvalue_vals )
1855 for (temp=qm->templates; temp; temp=temp->qmnext) {
1856 if ( temp->negttl ) {
1857 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1859 temp->attr_set_index,
1863 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1864 temp->attr_set_index,
1867 bv.bv_len += temp->querystr.bv_len + 2;
1868 bv.bv_val = ch_malloc( bv.bv_len+1 );
1871 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1873 strcpy( ptr, c->msg );
1874 ber_bvarray_add( &c->rvalue_vals, &bv );
1876 if ( !c->rvalue_vals )
1880 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1881 BER_BVSTR( &bv, "head" );
1883 BER_BVSTR( &bv, "tail" );
1885 value_add_one( &c->rvalue_vals, &bv );
1888 c->value_int = cm->max_queries;
1892 } else if ( c->op == LDAP_MOD_DELETE ) {
1893 return 1; /* FIXME */
1905 if ( cm->numattrsets > 0 ) {
1906 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1907 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1911 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1912 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1914 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1917 if ( cm->numattrsets <= 0 ) {
1918 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1919 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1922 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1923 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1924 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1928 if ( !backend_db_init( c->argv[1], &cm->db )) {
1929 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1930 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1934 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1935 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1937 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1940 if ( cm->max_entries <= 0 ) {
1941 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1942 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1946 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1947 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1949 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1952 if ( cm->num_entries_limit <= 0 ) {
1953 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1954 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1957 if ( cm->num_entries_limit > cm->max_entries ) {
1958 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1959 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1963 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1964 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1966 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1969 cm->cc_period = (time_t)t;
1970 Debug( pcache_debug,
1971 "Total # of attribute sets to be cached = %d.\n",
1972 cm->numattrsets, 0, 0 );
1973 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1974 sizeof( struct attr_set ) );
1977 if ( cm->numattrsets == 0 ) {
1978 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1979 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1982 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1983 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1985 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1989 if ( num < 0 || num >= cm->numattrsets ) {
1990 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1991 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1992 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1995 qm->attr_sets[num].flags |= PC_CONFIGURED;
1996 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1997 qm->attr_sets[num].count = c->argc - 2;
1998 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
1999 (c->argc-1) * sizeof( AttributeName ));
2000 attr_name = qm->attr_sets[num].attrs;
2001 for ( i = 2; i < c->argc; i++ ) {
2002 attr_name->an_desc = NULL;
2003 if ( slap_str2ad( c->argv[i],
2004 &attr_name->an_desc, &text ) )
2006 strcpy( c->msg, text );
2007 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2008 ch_free( qm->attr_sets[num].attrs );
2009 qm->attr_sets[num].attrs = NULL;
2010 qm->attr_sets[num].count = 0;
2013 attr_name->an_name = attr_name->an_desc->ad_cname;
2014 attr_name->an_oc = NULL;
2015 attr_name->an_oc_exclude = 0;
2016 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2017 qm->attr_sets[num].flags |= PC_GOT_OC;
2019 BER_BVZERO( &attr_name->an_name );
2024 if ( cm->numattrsets == 0 ) {
2025 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
2026 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2029 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2030 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
2032 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2036 if ( i < 0 || i >= cm->numattrsets ||
2037 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2038 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
2039 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2040 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2043 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2044 temp->qmnext = qm->templates;
2045 qm->templates = temp;
2046 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2047 temp->query = temp->query_last = NULL;
2048 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2049 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
2051 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2054 temp->ttl = (time_t)t;
2055 if ( c->argc == 5 ) {
2056 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2057 snprintf( c->msg, sizeof( c->msg ),
2058 "unable to parse template negttl=\"%s\"",
2060 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2063 temp->negttl = (time_t)t;
2068 temp->no_of_queries = 0;
2070 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2071 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2072 Debug( pcache_debug, " query template: %s\n",
2073 temp->querystr.bv_val, 0, 0 );
2074 temp->attr_set_index = i;
2075 qm->attr_sets[i].flags |= PC_REFERENCED;
2076 temp->qtnext = qm->attr_sets[i].templates;
2077 qm->attr_sets[i].templates = temp;
2078 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2079 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2080 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2081 Debug( pcache_debug, "\t%s\n",
2082 attrarray[i].an_name.bv_val, 0, 0 );
2086 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2087 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2089 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2090 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2093 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
2094 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2099 if ( c->value_int <= 0 ) {
2100 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
2101 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2104 cm->max_queries = c->value_int;
2119 slap_overinst *on = (slap_overinst *)be->bd_info;
2120 cache_manager* cm = on->on_bi.bi_private;
2122 /* Something for the cache database? */
2123 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2124 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2126 return SLAP_CONF_UNKNOWN;
2133 slap_overinst *on = (slap_overinst *)be->bd_info;
2137 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2138 on->on_bi.bi_private = cm;
2140 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2143 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2144 cm->db.be_private = NULL;
2145 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2147 cm->numattrsets = 0;
2148 cm->num_entries_limit = 5;
2149 cm->num_cached_queries = 0;
2150 cm->max_entries = 0;
2151 cm->cur_entries = 0;
2152 cm->max_queries = 10000;
2153 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2154 cm->cc_period = 1000;
2157 qm->attr_sets = NULL;
2158 qm->templates = NULL;
2160 qm->lru_bottom = NULL;
2162 qm->qcfunc = query_containment;
2163 qm->crfunc = cache_replacement;
2164 qm->addfunc = add_query;
2165 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2167 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2175 slap_overinst *on = (slap_overinst *)be->bd_info;
2176 cache_manager *cm = on->on_bi.bi_private;
2177 query_manager* qm = cm->qm;
2178 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2180 /* check attr sets */
2181 for ( i = 0; i < cm->numattrsets; i++) {
2182 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2183 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2184 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2188 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2192 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2193 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2198 if ( ncf || rf || nrf ) {
2199 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2200 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2201 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2208 /* need to inherit something from the original database... */
2209 cm->db.be_def_limit = be->be_def_limit;
2210 cm->db.be_limits = be->be_limits;
2211 cm->db.be_acl = be->be_acl;
2212 cm->db.be_dfltaccess = be->be_dfltaccess;
2214 if ( SLAP_DBMONITORING( be ) ) {
2215 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2218 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2221 rc = backend_startup_one( &cm->db );
2223 /* There is no runqueue in TOOL mode */
2224 if ( slapMode & SLAP_SERVER_MODE ) {
2225 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2226 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2227 consistency_check, on,
2228 "pcache_consistency", be->be_suffix[0].bv_val );
2229 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2231 /* Cached database must have the rootdn */
2232 if ( BER_BVISNULL( &cm->db.be_rootndn )
2233 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2235 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2236 "underlying database of type \"%s\"\n"
2237 " serving naming context \"%s\"\n"
2238 " has no \"rootdn\", required by \"proxycache\".\n",
2239 on->on_info->oi_orig->bi_type,
2240 cm->db.be_suffix[0].bv_val, 0 );
2249 pcache_free_qbase( void *v )
2255 tavl_free( qb->scopes[i], NULL );
2264 slap_overinst *on = (slap_overinst *)be->bd_info;
2265 cache_manager *cm = on->on_bi.bi_private;
2266 query_manager *qm = cm->qm;
2270 /* cleanup stuff inherited from the original database... */
2271 cm->db.be_limits = NULL;
2272 cm->db.be_acl = NULL;
2274 if ( cm->db.bd_info->bi_db_close ) {
2275 rc = cm->db.bd_info->bi_db_close( &cm->db );
2277 while ( (tm = qm->templates) != NULL ) {
2278 CachedQuery *qc, *qn;
2279 qm->templates = tm->qmnext;
2280 for ( qc = tm->query; qc; qc = qn ) {
2284 avl_free( tm->qbase, pcache_free_qbase );
2285 free( tm->querystr.bv_val );
2286 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2287 free( tm->t_attrs.attrs );
2291 for ( i=0; i<cm->numattrsets; i++ ) {
2292 free( qm->attr_sets[i].attrs );
2294 free( qm->attr_sets );
2295 qm->attr_sets = NULL;
2305 slap_overinst *on = (slap_overinst *)be->bd_info;
2306 cache_manager *cm = on->on_bi.bi_private;
2307 query_manager *qm = cm->qm;
2309 if ( cm->db.be_private != NULL ) {
2310 backend_stopdown_one( &cm->db );
2313 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2314 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2321 static slap_overinst pcache;
2323 static char *obsolete_names[] = {
2328 int pcache_initialize()
2331 struct berval debugbv = BER_BVC("pcache");
2333 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2336 code = register_at( queryid_schema, &ad_queryid, 0 );
2338 Debug( LDAP_DEBUG_ANY,
2339 "pcache_initialize: register_at failed\n", 0, 0, 0 );
2343 pcache.on_bi.bi_type = "pcache";
2344 pcache.on_bi.bi_obsolete_names = obsolete_names;
2345 pcache.on_bi.bi_db_init = pcache_db_init;
2346 pcache.on_bi.bi_db_config = pcache_db_config;
2347 pcache.on_bi.bi_db_open = pcache_db_open;
2348 pcache.on_bi.bi_db_close = pcache_db_close;
2349 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2351 pcache.on_bi.bi_op_search = pcache_op_search;
2353 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2355 pcache.on_bi.bi_cf_ocs = pcocs;
2357 code = config_register_schema( pccfg, pcocs );
2358 if ( code ) return code;
2360 return overlay_register( &pcache );
2363 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2364 int init_module(int argc, char *argv[]) {
2365 return pcache_initialize();
2369 #endif /* defined(SLAPD_OVER_PROXYCACHE) */