s3: Add gencache_iterate_blobs
[Samba.git] / source3 / lib / gencache.c
blobdb0b179e653d3b535175c5dfb9a793faa922f477
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"
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_TDB
29 #define TIMEOUT_LEN 12
30 #define CACHE_DATA_FMT "%12u/"
31 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
32 #define BLOB_TYPE "DATA_BLOB"
33 #define BLOB_TYPE_LEN 9
35 static struct tdb_context *cache;
36 static struct tdb_context *cache_notrans;
38 /**
39 * @file gencache.c
40 * @brief Generic, persistent and shared between processes cache mechanism
41 * for use by various parts of the Samba code
43 **/
46 /**
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
51 * false on failure
52 **/
54 static bool gencache_init(void)
56 char* cache_fname = NULL;
57 int open_flags = O_RDWR|O_CREAT;
58 bool first_try = true;
60 /* skip file open if it's already opened */
61 if (cache) return True;
63 cache_fname = lock_path("gencache.tdb");
65 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
67 again:
68 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
69 if (cache) {
70 int ret;
71 ret = tdb_check(cache, NULL, NULL);
72 if (ret != 0) {
73 tdb_close(cache);
74 cache = NULL;
75 if (!first_try) {
76 DEBUG(0, ("gencache_init: tdb_check(%s) failed\n",
77 cache_fname));
78 return false;
80 first_try = false;
81 DEBUG(0, ("gencache_init: tdb_check(%s) failed - retry after CLEAR_IF_FIRST\n",
82 cache_fname));
83 cache = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
84 if (cache) {
85 tdb_close(cache);
86 cache = NULL;
87 goto again;
92 if (!cache && (errno == EACCES)) {
93 open_flags = O_RDONLY;
94 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags,
95 0644);
96 if (cache) {
97 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
101 if (!cache) {
102 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
103 return False;
106 cache_fname = lock_path("gencache_notrans.tdb");
108 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
110 cache_notrans = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
111 open_flags, 0644);
112 if (cache_notrans == NULL) {
113 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
114 strerror(errno)));
115 tdb_close(cache);
116 cache = NULL;
117 return false;
120 return True;
123 static TDB_DATA last_stabilize_key(void)
125 TDB_DATA result;
126 result.dptr = (uint8_t *)"@LAST_STABILIZED";
127 result.dsize = 17;
128 return result;
132 * Set an entry in the cache file. If there's no such
133 * one, then add it.
135 * @param keystr string that represents a key of this entry
136 * @param blob DATA_BLOB value being cached
137 * @param timeout time when the value is expired
139 * @retval true when entry is successfuly stored
140 * @retval false on failure
143 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
144 time_t timeout)
146 int ret;
147 TDB_DATA databuf;
148 char* val;
149 time_t last_stabilize;
150 static int writecount;
152 if (tdb_data_cmp(string_term_tdb_data(keystr),
153 last_stabilize_key()) == 0) {
154 DEBUG(10, ("Can't store %s as a key\n", keystr));
155 return false;
158 if ((keystr == NULL) || (blob == NULL)) {
159 return false;
162 if (!gencache_init()) return False;
164 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
165 if (val == NULL) {
166 return False;
168 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
169 if (val == NULL) {
170 return false;
172 val = (char *)talloc_append_blob(NULL, val, *blob);
173 if (val == NULL) {
174 return false;
177 DEBUG(10, ("Adding cache entry with key = %s and timeout ="
178 " %s (%d seconds %s)\n", keystr, ctime(&timeout),
179 (int)(timeout - time(NULL)),
180 timeout > time(NULL) ? "ahead" : "in the past"));
182 ret = tdb_store_bystring(
183 cache_notrans, keystr,
184 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
186 TALLOC_FREE(val);
188 if (ret != 0) {
189 return false;
193 * Every 100 writes within a single process, stabilize the cache with
194 * a transaction. This is done to prevent a single transaction to
195 * become huge and chew lots of memory.
197 writecount += 1;
198 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
199 gencache_stabilize();
200 writecount = 0;
201 goto done;
205 * Every 5 minutes, call gencache_stabilize() to not let grow
206 * gencache_notrans.tdb too large.
209 last_stabilize = 0;
210 databuf = tdb_fetch(cache_notrans, last_stabilize_key());
211 if ((databuf.dptr != NULL)
212 && (databuf.dptr[databuf.dsize-1] == '\0')) {
213 last_stabilize = atoi((char *)databuf.dptr);
214 SAFE_FREE(databuf.dptr);
216 if ((last_stabilize
217 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
218 < time(NULL)) {
219 gencache_stabilize();
222 done:
223 return ret == 0;
227 * Delete one entry from the cache file.
229 * @param keystr string that represents a key of this entry
231 * @retval true upon successful deletion
232 * @retval false in case of failure
235 bool gencache_del(const char *keystr)
237 bool exists, was_expired;
238 bool ret = false;
239 DATA_BLOB value;
241 if (keystr == NULL) {
242 return false;
245 if (!gencache_init()) return False;
247 DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
250 * We delete an element by setting its timeout to 0. This way we don't
251 * have to do a transaction on gencache.tdb every time we delete an
252 * element.
255 exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
257 if (!exists && was_expired) {
259 * gencache_get_data_blob has implicitly deleted this
260 * entry, so we have to return success here.
262 return true;
265 if (exists) {
266 data_blob_free(&value);
267 ret = gencache_set(keystr, "", 0);
269 return ret;
272 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
274 time_t res;
275 char *endptr;
277 if (val == NULL) {
278 return false;
281 res = strtol(val, &endptr, 10);
283 if ((endptr == NULL) || (*endptr != '/')) {
284 DEBUG(2, ("Invalid gencache data format: %s\n", val));
285 return false;
287 if (pres != NULL) {
288 *pres = res;
290 if (pendptr != NULL) {
291 *pendptr = endptr;
293 return true;
296 struct gencache_parse_state {
297 void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
298 void *private_data;
301 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
303 struct gencache_parse_state *state;
304 DATA_BLOB blob;
305 time_t t;
306 char *endptr;
307 bool ret;
309 if (data.dptr == NULL) {
310 return -1;
312 ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
313 if (!ret) {
314 return -1;
316 state = (struct gencache_parse_state *)private_data;
317 blob = data_blob_const(
318 endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
319 state->parser(t, blob, state->private_data);
320 return 0;
323 bool gencache_parse(const char *keystr,
324 void (*parser)(time_t timeout, DATA_BLOB blob,
325 void *private_data),
326 void *private_data)
328 struct gencache_parse_state state;
329 TDB_DATA key;
330 int ret;
332 if (keystr == NULL) {
333 return false;
335 if (tdb_data_cmp(string_term_tdb_data(keystr),
336 last_stabilize_key()) == 0) {
337 return false;
339 if (!gencache_init()) {
340 return false;
343 key = string_term_tdb_data(keystr);
344 state.parser = parser;
345 state.private_data = private_data;
347 ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
348 if (ret != -1) {
349 return true;
351 ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
352 return (ret != -1);
355 struct gencache_get_data_blob_state {
356 DATA_BLOB *blob;
357 time_t timeout;
358 bool result;
361 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
362 void *private_data)
364 struct gencache_get_data_blob_state *state =
365 (struct gencache_get_data_blob_state *)private_data;
367 if (timeout == 0) {
368 state->result = false;
369 return;
371 state->timeout = timeout;
373 if (state->blob == NULL) {
374 state->result = true;
375 return;
378 *state->blob = data_blob(blob.data, blob.length);
379 if (state->blob->data == NULL) {
380 state->result = false;
381 return;
383 state->result = true;
387 * Get existing entry from the cache file.
389 * @param keystr string that represents a key of this entry
390 * @param blob DATA_BLOB that is filled with entry's blob
391 * @param timeout pointer to a time_t that is filled with entry's
392 * timeout
394 * @retval true when entry is successfuly fetched
395 * @retval False for failure
398 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
399 time_t *timeout, bool *was_expired)
401 struct gencache_get_data_blob_state state;
402 bool expired = false;
404 state.result = false;
405 state.blob = blob;
407 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
408 goto fail;
410 if (!state.result) {
411 goto fail;
413 if (state.timeout <= time(NULL)) {
415 * We're expired, delete the entry. We can't use gencache_del
416 * here, because that uses gencache_get_data_blob for checking
417 * the existence of a record. We know the thing exists and
418 * directly store an empty value with 0 timeout.
420 gencache_set(keystr, "", 0);
421 expired = true;
422 goto fail;
424 if (timeout) {
425 *timeout = state.timeout;
428 return True;
430 fail:
431 if (was_expired != NULL) {
432 *was_expired = expired;
434 return false;
437 struct stabilize_state {
438 bool written;
439 bool error;
441 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
442 void *priv);
445 * Stabilize gencache
447 * Migrate the clear-if-first gencache data to the stable,
448 * transaction-based gencache.tdb
451 bool gencache_stabilize(void)
453 struct stabilize_state state;
454 int res;
455 char *now;
457 if (!gencache_init()) {
458 return false;
461 res = tdb_transaction_start_nonblock(cache);
462 if (res == -1) {
464 if (tdb_error(cache) == TDB_ERR_NOLOCK) {
466 * Someone else already does the stabilize,
467 * this does not have to be done twice
469 return true;
472 DEBUG(10, ("Could not start transaction on gencache.tdb: "
473 "%s\n", tdb_errorstr(cache)));
474 return false;
476 res = tdb_transaction_start(cache_notrans);
477 if (res == -1) {
478 tdb_transaction_cancel(cache);
479 DEBUG(10, ("Could not start transaction on "
480 "gencache_notrans.tdb: %s\n",
481 tdb_errorstr(cache_notrans)));
482 return false;
485 state.error = false;
486 state.written = false;
488 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
489 if ((res == -1) || state.error) {
490 if ((tdb_transaction_cancel(cache_notrans) == -1)
491 || (tdb_transaction_cancel(cache) == -1)) {
492 smb_panic("tdb_transaction_cancel failed\n");
494 return false;
497 if (!state.written) {
498 if ((tdb_transaction_cancel(cache_notrans) == -1)
499 || (tdb_transaction_cancel(cache) == -1)) {
500 smb_panic("tdb_transaction_cancel failed\n");
502 return true;
505 res = tdb_transaction_commit(cache);
506 if (res == -1) {
507 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
508 "%s\n", tdb_errorstr(cache)));
509 if (tdb_transaction_cancel(cache_notrans) == -1) {
510 smb_panic("tdb_transaction_cancel failed\n");
512 return false;
515 res = tdb_transaction_commit(cache_notrans);
516 if (res == -1) {
517 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
518 "%s\n", tdb_errorstr(cache)));
519 return false;
522 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
523 if (now != NULL) {
524 tdb_store(cache_notrans, last_stabilize_key(),
525 string_term_tdb_data(now), 0);
526 TALLOC_FREE(now);
529 return true;
532 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
533 void *priv)
535 struct stabilize_state *state = (struct stabilize_state *)priv;
536 int res;
537 time_t timeout;
539 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
540 return 0;
543 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
544 DEBUG(10, ("Ignoring invalid entry\n"));
545 return 0;
547 if ((timeout < time(NULL)) || (val.dsize == 0)) {
548 res = tdb_delete(cache, key);
549 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
550 res = 0;
551 } else {
552 state->written = true;
554 } else {
555 res = tdb_store(cache, key, val, 0);
556 if (res == 0) {
557 state->written = true;
561 if (res == -1) {
562 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
563 tdb_errorstr(cache)));
564 state->error = true;
565 return -1;
568 if (tdb_delete(cache_notrans, key) == -1) {
569 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
570 "%s\n", tdb_errorstr(cache_notrans)));
571 state->error = true;
572 return -1;
574 return 0;
578 * Get existing entry from the cache file.
580 * @param keystr string that represents a key of this entry
581 * @param valstr buffer that is allocated and filled with the entry value
582 * buffer's disposing must be done outside
583 * @param timeout pointer to a time_t that is filled with entry's
584 * timeout
586 * @retval true when entry is successfuly fetched
587 * @retval False for failure
590 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
592 DATA_BLOB blob;
593 bool ret = False;
595 ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
596 if (!ret) {
597 return false;
599 if ((blob.data == NULL) || (blob.length == 0)) {
600 SAFE_FREE(blob.data);
601 return false;
603 if (blob.data[blob.length-1] != '\0') {
604 /* Not NULL terminated, can't be a string */
605 SAFE_FREE(blob.data);
606 return false;
608 if (value) {
609 *value = SMB_STRDUP((char *)blob.data);
610 data_blob_free(&blob);
611 if (*value == NULL) {
612 return false;
614 return true;
616 data_blob_free(&blob);
617 return true;
621 * Set an entry in the cache file. If there's no such
622 * one, then add it.
624 * @param keystr string that represents a key of this entry
625 * @param value text representation value being cached
626 * @param timeout time when the value is expired
628 * @retval true when entry is successfuly stored
629 * @retval false on failure
632 bool gencache_set(const char *keystr, const char *value, time_t timeout)
634 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
635 return gencache_set_data_blob(keystr, &blob, timeout);
638 struct gencache_iterate_blobs_state {
639 void (*fn)(const char *key, DATA_BLOB value,
640 time_t timeout, void *private_data);
641 const char *pattern;
642 void *private_data;
643 bool in_persistent;
646 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
647 TDB_DATA data, void *priv)
649 struct gencache_iterate_blobs_state *state =
650 (struct gencache_iterate_blobs_state *)priv;
651 char *keystr;
652 char *free_key = NULL;
653 time_t timeout;
654 char *endptr;
656 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
657 return 0;
659 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
660 return 0;
663 if (key.dptr[key.dsize-1] == '\0') {
664 keystr = (char *)key.dptr;
665 } else {
666 /* ensure 0-termination */
667 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
668 free_key = keystr;
671 if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
672 goto done;
674 endptr += 1;
676 if (fnmatch(state->pattern, keystr, 0) != 0) {
677 goto done;
680 DEBUG(10, ("Calling function with arguments (key=%s, timeout=%s)\n",
681 keystr, ctime(&timeout)));
683 state->fn(keystr,
684 data_blob_const(endptr,
685 data.dsize - PTR_DIFF(endptr, data.dptr)),
686 timeout, state->private_data);
688 done:
689 SAFE_FREE(free_key);
690 return 0;
693 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
694 time_t timeout, void *private_data),
695 void *private_data, const char *pattern)
697 struct gencache_iterate_blobs_state state;
699 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
700 return;
703 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
705 state.fn = fn;
706 state.pattern = pattern;
707 state.private_data = private_data;
709 state.in_persistent = false;
710 tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);
712 state.in_persistent = true;
713 tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
717 * Iterate through all entries which key matches to specified pattern
719 * @param fn pointer to the function that will be supplied with each single
720 * matching cache entry (key, value and timeout) as an arguments
721 * @param data void pointer to an arbitrary data that is passed directly to the fn
722 * function on each call
723 * @param keystr_pattern pattern the existing entries' keys are matched to
727 struct gencache_iterate_state {
728 void (*fn)(const char *key, const char *value, time_t timeout,
729 void *priv);
730 void *private_data;
733 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
734 time_t timeout, void *private_data)
736 struct gencache_iterate_state *state =
737 (struct gencache_iterate_state *)private_data;
738 char *valstr;
739 char *free_val = NULL;
741 if (value.data[value.length-1] == '\0') {
742 valstr = (char *)value.data;
743 } else {
744 /* ensure 0-termination */
745 valstr = SMB_STRNDUP((char *)value.data, value.length);
746 free_val = valstr;
749 DEBUG(10, ("Calling function with arguments "
750 "(key = %s, value = %s, timeout = %s)\n",
751 key, valstr, ctime(&timeout)));
753 state->fn(key, valstr, timeout, state->private_data);
755 SAFE_FREE(free_val);
758 void gencache_iterate(void (*fn)(const char *key, const char *value,
759 time_t timeout, void *dptr),
760 void *private_data, const char *pattern)
762 struct gencache_iterate_state state;
764 if (fn == NULL) {
765 return;
767 state.fn = fn;
768 state.private_data = private_data;
769 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);