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