Simplify and optimize commit clean operation
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* $Id: mfile.c,v 1.68 2006-10-09 22:10:00 adam Exp $
2    Copyright (C) 1995-2006
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 */
22
23
24
25
26  /*
27   * TODO: The size estimates in init may not be accurate due to
28   * only partially written final blocks.
29   */
30
31 #include <sys/types.h>
32 #include <fcntl.h>
33 #ifdef WIN32
34 #include <io.h>
35 #endif
36 #if HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #include <direntz.h>
40 #include <string.h>
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <assert.h>
44 #include <errno.h>
45
46 #include <zebra-lock.h>
47 #include <idzebra/util.h>
48 #include <yaz/yaz-util.h>
49 #include "mfile.h"
50
51 static int scan_areadef(MFile_area ma, const char *ad, const char *base)
52 {
53     /*
54      * If no definition is given, use current directory, unlimited.
55      */
56     char dirname[FILENAME_MAX+1]; 
57     mf_dir **dp = &ma->dirs, *dir = *dp;
58
59     if (!ad)
60         ad = ".:-1b";
61     for (;;)
62     {
63         const char *ad0 = ad;
64         int i = 0, fact = 1, multi;
65         mfile_off_t size = 0;
66
67         while (*ad == ' ' || *ad == '\t')
68             ad++;
69         if (!*ad)
70             break;
71         if (!yaz_is_abspath(ad) && base)
72         {
73             strcpy (dirname, base);
74             i = strlen(dirname);
75             dirname[i++] = '/';
76         }
77         while (*ad)
78         {
79             if (*ad == ':' && strchr ("+-0123456789", ad[1]))
80                 break;
81             if (i < FILENAME_MAX)
82                 dirname[i++] = *ad;
83             ad++;
84         }
85         dirname[i] = '\0';
86         if (*ad++ != ':')
87         {
88             yaz_log (YLOG_WARN, "Missing colon after path: %s", ad0);
89             return -1;
90         }
91         if (i == 0)
92         {
93             yaz_log (YLOG_WARN, "Empty path: %s", ad0);
94             return -1;
95         }
96         while (*ad == ' ' || *ad == '\t')
97             ad++;
98         if (*ad == '-')
99         {
100             fact = -1;
101             ad++;
102         }
103         else if (*ad == '+')
104             ad++;
105         size = 0;
106         if (*ad < '0' || *ad > '9')
107         {
108             yaz_log (YLOG_FATAL, "Missing size after path: %s", ad0);
109             return -1;
110         }
111         size = 0;
112         while (*ad >= '0' && *ad <= '9')
113             size = size*10 + (*ad++ - '0');
114         switch (*ad)
115         {
116         case 'B': case 'b': multi = 1; break;
117         case 'K': case 'k': multi = 1024; break;
118         case 'M': case 'm': multi = 1048576; break;
119         case 'G': case 'g': multi = 1073741824; break;
120         case '\0':
121             yaz_log (YLOG_FATAL, "Missing unit: %s", ad0);
122             return -1;
123         default:
124             yaz_log (YLOG_FATAL, "Illegal unit: %c in %s", *ad, ad0);
125             return -1;
126         }
127         ad++;
128         *dp = dir = (mf_dir *) xmalloc(sizeof(mf_dir));
129         dir->next = 0;
130         strcpy(dir->name, dirname);
131         dir->max_bytes = dir->avail_bytes = fact * size * multi;
132         dp = &dir->next;
133     }
134     return 0;
135 }
136
137 static zint file_position(MFile mf, zint pos, int offset)
138 {
139     zint off = 0, ps;
140     int c = mf->cur_file;
141
142     if ((c > 0 && pos <= mf->files[c-1].top) ||
143         (c < mf->no_files -1 && pos > mf->files[c].top))
144     {
145         c = 0;
146         while (c + 1 < mf->no_files && mf->files[c].top < pos)
147         {
148             off += mf->files[c].blocks;
149             c++;
150         }
151         assert(c < mf->no_files);
152     }
153     else
154         off = c ? (mf->files[c-1].top + 1) : 0;
155     if (mf->files[c].fd < 0)
156     {
157         if ((mf->files[c].fd = open(mf->files[c].path,
158                                     mf->wr ?
159                                         (O_BINARY|O_RDWR|O_CREAT) :
160                                         (O_BINARY|O_RDONLY), 0666)) < 0)
161         {
162             if (!mf->wr && errno == ENOENT && off == 0)
163                 return -2;
164             yaz_log (YLOG_WARN|YLOG_ERRNO, "Failed to open %s", mf->files[c].path);
165             return -1;
166         }
167     }
168     ps = pos - off;
169     if (mfile_seek(mf->files[c].fd, ps * (mfile_off_t) mf->blocksize + offset,
170         SEEK_SET) < 0)
171     {
172         yaz_log (YLOG_WARN|YLOG_ERRNO, "Failed to seek in %s", mf->files[c].path);
173         yaz_log(YLOG_WARN, "pos=" ZINT_FORMAT " off=" ZINT_FORMAT " blocksize=%d offset=%d",
174                        pos, off, mf->blocksize, offset);
175         return -1;
176     }
177     mf->cur_file = c;
178     return ps;
179 }
180
181 static int cmp_part_file(const void *p1, const void *p2)
182 {
183     zint d = ((part_file *)p1)->number - ((part_file *)p2)->number;
184     if (d > 0)
185         return 1;
186     if (d < 0)
187         return -1;
188     return 0;
189 }
190
191 /*
192  * Create a new area, cotaining metafiles in directories.
193  * Find the part-files in each directory, and inventory the existing metafiles.
194  */
195 MFile_area mf_init(const char *name, const char *spec, const char *base)
196 {
197     MFile_area ma = (MFile_area) xmalloc(sizeof(*ma));
198     mf_dir *dirp;
199     meta_file *meta_f;
200     part_file *part_f = 0;
201     DIR *dd;
202     struct dirent *dent;
203     int fd, number;
204     char metaname[FILENAME_MAX+1], tmpnam[FILENAME_MAX+1];
205     
206     yaz_log (YLOG_DEBUG, "mf_init(%s)", name);
207     strcpy(ma->name, name);
208     ma->mfiles = 0;
209     ma->dirs = 0;
210     if (scan_areadef(ma, spec, base) < 0)
211     {
212         yaz_log (YLOG_WARN, "Failed to access description of '%s'", name);
213         return 0;
214     }
215     /* look at each directory */
216     for (dirp = ma->dirs; dirp; dirp = dirp->next)
217     {
218         if (!(dd = opendir(dirp->name)))
219         {
220             yaz_log (YLOG_WARN|YLOG_ERRNO, "Failed to open directory %s",
221                                      dirp->name);
222             return 0;
223         }
224         /* look at each file */
225         while ((dent = readdir(dd)))
226         {
227             int len = strlen(dent->d_name);
228             const char *cp = strrchr (dent->d_name, '-');
229             if (strchr (".-", *dent->d_name))
230                 continue;
231             if (len < 5 || !cp || strcmp (dent->d_name + len - 3, ".mf"))
232                 continue;
233             number = atoi(cp+1);
234             memcpy (metaname, dent->d_name, cp - dent->d_name);
235             metaname[ cp - dent->d_name] = '\0';
236
237             for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
238             {
239                 /* known metafile */
240                 if (!strcmp(meta_f->name, metaname))
241                 {
242                     part_f = &meta_f->files[meta_f->no_files++];
243                     break;
244                 }
245             }
246             /* new metafile */
247             if (!meta_f)
248             {
249                 meta_f = (meta_file *) xmalloc(sizeof(*meta_f));
250                 zebra_mutex_init (&meta_f->mutex);
251                 meta_f->ma = ma;
252                 meta_f->next = ma->mfiles;
253                 meta_f->open = 0;
254                 meta_f->cur_file = -1;
255                 ma->mfiles = meta_f;
256                 strcpy(meta_f->name, metaname);
257                 part_f = &meta_f->files[0];
258                 meta_f->no_files = 1;
259             }
260             part_f->number = number;
261             part_f->dir = dirp;
262             part_f->fd = -1;
263             sprintf(tmpnam, "%s/%s", dirp->name, dent->d_name);
264             part_f->path = xstrdup(tmpnam);
265             /* get size */
266             if ((fd = open(part_f->path, O_BINARY|O_RDONLY)) < 0)
267             {
268                 yaz_log (YLOG_FATAL|YLOG_ERRNO, "Failed to access %s",
269                       dent->d_name);
270                 return 0;
271             }
272             if ((part_f->bytes = mfile_seek(fd, 0, SEEK_END)) < 0)
273             {
274                 yaz_log (YLOG_FATAL|YLOG_ERRNO, "Failed to seek in %s",
275                       dent->d_name);
276                 return 0;
277             }
278 #ifndef WIN32
279             fsync(fd);
280 #endif
281             close(fd);
282             if (dirp->max_bytes >= 0)
283                 dirp->avail_bytes -= part_f->bytes;
284         }
285         closedir(dd);
286     }
287     for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
288     {
289         yaz_log (YLOG_DEBUG, "mf_init: %s consists of %d part(s)", meta_f->name,
290               meta_f->no_files);
291         qsort(meta_f->files, meta_f->no_files, sizeof(part_file),
292               cmp_part_file);
293     }
294     return ma;
295 }
296
297 void mf_destroy(MFile_area ma)
298 {
299     mf_dir *dp;
300     meta_file *meta_f;
301
302     if (!ma)
303         return;
304     dp = ma->dirs;
305     while (dp)
306     {
307         mf_dir *d = dp;
308         dp = dp->next;
309         xfree (d);
310     }
311     mf_reset(ma, 0);
312     xfree (ma);
313 }
314
315 void mf_reset(MFile_area ma, int unlink_flag)
316 {
317     meta_file *meta_f;
318
319     if (!ma)
320         return;
321     meta_f = ma->mfiles;
322     while (meta_f)
323     {
324         int i;
325         meta_file *m = meta_f;
326
327         meta_f = meta_f->next;
328
329         assert (!m->open);
330         for (i = 0; i<m->no_files; i++)
331         {
332             if (unlink_flag)
333                 unlink (m->files[i].path);
334             xfree (m->files[i].path);
335         }
336         zebra_mutex_destroy (&m->mutex);
337         xfree (m);
338     }
339     ma->mfiles = 0;
340 }
341
342 /*
343  * Open a metafile.
344  */
345 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
346 {
347     meta_file *mnew;
348     int i;
349     char tmp[FILENAME_MAX+1];
350     mf_dir *dp;
351
352     yaz_log(YLOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
353          wflag ? "RW" : "RDONLY");
354     assert (ma);
355     for (mnew = ma->mfiles; mnew; mnew = mnew->next)
356         if (!strcmp(name, mnew->name))
357         {
358             if (mnew->open)
359                 abort();
360             else
361                 break;
362         }
363     if (!mnew)
364     {
365         mnew = (meta_file *) xmalloc(sizeof(*mnew));
366         strcpy(mnew->name, name);
367         /* allocate one, empty file */
368         zebra_mutex_init (&mnew->mutex);
369         mnew->no_files = 1;
370         mnew->files[0].bytes = 0;
371         mnew->files[0].blocks = 0;
372         mnew->files[0].top = -1;
373         mnew->files[0].number = 0;
374         mnew->files[0].fd = -1;
375         mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
376         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
377             mnew->min_bytes_creat; dp = dp->next);
378         if (!dp)
379         {
380             yaz_log (YLOG_FATAL, "Insufficient space for new mfile.");
381             return 0;
382         }
383         mnew->files[0].dir = dp;
384         sprintf(tmp, "%s/%s-%d.mf", dp->name, mnew->name, 0);
385         mnew->files[0].path = xstrdup(tmp);
386         mnew->ma = ma;
387         mnew->next = ma->mfiles;
388         ma->mfiles = mnew;
389     }
390     else
391     {
392         for (i = 0; i < mnew->no_files; i++)
393         {
394             if (mnew->files[i].bytes % block_size)
395                 mnew->files[i].bytes += block_size - mnew->files[i].bytes %
396                     block_size;
397             mnew->files[i].blocks = (int) (mnew->files[i].bytes / block_size);
398         }
399         assert(!mnew->open);
400     }
401     mnew->blocksize = block_size;
402     mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
403     mnew->wr=wflag;
404     mnew->cur_file = 0;
405     mnew->open = 1;
406
407     for (i = 0; i < mnew->no_files; i++)
408     {
409         mnew->files[i].blocks = (int)(mnew->files[i].bytes / mnew->blocksize);
410         if (i == mnew->no_files - 1)
411             mnew->files[i].top = -1;
412         else
413             mnew->files[i].top =
414                 i ? (mnew->files[i-1].top + mnew->files[i].blocks)
415                 : (mnew->files[i].blocks - 1);
416     }
417     return mnew;
418 }
419
420 /*
421  * Close a metafile.
422  */
423 int mf_close(MFile mf)
424 {
425     int i;
426
427     yaz_log (YLOG_DEBUG, "mf_close(%s)", mf->name);
428     assert(mf->open);
429     for (i = 0; i < mf->no_files; i++)
430     {
431         if (mf->files[i].fd >= 0)
432         {
433 #ifndef WIN32
434             fsync(mf->files[i].fd);
435 #endif
436             close(mf->files[i].fd);
437             mf->files[i].fd = -1;
438         }
439     }
440     mf->open = 0;
441     return 0;
442 }
443
444 /*
445  * Read one block from a metafile. Interface mirrors bfile.
446  */
447 int mf_read(MFile mf, zint no, int offset, int nbytes, void *buf)
448 {
449     zint rd;
450     int toread;
451
452     zebra_mutex_lock (&mf->mutex);
453     if ((rd = file_position(mf, no, offset)) < 0)
454     {
455         if (rd == -2)
456         {
457             zebra_mutex_unlock (&mf->mutex);
458             return 0;
459         }
460         else
461         {
462             yaz_log (YLOG_FATAL, "mf_read %s internal error", mf->name);
463             exit(1);
464         }
465     }
466     toread = nbytes ? nbytes : mf->blocksize;
467     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
468     {
469         yaz_log (YLOG_FATAL|YLOG_ERRNO, "mf_read: Read failed (%s)",
470               mf->files[mf->cur_file].path);
471         exit(1);
472     }
473     zebra_mutex_unlock (&mf->mutex);
474     if (rd < toread)
475         return 0;
476     else
477         return 1;
478 }
479
480 /*
481  * Write.
482  */
483 int mf_write(MFile mf, zint no, int offset, int nbytes, const void *buf)
484 {
485     zint ps;
486     zint nblocks;
487     int towrite;
488     mf_dir *dp;
489     char tmp[FILENAME_MAX+1];
490     unsigned char dummych = '\xff';
491
492     zebra_mutex_lock (&mf->mutex);
493     if ((ps = file_position(mf, no, offset)) < 0)
494     {
495         yaz_log (YLOG_FATAL, "mf_write %s internal error (1)", mf->name);
496         exit(1);
497     }
498     /* file needs to grow */
499     while (ps >= mf->files[mf->cur_file].blocks)
500     {
501         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
502                        mf->blocksize;
503         /* file overflow - allocate new file */
504         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
505             needed > mf->files[mf->cur_file].dir->avail_bytes)
506         {
507             /* cap off file? */
508             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
509                 mf->blocksize)) > 0)
510             {
511                 yaz_log (YLOG_DEBUG, "Capping off file %s at pos " ZINT_FORMAT,
512                     mf->files[mf->cur_file].path, nblocks);
513                 if ((ps = file_position(mf,
514                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
515                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
516                 {
517                     yaz_log (YLOG_FATAL, "mf_write %s internal error (2)",
518                                  mf->name);
519                     exit(1);
520                 }
521                 yaz_log (YLOG_DEBUG, "ps = " ZINT_FORMAT, ps);
522                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
523                 {
524                     yaz_log (YLOG_ERRNO|YLOG_FATAL, "mf_write %s internal error (3)",
525                                       mf->name);
526                     exit(1);
527                 }
528                 mf->files[mf->cur_file].blocks += nblocks;
529                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
530                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
531                     mf->blocksize;
532             }
533             /* get other bit */
534             yaz_log (YLOG_DEBUG, "Creating new file.");
535             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
536                 dp->avail_bytes < needed; dp = dp->next);
537             if (!dp)
538             {
539                 yaz_log (YLOG_FATAL, "Cannot allocate more space for %s",
540                       mf->name);
541                 exit(1);
542             }
543             mf->files[mf->cur_file].top = (mf->cur_file ?
544                 mf->files[mf->cur_file-1].top : -1) +
545                 mf->files[mf->cur_file].blocks;
546             mf->files[++(mf->cur_file)].top = -1;
547             mf->files[mf->cur_file].dir = dp;
548             mf->files[mf->cur_file].number =
549                 mf->files[mf->cur_file-1].number + 1;
550             mf->files[mf->cur_file].blocks = 0;
551             mf->files[mf->cur_file].bytes = 0;
552             mf->files[mf->cur_file].fd = -1;
553             sprintf(tmp, "%s/%s-" ZINT_FORMAT ".mf", dp->name, mf->name,
554                 mf->files[mf->cur_file].number);
555             mf->files[mf->cur_file].path = xstrdup(tmp);
556             mf->no_files++;
557             /* open new file and position at beginning */
558             if ((ps = file_position(mf, no, offset)) < 0)
559             {
560                 yaz_log (YLOG_FATAL, "mf_write %s internal error (4)",
561                                  mf->name);
562                 exit(1);
563             }   
564         }
565         else
566         {
567             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
568             mf->files[mf->cur_file].blocks += nblocks;
569             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
570             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
571                 mf->files[mf->cur_file].dir->avail_bytes -=
572                 nblocks * mf->blocksize;
573         }
574     }
575     towrite = nbytes ? nbytes : mf->blocksize;
576     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
577     {
578         yaz_log (YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
579                 mf->name, mf->cur_file);
580         exit(1);
581     }
582     zebra_mutex_unlock (&mf->mutex);
583     return 0;
584 }
585
586 int mf_area_directory_stat(MFile_area ma, int no, const char **directory,
587                            double *used_bytes, double *max_bytes)
588 {
589     int i;
590     mf_dir *d = ma->dirs;
591     for (i = 0; d && i<no; i++, d = d->next)
592         ;
593     if (!d)
594         return 0;
595     if (directory)
596         *directory = d->name;
597     if (max_bytes)
598     {
599         /* possible loss of data. But it's just statistics and lies */
600         *max_bytes = (double) d->max_bytes;
601     }
602     if (used_bytes)
603     {
604         /* possible loss of data. But it's just statistics and lies */
605         *used_bytes = (double) (d->max_bytes - d->avail_bytes);
606     }
607     return 1;
608 }
609 /*
610  * Local variables:
611  * c-basic-offset: 4
612  * indent-tabs-mode: nil
613  * End:
614  * vim: shiftwidth=4 tabstop=8 expandtab
615  */
616