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 ht_setup(HashTable *ht) {
73 Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
75 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
79 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
80 if (!new) TFREE(Tcl_GetHashValue(he));
81 Tcl_SetHashValue(he, val_eat);
82 /* eats the value since the data structure owns the memory */
84 static void ht_maybeupdate(HashTable *ht, const char *key,
86 /* like ht_update except does not overwrite existing values */
90 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
91 if (!new) { TFREE(val_eat); return; }
92 Tcl_SetHashValue(he, val_eat);
95 static fixme ht_lookup(HashTable *ht, const char *key) {
99 he= Tcl_FindHashEntry(ht, key);
100 if (!he) return notfound;
102 htv= Tcl_GetHashValue(he);
106 static int ht_forall(HashTable *ht,
107 int (*fn)(const char *key, HashValue *val,
108 struct ht_forall_ctx *ctx),
109 struct ht_forall_ctx *ctx) {
110 /* Returns first positive value returned by any call to fn, or 0. */
117 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
119 he= Tcl_NextHashEntry(&sp)) {
120 val= Tcl_GetHashValue(he);
121 if (!val->len) continue;
123 key= Tcl_GetHashKey(&ht->t, he);
125 r= fn(key, val, ctx);
131 static void ht_destroy(HashTable *ht) {
135 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
137 he= Tcl_NextHashEntry(&sp)) {
138 /* ht_forall skips empty (deleted) entries so is no good for this */
139 TFREE(Tcl_GetHashValue(he));
141 Tcl_DeleteHashTable(&ht->t);
144 /*==================== Existential ====================*/
146 /*---------- Rw data structure ----------*/
151 struct cdb cdb; /* valid iff cdb_fd >= 0 */
154 Pathbuf pbsome, pbother;
156 ScriptToInvoke on_info, on_lexminval;
159 static int rw_close(Tcl_Interp *ip, Rw *rw) {
163 ht_destroy(&rw->logincore);
164 if (rw->cdb_fd >= 0) cdb_free(&rw->cdb);
165 maybe_close(rw->cdb_fd);
166 maybe_close(rw->lock_fd);
169 r= fclose(rw->logfile);
170 if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
171 " fclose logfile during untidy close"); }
174 pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
179 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
180 const IdDataSpec cdbtcl_rwdatabases= {
181 "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
184 /*---------- File handling ----------*/
186 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
187 /* *lockfd_r must be -1 on entry. If may be set to >=0 even
188 * on error, and must be closed by the caller. */
193 um= umask(~(mode_t)0);
196 lockmode= 0666 & ~((um & 0444)>>1);
197 /* Remove r where umask would remove w;
198 * eg umask intending 0664 here gives 0660 */
200 *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
202 return cht_posixerr(ip, errno, "could not open/create lockfile");
205 fl.l_whence= SEEK_SET;
210 r= fcntl(*lockfd_r, F_SETLK, &fl);
212 if (errno == EACCES || errno == EAGAIN)
213 return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
214 else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
221 /*---------- Log reading and writing ----------*/
223 static int readlognum(FILE *f, int delim, int *num_r) {
225 char numbuf[20], *p, *ep;
230 c= getc(f); if (c==EOF) return -2;
231 if (c == delim) break;
232 if (!isdigit((unsigned char)c)) return -2;
234 if (p == numbuf+sizeof(numbuf)) return -2;
236 if (p == numbuf) return -2;
239 errno=0; ul= strtoul(numbuf, &ep, 10);
240 if (*ep || errno || ul >= INT_MAX/2) return -2;
245 static int readstorelogrecord(FILE *f, HashTable *ht,
246 int (*omitfn)(const HashValue*,
247 struct ht_forall_ctx *ctx),
248 struct ht_forall_ctx *ctx,
249 void (*updatefn)(HashTable*, const char*,
254 * -2 corrupt or error
255 * -3 got newline indicating end
256 * >0 value from omitfn
264 if (c==EOF) { if (feof(f)) return -1; return -2; }
265 if (c=='\n') return -3;
266 if (c!='+') return -2;
268 rc= readlognum(f, ',', &keylen); if (rc) return rc;
269 rc= readlognum(f, ':', &vallen); if (rc) return rc;
271 key= TALLOC(keylen+1);
272 val= htv_prep(vallen);
274 r= fread(key, 1,keylen, f);
275 if (r!=keylen) goto x2_free_keyval;
276 if (memchr(key,0,keylen)) goto x2_free_keyval;
279 c= getc(f); if (c!='-') goto x2_free_keyval;
280 c= getc(f); if (c!='>') goto x2_free_keyval;
282 r= fread(htv_fillptr(val), 1,vallen, f);
283 if (r!=vallen) goto x2_free_keyval;
285 rc= omitfn ? omitfn(val, ctx) : TCL_OK;
286 if (rc) { assert(rc>0); TFREE(val); }
287 else updatefn(ht, key, val);
298 static int writerecord(FILE *f, const char *key, const HashValue *val) {
301 r= fprintf(f, "+%d,%d:%s->", strlen(key), val->len, key);
304 r= fwrite(val->data, 1, val->len, f);
305 if (r != val->len) return -1;
310 /*---------- Creating ----------*/
312 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
314 static const char *const toremoves[]= {
315 ".main", ".cdb", ".log", ".tmp", 0
319 int lock_fd=-1, fd=-1, rc, r;
320 const char *const *toremove;
322 pathbuf_init(&pb, pathb);
323 rc= acquire_lock(ip, &pb, &lock_fd); if (rc) goto x_rc;
325 fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
326 if (fd <= 0) PE("create new database file");
328 for (toremove=toremoves; *toremove; toremove++) {
329 r= remove(*toremove);
330 if (r && errno != ENOENT)
331 PE("delete possible spurious file during creation");
338 maybe_close(lock_fd);
343 /*---------- Info callbacks ----------*/
345 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
346 const char *arg2fmt, const char *arg3, va_list al) {
350 vsnprintf(buf, sizeof(buf), arg2fmt, al);
353 aa[na++]= cht_ret_string(ip, arg1);
354 aa[na++]= cht_ret_string(ip, buf);
355 if (arg3) aa[na++]= cht_ret_string(ip, arg3);
357 return cht_scriptinv_invoke_fg(&rw->on_info, na, aa);
360 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
361 const char *arg2fmt, const char *arg3, ...) {
365 rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
370 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
371 const char *arg2fmt, ...) {
374 va_start(al, arg2fmt);
375 rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
380 /*---------- Opening ----------*/
382 static int cdbinit(Tcl_Interp *ip, Rw *rw) {
383 /* On entry, cdb_fd >=0 but cdb is _undefined_/
384 * On exit, either cdb_fd<0 or cdb is initialised */
387 r= cdb_init(&rw->cdb, rw->cdb_fd);
389 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
390 close(rw->cdb_fd); rw->cdb_fd= -1; return rc;
395 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
396 Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
398 const Cdbwr_SubCommand *subcmd= cd;
399 int r, rc, mainfd=-1;
402 off_t logrecstart, logjunkpos;
404 rw= TALLOC(sizeof(*rw));
405 ht_setup(&rw->logincore);
406 cht_scriptinv_init(&rw->on_info);
407 cht_scriptinv_init(&rw->on_lexminval);
408 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
409 pathbuf_init(&rw->pbsome, pathb);
410 pathbuf_init(&rw->pbother, pathb);
414 rc= cht_scriptinv_set(&rw->on_lexminval, ip, on_lexminval, 0);
417 rw->on_lexminval.llength= 0;
420 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
421 if (mainfd<0) PE("open exist3ing database file .main");
422 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
424 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
425 rw->mainsz= stab.st_size;
427 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
428 if (rw->cdb_fd >=0) {
429 rc= cdbinit(ip, rw); if (rc) goto x_rc;
430 } else if (errno == ENOENT) {
432 rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
433 " .cdb must have been accidentally deleted!",
442 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
444 if (errno != ENOENT) PE("failed to open .log during open");
445 rw->logfile= fopen(rw->pbsome.buf, "w");
446 if (!rw->logfile) PE("create .log during (clean) open");
447 } else { /* rw->logfile */
448 r= fstat(fileno(rw->logfile), &stab);
449 if (r==-1) PE("fstat .log during open");
450 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
451 (unsigned long)stab.st_size);
455 logrecstart= ftello(rw->logfile);
456 if (logrecstart < 0) PE("ftello .log during (dirty) open");
457 r= readstorelogrecord(rw->logfile, &rw->logincore, 0,0, ht_update);
458 if (ferror(rw->logfile)) {
459 rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
464 } else if (r==-2 || r==-3) {
466 logjunkpos= ftello(rw->logfile);
467 if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
469 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
470 (unsigned long)logjunkpos, (unsigned long)logrecstart);
472 if (!(subcmd->flags & RWSCF_OKJUNK)) {
473 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
474 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
476 Tcl_AppendResult(ip, "syntax error (junk) in .log during"
477 " (dirty) open, at file position ", buf, (char*)0);
481 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
482 (unsigned long)logjunkpos);
485 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
486 if (r) PE("failed to fseeko .log before junk during dirty open");
488 r= ftruncate(fileno(rw->logfile), logrecstart);
489 if (r) PE("ftruncate .log to chop junk during dirty open");
495 /* now log is positioned for appending and everything is read */
507 int cht_do_cdbwr_open_okjunk(ClientData cd, Tcl_Interp *ip, const char *pathb,
508 Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
510 return cht_do_cdbwr_open(cd,ip,pathb,on_info,on_lexminval,result);
513 /*==================== COMPACTION ====================*/
515 struct ht_forall_ctx {
516 struct cdb_make cdbm;
520 const char *lexminval;
523 /*---------- helper functions ----------*/
525 static int expiredp(const HashValue *val, struct ht_forall_ctx *a) {
527 if (!val->len) return 0;
528 l= val->len < a->lexminvall ? val->len : a->lexminvall;
529 r= memcmp(val->data, a->lexminval, l);
532 return val->len < a->lexminvall;
535 static int delete_ifexpired(const char *key, HashValue *val,
536 struct ht_forall_ctx *a) {
537 if (!expiredp(val, a)) return 0;
539 /* we don't actually need to realloc it to free the memory because
540 * this will shortly all be deleted as part of the compaction */
544 static int addto_cdb(const char *key, HashValue *val,
545 struct ht_forall_ctx *a) {
546 return cdb_make_add(&a->cdbm, key, strlen(key), val->data, val->len);
549 static int addto_main(const char *key, HashValue *val,
550 struct ht_forall_ctx *a) {
552 return writerecord(a->mainfile, key, val);
555 /*---------- compact main entrypoint ----------*/
557 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsz,
559 /* creates new .cdb and .main
561 * leaves .log with old data
562 * leaves cdb fd open onto old db
563 * leaves logincore full of crap
566 int cdbfd, cdbmaking;
567 off_t errpos, newmainsz;
570 struct ht_forall_ctx a;
576 a.reccount= reccount_r;
578 r= fclose(rw->logfile);
579 if (r) { rc= cht_posixerr(ip, errno, "probable data loss! failed to fclose"
580 " logfile during compact"); goto x_rc; }
583 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
584 logsz, (unsigned long)rw->mainsz);
587 if (rw->on_lexminval.llength) {
588 rc= cht_scriptinv_invoke_fg(&rw->on_lexminval, 0,0);
591 res= Tcl_GetObjResult(ip); assert(res);
592 a.lexminval= Tcl_GetStringFromObj(res, &a.lexminvall);
595 /* we rely not calling Tcl_Eval during the actual compaction;
596 * if we did Tcl_Eval then the interp result would be trashed.
598 rc= ht_forall(&rw->logincore, delete_ifexpired, &a);
604 /* merge unsuperseded records from main into hash table */
606 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
607 if (!a.mainfile) PE("failed to open .main for reading during compact");
610 r= readstorelogrecord(a.mainfile, &rw->logincore,
613 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
614 " .main during compact"); goto x_rc;
618 } else if (r==-1 || r==-2) {
619 errpos= ftello(a.mainfile);
620 if (errpos<0) PE("ftello .main during report of syntax error");
621 snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
622 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
623 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
625 Tcl_AppendResult(ip, "syntax error in .main during"
626 " compact, at file position ", buf, (char*)0);
638 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
639 if (cdbfd<0) PE("create .tmp for new cdb during compact");
641 r= cdb_make_start(&a.cdbm, cdbfd);
642 if (r) PE("cdb_make_start during compact");
645 r= ht_forall(&rw->logincore, addto_cdb, &a);
646 if (r) PE("cdb_make_add during compact");
648 r= cdb_make_finish(&a.cdbm);
649 if(r) PE("cdb_make_finish during compact");
652 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
653 r= close(cdbfd); if (r) PE("close new cdb during compact");
656 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
657 if (r) PE("install new .cdb during compact");
659 /* create new main */
661 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
662 if (!a.mainfile) PE("create .tmp for new main during compact");
664 r= ht_forall(&rw->logincore, addto_main, &a);
665 if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
666 " during compact"); goto x_rc; }
668 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
669 r= fdatasync(fileno(a.mainfile));
670 if (r) PE("fdatasync new main during compact");
672 newmainsz= ftello(a.mainfile);
673 if (newmainsz<0) PE("ftello new main during compact");
675 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
678 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
679 if (r) PE("install new .main during compact");
681 rw->mainsz= newmainsz;
685 rc= infocb(ip, rw, "compact-end", "main=%luby nrecs=%l",
686 (unsigned long)rw->mainsz, *a.reccount);
692 if (a.mainfile) fclose(a.mainfile);
693 if (cdbmaking) cdb_make_finish(&a.cdbm);
695 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
699 /*---------- Closing ----------*/
701 static int compact_forclose(Tcl_Interp *ip, Rw *rw, long *reccount_r) {
705 logsz= ftello(rw->logfile);
706 if (logsz < 0) PE("ftello logfile (during tidy close)");
708 rc= compact_core(ip, rw, logsz, reccount_r); if (rc) goto x_rc;
710 r= remove(pathbuf_sfx(&rw->pbsome,".log"));
711 if (r) PE("remove .log (during tidy close)");
718 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
724 if (rw->autocompact) rc= compact_forclose(ip, rw, &reccount);
729 logsz= ftello(rw->logfile);
731 rc= cht_posixerr(ip, errno, "ftell logfile during close info");
733 rc= infocb(ip, rw, "close", "main=%luby log=%luby",
735 } else if (reccount>=0) {
736 rc= infocb(ip, rw, "close", "main=%luby nrecs=%l", rw->mainsz, reccount);
738 rc= infocb(ip, rw, "close", "main=%luby", rw->mainsz);
741 rc_close= rw_close(ip,rw);
742 if (rc_close) rc= rc_close;
744 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
748 /*---------- Other compaction-related entrypoints ----------*/
750 static int compact_keepopen(Tcl_Interp *ip, Rw *rw, int force) {
755 logsz= ftello(rw->logfile);
756 if (logsz < 0) return cht_posixerr(ip, errno, "ftell .log"
757 " during compact check or force");
759 if (!force && logsz < rw->mainsz / 10 + 1000) return TCL_OK;
761 rc= compact_core(ip, rw, logsz, &reccount); if (rc) goto x_rc;
763 maybe_close(rw->cdb_fd);
765 ht_destroy(&rw->logincore);
766 ht_setup(&rw->logincore);
768 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
769 if (rw->cdb_fd < 0) PE("reopen .cdb after compact");
771 rc= cdbinit(ip, rw); if (rc) goto x_rc;
773 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "w");
774 if (!rw->logfile) PE("reopen .log after compact");
776 r= fsync(fileno(rw->logfile)); if (r) PE("fsync .log after compact reopen");
781 /* doom! all updates fail after this (because rw->logfile is 0), and
782 * we may be using a lot more RAM than would be ideal. Program will
783 * have to reopen if it really wants sanity. */
787 int cht_do_cdbwr_compact_force(ClientData cd, Tcl_Interp *ip, void *rw_v) {
788 return compact_keepopen(ip, rw_v, 1);
790 int cht_do_cdbwr_compact_check(ClientData cd, Tcl_Interp *ip, void *rw_v) {
791 return compact_keepopen(ip, rw_v, 0);
794 int cht_do_cdbwr_compact_explicit(ClientData cd, Tcl_Interp *ip, void *rw_v) {
799 int cht_do_cdbwr_compact_auto(ClientData cd, Tcl_Interp *ip, void *rw_v) {
805 /*---------- Updateing ----------*/
807 static int update(Tcl_Interp *ip, Rw *rw, const char *key,
808 const Byte *data, int dlen) {
812 if (!rw->logfile) return cht_staticerr
813 (ip, "previous compact failed; cdbwr must be closed and reopened "
814 "before any further updates", "CDB BROKEN");
816 val= htv_prep(dlen); assert(val);
817 memcpy(htv_fillptr(val), data, dlen);
819 r= writerecord(rw->logfile, key, val);
820 if (!r) r= fflush(rw->logfile);
821 if (r) PE("write update to logfile");
823 ht_update(&rw->logincore, key, val);
824 return compact_keepopen(ip, rw, 0);
831 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip,
832 void *rw_v, const char *key, Tcl_Obj *value) {
835 data= Tcl_GetStringFromObj(value, &dlen); assert(data);
836 return update(ip, rw_v, key, data, dlen);
839 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip,
840 void *rw_v, const char *key, HBytes_Value value) {
841 return update(ip, rw_v, key, cht_hb_data(&value), cht_hb_len(&value));
844 int cht_do_cdbwr_delete(ClientData cd, Tcl_Interp *ip, void *rw_v,
846 return update(ip, rw_v, key, 0, 0);
849 /*---------- Lookups ----------*/
851 static int lookup(Tcl_Interp *ip, Rw *rw, const char *key, ) {
854 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *db,
855 const char *key, Tcl_Obj *def, Tcl_Obj **result) {
859 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *db, const char *key, HBytes_Value def, HBytes_Value *result);