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);
67 static Byte *htv_fillptr(HashValue *hd) {
70 static void htv_fill(HashValue *hd, const Byte *data) {
71 memcpy(hd->data, data, hd->len);
74 static void ht_setup(HashTable *ht) {
75 Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
77 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
81 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
82 if (!new) TFREE(Tcl_GetHashValue(he));
83 Tcl_SetHashValue(he, val_eat);
84 /* eats the value since the data structure owns the memory */
86 static void ht_maybeupdate(HashTable *ht, const char *key,
88 /* like ht_update except does not overwrite existing values */
92 he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
93 if (!new) { TFREE(val_eat); return; }
94 Tcl_SetHashValue(he, val_eat);
97 static int ht_forall(HashTable *ht,
98 int (*fn)(const char *key, HashValue *val,
99 struct ht_forall_ctx *ctx),
100 struct ht_forall_ctx *ctx) {
101 /* Returns first positive value returned by any call to fn, or 0. */
108 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
110 he= Tcl_NextHashEntry(&sp)) {
111 val= Tcl_GetHashValue(he);
112 if (!val->len) continue;
114 key= Tcl_GetHashKey(&ht->t, he);
116 r= fn(key, val, ctx);
122 static void ht_destroy(HashTable *ht) {
126 for (he= Tcl_FirstHashEntry(&ht->t, &sp);
128 he= Tcl_NextHashEntry(&sp)) {
129 /* ht_forall skips empty (deleted) entries so is no good for this */
130 TFREE(Tcl_GetHashValue(he));
132 Tcl_DeleteHashTable(&ht->t);
135 /*==================== Existential ====================*/
137 /*---------- Rw data structure ----------*/
142 struct cdb cdb; /* valid iff cdb_fd >= 0 */
143 off_t cdb_bytes; /* valid iff cdb_fd >= 0 */
146 Pathbuf pbsome, pbother;
148 ScriptToInvoke on_info, on_lexminval;
151 static int rw_close(Tcl_Interp *ip, Rw *rw) {
155 ht_destroy(&rw->logincore);
156 maybe_close(rw->cdb_fd);
157 maybe_close(rw->lock_fd);
160 r= fclose(rw->logfile);
161 if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
162 " fclose logfile during untidy close"); }
165 pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
170 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
171 const IdDataSpec cdbtcl_rwdatabases= {
172 "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
175 /*---------- File handling ----------*/
177 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
178 /* *lockfd_r must be -1 on entry. If may be set to >=0 even
179 * on error, and must be closed by the caller. */
184 um= umask(~(mode_t)0);
187 lockmode= 0666 & ~((um & 0444)>>1);
188 /* Remove r where umask would remove w;
189 * eg umask intending 0664 here gives 0660 */
191 *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
193 return cht_posixerr(ip, errno, "could not open/create lockfile");
196 fl.l_whence= SEEK_SET;
201 r= fcntl(*lockfd_r, F_SETLK, &fl);
203 if (errno == EACCES || errno == EAGAIN)
204 return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
205 else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
212 /*---------- Log reading ----------*/
214 static int readlognum(FILE *f, int delim, int *num_r) {
216 char numbuf[20], *p, *ep;
221 c= getc(f); if (c==EOF) return -2;
222 if (c == delim) break;
223 if (!isdigit((unsigned char)c)) return -2;
225 if (p == numbuf+sizeof(numbuf)) return -2;
227 if (p == numbuf) return -2;
230 errno=0; ul= strtoul(numbuf, &ep, 10);
231 if (*ep || errno || ul >= INT_MAX/2) return -2;
236 static int readstorelogrecord(FILE *f, HashTable *ht,
237 int (*omitfn)(const HashValue*,
238 struct ht_forall_ctx *ctx),
239 struct ht_forall_ctx *ctx,
240 void (*updatefn)(HashTable*, const char*,
245 * -2 corrupt or error
246 * -3 got newline indicating end
247 * >0 value from omitfn
255 if (c==EOF) { if (feof(f)) return -1; return -2; }
256 if (c=='\n') return -3;
257 if (c!='+') return -2;
259 rc= readlognum(f, ',', &keylen); if (rc) return rc;
260 rc= readlognum(f, ':', &vallen); if (rc) return rc;
262 key= TALLOC(keylen+1);
263 val= htv_prep(vallen);
265 r= fread(key, 1,keylen, f);
266 if (r!=keylen) goto x2_free_keyval;
267 if (memchr(key,0,keylen)) goto x2_free_keyval;
270 c= getc(f); if (c!='-') goto x2_free_keyval;
271 c= getc(f); if (c!='>') goto x2_free_keyval;
273 r= fread(htv_fillptr(val), 1,vallen, f);
274 if (r!=vallen) goto x2_free_keyval;
276 rc= omitfn ? omitfn(val, ctx) : TCL_OK;
277 if (rc) { assert(rc>0); TFREE(val); }
278 else updatefn(ht, key, val);
289 /*---------- Creating ----------*/
291 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
293 static const char *const toremoves[]= {
294 ".main", ".cdb", ".log", ".tmp", 0
298 int lock_fd=-1, fd=-1, rc, r;
299 const char *const *toremove;
301 pathbuf_init(&pb, pathb);
302 rc= acquire_lock(ip, &pb, &lock_fd); if (rc) goto x_rc;
304 fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
305 if (fd <= 0) PE("create new database file");
307 for (toremove=toremoves; *toremove; toremove++) {
308 r= remove(*toremove);
309 if (r && errno != ENOENT)
310 PE("delete possible spurious file during creation");
317 maybe_close(lock_fd);
322 /*---------- Info callbacks ----------*/
324 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
325 const char *arg2fmt, const char *arg3, va_list al) {
329 vsnprintf(buf, sizeof(buf), arg2fmt, al);
332 aa[na++]= cht_ret_string(ip, arg1);
333 aa[na++]= cht_ret_string(ip, buf);
334 if (arg3) aa[na++]= cht_ret_string(ip, arg3);
336 return cht_scriptinv_invoke_fg(&rw->on_info, na, aa);
339 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
340 const char *arg2fmt, const char *arg3, ...) {
344 rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
349 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
350 const char *arg2fmt, ...) {
353 va_start(al, arg2fmt);
354 rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
359 /*---------- Opening ----------*/
361 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
362 Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
364 const Cdbwr_SubCommand *subcmd= cd;
365 int r, rc, mainfd=-1;
368 off_t logrecstart, logjunkpos;
370 rw= TALLOC(sizeof(*rw));
371 ht_setup(&rw->logincore);
372 cht_scriptinv_init(&rw->on_info);
373 cht_scriptinv_init(&rw->on_lexminval);
374 rw->cdb_fd= rw->lock_fd= -1; rw->logfile= 0;
375 pathbuf_init(&rw->pbsome, pathb);
376 pathbuf_init(&rw->pbother, pathb);
380 rc= cht_scriptinv_set(&rw->on_lexminval, ip, on_lexminval, 0);
383 rw->on_lexminval.llength= 0;
386 mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
387 if (mainfd<0) PE("open exist3ing database file .main");
388 rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd); if (rc) goto x_rc;
390 r= fstat(mainfd, &stab); if (r) PE("fstat .main");
391 rw->mainsz= stab.st_size;
393 rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
394 if (rw->cdb_fd >=0) {
395 r= cdb_init(&rw->cdb, rw->cdb_fd);
397 rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
398 close(rw->cdb_fd); rw->cdb_fd= -1; goto x_rc;
400 } else if (errno == ENOENT) {
402 rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
403 " .cdb must have been accidentally deleted!",
412 rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
414 if (errno != ENOENT) PE("failed to open .log during open");
415 rw->logfile= fopen(rw->pbsome.buf, "w");
416 if (!rw->logfile) PE("create .log during (clean) open");
417 } else { /* rw->logfile */
418 r= fstat(fileno(rw->logfile), &stab);
419 if (r==-1) PE("fstat .log during open");
420 rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
421 (unsigned long)stab.st_size);
425 logrecstart= ftello(rw->logfile);
426 if (logrecstart < 0) PE("ftello .log during (dirty) open");
427 r= readstorelogrecord(rw->logfile, &rw->logincore, 0,0, ht_update);
428 if (ferror(rw->logfile)) {
429 rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
434 } else if (r==-2 || r==-3) {
436 logjunkpos= ftello(rw->logfile);
437 if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
439 snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
440 (unsigned long)logjunkpos, (unsigned long)logrecstart);
442 if (!(subcmd->flags & RWSCF_OKJUNK)) {
443 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
444 snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
446 Tcl_AppendResult(ip, "syntax error (junk) in .log during"
447 " (dirty) open, at file position ", buf, (char*)0);
451 rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
452 (unsigned long)logjunkpos);
455 r= fseeko(rw->logfile, logrecstart, SEEK_SET);
456 if (r) PE("failed to fseeko .log before junk during dirty open");
458 r= ftruncate(fileno(rw->logfile), logrecstart);
459 if (r) PE("ftruncate .log to chop junk during dirty open");
465 /* now log is positioned for appending and everything is read */
477 /*==================== COMPACTING ====================*/
479 struct ht_forall_ctx {
480 struct cdb_make cdbm;
484 const char *lexminval;
487 /*---------- helper functions ----------*/
489 static int expiredp(const HashValue *val, struct ht_forall_ctx *a) {
491 if (!val->len) return 0;
492 l= val->len < a->lexminvall ? val->len : a->lexminvall;
493 r= memcmp(val->data, a->lexminval, l);
496 return val->len < a->lexminvall;
499 static int delete_ifexpired(const char *key, HashValue *val,
500 struct ht_forall_ctx *a) {
501 if (!expiredp(val, a)) return 0;
503 /* we don't actually need to realloc it to free the memory because
504 * this will shortly all be deleted as part of the compaction */
508 static int addto_cdb(const char *key, HashValue *val,
509 struct ht_forall_ctx *a) {
510 return cdb_make_add(&a->cdbm, key, strlen(key), val->data, val->len);
513 static int addto_main(const char *key, HashValue *val,
514 struct ht_forall_ctx *a) {
519 r= fprintf(a->mainfile, "+%d,%d:%s->", strlen(key), val->len, key);
522 r= fwrite(val->data, 1, val->len, a->mainfile);
523 if (r != val->len) return -1;
528 /*---------- compact main entrypoint ----------*/
530 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsize,
532 /* creates new .cdb and .main
534 * leaves .log with old data
535 * leaves cdb fd open onto old db
536 * leaves logincore full of crap
539 int cdbfd, cdbmaking;
540 off_t errpos, newmainsz;
543 struct ht_forall_ctx a;
549 a.reccount= reccount_r;
551 r= fclose(rw->logfile);
552 if (r) { rc= cht_posixerr(ip, errno, "probable data loss! failed to fclose"
553 " logfile during compact"); goto x_rc; }
556 rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
557 logsize, (unsigned long)rw->mainsz);
560 if (rw->on_lexminval.llength) {
561 rc= cht_scriptinv_invoke_fg(&rw->on_lexminval, 0,0);
564 res= Tcl_GetObjResult(ip); assert(res);
565 a.lexminval= Tcl_GetStringFromObj(res, &a.lexminvall);
568 /* we rely not calling Tcl_Eval during the actual compaction;
569 * if we did Tcl_Eval then the interp result would be trashed.
571 rc= ht_forall(&rw->logincore, delete_ifexpired, &a);
577 /* merge unsuperseded records from main into hash table */
579 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
580 if (!a.mainfile) PE("failed to open .main for reading during compact");
583 r= readstorelogrecord(a.mainfile, &rw->logincore,
586 if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
587 " .main during compact"); goto x_rc;
591 } else if (r==-1 || r==-2) {
592 errpos= ftello(a.mainfile);
593 if (errpos<0) PE("ftello .main during report of syntax error");
594 snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
595 Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
596 snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
598 Tcl_AppendResult(ip, "syntax error in .main during"
599 " compact, at file position ", buf, (char*)0);
611 cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
612 if (cdbfd<0) PE("create .tmp for new cdb during compact");
614 r= cdb_make_start(&a.cdbm, cdbfd);
615 if (r) PE("cdb_make_start during compact");
618 r= ht_forall(&rw->logincore, addto_cdb, &a);
619 if (r) PE("cdb_make_add during compact");
621 r= cdb_make_finish(&a.cdbm);
622 if(r) PE("cdb_make_finish during compact");
625 r= fdatasync(cdbfd); if (r) PE("fdatasync new cdb during compact");
626 r= close(cdbfd); if (r) PE("close new cdb during compact");
629 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
630 if (r) PE("install new .cdb during compact");
632 /* create new main */
634 a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
635 if (!a.mainfile) PE("create .tmp for new main during compact");
637 r= ht_forall(&rw->logincore, addto_main, &a);
638 if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
639 " during compact"); goto x_rc; }
641 r= fflush(a.mainfile); if (r) PE("fflush new main during compact");
642 r= fdatasync(fileno(a.mainfile));
643 if (r) PE("fdatasync new main during compact");
645 newmainsz= ftello(a.mainfile);
646 if (newmainsz<0) PE("ftello new main during compact");
648 r= fclose(a.mainfile); if (r) PE("fclose new main during compact");
651 r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
652 if (r) PE("install new .main during compact");
654 rw->mainsz= newmainsz;
658 rc= infocb(ip, rw, "compact-end", "log=%luby main=%luby nrecs=%l",
659 logsize, (unsigned long)rw->mainsz, *a.reccount);
664 if (a.mainfile) fclose(a.mainfile);
665 if (cdbmaking) cdb_make_finish(&a.cdbm);
667 remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
670 /*---------- Closing ----------*/
672 static int compact_forclose(Tcl_Interp *ip, Rw *rw, long *reccount_r) {
676 logsz= ftello(rw->logfile);
677 if (logsz < 0) PE("ftello logfile (during tidy close)");
679 rc= compact_core(ip, rw, logsz, reccount_r); if (rc) goto x_rc;
681 r= remove(pathbuf_sfx(&rw->pbsome,".log"));
682 if (r) PE("remove .log (during tidy close)");
689 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
695 if (rw->autocompact) rc= compact_forclose(ip, rw, &reccount);
700 logsz= ftello(rw->logfile);
702 rc= cht_posixerr(ip, errno, "ftell logfile during close info");
704 rc= infocb(ip, rw, "close", "main=%luby log=%luby",
706 } else if (reccount>=0) {
707 rc= infocb(ip, rw, "close", "main=%luby nrecs=%l", rw->mainsz, reccount);
709 rc= infocb(ip, rw, "close", "main=%luby", rw->mainsz);
712 rc_close= rw_close(ip,rw);
713 if (rc_close) rc= rc_close;
715 cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
719 /*==================== Other entrypoints ====================*/