2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 2003-2007 The OpenLDAP Foundation.
5 * Portions Copyright 2003 IBM Corporation.
6 * Portions Copyright 2003 Symas Corporation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted only as authorized by the OpenLDAP
13 * A copy of this license is available in the file LICENSE in the
14 * top-level directory of the distribution or, alternatively, at
15 * <http://www.OpenLDAP.org/license.html>.
18 * This work was initially developed by Apurva Kumar for inclusion
19 * in OpenLDAP Software and subsequently rewritten by Howard Chu.
24 #ifdef SLAPD_OVER_PROXYCACHE
28 #include <ac/string.h>
38 /* query cache structs */
41 typedef struct Query_s {
42 Filter* filter; /* Search Filter */
43 struct berval base; /* Search Base */
44 int scope; /* Search scope */
47 struct query_template_s;
49 typedef struct Qbase_s {
50 Avlnode *scopes[4]; /* threaded AVL trees of cached queries */
55 /* struct representing a cached query */
56 typedef struct cached_query_s {
61 struct berval q_uuid; /* query identifier */
62 struct query_template_s *qtemp; /* template of the query */
63 time_t expiry_time; /* time till the query is considered valid */
64 struct cached_query_s *next; /* next query in the template */
65 struct cached_query_s *prev; /* previous query in the template */
66 struct cached_query_s *lru_up; /* previous query in the LRU list */
67 struct cached_query_s *lru_down; /* next query in the LRU list */
73 * ldap:///<base>??<scope>?<filter>?x-uuid=<uid>,x-template=<template>,x-attrset=<attrset>,x-expiry=<expiry>
75 * <base> ::= CachedQuery.qbase->base
76 * <scope> ::= CachedQuery.scope
77 * <filter> ::= filter2bv(CachedQuery.filter)
78 * <uuid> ::= CachedQuery.q_uuid
79 * <template> ::= CachedQuery.qtemp->querystr [FIXME: better give it an ID?]
80 * <attrset> ::= CachedQuery.qtemp->attr_set_index [FIXME: better give it an ID?]
81 * <expiry> ::= CachedQuery.expiry_time
83 * quick hack: parse URI, call add_query() and then fix
84 * CachedQuery.expiry_time and CachedQuery.q_uuid
88 * Represents a set of projected attributes.
92 struct query_template_s *templates;
93 AttributeName* attrs; /* specifies the set */
95 #define PC_CONFIGURED (0x1)
96 #define PC_REFERENCED (0x2)
97 #define PC_GOT_OC (0x4)
98 int count; /* number of attributes */
101 /* struct representing a query template
102 * e.g. template string = &(cn=)(mail=)
104 typedef struct query_template_s {
105 struct query_template_s *qtnext;
106 struct query_template_s *qmnext;
109 CachedQuery* query; /* most recent query cached for the template */
110 CachedQuery* query_last; /* oldest query cached for the template */
111 ldap_pvt_thread_rdwr_t t_rwlock; /* Rd/wr lock for accessing queries in the template */
112 struct berval querystr; /* Filter string corresponding to the QT */
114 int attr_set_index; /* determines the projected attributes */
115 int no_of_queries; /* Total number of queries in the template */
116 time_t ttl; /* TTL for the queries of this template */
117 time_t negttl; /* TTL for negative results */
118 struct attr_set t_attrs; /* filter attrs + attr_set */
121 struct query_manager_s;
123 /* prototypes for functions for 1) query containment
124 * 2) query addition, 3) cache replacement
126 typedef CachedQuery * (QCfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*);
127 typedef CachedQuery * (AddQueryfunc)(Operation *op, struct query_manager_s*, Query*, QueryTemplate*, int positive);
128 typedef void (CRfunc)(struct query_manager_s*, struct berval * );
130 /* LDAP query cache */
131 typedef struct query_manager_s {
132 struct attr_set* attr_sets; /* possible sets of projected attributes */
133 QueryTemplate* templates; /* cacheable templates */
135 CachedQuery* lru_top; /* top and bottom of LRU list */
136 CachedQuery* lru_bottom;
138 ldap_pvt_thread_mutex_t lru_mutex; /* mutex for accessing LRU list */
140 /* Query cache methods */
141 QCfunc *qcfunc; /* Query containment*/
142 CRfunc *crfunc; /* cache replacement */
143 AddQueryfunc *addfunc; /* add query */
146 /* LDAP query cache manager */
147 typedef struct cache_manager_s {
148 BackendDB db; /* underlying database */
149 unsigned long num_cached_queries; /* total number of cached queries */
150 unsigned long max_queries; /* upper bound on # of cached queries */
151 int save_queries; /* save cached queries across restarts */
152 int numattrsets; /* number of attribute sets */
153 int cur_entries; /* current number of entries cached */
154 int max_entries; /* max number of entries cached */
155 int num_entries_limit; /* max # of entries in a cacheable query */
157 char response_cb; /* install the response callback
158 * at the tail of the callback list */
159 #define PCACHE_RESPONSE_CB_HEAD 0
160 #define PCACHE_RESPONSE_CB_TAIL 1
162 time_t cc_period; /* interval between successive consistency checks (sec) */
166 ldap_pvt_thread_mutex_t cache_mutex;
168 query_manager* qm; /* query cache managed by the cache manager */
171 static int pcache_debug;
173 static AttributeDescription *ad_queryid, *ad_cachedQueryURL;
176 AttributeDescription **adp;
178 { "( 1.3.6.1.4.1.4203.666.1.12 NAME 'queryid' "
179 "DESC 'list of queries the entry belongs to' "
180 "EQUALITY octetStringMatch "
181 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{64} "
182 "NO-USER-MODIFICATION USAGE directoryOperation )",
184 { "(1.3.6.1.4.1.4203.666.1.999999 NAME 'cachedQueryURL' "
185 "DESC 'URI describing a cached query' "
186 "EQUALITY caseExactMatch "
187 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
188 "NO-USER-MODIFICATION USAGE directoryOperation )",
189 &ad_cachedQueryURL },
198 AttributeName** filter_attrs,
200 int* filter_got_oc );
207 QueryTemplate *templ,
211 * Turn a cached query into its URL representation
214 query2url( CachedQuery *q, struct berval *urlbv )
216 struct berval bv_scope,
218 char attrset_buf[ 32 ],
221 ber_len_t attrset_len,
224 ldap_pvt_scope2bv( q->scope, &bv_scope );
225 filter2bv( q->filter, &bv_filter );
226 attrset_len = snprintf( attrset_buf, sizeof( attrset_buf ),
227 "%lu", (unsigned long)q->qtemp->attr_set_index );
228 expiry_len = snprintf( expiry_buf, sizeof( expiry_buf ),
229 "%lu", (unsigned long)q->expiry_time );
231 urlbv->bv_len = STRLENOF( "ldap:///" )
232 + q->qbase->base.bv_len
237 + STRLENOF( "?x-uuid=" )
239 + STRLENOF( ",x-attrset=" )
241 + STRLENOF( ",x-expiry=" )
243 ptr = urlbv->bv_val = ch_malloc( urlbv->bv_len + 1 );
244 ptr = lutil_strcopy( ptr, "ldap:///" );
245 ptr = lutil_strcopy( ptr, q->qbase->base.bv_val );
246 ptr = lutil_strcopy( ptr, "??" );
247 ptr = lutil_strcopy( ptr, bv_scope.bv_val );
248 ptr = lutil_strcopy( ptr, "?" );
249 ptr = lutil_strcopy( ptr, bv_filter.bv_val );
250 ptr = lutil_strcopy( ptr, "?x-uuid=" );
251 ptr = lutil_strcopy( ptr, q->q_uuid.bv_val );
252 ptr = lutil_strcopy( ptr, ",x-attrset=" );
253 ptr = lutil_strcopy( ptr, attrset_buf );
254 ptr = lutil_strcopy( ptr, ",x-expiry=" );
255 ptr = lutil_strcopy( ptr, expiry_buf );
257 ber_memfree( bv_filter.bv_val );
263 * Turn an URL representing a formerly cached query into a cached query,
264 * and try to cache it
275 LDAPURLDesc *lud = NULL;
277 tempstr = BER_BVNULL,
287 rc = ldap_url_parse( url, &lud );
288 if ( rc != LDAP_URL_SUCCESS ) {
292 /* non-allowed fields */
293 if ( lud->lud_host != NULL ) {
298 if ( lud->lud_attrs != NULL ) {
304 if ( strcmp( lud->lud_scheme, "ldap" ) != 0 ) {
309 /* required fields */
310 if ( lud->lud_dn == NULL || lud->lud_dn[ 0 ] == '\0' ) {
315 switch ( lud->lud_scope ) {
316 case LDAP_SCOPE_BASE:
317 case LDAP_SCOPE_ONELEVEL:
318 case LDAP_SCOPE_SUBTREE:
319 case LDAP_SCOPE_SUBORDINATE:
327 if ( lud->lud_filter == NULL || lud->lud_filter[ 0 ] == '\0' ) {
332 if ( lud->lud_exts == NULL ) {
337 for ( i = 0; lud->lud_exts[ i ] != NULL; i++ ) {
338 if ( strncmp( lud->lud_exts[ i ], "x-uuid=", STRLENOF( "x-uuid=" ) ) == 0 ) {
339 ber_str2bv( &lud->lud_exts[ i ][ STRLENOF( "x-uuid=" ) ], 0, 0, &uuid );
345 } else if ( strncmp( lud->lud_exts[ i ], "x-attrset=", STRLENOF( "x-attrset=" ) ) == 0 ) {
346 rc = lutil_atoi( &attrset, &lud->lud_exts[ i ][ STRLENOF( "x-attrset=" ) ] );
352 } else if ( strncmp( lud->lud_exts[ i ], "x-expiry=", STRLENOF( "x-expiry=" ) ) == 0 ) {
355 rc = lutil_atoul( &l, &lud->lud_exts[ i ][ STRLENOF( "x-expiry=" ) ] );
359 expiry_time = (time_t)l;
362 /* ignore expired queries */
363 if ( expiry_time <= slap_get_time()) {
379 if ( !got_attrset ) {
389 ber_str2bv( lud->lud_dn, 0, 0, &base );
390 rc = dnNormalize( 0, NULL, NULL, &base, &query.base, NULL );
391 if ( rc != LDAP_SUCCESS ) {
394 query.scope = lud->lud_scope;
395 query.filter = str2filter( lud->lud_filter );
397 tempstr.bv_val = ch_malloc( strlen( lud->lud_filter ) + 1 );
399 if ( filter2template( op, query.filter, &tempstr, NULL, NULL, NULL ) ) {
400 ch_free( tempstr.bv_val );
405 /* check for query containment */
406 qt = qm->attr_sets[attrset].templates;
407 for ( ; qt; qt = qt->qtnext ) {
408 /* find if template i can potentially answer tempstr */
409 if ( bvmatch( &qt->querystr, &tempstr ) ) {
420 cq = add_query( op, qm, &query, qt, 1 );
422 cq->expiry_time = expiry_time;
423 ber_dupbv( &cq->q_uuid, &uuid );
424 /* it's now into cq->filter */
432 if ( query.filter != NULL ) filter_free( query.filter );
433 if ( !BER_BVISNULL( &tempstr ) ) ch_free( tempstr.bv_val );
434 if ( !BER_BVISNULL( &query.base ) ) ch_free( query.base.bv_val );
435 if ( lud != NULL ) ldap_free_urldesc( lud );
440 /* Return 1 for an added entry, else 0 */
445 struct berval* query_uuid )
448 Modifications* modlist = NULL;
449 const char* text = NULL;
451 char textbuf[SLAP_TEXT_BUFLEN];
452 size_t textlen = sizeof(textbuf);
454 SlapReply sreply = {REP_RESULT};
456 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
461 /* add queryid attribute */
462 attr_merge_one( e, ad_queryid, query_uuid, NULL );
464 /* append the attribute list from the fetched entry */
465 e->e_attrs->a_next = attr;
467 op->o_tag = LDAP_REQ_ADD;
468 op->o_protocol = LDAP_VERSION3;
469 op->o_callback = &cb;
470 op->o_time = slap_get_time();
471 op->o_do_not_cache = 1;
474 op->o_req_dn = e->e_name;
475 op->o_req_ndn = e->e_nname;
476 rc = op->o_bd->be_add( op, &sreply );
478 if ( rc != LDAP_SUCCESS ) {
479 if ( rc == LDAP_ALREADY_EXISTS ) {
480 slap_entry2mods( e, &modlist, &text, textbuf, textlen );
481 modlist->sml_op = LDAP_MOD_ADD;
482 op->o_tag = LDAP_REQ_MODIFY;
483 op->orm_modlist = modlist;
484 op->o_bd->be_modify( op, &sreply );
485 slap_mods_free( modlist, 1 );
486 } else if ( rc == LDAP_REFERRAL ||
487 rc == LDAP_NO_SUCH_OBJECT ) {
488 syncrepl_add_glue( op, e );
497 if ( op->ora_e == e )
498 be_entry_release_w( op, e );
505 /* Length-ordered sort on normalized DNs */
506 static int pcache_dn_cmp( const void *v1, const void *v2 )
508 const Qbase *q1 = v1, *q2 = v2;
510 int rc = q1->base.bv_len - q2->base.bv_len;
512 rc = strncmp( q1->base.bv_val, q2->base.bv_val, q1->base.bv_len );
516 static int lex_bvcmp( struct berval *bv1, struct berval *bv2 )
519 dif = bv1->bv_len - bv2->bv_len;
521 if ( dif > 0 ) len -= dif;
522 len = memcmp( bv1->bv_val, bv2->bv_val, len );
528 /* compare the first value in each filter */
529 static int pcache_filter_cmp( const void *v1, const void *v2 )
531 const CachedQuery *q1 = v1, *q2 =v2;
532 int rc, weight1, weight2;
534 switch( q1->first->f_choice ) {
535 case LDAP_FILTER_PRESENT:
538 case LDAP_FILTER_EQUALITY:
546 switch( q2->first->f_choice ) {
547 case LDAP_FILTER_PRESENT:
550 case LDAP_FILTER_EQUALITY:
558 rc = weight1 - weight2;
563 rc = lex_bvcmp( &q1->first->f_av_value, &q2->first->f_av_value );
566 if ( q1->first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
568 if ( !BER_BVISNULL( &q1->first->f_sub_initial )) {
569 if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
570 rc = lex_bvcmp( &q1->first->f_sub_initial,
571 &q2->first->f_sub_initial );
575 } else if ( !BER_BVISNULL( &q2->first->f_sub_initial )) {
579 if ( q1->first->f_sub_any ) {
580 if ( q2->first->f_sub_any ) {
581 rc = lex_bvcmp( q1->first->f_sub_any,
582 q2->first->f_sub_any );
586 } else if ( q2->first->f_sub_any ) {
590 if ( !BER_BVISNULL( &q1->first->f_sub_final )) {
591 if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
592 rc = lex_bvcmp( &q1->first->f_sub_final,
593 &q2->first->f_sub_final );
597 } else if ( !BER_BVISNULL( &q2->first->f_sub_final )) {
601 rc = lex_bvcmp( &q1->first->f_mr_value,
602 &q2->first->f_mr_value );
611 /* add query on top of LRU list */
613 add_query_on_top (query_manager* qm, CachedQuery* qc)
615 CachedQuery* top = qm->lru_top;
626 Debug( pcache_debug, "Base of added query = %s\n",
627 qc->qbase->base.bv_val, 0, 0 );
630 /* remove_query from LRU list */
633 remove_query (query_manager* qm, CachedQuery* qc)
656 qc->lru_up = qc->lru_down = NULL;
659 /* find and remove string2 from string1
660 * from start if position = 1,
661 * from end if position = 3,
662 * from anywhere if position = 2
663 * string1 is overwritten if position = 2.
667 find_and_remove(struct berval* ber1, struct berval* ber2, int position)
678 if ( ber1->bv_len >= ber2->bv_len && !memcmp( ber1->bv_val,
679 ber2->bv_val, ber2->bv_len )) {
681 ber1->bv_val += ber2->bv_len;
682 ber1->bv_len -= ber2->bv_len;
687 ber1->bv_val[ber1->bv_len] = '\0';
688 temp = strstr( ber1->bv_val, ber2->bv_val );
690 strcpy( temp, temp+ber2->bv_len );
691 ber1->bv_len -= ber2->bv_len;
697 if ( ber1->bv_len >= ber2->bv_len &&
698 !memcmp( ber1->bv_val+ber1->bv_len-ber2->bv_len, ber2->bv_val,
701 ber1->bv_len -= ber2->bv_len;
709 static struct berval*
710 merge_init_final(Operation *op, struct berval* init, struct berval* any,
711 struct berval* final)
713 struct berval* merged, *temp;
714 int i, any_count, count;
716 for (any_count=0; any && any[any_count].bv_val; any_count++)
726 merged = (struct berval*)op->o_tmpalloc( (count+1)*sizeof(struct berval),
731 ber_dupbv_x( temp, init, op->o_tmpmemctx );
735 for (i=0; i<any_count; i++) {
736 ber_dupbv_x( temp, any, op->o_tmpmemctx );
741 ber_dupbv_x( temp, final, op->o_tmpmemctx );
748 /* Each element in stored must be found in incoming. Incoming is overwritten.
751 strings_containment(struct berval* stored, struct berval* incoming)
753 struct berval* element;
757 for ( element=stored; element->bv_val != NULL; element++ ) {
758 for (j = k; incoming[j].bv_val != NULL; j++) {
759 if (find_and_remove(&(incoming[j]), element, 2)) {
776 substr_containment_substr(Operation *op, Filter* stored, Filter* incoming)
780 struct berval init_incoming;
781 struct berval final_incoming;
782 struct berval *remaining_incoming = NULL;
784 if ((!(incoming->f_sub_initial.bv_val) && (stored->f_sub_initial.bv_val))
785 || (!(incoming->f_sub_final.bv_val) && (stored->f_sub_final.bv_val)))
788 init_incoming = incoming->f_sub_initial;
789 final_incoming = incoming->f_sub_final;
791 if (find_and_remove(&init_incoming,
792 &(stored->f_sub_initial), 1) && find_and_remove(&final_incoming,
793 &(stored->f_sub_final), 3))
795 if (stored->f_sub_any == NULL) {
799 remaining_incoming = merge_init_final(op, &init_incoming,
800 incoming->f_sub_any, &final_incoming);
801 rc = strings_containment(stored->f_sub_any, remaining_incoming);
802 ber_bvarray_free_x( remaining_incoming, op->o_tmpmemctx );
809 substr_containment_equality(Operation *op, Filter* stored, Filter* incoming)
811 struct berval incoming_val[2];
814 incoming_val[1] = incoming->f_av_value;
816 if (find_and_remove(incoming_val+1,
817 &(stored->f_sub_initial), 1) && find_and_remove(incoming_val+1,
818 &(stored->f_sub_final), 3)) {
819 if (stored->f_sub_any == NULL){
823 ber_dupbv_x( incoming_val, incoming_val+1, op->o_tmpmemctx );
824 BER_BVZERO( incoming_val+1 );
825 rc = strings_containment(stored->f_sub_any, incoming_val);
826 op->o_tmpfree( incoming_val[0].bv_val, op->o_tmpmemctx );
833 filter_first( Filter *f )
835 while ( f->f_choice == LDAP_FILTER_OR || f->f_choice == LDAP_FILTER_AND )
842 find_filter( Operation *op, Avlnode *root, Filter *inputf, Filter *first )
846 MatchingRule* mrule = NULL;
847 int res=0, eqpass= 0;
855 /* substring matches sort to the end, and we just have to
856 * walk the entire list.
858 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS ) {
859 ptr = tavl_end( root, 1 );
862 ptr = tavl_find3( root, &cq, pcache_filter_cmp, &ret );
863 dir = (first->f_choice == LDAP_FILTER_GE) ? TAVL_DIR_LEFT :
872 /* an incoming substr query can only be satisfied by a cached
875 if ( first->f_choice == LDAP_FILTER_SUBSTRINGS &&
876 qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
879 /* an incoming eq query can be satisfied by a cached eq or substr
882 if ( first->f_choice == LDAP_FILTER_EQUALITY ) {
884 if ( qc->first->f_choice != LDAP_FILTER_EQUALITY ) {
885 nextpass: eqpass = 1;
886 ptr = tavl_end( root, 1 );
891 if ( qc->first->f_choice != LDAP_FILTER_SUBSTRINGS )
897 switch (fs->f_choice) {
898 case LDAP_FILTER_EQUALITY:
899 if (fi->f_choice == LDAP_FILTER_EQUALITY)
900 mrule = fs->f_ava->aa_desc->ad_type->sat_equality;
906 mrule = fs->f_ava->aa_desc->ad_type->sat_ordering;
913 rc = value_match(&ret, fs->f_ava->aa_desc, mrule,
914 SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,
915 &(fi->f_ava->aa_value),
916 &(fs->f_ava->aa_value), &text);
917 if (rc != LDAP_SUCCESS) {
920 if ( fi==first && fi->f_choice==LDAP_FILTER_EQUALITY && ret )
923 switch (fs->f_choice) {
925 case LDAP_FILTER_AND:
930 case LDAP_FILTER_SUBSTRINGS:
931 /* check if the equality query can be
932 * answered with cached substring query */
933 if ((fi->f_choice == LDAP_FILTER_EQUALITY)
934 && substr_containment_equality( op,
937 /* check if the substring query can be
938 * answered with cached substring query */
939 if ((fi->f_choice ==LDAP_FILTER_SUBSTRINGS
940 ) && substr_containment_substr( op,
946 case LDAP_FILTER_PRESENT:
951 case LDAP_FILTER_EQUALITY:
958 if (mrule && ret >= 0)
964 if (mrule && ret <= 0)
969 case LDAP_FILTER_NOT:
975 } while((res) && (fi != NULL) && (fs != NULL));
979 ptr = tavl_next( ptr, dir );
984 /* check whether query is contained in any of
985 * the cached queries in template
988 query_containment(Operation *op, query_manager *qm,
990 QueryTemplate *templa)
993 int depth = 0, tscope;
994 Qbase qbase, *qbptr = NULL;
997 if (query->filter != NULL) {
1000 Debug( pcache_debug, "Lock QC index = %p\n",
1001 (void *) templa, 0, 0 );
1002 qbase.base = query->base;
1004 first = filter_first( query->filter );
1006 ldap_pvt_thread_rdwr_rlock(&templa->t_rwlock);
1009 qbptr = avl_find( templa->qbase, &qbase, pcache_dn_cmp );
1011 tscope = query->scope;
1012 /* Find a matching scope:
1013 * match at depth 0 OK
1016 * subord at depth > 0 OK
1017 * subtree at any depth OK
1019 * subtree or subord at any depth OK
1021 * subtree or subord at any depth OK
1023 * subord at depth > 0 OK
1024 * subtree at any depth OK
1026 for ( tscope = 0 ; tscope <= LDAP_SCOPE_CHILDREN; tscope++ ) {
1027 switch ( query->scope ) {
1028 case LDAP_SCOPE_BASE:
1029 if ( tscope == LDAP_SCOPE_BASE && depth ) continue;
1030 if ( tscope == LDAP_SCOPE_ONE && depth != 1) continue;
1031 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1033 case LDAP_SCOPE_ONE:
1034 if ( tscope == LDAP_SCOPE_BASE )
1035 tscope = LDAP_SCOPE_ONE;
1036 if ( tscope == LDAP_SCOPE_ONE && depth ) continue;
1037 if ( !depth ) break;
1038 if ( tscope < LDAP_SCOPE_SUBTREE )
1039 tscope = LDAP_SCOPE_SUBTREE;
1041 case LDAP_SCOPE_SUBTREE:
1042 if ( tscope < LDAP_SCOPE_SUBTREE )
1043 tscope = LDAP_SCOPE_SUBTREE;
1044 if ( tscope == LDAP_SCOPE_CHILDREN && !depth ) continue;
1046 case LDAP_SCOPE_CHILDREN:
1047 if ( tscope < LDAP_SCOPE_SUBTREE )
1048 tscope = LDAP_SCOPE_SUBTREE;
1051 if ( !qbptr->scopes[tscope] ) continue;
1054 qc = find_filter( op, qbptr->scopes[tscope],
1055 query->filter, first );
1057 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1058 if (qm->lru_top != qc) {
1059 remove_query(qm, qc);
1060 add_query_on_top(qm, qc);
1062 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1067 if ( be_issuffix( op->o_bd, &qbase.base ))
1070 dnParent( &qbase.base, &pdn );
1075 Debug( pcache_debug,
1076 "Not answerable: Unlock QC index=%p\n",
1077 (void *) templa, 0, 0 );
1078 ldap_pvt_thread_rdwr_runlock(&templa->t_rwlock);
1084 free_query (CachedQuery* qc)
1086 free(qc->q_uuid.bv_val);
1087 filter_free(qc->filter);
1092 /* Add query to query cache */
1093 static CachedQuery *
1098 QueryTemplate *templ,
1101 CachedQuery* new_cached_query = (CachedQuery*) ch_malloc(sizeof(CachedQuery));
1106 new_cached_query->qtemp = templ;
1107 BER_BVZERO( &new_cached_query->q_uuid );
1109 new_cached_query->expiry_time = slap_get_time() + templ->ttl;
1111 new_cached_query->expiry_time = slap_get_time() + templ->negttl;
1113 new_cached_query->lru_up = NULL;
1114 new_cached_query->lru_down = NULL;
1115 Debug( pcache_debug, "Added query expires at %ld\n",
1116 (long) new_cached_query->expiry_time, 0, 0 );
1118 new_cached_query->scope = query->scope;
1119 new_cached_query->filter = query->filter;
1120 new_cached_query->first = first = filter_first( query->filter );
1122 qb.base = query->base;
1124 /* Adding a query */
1125 Debug( pcache_debug, "Lock AQ index = %p\n",
1126 (void *) templ, 0, 0 );
1127 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1128 qbase = avl_find( templ->qbase, &qb, pcache_dn_cmp );
1130 qbase = ch_calloc( 1, sizeof(Qbase) + qb.base.bv_len + 1 );
1131 qbase->base.bv_len = qb.base.bv_len;
1132 qbase->base.bv_val = (char *)(qbase+1);
1133 memcpy( qbase->base.bv_val, qb.base.bv_val, qb.base.bv_len );
1134 qbase->base.bv_val[qbase->base.bv_len] = '\0';
1135 avl_insert( &templ->qbase, qbase, pcache_dn_cmp, avl_dup_error );
1137 new_cached_query->next = templ->query;
1138 new_cached_query->prev = NULL;
1139 new_cached_query->qbase = qbase;
1140 rc = tavl_insert( &qbase->scopes[query->scope], new_cached_query,
1141 pcache_filter_cmp, avl_dup_error );
1144 if (templ->query == NULL)
1145 templ->query_last = new_cached_query;
1147 templ->query->prev = new_cached_query;
1148 templ->query = new_cached_query;
1149 templ->no_of_queries++;
1151 ch_free( new_cached_query );
1152 new_cached_query = find_filter( op, qbase->scopes[query->scope],
1153 query->filter, first );
1154 filter_free( query->filter );
1156 Debug( pcache_debug, "TEMPLATE %p QUERIES++ %d\n",
1157 (void *) templ, templ->no_of_queries, 0 );
1159 Debug( pcache_debug, "Unlock AQ index = %p \n",
1160 (void *) templ, 0, 0 );
1161 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1163 /* Adding on top of LRU list */
1165 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1166 add_query_on_top(qm, new_cached_query);
1167 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1169 return rc == 0 ? new_cached_query : NULL;
1173 remove_from_template (CachedQuery* qc, QueryTemplate* template)
1175 if (!qc->prev && !qc->next) {
1176 template->query_last = template->query = NULL;
1177 } else if (qc->prev == NULL) {
1178 qc->next->prev = NULL;
1179 template->query = qc->next;
1180 } else if (qc->next == NULL) {
1181 qc->prev->next = NULL;
1182 template->query_last = qc->prev;
1184 qc->next->prev = qc->prev;
1185 qc->prev->next = qc->next;
1187 tavl_delete( &qc->qbase->scopes[qc->scope], qc, pcache_filter_cmp );
1188 qc->qbase->queries--;
1189 if ( qc->qbase->queries == 0 ) {
1190 avl_delete( &template->qbase, qc->qbase, pcache_dn_cmp );
1191 ch_free( qc->qbase );
1195 template->no_of_queries--;
1198 /* remove bottom query of LRU list from the query cache */
1199 static void cache_replacement(query_manager* qm, struct berval *result)
1201 CachedQuery* bottom;
1202 QueryTemplate *temp;
1204 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1205 bottom = qm->lru_bottom;
1207 result->bv_val = NULL;
1211 Debug ( pcache_debug,
1212 "Cache replacement invoked without "
1213 "any query in LRU list\n", 0, 0, 0 );
1214 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1218 temp = bottom->qtemp;
1219 remove_query(qm, bottom);
1220 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1222 *result = bottom->q_uuid;
1223 bottom->q_uuid.bv_val = NULL;
1225 Debug( pcache_debug, "Lock CR index = %p\n", (void *) temp, 0, 0 );
1226 ldap_pvt_thread_rdwr_wlock(&temp->t_rwlock);
1227 remove_from_template(bottom, temp);
1228 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1229 (void *) temp, temp->no_of_queries, 0 );
1230 Debug( pcache_debug, "Unlock CR index = %p\n", (void *) temp, 0, 0 );
1231 ldap_pvt_thread_rdwr_wunlock(&temp->t_rwlock);
1236 struct query_info *next;
1248 struct query_info *qi;
1251 if ( rs->sr_type != REP_SEARCH ) return 0;
1253 for (attr = rs->sr_entry->e_attrs; attr!= NULL; attr = attr->a_next) {
1254 if (attr->a_desc == ad_queryid) {
1255 for (count=0; attr->a_vals[count].bv_val; count++)
1260 if ( count == 0 ) return 0;
1261 qi = op->o_tmpalloc( sizeof( struct query_info ), op->o_tmpmemctx );
1262 qi->next = op->o_callback->sc_private;
1263 op->o_callback->sc_private = qi;
1264 ber_dupbv_x( &qi->xdn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1265 qi->del = ( count == 1 );
1274 struct berval* query_uuid)
1276 struct query_info *qi, *qnext;
1277 char filter_str[64];
1278 #ifdef LDAP_COMP_MATCH
1279 AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1281 AttributeAssertion ava = { NULL, BER_BVNULL };
1283 Filter filter = {LDAP_FILTER_EQUALITY};
1284 SlapReply sreply = {REP_RESULT};
1285 slap_callback cb = { NULL, remove_func, NULL, NULL };
1288 sreply.sr_entry = NULL;
1289 sreply.sr_nentries = 0;
1290 op->ors_filterstr.bv_len = snprintf(filter_str, sizeof(filter_str),
1291 "(%s=%s)", ad_queryid->ad_cname.bv_val, query_uuid->bv_val);
1292 filter.f_ava = &ava;
1293 filter.f_av_desc = ad_queryid;
1294 filter.f_av_value = *query_uuid;
1296 op->o_tag = LDAP_REQ_SEARCH;
1297 op->o_protocol = LDAP_VERSION3;
1298 op->o_callback = &cb;
1299 op->o_time = slap_get_time();
1300 op->o_do_not_cache = 1;
1302 op->o_req_dn = op->o_bd->be_suffix[0];
1303 op->o_req_ndn = op->o_bd->be_nsuffix[0];
1304 op->ors_scope = LDAP_SCOPE_SUBTREE;
1305 op->ors_deref = LDAP_DEREF_NEVER;
1306 op->ors_slimit = SLAP_NO_LIMIT;
1307 op->ors_tlimit = SLAP_NO_LIMIT;
1308 op->ors_filter = &filter;
1309 op->ors_filterstr.bv_val = filter_str;
1310 op->ors_filterstr.bv_len = strlen(filter_str);
1311 op->ors_attrs = NULL;
1312 op->ors_attrsonly = 0;
1314 op->o_bd->be_search( op, &sreply );
1316 for ( qi=cb.sc_private; qi; qi=qnext ) {
1319 op->o_req_dn = qi->xdn;
1320 op->o_req_ndn = qi->xdn;
1323 Debug( pcache_debug, "DELETING ENTRY TEMPLATE=%s\n",
1324 query_uuid->bv_val, 0, 0 );
1326 op->o_tag = LDAP_REQ_DELETE;
1328 if (op->o_bd->be_delete(op, &sreply) == LDAP_SUCCESS) {
1333 struct berval vals[2];
1335 vals[0] = *query_uuid;
1336 vals[1].bv_val = NULL;
1338 mod.sml_op = LDAP_MOD_DELETE;
1340 mod.sml_desc = ad_queryid;
1341 mod.sml_type = ad_queryid->ad_cname;
1342 mod.sml_values = vals;
1343 mod.sml_nvalues = NULL;
1344 mod.sml_next = NULL;
1345 Debug( pcache_debug,
1346 "REMOVING TEMP ATTR : TEMPLATE=%s\n",
1347 query_uuid->bv_val, 0, 0 );
1349 op->orm_modlist = &mod;
1351 op->o_bd->be_modify( op, &sreply );
1353 op->o_tmpfree( qi->xdn.bv_val, op->o_tmpmemctx );
1354 op->o_tmpfree( qi, op->o_tmpmemctx );
1361 AttributeName* attrs,
1370 struct berval *fstr,
1371 AttributeName** filter_attrs,
1373 int* filter_got_oc )
1375 AttributeDescription *ad;
1377 switch ( f->f_choice ) {
1378 case LDAP_FILTER_EQUALITY:
1380 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1381 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1384 case LDAP_FILTER_GE:
1386 sprintf( fstr->bv_val+fstr->bv_len, "(%s>=)", ad->ad_cname.bv_val);
1387 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(>=)") - 1 );
1390 case LDAP_FILTER_LE:
1392 sprintf( fstr->bv_val+fstr->bv_len, "(%s<=)", ad->ad_cname.bv_val);
1393 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(<=)") - 1 );
1396 case LDAP_FILTER_APPROX:
1398 sprintf( fstr->bv_val+fstr->bv_len, "(%s~=)", ad->ad_cname.bv_val);
1399 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(~=)") - 1 );
1402 case LDAP_FILTER_SUBSTRINGS:
1404 sprintf( fstr->bv_val+fstr->bv_len, "(%s=)", ad->ad_cname.bv_val );
1405 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=)") - 1 );
1408 case LDAP_FILTER_PRESENT:
1410 sprintf( fstr->bv_val+fstr->bv_len, "(%s=*)", ad->ad_cname.bv_val );
1411 fstr->bv_len += ad->ad_cname.bv_len + ( sizeof("(=*)") - 1 );
1414 case LDAP_FILTER_AND:
1415 case LDAP_FILTER_OR:
1416 case LDAP_FILTER_NOT: {
1418 sprintf( fstr->bv_val+fstr->bv_len, "(%c",
1419 f->f_choice == LDAP_FILTER_AND ? '&' :
1420 f->f_choice == LDAP_FILTER_OR ? '|' : '!' );
1421 fstr->bv_len += sizeof("(%") - 1;
1423 for ( f = f->f_list; f != NULL; f = f->f_next ) {
1424 rc = filter2template( op, f, fstr, filter_attrs, filter_cnt,
1428 sprintf( fstr->bv_val+fstr->bv_len, ")" );
1429 fstr->bv_len += sizeof(")") - 1;
1435 strcpy( fstr->bv_val, "(?=?)" );
1436 fstr->bv_len += sizeof("(?=?)")-1;
1440 if ( filter_attrs != NULL ) {
1441 *filter_attrs = (AttributeName *)op->o_tmprealloc(*filter_attrs,
1442 (*filter_cnt + 2)*sizeof(AttributeName), op->o_tmpmemctx);
1444 (*filter_attrs)[*filter_cnt].an_desc = ad;
1445 (*filter_attrs)[*filter_cnt].an_name = ad->ad_cname;
1446 (*filter_attrs)[*filter_cnt].an_oc = NULL;
1447 (*filter_attrs)[*filter_cnt].an_oc_exclude = 0;
1448 BER_BVZERO( &(*filter_attrs)[*filter_cnt+1].an_name );
1450 if ( ad == slap_schema.si_ad_objectClass )
1457 struct search_info {
1460 QueryTemplate *qtemp;
1461 AttributeName* save_attrs; /* original attributes, saved for response */
1472 struct berval *query_uuid)
1474 struct search_info *si = op->o_callback->sc_private;
1475 slap_overinst *on = si->on;
1476 cache_manager *cm = on->on_bi.bi_private;
1477 query_manager* qm = cm->qm;
1480 struct berval crp_uuid;
1481 char uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1482 Operation op_tmp = *op;
1484 query_uuid->bv_len = lutil_uuidstr(uuidbuf, sizeof(uuidbuf));
1485 ber_str2bv(uuidbuf, query_uuid->bv_len, 1, query_uuid);
1487 op_tmp.o_bd = &cm->db;
1488 op_tmp.o_dn = cm->db.be_rootdn;
1489 op_tmp.o_ndn = cm->db.be_rootndn;
1491 Debug( pcache_debug, "UUID for query being added = %s\n",
1494 for ( e=si->head; e; e=si->head ) {
1495 si->head = e->e_private;
1496 e->e_private = NULL;
1497 while ( cm->cur_entries > (cm->max_entries) ) {
1498 qm->crfunc(qm, &crp_uuid);
1499 if (crp_uuid.bv_val) {
1500 Debug( pcache_debug,
1501 "Removing query UUID %s\n",
1502 crp_uuid.bv_val, 0, 0 );
1503 return_val = remove_query_data(&op_tmp, rs, &crp_uuid);
1504 Debug( pcache_debug,
1505 "QUERY REMOVED, SIZE=%d\n",
1507 ldap_pvt_thread_mutex_lock(
1509 cm->cur_entries -= return_val;
1510 cm->num_cached_queries--;
1511 Debug( pcache_debug,
1512 "STORED QUERIES = %lu\n",
1513 cm->num_cached_queries, 0, 0 );
1514 ldap_pvt_thread_mutex_unlock(
1516 Debug( pcache_debug,
1517 "QUERY REMOVED, CACHE ="
1519 cm->cur_entries, 0, 0 );
1523 return_val = merge_entry(&op_tmp, e, query_uuid);
1524 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1525 cm->cur_entries += return_val;
1526 Debug( pcache_debug,
1527 "ENTRY ADDED/MERGED, CACHED ENTRIES=%d\n",
1528 cm->cur_entries, 0, 0 );
1530 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1537 pcache_op_cleanup( Operation *op, SlapReply *rs ) {
1538 slap_callback *cb = op->o_callback;
1539 struct search_info *si = cb->sc_private;
1540 if ( si->save_attrs != NULL ) {
1541 rs->sr_attrs = si->save_attrs;
1542 op->ors_attrs = si->save_attrs;
1544 op->o_callback = op->o_callback->sc_next;
1545 op->o_tmpfree( cb, op->o_tmpmemctx );
1546 return SLAP_CB_CONTINUE;
1554 struct search_info *si = op->o_callback->sc_private;
1555 slap_overinst *on = si->on;
1556 cache_manager *cm = on->on_bi.bi_private;
1557 query_manager* qm = cm->qm;
1559 if ( si->save_attrs != NULL ) {
1560 rs->sr_attrs = si->save_attrs;
1561 op->ors_attrs = si->save_attrs;
1564 if ( rs->sr_type == REP_SEARCH ) {
1566 /* If we haven't exceeded the limit for this query,
1567 * build a chain of answers to store. If we hit the
1568 * limit, empty the chain and ignore the rest.
1571 if ( si->count < si->max ) {
1573 e = entry_dup( rs->sr_entry );
1574 if ( !si->head ) si->head = e;
1575 if ( si->tail ) si->tail->e_private = e;
1580 for (;si->head; si->head=e) {
1581 e = si->head->e_private;
1582 si->head->e_private = NULL;
1583 entry_free(si->head);
1589 } else if ( rs->sr_type == REP_RESULT ) {
1591 ( si->qtemp->negttl && !si->count && !si->over &&
1592 rs->sr_err == LDAP_SUCCESS )) {
1593 CachedQuery *qc = qm->addfunc(op, qm, &si->query, si->qtemp,
1598 cache_entries( op, rs, &qc->q_uuid );
1599 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1600 cm->num_cached_queries++;
1601 Debug( pcache_debug, "STORED QUERIES = %lu\n",
1602 cm->num_cached_queries, 0, 0 );
1603 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1605 /* If the consistency checker suspended itself,
1608 if ( cm->cc_paused ) {
1609 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1610 if ( cm->cc_paused ) {
1612 ldap_pvt_runqueue_resched( &slapd_rq, cm->cc_arg, 0 );
1614 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1616 } else if ( si->count ) {
1617 /* duplicate query, free it */
1619 for (;si->head; si->head=e) {
1620 e = si->head->e_private;
1621 si->head->e_private = NULL;
1622 entry_free(si->head);
1626 filter_free( si->query.filter );
1629 op->o_callback->sc_cleanup = pcache_op_cleanup;
1631 return SLAP_CB_CONTINUE;
1637 AttributeName** new_attrs,
1638 struct attr_set *attrs,
1639 AttributeName* filter_attrs,
1649 /* duplicate attrs */
1650 count = attrs->count + fattr_cnt;
1651 if ( !fattr_got_oc && !(attrs->flags & PC_GOT_OC)) {
1656 *new_attrs = (AttributeName*)ch_calloc( count + 1,
1657 sizeof(AttributeName) );
1658 for (i=0; i<attrs->count; i++) {
1659 (*new_attrs)[i].an_name = attrs->attrs[i].an_name;
1660 (*new_attrs)[i].an_desc = attrs->attrs[i].an_desc;
1662 BER_BVZERO( &(*new_attrs)[i].an_name );
1663 alluser = an_find(*new_attrs, &AllUser);
1664 allop = an_find(*new_attrs, &AllOper);
1667 for ( i=0; i<fattr_cnt; i++ ) {
1668 if ( an_find(*new_attrs, &filter_attrs[i].an_name ) ) {
1671 if ( is_at_operational(filter_attrs[i].an_desc->ad_type) ) {
1675 } else if ( alluser ) {
1678 (*new_attrs)[j].an_name = filter_attrs[i].an_name;
1679 (*new_attrs)[j].an_desc = filter_attrs[i].an_desc;
1680 (*new_attrs)[j].an_oc = NULL;
1681 (*new_attrs)[j].an_oc_exclude = 0;
1685 (*new_attrs)[j].an_name = slap_schema.si_ad_objectClass->ad_cname;
1686 (*new_attrs)[j].an_desc = slap_schema.si_ad_objectClass;
1687 (*new_attrs)[j].an_oc = NULL;
1688 (*new_attrs)[j].an_oc_exclude = 0;
1691 BER_BVZERO( &(*new_attrs)[j].an_name );
1694 /* NOTE: this is a quick workaround to let pcache minimally interact
1695 * with pagedResults. A more articulated solutions would be to
1696 * perform the remote query without control and cache all results,
1697 * performing the pagedResults search only within the client
1698 * and the proxy. This requires pcache to understand pagedResults. */
1700 pcache_chk_controls(
1704 const char *non = "";
1705 const char *stripped = "";
1707 switch( op->o_pagedresults ) {
1708 case SLAP_CONTROL_NONCRITICAL:
1710 stripped = "; stripped";
1713 case SLAP_CONTROL_CRITICAL:
1714 Debug( pcache_debug, "%s: "
1715 "%scritical pagedResults control "
1716 "disabled with proxy cache%s.\n",
1717 op->o_log_prefix, non, stripped );
1719 slap_remove_control( op, rs, slap_cids.sc_pagedResults, NULL );
1723 rs->sr_err = SLAP_CB_CONTINUE;
1735 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1736 cache_manager *cm = on->on_bi.bi_private;
1737 query_manager* qm = cm->qm;
1741 AttributeName *filter_attrs = NULL;
1744 QueryTemplate *qtemp = NULL;
1747 CachedQuery *answerable = NULL;
1750 int fattr_got_oc = 0;
1752 struct berval tempstr;
1754 tempstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len+1, op->o_tmpmemctx );
1756 if ( filter2template( op, op->ors_filter, &tempstr, &filter_attrs,
1757 &fattr_cnt, &fattr_got_oc )) {
1758 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1759 return SLAP_CB_CONTINUE;
1762 Debug( pcache_debug, "query template of incoming query = %s\n",
1763 tempstr.bv_val, 0, 0 );
1765 /* FIXME: cannot cache/answer requests with pagedResults control */
1768 attr_set = get_attr_set(op->ors_attrs, qm, cm->numattrsets);
1770 query.filter = op->ors_filter;
1771 query.base = op->o_req_ndn;
1772 query.scope = op->ors_scope;
1774 /* check for query containment */
1775 if (attr_set > -1) {
1776 QueryTemplate *qt = qm->attr_sets[attr_set].templates;
1777 for (; qt; qt = qt->qtnext ) {
1778 /* find if template i can potentially answer tempstr */
1779 if (qt->querystr.bv_len != tempstr.bv_len ||
1780 strcasecmp( qt->querystr.bv_val, tempstr.bv_val ))
1784 Debug( pcache_debug, "Entering QC, querystr = %s\n",
1785 op->ors_filterstr.bv_val, 0, 0 );
1786 answerable = (*(qm->qcfunc))(op, qm, &query, qt);
1792 op->o_tmpfree( tempstr.bv_val, op->o_tmpmemctx );
1795 /* Need to clear the callbacks of the original operation,
1796 * in case there are other overlays */
1797 BackendDB *save_bd = op->o_bd;
1798 slap_callback *save_cb = op->o_callback;
1800 Debug( pcache_debug, "QUERY ANSWERABLE\n", 0, 0, 0 );
1801 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1802 if ( BER_BVISNULL( &answerable->q_uuid )) {
1803 /* No entries cached, just an empty result set */
1805 send_ldap_result( op, rs );
1808 op->o_callback = NULL;
1809 i = cm->db.bd_info->bi_op_search( op, rs );
1811 ldap_pvt_thread_rdwr_runlock(&qtemp->t_rwlock);
1813 op->o_callback = save_cb;
1817 Debug( pcache_debug, "QUERY NOT ANSWERABLE\n", 0, 0, 0 );
1819 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
1820 if (cm->num_cached_queries >= cm->max_queries) {
1823 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
1825 if (op->ors_attrsonly)
1830 struct search_info *si;
1832 Debug( pcache_debug, "QUERY CACHEABLE\n", 0, 0, 0 );
1833 query.filter = filter_dup(op->ors_filter, NULL);
1834 ldap_pvt_thread_rdwr_wlock(&qtemp->t_rwlock);
1835 if ( !qtemp->t_attrs.count ) {
1836 add_filter_attrs(op, &qtemp->t_attrs.attrs,
1837 &qm->attr_sets[attr_set],
1838 filter_attrs, fattr_cnt, fattr_got_oc);
1840 ldap_pvt_thread_rdwr_wunlock(&qtemp->t_rwlock);
1842 cb = op->o_tmpalloc( sizeof(*cb) + sizeof(*si), op->o_tmpmemctx );
1843 cb->sc_response = pcache_response;
1844 cb->sc_cleanup = NULL;
1845 cb->sc_private = (cb+1);
1846 si = cb->sc_private;
1850 si->max = cm->num_entries_limit ;
1855 si->save_attrs = op->ors_attrs;
1857 op->ors_attrs = qtemp->t_attrs.attrs;
1859 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
1860 cb->sc_next = op->o_callback;
1861 op->o_callback = cb;
1864 slap_callback **pcb;
1866 /* need to move the callback at the end, in case other
1867 * overlays are present, so that the final entry is
1868 * actually cached */
1870 for ( pcb = &op->o_callback; *pcb; pcb = &(*pcb)->sc_next );
1875 Debug( pcache_debug, "QUERY NOT CACHEABLE\n",
1879 op->o_tmpfree( filter_attrs, op->o_tmpmemctx );
1881 return SLAP_CB_CONTINUE;
1886 AttributeName* attrs,
1894 for ( ; attrs[count].an_name.bv_val; count++ );
1897 /* recognize a single "*" or a "1.1" */
1900 attrs = slap_anlist_all_user_attributes;
1902 } else if ( count == 1 && strcmp( attrs[0].an_name.bv_val, LDAP_NO_ATTRS ) == 0 ) {
1907 for ( i = 0; i < num; i++ ) {
1911 if ( count > qm->attr_sets[i].count ) {
1916 if ( !qm->attr_sets[i].count ) {
1922 for ( a2 = attrs; a2->an_name.bv_val; a2++ ) {
1923 if ( !an_find( qm->attr_sets[i].attrs, &a2->an_name ) ) {
1946 struct re_s *rtask = arg;
1947 slap_overinst *on = rtask->arg;
1948 cache_manager *cm = on->on_bi.bi_private;
1949 query_manager *qm = cm->qm;
1950 Connection conn = {0};
1951 OperationBuffer opbuf;
1954 SlapReply rs = {REP_RESULT};
1956 int return_val, pause = 1;
1957 QueryTemplate* templ;
1959 connection_fake_init( &conn, &opbuf, ctx );
1963 op->o_dn = cm->db.be_rootdn;
1964 op->o_ndn = cm->db.be_rootndn;
1968 for (templ = qm->templates; templ; templ=templ->qmnext) {
1969 query = templ->query_last;
1970 if ( query ) pause = 0;
1971 op->o_time = slap_get_time();
1972 while (query && (query->expiry_time < op->o_time)) {
1974 Debug( pcache_debug, "Lock CR index = %p\n",
1975 (void *) templ, 0, 0 );
1976 ldap_pvt_thread_rdwr_wlock(&templ->t_rwlock);
1977 if ( query == templ->query_last ) {
1979 remove_from_template(query, templ);
1980 Debug( pcache_debug, "TEMPLATE %p QUERIES-- %d\n",
1981 (void *) templ, templ->no_of_queries, 0 );
1982 Debug( pcache_debug, "Unlock CR index = %p\n",
1983 (void *) templ, 0, 0 );
1985 ldap_pvt_thread_rdwr_wunlock(&templ->t_rwlock);
1987 query = templ->query_last;
1990 ldap_pvt_thread_mutex_lock(&qm->lru_mutex);
1991 remove_query(qm, query);
1992 ldap_pvt_thread_mutex_unlock(&qm->lru_mutex);
1993 if ( BER_BVISNULL( &query->q_uuid ))
1996 return_val = remove_query_data(op, &rs, &query->q_uuid);
1997 Debug( pcache_debug, "STALE QUERY REMOVED, SIZE=%d\n",
1999 ldap_pvt_thread_mutex_lock(&cm->cache_mutex);
2000 cm->cur_entries -= return_val;
2001 cm->num_cached_queries--;
2002 Debug( pcache_debug, "STORED QUERIES = %lu\n",
2003 cm->num_cached_queries, 0, 0 );
2004 ldap_pvt_thread_mutex_unlock(&cm->cache_mutex);
2005 Debug( pcache_debug,
2006 "STALE QUERY REMOVED, CACHE ="
2008 cm->cur_entries, 0, 0 );
2010 query = templ->query_last;
2013 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2014 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2015 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
2017 /* If there were no queries, defer processing for a while */
2018 cm->cc_paused = pause;
2019 ldap_pvt_runqueue_resched( &slapd_rq, rtask, pause );
2021 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2026 #define MAX_ATTR_SETS 500
2036 static ConfigDriver pc_cf_gen;
2037 static ConfigLDAPadd pc_ldadd;
2038 static ConfigCfAdd pc_cfadd;
2040 static ConfigTable pccfg[] = {
2041 { "proxycache", "backend> <max_entries> <numattrsets> <entry limit> "
2043 6, 6, 0, ARG_MAGIC|ARG_NO_DELETE|PC_MAIN, pc_cf_gen,
2044 "( OLcfgOvAt:2.1 NAME 'olcProxyCache' "
2045 "DESC 'ProxyCache basic parameters' "
2046 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2047 { "proxyattrset", "index> <attributes...",
2048 2, 0, 0, ARG_MAGIC|PC_ATTR, pc_cf_gen,
2049 "( OLcfgOvAt:2.2 NAME 'olcProxyAttrset' "
2050 "DESC 'A set of attributes to cache' "
2051 "SYNTAX OMsDirectoryString )", NULL, NULL },
2052 { "proxytemplate", "filter> <attrset-index> <TTL> <negTTL",
2053 4, 5, 0, ARG_MAGIC|PC_TEMP, pc_cf_gen,
2054 "( OLcfgOvAt:2.3 NAME 'olcProxyTemplate' "
2055 "DESC 'Filter template, attrset, cache TTL, optional negative TTL' "
2056 "SYNTAX OMsDirectoryString )", NULL, NULL },
2057 { "response-callback", "head|tail(default)",
2058 2, 2, 0, ARG_MAGIC|PC_RESP, pc_cf_gen,
2059 "( OLcfgOvAt:2.4 NAME 'olcProxyResponseCB' "
2060 "DESC 'Response callback position in overlay stack' "
2061 "SYNTAX OMsDirectoryString )", NULL, NULL },
2062 { "proxyCacheQueries", "queries",
2063 2, 2, 0, ARG_INT|ARG_MAGIC|PC_QUERIES, pc_cf_gen,
2064 "( OLcfgOvAt:2.5 NAME 'olcProxyCacheQueries' "
2065 "DESC 'Maximum number of queries to cache' "
2066 "SYNTAX OMsInteger )", NULL, NULL },
2067 { "proxySaveQueries", "TRUE|FALSE",
2068 2, 2, 0, ARG_ON_OFF|ARG_OFFSET, (void *)offsetof(cache_manager, save_queries),
2069 "( OLcfgOvAt:2.6 NAME 'olcProxySaveQueries' "
2070 "DESC 'Save cached queries for hot restart' "
2071 "SYNTAX OMsBoolean )", NULL, NULL },
2073 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2076 static ConfigOCs pcocs[] = {
2077 { "( OLcfgOvOc:2.1 "
2078 "NAME 'olcPcacheConfig' "
2079 "DESC 'ProxyCache configuration' "
2080 "SUP olcOverlayConfig "
2081 "MUST ( olcProxyCache $ olcProxyAttrset $ olcProxyTemplate ) "
2082 "MAY ( olcProxyResponseCB $ olcProxyCacheQueries $ olcProxySaveQueries ) )",
2083 Cft_Overlay, pccfg, NULL, pc_cfadd },
2084 { "( OLcfgOvOc:2.2 "
2085 "NAME 'olcPcacheDatabase' "
2086 "DESC 'Cache database configuration' "
2087 "AUXILIARY )", Cft_Misc, pccfg, pc_ldadd },
2092 pc_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
2097 if ( p->ce_type != Cft_Overlay || !p->ce_bi ||
2098 p->ce_bi->bi_cf_ocs != pcocs )
2099 return LDAP_CONSTRAINT_VIOLATION;
2101 on = (slap_overinst *)p->ce_bi;
2102 cm = on->on_bi.bi_private;
2104 return LDAP_SUCCESS;
2108 pc_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
2110 CfEntryInfo *pe = p->e_private;
2111 slap_overinst *on = (slap_overinst *)pe->ce_bi;
2112 cache_manager *cm = on->on_bi.bi_private;
2115 /* FIXME: should not hardcode "olcDatabase" here */
2116 bv.bv_len = sprintf( ca->cr_msg, "olcDatabase=%s", cm->db.bd_info->bi_type );
2117 bv.bv_val = ca->cr_msg;
2120 /* We can only create this entry if the database is table-driven
2122 if ( cm->db.bd_info->bi_cf_ocs )
2123 config_build_entry( op, rs, pe, ca, &bv, cm->db.bd_info->bi_cf_ocs,
2130 pc_cf_gen( ConfigArgs *c )
2132 slap_overinst *on = (slap_overinst *)c->bi;
2133 cache_manager* cm = on->on_bi.bi_private;
2134 query_manager* qm = cm->qm;
2135 QueryTemplate* temp;
2136 AttributeName* attr_name;
2137 AttributeName* attrarray;
2138 const char* text=NULL;
2143 if ( c->op == SLAP_CONFIG_EMIT ) {
2147 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s %d %d %d %ld",
2148 cm->db.bd_info->bi_type, cm->max_entries, cm->numattrsets,
2149 cm->num_entries_limit, cm->cc_period );
2150 bv.bv_val = c->cr_msg;
2151 value_add_one( &c->rvalue_vals, &bv );
2154 for (i=0; i<cm->numattrsets; i++) {
2155 if ( !qm->attr_sets[i].count ) continue;
2157 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), "%d", i );
2159 /* count the attr length */
2160 for ( attr_name = qm->attr_sets[i].attrs;
2161 attr_name->an_name.bv_val; attr_name++ )
2162 bv.bv_len += attr_name->an_name.bv_len + 1;
2164 bv.bv_val = ch_malloc( bv.bv_len+1 );
2165 ptr = lutil_strcopy( bv.bv_val, c->cr_msg );
2166 for ( attr_name = qm->attr_sets[i].attrs;
2167 attr_name->an_name.bv_val; attr_name++ ) {
2169 ptr = lutil_strcopy( ptr, attr_name->an_name.bv_val );
2171 ber_bvarray_add( &c->rvalue_vals, &bv );
2173 if ( !c->rvalue_vals )
2177 for (temp=qm->templates; temp; temp=temp->qmnext) {
2178 if ( temp->negttl ) {
2179 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2181 temp->attr_set_index,
2185 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ), " %d %ld",
2186 temp->attr_set_index,
2189 bv.bv_len += temp->querystr.bv_len + 2;
2190 bv.bv_val = ch_malloc( bv.bv_len+1 );
2193 ptr = lutil_strcopy( ptr, temp->querystr.bv_val );
2195 strcpy( ptr, c->cr_msg );
2196 ber_bvarray_add( &c->rvalue_vals, &bv );
2198 if ( !c->rvalue_vals )
2202 if ( cm->response_cb == PCACHE_RESPONSE_CB_HEAD ) {
2203 BER_BVSTR( &bv, "head" );
2205 BER_BVSTR( &bv, "tail" );
2207 value_add_one( &c->rvalue_vals, &bv );
2210 c->value_int = cm->max_queries;
2214 } else if ( c->op == LDAP_MOD_DELETE ) {
2215 return 1; /* FIXME */
2227 if ( cm->numattrsets > 0 ) {
2228 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive already provided" );
2229 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2233 if ( lutil_atoi( &cm->numattrsets, c->argv[3] ) != 0 ) {
2234 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse num attrsets=\"%s\" (arg #3)",
2236 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2239 if ( cm->numattrsets <= 0 ) {
2240 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be positive" );
2241 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2244 if ( cm->numattrsets > MAX_ATTR_SETS ) {
2245 snprintf( c->cr_msg, sizeof( c->cr_msg ), "numattrsets (arg #3) must be <= %d", MAX_ATTR_SETS );
2246 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2250 if ( !backend_db_init( c->argv[1], &cm->db, -1, NULL )) {
2251 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown backend type (arg #1)" );
2252 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2256 if ( lutil_atoi( &cm->max_entries, c->argv[2] ) != 0 ) {
2257 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse max entries=\"%s\" (arg #2)",
2259 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2262 if ( cm->max_entries <= 0 ) {
2263 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max entries (arg #2) must be positive.\n" );
2264 Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->cr_msg, 0 );
2268 if ( lutil_atoi( &cm->num_entries_limit, c->argv[4] ) != 0 ) {
2269 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse entry limit=\"%s\" (arg #4)",
2271 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2274 if ( cm->num_entries_limit <= 0 ) {
2275 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be positive" );
2276 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2279 if ( cm->num_entries_limit > cm->max_entries ) {
2280 snprintf( c->cr_msg, sizeof( c->cr_msg ), "entry limit (arg #4) must be less than max entries %d (arg #2)", cm->max_entries );
2281 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2285 if ( lutil_parse_time( c->argv[5], &t ) != 0 ) {
2286 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse period=\"%s\" (arg #5)",
2288 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2291 cm->cc_period = (time_t)t;
2292 Debug( pcache_debug,
2293 "Total # of attribute sets to be cached = %d.\n",
2294 cm->numattrsets, 0, 0 );
2295 qm->attr_sets = ( struct attr_set * )ch_calloc( cm->numattrsets,
2296 sizeof( struct attr_set ) );
2299 if ( cm->numattrsets == 0 ) {
2300 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2301 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2304 if ( lutil_atoi( &num, c->argv[1] ) != 0 ) {
2305 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse attrset #=\"%s\"",
2307 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2311 if ( num < 0 || num >= cm->numattrsets ) {
2312 snprintf( c->cr_msg, sizeof( c->cr_msg ), "attrset index %d out of bounds (must be %s%d)",
2313 num, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2314 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2317 qm->attr_sets[num].flags |= PC_CONFIGURED;
2318 if ( c->argc == 2 ) {
2320 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2321 "need an explicit attr in attrlist; use \"*\" to indicate all attrs" );
2322 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2325 } else if ( c->argc == 3 ) {
2326 if ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2327 qm->attr_sets[num].count = 1;
2328 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2329 sizeof( AttributeName ) );
2330 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2333 } else if ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2334 qm->attr_sets[num].count = 1;
2335 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 2,
2336 sizeof( AttributeName ) );
2337 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2340 } else if ( strcmp( c->argv[2], LDAP_NO_ATTRS ) == 0 ) {
2343 /* else: fallthru */
2345 } else if ( c->argc == 4 ) {
2346 if ( ( strcmp( c->argv[2], LDAP_ALL_USER_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 )
2347 || ( strcmp( c->argv[2], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 && strcmp( c->argv[3], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) )
2349 qm->attr_sets[num].count = 2;
2350 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( 3,
2351 sizeof( AttributeName ) );
2352 BER_BVSTR( &qm->attr_sets[num].attrs[0].an_name, LDAP_ALL_USER_ATTRIBUTES );
2353 BER_BVSTR( &qm->attr_sets[num].attrs[1].an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2356 /* else: fallthru */
2359 if ( c->argc > 2 ) {
2360 int all_user = 0, all_op = 0;
2362 qm->attr_sets[num].count = c->argc - 2;
2363 qm->attr_sets[num].attrs = (AttributeName*)ch_calloc( c->argc - 1,
2364 sizeof( AttributeName ) );
2365 attr_name = qm->attr_sets[num].attrs;
2366 for ( i = 2; i < c->argc; i++ ) {
2367 attr_name->an_desc = NULL;
2368 if ( strcmp( c->argv[i], LDAP_NO_ATTRS ) == 0 ) {
2369 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2370 "invalid attr #%d \"%s\" in attrlist",
2371 i - 2, c->argv[i] );
2372 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2373 ch_free( qm->attr_sets[num].attrs );
2374 qm->attr_sets[num].attrs = NULL;
2375 qm->attr_sets[num].count = 0;
2378 if ( strcmp( c->argv[i], LDAP_ALL_USER_ATTRIBUTES ) == 0 ) {
2380 BER_BVSTR( &attr_name->an_name, LDAP_ALL_USER_ATTRIBUTES );
2381 } else if ( strcmp( c->argv[i], LDAP_ALL_OPERATIONAL_ATTRIBUTES ) == 0 ) {
2383 BER_BVSTR( &attr_name->an_name, LDAP_ALL_OPERATIONAL_ATTRIBUTES );
2385 if ( slap_str2ad( c->argv[i], &attr_name->an_desc, &text ) ) {
2386 strcpy( c->cr_msg, text );
2387 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2388 ch_free( qm->attr_sets[num].attrs );
2389 qm->attr_sets[num].attrs = NULL;
2390 qm->attr_sets[num].count = 0;
2393 attr_name->an_name = attr_name->an_desc->ad_cname;
2395 attr_name->an_oc = NULL;
2396 attr_name->an_oc_exclude = 0;
2397 if ( attr_name->an_desc == slap_schema.si_ad_objectClass )
2398 qm->attr_sets[num].flags |= PC_GOT_OC;
2400 BER_BVZERO( &attr_name->an_name );
2403 /* warn if list contains both "*" and "+" */
2404 if ( i > 4 && all_user && all_op ) {
2405 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2406 "warning: attribute list contains \"*\" and \"+\"" );
2407 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2412 if ( cm->numattrsets == 0 ) {
2413 snprintf( c->cr_msg, sizeof( c->cr_msg ), "\"proxycache\" directive not provided yet" );
2414 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2417 if ( lutil_atoi( &i, c->argv[2] ) != 0 ) {
2418 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template #=\"%s\"",
2420 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2424 if ( i < 0 || i >= cm->numattrsets ||
2425 !(qm->attr_sets[i].flags & PC_CONFIGURED )) {
2426 snprintf( c->cr_msg, sizeof( c->cr_msg ), "template index %d invalid (%s%d)",
2427 i, cm->numattrsets > 1 ? "0->" : "", cm->numattrsets - 1 );
2428 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2431 temp = ch_calloc( 1, sizeof( QueryTemplate ));
2432 temp->qmnext = qm->templates;
2433 qm->templates = temp;
2434 ldap_pvt_thread_rdwr_init( &temp->t_rwlock );
2435 temp->query = temp->query_last = NULL;
2436 if ( lutil_parse_time( c->argv[3], &t ) != 0 ) {
2437 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unable to parse template ttl=\"%s\"",
2439 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2442 temp->ttl = (time_t)t;
2443 if ( c->argc == 5 ) {
2444 if ( lutil_parse_time( c->argv[4], &t ) != 0 ) {
2445 snprintf( c->cr_msg, sizeof( c->cr_msg ),
2446 "unable to parse template negttl=\"%s\"",
2448 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2451 temp->negttl = (time_t)t;
2456 temp->no_of_queries = 0;
2458 ber_str2bv( c->argv[1], 0, 1, &temp->querystr );
2459 Debug( pcache_debug, "Template:\n", 0, 0, 0 );
2460 Debug( pcache_debug, " query template: %s\n",
2461 temp->querystr.bv_val, 0, 0 );
2462 temp->attr_set_index = i;
2463 qm->attr_sets[i].flags |= PC_REFERENCED;
2464 temp->qtnext = qm->attr_sets[i].templates;
2465 qm->attr_sets[i].templates = temp;
2466 Debug( pcache_debug, " attributes: \n", 0, 0, 0 );
2467 if ( ( attrarray = qm->attr_sets[i].attrs ) != NULL ) {
2468 for ( i=0; attrarray[i].an_name.bv_val; i++ )
2469 Debug( pcache_debug, "\t%s\n",
2470 attrarray[i].an_name.bv_val, 0, 0 );
2474 if ( strcasecmp( c->argv[1], "head" ) == 0 ) {
2475 cm->response_cb = PCACHE_RESPONSE_CB_HEAD;
2477 } else if ( strcasecmp( c->argv[1], "tail" ) == 0 ) {
2478 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2481 snprintf( c->cr_msg, sizeof( c->cr_msg ), "unknown specifier" );
2482 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2487 if ( c->value_int <= 0 ) {
2488 snprintf( c->cr_msg, sizeof( c->cr_msg ), "max queries must be positive" );
2489 Debug( LDAP_DEBUG_CONFIG, "%s: %s.\n", c->log, c->cr_msg, 0 );
2492 cm->max_queries = c->value_int;
2507 slap_overinst *on = (slap_overinst *)be->bd_info;
2508 cache_manager* cm = on->on_bi.bi_private;
2510 /* Something for the cache database? */
2511 if ( cm->db.bd_info && cm->db.bd_info->bi_db_config )
2512 return cm->db.bd_info->bi_db_config( &cm->db, fname, lineno,
2514 return SLAP_CONF_UNKNOWN;
2522 slap_overinst *on = (slap_overinst *)be->bd_info;
2526 cm = (cache_manager *)ch_malloc(sizeof(cache_manager));
2527 on->on_bi.bi_private = cm;
2529 qm = (query_manager*)ch_malloc(sizeof(query_manager));
2532 SLAP_DBFLAGS(&cm->db) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2533 cm->db.be_private = NULL;
2534 cm->db.be_pcl_mutexp = &cm->db.be_pcl_mutex;
2536 cm->numattrsets = 0;
2537 cm->num_entries_limit = 5;
2538 cm->num_cached_queries = 0;
2539 cm->max_entries = 0;
2540 cm->cur_entries = 0;
2541 cm->max_queries = 10000;
2542 cm->response_cb = PCACHE_RESPONSE_CB_TAIL;
2543 cm->cc_period = 1000;
2546 qm->attr_sets = NULL;
2547 qm->templates = NULL;
2549 qm->lru_bottom = NULL;
2551 qm->qcfunc = query_containment;
2552 qm->crfunc = cache_replacement;
2553 qm->addfunc = add_query;
2554 ldap_pvt_thread_mutex_init(&qm->lru_mutex);
2556 ldap_pvt_thread_mutex_init(&cm->cache_mutex);
2561 pcache_cachedquery_open_cb( Operation *op, SlapReply *rs )
2563 assert( op->o_tag == LDAP_REQ_SEARCH );
2565 if ( rs->sr_type == REP_SEARCH ) {
2568 a = attr_find( rs->sr_entry->e_attrs, ad_cachedQueryURL );
2572 assert( a->a_nvals != NULL );
2574 valsp = op->o_callback->sc_private;
2575 assert( *valsp == NULL );
2577 ber_bvarray_dup_x( valsp, a->a_nvals, op->o_tmpmemctx );
2589 slap_overinst *on = (slap_overinst *)be->bd_info;
2590 cache_manager *cm = on->on_bi.bi_private;
2591 query_manager* qm = cm->qm;
2592 int i, ncf = 0, rf = 0, nrf = 0, rc = 0;
2594 /* check attr sets */
2595 for ( i = 0; i < cm->numattrsets; i++) {
2596 if ( !( qm->attr_sets[i].flags & PC_CONFIGURED ) ) {
2597 if ( qm->attr_sets[i].flags & PC_REFERENCED ) {
2598 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d not configured but referenced.\n", i, 0, 0 );
2602 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, attr set #%d not configured.\n", i, 0, 0 );
2606 } else if ( !( qm->attr_sets[i].flags & PC_REFERENCED ) ) {
2607 Debug( LDAP_DEBUG_CONFIG, "pcache: attr set #%d configured but not referenced.\n", i, 0, 0 );
2612 if ( ncf || rf || nrf ) {
2613 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets configured but not referenced.\n", nrf, 0, 0 );
2614 Debug( LDAP_DEBUG_CONFIG, "pcache: warning, %d attr sets not configured.\n", ncf, 0, 0 );
2615 Debug( LDAP_DEBUG_CONFIG, "pcache: %d attr sets not configured but referenced.\n", rf, 0, 0 );
2622 /* need to inherit something from the original database... */
2623 cm->db.be_def_limit = be->be_def_limit;
2624 cm->db.be_limits = be->be_limits;
2625 cm->db.be_acl = be->be_acl;
2626 cm->db.be_dfltaccess = be->be_dfltaccess;
2628 if ( SLAP_DBMONITORING( be ) ) {
2629 SLAP_DBFLAGS( &cm->db ) |= SLAP_DBFLAG_MONITORING;
2632 SLAP_DBFLAGS( &cm->db ) &= ~SLAP_DBFLAG_MONITORING;
2635 rc = backend_startup_one( &cm->db, NULL );
2637 /* There is no runqueue in TOOL mode */
2638 if ( slapMode & SLAP_SERVER_MODE ) {
2639 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2640 ldap_pvt_runqueue_insert( &slapd_rq, cm->cc_period,
2641 consistency_check, on,
2642 "pcache_consistency", be->be_suffix[0].bv_val );
2643 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2645 /* Cached database must have the rootdn */
2646 if ( BER_BVISNULL( &cm->db.be_rootndn )
2647 || BER_BVISEMPTY( &cm->db.be_rootndn ) )
2649 Debug( LDAP_DEBUG_ANY, "pcache_db_open(): "
2650 "underlying database of type \"%s\"\n"
2651 " serving naming context \"%s\"\n"
2652 " has no \"rootdn\", required by \"proxycache\".\n",
2653 on->on_info->oi_orig->bi_type,
2654 cm->db.be_suffix[0].bv_val, 0 );
2658 if ( cm->save_queries ) {
2659 void *thrctx = ldap_pvt_thread_pool_context();
2660 Connection conn = { 0 };
2661 OperationBuffer opbuf;
2663 slap_callback cb = { 0 };
2664 SlapReply rs = { 0 };
2665 BerVarray vals = NULL;
2666 AttributeName attrs[ 2 ] = { 0 };
2668 connection_fake_init( &conn, &opbuf, thrctx );
2673 op->o_tag = LDAP_REQ_SEARCH;
2674 op->o_protocol = LDAP_VERSION3;
2675 cb.sc_response = pcache_cachedquery_open_cb;
2676 cb.sc_private = &vals;
2677 op->o_callback = &cb;
2678 op->o_time = slap_get_time();
2679 op->o_do_not_cache = 1;
2680 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2682 op->o_dn = cm->db.be_rootdn;
2683 op->o_ndn = cm->db.be_rootndn;
2684 op->o_req_dn = cm->db.be_suffix[ 0 ];
2685 op->o_req_ndn = cm->db.be_nsuffix[ 0 ];
2687 op->ors_scope = LDAP_SCOPE_BASE;
2688 op->ors_deref = LDAP_DEREF_NEVER;
2690 op->ors_tlimit = SLAP_NO_LIMIT;
2691 ber_str2bv( "(cachedQueryURL=*)", 0, 0, &op->ors_filterstr );
2692 op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
2693 if ( op->ors_filter != NULL ) {
2694 attrs[ 0 ].an_desc = ad_cachedQueryURL;
2695 attrs[ 0 ].an_name = ad_cachedQueryURL->ad_cname;
2696 op->ors_attrs = attrs;
2697 op->ors_attrsonly = 0;
2699 rc = op->o_bd->be_search( op, &rs );
2700 if ( rc == LDAP_SUCCESS && vals != NULL ) {
2703 for ( i = 0; !BER_BVISNULL( &vals[ i ] ); i++ ) {
2704 if ( url2query( vals[ i ].bv_val, op, qm ) == 0 ) {
2705 cm->num_cached_queries++;
2709 ber_bvarray_free_x( vals, op->o_tmpmemctx );
2712 filter_free_x( op, op->ors_filter );
2724 pcache_free_qbase( void *v )
2730 tavl_free( qb->scopes[i], NULL );
2740 slap_overinst *on = (slap_overinst *)be->bd_info;
2741 cache_manager *cm = on->on_bi.bi_private;
2742 query_manager *qm = cm->qm;
2746 if ( cm->save_queries && qm->templates != NULL ) {
2748 BerVarray vals = NULL;
2750 for ( tm = qm->templates; tm != NULL; tm = tm->qmnext ) {
2751 for ( qc = tm->query; qc; qc = qc->next ) {
2754 if ( query2url( qc, &bv ) == 0 ) {
2755 ber_bvarray_add( &vals, &bv );
2760 if ( vals != NULL ) {
2761 void *thrctx = ldap_pvt_thread_pool_context();
2762 Connection conn = { 0 };
2763 OperationBuffer opbuf;
2765 slap_callback cb = { 0 };
2767 SlapReply rs = { REP_RESULT };
2768 Modifications mod = { 0 };
2770 connection_fake_init( &conn, &opbuf, thrctx );
2774 op->o_dn = cm->db.be_rootdn;
2775 op->o_ndn = cm->db.be_rootndn;
2777 op->o_tag = LDAP_REQ_MODIFY;
2778 op->o_protocol = LDAP_VERSION3;
2779 cb.sc_response = slap_null_cb;
2780 op->o_callback = &cb;
2781 op->o_time = slap_get_time();
2782 op->o_do_not_cache = 1;
2783 op->o_managedsait = SLAP_CONTROL_CRITICAL;
2785 op->o_req_dn = op->o_bd->be_suffix[0];
2786 op->o_req_ndn = op->o_bd->be_nsuffix[0];
2788 mod.sml_op = LDAP_MOD_REPLACE;
2790 mod.sml_desc = ad_cachedQueryURL;
2791 mod.sml_type = ad_cachedQueryURL->ad_cname;
2792 mod.sml_values = vals;
2793 mod.sml_nvalues = NULL;
2794 mod.sml_next = NULL;
2795 Debug( pcache_debug,
2796 "SETTING CACHED QUERY URLS\n",
2799 op->orm_modlist = &mod;
2801 op->o_bd->be_modify( op, &rs );
2803 ber_bvarray_free( vals );
2807 /* cleanup stuff inherited from the original database... */
2808 cm->db.be_limits = NULL;
2809 cm->db.be_acl = NULL;
2811 if ( cm->db.bd_info->bi_db_close ) {
2812 rc = cm->db.bd_info->bi_db_close( &cm->db, NULL );
2814 while ( (tm = qm->templates) != NULL ) {
2815 CachedQuery *qc, *qn;
2816 qm->templates = tm->qmnext;
2817 for ( qc = tm->query; qc; qc = qn ) {
2821 avl_free( tm->qbase, pcache_free_qbase );
2822 free( tm->querystr.bv_val );
2823 ldap_pvt_thread_rdwr_destroy( &tm->t_rwlock );
2824 free( tm->t_attrs.attrs );
2828 for ( i=0; i<cm->numattrsets; i++ ) {
2829 free( qm->attr_sets[i].attrs );
2831 free( qm->attr_sets );
2832 qm->attr_sets = NULL;
2843 slap_overinst *on = (slap_overinst *)be->bd_info;
2844 cache_manager *cm = on->on_bi.bi_private;
2845 query_manager *qm = cm->qm;
2847 if ( cm->db.be_private != NULL ) {
2848 backend_stopdown_one( &cm->db );
2851 ldap_pvt_thread_mutex_destroy( &qm->lru_mutex );
2852 ldap_pvt_thread_mutex_destroy( &cm->cache_mutex );
2859 static slap_overinst pcache;
2861 static char *obsolete_names[] = {
2866 int pcache_initialize()
2869 struct berval debugbv = BER_BVC("pcache");
2871 code = slap_loglevel_get( &debugbv, &pcache_debug );
2876 for ( i = 0; as[i].desc != NULL; i++ ) {
2877 code = register_at( as[i].desc, as[i].adp, 0 );
2879 Debug( LDAP_DEBUG_ANY,
2880 "pcache_initialize: register_at #%d failed\n", i, 0, 0 );
2885 pcache.on_bi.bi_type = "pcache";
2886 pcache.on_bi.bi_obsolete_names = obsolete_names;
2887 pcache.on_bi.bi_db_init = pcache_db_init;
2888 pcache.on_bi.bi_db_config = pcache_db_config;
2889 pcache.on_bi.bi_db_open = pcache_db_open;
2890 pcache.on_bi.bi_db_close = pcache_db_close;
2891 pcache.on_bi.bi_db_destroy = pcache_db_destroy;
2893 pcache.on_bi.bi_op_search = pcache_op_search;
2895 pcache.on_bi.bi_chk_controls = pcache_chk_controls;
2897 pcache.on_bi.bi_cf_ocs = pcocs;
2899 code = config_register_schema( pccfg, pcocs );
2900 if ( code ) return code;
2902 return overlay_register( &pcache );
2905 #if SLAPD_OVER_PROXYCACHE == SLAPD_MOD_DYNAMIC
2906 int init_module(int argc, char *argv[]) {
2907 return pcache_initialize();
2911 #endif /* defined(SLAPD_OVER_PROXYCACHE) */