3 #include "chiark_tcl_cdb.h"
8 /*---------- Forward declarations ----------*/
12 /*---------- Useful routines ----------*/
14 static void maybe_close(int fd) {
19 rc= cht_posixerr(ip, errno, "failed to " m); goto x_rc; \
22 /*==================== Subsystems and subtypes ====================*/
24 /*---------- Pathbuf ----------*/
26 typedef struct Pathbuf {
32 static void pathbuf_init(Pathbuf *pb, const char *pathb) {
34 pb->buf= TALLOC(l + 4);
35 memcpy(pb->buf, pathb, l);
39 static const char *pathbuf_sfx(Pathbuf *pb, const char *suffix) {
40 assert(strlen(suffix) <= MAX_SUFFIX);
41 strcpy(pb->sfx, suffix);
44 static void pathbuf_free(Pathbuf *pb) {
49 /*---------- Our hash table ----------*/
51 typedef struct HashTable {
53 Byte padding[128]; /* allow for expansion by Tcl, urgh */
57 typedef struct HashValue {
62 static HashValue *htv_prep(int len) {
64 hd= TALLOC((hd->data - (Byte*)hd) + len);
68 static Byte *htv_fillptr(HashValue *hd) {
72 static void htv_fill(HashValue *hd, const Byte *data) {
73 memcpy(hd->data, data, hd->len);
77 static void ht_setup(HashTable *ht) {
78 Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
80 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
84 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
85 if (!new) TFREE(Tcl_GetHashValue(he));
86 Tcl_SetHashValue(he, val_eat);
87 /* eats the value since the data structure owns the memory */
89 static void ht_maybeupdate(HashTable *ht, const char *key,
91 /* like ht_update except does not overwrite existing values */
95 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
96 if (!new) { TFREE(val_eat); return; }
97 Tcl_SetHashValue(he, val_eat);
100 static int ht_forall(HashTable *ht,
101 int (*fn)(const char *key, HashValue *val,
102 struct ht_forall_ctx *ctx),
103 struct ht_forall_ctx *ctx) {
104 /* Returns first positive value returned by any call to fn, or 0. */
111 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
113 he= Tcl_NextHashEntry(&sp)) {
114 val= Tcl_GetHashValue(he);
115 if (!val->len) continue;
117 key= Tcl_GetHashKey(&ht->t, he);
119 r= fn(key, val, ctx);
125 static void ht_destroy(HashTable *ht) {
129 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
131 he= Tcl_NextHashEntry(&sp)) {
132 /* ht_forall skips empty (deleted) entries so is no good for this */
133 TFREE(Tcl_GetHashValue(he));
135 Tcl_DeleteHashTable(&ht->t);
138 /*==================== Existential ====================*/
140 /*---------- Rw data structure ----------*/
145 struct cdb cdb; /* valid iff cdb_fd >= 0 */
148 Pathbuf pbsome, pbother;
150 ScriptToInvoke on_info, on_lexminval;
153 static int rw_close(Tcl_Interp *ip, Rw *rw) {
157 ht_destroy(&rw->logincore);
158 if (rw->cdb_fd >= 0) cdb_free(&rw->cdb);
159 maybe_close(rw->cdb_fd);
160 maybe_close(rw->lock_fd);
163 r= fclose(rw->logfile);
164 if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
165 " fclose logfile during untidy close"); }
168 pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
173 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
174 const IdDataSpec cdbtcl_rwdatabases= {
175 "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
178 /*---------- File handling ----------*/
180 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
181 /* *lockfd_r must be -1 on entry. If may be set to >=0 even
182 * on error, and must be closed by the caller. */
187 um= umask(~(mode_t)0);
190 lockmode= 0666 & ~((um & 0444)>>1);
191 /* Remove r where umask would remove w;
192 * eg umask intending 0664 here gives 0660 */
194 *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
196 return cht_posixerr(ip, errno, "could not open/create lockfile");
199 fl.l_whence= SEEK_SET;
204 r= fcntl(*lockfd_r, F_SETLK, &fl);
206 if (errno == EACCES || errno == EAGAIN)
207 return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
208 else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
215 /*---------- Log reading ----------*/
217 static int readlognum(FILE *f, int delim, int *num_r) {
219 char numbuf[20], *p, *ep;
224 c= getc(f); if (c==EOF) return -2;
225 if (c == delim) break;
226 if (!isdigit((unsigned char)c)) return -2;
228 if (p == numbuf+sizeof(numbuf)) return -2;
230 if (p == numbuf) return -2;
233 errno=0; ul= strtoul(numbuf, &ep, 10);
234 if (*ep || errno || ul >= INT_MAX/2) return -2;
239 static int readstorelogrecord(FILE *f, HashTable *ht,
240 int (*omitfn)(const HashValue*,
241 struct ht_forall_ctx *ctx),
242 struct ht_forall_ctx *ctx,
243 void (*updatefn)(HashTable*, const char*,
248 * -2 corrupt or error
249 * -3 got newline indicating end
250 * >0 value from omitfn
258 if (c==EOF) { if (feof(f)) return -1; return -2; }
259 if (c=='\n') return -3;
260 if (c!='+') return -2;
262 rc= readlognum(f, ',', &keylen); if (rc) return rc;
263 rc= readlognum(f, ':', &vallen); if (rc) return rc;
265 key= TALLOC(keylen+1);
266 val= htv_prep(vallen);
268 r= fread(key, 1,keylen, f);
269 if (r!=keylen) goto x2_free_keyval;
270 if (memchr(key,0,keylen)) goto x2_free_keyval;
273 c= getc(f); if (c!='-') goto x2_free_keyval;
274 c= getc(f); if (c!='>') goto x2_free_keyval;
276 r= fread(htv_fillptr(val), 1,vallen, f);
277 if (r!=vallen) goto x2_free_keyval;
279 rc= omitfn ? omitfn(val, ctx) : TCL_OK;
280 if (rc) { assert(rc>0); TFREE(val); }
281 else updatefn(ht, key, val);
292 /*---------- Creating ----------*/
294 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
296 static const char *const toremoves[]= {
297 ".main", ".cdb", ".log", ".tmp", 0
301 int lock_fd=-1, fd=-1, rc, r;
302 const char *const *toremove;
304 pathbuf_init(&pb, pathb);
305 rc= acquire_lock(ip, &pb, &lock_fd); if (rc) goto x_rc;
307 fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
308 if (fd <= 0) PE("create new database file");
310 for (toremove=toremoves; *toremove; toremove++) {
311 r= remove(*toremove);
312 if (r && errno != ENOENT)
313 PE("delete possible spurious file during creation");
320 maybe_close(lock_fd);
325 /*---------- Info callbacks ----------*/
327 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
328 const char *arg2fmt, const char *arg3, va_list al) {
332 vsnprintf(buf, sizeof(buf), arg2fmt, al);
335 aa[na++]= cht_ret_string(ip, arg1);
336 aa[na++]= cht_ret_string(ip, buf);
337 if (arg3) aa[na++]= cht_ret_string(ip, arg3);
339 return cht_scriptinv_invoke_fg(&rw->on_info, na, aa);
342 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
343 const char *arg2fmt, const char *arg3, ...) {
347 rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
352 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
353 const char *arg2fmt, ...) {
356 va_start(al, arg2fmt);
357 rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
362 /*---------- Opening ----------*/
364 static int cdbinit(Tcl_Interp *ip, Rw *rw) {
365 /* On entry, cdb_fd >=0 but cdb is _undefined_/
366 * On exit, either cdb_fd<0 or cdb is initialised */
369 r= cdb_init(&rw->cdb, rw->cdb_fd);
371 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
372 close(rw->cdb_fd); rw->cdb_fd= -1; return rc;
377 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
378 Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
380 const Cdbwr_SubCommand *subcmd= cd;
381 int r, rc, mainfd=-1;
384 off_t logrecstart, logjunkpos;
386 rw= TALLOC(sizeof(*rw));
387 ht_setup(&rw->logincore);
388 cht_scriptinv_init(&rw->on_info);
389 cht_scriptinv_init(&rw->on_lexminval);
390 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
391 pathbuf_init(&rw->pbsome, pathb);
392 pathbuf_init(&rw->pbother, pathb);
396 rc= cht_scriptinv_set(&rw->on_lexminval, ip, on_lexminval, 0);
399 rw->on_lexminval.llength= 0;
402 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
403 if (mainfd<0) PE("open exist3ing database file .main");
404 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
406 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
407 rw->mainsz= stab.st_size;
409 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
410 if (rw->cdb_fd >=0) {
411 rc= cdbinit(ip, rw); if (rc) goto x_rc;
412 } else if (errno == ENOENT) {
414 rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
415 " .cdb must have been accidentally deleted!",
424 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
426 if (errno != ENOENT) PE("failed to open .log during open");
427 rw->logfile= fopen(rw->pbsome.buf, "w");
428 if (!rw->logfile) PE("create .log during (clean) open");
429 } else { /* rw->logfile */
430 r= fstat(fileno(rw->logfile), &stab);
431 if (r==-1) PE("fstat .log during open");
432 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
433 (unsigned long)stab.st_size);
437 logrecstart= ftello(rw->logfile);
438 if (logrecstart < 0) PE("ftello .log during (dirty) open");
439 r= readstorelogrecord(rw->logfile, &rw->logincore, 0,0, ht_update);
440 if (ferror(rw->logfile)) {
441 rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
446 } else if (r==-2 || r==-3) {
448 logjunkpos= ftello(rw->logfile);
449 if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
451 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
452 (unsigned long)logjunkpos, (unsigned long)logrecstart);
454 if (!(subcmd->flags & RWSCF_OKJUNK)) {
455 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
456 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
458 Tcl_AppendResult(ip, "syntax error (junk) in .log during"
459 " (dirty) open, at file position ", buf, (char*)0);
463 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
464 (unsigned long)logjunkpos);
467 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
468 if (r) PE("failed to fseeko .log before junk during dirty open");
470 r= ftruncate(fileno(rw->logfile), logrecstart);
471 if (r) PE("ftruncate .log to chop junk during dirty open");
477 /* now log is positioned for appending and everything is read */
489 /*==================== COMPACTION ====================*/
491 struct ht_forall_ctx {
492 struct cdb_make cdbm;
496 const char *lexminval;
499 /*---------- helper functions ----------*/
501 static int expiredp(const HashValue *val, struct ht_forall_ctx *a) {
503 if (!val->len) return 0;
504 l= val->len < a->lexminvall ? val->len : a->lexminvall;
505 r= memcmp(val->data, a->lexminval, l);
508 return val->len < a->lexminvall;
511 static int delete_ifexpired(const char *key, HashValue *val,
512 struct ht_forall_ctx *a) {
513 if (!expiredp(val, a)) return 0;
515 /* we don't actually need to realloc it to free the memory because
516 * this will shortly all be deleted as part of the compaction */
520 static int addto_cdb(const char *key, HashValue *val,
521 struct ht_forall_ctx *a) {
522 return cdb_make_add(&a->cdbm, key, strlen(key), val->data, val->len);
525 static int addto_main(const char *key, HashValue *val,
526 struct ht_forall_ctx *a) {
531 r= fprintf(a->mainfile, "+%d,%d:%s->", strlen(key), val->len, key);
534 r= fwrite(val->data, 1, val->len, a->mainfile);
535 if (r != val->len) return -1;
540 /*---------- compact main entrypoint ----------*/
542 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsz,
544 /* creates new .cdb and .main
546 * leaves .log with old data
547 * leaves cdb fd open onto old db
548 * leaves logincore full of crap
551 int cdbfd, cdbmaking;
552 off_t errpos, newmainsz;
555 struct ht_forall_ctx a;
561 a.reccount= reccount_r;
563 r= fclose(rw->logfile);
564 if (r) { rc= cht_posixerr(ip, errno, "probable data loss! failed to fclose"
565 " logfile during compact"); goto x_rc; }
568 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
569 logsz, (unsigned long)rw->mainsz);
572 if (rw->on_lexminval.llength) {
573 rc= cht_scriptinv_invoke_fg(&rw->on_lexminval, 0,0);
576 res= Tcl_GetObjResult(ip); assert(res);
577 a.lexminval= Tcl_GetStringFromObj(res, &a.lexminvall);
580 /* we rely not calling Tcl_Eval during the actual compaction;
581 * if we did Tcl_Eval then the interp result would be trashed.
583 rc= ht_forall(&rw->logincore, delete_ifexpired, &a);
589 /* merge unsuperseded records from main into hash table */
591 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
592 if (!a.mainfile) PE("failed to open .main for reading during compact");
595 r= readstorelogrecord(a.mainfile, &rw->logincore,
598 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
599 " .main during compact"); goto x_rc;
603 } else if (r==-1 || r==-2) {
604 errpos= ftello(a.mainfile);
605 if (errpos<0) PE("ftello .main during report of syntax error");
606 snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
607 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
608 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
610 Tcl_AppendResult(ip, "syntax error in .main during"
611 " compact, at file position ", buf, (char*)0);
623 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
624 if (cdbfd<0) PE("create .tmp for new cdb during compact");
626 r= cdb_make_start(&a.cdbm, cdbfd);
627 if (r) PE("cdb_make_start during compact");
630 r= ht_forall(&rw->logincore, addto_cdb, &a);
631 if (r) PE("cdb_make_add during compact");
633 r= cdb_make_finish(&a.cdbm);
634 if(r) PE("cdb_make_finish during compact");
637 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
638 r= close(cdbfd); if (r) PE("close new cdb during compact");
641 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
642 if (r) PE("install new .cdb during compact");
644 /* create new main */
646 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
647 if (!a.mainfile) PE("create .tmp for new main during compact");
649 r= ht_forall(&rw->logincore, addto_main, &a);
650 if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
651 " during compact"); goto x_rc; }
653 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
654 r= fdatasync(fileno(a.mainfile));
655 if (r) PE("fdatasync new main during compact");
657 newmainsz= ftello(a.mainfile);
658 if (newmainsz<0) PE("ftello new main during compact");
660 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
663 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
664 if (r) PE("install new .main during compact");
666 rw->mainsz= newmainsz;
670 rc= infocb(ip, rw, "compact-end", "main=%luby nrecs=%l",
671 (unsigned long)rw->mainsz, *a.reccount);
677 if (a.mainfile) fclose(a.mainfile);
678 if (cdbmaking) cdb_make_finish(&a.cdbm);
680 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
684 /*---------- Closing ----------*/
686 static int compact_forclose(Tcl_Interp *ip, Rw *rw, long *reccount_r) {
690 logsz= ftello(rw->logfile);
691 if (logsz < 0) PE("ftello logfile (during tidy close)");
693 rc= compact_core(ip, rw, logsz, reccount_r); if (rc) goto x_rc;
695 r= remove(pathbuf_sfx(&rw->pbsome,".log"));
696 if (r) PE("remove .log (during tidy close)");
703 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
709 if (rw->autocompact) rc= compact_forclose(ip, rw, &reccount);
714 logsz= ftello(rw->logfile);
716 rc= cht_posixerr(ip, errno, "ftell logfile during close info");
718 rc= infocb(ip, rw, "close", "main=%luby log=%luby",
720 } else if (reccount>=0) {
721 rc= infocb(ip, rw, "close", "main=%luby nrecs=%l", rw->mainsz, reccount);
723 rc= infocb(ip, rw, "close", "main=%luby", rw->mainsz);
726 rc_close= rw_close(ip,rw);
727 if (rc_close) rc= rc_close;
729 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
733 /*---------- Other compaction-related entrypoints ----------*/
735 static int compact_keeopen(Tcl_Interp *ip, Rw *rw, int force) {
740 logsz= ftello(rw->logfile);
741 if (logsz < 0) return cht_posixerr(ip, errno, "ftell .log"
742 " during compact check or force");
744 if (!force && logsz < rw->mainsz / 10 + 1000) return TCL_OK;
746 rc= compact_core(ip, rw, logsz, &reccount); if (rc) goto x_rc;
748 maybe_close(rw->cdb_fd);
750 ht_destroy(&rw->logincore);
751 ht_setup(&rw->logincore);
753 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
754 if (rw->cdb_fd < 0) PE("reopen .cdb after compact");
756 rc= cdbinit(ip, rw); if (rc) goto x_rc;
758 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "w");
759 if (!rw->logfile) PE("reopen .log after compact");
761 r= fsync(fileno(rw->logfile)); if (r) PE("fsync .log after compact reopen");
766 /* doom! all updates fail after this (because rw->logfile is 0), and
767 * we may be usin a lot more RAM than would be ideal. Program will
768 * have to reopen if it really wants sanity. */
772 int cht_do_cdbwr_compact_force(ClientData cd, Tcl_Interp *ip, void *rw_v) {
773 return compact_keeopen(ip, rw_v, 1);
775 int cht_do_cdbwr_compact_check(ClientData cd, Tcl_Interp *ip, void *rw_v) {
776 return compact_keeopen(ip, rw_v, 0);
779 int cht_do_cdbwr_compact_explicit(ClientData cd, Tcl_Interp *ip, void *rw_v) {
784 int cht_do_cdbwr_compact_auto(ClientData cd, Tcl_Interp *ip, void *rw_v) {