gencache: Convert to a binary timestamp
[Samba.git] / source3 / lib / gencache.c
blob5aa52a06e7c4f841a4762dadf60217d1554250f3
1 /*
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/>.
24 #include "includes.h"
25 #include "lib/gencache.h"
26 #include "system/filesys.h"
27 #include "system/glob.h"
28 #include "util_tdb.h"
29 #include "tdb_wrap/tdb_wrap.h"
31 #undef DBGC_CLASS
32 #define DBGC_CLASS DBGC_TDB
34 static struct tdb_wrap *cache;
35 static struct tdb_wrap *cache_notrans;
37 /**
38 * @file gencache.c
39 * @brief Generic, persistent and shared between processes cache mechanism
40 * for use by various parts of the Samba code
42 **/
44 struct gencache_timeout {
45 time_t timeout;
48 bool gencache_timeout_expired(const struct gencache_timeout *t)
50 return t->timeout <= time(NULL);
53 /**
54 * Cache initialisation function. Opens cache tdb file or creates
55 * it if does not exist.
57 * @return true on successful initialisation of the cache or
58 * false on failure
59 **/
61 static bool gencache_init(void)
63 char* cache_fname = NULL;
64 int open_flags = O_RDWR|O_CREAT;
65 int hash_size;
67 /* skip file open if it's already opened */
68 if (cache) {
69 return true;
72 hash_size = lp_parm_int(-1, "gencache", "hash_size", 10000);
74 cache_fname = cache_path(talloc_tos(), "gencache.tdb");
75 if (cache_fname == NULL) {
76 return false;
79 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
81 cache = tdb_wrap_open(NULL, cache_fname, hash_size,
82 TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
83 open_flags, 0644);
85 if (!cache && (errno == EACCES)) {
86 open_flags = O_RDONLY;
87 cache = tdb_wrap_open(NULL, cache_fname, hash_size,
88 TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
89 open_flags, 0644);
90 if (cache) {
91 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
94 TALLOC_FREE(cache_fname);
96 if (!cache) {
97 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
98 return false;
101 cache_fname = lock_path(talloc_tos(), "gencache_notrans.tdb");
102 if (cache_fname == NULL) {
103 TALLOC_FREE(cache);
104 return false;
107 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
109 cache_notrans = tdb_wrap_open(NULL, cache_fname, hash_size,
110 TDB_CLEAR_IF_FIRST|
111 TDB_INCOMPATIBLE_HASH|
112 TDB_NOSYNC|
113 TDB_MUTEX_LOCKING,
114 open_flags, 0644);
115 if (cache_notrans == NULL) {
116 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
117 strerror(errno)));
118 TALLOC_FREE(cache_fname);
119 TALLOC_FREE(cache);
120 return false;
122 TALLOC_FREE(cache_fname);
124 return true;
127 static TDB_DATA last_stabilize_key(void)
129 const char key[] = "@LAST_STABILIZED";
131 return (TDB_DATA) {
132 .dptr = discard_const_p(uint8_t, key),
133 .dsize = sizeof(key),
137 struct gencache_have_val_state {
138 time_t new_timeout;
139 const DATA_BLOB *data;
140 bool gotit;
143 static void gencache_have_val_parser(const struct gencache_timeout *old_timeout,
144 DATA_BLOB data,
145 void *private_data)
147 struct gencache_have_val_state *state =
148 (struct gencache_have_val_state *)private_data;
149 time_t now = time(NULL);
150 int cache_time_left, new_time_left, additional_time;
153 * Excuse the many variables, but these time calculations are
154 * confusing to me. We do not want to write to gencache with a
155 * possibly expensive transaction if we are about to write the same
156 * value, just extending the remaining timeout by less than 10%.
159 cache_time_left = old_timeout->timeout - now;
160 if (cache_time_left <= 0) {
162 * timed out, write new value
164 return;
167 new_time_left = state->new_timeout - now;
168 if (new_time_left <= 0) {
170 * Huh -- no new timeout?? Write it.
172 return;
175 if (new_time_left < cache_time_left) {
177 * Someone wants to shorten the timeout. Let it happen.
179 return;
183 * By how much does the new timeout extend the remaining cache time?
185 additional_time = new_time_left - cache_time_left;
187 if (additional_time * 10 < 0) {
189 * Integer overflow. We extend by so much that we have to write it.
191 return;
195 * The comparison below is essentially equivalent to
197 * new_time_left > cache_time_left * 1.10
199 * but without floating point calculations.
202 if (additional_time * 10 > cache_time_left) {
204 * We extend the cache timeout by more than 10%. Do it.
206 return;
210 * Now the more expensive data compare.
212 if (data_blob_cmp(state->data, &data) != 0) {
214 * Write a new value. Certainly do it.
216 return;
220 * Extending the timeout by less than 10% for the same cache value is
221 * not worth the trouble writing a value into gencache under a
222 * possibly expensive transaction.
224 state->gotit = true;
227 static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
228 time_t timeout)
230 struct gencache_have_val_state state;
232 state.new_timeout = timeout;
233 state.data = data;
234 state.gotit = false;
236 if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
237 return false;
239 return state.gotit;
242 static int last_stabilize_parser(TDB_DATA key, TDB_DATA data,
243 void *private_data)
245 time_t *last_stabilize = private_data;
247 if ((data.dsize != 0) && (data.dptr[data.dsize-1] == '\0')) {
248 *last_stabilize = atoi((char *)data.dptr);
250 return 0;
254 * Set an entry in the cache file. If there's no such
255 * one, then add it.
257 * @param keystr string that represents a key of this entry
258 * @param blob DATA_BLOB value being cached
259 * @param timeout time when the value is expired
261 * @retval true when entry is successfully stored
262 * @retval false on failure
265 bool gencache_set_data_blob(const char *keystr, DATA_BLOB blob,
266 time_t timeout)
268 TDB_DATA key;
269 int ret;
270 time_t last_stabilize;
271 static int writecount;
272 TDB_DATA dbufs[2];
274 if ((keystr == NULL) || (blob.data == NULL)) {
275 return false;
278 key = string_term_tdb_data(keystr);
280 ret = tdb_data_cmp(key, last_stabilize_key());
281 if (ret == 0) {
282 DEBUG(10, ("Can't store %s as a key\n", keystr));
283 return false;
286 if (!gencache_init()) {
287 return false;
290 if ((timeout != 0) && gencache_have_val(keystr, &blob, timeout)) {
291 DEBUG(10, ("Did not store value for %s, we already got it\n",
292 keystr));
293 return true;
296 dbufs[0] = (TDB_DATA) { .dptr = (uint8_t *)&timeout,
297 .dsize = sizeof(time_t) };
298 dbufs[1] = (TDB_DATA) { .dptr = blob.data, .dsize = blob.length };
300 DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
301 "[%s] (%d seconds %s)\n", keystr,
302 timestring(talloc_tos(), timeout),
303 (int)(timeout - time(NULL)),
304 timeout > time(NULL) ? "ahead" : "in the past"));
306 ret = tdb_storev(cache_notrans->tdb, key, dbufs, 2, 0);
307 if (ret != 0) {
308 return false;
312 * Every 100 writes within a single process, stabilize the cache with
313 * a transaction. This is done to prevent a single transaction to
314 * become huge and chew lots of memory.
316 writecount += 1;
317 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
318 gencache_stabilize();
319 writecount = 0;
320 goto done;
324 * Every 5 minutes, call gencache_stabilize() to not let grow
325 * gencache_notrans.tdb too large.
328 last_stabilize = 0;
330 tdb_parse_record(cache_notrans->tdb, last_stabilize_key(),
331 last_stabilize_parser, &last_stabilize);
333 if ((last_stabilize
334 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
335 < time(NULL)) {
336 gencache_stabilize();
339 done:
340 return ret == 0;
343 static void gencache_del_parser(const struct gencache_timeout *t,
344 DATA_BLOB blob,
345 void *private_data)
347 if (t->timeout != 0) {
348 bool *exists = private_data;
349 *exists = true;
354 * Delete one entry from the cache file.
356 * @param keystr string that represents a key of this entry
358 * @retval true upon successful deletion
359 * @retval false in case of failure
362 bool gencache_del(const char *keystr)
364 TDB_DATA key = string_term_tdb_data(keystr);
365 bool exists = false;
366 bool result = false;
367 int ret;
369 if (keystr == NULL) {
370 return false;
373 if (!gencache_init()) {
374 return false;
377 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
379 ret = tdb_chainlock(cache_notrans->tdb, key);
380 if (ret == -1) {
381 return false;
384 gencache_parse(keystr, gencache_del_parser, &exists);
386 if (exists) {
388 * We delete an element by setting its timeout to
389 * 0. This way we don't have to do a transaction on
390 * gencache.tdb every time we delete an element.
392 result = gencache_set(keystr, "", 0);
395 tdb_chainunlock(cache_notrans->tdb, key);
397 return result;
400 static bool gencache_pull_timeout(TDB_DATA data, time_t *pres, DATA_BLOB *payload)
402 if ((data.dptr == NULL) || (data.dsize < sizeof(time_t))) {
403 return false;
405 if (pres != NULL) {
406 memcpy(pres, data.dptr, sizeof(time_t));
408 if (payload != NULL) {
409 *payload = (DATA_BLOB) {
410 .data = data.dptr + sizeof(time_t),
411 .length = data.dsize - sizeof(time_t),
414 return true;
417 struct gencache_parse_state {
418 void (*parser)(const struct gencache_timeout *timeout,
419 DATA_BLOB blob,
420 void *private_data);
421 void *private_data;
422 bool copy_to_notrans;
425 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
427 struct gencache_parse_state *state;
428 struct gencache_timeout t;
429 DATA_BLOB payload;
430 bool ret;
432 ret = gencache_pull_timeout(data, &t.timeout, &payload);
433 if (!ret) {
434 return -1;
436 state = (struct gencache_parse_state *)private_data;
437 state->parser(&t, payload, state->private_data);
439 if (state->copy_to_notrans) {
440 tdb_store(cache_notrans->tdb, key, data, 0);
443 return 0;
446 bool gencache_parse(const char *keystr,
447 void (*parser)(const struct gencache_timeout *timeout,
448 DATA_BLOB blob,
449 void *private_data),
450 void *private_data)
452 struct gencache_parse_state state;
453 TDB_DATA key = string_term_tdb_data(keystr);
454 int ret;
456 if (keystr == NULL) {
457 return false;
459 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
460 return false;
462 if (!gencache_init()) {
463 return false;
466 state.parser = parser;
467 state.private_data = private_data;
468 state.copy_to_notrans = false;
470 ret = tdb_chainlock(cache_notrans->tdb, key);
471 if (ret != 0) {
472 return false;
475 ret = tdb_parse_record(cache_notrans->tdb, key,
476 gencache_parse_fn, &state);
477 if (ret == 0) {
478 tdb_chainunlock(cache_notrans->tdb, key);
479 return true;
482 state.copy_to_notrans = true;
484 ret = tdb_parse_record(cache->tdb, key, gencache_parse_fn, &state);
486 if ((ret == -1) && (tdb_error(cache->tdb) == TDB_ERR_NOEXIST)) {
488 * The record does not exist. Set a delete-marker in
489 * gencache_notrans, so that we don't have to look at
490 * the fcntl-based cache again.
492 gencache_set(keystr, "", 0);
495 tdb_chainunlock(cache_notrans->tdb, key);
497 return (ret == 0);
500 struct gencache_get_data_blob_state {
501 TALLOC_CTX *mem_ctx;
502 DATA_BLOB *blob;
503 time_t timeout;
504 bool result;
507 static void gencache_get_data_blob_parser(const struct gencache_timeout *t,
508 DATA_BLOB blob,
509 void *private_data)
511 struct gencache_get_data_blob_state *state =
512 (struct gencache_get_data_blob_state *)private_data;
514 if (t->timeout == 0) {
515 state->result = false;
516 return;
518 state->timeout = t->timeout;
520 if (state->blob == NULL) {
521 state->result = true;
522 return;
525 *state->blob = data_blob_talloc(state->mem_ctx, blob.data,
526 blob.length);
527 if (state->blob->data == NULL) {
528 state->result = false;
529 return;
531 state->result = true;
535 * Get existing entry from the cache file.
537 * @param keystr string that represents a key of this entry
538 * @param blob DATA_BLOB that is filled with entry's blob
539 * @param timeout pointer to a time_t that is filled with entry's
540 * timeout
542 * @retval true when entry is successfully fetched
543 * @retval false for failure
546 bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
547 DATA_BLOB *blob,
548 time_t *timeout, bool *was_expired)
550 struct gencache_get_data_blob_state state;
551 bool expired = false;
553 state.result = false;
554 state.mem_ctx = mem_ctx;
555 state.blob = blob;
557 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
558 goto fail;
560 if (!state.result) {
561 goto fail;
563 if (state.timeout <= time(NULL)) {
565 * We're expired, delete the entry. We can't use gencache_del
566 * here, because that uses gencache_get_data_blob for checking
567 * the existence of a record. We know the thing exists and
568 * directly store an empty value with 0 timeout.
570 gencache_set(keystr, "", 0);
571 expired = true;
572 goto fail;
574 if (timeout) {
575 *timeout = state.timeout;
578 return true;
580 fail:
581 if (was_expired != NULL) {
582 *was_expired = expired;
584 if (state.result && state.blob) {
585 data_blob_free(state.blob);
587 return false;
590 struct stabilize_state {
591 bool written;
593 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
594 void *priv);
597 * Stabilize gencache
599 * Migrate the clear-if-first gencache data to the stable,
600 * transaction-based gencache.tdb
603 bool gencache_stabilize(void)
605 struct stabilize_state state;
606 int res;
607 char *now;
609 if (!gencache_init()) {
610 return false;
613 res = tdb_transaction_start_nonblock(cache->tdb);
614 if (res != 0) {
615 if (tdb_error(cache->tdb) == TDB_ERR_NOLOCK)
618 * Someone else already does the stabilize,
619 * this does not have to be done twice
621 return true;
624 DEBUG(10, ("Could not start transaction on gencache.tdb: "
625 "%s\n", tdb_errorstr(cache->tdb)));
626 return false;
629 res = tdb_lockall_nonblock(cache_notrans->tdb);
630 if (res != 0) {
631 tdb_transaction_cancel(cache->tdb);
632 DEBUG(10, ("Could not get allrecord lock on "
633 "gencache_notrans.tdb: %s\n",
634 tdb_errorstr(cache_notrans->tdb)));
635 return false;
638 state.written = false;
640 res = tdb_traverse(cache_notrans->tdb, stabilize_fn, &state);
641 if (res < 0) {
642 tdb_unlockall(cache_notrans->tdb);
643 tdb_transaction_cancel(cache->tdb);
644 return false;
647 if (!state.written) {
648 tdb_unlockall(cache_notrans->tdb);
649 tdb_transaction_cancel(cache->tdb);
650 return true;
653 res = tdb_transaction_commit(cache->tdb);
654 if (res != 0) {
655 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
656 "%s\n", tdb_errorstr(cache->tdb)));
657 tdb_unlockall(cache_notrans->tdb);
658 return false;
661 res = tdb_wipe_all(cache_notrans->tdb);
662 if (res < 0) {
663 DBG_DEBUG("tdb_wipe_all on gencache_notrans.tdb failed: %s\n",
664 tdb_errorstr(cache_notrans->tdb));
667 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
668 if (now != NULL) {
669 tdb_store(cache_notrans->tdb, last_stabilize_key(),
670 string_term_tdb_data(now), 0);
671 TALLOC_FREE(now);
674 res = tdb_unlockall(cache_notrans->tdb);
675 if (res != 0) {
676 DEBUG(10, ("tdb_unlockall on gencache.tdb failed: "
677 "%s\n", tdb_errorstr(cache->tdb)));
678 return false;
681 return true;
684 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
685 void *priv)
687 struct stabilize_state *state = (struct stabilize_state *)priv;
688 int res;
689 time_t timeout;
691 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
692 return 0;
695 if (!gencache_pull_timeout(val, &timeout, NULL)) {
696 DEBUG(10, ("Ignoring invalid entry\n"));
697 return 0;
699 if ((timeout < time(NULL)) || (val.dsize == 0)) {
700 res = tdb_delete(cache->tdb, key);
701 if (res == 0) {
702 state->written = true;
703 } else if (tdb_error(cache->tdb) == TDB_ERR_NOEXIST) {
704 res = 0;
706 } else {
707 res = tdb_store(cache->tdb, key, val, 0);
708 if (res == 0) {
709 state->written = true;
713 if (res != 0) {
714 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
715 tdb_errorstr(cache->tdb)));
716 return -1;
719 return 0;
723 * Get existing entry from the cache file.
725 * @param keystr string that represents a key of this entry
726 * @param valstr buffer that is allocated and filled with the entry value
727 * buffer's disposing must be done outside
728 * @param timeout pointer to a time_t that is filled with entry's
729 * timeout
731 * @retval true when entry is successfully fetched
732 * @retval false for failure
735 bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
736 time_t *ptimeout)
738 DATA_BLOB blob;
739 bool ret = false;
741 ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
742 if (!ret) {
743 return false;
745 if ((blob.data == NULL) || (blob.length == 0)) {
746 data_blob_free(&blob);
747 return false;
749 if (blob.data[blob.length-1] != '\0') {
750 /* Not NULL terminated, can't be a string */
751 data_blob_free(&blob);
752 return false;
754 if (value) {
756 * talloc_move generates a type-punned warning here. As we
757 * leave the function immediately, do a simple talloc_steal.
759 *value = (char *)talloc_steal(mem_ctx, blob.data);
760 return true;
762 data_blob_free(&blob);
763 return true;
767 * Set an entry in the cache file. If there's no such
768 * one, then add it.
770 * @param keystr string that represents a key of this entry
771 * @param value text representation value being cached
772 * @param timeout time when the value is expired
774 * @retval true when entry is successfully stored
775 * @retval false on failure
778 bool gencache_set(const char *keystr, const char *value, time_t timeout)
780 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
781 return gencache_set_data_blob(keystr, blob, timeout);
784 struct gencache_iterate_blobs_state {
785 void (*fn)(const char *key, DATA_BLOB value,
786 time_t timeout, void *private_data);
787 const char *pattern;
788 void *private_data;
789 bool in_persistent;
792 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
793 TDB_DATA data, void *priv)
795 struct gencache_iterate_blobs_state *state =
796 (struct gencache_iterate_blobs_state *)priv;
797 char *keystr;
798 char *free_key = NULL;
799 time_t timeout;
800 DATA_BLOB payload;
802 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
803 return 0;
805 if (state->in_persistent && tdb_exists(cache_notrans->tdb, key)) {
806 return 0;
809 if (key.dptr[key.dsize-1] == '\0') {
810 keystr = (char *)key.dptr;
811 } else {
812 /* ensure 0-termination */
813 keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
814 free_key = keystr;
815 if (keystr == NULL) {
816 goto done;
820 if (!gencache_pull_timeout(data, &timeout, &payload)) {
821 goto done;
824 if (timeout == 0) {
825 /* delete marker */
826 goto done;
829 if (fnmatch(state->pattern, keystr, 0) != 0) {
830 goto done;
833 DEBUG(10, ("Calling function with arguments "
834 "(key=[%s], timeout=[%s])\n",
835 keystr, timestring(talloc_tos(), timeout)));
837 state->fn(keystr, payload, timeout, state->private_data);
839 done:
840 TALLOC_FREE(free_key);
841 return 0;
844 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
845 time_t timeout, void *private_data),
846 void *private_data, const char *pattern)
848 struct gencache_iterate_blobs_state state;
850 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
851 return;
854 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
856 state.fn = fn;
857 state.pattern = pattern;
858 state.private_data = private_data;
860 state.in_persistent = false;
861 tdb_traverse(cache_notrans->tdb, gencache_iterate_blobs_fn, &state);
863 state.in_persistent = true;
864 tdb_traverse(cache->tdb, gencache_iterate_blobs_fn, &state);
868 * Iterate through all entries which key matches to specified pattern
870 * @param fn pointer to the function that will be supplied with each single
871 * matching cache entry (key, value and timeout) as an arguments
872 * @param data void pointer to an arbitrary data that is passed directly to the fn
873 * function on each call
874 * @param keystr_pattern pattern the existing entries' keys are matched to
878 struct gencache_iterate_state {
879 void (*fn)(const char *key, const char *value, time_t timeout,
880 void *priv);
881 void *private_data;
884 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
885 time_t timeout, void *private_data)
887 struct gencache_iterate_state *state =
888 (struct gencache_iterate_state *)private_data;
889 char *valstr;
890 char *free_val = NULL;
892 if (value.data[value.length-1] == '\0') {
893 valstr = (char *)value.data;
894 } else {
895 /* ensure 0-termination */
896 valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
897 free_val = valstr;
898 if (valstr == NULL) {
899 goto done;
903 DEBUG(10, ("Calling function with arguments "
904 "(key=[%s], value=[%s], timeout=[%s])\n",
905 key, valstr, timestring(talloc_tos(), timeout)));
907 state->fn(key, valstr, timeout, state->private_data);
909 done:
911 TALLOC_FREE(free_val);
914 void gencache_iterate(void (*fn)(const char *key, const char *value,
915 time_t timeout, void *dptr),
916 void *private_data, const char *pattern)
918 struct gencache_iterate_state state;
920 if (fn == NULL) {
921 return;
923 state.fn = fn;
924 state.private_data = private_data;
925 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);