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 "system/filesys.h"
26 #include "system/glob.h"
28 #include "tdb_wrap/tdb_wrap.h"
31 #define DBGC_CLASS DBGC_TDB
33 #define CACHE_DATA_FMT "%12u/"
35 static struct tdb_wrap *cache;
36 static struct tdb_wrap *cache_notrans;
40 * @brief Generic, persistent and shared between processes cache mechanism
41 * for use by various parts of the Samba code
47 * Cache initialisation function. Opens cache tdb file or creates
48 * it if does not exist.
50 * @return true on successful initialisation of the cache or
54 static bool gencache_init(void)
56 char* cache_fname = NULL;
57 int open_flags = O_RDWR|O_CREAT;
59 /* skip file open if it's already opened */
64 cache_fname = cache_path("gencache.tdb");
65 if (cache_fname == NULL) {
69 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
71 cache = tdb_wrap_open(NULL, cache_fname, 0,
72 TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
76 ret = tdb_check(cache->tdb, NULL, NULL);
81 * Retry with CLEAR_IF_FIRST.
83 * Warning: Converting this to dbwrap won't work
84 * directly. gencache.c does transactions on this tdb,
85 * and dbwrap forbids this for CLEAR_IF_FIRST
86 * databases. tdb does allow transactions on
87 * CLEAR_IF_FIRST databases, so lets use it here to
88 * clean up a broken database.
90 cache = tdb_wrap_open(NULL, cache_fname, 0,
92 TDB_INCOMPATIBLE_HASH|
98 if (!cache && (errno == EACCES)) {
99 open_flags = O_RDONLY;
100 cache = tdb_wrap_open(NULL, cache_fname, 0,
101 TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
104 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
107 TALLOC_FREE(cache_fname);
110 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
114 cache_fname = lock_path("gencache_notrans.tdb");
115 if (cache_fname == NULL) {
120 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
122 cache_notrans = tdb_wrap_open(NULL, cache_fname, 0,
124 TDB_INCOMPATIBLE_HASH|
128 if (cache_notrans == NULL) {
129 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
131 TALLOC_FREE(cache_fname);
135 TALLOC_FREE(cache_fname);
140 static TDB_DATA last_stabilize_key(void)
143 result.dptr = discard_const_p(uint8_t, "@LAST_STABILIZED");
148 struct gencache_have_val_state {
150 const DATA_BLOB *data;
154 static void gencache_have_val_parser(time_t old_timeout, DATA_BLOB data,
157 struct gencache_have_val_state *state =
158 (struct gencache_have_val_state *)private_data;
159 time_t now = time(NULL);
160 int cache_time_left, new_time_left, additional_time;
163 * Excuse the many variables, but these time calculations are
164 * confusing to me. We do not want to write to gencache with a
165 * possibly expensive transaction if we are about to write the same
166 * value, just extending the remaining timeout by less than 10%.
169 cache_time_left = old_timeout - now;
170 if (cache_time_left <= 0) {
172 * timed out, write new value
177 new_time_left = state->new_timeout - now;
178 if (new_time_left <= 0) {
180 * Huh -- no new timeout?? Write it.
185 if (new_time_left < cache_time_left) {
187 * Someone wants to shorten the timeout. Let it happen.
193 * By how much does the new timeout extend the remaining cache time?
195 additional_time = new_time_left - cache_time_left;
197 if (additional_time * 10 < 0) {
199 * Integer overflow. We extend by so much that we have to write it.
205 * The comparison below is essentially equivalent to
207 * new_time_left > cache_time_left * 1.10
209 * but without floating point calculations.
212 if (additional_time * 10 > cache_time_left) {
214 * We extend the cache timeout by more than 10%. Do it.
220 * Now the more expensive data compare.
222 if (data_blob_cmp(state->data, &data) != 0) {
224 * Write a new value. Certainly do it.
230 * Extending the timeout by less than 10% for the same cache value is
231 * not worth the trouble writing a value into gencache under a
232 * possibly expensive transaction.
237 static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
240 struct gencache_have_val_state state;
242 state.new_timeout = timeout;
246 if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
252 static int last_stabilize_parser(TDB_DATA key, TDB_DATA data,
255 time_t *last_stabilize = private_data;
257 if ((data.dsize != 0) && (data.dptr[data.dsize-1] == '\0')) {
258 *last_stabilize = atoi((char *)data.dptr);
264 * Set an entry in the cache file. If there's no such
267 * @param keystr string that represents a key of this entry
268 * @param blob DATA_BLOB value being cached
269 * @param timeout time when the value is expired
271 * @retval true when entry is successfully stored
272 * @retval false on failure
275 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
281 time_t last_stabilize;
282 static int writecount;
285 if (tdb_data_cmp(string_term_tdb_data(keystr),
286 last_stabilize_key()) == 0) {
287 DEBUG(10, ("Can't store %s as a key\n", keystr));
291 if ((keystr == NULL) || (blob == NULL)) {
295 if (!gencache_init()) {
299 if ((timeout != 0) && gencache_have_val(keystr, blob, timeout)) {
300 DEBUG(10, ("Did not store value for %s, we already got it\n",
305 hdr_len = fstr_sprintf(hdr, CACHE_DATA_FMT, (int)timeout);
310 if ((blob->length + (size_t)hdr_len) < blob->length) {
314 dbufs[0] = (TDB_DATA) { .dptr = (uint8_t *)hdr, .dsize = hdr_len };
315 dbufs[1] = (TDB_DATA) { .dptr = blob->data, .dsize = blob->length };
317 DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
318 "[%s] (%d seconds %s)\n", keystr,
319 timestring(talloc_tos(), timeout),
320 (int)(timeout - time(NULL)),
321 timeout > time(NULL) ? "ahead" : "in the past"));
323 ret = tdb_storev(cache_notrans->tdb, string_term_tdb_data(keystr),
330 * Every 100 writes within a single process, stabilize the cache with
331 * a transaction. This is done to prevent a single transaction to
332 * become huge and chew lots of memory.
335 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
336 gencache_stabilize();
342 * Every 5 minutes, call gencache_stabilize() to not let grow
343 * gencache_notrans.tdb too large.
348 tdb_parse_record(cache_notrans->tdb, last_stabilize_key(),
349 last_stabilize_parser, &last_stabilize);
352 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
354 gencache_stabilize();
361 static void gencache_del_parser(time_t timeout, DATA_BLOB blob,
365 bool *exists = private_data;
371 * Delete one entry from the cache file.
373 * @param keystr string that represents a key of this entry
375 * @retval true upon successful deletion
376 * @retval false in case of failure
379 bool gencache_del(const char *keystr)
381 TDB_DATA key = string_term_tdb_data(keystr);
386 if (keystr == NULL) {
390 if (!gencache_init()) {
394 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
396 ret = tdb_chainlock(cache_notrans->tdb, key);
401 gencache_parse(keystr, gencache_del_parser, &exists);
405 * We delete an element by setting its timeout to
406 * 0. This way we don't have to do a transaction on
407 * gencache.tdb every time we delete an element.
409 result = gencache_set(keystr, "", 0);
412 tdb_chainunlock(cache_notrans->tdb, key);
417 static bool gencache_pull_timeout(uint8_t *val, time_t *pres, char **payload)
426 res = strtol((char *)val, &endptr, 10);
428 if ((endptr == NULL) || (*endptr != '/')) {
429 DEBUG(2, ("Invalid gencache data format: %s\n", (char *)val));
435 if (payload != NULL) {
441 struct gencache_parse_state {
442 void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
444 bool copy_to_notrans;
447 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
449 struct gencache_parse_state *state;
455 if (data.dptr == NULL) {
458 ret = gencache_pull_timeout(data.dptr, &t, &payload);
462 state = (struct gencache_parse_state *)private_data;
463 blob = data_blob_const(
464 payload, data.dsize - PTR_DIFF(payload, data.dptr));
465 state->parser(t, blob, state->private_data);
467 if (state->copy_to_notrans) {
468 tdb_store(cache_notrans->tdb, key, data, 0);
474 bool gencache_parse(const char *keystr,
475 void (*parser)(time_t timeout, DATA_BLOB blob,
479 struct gencache_parse_state state;
480 TDB_DATA key = string_term_tdb_data(keystr);
483 if (keystr == NULL) {
486 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
489 if (!gencache_init()) {
493 state.parser = parser;
494 state.private_data = private_data;
495 state.copy_to_notrans = false;
497 ret = tdb_chainlock(cache_notrans->tdb, key);
502 ret = tdb_parse_record(cache_notrans->tdb, key,
503 gencache_parse_fn, &state);
505 tdb_chainunlock(cache_notrans->tdb, key);
509 state.copy_to_notrans = true;
511 ret = tdb_parse_record(cache->tdb, key, gencache_parse_fn, &state);
513 if ((ret == -1) && (tdb_error(cache->tdb) == TDB_ERR_NOEXIST)) {
515 * The record does not exist. Set a delete-marker in
516 * gencache_notrans, so that we don't have to look at
517 * the fcntl-based cache again.
519 gencache_set(keystr, "", 0);
522 tdb_chainunlock(cache_notrans->tdb, key);
527 struct gencache_get_data_blob_state {
534 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
537 struct gencache_get_data_blob_state *state =
538 (struct gencache_get_data_blob_state *)private_data;
541 state->result = false;
544 state->timeout = timeout;
546 if (state->blob == NULL) {
547 state->result = true;
551 *state->blob = data_blob_talloc(state->mem_ctx, blob.data,
553 if (state->blob->data == NULL) {
554 state->result = false;
557 state->result = true;
561 * Get existing entry from the cache file.
563 * @param keystr string that represents a key of this entry
564 * @param blob DATA_BLOB that is filled with entry's blob
565 * @param timeout pointer to a time_t that is filled with entry's
568 * @retval true when entry is successfuly fetched
569 * @retval false for failure
572 bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
574 time_t *timeout, bool *was_expired)
576 struct gencache_get_data_blob_state state;
577 bool expired = false;
579 state.result = false;
580 state.mem_ctx = mem_ctx;
583 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
589 if (state.timeout <= time(NULL)) {
591 * We're expired, delete the entry. We can't use gencache_del
592 * here, because that uses gencache_get_data_blob for checking
593 * the existence of a record. We know the thing exists and
594 * directly store an empty value with 0 timeout.
596 gencache_set(keystr, "", 0);
601 *timeout = state.timeout;
607 if (was_expired != NULL) {
608 *was_expired = expired;
610 if (state.result && state.blob) {
611 data_blob_free(state.blob);
616 struct stabilize_state {
619 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
622 static int wipe_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
628 * Migrate the clear-if-first gencache data to the stable,
629 * transaction-based gencache.tdb
632 bool gencache_stabilize(void)
634 struct stabilize_state state;
638 if (!gencache_init()) {
642 res = tdb_transaction_start_nonblock(cache->tdb);
644 if (tdb_error(cache->tdb) == TDB_ERR_NOLOCK)
647 * Someone else already does the stabilize,
648 * this does not have to be done twice
653 DEBUG(10, ("Could not start transaction on gencache.tdb: "
654 "%s\n", tdb_errorstr(cache->tdb)));
658 res = tdb_lockall_nonblock(cache_notrans->tdb);
660 tdb_transaction_cancel(cache->tdb);
661 DEBUG(10, ("Could not get allrecord lock on "
662 "gencache_notrans.tdb: %s\n",
663 tdb_errorstr(cache_notrans->tdb)));
667 state.written = false;
669 res = tdb_traverse(cache_notrans->tdb, stabilize_fn, &state);
671 tdb_unlockall(cache_notrans->tdb);
672 tdb_transaction_cancel(cache->tdb);
676 if (!state.written) {
677 tdb_unlockall(cache_notrans->tdb);
678 tdb_transaction_cancel(cache->tdb);
682 res = tdb_transaction_commit(cache->tdb);
684 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
685 "%s\n", tdb_errorstr(cache->tdb)));
686 tdb_unlockall(cache_notrans->tdb);
690 res = tdb_traverse(cache_notrans->tdb, wipe_fn, NULL);
692 DEBUG(10, ("tdb_traverse with wipe_fn on gencache_notrans.tdb "
694 tdb_errorstr(cache_notrans->tdb)));
695 tdb_unlockall(cache_notrans->tdb);
699 res = tdb_unlockall(cache_notrans->tdb);
701 DEBUG(10, ("tdb_unlockall on gencache.tdb failed: "
702 "%s\n", tdb_errorstr(cache->tdb)));
706 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
708 tdb_store(cache_notrans->tdb, last_stabilize_key(),
709 string_term_tdb_data(now), 0);
716 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
719 struct stabilize_state *state = (struct stabilize_state *)priv;
723 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
727 if (!gencache_pull_timeout(val.dptr, &timeout, NULL)) {
728 DEBUG(10, ("Ignoring invalid entry\n"));
731 if ((timeout < time(NULL)) || (val.dsize == 0)) {
732 res = tdb_delete(cache->tdb, key);
734 state->written = true;
735 } else if (tdb_error(cache->tdb) == TDB_ERR_NOEXIST) {
739 res = tdb_store(cache->tdb, key, val, 0);
741 state->written = true;
746 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
747 tdb_errorstr(cache->tdb)));
754 static int wipe_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
761 res = tdb_data_cmp(key, last_stabilize_key());
766 ok = gencache_pull_timeout(val.dptr, &timeout, NULL);
768 DEBUG(10, ("Ignoring invalid entry\n"));
772 res = tdb_delete(tdb, key);
774 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
775 "%s\n", tdb_errorstr(cache_notrans->tdb)));
784 * Get existing entry from the cache file.
786 * @param keystr string that represents a key of this entry
787 * @param valstr buffer that is allocated and filled with the entry value
788 * buffer's disposing must be done outside
789 * @param timeout pointer to a time_t that is filled with entry's
792 * @retval true when entry is successfully fetched
793 * @retval false for failure
796 bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
802 ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
806 if ((blob.data == NULL) || (blob.length == 0)) {
807 data_blob_free(&blob);
810 if (blob.data[blob.length-1] != '\0') {
811 /* Not NULL terminated, can't be a string */
812 data_blob_free(&blob);
817 * talloc_move generates a type-punned warning here. As we
818 * leave the function immediately, do a simple talloc_steal.
820 *value = (char *)talloc_steal(mem_ctx, blob.data);
823 data_blob_free(&blob);
828 * Set an entry in the cache file. If there's no such
831 * @param keystr string that represents a key of this entry
832 * @param value text representation value being cached
833 * @param timeout time when the value is expired
835 * @retval true when entry is successfuly stored
836 * @retval false on failure
839 bool gencache_set(const char *keystr, const char *value, time_t timeout)
841 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
842 return gencache_set_data_blob(keystr, &blob, timeout);
845 struct gencache_iterate_blobs_state {
846 void (*fn)(const char *key, DATA_BLOB value,
847 time_t timeout, void *private_data);
853 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
854 TDB_DATA data, void *priv)
856 struct gencache_iterate_blobs_state *state =
857 (struct gencache_iterate_blobs_state *)priv;
859 char *free_key = NULL;
863 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
866 if (state->in_persistent && tdb_exists(cache_notrans->tdb, key)) {
870 if (key.dptr[key.dsize-1] == '\0') {
871 keystr = (char *)key.dptr;
873 /* ensure 0-termination */
874 keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
876 if (keystr == NULL) {
881 if (!gencache_pull_timeout(data.dptr, &timeout, &payload)) {
890 if (fnmatch(state->pattern, keystr, 0) != 0) {
894 DEBUG(10, ("Calling function with arguments "
895 "(key=[%s], timeout=[%s])\n",
896 keystr, timestring(talloc_tos(), timeout)));
899 data_blob_const(payload,
900 data.dsize - PTR_DIFF(payload, data.dptr)),
901 timeout, state->private_data);
904 TALLOC_FREE(free_key);
908 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
909 time_t timeout, void *private_data),
910 void *private_data, const char *pattern)
912 struct gencache_iterate_blobs_state state;
914 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
918 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
921 state.pattern = pattern;
922 state.private_data = private_data;
924 state.in_persistent = false;
925 tdb_traverse(cache_notrans->tdb, gencache_iterate_blobs_fn, &state);
927 state.in_persistent = true;
928 tdb_traverse(cache->tdb, gencache_iterate_blobs_fn, &state);
932 * Iterate through all entries which key matches to specified pattern
934 * @param fn pointer to the function that will be supplied with each single
935 * matching cache entry (key, value and timeout) as an arguments
936 * @param data void pointer to an arbitrary data that is passed directly to the fn
937 * function on each call
938 * @param keystr_pattern pattern the existing entries' keys are matched to
942 struct gencache_iterate_state {
943 void (*fn)(const char *key, const char *value, time_t timeout,
948 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
949 time_t timeout, void *private_data)
951 struct gencache_iterate_state *state =
952 (struct gencache_iterate_state *)private_data;
954 char *free_val = NULL;
956 if (value.data[value.length-1] == '\0') {
957 valstr = (char *)value.data;
959 /* ensure 0-termination */
960 valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
962 if (valstr == NULL) {
967 DEBUG(10, ("Calling function with arguments "
968 "(key=[%s], value=[%s], timeout=[%s])\n",
969 key, valstr, timestring(talloc_tos(), timeout)));
971 state->fn(key, valstr, timeout, state->private_data);
975 TALLOC_FREE(free_val);
978 void gencache_iterate(void (*fn)(const char *key, const char *value,
979 time_t timeout, void *dptr),
980 void *private_data, const char *pattern)
982 struct gencache_iterate_state state;
988 state.private_data = private_data;
989 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);