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 "../lib/util/memcache.h"
31 #define DBGC_CLASS DBGC_TDB
33 #define TIMEOUT_LEN 12
34 #define CACHE_DATA_FMT "%12u/"
35 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
36 #define BLOB_TYPE "DATA_BLOB"
37 #define BLOB_TYPE_LEN 9
39 static struct tdb_context *cache;
40 static struct tdb_context *cache_notrans;
41 static int cache_notrans_seqnum;
45 * @brief Generic, persistent and shared between processes cache mechanism
46 * for use by various parts of the Samba code
52 * Cache initialisation function. Opens cache tdb file or creates
53 * it if does not exist.
55 * @return true on successful initialisation of the cache or
59 static bool gencache_init(void)
61 char* cache_fname = NULL;
62 int open_flags = O_RDWR|O_CREAT;
64 /* skip file open if it's already opened */
65 if (cache) return True;
67 cache_fname = cache_path("gencache.tdb");
68 if (cache_fname == NULL) {
72 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
74 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
77 ret = tdb_check(cache, NULL, NULL);
82 * Retry with CLEAR_IF_FIRST.
84 * Warning: Converting this to dbwrap won't work
85 * directly. gencache.c does transactions on this tdb,
86 * and dbwrap forbids this for CLEAR_IF_FIRST
87 * databases. tdb does allow transactions on
88 * CLEAR_IF_FIRST databases, so lets use it here to
89 * clean up a broken database.
91 cache = tdb_open_log(cache_fname, 0,
93 TDB_INCOMPATIBLE_HASH|
99 if (!cache && (errno == EACCES)) {
100 open_flags = O_RDONLY;
101 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags,
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) {
121 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
123 cache_notrans = tdb_open_log(cache_fname, 0,
125 TDB_INCOMPATIBLE_HASH|
129 if (cache_notrans == NULL) {
130 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
132 TALLOC_FREE(cache_fname);
137 TALLOC_FREE(cache_fname);
142 static TDB_DATA last_stabilize_key(void)
145 result.dptr = discard_const_p(uint8_t, "@LAST_STABILIZED");
150 struct gencache_have_val_state {
152 const DATA_BLOB *data;
156 static void gencache_have_val_parser(time_t old_timeout, DATA_BLOB data,
159 struct gencache_have_val_state *state =
160 (struct gencache_have_val_state *)private_data;
161 time_t now = time(NULL);
162 int cache_time_left, new_time_left, additional_time;
165 * Excuse the many variables, but these time calculations are
166 * confusing to me. We do not want to write to gencache with a
167 * possibly expensive transaction if we are about to write the same
168 * value, just extending the remaining timeout by less than 10%.
171 cache_time_left = old_timeout - now;
172 if (cache_time_left <= 0) {
174 * timed out, write new value
179 new_time_left = state->new_timeout - now;
180 if (new_time_left <= 0) {
182 * Huh -- no new timeout?? Write it.
187 if (new_time_left < cache_time_left) {
189 * Someone wants to shorten the timeout. Let it happen.
195 * By how much does the new timeout extend the remaining cache time?
197 additional_time = new_time_left - cache_time_left;
199 if (additional_time * 10 < 0) {
201 * Integer overflow. We extend by so much that we have to write it.
207 * The comparison below is essentially equivalent to
209 * new_time_left > cache_time_left * 1.10
211 * but without floating point calculations.
214 if (additional_time * 10 > cache_time_left) {
216 * We extend the cache timeout by more than 10%. Do it.
222 * Now the more expensive data compare.
224 if (data_blob_cmp(state->data, &data) != 0) {
226 * Write a new value. Certainly do it.
232 * Extending the timeout by less than 10% for the same cache value is
233 * not worth the trouble writing a value into gencache under a
234 * possibly expensive transaction.
239 static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
242 struct gencache_have_val_state state;
244 state.new_timeout = timeout;
248 if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
255 * Set an entry in the cache file. If there's no such
258 * @param keystr string that represents a key of this entry
259 * @param blob DATA_BLOB value being cached
260 * @param timeout time when the value is expired
262 * @retval true when entry is successfuly stored
263 * @retval false on failure
266 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
272 time_t last_stabilize;
273 static int writecount;
275 if (tdb_data_cmp(string_term_tdb_data(keystr),
276 last_stabilize_key()) == 0) {
277 DEBUG(10, ("Can't store %s as a key\n", keystr));
281 if ((keystr == NULL) || (blob == NULL)) {
285 if (!gencache_init()) return False;
287 if (gencache_have_val(keystr, blob, timeout)) {
288 DEBUG(10, ("Did not store value for %s, we already got it\n",
293 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
297 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
301 val = (char *)talloc_append_blob(NULL, val, *blob);
306 DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
307 "[%s] (%d seconds %s)\n", keystr,
308 timestring(talloc_tos(), timeout),
309 (int)(timeout - time(NULL)),
310 timeout > time(NULL) ? "ahead" : "in the past"));
312 ret = tdb_store_bystring(
313 cache_notrans, keystr,
314 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
323 * Every 100 writes within a single process, stabilize the cache with
324 * a transaction. This is done to prevent a single transaction to
325 * become huge and chew lots of memory.
328 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
329 gencache_stabilize();
335 * Every 5 minutes, call gencache_stabilize() to not let grow
336 * gencache_notrans.tdb too large.
340 databuf = tdb_fetch_compat(cache_notrans, last_stabilize_key());
341 if ((databuf.dptr != NULL)
342 && (databuf.dptr[databuf.dsize-1] == '\0')) {
343 last_stabilize = atoi((char *)databuf.dptr);
344 SAFE_FREE(databuf.dptr);
347 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
349 gencache_stabilize();
357 * Delete one entry from the cache file.
359 * @param keystr string that represents a key of this entry
361 * @retval true upon successful deletion
362 * @retval false in case of failure
365 bool gencache_del(const char *keystr)
367 bool exists, was_expired;
371 if (keystr == NULL) {
375 if (!gencache_init()) return False;
377 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
380 * We delete an element by setting its timeout to 0. This way we don't
381 * have to do a transaction on gencache.tdb every time we delete an
385 exists = gencache_get_data_blob(keystr, NULL, &value, NULL,
388 if (!exists && was_expired) {
390 * gencache_get_data_blob has implicitly deleted this
391 * entry, so we have to return success here.
397 data_blob_free(&value);
398 ret = gencache_set(keystr, "", 0);
403 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
412 res = strtol(val, &endptr, 10);
414 if ((endptr == NULL) || (*endptr != '/')) {
415 DEBUG(2, ("Invalid gencache data format: %s\n", val));
421 if (pendptr != NULL) {
427 struct gencache_parse_state {
428 void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
433 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
435 struct gencache_parse_state *state;
441 if (data.dptr == NULL) {
444 ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
448 state = (struct gencache_parse_state *)private_data;
449 blob = data_blob_const(
450 endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
451 state->parser(t, blob, state->private_data);
453 if (!state->is_memcache) {
454 memcache_add(NULL, GENCACHE_RAM,
455 data_blob_const(key.dptr, key.dsize),
456 data_blob_const(data.dptr, data.dsize));
462 bool gencache_parse(const char *keystr,
463 void (*parser)(time_t timeout, DATA_BLOB blob,
467 struct gencache_parse_state state;
468 TDB_DATA key = string_term_tdb_data(keystr);
469 DATA_BLOB memcache_val;
472 if (keystr == NULL) {
475 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
478 if (!gencache_init()) {
482 state.parser = parser;
483 state.private_data = private_data;
485 if (memcache_lookup(NULL, GENCACHE_RAM,
486 data_blob_const(key.dptr, key.dsize),
489 * Make sure that nobody has changed the gencache behind our
492 int current_seqnum = tdb_get_seqnum(cache_notrans);
493 if (current_seqnum == cache_notrans_seqnum) {
495 * Ok, our memcache is still current, use it without
496 * going to the tdb files.
498 state.is_memcache = true;
499 gencache_parse_fn(key, make_tdb_data(memcache_val.data,
500 memcache_val.length),
504 memcache_flush(NULL, GENCACHE_RAM);
505 cache_notrans_seqnum = current_seqnum;
508 state.is_memcache = false;
510 ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
514 ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
518 struct gencache_get_data_blob_state {
525 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
528 struct gencache_get_data_blob_state *state =
529 (struct gencache_get_data_blob_state *)private_data;
532 state->result = false;
535 state->timeout = timeout;
537 if (state->blob == NULL) {
538 state->result = true;
542 *state->blob = data_blob_talloc(state->mem_ctx, blob.data,
544 if (state->blob->data == NULL) {
545 state->result = false;
548 state->result = true;
552 * Get existing entry from the cache file.
554 * @param keystr string that represents a key of this entry
555 * @param blob DATA_BLOB that is filled with entry's blob
556 * @param timeout pointer to a time_t that is filled with entry's
559 * @retval true when entry is successfuly fetched
560 * @retval False for failure
563 bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
565 time_t *timeout, bool *was_expired)
567 struct gencache_get_data_blob_state state;
568 bool expired = false;
570 state.result = false;
571 state.mem_ctx = mem_ctx;
574 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
580 if (state.timeout <= time(NULL)) {
582 * We're expired, delete the entry. We can't use gencache_del
583 * here, because that uses gencache_get_data_blob for checking
584 * the existence of a record. We know the thing exists and
585 * directly store an empty value with 0 timeout.
587 gencache_set(keystr, "", 0);
592 *timeout = state.timeout;
598 if (was_expired != NULL) {
599 *was_expired = expired;
601 if (state.result && state.blob) {
602 data_blob_free(state.blob);
607 struct stabilize_state {
611 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
617 * Migrate the clear-if-first gencache data to the stable,
618 * transaction-based gencache.tdb
621 bool gencache_stabilize(void)
623 struct stabilize_state state;
627 if (!gencache_init()) {
631 res = tdb_transaction_start_nonblock(cache);
633 if (tdb_error(cache) == TDB_ERR_NOLOCK)
636 * Someone else already does the stabilize,
637 * this does not have to be done twice
642 DEBUG(10, ("Could not start transaction on gencache.tdb: "
643 "%s\n", tdb_errorstr_compat(cache)));
646 res = tdb_transaction_start(cache_notrans);
648 tdb_transaction_cancel(cache);
649 DEBUG(10, ("Could not start transaction on "
650 "gencache_notrans.tdb: %s\n",
651 tdb_errorstr_compat(cache_notrans)));
656 state.written = false;
658 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
659 if ((res < 0) || state.error) {
660 tdb_transaction_cancel(cache_notrans);
661 tdb_transaction_cancel(cache);
665 if (!state.written) {
666 tdb_transaction_cancel(cache_notrans);
667 tdb_transaction_cancel(cache);
671 res = tdb_transaction_commit(cache);
673 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
674 "%s\n", tdb_errorstr_compat(cache)));
675 tdb_transaction_cancel(cache_notrans);
679 res = tdb_transaction_commit(cache_notrans);
681 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
682 "%s\n", tdb_errorstr_compat(cache)));
686 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
688 tdb_store(cache_notrans, last_stabilize_key(),
689 string_term_tdb_data(now), 0);
696 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
699 struct stabilize_state *state = (struct stabilize_state *)priv;
703 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
707 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
708 DEBUG(10, ("Ignoring invalid entry\n"));
711 if ((timeout < time(NULL)) || (val.dsize == 0)) {
712 res = tdb_delete(cache, key);
713 if ((res != 0) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
716 state->written = true;
719 res = tdb_store(cache, key, val, 0);
721 state->written = true;
726 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
727 tdb_errorstr_compat(cache)));
732 if (tdb_delete(cache_notrans, key) != 0) {
733 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
734 "%s\n", tdb_errorstr_compat(cache_notrans)));
742 * Get existing entry from the cache file.
744 * @param keystr string that represents a key of this entry
745 * @param valstr buffer that is allocated and filled with the entry value
746 * buffer's disposing must be done outside
747 * @param timeout pointer to a time_t that is filled with entry's
750 * @retval true when entry is successfuly fetched
751 * @retval False for failure
754 bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
760 ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
764 if ((blob.data == NULL) || (blob.length == 0)) {
765 data_blob_free(&blob);
768 if (blob.data[blob.length-1] != '\0') {
769 /* Not NULL terminated, can't be a string */
770 data_blob_free(&blob);
775 * talloc_move generates a type-punned warning here. As we
776 * leave the function immediately, do a simple talloc_steal.
778 *value = (char *)talloc_steal(mem_ctx, blob.data);
781 data_blob_free(&blob);
786 * Set an entry in the cache file. If there's no such
789 * @param keystr string that represents a key of this entry
790 * @param value text representation value being cached
791 * @param timeout time when the value is expired
793 * @retval true when entry is successfuly stored
794 * @retval false on failure
797 bool gencache_set(const char *keystr, const char *value, time_t timeout)
799 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
800 return gencache_set_data_blob(keystr, &blob, timeout);
803 struct gencache_iterate_blobs_state {
804 void (*fn)(const char *key, DATA_BLOB value,
805 time_t timeout, void *private_data);
811 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
812 TDB_DATA data, void *priv)
814 struct gencache_iterate_blobs_state *state =
815 (struct gencache_iterate_blobs_state *)priv;
817 char *free_key = NULL;
821 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
824 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
828 if (key.dptr[key.dsize-1] == '\0') {
829 keystr = (char *)key.dptr;
831 /* ensure 0-termination */
832 keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
834 if (keystr == NULL) {
839 if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
844 if (fnmatch(state->pattern, keystr, 0) != 0) {
848 DEBUG(10, ("Calling function with arguments "
849 "(key=[%s], timeout=[%s])\n",
850 keystr, timestring(talloc_tos(), timeout)));
853 data_blob_const(endptr,
854 data.dsize - PTR_DIFF(endptr, data.dptr)),
855 timeout, state->private_data);
858 TALLOC_FREE(free_key);
862 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
863 time_t timeout, void *private_data),
864 void *private_data, const char *pattern)
866 struct gencache_iterate_blobs_state state;
868 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
872 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
875 state.pattern = pattern;
876 state.private_data = private_data;
878 state.in_persistent = false;
879 tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);
881 state.in_persistent = true;
882 tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
886 * Iterate through all entries which key matches to specified pattern
888 * @param fn pointer to the function that will be supplied with each single
889 * matching cache entry (key, value and timeout) as an arguments
890 * @param data void pointer to an arbitrary data that is passed directly to the fn
891 * function on each call
892 * @param keystr_pattern pattern the existing entries' keys are matched to
896 struct gencache_iterate_state {
897 void (*fn)(const char *key, const char *value, time_t timeout,
902 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
903 time_t timeout, void *private_data)
905 struct gencache_iterate_state *state =
906 (struct gencache_iterate_state *)private_data;
908 char *free_val = NULL;
910 if (value.data[value.length-1] == '\0') {
911 valstr = (char *)value.data;
913 /* ensure 0-termination */
914 valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
916 if (valstr == NULL) {
921 DEBUG(10, ("Calling function with arguments "
922 "(key=[%s], value=[%s], timeout=[%s])\n",
923 key, valstr, timestring(talloc_tos(), timeout)));
925 state->fn(key, valstr, timeout, state->private_data);
929 TALLOC_FREE(free_val);
932 void gencache_iterate(void (*fn)(const char *key, const char *value,
933 time_t timeout, void *dptr),
934 void *private_data, const char *pattern)
936 struct gencache_iterate_state state;
942 state.private_data = private_data;
943 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);