2 * cdb, cdb-wr - Tcl bindings for tinycdb and a journalling write extension
3 * Copyright 2006-2012 Ian Jackson
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "chiark_tcl_cdb.h"
21 #define KEYLEN_MAX (INT_MAX/2)
26 /*---------- Forward declarations ----------*/
30 /*---------- Useful routines ----------*/
32 static void maybe_close(int fd) {
36 /*==================== Subsystems and subtypes ====================*/
38 /*---------- Pathbuf ----------*/
40 typedef struct Pathbuf {
46 static void pathbuf_init(Pathbuf *pb, const char *pathb) {
47 size_t l= strlen(pathb);
49 pb->buf= TALLOC(l + MAX_SUFFIX + 1);
50 memcpy(pb->buf, pathb, l);
53 static const char *pathbuf_sfx(Pathbuf *pb, const char *suffix) {
54 assert(strlen(suffix) <= MAX_SUFFIX);
55 strcpy(pb->sfx, suffix);
58 static void pathbuf_free(Pathbuf *pb) {
63 /*---------- Our hash table ----------*/
65 typedef struct HashTable {
67 Byte padding[128]; /* allow for expansion by Tcl, urgh */
71 typedef struct HashValue {
76 static HashValue *htv_prep(int len) {
78 hd= TALLOC(offsetof(typeof(*hd), data) + len);
82 static Byte *htv_fillptr(HashValue *hd) {
86 static void ht_setup(HashTable *ht) {
87 Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
89 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
93 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
94 if (!new) TFREE(Tcl_GetHashValue(he));
95 Tcl_SetHashValue(he, val_eat);
96 /* eats the value since the data structure owns the memory */
98 static void ht_maybeupdate(HashTable *ht, const char *key,
100 /* like ht_update except does not overwrite existing values */
104 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
105 if (!new) { TFREE(val_eat); return; }
106 Tcl_SetHashValue(he, val_eat);
109 static const HashValue *ht_lookup(HashTable *ht, const char *key) {
112 he= Tcl_FindHashEntry(&ht->t, key);
115 return Tcl_GetHashValue(he);
118 static int ht_forall(HashTable *ht,
119 int (*fn)(const char *key, HashValue *val,
120 struct ht_forall_ctx *ctx),
121 struct ht_forall_ctx *ctx) {
122 /* Returns first positive value returned by any call to fn, or 0. */
129 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
131 he= Tcl_NextHashEntry(&sp)) {
132 val= Tcl_GetHashValue(he);
133 if (!val->len) continue;
135 key= Tcl_GetHashKey(&ht->t, he);
137 r= fn(key, val, ctx);
143 static void ht_destroy(HashTable *ht) {
147 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
149 he= Tcl_NextHashEntry(&sp)) {
150 /* ht_forall skips empty (deleted) entries so is no good for this */
151 TFREE(Tcl_GetHashValue(he));
153 Tcl_DeleteHashTable(&ht->t);
156 /*==================== Existential ====================*/
158 /*---------- Rw data structure ----------*/
163 struct cdb cdb; /* valid iff cdb_fd >= 0 */
164 FILE *logfile; /* may be 0; if so, is broken */
166 Pathbuf pbsome, pbother;
168 ScriptToInvoke on_info, on_lexminval;
171 static void rw_cdb_close(Tcl_Interp *ip, Rw *rw) {
172 if (rw->cdb_fd >= 0) cdb_free(&rw->cdb);
173 maybe_close(rw->cdb_fd);
176 static int rw_close(Tcl_Interp *ip, Rw *rw) {
180 ht_destroy(&rw->logincore);
182 maybe_close(rw->lock_fd);
185 r= fclose(rw->logfile);
186 if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
187 " fclose logfile during untidy close"); }
190 pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
194 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw_v) {
198 const IdDataSpec cdbtcl_rwdatabases= {
199 "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
202 /*---------- File handling ----------*/
204 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
205 /* *lockfd_r must be -1 on entry. If may be set to >=0 even
206 * on error, and must be closed by the caller. */
211 um= umask(~(mode_t)0);
214 lockmode= 0666 & ~((um & 0444)>>1);
215 /* Remove r where umask would remove w;
216 * eg umask intending 0664 here gives 0660 */
218 *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDWR|O_CREAT, lockmode);
220 return cht_posixerr(ip, errno, "could not open/create lockfile");
223 fl.l_whence= SEEK_SET;
228 r= fcntl(*lockfd_r, F_SETLK, &fl);
230 if (errno == EACCES || errno == EAGAIN)
231 return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
232 else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
239 /*---------- Log reading and writing ----------*/
241 static int readlognum(FILE *f, int delim, int *num_r) {
243 char numbuf[20], *p, *ep;
248 c= getc(f); if (c==EOF) return -2;
249 if (c == delim) break;
250 if (!isdigit((unsigned char)c)) return -2;
252 if (p == numbuf+sizeof(numbuf)) return -2;
254 if (p == numbuf) return -2;
257 errno=0; ul= strtoul(numbuf, &ep, 10);
258 if (*ep || errno || ul >= KEYLEN_MAX) return -2;
263 static int readstorelogrecord(FILE *f, HashTable *ht,
264 int (*omitfn)(const HashValue*,
265 struct ht_forall_ctx *ctx),
266 struct ht_forall_ctx *ctx,
267 void (*updatefn)(HashTable*, const char*,
272 * -2 corrupt or error
273 * -3 got newline indicating end
274 * >0 value from omitfn
282 if (c==EOF) { return feof(f) ? -1 : -2; }
283 if (c=='\n') return -3;
284 if (c!='+') return -2;
286 rc= readlognum(f, ',', &keylen); if (rc) return rc;
287 rc= readlognum(f, ':', &vallen); if (rc) return rc;
289 key= TALLOC(keylen+1);
290 val= htv_prep(vallen);
292 r= fread(key, 1,keylen, f);
293 if (r!=keylen) goto x2_free_keyval;
294 if (memchr(key,0,keylen)) goto x2_free_keyval;
297 c= getc(f); if (c!='-') goto x2_free_keyval;
298 c= getc(f); if (c!='>') goto x2_free_keyval;
300 r= fread(htv_fillptr(val), 1,vallen, f);
301 if (r!=vallen) goto x2_free_keyval;
303 c= getc(f); if (c!='\n') goto x2_free_keyval;
305 rc= omitfn ? omitfn(val, ctx) : TCL_OK;
306 if (rc) { assert(rc>0); TFREE(val); }
307 else updatefn(ht, key, val);
318 static int writerecord(FILE *f, const char *key, const HashValue *val) {
321 r= fprintf(f, "+%d,%d:%s->", (int)strlen(key), val->len, key);
324 r= fwrite(val->data, 1, val->len, f);
325 if (r != val->len) return -1;
328 if (r==EOF) return -1;
333 /*---------- Creating ----------*/
335 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
337 static const char *const toremoves[]= { ".cdb", ".jrn", ".tmp", 0 };
340 int lock_fd=-1, rc, r;
342 const char *const *toremove;
345 pathbuf_init(&pb, pathb);
346 pathbuf_init(&pbmain, pathb);
348 rc= acquire_lock(ip, &pb, &lock_fd); if (rc) goto x_rc;
350 r= lstat(pathbuf_sfx(&pbmain, ".main"), &stab);
351 if (!r) { rc= cht_staticerr(ip, "database already exists during creation",
352 "CDB ALREADY-EXISTS"); goto x_rc; }
353 if (errno != ENOENT) PE("check for existing database .main during creation");
355 for (toremove=toremoves; *toremove; toremove++) {
356 r= remove(pathbuf_sfx(&pb, *toremove));
357 if (r && errno != ENOENT)
358 PE("delete possible spurious file during creation");
361 f= fopen(pathbuf_sfx(&pb, ".tmp"), "w");
362 if (!f) PE("create new database .tmp");
363 r= putc('\n', f); if (r==EOF) PE("write sentinel to new database .tmp");
364 r= fclose(f); f=0; if (r) PE("close new database .tmp during creation");
366 r= rename(pb.buf, pbmain.buf);
367 if (r) PE("install new database .tmp as .main (finalising creation)");
373 maybe_close(lock_fd);
375 pathbuf_free(&pbmain);
379 /*---------- Info callbacks ----------*/
381 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
382 const char *arg2fmt, const char *arg3, va_list al) {
386 vsnprintf(buf, sizeof(buf), arg2fmt, al);
389 aa[na++]= cht_ret_string(ip, arg1);
390 aa[na++]= cht_ret_string(ip, buf);
391 if (arg3) aa[na++]= cht_ret_string(ip, arg3);
393 return cht_scriptinv_invoke_fg(&rw->on_info, na, aa);
396 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
397 const char *arg2fmt, const char *arg3, ...) {
401 rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
406 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
407 const char *arg2fmt, ...) {
410 va_start(al, arg2fmt);
411 rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
416 /*---------- Opening ----------*/
418 static int cdbinit(Tcl_Interp *ip, Rw *rw) {
419 /* On entry, cdb_fd >=0 but cdb is _undefined_
420 * On exit, either cdb_fd<0 or cdb is initialised */
423 r= cdb_init(&rw->cdb, rw->cdb_fd);
425 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
426 close(rw->cdb_fd); rw->cdb_fd= -1; return rc;
431 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
432 Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
434 const Cdbwr_SubCommand *subcmd= cd;
435 int r, rc, mainfd=-1;
438 off_t logrecstart, logjunkpos;
440 rw= TALLOC(sizeof(*rw));
442 ht_setup(&rw->logincore);
443 cht_scriptinv_init(&rw->on_info);
444 cht_scriptinv_init(&rw->on_lexminval);
445 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
446 pathbuf_init(&rw->pbsome, pathb);
447 pathbuf_init(&rw->pbother, pathb);
450 rc= cht_scriptinv_set(&rw->on_info, ip, on_info, 0);
453 rc= cht_scriptinv_set(&rw->on_lexminval, ip, on_lexminval, 0);
456 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
457 if (mainfd<0) PE("open existing database file .main");
458 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
460 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
461 rw->mainsz= stab.st_size;
463 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
464 if (rw->cdb_fd >=0) {
465 rc= cdbinit(ip, rw); if (rc) goto x_rc;
466 } else if (errno == ENOENT) {
467 if (rw->mainsz > 1) {
468 rc= cht_staticerr(ip, ".cdb does not exist but .main is >1byte -"
469 " .cdb must have been accidentally deleted!",
478 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".jrn"), "r+");
480 if (errno != ENOENT) PE("failed to open .jrn during open");
481 rw->logfile= fopen(rw->pbsome.buf, "w");
482 if (!rw->logfile) PE("create .jrn during (clean) open");
483 } else { /* rw->logfile */
484 r= fstat(fileno(rw->logfile), &stab);
485 if (r==-1) PE("fstat .jrn during open");
486 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
487 (unsigned long)stab.st_size);
491 logrecstart= ftello(rw->logfile);
492 if (logrecstart < 0) PE("ftello .jrn during (dirty) open");
493 r= readstorelogrecord(rw->logfile, &rw->logincore, 0,0, ht_update);
494 if (ferror(rw->logfile)) {
495 rc= cht_posixerr(ip, errno, "error reading .jrn during (dirty) open");
500 } else if (r==-2 || r==-3) {
502 logjunkpos= ftello(rw->logfile);
503 if(logjunkpos<0) PE("ftello .jrn during report of junk in dirty open");
505 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
506 (unsigned long)logjunkpos, (unsigned long)logrecstart);
508 if (!(subcmd->flags & RWSCF_OKJUNK)) {
509 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
510 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
512 Tcl_AppendResult(ip, "syntax error (junk) in .jrn during"
513 " (dirty) open, at file position ", buf, (char*)0);
517 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
518 (unsigned long)logjunkpos);
521 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
522 if (r) PE("failed to fseeko .jrn before junk during dirty open");
524 r= ftruncate(fileno(rw->logfile), logrecstart);
525 if (r) PE("ftruncate .jrn to chop junk during dirty open");
531 /* now log is positioned for appending and everything is read */
544 int cht_do_cdbwr_open_okjunk(ClientData cd, Tcl_Interp *ip, const char *pathb,
545 Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
547 return cht_do_cdbwr_open(cd,ip,pathb,on_info,on_lexminval,result);
550 /*==================== COMPACTION ====================*/
552 struct ht_forall_ctx {
553 struct cdb_make cdbm;
557 const char *lexminval; /* may be invalid if lexminvall <= 0 */
560 /*---------- helper functions ----------*/
562 static int expiredp(const HashValue *val, struct ht_forall_ctx *a) {
564 if (!val->len || a->lexminvall<=0) return 0;
565 l= val->len < a->lexminvall ? val->len : a->lexminvall;
566 r= memcmp(val->data, a->lexminval, l);
569 return val->len < a->lexminvall;
572 static int delete_ifexpired(const char *key, HashValue *val,
573 struct ht_forall_ctx *a) {
574 if (!expiredp(val, a)) return 0;
576 /* we don't actually need to realloc it to free the memory because
577 * this will shortly all be deleted as part of the compaction */
581 static int addto_cdb(const char *key, HashValue *val,
582 struct ht_forall_ctx *a) {
583 return cdb_make_add(&a->cdbm, key, strlen(key), val->data, val->len);
586 static int addto_main(const char *key, HashValue *val,
587 struct ht_forall_ctx *a) {
589 return writerecord(a->mainfile, key, val);
592 /*---------- compact main entrypoint ----------*/
594 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsz,
596 /* creates new .cdb and .main
598 * leaves .jrn with old data
599 * leaves cdb fd open onto old db
600 * leaves logincore full of crap
603 int cdbfd, cdbmaking;
604 off_t errpos, newmainsz;
607 struct ht_forall_ctx a;
613 a.reccount= reccount_r;
615 r= fclose(rw->logfile);
617 if (r) { rc= cht_posixerr(ip, errno, "probable data loss! failed to fclose"
618 " logfile during compact"); goto x_rc; }
620 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
621 logsz, (unsigned long)rw->mainsz);
624 if (cht_scriptinv_interp(&rw->on_lexminval)) {
625 rc= cht_scriptinv_invoke_fg(&rw->on_lexminval, 0,0);
628 res= Tcl_GetObjResult(ip); assert(res);
629 a.lexminval= Tcl_GetStringFromObj(res, &a.lexminvall);
632 /* we rely not calling Tcl_Eval during the actual compaction;
633 * if we did Tcl_Eval then the interp result would be trashed.
635 rc= ht_forall(&rw->logincore, delete_ifexpired, &a);
641 /* merge unsuperseded records from main into hash table */
643 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
644 if (!a.mainfile) PE("failed to open .main for reading during compact");
647 r= readstorelogrecord(a.mainfile, &rw->logincore,
650 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
651 " .main during compact"); goto x_rc; }
654 } else if (r==-1 || r==-2) {
655 errpos= ftello(a.mainfile);
656 if (errpos<0) PE("ftello .main during report of syntax error");
657 snprintf(buf,sizeof(buf), "CDB %s MAIN %lu",
658 r==-1 ? "TRUNCATED" : "SYNTAX", (unsigned long)errpos);
659 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
660 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
663 r==-1 ? "unexpected eof (truncated file)"
664 " in .main during compact, at file position "
666 " in .main during compact, at file position ",
679 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
680 if (cdbfd<0) PE("create .tmp for new cdb during compact");
682 r= cdb_make_start(&a.cdbm, cdbfd);
683 if (r) PE("cdb_make_start during compact");
686 r= ht_forall(&rw->logincore, addto_cdb, &a);
687 if (r) PE("cdb_make_add during compact");
689 r= cdb_make_finish(&a.cdbm);
690 if(r) PE("cdb_make_finish during compact");
693 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
694 r= close(cdbfd); if (r) PE("close new cdb during compact");
697 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
698 if (r) PE("install new .cdb during compact");
700 /* create new main */
702 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
703 if (!a.mainfile) PE("create .tmp for new main during compact");
705 r= ht_forall(&rw->logincore, addto_main, &a);
706 if (r) { rc= cht_posixerr(ip, errno, "error writing to new .main"
707 " during compact"); goto x_rc; }
709 r= putc('\n', a.mainfile);
710 if (r==EOF) PE("write trailing \n to main during compact");
712 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
713 r= fdatasync(fileno(a.mainfile));
714 if (r) PE("fdatasync new main during compact");
716 newmainsz= ftello(a.mainfile);
717 if (newmainsz<0) PE("ftello new main during compact");
719 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
722 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
723 if (r) PE("install new .main during compact");
725 rw->mainsz= newmainsz;
729 rc= infocb(ip, rw, "compact-end", "main=%luby nrecs=%ld",
730 (unsigned long)rw->mainsz, *a.reccount);
736 if (a.mainfile) fclose(a.mainfile);
737 if (cdbmaking) cdb_make_finish(&a.cdbm);
739 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
743 /*---------- Closing ----------*/
745 static int compact_forclose(Tcl_Interp *ip, Rw *rw, long *reccount_r) {
749 logsz= ftello(rw->logfile);
750 if (logsz < 0) PE("ftello logfile (during tidy close)");
752 rc= compact_core(ip, rw, logsz, reccount_r); if (rc) goto x_rc;
754 r= remove(pathbuf_sfx(&rw->pbsome,".jrn"));
755 if (r) PE("remove .jrn (during tidy close)");
762 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
768 if (rw->autocompact) rc= compact_forclose(ip, rw, &reccount);
773 logsz= ftello(rw->logfile);
775 rc= cht_posixerr(ip, errno, "ftell logfile during close info");
777 rc= infocb(ip, rw, "close", "main=%luby log=%luby",
779 } else if (reccount>=0) {
780 rc= infocb(ip, rw, "close", "main=%luby nrecs=%ld",
781 rw->mainsz, reccount);
783 rc= infocb(ip, rw, "close", "main=%luby", rw->mainsz);
786 rc_close= rw_close(ip,rw);
787 if (rc_close) rc= rc_close;
789 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
794 /*---------- Other compaction-related entrypoints ----------*/
796 static int compact_keepopen(Tcl_Interp *ip, Rw *rw, int force) {
801 logsz= ftello(rw->logfile);
802 if (logsz < 0) return cht_posixerr(ip, errno, "ftell .jrn"
803 " during compact check or force");
805 if (!force && logsz < rw->mainsz / 3 + 1000) return TCL_OK;
806 /* Test case: ^^^ testing best value for this
807 * main=9690434by nrecs=122803 read all in one go
808 * no autocompact, : 6.96user 0.68system 0:08.93elapsed
809 * auto, mulitplier 2: 7.10user 0.79system 0:09.54elapsed
810 * auto, unity: 7.80user 0.98system 0:11.84elapsed
811 * auto, divisor 2: 8.23user 1.05system 0:13.30elapsed
812 * auto, divisor 3: 8.55user 1.12system 0:12.88elapsed
813 * auto, divisor 5: 9.95user 1.43system 0:15.72elapsed
816 rc= compact_core(ip, rw, logsz, &reccount); if (rc) goto x_rc;
819 ht_destroy(&rw->logincore);
820 ht_setup(&rw->logincore);
822 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
823 if (rw->cdb_fd < 0) PE("reopen .cdb after compact");
825 rc= cdbinit(ip, rw); if (rc) goto x_rc;
827 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".jrn"), "w");
828 if (!rw->logfile) PE("reopen .jrn after compact");
830 r= fsync(fileno(rw->logfile)); if (r) PE("fsync .jrn after compact reopen");
835 /* doom! all updates fail after this (because rw->logfile is 0), and
836 * we may be using a lot more RAM than would be ideal. Program will
837 * have to reopen if it really wants sanity. */
841 int cht_do_cdbwr_compact_force(ClientData cd, Tcl_Interp *ip, void *rw_v) {
842 return compact_keepopen(ip, rw_v, 1);
844 int cht_do_cdbwr_compact_check(ClientData cd, Tcl_Interp *ip, void *rw_v) {
845 return compact_keepopen(ip, rw_v, 0);
848 int cht_do_cdbwr_compact_explicit(ClientData cd, Tcl_Interp *ip, void *rw_v) {
853 int cht_do_cdbwr_compact_auto(ClientData cd, Tcl_Interp *ip, void *rw_v) {
859 /*---------- Updateing ----------*/
861 static int update(Tcl_Interp *ip, Rw *rw, const char *key,
862 const Byte *data, int dlen) {
868 if (strlen(key) >= KEYLEN_MAX)
869 return cht_staticerr(ip, "key too long", "CDB KEYOVERFLOW");
871 if (!rw->logfile) return cht_staticerr
872 (ip, "failure during previous compact or error recovery;"
873 " cdbwr must be closed and reopened before any further updates",
876 recstart= ftello(rw->logfile);
878 return cht_posixerr(ip, errno, "failed to ftello .jrn during update");
880 val= htv_prep(dlen); assert(val);
881 memcpy(htv_fillptr(val), data, dlen);
883 r= writerecord(rw->logfile, key, val);
884 if (!r) r= fflush(rw->logfile);
885 if (r) PE("write update to logfile");
887 ht_update(&rw->logincore, key, val);
889 if (!rw->autocompact) return TCL_OK;
890 return compact_keepopen(ip, rw, 0);
896 /* Now, we have to try to sort out the journal so that it's
897 * truncated and positioned to where this abortively-written record
898 * started, with no buffered output and the error indicator clear.
900 * There seems to be no portable way to ensure the buffered unwritten
901 * output is discarded, so we close and reopen the stream.
905 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".jrn"), "r+");
906 if (!rw->logfile) { failed= "fopen"; goto reset_fail; }
908 r= ftruncate(fileno(rw->logfile), recstart);
909 if (r) { failed= "ftruncate"; goto reset_fail; }
911 r= fseeko(rw->logfile, recstart, SEEK_SET);
912 if (r) { failed= "fseeko"; goto reset_fail; }
917 Tcl_AppendResult(ip, " (additionally, ", failed, " failed"
918 " in error recovery: ", strerror(errno), ")", (char*)0);
919 if (rw->logfile) { fclose(rw->logfile); rw->logfile= 0; }
924 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip,
925 void *rw_v, const char *key, Tcl_Obj *value) {
928 data= Tcl_GetStringFromObj(value, &dlen); assert(data);
929 return update(ip, rw_v, key, data, dlen);
932 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip,
933 void *rw_v, const char *key, HBytes_Value value) {
934 return update(ip, rw_v, key, cht_hb_data(&value), cht_hb_len(&value));
937 int cht_do_cdbwr_delete(ClientData cd, Tcl_Interp *ip, void *rw_v,
939 return update(ip, rw_v, key, 0, 0);
942 /*---------- Lookups ----------*/
944 static int lookup_rw(Tcl_Interp *ip, void *rw_v, const char *key,
945 const Byte **data_r, int *len_r /* -1 => notfound */) {
947 const HashValue *val;
949 val= ht_lookup(&rw->logincore, key);
951 if (val->len) { *data_r= val->data; *len_r= val->len; return TCL_OK; }
955 if (rw->cdb_fd<0) goto not_found;
957 return cht_cdb_lookup_cdb(ip, &rw->cdb, key, strlen(key), data_r, len_r);
965 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *rw_v,
966 const char *key, Tcl_Obj *def,
971 r= lookup_rw(ip, rw_v, key, &data, &dlen); if (r) return r;
972 return cht_cdb_donesomelookup(ip, rw_v, def, result, data, dlen,
973 cht_cdb_storeanswer_string);
976 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *rw_v,
977 const char *key, Tcl_Obj *def,
982 r= lookup_rw(ip, rw_v, key, &data, &dlen); if (r) return r;
983 return cht_cdb_donesomelookup(ip, rw_v, def, result, data, dlen,
984 cht_cdb_storeanswer_hb);