2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2006 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
38 /* query cache structs */
41 typedef struct Query_s {
42 Filter* filter; /* Search Filter */
43 struct berval base; /* Search Base */
44 int scope; /* Search scope */
47 struct query_template_s;
49 typedef struct Qbase_s {
50 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
54 /* struct representing a cached query */
55 typedef struct cached_query_s {
60 struct berval q_uuid; /* query identifier */
61 struct query_template_s *qtemp; /* template of the query */
62 time_t expiry_time; /* time till the query is considered valid */
63 struct cached_query_s *next; /* next query in the template */
64 struct cached_query_s *prev; /* previous query in the template */
65 struct cached_query_s *lru_up; /* previous query in the LRU list */
66 struct cached_query_s *lru_down; /* next query in the LRU list */
70 * Represents a set of projected attributes.
74 struct query_template_s *templates;
75 AttributeName* attrs; /* specifies the set */
77 #define PC_CONFIGURED (0x1)
78 #define PC_REFERENCED (0x2)
79 #define PC_GOT_OC (0x4)
80 int count; /* number of attributes */
83 /* struct representing a query template
84 * e.g. template string = &(cn=)(mail=)
86 typedef struct query_template_s {
87 struct query_template_s *qtnext;
88 struct query_template_s *qmnext;
91 CachedQuery* query; /* most recent query cached for the template */
92 CachedQuery* query_last; /* oldest query cached for the template */
93 ldap_pvt_thread_rdwr_t *t_rwlock; /* Rd/wr lock for accessing queries in the template */
94 struct berval querystr; /* Filter string corresponding to the QT */
96 int attr_set_index; /* determines the projected attributes */
97 int no_of_queries; /* Total number of queries in the template */
98 time_t ttl; /* TTL for the queries of this template */
99 time_t negttl; /* TTL for negative results */
100 struct attr_set t_attrs; /* filter attrs + attr_set */
103 struct query_manager_s;
105 /* prototypes for functions for 1) query containment
106 * 2) query addition, 3) cache replacement
108 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
109 typedef void (AddQueryfunc)(struct query_manager_s*, Query*, QueryTemplate*, struct berval*);
110 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
112 /* LDAP query cache */
113 typedef struct query_manager_s {
114 struct attr_set* attr_sets; /* possible sets of projected attributes */
115 QueryTemplate* templates; /* cacheable templates */
117 CachedQuery* lru_top; /* top and bottom of LRU list */
118 CachedQuery* lru_bottom;
120 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
122 /* Query cache methods */
123 QCfunc *qcfunc; /* Query containment*/
124 CRfunc *crfunc; /* cache replacement */
125 AddQueryfunc *addfunc; /* add query */
128 /* LDAP query cache manager */
129 typedef struct cache_manager_s {
130 BackendDB db; /* underlying database */
131 unsigned long num_cached_queries; /* total number of cached queries */
132 unsigned long max_queries; /* upper bound on # of cached queries */
133 int numattrsets; /* number of attribute sets */
134 int cur_entries; /* current number of entries cached */
135 int max_entries; /* max number of entries cached */
136 int num_entries_limit; /* max # of entries in a cacheable query */
138 char response_cb; /* install the response callback
139 * at the tail of the callback list */
140 #define PCACHE_RESPONSE_CB_HEAD 0
141 #define PCACHE_RESPONSE_CB_TAIL 1
143 time_t cc_period; /* interval between successive consistency checks (sec) */
147 ldap_pvt_thread_mutex_t cache_mutex;
149 query_manager* qm; /* query cache managed by the cache manager */
152 static int pcache_debug;
154 static AttributeDescription *ad_queryid;
155 static char *queryid_schema = "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
156 "DESC 'list of queries the entry belongs to' "
157 "EQUALITY octetStringMatch "
158 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
159 "NO-USER-MODIFICATION USAGE directoryOperation )";
161 /* Return 1 for an added entry, else 0 */
166 struct berval* query_uuid )
169 Modifications* modlist = NULL;
170 const char* text = NULL;
172 char textbuf[SLAP_TEXT_BUFLEN];
173 size_t textlen = sizeof(textbuf);
175 SlapReply sreply = {REP_RESULT};
177 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
182 /* add queryid attribute */
183 attr_merge_one( e, ad_queryid, query_uuid, NULL );
185 /* append the attribute list from the fetched entry */
186 e->e_attrs->a_next = attr;
188 op->o_tag = LDAP_REQ_ADD;
189 op->o_protocol = LDAP_VERSION3;
190 op->o_callback = &cb;
191 op->o_time = slap_get_time();
192 op->o_do_not_cache = 1;
195 op->o_req_dn = e->e_name;
196 op->o_req_ndn = e->e_nname;
197 rc = op->o_bd->be_add( op, &sreply );
199 if ( rc != LDAP_SUCCESS ) {
200 if ( rc == LDAP_ALREADY_EXISTS ) {
201 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
202 modlist->sml_op = LDAP_MOD_ADD;
203 op->o_tag = LDAP_REQ_MODIFY;
204 op->orm_modlist = modlist;
205 op->o_bd->be_modify( op, &sreply );
206 slap_mods_free( modlist, 1 );
207 } else if ( rc == LDAP_REFERRAL ||
208 rc == LDAP_NO_SUCH_OBJECT ) {
209 syncrepl_add_glue( op, e );
218 be_entry_release_w( op, e );
225 /* Length-ordered sort on normalized DNs */
226 static int pcache_dn_cmp( const void *v1, const void *v2 )
228 const Qbase *q1 = v1, *q2 = v2;
230 int rc = q1->base.bv_len - q2->base.bv_len;
232 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
236 /* compare the first value in each filter */
237 static int pcache_filter_cmp( const void *v1, const void *v2 )
239 const CachedQuery *q1 = v1, *q2 =v2;
240 int rc, weight1, weight2;
242 switch( q1->first->f_choice ) {
243 case LDAP_FILTER_PRESENT:
246 case LDAP_FILTER_EQUALITY:
254 switch( q2->first->f_choice ) {
255 case LDAP_FILTER_PRESENT:
258 case LDAP_FILTER_EQUALITY:
266 rc = weight1 - weight2;
271 rc = ber_bvcmp( &q1->first->f_ava->aa_value,
272 &q2->first->f_ava->aa_value );
275 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
277 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
278 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
279 rc = ber_bvcmp( &q1->first->f_sub_initial,
280 &q2->first->f_sub_initial );
284 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
288 if ( q1->first->f_sub_any ) {
289 if ( q2->first->f_sub_any ) {
290 rc = ber_bvcmp( q1->first->f_sub_any,
291 q2->first->f_sub_any );
295 } else if ( q2->first->f_sub_any ) {
299 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
300 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
301 rc = ber_bvcmp( &q1->first->f_sub_final,
302 &q2->first->f_sub_final );
306 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
310 rc = ber_bvcmp( &q1->first->f_mr_value,
311 &q2->first->f_mr_value );
320 /* add query on top of LRU list */
322 add_query_on_top (query_manager* qm, CachedQuery* qc)
324 CachedQuery* top = qm->lru_top;
325 Query* q = (Query*)qc;
336 Debug( pcache_debug, "Base of added query = %s\n",
337 q->base.bv_val, 0, 0 );
340 /* remove_query from LRU list */
343 remove_query (query_manager* qm, CachedQuery* qc)
366 qc->lru_up = qc->lru_down = NULL;
369 /* find and remove string2 from string1
370 * from start if position = 1,
371 * from end if position = 3,
372 * from anywhere if position = 2
373 * string1 is overwritten if position = 2.
377 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
388 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
389 ber2->bv_val, ber2->bv_len )) {
391 ber1->bv_val += ber2->bv_len;
392 ber1->bv_len -= ber2->bv_len;
397 ber1->bv_val[ber1->bv_len] = '\0';
398 temp = strstr( ber1->bv_val, ber2->bv_val );
400 strcpy( temp, temp+ber2->bv_len );
401 ber1->bv_len -= ber2->bv_len;
407 if ( ber1->bv_len >= ber2->bv_len &&
408 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
411 ber1->bv_len -= ber2->bv_len;
419 static struct berval*
420 merge_init_final(Operation *op, struct berval* init, struct berval* any,
421 struct berval* final)
423 struct berval* merged, *temp;
424 int i, any_count, count;
426 for (any_count=0; any && any[any_count].bv_val; any_count++)
436 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
441 ber_dupbv_x( temp, init, op->o_tmpmemctx );
445 for (i=0; i<any_count; i++) {
446 ber_dupbv_x( temp, any, op->o_tmpmemctx );
451 ber_dupbv_x( temp, final, op->o_tmpmemctx );
458 /* Each element in stored must be found in incoming. Incoming is overwritten.
461 strings_containment(struct berval* stored, struct berval* incoming)
463 struct berval* element;
467 for ( element=stored; element->bv_val != NULL; element++ ) {
468 for (j = k; incoming[j].bv_val != NULL; j++) {
469 if (find_and_remove(&(incoming[j]), element, 2)) {
486 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
490 struct berval init_incoming;
491 struct berval final_incoming;
492 struct berval *remaining_incoming = NULL;
494 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
495 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
498 init_incoming = incoming->f_sub_initial;
499 final_incoming = incoming->f_sub_final;
501 if (find_and_remove(&init_incoming,
502 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
503 &(stored->f_sub_final), 3))
505 if (stored->f_sub_any == NULL) {
509 remaining_incoming = merge_init_final(op, &init_incoming,
510 incoming->f_sub_any, &final_incoming);
511 rc = strings_containment(stored->f_sub_any, remaining_incoming);
512 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
519 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
521 struct berval incoming_val[2];
524 incoming_val[1] = incoming->f_av_value;
526 if (find_and_remove(incoming_val+1,
527 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
528 &(stored->f_sub_final), 3)) {
529 if (stored->f_sub_any == NULL){
533 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
534 BER_BVZERO( incoming_val+1 );
535 rc = strings_containment(stored->f_sub_any, incoming_val);
536 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
543 filter_first( Filter *f )
545 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
552 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
557 MatchingRule* mrule = NULL;
566 /* substring matches sort to the end, and we just have to
567 * walk the entire list.
569 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
570 ptr = tavl_end( root, 1 );
573 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
574 dir = (first->f_choice == LDAP_FILTER_LE) ? TAVL_DIR_LEFT :
584 switch (fs->f_choice) {
585 case LDAP_FILTER_EQUALITY:
586 if (fi->f_choice == LDAP_FILTER_EQUALITY)
587 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
593 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
600 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
601 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
602 &(fi->f_ava->aa_value),
603 &(fs->f_ava->aa_value), &text);
604 if (rc != LDAP_SUCCESS) {
608 switch (fs->f_choice) {
610 case LDAP_FILTER_AND:
615 case LDAP_FILTER_SUBSTRINGS:
616 /* check if the equality query can be
617 * answered with cached substring query */
618 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
619 && substr_containment_equality( op,
622 /* check if the substring query can be
623 * answered with cached substring query */
624 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
625 ) && substr_containment_substr( op,
631 case LDAP_FILTER_PRESENT:
636 case LDAP_FILTER_EQUALITY:
643 if (mrule && ret >= 0)
649 if (mrule && ret <= 0)
654 case LDAP_FILTER_NOT:
660 } while((res) && (fi != NULL) && (fs != NULL));
664 ptr = tavl_next( ptr, dir );
669 /* check whether query is contained in any of
670 * the cached queries in template
673 query_containment(Operation *op, query_manager *qm,
675 QueryTemplate *templa)
678 int depth = 0, tscope;
679 Qbase qbase, *qbptr = NULL;
682 if (query->filter != NULL) {
685 Debug( pcache_debug, "Lock QC index = %p\n",
687 qbase.base = query->base;
689 first = filter_first( query->filter );
691 ldap_pvt_thread_rdwr_rlock(templa->t_rwlock);
694 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
696 tscope = query->scope;
697 /* Find a matching scope:
698 * match at depth 0 OK
701 * subord at depth > 0 OK
702 * subtree at any depth OK
704 * subtree or subord at any depth OK
706 * subtree or subord at any depth OK
708 * subord at depth > 0 OK
709 * subtree at any depth OK
711 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
712 switch ( query->scope ) {
713 case LDAP_SCOPE_BASE:
714 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
715 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
716 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
719 if ( tscope == LDAP_SCOPE_BASE )
720 tscope = LDAP_SCOPE_ONE;
721 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
723 if ( tscope < LDAP_SCOPE_SUBTREE )
724 tscope = LDAP_SCOPE_SUBTREE;
726 case LDAP_SCOPE_SUBTREE:
727 if ( tscope < LDAP_SCOPE_SUBTREE )
728 tscope = LDAP_SCOPE_SUBTREE;
729 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
731 case LDAP_SCOPE_CHILDREN:
732 if ( tscope < LDAP_SCOPE_SUBTREE )
733 tscope = LDAP_SCOPE_SUBTREE;
736 if ( !qbptr->scopes[tscope] ) continue;
739 qc = find_filter( op, qbptr->scopes[tscope],
740 query->filter, first );
742 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
743 if (qm->lru_top != qc) {
744 remove_query(qm, qc);
745 add_query_on_top(qm, qc);
747 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
752 if ( be_issuffix( op->o_bd, &qbase.base ))
755 dnParent( &qbase.base, &pdn );
760 "Not answerable: Unlock QC index=%p\n",
762 ldap_pvt_thread_rdwr_runlock(templa->t_rwlock);
768 free_query (CachedQuery* qc)
770 free(qc->q_uuid.bv_val);
771 filter_free(qc->filter);
776 /* Add query to query cache */
777 static void add_query(
780 QueryTemplate *templ,
783 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
786 new_cached_query->qtemp = templ;
788 new_cached_query->q_uuid = *uuid;
789 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
791 BER_BVZERO( &new_cached_query->q_uuid );
792 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
794 new_cached_query->lru_up = NULL;
795 new_cached_query->lru_down = NULL;
796 Debug( pcache_debug, "Added query expires at %ld\n",
797 (long) new_cached_query->expiry_time, 0, 0 );
799 new_cached_query->scope = query->scope;
800 new_cached_query->filter = query->filter;
801 new_cached_query->first = filter_first( query->filter );
803 qb.base = query->base;
806 Debug( pcache_debug, "Lock AQ index = %p\n",
808 ldap_pvt_thread_rdwr_wlock(templ->t_rwlock);
809 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
811 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
812 qbase->base.bv_len =qb.base.bv_len;
813 qbase->base.bv_val = (char *)(qbase+1);
814 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
815 qbase->base.bv_val[qbase->base.bv_len] = '\0';
816 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
818 if (templ->query == NULL)
819 templ->query_last = new_cached_query;
821 templ->query->prev = new_cached_query;
822 new_cached_query->next = templ->query;
823 new_cached_query->prev = NULL;
824 new_cached_query->qbase = qbase;
825 tavl_insert( &qbase->scopes[query->scope], new_cached_query,
826 pcache_filter_cmp, avl_dup_ok );
827 templ->query = new_cached_query;
828 templ->no_of_queries++;
829 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
830 templ, templ->no_of_queries, 0 );
832 Debug( pcache_debug, "Unlock AQ index = %p \n",
834 ldap_pvt_thread_rdwr_wunlock(templ->t_rwlock);
836 /* Adding on top of LRU list */
837 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
838 add_query_on_top(qm, new_cached_query);
839 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
843 remove_from_template (CachedQuery* qc, QueryTemplate* template)
845 if (!qc->prev && !qc->next) {
846 template->query_last = template->query = NULL;
847 } else if (qc->prev == NULL) {
848 qc->next->prev = NULL;
849 template->query = qc->next;
850 } else if (qc->next == NULL) {
851 qc->prev->next = NULL;
852 template->query_last = qc->prev;
854 qc->next->prev = qc->prev;
855 qc->prev->next = qc->next;
857 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
858 if ( qc->qbase->scopes[0] == NULL &&
859 qc->qbase->scopes[1] == NULL &&
860 qc->qbase->scopes[2] == NULL &&
861 qc->qbase->scopes[3] == NULL ) {
862 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
863 ch_free( qc->qbase );
867 template->no_of_queries--;
870 /* remove bottom query of LRU list from the query cache */
871 static void cache_replacement(query_manager* qm, struct berval *result)
876 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
877 bottom = qm->lru_bottom;
879 result->bv_val = NULL;
883 Debug ( pcache_debug,
884 "Cache replacement invoked without "
885 "any query in LRU list\n", 0, 0, 0 );
886 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
890 temp = bottom->qtemp;
891 remove_query(qm, bottom);
892 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
894 *result = bottom->q_uuid;
895 bottom->q_uuid.bv_val = NULL;
897 Debug( pcache_debug, "Lock CR index = %p\n", temp, 0, 0 );
898 ldap_pvt_thread_rdwr_wlock(temp->t_rwlock);
899 remove_from_template(bottom, temp);
900 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
901 temp, temp->no_of_queries, 0 );
902 Debug( pcache_debug, "Unlock CR index = %p\n", temp, 0, 0 );
903 ldap_pvt_thread_rdwr_wunlock(temp->t_rwlock);
908 struct query_info *next;
920 struct query_info *qi;
923 if ( rs->sr_type != REP_SEARCH ) return 0;
925 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
926 if (attr->a_desc == ad_queryid) {
927 for (count=0; attr->a_vals[count].bv_val; count++)
932 if ( count == 0 ) return 0;
933 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
934 qi->next = op->o_callback->sc_private;
935 op->o_callback->sc_private = qi;
936 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
937 qi->del = ( count == 1 );
946 struct berval* query_uuid)
948 struct query_info *qi, *qnext;
950 #ifdef LDAP_COMP_MATCH
951 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
953 AttributeAssertion ava = { NULL, BER_BVNULL };
955 Filter filter = {LDAP_FILTER_EQUALITY};
956 SlapReply sreply = {REP_RESULT};
957 slap_callback cb = { NULL, remove_func, NULL, NULL };
960 sreply.sr_entry = NULL;
961 sreply.sr_nentries = 0;
962 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
963 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
965 filter.f_av_desc = ad_queryid;
966 filter.f_av_value = *query_uuid;
968 op->o_tag = LDAP_REQ_SEARCH;
969 op->o_protocol = LDAP_VERSION3;
970 op->o_callback = &cb;
971 op->o_time = slap_get_time();
972 op->o_do_not_cache = 1;
974 op->o_req_dn = op->o_bd->be_suffix[0];
975 op->o_req_ndn = op->o_bd->be_nsuffix[0];
976 op->ors_scope = LDAP_SCOPE_SUBTREE;
977 op->ors_deref = LDAP_DEREF_NEVER;
978 op->ors_slimit = SLAP_NO_LIMIT;
979 op->ors_tlimit = SLAP_NO_LIMIT;
980 op->ors_filter = &filter;
981 op->ors_filterstr.bv_val = filter_str;
982 op->ors_filterstr.bv_len = strlen(filter_str);
983 op->ors_attrs = NULL;
984 op->ors_attrsonly = 0;
986 op->o_bd->be_search( op, &sreply );
988 for ( qi=cb.sc_private; qi; qi=qnext ) {
991 op->o_req_dn = qi->xdn;
992 op->o_req_ndn = qi->xdn;
995 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
996 query_uuid->bv_val, 0, 0 );
998 op->o_tag = LDAP_REQ_DELETE;
1000 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1005 struct berval vals[2];
1007 vals[0] = *query_uuid;
1008 vals[1].bv_val = NULL;
1010 mod.sml_op = LDAP_MOD_DELETE;
1012 mod.sml_desc = ad_queryid;
1013 mod.sml_type = ad_queryid->ad_cname;
1014 mod.sml_values = vals;
1015 mod.sml_nvalues = NULL;
1016 mod.sml_next = NULL;
1017 Debug( pcache_debug,
1018 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1019 query_uuid->bv_val, 0, 0 );
1021 op->orm_modlist = &mod;
1023 op->o_bd->be_modify( op, &sreply );
1025 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1026 op->o_tmpfree( qi, op->o_tmpmemctx );
1033 AttributeName* attrs,
1042 struct berval *fstr,
1043 AttributeName** filter_attrs,
1045 int* filter_got_oc )
1047 AttributeDescription *ad;
1049 switch ( f->f_choice ) {
1050 case LDAP_FILTER_EQUALITY:
1052 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1053 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1056 case LDAP_FILTER_GE:
1058 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1059 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1062 case LDAP_FILTER_LE:
1064 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1065 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1068 case LDAP_FILTER_APPROX:
1070 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1071 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1074 case LDAP_FILTER_SUBSTRINGS:
1076 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1077 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1080 case LDAP_FILTER_PRESENT:
1082 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1083 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1086 case LDAP_FILTER_AND:
1087 case LDAP_FILTER_OR:
1088 case LDAP_FILTER_NOT: {
1090 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1091 f->f_choice == LDAP_FILTER_AND ? '&' :
1092 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1093 fstr->bv_len += sizeof("(%") - 1;
1095 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1096 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1100 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1101 fstr->bv_len += sizeof(")") - 1;
1107 strcpy( fstr->bv_val, "(?=?)" );
1108 fstr->bv_len += sizeof("(?=?)")-1;
1112 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1113 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1115 (*filter_attrs)[*filter_cnt].an_desc = ad;
1116 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1117 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1118 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1119 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1121 if ( ad == slap_schema.si_ad_objectClass )
1126 struct search_info {
1129 QueryTemplate *qtemp;
1130 AttributeName* save_attrs; /* original attributes, saved for response */
1141 struct berval *query_uuid)
1143 struct search_info *si = op->o_callback->sc_private;
1144 slap_overinst *on = si->on;
1145 cache_manager *cm = on->on_bi.bi_private;
1146 query_manager* qm = cm->qm;
1149 struct berval crp_uuid;
1150 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1151 Operation op_tmp = *op;
1153 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1154 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1156 op_tmp.o_bd = &cm->db;
1157 op_tmp.o_dn = cm->db.be_rootdn;
1158 op_tmp.o_ndn = cm->db.be_rootndn;
1160 Debug( pcache_debug, "UUID for query being added = %s\n",
1163 for ( e=si->head; e; e=si->head ) {
1164 si->head = e->e_private;
1165 e->e_private = NULL;
1166 while ( cm->cur_entries > (cm->max_entries) ) {
1167 qm->crfunc(qm, &crp_uuid);
1168 if (crp_uuid.bv_val) {
1169 Debug( pcache_debug,
1170 "Removing query UUID %s\n",
1171 crp_uuid.bv_val, 0, 0 );
1172 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1173 Debug( pcache_debug,
1174 "QUERY REMOVED, SIZE=%d\n",
1176 ldap_pvt_thread_mutex_lock(
1178 cm->cur_entries -= return_val;
1179 cm->num_cached_queries--;
1180 Debug( pcache_debug,
1181 "STORED QUERIES = %lu\n",
1182 cm->num_cached_queries, 0, 0 );
1183 ldap_pvt_thread_mutex_unlock(
1185 Debug( pcache_debug,
1186 "QUERY REMOVED, CACHE ="
1188 cm->cur_entries, 0, 0 );
1192 return_val = merge_entry(&op_tmp, e, query_uuid);
1193 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1194 cm->cur_entries += return_val;
1195 Debug( pcache_debug,
1196 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1197 cm->cur_entries, 0, 0 );
1199 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1210 struct search_info *si = op->o_callback->sc_private;
1211 slap_overinst *on = si->on;
1212 cache_manager *cm = on->on_bi.bi_private;
1213 query_manager* qm = cm->qm;
1216 if ( si->save_attrs != NULL ) {
1217 rs->sr_attrs = si->save_attrs;
1218 op->ors_attrs = si->save_attrs;
1219 si->save_attrs = NULL;
1222 if ( rs->sr_type == REP_SEARCH ) {
1224 /* If we haven't exceeded the limit for this query,
1225 * build a chain of answers to store. If we hit the
1226 * limit, empty the chain and ignore the rest.
1229 if ( si->count < si->max ) {
1231 e = entry_dup( rs->sr_entry );
1232 if ( !si->head ) si->head = e;
1233 if ( si->tail ) si->tail->e_private = e;
1238 for (;si->head; si->head=e) {
1239 e = si->head->e_private;
1240 si->head->e_private = NULL;
1241 entry_free(si->head);
1247 } else if ( rs->sr_type == REP_RESULT ) {
1248 QueryTemplate* templ = si->qtemp;
1249 if (( si->count && cache_entries( op, rs, &uuid ) == 0 ) ||
1250 ( templ->negttl && !si->count && !si->over &&
1251 rs->sr_err == LDAP_SUCCESS )) {
1252 qm->addfunc(qm, &si->query, si->qtemp,
1253 si->count ? &uuid : NULL);
1255 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1256 cm->num_cached_queries++;
1257 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1258 cm->num_cached_queries, 0, 0 );
1259 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1261 /* If the consistency checker suspended itself,
1264 if ( cm->cc_paused ) {
1265 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1266 if ( cm->cc_paused ) {
1268 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1270 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1273 filter_free( si->query.filter );
1277 op->o_callback->sc_cleanup = slap_freeself_cb;
1279 return SLAP_CB_CONTINUE;
1285 AttributeName** new_attrs,
1286 struct attr_set *attrs,
1287 AttributeName* filter_attrs,
1297 /* duplicate attrs */
1298 count = attrs->count + fattr_cnt;
1299 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1304 *new_attrs = (AttributeName*)ch_malloc((count+1)*
1305 sizeof(AttributeName));
1306 for (i=0; i<attrs->count; i++) {
1307 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1308 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1310 BER_BVZERO( &(*new_attrs)[i].an_name );
1311 alluser = an_find(*new_attrs, &AllUser);
1312 allop = an_find(*new_attrs, &AllOper);
1315 for ( i=0; i<fattr_cnt; i++ ) {
1316 if ( an_find(*new_attrs, &filter_attrs[i].an_name ))
1318 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1323 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1324 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1325 (*new_attrs)[j].an_oc = NULL;
1326 (*new_attrs)[j].an_oc_exclude = 0;
1330 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1331 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1332 (*new_attrs)[j].an_oc = NULL;
1333 (*new_attrs)[j].an_oc_exclude = 0;
1336 BER_BVZERO( &(*new_attrs)[j].an_name );
1339 /* NOTE: this is a quick workaround to let pcache minimally interact
1340 * with pagedResults. A more articulated solutions would be to
1341 * perform the remote query without control and cache all results,
1342 * performing the pagedResults search only within the client
1343 * and the proxy. This requires pcache to understand pagedResults. */
1345 pcache_chk_controls(
1349 const char *non = "";
1350 const char *stripped = "";
1352 switch( op->o_pagedresults ) {
1353 case SLAP_CONTROL_NONCRITICAL:
1355 stripped = "; stripped";
1358 case SLAP_CONTROL_CRITICAL:
1359 Debug( pcache_debug, "%s: "
1360 "%scritical pagedResults control "
1361 "disabled with proxy cache%s.\n",
1362 op->o_log_prefix, non, stripped );
1364 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1368 rs->sr_err = SLAP_CB_CONTINUE;
1380 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1381 cache_manager *cm = on->on_bi.bi_private;
1382 query_manager* qm = cm->qm;
1386 AttributeName *filter_attrs = NULL;
1389 QueryTemplate *qtemp = NULL;
1392 CachedQuery *answerable = NULL;
1395 int fattr_got_oc = 0;
1397 struct berval tempstr;
1399 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1401 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1402 &fattr_cnt, &fattr_got_oc )) {
1403 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1404 return SLAP_CB_CONTINUE;
1407 Debug( pcache_debug, "query template of incoming query = %s\n",
1408 tempstr.bv_val, 0, 0 );
1410 /* FIXME: cannot cache/answer requests with pagedResults control */
1413 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1415 query.filter = op->ors_filter;
1416 query.base = op->o_req_ndn;
1417 query.scope = op->ors_scope;
1419 /* check for query containment */
1420 if (attr_set > -1) {
1421 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1422 for (; qt; qt = qt->qtnext ) {
1423 /* find if template i can potentially answer tempstr */
1424 if (qt->querystr.bv_len != tempstr.bv_len ||
1425 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1429 Debug( LDAP_DEBUG_NONE, "Entering QC, querystr = %s\n",
1430 op->ors_filterstr.bv_val, 0, 0 );
1431 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1437 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1440 /* Need to clear the callbacks of the original operation,
1441 * in case there are other overlays */
1442 BackendDB *save_bd = op->o_bd;
1443 slap_callback *save_cb = op->o_callback;
1445 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1446 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1447 ldap_pvt_thread_rdwr_runlock(qtemp->t_rwlock);
1448 if ( BER_BVISNULL( &answerable->q_uuid )) {
1449 /* No entries cached, just an empty result set */
1451 send_ldap_result( op, rs );
1454 op->o_callback = NULL;
1455 i = cm->db.bd_info->bi_op_search( op, rs );
1458 op->o_callback = save_cb;
1462 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1464 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1465 if (cm->num_cached_queries >= cm->max_queries) {
1468 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1470 if (op->ors_attrsonly)
1475 struct search_info *si;
1477 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1478 query.filter = filter_dup(op->ors_filter, NULL);
1479 ldap_pvt_thread_rdwr_wlock(qtemp->t_rwlock);
1480 if ( !qtemp->t_attrs.count ) {
1481 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1482 &qm->attr_sets[attr_set],
1483 filter_attrs, fattr_cnt, fattr_got_oc);
1485 ldap_pvt_thread_rdwr_wunlock(qtemp->t_rwlock);
1487 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx);
1488 cb->sc_response = pcache_response;
1489 cb->sc_cleanup = NULL;
1490 cb->sc_private = (cb+1);
1491 si = cb->sc_private;
1495 si->max = cm->num_entries_limit ;
1500 si->save_attrs = op->ors_attrs;
1502 op->ors_attrs = qtemp->t_attrs.attrs;
1504 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1505 cb->sc_next = op->o_callback;
1506 op->o_callback = cb;
1509 slap_callback **pcb;
1511 /* need to move the callback at the end, in case other
1512 * overlays are present, so that the final entry is
1513 * actually cached */
1515 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1520 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1524 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1526 return SLAP_CB_CONTINUE;
1531 AttributeName* attrs,
1539 for ( ; attrs[count].an_name.bv_val; count++ );
1542 for (i=0; i<num; i++) {
1546 if ( count > qm->attr_sets[i].count )
1549 if ( !qm->attr_sets[i].count )
1553 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1554 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name )) {
1572 struct re_s *rtask = arg;
1573 slap_overinst *on = rtask->arg;
1574 cache_manager *cm = on->on_bi.bi_private;
1575 query_manager *qm = cm->qm;
1576 Connection conn = {0};
1577 OperationBuffer opbuf;
1580 SlapReply rs = {REP_RESULT};
1581 CachedQuery* query, *query_prev;
1582 int i, return_val, pause = 1;
1583 QueryTemplate* templ;
1585 op = (Operation *) &opbuf;
1586 connection_fake_init( &conn, op, ctx );
1589 op->o_dn = cm->db.be_rootdn;
1590 op->o_ndn = cm->db.be_rootndn;
1594 for (templ = qm->templates; templ; templ=templ->qmnext) {
1595 query = templ->query_last;
1596 if ( query ) pause = 0;
1597 op->o_time = slap_get_time();
1598 while (query && (query->expiry_time < op->o_time)) {
1599 Debug( pcache_debug, "Lock CR index = %d\n",
1601 ldap_pvt_thread_rdwr_wlock(templ->t_rwlock);
1602 remove_from_template(query, templ);
1603 Debug( pcache_debug, "TEMPLATE %d QUERIES-- %d\n",
1604 i, templ->no_of_queries, 0 );
1605 Debug( pcache_debug, "Unlock CR index = %d\n",
1607 ldap_pvt_thread_rdwr_wunlock(templ->t_rwlock);
1608 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1609 remove_query(qm, query);
1610 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1611 if ( BER_BVISNULL( &query->q_uuid ))
1614 return_val = remove_query_data(op, &rs, &query->q_uuid);
1615 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1617 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1618 cm->cur_entries -= return_val;
1619 cm->num_cached_queries--;
1620 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1621 cm->num_cached_queries, 0, 0 );
1622 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1623 Debug( pcache_debug,
1624 "STALE QUERY REMOVED, CACHE ="
1626 cm->cur_entries, 0, 0 );
1628 query = query->prev;
1629 free_query(query_prev);
1632 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1633 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1634 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1636 /* If there were no queries, defer processing for a while */
1637 cm->cc_paused = pause;
1638 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
1640 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1645 #define MAX_ATTR_SETS 500
1655 static ConfigDriver pc_cf_gen;
1656 static ConfigLDAPadd pc_ldadd;
1657 static ConfigCfAdd pc_cfadd;
1659 static ConfigTable pccfg[] = {
1660 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
1662 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
1663 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
1664 "DESC 'ProxyCache basic parameters' "
1665 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
1666 { "proxyattrset", "index> <attributes...",
1667 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
1668 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
1669 "DESC 'A set of attributes to cache' "
1670 "SYNTAX OMsDirectoryString )", NULL, NULL },
1671 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
1672 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
1673 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
1674 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
1675 "SYNTAX OMsDirectoryString )", NULL, NULL },
1676 { "response-callback", "head|tail(default)",
1677 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
1678 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
1679 "DESC 'Response callback position in overlay stack' "
1680 "SYNTAX OMsDirectoryString )", NULL, NULL },
1681 { "proxyCacheQueries", "queries",
1682 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
1683 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
1684 "DESC 'Maximum number of queries to cache' "
1685 "SYNTAX OMsInteger )", NULL, NULL },
1687 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
1690 static ConfigOCs pcocs[] = {
1691 { "( OLcfgOvOc:2.1 "
1692 "NAME 'olcPcacheConfig' "
1693 "DESC 'ProxyCache configuration' "
1694 "SUP olcOverlayConfig "
1695 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
1696 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries ) )", Cft_Overlay, pccfg, NULL, pc_cfadd },
1697 { "( OLcfgOvOc:2.2 "
1698 "NAME 'olcPcacheDatabase' "
1699 "DESC 'Cache database configuration' "
1700 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
1705 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
1710 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
1711 p->ce_bi->bi_cf_ocs != pcocs )
1712 return LDAP_CONSTRAINT_VIOLATION;
1714 on = (slap_overinst *)p->ce_bi;
1715 cm = on->on_bi.bi_private;
1717 return LDAP_SUCCESS;
1721 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
1723 CfEntryInfo *pe = p->e_private;
1724 slap_overinst *on = (slap_overinst *)pe->ce_bi;
1725 cache_manager *cm = on->on_bi.bi_private;
1728 /* FIXME: should not hardcode "olcDatabase" here */
1729 bv.bv_len = sprintf( ca->msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
1730 bv.bv_val = ca->msg;
1733 /* We can only create this entry if the database is table-driven
1735 if ( cm->db.bd_info->bi_cf_ocs )
1736 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
1743 pc_cf_gen( ConfigArgs *c )
1745 slap_overinst *on = (slap_overinst *)c->bi;
1746 cache_manager* cm = on->on_bi.bi_private;
1747 query_manager* qm = cm->qm;
1748 QueryTemplate* temp;
1749 AttributeName* attr_name;
1750 AttributeName* attrarray;
1751 const char* text=NULL;
1756 if ( c->op == SLAP_CONFIG_EMIT ) {
1760 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%s %d %d %d %ld",
1761 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
1762 cm->num_entries_limit, cm->cc_period );
1764 value_add_one( &c->rvalue_vals, &bv );
1767 for (i=0; i<cm->numattrsets; i++) {
1768 if ( !qm->attr_sets[i].count ) continue;
1770 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), "%d", i );
1772 /* count the attr length */
1773 for ( attr_name = qm->attr_sets[i].attrs;
1774 attr_name->an_name.bv_val; attr_name++ )
1775 bv.bv_len += attr_name->an_name.bv_len + 1;
1777 bv.bv_val = ch_malloc( bv.bv_len+1 );
1778 ptr = lutil_strcopy( bv.bv_val, c->msg );
1779 for ( attr_name = qm->attr_sets[i].attrs;
1780 attr_name->an_name.bv_val; attr_name++ ) {
1782 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
1784 ber_bvarray_add( &c->rvalue_vals, &bv );
1786 if ( !c->rvalue_vals )
1790 for (temp=qm->templates; temp; temp=temp->qmnext) {
1791 if ( temp->negttl ) {
1792 bv.bv_len = snprintf( c->msg, sizeof( c->msg ),
1794 temp->attr_set_index,
1798 bv.bv_len = snprintf( c->msg, sizeof( c->msg ), " %d %ld",
1799 temp->attr_set_index,
1802 bv.bv_len += temp->querystr.bv_len + 2;
1803 bv.bv_val = ch_malloc( bv.bv_len+1 );
1806 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
1808 strcpy( ptr, c->msg );
1809 ber_bvarray_add( &c->rvalue_vals, &bv );
1811 if ( !c->rvalue_vals )
1815 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1816 BER_BVSTR( &bv, "head" );
1818 BER_BVSTR( &bv, "tail" );
1820 value_add_one( &c->rvalue_vals, &bv );
1823 c->value_int = cm->max_queries;
1827 } else if ( c->op == LDAP_MOD_DELETE ) {
1828 return 1; /* FIXME */
1840 if ( cm->numattrsets > 0 ) {
1841 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive already provided" );
1842 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1846 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
1847 snprintf( c->msg, sizeof( c->msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
1849 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1852 if ( cm->numattrsets <= 0 ) {
1853 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be positive" );
1854 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1857 if ( cm->numattrsets > MAX_ATTR_SETS ) {
1858 snprintf( c->msg, sizeof( c->msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
1859 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1863 if ( !backend_db_init( c->argv[1], &cm->db )) {
1864 snprintf( c->msg, sizeof( c->msg ), "unknown backend type (arg #1)" );
1865 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1869 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
1870 snprintf( c->msg, sizeof( c->msg ), "unable to parse max entries=\"%s\" (arg #2)",
1872 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1875 if ( cm->max_entries <= 0 ) {
1876 snprintf( c->msg, sizeof( c->msg ), "max entries (arg #2) must be positive.\n" );
1877 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
1881 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
1882 snprintf( c->msg, sizeof( c->msg ), "unable to parse entry limit=\"%s\" (arg #4)",
1884 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1887 if ( cm->num_entries_limit <= 0 ) {
1888 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be positive" );
1889 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1892 if ( cm->num_entries_limit > cm->max_entries ) {
1893 snprintf( c->msg, sizeof( c->msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
1894 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1898 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
1899 snprintf( c->msg, sizeof( c->msg ), "unable to parse period=\"%s\" (arg #5)",
1901 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1904 cm->cc_period = (time_t)t;
1905 Debug( pcache_debug,
1906 "Total # of attribute sets to be cached = %d.\n",
1907 cm->numattrsets, 0, 0 );
1908 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
1909 sizeof( struct attr_set ) );
1912 if ( cm->numattrsets == 0 ) {
1913 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1914 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1917 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
1918 snprintf( c->msg, sizeof( c->msg ), "unable to parse attrset #=\"%s\"",
1920 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1924 if ( num < 0 || num >= cm->numattrsets ) {
1925 snprintf( c->msg, sizeof( c->msg ), "attrset index %d out of bounds (must be %s%d)",
1926 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1927 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1930 qm->attr_sets[num].flags |= PC_CONFIGURED;
1931 if ( c->argc > 2 && strcmp( c->argv[2], "*" ) ) {
1932 qm->attr_sets[num].count = c->argc - 2;
1933 qm->attr_sets[num].attrs = (AttributeName*)ch_malloc(
1934 (c->argc-1) * sizeof( AttributeName ));
1935 attr_name = qm->attr_sets[num].attrs;
1936 for ( i = 2; i < c->argc; i++ ) {
1937 attr_name->an_desc = NULL;
1938 if ( slap_str2ad( c->argv[i],
1939 &attr_name->an_desc, &text ) )
1941 strcpy( c->msg, text );
1942 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1943 ch_free( qm->attr_sets[num].attrs );
1944 qm->attr_sets[num].attrs = NULL;
1945 qm->attr_sets[num].count = 0;
1948 attr_name->an_name = attr_name->an_desc->ad_cname;
1949 attr_name->an_oc = NULL;
1950 attr_name->an_oc_exclude = 0;
1951 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
1952 qm->attr_sets[num].flags |= PC_GOT_OC;
1954 BER_BVZERO( &attr_name->an_name );
1959 if ( cm->numattrsets == 0 ) {
1960 snprintf( c->msg, sizeof( c->msg ), "\"proxycache\" directive not provided yet" );
1961 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1964 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
1965 snprintf( c->msg, sizeof( c->msg ), "unable to parse template #=\"%s\"",
1967 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1971 if ( i < 0 || i >= cm->numattrsets ||
1972 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
1973 snprintf( c->msg, sizeof( c->msg ), "template index %d invalid (%s%d)",
1974 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
1975 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1978 temp = ch_calloc( 1, sizeof( QueryTemplate ));
1979 temp->qmnext = qm->templates;
1980 qm->templates = temp;
1981 temp->t_rwlock = ch_malloc( sizeof( ldap_pvt_thread_rdwr_t ) );
1982 ldap_pvt_thread_rdwr_init( temp->t_rwlock );
1983 temp->query = temp->query_last = NULL;
1984 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
1985 snprintf( c->msg, sizeof( c->msg ), "unable to parse template ttl=\"%s\"",
1987 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1990 temp->ttl = (time_t)t;
1991 if ( c->argc == 5 ) {
1992 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
1993 snprintf( c->msg, sizeof( c->msg ),
1994 "unable to parse template negttl=\"%s\"",
1996 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
1999 temp->negttl = (time_t)t;
2004 temp->no_of_queries = 0;
2006 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2007 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2008 Debug( pcache_debug, " query template: %s\n",
2009 temp->querystr.bv_val, 0, 0 );
2010 temp->attr_set_index = i;
2011 qm->attr_sets[i].flags |= PC_REFERENCED;
2012 temp->qtnext = qm->attr_sets[i].templates;
2013 qm->attr_sets[i].templates = temp;
2014 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2015 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2016 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2017 Debug( pcache_debug, "\t%s\n",
2018 attrarray[i].an_name.bv_val, 0, 0 );
2021 temp->querystr.bv_val = NULL;
2024 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2025 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2027 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2028 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2031 snprintf( c->msg, sizeof( c->msg ), "unknown specifier" );
2032 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2037 if ( c->value_int <= 0 ) {
2038 snprintf( c->msg, sizeof( c->msg ), "max queries must be positive" );
2039 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->msg, 0 );
2042 cm->max_queries = c->value_int;
2057 slap_overinst *on = (slap_overinst *)be->bd_info;
2058 cache_manager* cm = on->on_bi.bi_private;
2060 /* Something for the cache database? */
2061 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2062 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2064 return SLAP_CONF_UNKNOWN;
2072 slap_overinst *on = (slap_overinst *)be->bd_info;
2076 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2077 on->on_bi.bi_private = cm;
2079 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2082 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2083 cm->db.be_private = NULL;
2084 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2086 cm->numattrsets = 0;
2087 cm->num_entries_limit = 5;
2088 cm->num_cached_queries = 0;
2089 cm->max_entries = 0;
2090 cm->cur_entries = 0;
2091 cm->max_queries = 10000;
2092 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2093 cm->cc_period = 1000;
2096 qm->attr_sets = NULL;
2097 qm->templates = NULL;
2099 qm->lru_bottom = NULL;
2101 qm->qcfunc = query_containment;
2102 qm->crfunc = cache_replacement;
2103 qm->addfunc = add_query;
2104 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2106 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2115 slap_overinst *on = (slap_overinst *)be->bd_info;
2116 cache_manager *cm = on->on_bi.bi_private;
2117 query_manager* qm = cm->qm;
2118 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2120 /* check attr sets */
2121 for ( i = 0; i < cm->numattrsets; i++) {
2122 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2123 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2124 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2128 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2132 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2133 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2138 if ( ncf || rf || nrf ) {
2139 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2140 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2141 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2148 /* need to inherit something from the original database... */
2149 cm->db.be_def_limit = be->be_def_limit;
2150 cm->db.be_limits = be->be_limits;
2151 cm->db.be_acl = be->be_acl;
2152 cm->db.be_dfltaccess = be->be_dfltaccess;
2154 rc = backend_startup_one( &cm->db );
2156 /* There is no runqueue in TOOL mode */
2157 if ( slapMode & SLAP_SERVER_MODE ) {
2158 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2159 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2160 consistency_check, on,
2161 "pcache_consistency", be->be_suffix[0].bv_val );
2162 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2164 /* Cached database must have the rootdn */
2165 if ( BER_BVISNULL( &cm->db.be_rootndn )
2166 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2168 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2169 "underlying database of type \"%s\"\n"
2170 " serving naming context \"%s\"\n"
2171 " has no \"rootdn\", required by \"proxycache\".\n",
2172 on->on_info->oi_orig->bi_type,
2173 cm->db.be_suffix[0].bv_val, 0 );
2182 pcache_free_qbase( void *v )
2188 tavl_free( qb->scopes[i], NULL );
2197 slap_overinst *on = (slap_overinst *)be->bd_info;
2198 cache_manager *cm = on->on_bi.bi_private;
2199 query_manager *qm = cm->qm;
2203 /* cleanup stuff inherited from the original database... */
2204 cm->db.be_limits = NULL;
2205 cm->db.be_acl = NULL;
2207 if ( cm->db.bd_info->bi_db_close ) {
2208 rc = cm->db.bd_info->bi_db_close( &cm->db );
2210 while ( tm = qm->templates ) {
2211 CachedQuery *qc, *qn;
2212 qm->templates = tm->qmnext;
2213 for ( qc = tm->query; qc; qc = qn ) {
2217 avl_free( tm->qbase, pcache_free_qbase );
2218 free( tm->querystr.bv_val );
2219 ldap_pvt_thread_rdwr_destroy( tm->t_rwlock );
2220 ch_free( tm->t_rwlock );
2221 free( tm->t_attrs.attrs );
2225 for ( i=0; i<cm->numattrsets; i++ ) {
2226 free( qm->attr_sets[i].attrs );
2228 free( qm->attr_sets );
2229 qm->attr_sets = NULL;
2239 slap_overinst *on = (slap_overinst *)be->bd_info;
2240 cache_manager *cm = on->on_bi.bi_private;
2241 query_manager *qm = cm->qm;
2243 /* cleanup stuff inherited from the original database... */
2244 cm->db.be_suffix = NULL;
2245 cm->db.be_nsuffix = NULL;
2246 BER_BVZERO( &cm->db.be_rootdn );
2247 BER_BVZERO( &cm->db.be_rootndn );
2248 BER_BVZERO( &cm->db.be_rootpw );
2249 /* FIXME: there might be more... */
2251 if ( cm->db.be_private != NULL ) {
2252 backend_destroy_one( &cm->db, 0 );
2255 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2256 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2263 static slap_overinst pcache;
2265 static char *obsolete_names[] = {
2270 int pcache_initialize()
2272 LDAPAttributeType *at;
2275 struct berval debugbv = BER_BVC("pcache");
2277 if (( code = slap_loglevel_get( &debugbv, &pcache_debug )))
2280 at = ldap_str2attributetype( queryid_schema, &code, &err,
2281 LDAP_SCHEMA_ALLOW_ALL );
2283 Debug( LDAP_DEBUG_ANY,
2284 "pcache_initialize: ldap_str2attributetype failed %s %s\n",
2285 ldap_scherr2str(code), err, 0 );
2288 code = at_add( at, 0, NULL, &err );
2290 slap_str2ad( at->at_names[0], &ad_queryid, &err );
2294 Debug( LDAP_DEBUG_ANY,
2295 "pcache_initialize: at_add failed %s %s\n",
2296 scherr2str(code), err, 0 );
2300 pcache.on_bi.bi_type = "pcache";
2301 pcache.on_bi.bi_obsolete_names = obsolete_names;
2302 pcache.on_bi.bi_db_init = pcache_db_init;
2303 pcache.on_bi.bi_db_config = pcache_db_config;
2304 pcache.on_bi.bi_db_open = pcache_db_open;
2305 pcache.on_bi.bi_db_close = pcache_db_close;
2306 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2308 pcache.on_bi.bi_op_search = pcache_op_search;
2310 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2312 pcache.on_bi.bi_cf_ocs = pcocs;
2314 code = config_register_schema( pccfg, pcocs );
2315 if ( code ) return code;
2317 return overlay_register( &pcache );
2320 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2321 int init_module(int argc, char *argv[]) {
2322 return pcache_initialize();
2326 #endif /* defined(SLAPD_OVER_PROXYCACHE) */