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