s3: use TDB_INCOMPATIBLE_HASH (the jenkins hash) on all TDB_CLEAR_IF_FIRST tdb's.
[obnox/samba-ctdb.git] / source3 / lib / gencache.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Generic, persistent and shared between processes cache mechanism for use
5    by various parts of the Samba code
6
7    Copyright (C) Rafal Szczesniak    2002
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24
25 #undef  DBGC_CLASS
26 #define DBGC_CLASS DBGC_TDB
27
28 #define TIMEOUT_LEN 12
29 #define CACHE_DATA_FMT  "%12u/"
30 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
31 #define BLOB_TYPE "DATA_BLOB"
32 #define BLOB_TYPE_LEN 9
33
34 static struct tdb_context *cache;
35 static struct tdb_context *cache_notrans;
36
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
41  *
42  **/
43
44
45 /**
46  * Cache initialisation function. Opens cache tdb file or creates
47  * it if does not exist.
48  *
49  * @return true on successful initialisation of the cache or
50  *         false on failure
51  **/
52
53 static bool gencache_init(void)
54 {
55         char* cache_fname = NULL;
56         int open_flags = O_RDWR|O_CREAT;
57
58         /* skip file open if it's already opened */
59         if (cache) return True;
60
61         cache_fname = lock_path("gencache.tdb");
62
63         DEBUG(5, ("Opening cache file at %s\n", cache_fname));
64
65         cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, open_flags, 0644);
66
67         if (!cache && (errno == EACCES)) {
68                 open_flags = O_RDONLY;
69                 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, open_flags,
70                                      0644);
71                 if (cache) {
72                         DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
73                 }
74         }
75
76         if (!cache) {
77                 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
78                 return False;
79         }
80
81         cache_fname = lock_path("gencache_notrans.tdb");
82
83         DEBUG(5, ("Opening cache file at %s\n", cache_fname));
84
85         cache_notrans = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
86                                      open_flags, 0644);
87         if (cache_notrans == NULL) {
88                 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
89                           strerror(errno)));
90                 tdb_close(cache);
91                 return false;
92         }
93
94         return True;
95 }
96
97 static TDB_DATA last_stabilize_key(void)
98 {
99         TDB_DATA result;
100         result.dptr = (uint8_t *)"@LAST_STABILIZED";
101         result.dsize = 17;
102         return result;
103 }
104
105 /**
106  * Set an entry in the cache file. If there's no such
107  * one, then add it.
108  *
109  * @param keystr string that represents a key of this entry
110  * @param blob DATA_BLOB value being cached
111  * @param timeout time when the value is expired
112  *
113  * @retval true when entry is successfuly stored
114  * @retval false on failure
115  **/
116
117 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
118                             time_t timeout)
119 {
120         int ret;
121         TDB_DATA databuf;
122         char* val;
123         time_t last_stabilize;
124         static int writecount;
125
126         if (tdb_data_cmp(string_term_tdb_data(keystr),
127                          last_stabilize_key()) == 0) {
128                 DEBUG(10, ("Can't store %s as a key\n", keystr));
129                 return false;
130         }
131
132         if ((keystr == NULL) || (blob == NULL)) {
133                 return false;
134         }
135
136         if (!gencache_init()) return False;
137
138         val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
139         if (val == NULL) {
140                 return False;
141         }
142         val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
143         if (val == NULL) {
144                 return false;
145         }
146         val = (char *)talloc_append_blob(NULL, val, *blob);
147         if (val == NULL) {
148                 return false;
149         }
150
151         DEBUG(10, ("Adding cache entry with key = %s and timeout ="
152                    " %s (%d seconds %s)\n", keystr, ctime(&timeout),
153                    (int)(timeout - time(NULL)), 
154                    timeout > time(NULL) ? "ahead" : "in the past"));
155
156         ret = tdb_store_bystring(
157                 cache_notrans, keystr,
158                 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
159                 0);
160         TALLOC_FREE(val);
161
162         if (ret != 0) {
163                 return false;
164         }
165
166         /*
167          * Every 100 writes within a single process, stabilize the cache with
168          * a transaction. This is done to prevent a single transaction to
169          * become huge and chew lots of memory.
170          */
171         writecount += 1;
172         if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
173                 gencache_stabilize();
174                 writecount = 0;
175                 goto done;
176         }
177
178         /*
179          * Every 5 minutes, call gencache_stabilize() to not let grow
180          * gencache_notrans.tdb too large.
181          */
182
183         last_stabilize = 0;
184         databuf = tdb_fetch(cache_notrans, last_stabilize_key());
185         if ((databuf.dptr != NULL)
186             && (databuf.dptr[databuf.dsize-1] == '\0')) {
187                 last_stabilize = atoi((char *)databuf.dptr);
188                 SAFE_FREE(databuf.dptr);
189         }
190         if ((last_stabilize
191              + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
192             < time(NULL)) {
193                 gencache_stabilize();
194         }
195
196 done:
197         return ret == 0;
198 }
199
200 /**
201  * Delete one entry from the cache file.
202  *
203  * @param keystr string that represents a key of this entry
204  *
205  * @retval true upon successful deletion
206  * @retval false in case of failure
207  **/
208
209 bool gencache_del(const char *keystr)
210 {
211         bool exists, was_expired;
212         bool ret = false;
213         DATA_BLOB value;
214
215         if (keystr == NULL) {
216                 return false;
217         }
218
219         if (!gencache_init()) return False;     
220
221         DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
222
223         /*
224          * We delete an element by setting its timeout to 0. This way we don't
225          * have to do a transaction on gencache.tdb every time we delete an
226          * element.
227          */
228
229         exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
230
231         if (!exists && was_expired) {
232                 /*
233                  * gencache_get_data_blob has implicitly deleted this
234                  * entry, so we have to return success here.
235                  */
236                 return true;
237         }
238
239         if (exists) {
240                 data_blob_free(&value);
241                 ret = gencache_set(keystr, "", 0);
242         }
243         return ret;
244 }
245
246 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
247 {
248         time_t res;
249         char *endptr;
250
251         res = strtol(val, &endptr, 10);
252
253         if ((endptr == NULL) || (*endptr != '/')) {
254                 DEBUG(2, ("Invalid gencache data format: %s\n", val));
255                 return false;
256         }
257         if (pres != NULL) {
258                 *pres = res;
259         }
260         if (pendptr != NULL) {
261                 *pendptr = endptr;
262         }
263         return true;
264 }
265
266 /**
267  * Get existing entry from the cache file.
268  *
269  * @param keystr string that represents a key of this entry
270  * @param blob DATA_BLOB that is filled with entry's blob
271  * @param timeout pointer to a time_t that is filled with entry's
272  *        timeout
273  *
274  * @retval true when entry is successfuly fetched
275  * @retval False for failure
276  **/
277
278 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
279                             time_t *timeout, bool *was_expired)
280 {
281         TDB_DATA databuf;
282         time_t t;
283         char *endptr;
284         bool expired = false;
285
286         if (keystr == NULL) {
287                 goto fail;
288         }
289
290         if (tdb_data_cmp(string_term_tdb_data(keystr),
291                          last_stabilize_key()) == 0) {
292                 DEBUG(10, ("Can't get %s as a key\n", keystr));
293                 goto fail;
294         }
295
296         if (!gencache_init()) {
297                 goto fail;
298         }
299
300         databuf = tdb_fetch_bystring(cache_notrans, keystr);
301
302         if (databuf.dptr == NULL) {
303                 databuf = tdb_fetch_bystring(cache, keystr);
304         }
305
306         if (databuf.dptr == NULL) {
307                 DEBUG(10, ("Cache entry with key = %s couldn't be found \n",
308                            keystr));
309                 goto fail;
310         }
311
312         if (!gencache_pull_timeout((char *)databuf.dptr, &t, &endptr)) {
313                 SAFE_FREE(databuf.dptr);
314                 goto fail;
315         }
316
317         DEBUG(10, ("Returning %s cache entry: key = %s, value = %s, "
318                    "timeout = %s", t > time(NULL) ? "valid" :
319                    "expired", keystr, endptr+1, ctime(&t)));
320
321         if (t == 0) {
322                 /* Deleted */
323                 SAFE_FREE(databuf.dptr);
324                 goto fail;
325         }
326
327         if (t <= time(NULL)) {
328
329                 /*
330                  * We're expired, delete the entry. We can't use gencache_del
331                  * here, because that uses gencache_get_data_blob for checking
332                  * the existence of a record. We know the thing exists and
333                  * directly store an empty value with 0 timeout.
334                  */
335                 gencache_set(keystr, "", 0);
336
337                 SAFE_FREE(databuf.dptr);
338
339                 expired = true;
340                 goto fail;
341         }
342
343         if (blob != NULL) {
344                 *blob = data_blob(
345                         endptr+1,
346                         databuf.dsize - PTR_DIFF(endptr+1, databuf.dptr));
347                 if (blob->data == NULL) {
348                         SAFE_FREE(databuf.dptr);
349                         DEBUG(0, ("memdup failed\n"));
350                         goto fail;
351                 }
352         }
353
354         SAFE_FREE(databuf.dptr);
355
356         if (timeout) {
357                 *timeout = t;
358         }
359
360         return True;
361
362 fail:
363         if (was_expired != NULL) {
364                 *was_expired = expired;
365         }
366         return false;
367
368
369 struct stabilize_state {
370         bool written;
371         bool error;
372 };
373 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
374                         void *priv);
375
376 /**
377  * Stabilize gencache
378  *
379  * Migrate the clear-if-first gencache data to the stable,
380  * transaction-based gencache.tdb
381  */
382
383 bool gencache_stabilize(void)
384 {
385         struct stabilize_state state;
386         int res;
387         char *now;
388
389         if (!gencache_init()) {
390                 return false;
391         }
392
393         res = tdb_transaction_start_nonblock(cache);
394         if (res == -1) {
395
396                 if (tdb_error(cache) == TDB_ERR_NOLOCK) {
397                         /*
398                          * Someone else already does the stabilize,
399                          * this does not have to be done twice
400                          */
401                         return true;
402                 }
403
404                 DEBUG(10, ("Could not start transaction on gencache.tdb: "
405                            "%s\n", tdb_errorstr(cache)));
406                 return false;
407         }
408         res = tdb_transaction_start(cache_notrans);
409         if (res == -1) {
410                 tdb_transaction_cancel(cache);
411                 DEBUG(10, ("Could not start transaction on "
412                            "gencache_notrans.tdb: %s\n",
413                            tdb_errorstr(cache_notrans)));
414                 return false;
415         }
416
417         state.error = false;
418         state.written = false;
419
420         res = tdb_traverse(cache_notrans, stabilize_fn, &state);
421         if ((res == -1) || state.error) {
422                 if ((tdb_transaction_cancel(cache_notrans) == -1)
423                     || (tdb_transaction_cancel(cache) == -1)) {
424                         smb_panic("tdb_transaction_cancel failed\n");
425                 }
426                 return false;
427         }
428
429         if (!state.written) {
430                 if ((tdb_transaction_cancel(cache_notrans) == -1)
431                     || (tdb_transaction_cancel(cache) == -1)) {
432                         smb_panic("tdb_transaction_cancel failed\n");
433                 }
434                 return true;
435         }
436
437         res = tdb_transaction_commit(cache);
438         if (res == -1) {
439                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
440                            "%s\n", tdb_errorstr(cache)));
441                 if (tdb_transaction_cancel(cache_notrans) == -1) {
442                         smb_panic("tdb_transaction_cancel failed\n");
443                 }
444                 return false;
445         }
446
447         res = tdb_transaction_commit(cache_notrans);
448         if (res == -1) {
449                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
450                            "%s\n", tdb_errorstr(cache)));
451                 return false;
452         }
453
454         now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
455         if (now != NULL) {
456                 tdb_store(cache_notrans, last_stabilize_key(),
457                           string_term_tdb_data(now), 0);
458                 TALLOC_FREE(now);
459         }
460
461         return true;
462 }
463
464 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
465                         void *priv)
466 {
467         struct stabilize_state *state = (struct stabilize_state *)priv;
468         int res;
469         time_t timeout;
470
471         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
472                 return 0;
473         }
474
475         if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
476                 DEBUG(10, ("Ignoring invalid entry\n"));
477                 return 0;
478         }
479         if ((timeout < time(NULL)) || (val.dsize == 0)) {
480                 res = tdb_delete(cache, key);
481                 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
482                         res = 0;
483                 } else {
484                         state->written = true;
485                 }
486         } else {
487                 res = tdb_store(cache, key, val, 0);
488                 if (res == 0) {
489                         state->written = true;
490                 }
491         }
492
493         if (res == -1) {
494                 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
495                            tdb_errorstr(cache)));
496                 state->error = true;
497                 return -1;
498         }
499
500         if (tdb_delete(cache_notrans, key) == -1) {
501                 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
502                            "%s\n", tdb_errorstr(cache_notrans)));
503                 state->error = true;
504                 return -1;
505         }
506         return 0;
507 }
508
509 /**
510  * Get existing entry from the cache file.
511  *
512  * @param keystr string that represents a key of this entry
513  * @param valstr buffer that is allocated and filled with the entry value
514  *        buffer's disposing must be done outside
515  * @param timeout pointer to a time_t that is filled with entry's
516  *        timeout
517  *
518  * @retval true when entry is successfuly fetched
519  * @retval False for failure
520  **/
521
522 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
523 {
524         DATA_BLOB blob;
525         bool ret = False;
526
527         ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
528         if (!ret) {
529                 return false;
530         }
531         if ((blob.data == NULL) || (blob.length == 0)) {
532                 SAFE_FREE(blob.data);
533                 return false;
534         }
535         if (blob.data[blob.length-1] != '\0') {
536                 /* Not NULL terminated, can't be a string */
537                 SAFE_FREE(blob.data);
538                 return false;
539         }
540         *value = SMB_STRDUP((char *)blob.data);
541         data_blob_free(&blob);
542         if (*value == NULL) {
543                 return false;
544         }
545         return true;
546 }
547
548 /**
549  * Set an entry in the cache file. If there's no such
550  * one, then add it.
551  *
552  * @param keystr string that represents a key of this entry
553  * @param value text representation value being cached
554  * @param timeout time when the value is expired
555  *
556  * @retval true when entry is successfuly stored
557  * @retval false on failure
558  **/
559
560 bool gencache_set(const char *keystr, const char *value, time_t timeout)
561 {
562         DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
563         return gencache_set_data_blob(keystr, &blob, timeout);
564 }
565
566 /**
567  * Iterate through all entries which key matches to specified pattern
568  *
569  * @param fn pointer to the function that will be supplied with each single
570  *        matching cache entry (key, value and timeout) as an arguments
571  * @param data void pointer to an arbitrary data that is passed directly to the fn
572  *        function on each call
573  * @param keystr_pattern pattern the existing entries' keys are matched to
574  *
575  **/
576
577 struct gencache_iterate_state {
578         void (*fn)(const char *key, const char *value, time_t timeout,
579                    void *priv);
580         const char *pattern;
581         void *priv;
582         bool in_persistent;
583 };
584
585 static int gencache_iterate_fn(struct tdb_context *tdb, TDB_DATA key,
586                                TDB_DATA value, void *priv)
587 {
588         struct gencache_iterate_state *state =
589                 (struct gencache_iterate_state *)priv;
590         char *keystr;
591         char *free_key = NULL;
592         char *valstr;
593         char *free_val = NULL;
594         unsigned long u;
595         time_t timeout;
596         char *timeout_endp;
597
598         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
599                 return 0;
600         }
601
602         if (state->in_persistent && tdb_exists(cache_notrans, key)) {
603                 return 0;
604         }
605
606         if (key.dptr[key.dsize-1] == '\0') {
607                 keystr = (char *)key.dptr;
608         } else {
609                 /* ensure 0-termination */
610                 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
611                 free_key = keystr;
612         }
613
614         if ((value.dptr == NULL) || (value.dsize <= TIMEOUT_LEN)) {
615                 goto done;
616         }
617
618         if (fnmatch(state->pattern, keystr, 0) != 0) {
619                 goto done;
620         }
621
622         if (value.dptr[value.dsize-1] == '\0') {
623                 valstr = (char *)value.dptr;
624         } else {
625                 /* ensure 0-termination */
626                 valstr = SMB_STRNDUP((char *)value.dptr, value.dsize);
627                 free_val = valstr;
628         }
629
630         u = strtoul(valstr, &timeout_endp, 10);
631
632         if ((*timeout_endp != '/') || ((timeout_endp-valstr) != TIMEOUT_LEN)) {
633                 goto done;
634         }
635
636         timeout = u;
637         timeout_endp += 1;
638
639         DEBUG(10, ("Calling function with arguments "
640                    "(key = %s, value = %s, timeout = %s)\n",
641                    keystr, timeout_endp, ctime(&timeout)));
642         state->fn(keystr, timeout_endp, timeout, state->priv);
643
644  done:
645         SAFE_FREE(free_key);
646         SAFE_FREE(free_val);
647         return 0;
648 }
649
650 void gencache_iterate(void (*fn)(const char* key, const char *value, time_t timeout, void* dptr),
651                       void* data, const char* keystr_pattern)
652 {
653         struct gencache_iterate_state state;
654
655         if ((fn == NULL) || (keystr_pattern == NULL)) {
656                 return;
657         }
658
659         if (!gencache_init()) return;
660
661         DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
662
663         state.fn = fn;
664         state.pattern = keystr_pattern;
665         state.priv = data;
666
667         state.in_persistent = false;
668         tdb_traverse(cache_notrans, gencache_iterate_fn, &state);
669
670         state.in_persistent = true;
671         tdb_traverse(cache, gencache_iterate_fn, &state);
672 }