chiark / gitweb /
3613a7b8084642d31c807fde215590f20caf00b1
[chiark-tcl.git] / cdb / writeable.c
1 /**/
2
3 #include "chiark_tcl_cdb.h"
4
5 #define ftello ftell
6 #define fseeko fseek
7
8 /*---------- Forward declarations ----------*/
9
10 struct ht_forall_ctx;
11
12 /*---------- Useful routines ----------*/
13
14 static void maybe_close(int fd) {
15   if (fd>=0) close(fd);
16 }
17
18 #define PE(m) do{                                               \
19     rc= cht_posixerr(ip, errno, "failed to " m); goto x_rc;     \
20   }while(0)
21
22 /*==================== Subsystems and subtypes ====================*/
23
24 /*---------- Pathbuf ----------*/
25
26 typedef struct Pathbuf {
27   char *buf, *sfx;
28 } Pathbuf;
29
30 #define MAX_SUFFIX 4
31
32 static void pathbuf_init(Pathbuf *pb, const char *pathb) {
33   int l= strlen(pathb);
34   pb->buf= TALLOC(l + 4);
35   memcpy(pb->buf, pathb, l);
36   pb->sfx= pb->buf + l;
37   *pb->sfx++= '.';
38 }
39 static const char *pathbuf_sfx(Pathbuf *pb, const char *suffix) {
40   assert(strlen(suffix) <= MAX_SUFFIX);
41   strcpy(pb->sfx, suffix);
42   return pb->buf;
43 }
44 static void pathbuf_free(Pathbuf *pb) {
45   TFREE(pb->buf);
46   pb->buf= 0;
47 }
48
49 /*---------- Our hash table ----------*/
50
51 typedef struct HashTable {
52   Tcl_HashTable t;
53   Byte padding[128]; /* allow for expansion by Tcl, urgh */
54   Byte confound[16];
55 } HashTable;
56
57 typedef struct HashValue {
58   int len;
59   Byte data[1];
60 } HashValue;
61
62 static HashValue *htv_prep(int len) {
63   HashValue *hd;
64   hd= TALLOC((hd->data - (Byte*)hd) + len);
65   hd->len= len;
66   return hd;
67 }  
68 static Byte *htv_fillptr(HashValue *hd) {
69   return hd->data;
70 }
71
72 static void ht_setup(HashTable *ht) {
73   Tcl_InitHashTable(&ht->t, TCL_STRING_KEYS);
74 }
75 static void ht_update(HashTable *ht, const char *key, HashValue *val_eat) {
76   Tcl_HashEntry *he;
77   int new;
78
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 */
83 }
84 static void ht_maybeupdate(HashTable *ht, const char *key,
85                            HashValue *val_eat) {
86   /* like ht_update except does not overwrite existing values */
87   Tcl_HashEntry *he;
88   int new;
89
90   he= Tcl_CreateHashEntry(&ht->t, (char*)key, &new);
91   if (!new) { TFREE(val_eat); return; }
92   Tcl_SetHashValue(he, val_eat);
93 }
94
95 static fixme ht_lookup(HashTable *ht, const char *key) {
96   Tcl_HashEntry *he;
97   const HashValue *htv;
98   
99   he= Tcl_FindHashEntry(ht, key);
100   if (!he) return notfound;
101   
102   htv= Tcl_GetHashValue(he);
103   
104 }
105
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. */
111   Tcl_HashSearch sp;
112   Tcl_HashEntry *he;
113   const char *key;
114   HashValue *val;
115   int r;
116   
117   for (he= Tcl_FirstHashEntry(&ht->t, &sp);
118        he;
119        he= Tcl_NextHashEntry(&sp)) {
120     val= Tcl_GetHashValue(he);
121     if (!val->len) continue;
122
123     key= Tcl_GetHashKey(&ht->t, he);
124     
125     r= fn(key, val, ctx);
126     if (r) return r;
127   }
128   return 0;
129 }
130
131 static void ht_destroy(HashTable *ht) {
132   Tcl_HashSearch sp;
133   Tcl_HashEntry *he;
134   
135   for (he= Tcl_FirstHashEntry(&ht->t, &sp);
136        he;
137        he= Tcl_NextHashEntry(&sp)) {
138     /* ht_forall skips empty (deleted) entries so is no good for this */
139     TFREE(Tcl_GetHashValue(he));
140   }
141   Tcl_DeleteHashTable(&ht->t);
142 }
143
144 /*==================== Existential ====================*/
145
146 /*---------- Rw data structure ----------*/
147
148 typedef struct Rw {
149   int ix, autocompact;
150   int cdb_fd, lock_fd;
151   struct cdb cdb; /* valid iff cdb_fd >= 0 */
152   FILE *logfile;
153   HashTable logincore;
154   Pathbuf pbsome, pbother;
155   off_t mainsz;
156   ScriptToInvoke on_info, on_lexminval;
157 } Rw;
158
159 static int rw_close(Tcl_Interp *ip, Rw *rw) {
160   int rc, r;
161
162   rc= TCL_OK;
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);
167
168   if (rw->logfile) {
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"); }
172   }
173
174   pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
175   TFREE(rw);
176   return rc;
177 }
178
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
182 };
183
184 /*---------- File handling ----------*/
185
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. */
189   mode_t um, lockmode;
190   struct flock fl;
191   int r;
192
193   um= umask(~(mode_t)0);
194   umask(um);
195
196   lockmode= 0666 & ~((um & 0444)>>1);
197   /* Remove r where umask would remove w;
198    * eg umask intending 0664 here gives 0660 */
199   
200   *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
201   if (*lockfd_r < 0)
202     return cht_posixerr(ip, errno, "could not open/create lockfile");
203
204   fl.l_type= F_WRLCK;
205   fl.l_whence= SEEK_SET;
206   fl.l_start= 0;
207   fl.l_len= 0;
208   fl.l_pid= getpid();
209
210   r= fcntl(*lockfd_r, F_SETLK, &fl);
211   if (r == -1) {
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"
215                              " acquiring lock");
216   }
217
218   return TCL_OK;
219 }
220
221 /*---------- Log reading and writing ----------*/
222
223 static int readlognum(FILE *f, int delim, int *num_r) {
224   int c;
225   char numbuf[20], *p, *ep;
226   unsigned long ul;
227
228   p= numbuf;
229   for (;;) {
230     c= getc(f);  if (c==EOF) return -2;
231     if (c == delim) break;
232     if (!isdigit((unsigned char)c)) return -2;
233     *p++= c;
234     if (p == numbuf+sizeof(numbuf)) return -2;
235   }
236   if (p == numbuf) return -2;
237   *p= 0;
238
239   errno=0; ul= strtoul(numbuf, &ep, 10);
240   if (*ep || errno || ul >= INT_MAX/2) return -2;
241   *num_r= ul;
242   return 0;
243 }
244
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*,
250                                                HashValue*)) {
251   /* returns:
252    *      0     for OK
253    *     -1     eof
254    *     -2     corrupt or error
255    *     -3     got newline indicating end
256    *     >0     value from omitfn
257    */
258   int keylen, vallen;
259   char *key;
260   HashValue *val;
261   int c, rc, r;
262
263   c= getc(f);
264   if (c==EOF) { if (feof(f)) return -1; return -2; }
265   if (c=='\n') return -3;
266   if (c!='+') return -2;
267
268   rc= readlognum(f, ',', &keylen);  if (rc) return rc;
269   rc= readlognum(f, ':', &vallen);  if (rc) return rc;
270
271   key= TALLOC(keylen+1);
272   val= htv_prep(vallen);
273
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;
277   key[keylen]= 0;
278
279   c= getc(f);  if (c!='-') goto x2_free_keyval;
280   c= getc(f);  if (c!='>') goto x2_free_keyval;
281   
282   r= fread(htv_fillptr(val), 1,vallen, f);
283   if (r!=vallen) goto x2_free_keyval;
284
285   rc= omitfn ? omitfn(val, ctx) : TCL_OK;
286   if (rc) { assert(rc>0); TFREE(val); }
287   else updatefn(ht, key, val);
288   
289   TFREE(key);
290   return rc;
291
292  x2_free_keyval:
293   TFREE(val);
294   TFREE(key);
295   return -2;
296 }
297
298 static int writerecord(FILE *f, const char *key, const HashValue *val) {
299   int r;
300
301   r= fprintf(f, "+%d,%d:%s->", strlen(key), val->len, key);
302   if (r<0) return -1;
303   
304   r= fwrite(val->data, 1, val->len, f);
305   if (r != val->len) return -1;
306
307   return 0;
308 }
309
310 /*---------- Creating ----------*/
311
312 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
313                               const char *pathb) {
314   static const char *const toremoves[]= {
315     ".main", ".cdb", ".log", ".tmp", 0
316   };
317
318   Pathbuf pb;
319   int lock_fd=-1, fd=-1, rc, r;
320   const char *const *toremove;
321
322   pathbuf_init(&pb, pathb);
323   rc= acquire_lock(ip, &pb, &lock_fd);  if (rc) goto x_rc;
324   
325   fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
326   if (fd <= 0) PE("create new database file");
327
328   for (toremove=toremoves; *toremove; toremove++) {
329     r= remove(*toremove);
330     if (r && errno != ENOENT)
331       PE("delete possible spurious file during creation");
332   }
333   
334   rc= TCL_OK;
335
336  x_rc:
337   maybe_close(fd);
338   maybe_close(lock_fd);
339   pathbuf_free(&pb);
340   return rc;
341 }
342
343 /*---------- Info callbacks ----------*/
344
345 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
346                     const char *arg2fmt, const char *arg3, va_list al) {
347   Tcl_Obj *aa[3];
348   int na;
349   char buf[200];
350   vsnprintf(buf, sizeof(buf), arg2fmt, al);
351
352   na= 0;
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);
356   
357   return cht_scriptinv_invoke_fg(&rw->on_info, na, aa);
358 }
359   
360 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
361                    const char *arg2fmt, const char *arg3, ...) {
362   int rc;
363   va_list al;
364   va_start(al, arg3);
365   rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
366   va_end(al);
367   return rc;
368 }
369   
370 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
371                   const char *arg2fmt, ...) {
372   int rc;
373   va_list al;
374   va_start(al, arg2fmt);
375   rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
376   va_end(al);
377   return rc;
378 }
379   
380 /*---------- Opening ----------*/
381
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 */
385   int r, rc;
386   
387   r= cdb_init(&rw->cdb, rw->cdb_fd);
388   if (r) {
389     rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
390     close(rw->cdb_fd);  rw->cdb_fd= -1;  return rc;
391   }
392   return TCL_OK;
393 }
394
395 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
396                       Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
397                       void **result) {
398   const Cdbwr_SubCommand *subcmd= cd;
399   int r, rc, mainfd=-1;
400   Rw *rw;
401   struct stat stab;
402   off_t logrecstart, logjunkpos;
403
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);
411   rw->autocompact= 1;
412
413   if (on_lexminval) {
414     rc= cht_scriptinv_set(&rw->on_lexminval, ip, on_lexminval, 0);
415     if (rc) goto x_rc;
416   } else {
417     rw->on_lexminval.llength= 0;
418   }
419
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;
423
424   r= fstat(mainfd, &stab);  if (r) PE("fstat .main");
425   rw->mainsz= stab.st_size;
426
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) {
431     if (rw->mainsz) {
432       rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
433                         " .cdb must have been accidentally deleted!",
434                         "CDB CDBMISSING");
435       goto x_rc;
436     }
437     /* fine */
438   } else {
439     PE("open .cdb");
440   }
441
442   rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
443   if (!rw->logfile) {
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);
452     if (rc) goto x_rc;
453
454     for (;;) {
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");
460         goto x_rc;
461       }
462       if (r==-1) {
463         break;
464       } else if (r==-2 || r==-3) {
465         char buf[100];
466         logjunkpos= ftello(rw->logfile);
467         if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
468
469         snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
470                  (unsigned long)logjunkpos, (unsigned long)logrecstart);
471
472         if (!(subcmd->flags & RWSCF_OKJUNK)) {
473           Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
474           snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
475           Tcl_ResetResult(ip);
476           Tcl_AppendResult(ip, "syntax error (junk) in .log during"
477                            " (dirty) open, at file position ", buf, (char*)0);
478           rc= TCL_ERROR;
479           goto x_rc;
480         }
481         rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
482                     (unsigned long)logjunkpos);
483         if (rc) goto x_rc;
484
485         r= fseeko(rw->logfile, logrecstart, SEEK_SET);
486         if (r) PE("failed to fseeko .log before junk during dirty open");
487
488         r= ftruncate(fileno(rw->logfile), logrecstart);
489         if (r) PE("ftruncate .log to chop junk during dirty open");
490       } else {
491         assert(!r);
492       }
493     }
494   }
495   /* now log is positioned for appending and everything is read */
496
497   *result= rw;
498   maybe_close(mainfd);
499   return TCL_OK;
500
501  x_rc:
502   rw_close(0,rw);
503   maybe_close(mainfd);
504   return rc;
505 }
506
507 int cht_do_cdbwr_open_okjunk(ClientData cd, Tcl_Interp *ip, const char *pathb,
508                       Tcl_Obj *on_info, Tcl_Obj *on_lexminval,
509                       void **result) {
510   return cht_do_cdbwr_open(cd,ip,pathb,on_info,on_lexminval,result);
511 }
512
513 /*==================== COMPACTION ====================*/
514
515 struct ht_forall_ctx {
516   struct cdb_make cdbm;
517   FILE *mainfile;
518   int lexminvall;
519   long *reccount;
520   const char *lexminval;
521 };
522
523 /*---------- helper functions ----------*/
524
525 static int expiredp(const HashValue *val, struct ht_forall_ctx *a) {
526   int r, l;
527   if (!val->len) return 0;
528   l= val->len < a->lexminvall ? val->len : a->lexminvall;
529   r= memcmp(val->data, a->lexminval, l);
530   if (r>0) return 0;
531   if (r<0) return 1;
532   return val->len < a->lexminvall;
533 }
534
535 static int delete_ifexpired(const char *key, HashValue *val,
536                             struct ht_forall_ctx *a) {
537   if (!expiredp(val, a)) return 0;
538   val->len= 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 */
541   return 0;
542 }
543
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);
547 }
548
549 static int addto_main(const char *key, HashValue *val,
550                       struct ht_forall_ctx *a) {
551   (*a->reccount)++;
552   return writerecord(a->mainfile, key, val);
553 }
554
555 /*---------- compact main entrypoint ----------*/
556
557 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsz,
558                         long *reccount_r) {
559   /* creates new .cdb and .main
560    * closes logfile
561    * leaves .log with old data
562    * leaves cdb fd open onto old db
563    * leaves logincore full of crap
564    */
565   int r, rc;
566   int cdbfd, cdbmaking;
567   off_t errpos, newmainsz;
568   char buf[100];
569   Tcl_Obj *res;
570   struct ht_forall_ctx a;
571
572   a.mainfile= 0;
573   cdbfd= -1;
574   cdbmaking= 0;
575   *reccount_r= 0;
576   a.reccount= reccount_r;
577
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; }
581   rw->logfile= 0;
582   
583   rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
584              logsz, (unsigned long)rw->mainsz);
585   if (rc) goto x_rc;
586
587   if (rw->on_lexminval.llength) {
588     rc= cht_scriptinv_invoke_fg(&rw->on_lexminval, 0,0);
589     if (rc) goto x_rc;
590
591     res= Tcl_GetObjResult(ip);  assert(res);
592     a.lexminval= Tcl_GetStringFromObj(res, &a.lexminvall);
593     assert(a.lexminval);
594
595     /* we rely not calling Tcl_Eval during the actual compaction;
596      * if we did Tcl_Eval then the interp result would be trashed.
597      */
598     rc= ht_forall(&rw->logincore, delete_ifexpired, &a);
599
600   } else {
601     a.lexminval= "";
602   }
603
604   /* merge unsuperseded records from main into hash table */
605
606   a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
607   if (!a.mainfile) PE("failed to open .main for reading during compact");
608
609   for (;;) {
610     r= readstorelogrecord(a.mainfile, &rw->logincore,
611                           expiredp, &a,
612                           ht_maybeupdate);
613     if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
614                          " .main during compact"); goto x_rc;
615     }
616     if (r==-3) {
617       break;
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);
624       Tcl_ResetResult(ip);
625       Tcl_AppendResult(ip, "syntax error in .main during"
626                        " compact, at file position ", buf, (char*)0);
627       rc= TCL_ERROR;
628       goto x_rc;
629     } else {
630       assert(!rc);
631     }
632   }
633   fclose(a.mainfile);
634   a.mainfile= 0;
635
636   /* create new cdb */
637
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");
640
641   r= cdb_make_start(&a.cdbm, cdbfd);
642   if (r) PE("cdb_make_start during compact");
643   cdbmaking= 1;
644
645   r= ht_forall(&rw->logincore, addto_cdb, &a);
646   if (r) PE("cdb_make_add during compact");
647
648   r= cdb_make_finish(&a.cdbm);
649   if(r) PE("cdb_make_finish during compact");
650   cdbmaking= 0;
651
652   r= fdatasync(cdbfd);  if (r) PE("fdatasync new cdb during compact");
653   r= close(cdbfd);  if (r) PE("close new cdb during compact");
654   cdbfd= -1;
655
656   r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
657   if (r) PE("install new .cdb during compact");
658
659   /* create new main */
660
661   a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
662   if (!a.mainfile) PE("create .tmp for new main during compact");
663
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; }
667   
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");
671
672   newmainsz= ftello(a.mainfile);
673   if (newmainsz<0) PE("ftello new main during compact");
674   
675   r= fclose(a.mainfile);  if (r) PE("fclose new main during compact");
676   a.mainfile= 0;
677
678   r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
679   if (r) PE("install new .main during compact");
680
681   rw->mainsz= newmainsz;
682
683   /* done! */
684   
685   rc= infocb(ip, rw, "compact-end", "main=%luby nrecs=%l",
686              (unsigned long)rw->mainsz, *a.reccount);
687   if (rc) goto x_rc;
688
689   return rc;
690
691 x_rc:
692   if (a.mainfile) fclose(a.mainfile);
693   if (cdbmaking) cdb_make_finish(&a.cdbm);
694   maybe_close(cdbfd);
695   remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
696   return rc;
697 }
698
699 /*---------- Closing ----------*/
700
701 static int compact_forclose(Tcl_Interp *ip, Rw *rw, long *reccount_r) {
702   off_t logsz;
703   int r, rc;
704
705   logsz= ftello(rw->logfile);
706   if (logsz < 0) PE("ftello logfile (during tidy close)");
707
708   rc= compact_core(ip, rw, logsz, reccount_r);  if (rc) goto x_rc;
709
710   r= remove(pathbuf_sfx(&rw->pbsome,".log"));
711   if (r) PE("remove .log (during tidy close)");
712
713   return TCL_OK;
714
715 x_rc: return rc;
716 }
717   
718 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
719   Rw *rw= rw_v;
720   int rc, rc_close;
721   long reccount= -1;
722   off_t logsz;
723
724   if (rw->autocompact) rc= compact_forclose(ip, rw, &reccount);
725   else rc= TCL_OK;
726
727   if (!rc) {
728     if (!rw->logfile) {
729       logsz= ftello(rw->logfile);
730       if (logsz < 0)
731         rc= cht_posixerr(ip, errno, "ftell logfile during close info");
732       else
733         rc= infocb(ip, rw, "close", "main=%luby log=%luby",
734                    rw->mainsz, logsz);
735     } else if (reccount>=0) {
736       rc= infocb(ip, rw, "close", "main=%luby nrecs=%l", rw->mainsz, reccount);
737     } else {
738       rc= infocb(ip, rw, "close", "main=%luby", rw->mainsz);
739     }
740   }
741   rc_close= rw_close(ip,rw);
742   if (rc_close) rc= rc_close;
743   
744   cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
745   return rc;
746 }
747
748 /*---------- Other compaction-related entrypoints ----------*/
749
750 static int compact_keepopen(Tcl_Interp *ip, Rw *rw, int force) {
751   off_t logsz;
752   long reccount;
753   int rc, r;
754
755   logsz= ftello(rw->logfile);
756   if (logsz < 0) return cht_posixerr(ip, errno, "ftell .log"
757                                        " during compact check or force");
758
759   if (!force && logsz < rw->mainsz / 10 + 1000) return TCL_OK;
760
761   rc= compact_core(ip, rw, logsz, &reccount);  if (rc) goto x_rc;
762
763   maybe_close(rw->cdb_fd);
764   rw->cdb_fd= -1;
765   ht_destroy(&rw->logincore);
766   ht_setup(&rw->logincore);
767
768   rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
769   if (rw->cdb_fd < 0) PE("reopen .cdb after compact");
770
771   rc= cdbinit(ip, rw);  if (rc) goto x_rc;
772
773   rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "w");
774   if (!rw->logfile) PE("reopen .log after compact");
775
776   r= fsync(fileno(rw->logfile));  if (r) PE("fsync .log after compact reopen");
777
778   return TCL_OK;
779
780 x_rc:
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. */
784   return rc;
785 }
786
787 int cht_do_cdbwr_compact_force(ClientData cd, Tcl_Interp *ip, void *rw_v) {
788   return compact_keepopen(ip, rw_v, 1);
789 }
790 int cht_do_cdbwr_compact_check(ClientData cd, Tcl_Interp *ip, void *rw_v) {
791   return compact_keepopen(ip, rw_v, 0);
792 }
793
794 int cht_do_cdbwr_compact_explicit(ClientData cd, Tcl_Interp *ip, void *rw_v) {
795   Rw *rw= rw_v;
796   rw->autocompact= 0;
797   return TCL_OK;
798 }
799 int cht_do_cdbwr_compact_auto(ClientData cd, Tcl_Interp *ip, void *rw_v) {
800   Rw *rw= rw_v;
801   rw->autocompact= 1;
802   return TCL_OK;
803 }
804
805 /*---------- Updateing ----------*/
806
807 static int update(Tcl_Interp *ip, Rw *rw, const char *key,
808                   const Byte *data, int dlen) {
809   HashValue *val;
810   int rc, r;
811
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");
815   
816   val= htv_prep(dlen);  assert(val);
817   memcpy(htv_fillptr(val), data, dlen);
818
819   r= writerecord(rw->logfile, key, val);
820   if (!r) r= fflush(rw->logfile);
821   if (r) PE("write update to logfile");
822
823   ht_update(&rw->logincore, key, val);
824   return compact_keepopen(ip, rw, 0);
825
826  x_rc:
827   TFREE(val);
828   return rc;
829 }  
830
831 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip,
832                         void *rw_v, const char *key, Tcl_Obj *value) {
833   int dlen;
834   const char *data;
835   data= Tcl_GetStringFromObj(value, &dlen);  assert(data);
836   return update(ip, rw_v, key, data, dlen);
837 }
838
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));
842 }
843
844 int cht_do_cdbwr_delete(ClientData cd, Tcl_Interp *ip, void *rw_v,
845                         const char *key) {
846   return update(ip, rw_v, key, 0, 0);
847 }
848
849 /*---------- Lookups ----------*/
850
851 static int lookup(Tcl_Interp *ip, Rw *rw, const char *key, ) {
852   ht_lookup(
853
854 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *db,
855                         const char *key, Tcl_Obj *def, Tcl_Obj **result) {
856   
857 }
858
859 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *db, const char *key, HBytes_Value def, HBytes_Value *result);