chiark / gitweb /
halfway through implementing mintstamp
[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 /*---------- Pathbuf ----------*/
23
24 typedef struct Pathbuf {
25   char *buf, *sfx;
26 } Pathbuf;
27
28 #define MAX_SUFFIX 4
29
30 static void pathbuf_init(Pathbuf *pb, const char *pathb) {
31   int l= strlen(pathb);
32   pb->buf= TALLOC(l + 4);
33   memcpy(pb->buf, pathb, l);
34   pb->sfx= pb->buf + l;
35   *pb->sfx++= '.';
36 }
37 static const char *pathbuf_sfx(Pathbuf *pb, const char *suffix) {
38   assert(strlen(suffix) <= MAX_SUFFIX);
39   strcpy(pb->sfx, suffix);
40   return pb->buf;
41 }
42 static void pathbuf_free(Pathbuf *pb) {
43   TFREE(pb->buf);
44   pb->buf= 0;
45 }
46
47 /*---------- Our hash table ----------*/
48
49 typedef struct HashTable {
50   Tcl_HashTable t;
51   Byte padding[128]; /* allow for expansion by Tcl, urgh */
52   Byte confound[16];
53 } HashTable;
54
55 typedef struct HashValue {
56   int len;
57   Byte data[1];
58 } HashValue;
59
60 static HashValue *htv_prep(int len) {
61   HashValue *hd;
62   hd= TALLOC((hd->data - (Byte*)hd) + len);
63   hd->len= len;
64 }  
65 static Byte *htv_fillptr(HashValue *hd) {
66   return hd->data;
67 }
68 static void htv_fill(HashValue *hd, const Byte *data) {
69   memcpy(hd->data, data, hd->len);
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 int ht_forall(HashTable *ht,
96                      int (*fn)(const char *key, const HashValue *val,
97                                Tcl_HashEntry *he, struct ht_forall_ctx *ctx),
98                      struct ht_forall_ctx *ctx) {
99   /* Returns first positive value returned by any call to fn, or 0. */
100   Tcl_HashSearch sp;n
101   Tcl_HashEntry *he;
102   const char *key;
103   HashValue *val;
104   int r;
105   
106   for (he= Tcl_FirstHashEntry(&ht->t, &sp);
107        he;
108        he= Tcl_NextHashEntry(&sp)) {
109     val= Tcl_GetHashValue(he);
110     if (!val->len) continue;
111
112     key= Tcl_GetHashKey(&ht->t, he);
113     
114     r= fn(key, val, ctx);
115     if (r) return r;
116   }
117   return 0;
118 }
119
120 static void ht_destroy(HashTable *ht) {
121   Tcl_HashSearch sp;
122   Tcl_HashEntry *he;
123   
124   for (he= Tcl_FirstHashEntry(&ht->t, &sp);
125        he;
126        he= Tcl_NextHashEntry(&sp)) {
127     TFREE(Tcl_GetHashValue(he));
128   }
129   Tcl_DeleteHashTable(&ht->t);
130 }
131
132 /*---------- Rw data structure ----------*/
133
134 typedef struct {
135   int ix, autocompact;
136   int cdb_fd, lock_fd;
137   struct cdb cdb; /* valid iff cdb_fd >= 0 */
138   off_t cdb_bytes; /* valid iff cdb_fd >= 0 */
139   FILE *logfile;
140   HashTable logincore;
141   Pathbuf pbsome, pbother;
142   off_t mainsz;
143   ScriptToInvoke on_info, on_mintstamp;
144 } Rw;
145
146 static int rw_close(Tcl_Interp *ip, Rw *rw) {
147   int rc, r;
148
149   rc= TCL_OK;
150   ht_destroy(&rw->logincore);
151   maybe_close(rw->cdb_fd);
152   maybe_close(rw->lock_fd);
153
154   if (rw->logfile) {
155     r= fclose(rw->logfile);
156     if (r && ip) { rc= cht_posixerr(ip, errno, "probable data loss! failed to"
157                                     " fclose logfile during untidy close"); }
158   }
159
160   pathbuf_free(&rw->pbsome); pathbuf_free(&rw->pbother);
161   TFREE(rw);
162   return rc;
163 }
164
165 static void destroy_cdbrw_idtabcb(Tcl_Interp *ip, void *rw) { rw_close(0,rw); }
166 const IdDataSpec cdbtcl_rwdatabases= {
167   "cdb-rwdb", "cdb-openrwdatabases-table", destroy_cdbrw_idtabcb
168 };
169
170 /*---------- File handling ----------*/
171
172 static int acquire_lock(Tcl_Interp *ip, Pathbuf *pb, int *lockfd_r) {
173   /* *lockfd_r must be -1 on entry.  If may be set to >=0 even
174    * on error, and must be closed by the caller. */
175   mode_t um, lockmode;
176   struct flock fl;
177   int r;
178
179   um= umask(~(mode_t)0);
180   umask(um);
181
182   lockmode= 0666 & ~((um & 0444)>>1);
183   /* Remove r where umask would remove w;
184    * eg umask intending 0664 here gives 0660 */
185   
186   *lockfd_r= open(pathbuf_sfx(pb,".lock"), O_RDONLY|O_CREAT, lockmode);
187   if (*lockfd_r < 0)
188     return cht_posixerr(ip, errno, "could not open/create lockfile");
189
190   fl.l_type= F_WRLCK;
191   fl.l_whence= SEEK_SET;
192   fl.l_start= 0;
193   fl.l_len= 0;
194   fl.l_pid= getpid();
195
196   r= fcntl(*lockfd_r, F_SETLK, &fl);
197   if (r == -1) {
198     if (errno == EACCES || errno == EAGAIN)
199       return cht_staticerr(ip, "lock held by another process", "CDB LOCKED");
200     else return cht_posixerr(ip, errno, "unexpected error from fcntl while"
201                              " acquiring lock");
202   }
203 }
204
205 /*---------- Log reading ----------*/
206
207 static int readlognum(FILE *f, int delim, int *num_r) {
208   int c;
209   char numbuf[20], *p, *ep;
210   unsigned long ul;
211
212   p= numbuf;
213   for (;;) {
214     c= getc(f);  if (c==EOF) return -2;
215     if (c == delim) break;
216     if (!isdigit((unsigned char)c)) return -2;
217     *p++= c;
218     if (p == numbuf+sizeof(numbuf)) return -2;
219   }
220   if (p == numbuf) return -2;
221   *p= 0;
222
223   errno=0; ul= strtoul(numbuf, &ep, 10);
224   if (*ep || errno || ul >= INT_MAX/2) return -2;
225   *num_r= ul;
226   return 0;
227 }
228
229 static int readstorelogrecord(FILE *f, HashTable *ht,
230                               void (*updatefn)(HashTable*, const char*,
231                                                HashValue*)) {
232   /* returns:
233    *     0 for OK
234    *     -1 eof
235    *     -2 corrupt or error
236    *     -3 got newline indicating end
237    */
238   int keylen, vallen;
239   char *key;
240   HashValue *val;
241   int c, rc, r;
242
243   c= getc(f);
244   if (c==EOF) { if (feof(f)) return -1; return -2; }
245   if (c=='\n') return -3;
246   if (c!='+') return -2;
247
248   rc= readlognum(f, ',', &keylen);  if (rc) return rc;
249   rc= readlognum(f, ':', &vallen);  if (rc) return rc;
250
251   key= TALLOC(keylen+1);
252   val= htv_prep(vallen);
253
254   r= fread(key, 1,keylen, f);
255   if (r!=keylen) goto x2_free_keyval;
256   if (memchr(key,0,keylen)) goto x2_free_keyval;
257   key[keylen]= 0;
258
259   c= getc(f);  if (c!='-') goto x2_free_keyval;
260   c= getc(f);  if (c!='>') goto x2_free_keyval;
261   
262   r= fread(htv_fillptr(val), 1,vallen, f);
263   if (r!=vallen) goto x2_free_keyval;
264
265   updatefn(ht, key, val);
266   TFREE(key);
267   return TCL_OK;
268
269  x2_free_keyval:
270   TFREE(val);
271   TFREE(key);
272   return -2;
273 }
274
275 /*---------- Creating ----------*/
276
277 int cht_do_cdbwr_create_empty(ClientData cd, Tcl_Interp *ip,
278                               const char *pathb) {
279   static const char *const toremoves[]= {
280     ".main", ".cdb", ".log", ".tmp", 0
281   };
282
283   Pathbuf pb;
284   int lock_fd=-1, fd=-1, rc, r;
285   const char *const *toremove;
286
287   pathbuf_init(&pb, pathb);
288   rc= acquire_lock(ip, &pb, &lock_fd);  if (rc) goto x_rc;
289   
290   fd= open(pathbuf_sfx(&pb, ".main"), O_RDWR|O_CREAT|O_EXCL, 0666);
291   if (fd <= 0) PE("create new database file");
292
293   for (toremove=toremoves; *toremove; toremove++) {
294     r= remove(*toremove);
295     if (r && errno != ENOENT)
296       PE("delete possible spurious file during creation");
297   }
298   
299   rc= TCL_OK;
300
301  x_rc:
302   maybe_close(fd);
303   maybe_close(lock_fd);
304   pathbuf_free(&pb);
305   return rc;
306 }
307
308 /*---------- Info callbacks ----------*/
309
310 static int infocbv3(Tcl_Interp *ip, Rw *rw, const char *arg1,
311                     const char *arg2fmt, const char *arg3, va_list al) {
312   abort();
313 }
314   
315 static int infocb3(Tcl_Interp *ip, Rw *rw, const char *arg1,
316                    const char *arg2fmt, const char *arg3, ...) {
317   int rc;
318   va_list al;
319   va_start(al, arg3);
320   rc= infocbv3(ip,rw,arg1,arg2fmt,arg3,al);
321   va_end(al);
322   return rc;
323 }
324   
325 static int infocb(Tcl_Interp *ip, Rw *rw, const char *arg1,
326                   const char *arg2fmt, ...) {
327   int rc;
328   va_list al;
329   va_start(al, arg2fmt);
330   rc= infocbv3(ip,rw,arg1,arg2fmt,0,al);
331   va_end(al);
332   return rc;
333 }
334   
335 /*---------- Opening ----------*/
336
337 int cht_do_cdbwr_open(ClientData cd, Tcl_Interp *ip, const char *pathb,
338                       Tcl_Obj *on_info, Tcl_Obj *on_mintstamp,
339                       void **result) {
340   const Cdbwr_SubCommand *subcmd= cd;
341   int r, rc, mainfd=-1;
342   Rw *rw;
343   struct stat stab;
344   off_t logrecstart, logjunkpos;
345
346   rw= TALLOC(sizeof(*rw));
347   ht_setup(&rw->logincore);
348   scriptinv_init(&rw->on_info);
349   scriptinv_init(&rw->on_mintstamp);
350   rw->cdb_fd= rw->lock_fd= -1;  rw->logfile= 0;
351   rw->maxage= maxage;
352   pathbuf_init(&rw->pbsome, pathb);
353   pathbuf_init(&rw->pbother, pathb);
354   rw->autocompact= 1;
355
356   if (on_mintstamp) {
357     rc= scriptinv_set(&rw->on_mintstamp, ip, on_mintstamp, 0);
358     if (rc) goto x_rc;
359   } else {
360     rw->on_mintstamp.llength= 0;
361   }
362
363   mainfd= open(pathbuf_sfx(&rw->pbsome,".main"), O_RDONLY);
364   if (mainfd<0) PE("open exist3ing database file .main");
365   rc= acquire_lock(ip, &rw->pbsome, &rw->lock_fd);  if (rc) goto x_rc;
366
367   r= fstat(mainfd, &stab);  if (r) PE("fstat .main");
368   rw->mainsz= stab.st_size;
369
370   rw->cdb_fd= open(pathbuf_sfx(&rw->pbsome,".cdb"), O_RDONLY);
371   if (rw->cdb_fd >=0) {
372     r= cdb_init(&rw->cdb, rw->cdb_fd);
373     if (r) {
374       rc= cht_posixerr(ip, errno, "failed to initialise cdb reader");
375       close(rw->cdb_fd);  rw->cdb_fd= -1;  goto x_rc;
376     }
377   } else if (errno == ENOENT) {
378     if (rw->mainsz) {
379       rc= cht_staticerr(ip, ".cdb does not exist but .main is nonempty -"
380                         " .cdb must have been accidentally deleted!",
381                         "CDB CDBMISSING");
382       goto x_rc;
383     }
384     /* fine */
385   } else {
386     PE("open .cdb");
387   }
388
389   rw->logfile= fopen(pathbuf_sfx(&rw->pbsome,".log"), "r+");
390   if (!rw->logfile) {
391     if (errno != ENOENT) PE("failed to open .log during open");
392     rw->logfile= fopen(rw->pbsome.buf, "w");
393     if (!rw->logfile) PE("create .log during (clean) open");
394   } else { /* rw->logfile */
395     r= fstat(fileno(rw->logfile), &stab);
396     if (r==-1) PE("fstat .log during open");
397     rc= infocb(ip, rw, "open-dirty-start", "log=%luby",
398                (unsigned long)stab.st_size);
399     if (rc) goto x_rc;
400
401     for (;;) {
402       logrecstart= ftello(rw->logfile);
403       if (logrecstart < 0) PE("ftello .log during (dirty) open");
404       r= readstorelogrecord(rw->logfile, &rw->logincore, ht_update);
405       if (ferror(rw->logfile)) {
406         rc= cht_posixerr(ip, errno, "error reading .log during (dirty) open");
407         goto x_rc;
408       }
409       if (r==-1) {
410         break;
411       } else if (r==-2 || r==-3) {
412         char buf[100];
413         logjunkpos= ftello(rw->logfile);
414         if(logjunkpos<0) PE("ftello .log during report of junk in dirty open");
415
416         snprintf(buf,sizeof(buf), "CDB SYNTAX LOG %lu %lu",
417                  (unsigned long)logjunkpos, (unsigned long)logrecstart);
418
419         if (!(subcmd->flags & RWSCF_OKJUNK)) {
420           Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
421           snprintf(buf,sizeof(buf),"%lu",(unsigned long)logjunkpos);
422           Tcl_ResetResult(ip);
423           Tcl_AppendResult(ip, "syntax error (junk) in .log during"
424                            " (dirty) open, at file position ", buf, (char*)0);
425           rc= TCL_ERROR;
426           goto x_rc;
427         }
428         rc= infocb3(ip, rw, "open-dirty-junk", "errorfpos=%luby", buf,
429                     (unsigned long)logjunkpos);
430         if (rc) goto x_rc;
431
432         r= fseeko(rw->logfile, logrecstart, SEEK_SET);
433         if (r) PE("failed to fseeko .log before junk during dirty open");
434
435         r= ftruncate(fileno(rw->logfile), logrecstart);
436         if (r) PE("ftruncate .log to chop junk during dirty open");
437       } else {
438         assert(!r);
439       }
440     }
441   }
442   /* now log is positioned for appending and everything is read */
443
444   *result= rw;
445   maybe_close(mainfd);
446   return TCL_OK;
447
448  x_rc:
449   rw_close(0,rw);
450   maybe_close(mainfd);
451   return rc;
452 }
453
454 /*---------- Compacting ----------*/
455
456 static int compact_core(Tcl_Interp *ip, Rw *rw, unsigned long logsize) {
457   /* creates new .cdb and .main
458    * closes logfile
459    * leaves .log with old data
460    * leaves cdb fd open onto old db
461    * leaves logincore full of crap
462    */
463   int r, rc;
464   int cdbfd, cdbmaking;
465   off_t errpos;
466   char buf[100];
467   
468   struct ht_forall_ctx {
469     struct cdb_make cdbm;
470     FILE *mainfile;
471     int count;
472   } a;
473
474   a.mainfile= 0;
475   cdbfd= -1;
476   cdbmaking= 0;
477
478   r= fclose(rw->logfile);
479   if (r) { rc= cht_posixerr(ip, errno, "probable data loss!  failed to fclose"
480                             " logfile during compact");  goto x_rc; }
481   rw->logfile= 0;
482   
483   rc= infocb(ip, rw, "compact-start", "log=%luby main=%luby",
484              logsize, (unsigned long)rw->mainsz);
485   if (rc) goto x_rc;
486
487   if (rw->on_mintstamp.llength) {
488     rc= cht_scriptinv_invoke_fg(&rw->on_mintstamp, 0,0);
489     if (rc) goto x_rc;
490
491     Tcl_GetObjResult(ip)  fixme do something here
492   }
493
494   /* merge unsuperseded records from main into hash table */
495
496   a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".main"), "r");
497   if (!a.mainfile) PE("failed to open .main for reading during compact");
498
499   for (;;) {
500     r= readstorelogrecord(a.mainfile, &rw->logincore, ht_maybeupdate);
501     if (ferror(a.mainfile)) { rc= cht_posixerr(ip, errno, "error reading"
502                          " .main during compact"); goto x_rc;
503     }
504     if (r==-3) {
505       break;
506     } else if (r==-1 || r==-2) {
507       errpos= ftello(a.mainfile);
508       if (errpos<0) PE("ftello .main during report of syntax error");
509       snprintf(buf,sizeof(buf), "CDB SYNTAX MAIN %lu", (unsigned long)errpos);
510       Tcl_SetObjErrorCode(ip, Tcl_NewStringObj(buf,-1));
511       snprintf(buf,sizeof(buf), "%lu", (unsigned long)errpos);
512       Tcl_ResetResult(ip);
513       Tcl_AppendResult(ip, "syntax error in .main during"
514                        " compact, at file position ", buf, (char*)0);
515       rc= TCL_ERROR;
516       goto x_rc;
517     } else {
518       assert(!rc);
519     }
520   }
521   fclose(a.mainfile);
522   a.mainfile= 0;
523
524   /* create new cdb */
525
526   cdbfd= open(pathbuf_sfx(&rw->pbsome,".tmp"), O_WRONLY|O_CREAT|O_TRUNC, 0666);
527   if (cdbfd<0) PE("create .tmp for new cdb during compact");
528
529   r= cdb_make_start(&a.cdbm, cdbfd);
530   if (r) PE("cdb_make_start during compact");
531   cdbmaking= 1;
532
533   r= ht_forall(&rw->logincore, addto_cdb, &addctx);
534   if (r) PE("cdb_make_add during compact");
535
536   r= cdb_make_finish(&a.cdbm, cdbfd);
537   if(r) PE("cdb_make_finish during compact");
538   cdbmaking= 0;
539
540   r= fdatasync(cdbfd);  if (r) PE("fdatasync new cdb during compact");
541   r= close(cdbfd);  if (r) PE("close new cdb during compact");
542   cdbfd= -1;
543
544   r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".cdb"));
545   if (r) PE("install new .cdb during compact");
546
547   /* create new main */
548
549   a.mainfile= fopen(pathbuf_sfx(&rw->pbsome,".tmp"), "w");
550   if (!a.mainfile) PE("create .tmp for new main during compact");
551
552   a.count= 0;
553   r= ht_forall(&rw->logincore, addto_main, a.mainfile);
554   if (r) { rc= cht_posixerr(ip, r, "error writing to new .main"
555                             " during compact");  goto x_rc; }
556   
557   r= fflush(a.mainfile);  if (r) PE("fflush new main during compact");
558   r= fdatasync(fileno(a.mainfile));
559   if (r) PE("fdatasync new main during compact");
560   
561   r= fclose(a.mainfile);  if (r) PE("fclose new main during compact");
562   a.mainfile= 0;
563
564   r= rename(rw->pbsome.buf, pathbuf_sfx(&rw->pbother,".main"));
565   if (r) PE("install new .main during compact");
566
567   /* done! */
568   
569   rc= infocb(ip, rw, "compact-end", "log=%luby main=%luby",
570              logsize, (unsigned long)rw->mainsz);
571   if (rc) goto x_rc;
572
573   rc= TCL_OK;
574 x_rc:
575   if (mainfile) fclose(mainfile);
576   if (cdbmaking) cdb_make_finish(&a.cdbm, cdbfd);
577   maybe_close(cdbfd);
578   remove(pathbuf_sfx(&rw->pbsome,".tmp")); /* for tidyness */
579 }
580   
581 static void compact_forclose(Tcl_Interp *ip, Rw *rw) {
582   off_t logsz;
583   int rc;
584
585   logsz= ftello(rw->logfile);
586   if (logsz < 0) PE("ftello logfile (during tidy close)");
587
588   rc= compact_core(ip, rw, logsz);  if (rc) goto x_rc;
589
590   r= remove(pathbuf_sfx(&rw->pbsome,".log"));
591   if (r) PE("remove .log (during tidy close)");
592 }
593   
594 int cht_do_cdbwr_close(ClientData cd, Tcl_Interp *ip, void *rw_v) {
595   Rw *rw= rw_v;
596   int rc, compact_rc, infocb_rc;
597
598   if (rw->autocompact) compact_rc= compact_forclose(ip, rw);
599   else compact_rc= TCL_OK;
600
601   rc= rw_close(ip,rw);
602   infocb_rc= infocb_close(rw);
603   
604   cht_tabledataid_disposing(ip, rw_v, &cdbtcl_rwdatabases);
605   if (!rc) rc= compact_rc;
606   if (!rc) rc= infocb_rc;
607   return rc;
608 }
609
610   
611 int cht_do_cdbwr_lookup(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj **result);
612 int cht_do_cdbwr_lookup_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value *result);
613 int cht_do_cdbwr_update(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
614 int cht_do_cdbwr_update_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);
615 int cht_do_cdbwr_update_quick(ClientData cd, Tcl_Interp *ip, void *db, Tcl_Obj *key, Tcl_Obj *value);
616 int cht_do_cdbwr_update_quick_hb(ClientData cd, Tcl_Interp *ip, void *db, HBytes_Value key, HBytes_Value value);