2 Unix SMB/CIFS implementation.
4 Generic, persistent and shared between processes cache mechanism for use
5 by various parts of the Samba code
7 Copyright (C) Rafal Szczesniak 2002
8 Copyright (C) Volker Lendecke 2009
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "lib/gencache.h"
26 #include "system/filesys.h"
27 #include "system/glob.h"
29 #include "tdb_wrap/tdb_wrap.h"
32 #define DBGC_CLASS DBGC_TDB
34 #define CACHE_DATA_FMT "%12u/"
36 static struct tdb_wrap
*cache
;
37 static struct tdb_wrap
*cache_notrans
;
41 * @brief Generic, persistent and shared between processes cache mechanism
42 * for use by various parts of the Samba code
46 struct gencache_timeout
{
50 bool gencache_timeout_expired(const struct gencache_timeout
*t
)
52 return t
->timeout
<= time(NULL
);
56 * Cache initialisation function. Opens cache tdb file or creates
57 * it if does not exist.
59 * @return true on successful initialisation of the cache or
63 static bool gencache_init(void)
65 char* cache_fname
= NULL
;
66 int open_flags
= O_RDWR
|O_CREAT
;
69 /* skip file open if it's already opened */
74 hash_size
= lp_parm_int(-1, "gencache", "hash_size", 10000);
76 cache_fname
= cache_path(talloc_tos(), "gencache.tdb");
77 if (cache_fname
== NULL
) {
81 DEBUG(5, ("Opening cache file at %s\n", cache_fname
));
83 cache
= tdb_wrap_open(NULL
, cache_fname
, hash_size
,
84 TDB_DEFAULT
|TDB_INCOMPATIBLE_HASH
,
87 if (!cache
&& (errno
== EACCES
)) {
88 open_flags
= O_RDONLY
;
89 cache
= tdb_wrap_open(NULL
, cache_fname
, hash_size
,
90 TDB_DEFAULT
|TDB_INCOMPATIBLE_HASH
,
93 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname
));
96 TALLOC_FREE(cache_fname
);
99 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
103 cache_fname
= lock_path(talloc_tos(), "gencache_notrans.tdb");
104 if (cache_fname
== NULL
) {
109 DEBUG(5, ("Opening cache file at %s\n", cache_fname
));
111 cache_notrans
= tdb_wrap_open(NULL
, cache_fname
, hash_size
,
113 TDB_INCOMPATIBLE_HASH
|
117 if (cache_notrans
== NULL
) {
118 DEBUG(5, ("Opening %s failed: %s\n", cache_fname
,
120 TALLOC_FREE(cache_fname
);
124 TALLOC_FREE(cache_fname
);
129 static TDB_DATA
last_stabilize_key(void)
131 const char key
[] = "@LAST_STABILIZED";
134 .dptr
= discard_const_p(uint8_t, key
),
135 .dsize
= sizeof(key
),
139 struct gencache_have_val_state
{
141 const DATA_BLOB
*data
;
145 static void gencache_have_val_parser(const struct gencache_timeout
*old_timeout
,
149 struct gencache_have_val_state
*state
=
150 (struct gencache_have_val_state
*)private_data
;
151 time_t now
= time(NULL
);
152 int cache_time_left
, new_time_left
, additional_time
;
155 * Excuse the many variables, but these time calculations are
156 * confusing to me. We do not want to write to gencache with a
157 * possibly expensive transaction if we are about to write the same
158 * value, just extending the remaining timeout by less than 10%.
161 cache_time_left
= old_timeout
->timeout
- now
;
162 if (cache_time_left
<= 0) {
164 * timed out, write new value
169 new_time_left
= state
->new_timeout
- now
;
170 if (new_time_left
<= 0) {
172 * Huh -- no new timeout?? Write it.
177 if (new_time_left
< cache_time_left
) {
179 * Someone wants to shorten the timeout. Let it happen.
185 * By how much does the new timeout extend the remaining cache time?
187 additional_time
= new_time_left
- cache_time_left
;
189 if (additional_time
* 10 < 0) {
191 * Integer overflow. We extend by so much that we have to write it.
197 * The comparison below is essentially equivalent to
199 * new_time_left > cache_time_left * 1.10
201 * but without floating point calculations.
204 if (additional_time
* 10 > cache_time_left
) {
206 * We extend the cache timeout by more than 10%. Do it.
212 * Now the more expensive data compare.
214 if (data_blob_cmp(state
->data
, &data
) != 0) {
216 * Write a new value. Certainly do it.
222 * Extending the timeout by less than 10% for the same cache value is
223 * not worth the trouble writing a value into gencache under a
224 * possibly expensive transaction.
229 static bool gencache_have_val(const char *keystr
, const DATA_BLOB
*data
,
232 struct gencache_have_val_state state
;
234 state
.new_timeout
= timeout
;
238 if (!gencache_parse(keystr
, gencache_have_val_parser
, &state
)) {
244 static int last_stabilize_parser(TDB_DATA key
, TDB_DATA data
,
247 time_t *last_stabilize
= private_data
;
249 if ((data
.dsize
!= 0) && (data
.dptr
[data
.dsize
-1] == '\0')) {
250 *last_stabilize
= atoi((char *)data
.dptr
);
256 * Set an entry in the cache file. If there's no such
259 * @param keystr string that represents a key of this entry
260 * @param blob DATA_BLOB value being cached
261 * @param timeout time when the value is expired
263 * @retval true when entry is successfully stored
264 * @retval false on failure
267 bool gencache_set_data_blob(const char *keystr
, DATA_BLOB blob
,
274 time_t last_stabilize
;
275 static int writecount
;
278 if ((keystr
== NULL
) || (blob
.data
== NULL
)) {
282 key
= string_term_tdb_data(keystr
);
284 ret
= tdb_data_cmp(key
, last_stabilize_key());
286 DEBUG(10, ("Can't store %s as a key\n", keystr
));
290 if (!gencache_init()) {
294 if ((timeout
!= 0) && gencache_have_val(keystr
, &blob
, timeout
)) {
295 DEBUG(10, ("Did not store value for %s, we already got it\n",
300 hdr_len
= fstr_sprintf(hdr
, CACHE_DATA_FMT
, (int)timeout
);
306 dbufs
[0] = (TDB_DATA
) { .dptr
= (uint8_t *)hdr
, .dsize
= hdr_len
};
307 dbufs
[1] = (TDB_DATA
) { .dptr
= blob
.data
, .dsize
= blob
.length
};
309 DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
310 "[%s] (%d seconds %s)\n", keystr
,
311 timestring(talloc_tos(), timeout
),
312 (int)(timeout
- time(NULL
)),
313 timeout
> time(NULL
) ? "ahead" : "in the past"));
315 ret
= tdb_storev(cache_notrans
->tdb
, key
, dbufs
, 2, 0);
321 * Every 100 writes within a single process, stabilize the cache with
322 * a transaction. This is done to prevent a single transaction to
323 * become huge and chew lots of memory.
326 if (writecount
> lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
327 gencache_stabilize();
333 * Every 5 minutes, call gencache_stabilize() to not let grow
334 * gencache_notrans.tdb too large.
339 tdb_parse_record(cache_notrans
->tdb
, last_stabilize_key(),
340 last_stabilize_parser
, &last_stabilize
);
343 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
345 gencache_stabilize();
352 static void gencache_del_parser(const struct gencache_timeout
*t
,
356 if (t
->timeout
!= 0) {
357 bool *exists
= private_data
;
363 * Delete one entry from the cache file.
365 * @param keystr string that represents a key of this entry
367 * @retval true upon successful deletion
368 * @retval false in case of failure
371 bool gencache_del(const char *keystr
)
373 TDB_DATA key
= string_term_tdb_data(keystr
);
378 if (keystr
== NULL
) {
382 if (!gencache_init()) {
386 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr
));
388 ret
= tdb_chainlock(cache_notrans
->tdb
, key
);
393 gencache_parse(keystr
, gencache_del_parser
, &exists
);
397 * We delete an element by setting its timeout to
398 * 0. This way we don't have to do a transaction on
399 * gencache.tdb every time we delete an element.
401 result
= gencache_set(keystr
, "", 0);
404 tdb_chainunlock(cache_notrans
->tdb
, key
);
409 static bool gencache_pull_timeout(TDB_DATA data
, time_t *pres
, DATA_BLOB
*payload
)
415 if (data
.dptr
== NULL
) {
418 slash
= memchr(data
.dptr
, '/', data
.dsize
);
423 res
= strtol((char *)data
.dptr
, &endptr
, 10);
425 if ((endptr
== NULL
) || (*endptr
!= '/')) {
426 DBG_WARNING("Invalid gencache data format\n");
432 if (payload
!= NULL
) {
434 *payload
= (DATA_BLOB
) {
435 .data
= discard_const_p(uint8_t, endptr
),
436 .length
= data
.dsize
- PTR_DIFF(endptr
, data
.dptr
),
442 struct gencache_parse_state
{
443 void (*parser
)(const struct gencache_timeout
*timeout
,
447 bool copy_to_notrans
;
450 static int gencache_parse_fn(TDB_DATA key
, TDB_DATA data
, void *private_data
)
452 struct gencache_parse_state
*state
;
453 struct gencache_timeout t
;
457 ret
= gencache_pull_timeout(data
, &t
.timeout
, &payload
);
461 state
= (struct gencache_parse_state
*)private_data
;
462 state
->parser(&t
, payload
, state
->private_data
);
464 if (state
->copy_to_notrans
) {
465 tdb_store(cache_notrans
->tdb
, key
, data
, 0);
471 bool gencache_parse(const char *keystr
,
472 void (*parser
)(const struct gencache_timeout
*timeout
,
477 struct gencache_parse_state state
;
478 TDB_DATA key
= string_term_tdb_data(keystr
);
481 if (keystr
== NULL
) {
484 if (tdb_data_cmp(key
, last_stabilize_key()) == 0) {
487 if (!gencache_init()) {
491 state
.parser
= parser
;
492 state
.private_data
= private_data
;
493 state
.copy_to_notrans
= false;
495 ret
= tdb_chainlock(cache_notrans
->tdb
, key
);
500 ret
= tdb_parse_record(cache_notrans
->tdb
, key
,
501 gencache_parse_fn
, &state
);
503 tdb_chainunlock(cache_notrans
->tdb
, key
);
507 state
.copy_to_notrans
= true;
509 ret
= tdb_parse_record(cache
->tdb
, key
, gencache_parse_fn
, &state
);
511 if ((ret
== -1) && (tdb_error(cache
->tdb
) == TDB_ERR_NOEXIST
)) {
513 * The record does not exist. Set a delete-marker in
514 * gencache_notrans, so that we don't have to look at
515 * the fcntl-based cache again.
517 gencache_set(keystr
, "", 0);
520 tdb_chainunlock(cache_notrans
->tdb
, key
);
525 struct gencache_get_data_blob_state
{
532 static void gencache_get_data_blob_parser(const struct gencache_timeout
*t
,
536 struct gencache_get_data_blob_state
*state
=
537 (struct gencache_get_data_blob_state
*)private_data
;
539 if (t
->timeout
== 0) {
540 state
->result
= false;
543 state
->timeout
= t
->timeout
;
545 if (state
->blob
== NULL
) {
546 state
->result
= true;
550 *state
->blob
= data_blob_talloc(state
->mem_ctx
, blob
.data
,
552 if (state
->blob
->data
== NULL
) {
553 state
->result
= false;
556 state
->result
= true;
560 * Get existing entry from the cache file.
562 * @param keystr string that represents a key of this entry
563 * @param blob DATA_BLOB that is filled with entry's blob
564 * @param timeout pointer to a time_t that is filled with entry's
567 * @retval true when entry is successfully fetched
568 * @retval false for failure
571 bool gencache_get_data_blob(const char *keystr
, TALLOC_CTX
*mem_ctx
,
573 time_t *timeout
, bool *was_expired
)
575 struct gencache_get_data_blob_state state
;
576 bool expired
= false;
578 state
.result
= false;
579 state
.mem_ctx
= mem_ctx
;
582 if (!gencache_parse(keystr
, gencache_get_data_blob_parser
, &state
)) {
588 if (state
.timeout
<= time(NULL
)) {
590 * We're expired, delete the entry. We can't use gencache_del
591 * here, because that uses gencache_get_data_blob for checking
592 * the existence of a record. We know the thing exists and
593 * directly store an empty value with 0 timeout.
595 gencache_set(keystr
, "", 0);
600 *timeout
= state
.timeout
;
606 if (was_expired
!= NULL
) {
607 *was_expired
= expired
;
609 if (state
.result
&& state
.blob
) {
610 data_blob_free(state
.blob
);
615 struct stabilize_state
{
618 static int stabilize_fn(struct tdb_context
*tdb
, TDB_DATA key
, TDB_DATA val
,
624 * Migrate the clear-if-first gencache data to the stable,
625 * transaction-based gencache.tdb
628 bool gencache_stabilize(void)
630 struct stabilize_state state
;
634 if (!gencache_init()) {
638 res
= tdb_transaction_start_nonblock(cache
->tdb
);
640 if (tdb_error(cache
->tdb
) == TDB_ERR_NOLOCK
)
643 * Someone else already does the stabilize,
644 * this does not have to be done twice
649 DEBUG(10, ("Could not start transaction on gencache.tdb: "
650 "%s\n", tdb_errorstr(cache
->tdb
)));
654 res
= tdb_lockall_nonblock(cache_notrans
->tdb
);
656 tdb_transaction_cancel(cache
->tdb
);
657 DEBUG(10, ("Could not get allrecord lock on "
658 "gencache_notrans.tdb: %s\n",
659 tdb_errorstr(cache_notrans
->tdb
)));
663 state
.written
= false;
665 res
= tdb_traverse(cache_notrans
->tdb
, stabilize_fn
, &state
);
667 tdb_unlockall(cache_notrans
->tdb
);
668 tdb_transaction_cancel(cache
->tdb
);
672 if (!state
.written
) {
673 tdb_unlockall(cache_notrans
->tdb
);
674 tdb_transaction_cancel(cache
->tdb
);
678 res
= tdb_transaction_commit(cache
->tdb
);
680 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
681 "%s\n", tdb_errorstr(cache
->tdb
)));
682 tdb_unlockall(cache_notrans
->tdb
);
686 res
= tdb_wipe_all(cache_notrans
->tdb
);
688 DBG_DEBUG("tdb_wipe_all on gencache_notrans.tdb failed: %s\n",
689 tdb_errorstr(cache_notrans
->tdb
));
692 now
= talloc_asprintf(talloc_tos(), "%d", (int)time(NULL
));
694 tdb_store(cache_notrans
->tdb
, last_stabilize_key(),
695 string_term_tdb_data(now
), 0);
699 res
= tdb_unlockall(cache_notrans
->tdb
);
701 DEBUG(10, ("tdb_unlockall on gencache.tdb failed: "
702 "%s\n", tdb_errorstr(cache
->tdb
)));
709 static int stabilize_fn(struct tdb_context
*tdb
, TDB_DATA key
, TDB_DATA val
,
712 struct stabilize_state
*state
= (struct stabilize_state
*)priv
;
716 if (tdb_data_cmp(key
, last_stabilize_key()) == 0) {
720 if (!gencache_pull_timeout(val
, &timeout
, NULL
)) {
721 DEBUG(10, ("Ignoring invalid entry\n"));
724 if ((timeout
< time(NULL
)) || (val
.dsize
== 0)) {
725 res
= tdb_delete(cache
->tdb
, key
);
727 state
->written
= true;
728 } else if (tdb_error(cache
->tdb
) == TDB_ERR_NOEXIST
) {
732 res
= tdb_store(cache
->tdb
, key
, val
, 0);
734 state
->written
= true;
739 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
740 tdb_errorstr(cache
->tdb
)));
748 * Get existing entry from the cache file.
750 * @param keystr string that represents a key of this entry
751 * @param valstr buffer that is allocated and filled with the entry value
752 * buffer's disposing must be done outside
753 * @param timeout pointer to a time_t that is filled with entry's
756 * @retval true when entry is successfully fetched
757 * @retval false for failure
760 bool gencache_get(const char *keystr
, TALLOC_CTX
*mem_ctx
, char **value
,
766 ret
= gencache_get_data_blob(keystr
, mem_ctx
, &blob
, ptimeout
, NULL
);
770 if ((blob
.data
== NULL
) || (blob
.length
== 0)) {
771 data_blob_free(&blob
);
774 if (blob
.data
[blob
.length
-1] != '\0') {
775 /* Not NULL terminated, can't be a string */
776 data_blob_free(&blob
);
781 * talloc_move generates a type-punned warning here. As we
782 * leave the function immediately, do a simple talloc_steal.
784 *value
= (char *)talloc_steal(mem_ctx
, blob
.data
);
787 data_blob_free(&blob
);
792 * Set an entry in the cache file. If there's no such
795 * @param keystr string that represents a key of this entry
796 * @param value text representation value being cached
797 * @param timeout time when the value is expired
799 * @retval true when entry is successfully stored
800 * @retval false on failure
803 bool gencache_set(const char *keystr
, const char *value
, time_t timeout
)
805 DATA_BLOB blob
= data_blob_const(value
, strlen(value
)+1);
806 return gencache_set_data_blob(keystr
, blob
, timeout
);
809 struct gencache_iterate_blobs_state
{
810 void (*fn
)(const char *key
, DATA_BLOB value
,
811 time_t timeout
, void *private_data
);
817 static int gencache_iterate_blobs_fn(struct tdb_context
*tdb
, TDB_DATA key
,
818 TDB_DATA data
, void *priv
)
820 struct gencache_iterate_blobs_state
*state
=
821 (struct gencache_iterate_blobs_state
*)priv
;
823 char *free_key
= NULL
;
827 if (tdb_data_cmp(key
, last_stabilize_key()) == 0) {
830 if (state
->in_persistent
&& tdb_exists(cache_notrans
->tdb
, key
)) {
834 if (key
.dptr
[key
.dsize
-1] == '\0') {
835 keystr
= (char *)key
.dptr
;
837 /* ensure 0-termination */
838 keystr
= talloc_strndup(talloc_tos(), (char *)key
.dptr
, key
.dsize
);
840 if (keystr
== NULL
) {
845 if (!gencache_pull_timeout(data
, &timeout
, &payload
)) {
854 if (fnmatch(state
->pattern
, keystr
, 0) != 0) {
858 DEBUG(10, ("Calling function with arguments "
859 "(key=[%s], timeout=[%s])\n",
860 keystr
, timestring(talloc_tos(), timeout
)));
862 state
->fn(keystr
, payload
, timeout
, state
->private_data
);
865 TALLOC_FREE(free_key
);
869 void gencache_iterate_blobs(void (*fn
)(const char *key
, DATA_BLOB value
,
870 time_t timeout
, void *private_data
),
871 void *private_data
, const char *pattern
)
873 struct gencache_iterate_blobs_state state
;
875 if ((fn
== NULL
) || (pattern
== NULL
) || !gencache_init()) {
879 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern
));
882 state
.pattern
= pattern
;
883 state
.private_data
= private_data
;
885 state
.in_persistent
= false;
886 tdb_traverse(cache_notrans
->tdb
, gencache_iterate_blobs_fn
, &state
);
888 state
.in_persistent
= true;
889 tdb_traverse(cache
->tdb
, gencache_iterate_blobs_fn
, &state
);
893 * Iterate through all entries which key matches to specified pattern
895 * @param fn pointer to the function that will be supplied with each single
896 * matching cache entry (key, value and timeout) as an arguments
897 * @param data void pointer to an arbitrary data that is passed directly to the fn
898 * function on each call
899 * @param keystr_pattern pattern the existing entries' keys are matched to
903 struct gencache_iterate_state
{
904 void (*fn
)(const char *key
, const char *value
, time_t timeout
,
909 static void gencache_iterate_fn(const char *key
, DATA_BLOB value
,
910 time_t timeout
, void *private_data
)
912 struct gencache_iterate_state
*state
=
913 (struct gencache_iterate_state
*)private_data
;
915 char *free_val
= NULL
;
917 if (value
.data
[value
.length
-1] == '\0') {
918 valstr
= (char *)value
.data
;
920 /* ensure 0-termination */
921 valstr
= talloc_strndup(talloc_tos(), (char *)value
.data
, value
.length
);
923 if (valstr
== NULL
) {
928 DEBUG(10, ("Calling function with arguments "
929 "(key=[%s], value=[%s], timeout=[%s])\n",
930 key
, valstr
, timestring(talloc_tos(), timeout
)));
932 state
->fn(key
, valstr
, timeout
, state
->private_data
);
936 TALLOC_FREE(free_val
);
939 void gencache_iterate(void (*fn
)(const char *key
, const char *value
,
940 time_t timeout
, void *dptr
),
941 void *private_data
, const char *pattern
)
943 struct gencache_iterate_state state
;
949 state
.private_data
= private_data
;
950 gencache_iterate_blobs(gencache_iterate_fn
, &state
, pattern
);