2f6500fc03e407ecffcdd4223477261f9f8b0596
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* $Id: mfile.c,v 1.66 2006-06-07 10:14:39 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 Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
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                 meta_f->unlink_flag = 0;
256                 ma->mfiles = meta_f;
257                 strcpy(meta_f->name, metaname);
258                 part_f = &meta_f->files[0];
259                 meta_f->no_files = 1;
260             }
261             part_f->number = number;
262             part_f->dir = dirp;
263             part_f->fd = -1;
264             sprintf(tmpnam, "%s/%s", dirp->name, dent->d_name);
265             part_f->path = xstrdup(tmpnam);
266             /* get size */
267             if ((fd = open(part_f->path, O_BINARY|O_RDONLY)) < 0)
268             {
269                 yaz_log (YLOG_FATAL|YLOG_ERRNO, "Failed to access %s",
270                       dent->d_name);
271                 return 0;
272             }
273             if ((part_f->bytes = mfile_seek(fd, 0, SEEK_END)) < 0)
274             {
275                 yaz_log (YLOG_FATAL|YLOG_ERRNO, "Failed to seek in %s",
276                       dent->d_name);
277                 return 0;
278             }
279 #ifndef WIN32
280             fsync(fd);
281 #endif
282             close(fd);
283             if (dirp->max_bytes >= 0)
284                 dirp->avail_bytes -= part_f->bytes;
285         }
286         closedir(dd);
287     }
288     for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
289     {
290         yaz_log (YLOG_DEBUG, "mf_init: %s consists of %d part(s)", meta_f->name,
291               meta_f->no_files);
292         qsort(meta_f->files, meta_f->no_files, sizeof(part_file),
293               cmp_part_file);
294     }
295     return ma;
296 }
297
298 void mf_destroy(MFile_area ma)
299 {
300     mf_dir *dp;
301     meta_file *meta_f;
302
303     if (!ma)
304         return;
305     dp = ma->dirs;
306     while (dp)
307     {
308         mf_dir *d = dp;
309         dp = dp->next;
310         xfree (d);
311     }
312     meta_f = ma->mfiles;
313     while (meta_f)
314     {
315         int i;
316         meta_file *m = meta_f;
317         
318         for (i = 0; i<m->no_files; i++)
319         {
320             xfree (m->files[i].path);
321         }
322         zebra_mutex_destroy (&meta_f->mutex);
323         meta_f = meta_f->next;
324         xfree (m);
325     }
326     xfree (ma);
327 }
328
329 void mf_reset(MFile_area ma)
330 {
331     meta_file *meta_f;
332
333     if (!ma)
334         return;
335     meta_f = ma->mfiles;
336     while (meta_f)
337     {
338         int i;
339         meta_file *m = meta_f;
340
341         assert (!m->open);
342         for (i = 0; i<m->no_files; i++)
343         {
344             unlink (m->files[i].path);
345             xfree (m->files[i].path);
346         }
347         meta_f = meta_f->next;
348         xfree (m);
349     }
350     ma->mfiles = 0;
351 }
352
353 /*
354  * Open a metafile.
355  * If !ma, Use MF_DEFAULT_AREA.
356  */
357 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
358 {
359     meta_file *mnew;
360     int i;
361     char tmp[FILENAME_MAX+1];
362     mf_dir *dp;
363
364     yaz_log(YLOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
365          wflag ? "RW" : "RDONLY");
366     assert (ma);
367     for (mnew = ma->mfiles; mnew; mnew = mnew->next)
368         if (!strcmp(name, mnew->name))
369         {
370             if (mnew->open)
371                 abort();
372             else
373                 break;
374         }
375     if (!mnew)
376     {
377         mnew = (meta_file *) xmalloc(sizeof(*mnew));
378         strcpy(mnew->name, name);
379         /* allocate one, empty file */
380         zebra_mutex_init (&mnew->mutex);
381         mnew->no_files = 1;
382         mnew->files[0].bytes = 0;
383         mnew->files[0].blocks = 0;
384         mnew->files[0].top = -1;
385         mnew->files[0].number = 0;
386         mnew->files[0].fd = -1;
387         mnew->unlink_flag = 0;
388         mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
389         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
390             mnew->min_bytes_creat; dp = dp->next);
391         if (!dp)
392         {
393             yaz_log (YLOG_FATAL, "Insufficient space for new mfile.");
394             return 0;
395         }
396         mnew->files[0].dir = dp;
397         sprintf(tmp, "%s/%s-%d.mf", dp->name, mnew->name, 0);
398         mnew->files[0].path = xstrdup(tmp);
399         mnew->ma = ma;
400         mnew->next = ma->mfiles;
401         ma->mfiles = mnew;
402     }
403     else
404     {
405         for (i = 0; i < mnew->no_files; i++)
406         {
407             if (mnew->files[i].bytes % block_size)
408                 mnew->files[i].bytes += block_size - mnew->files[i].bytes %
409                     block_size;
410             mnew->files[i].blocks = (int) (mnew->files[i].bytes / block_size);
411         }
412         assert(!mnew->open);
413     }
414     mnew->blocksize = block_size;
415     mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
416     mnew->wr=wflag;
417     mnew->cur_file = 0;
418     mnew->open = 1;
419
420     for (i = 0; i < mnew->no_files; i++)
421     {
422         mnew->files[i].blocks = (int)(mnew->files[i].bytes / mnew->blocksize);
423         if (i == mnew->no_files - 1)
424             mnew->files[i].top = -1;
425         else
426             mnew->files[i].top =
427                 i ? (mnew->files[i-1].top + mnew->files[i].blocks)
428                 : (mnew->files[i].blocks - 1);
429     }
430     return mnew;
431 }
432
433 /*
434  * Close a metafile.
435  */
436 int mf_close(MFile mf)
437 {
438     int i;
439
440     yaz_log (YLOG_DEBUG, "mf_close(%s) unlink=%d", mf->name, mf->unlink_flag);
441     assert(mf->open);
442     for (i = 0; i < mf->no_files; i++)
443     {
444         if (mf->files[i].fd >= 0)
445         {
446 #ifndef WIN32
447             fsync(mf->files[i].fd);
448 #endif
449             close(mf->files[i].fd);
450             mf->files[i].fd = -1;
451         }
452         if (mf->unlink_flag)
453             unlink(mf->files[i].path);
454     }
455     mf->open = 0;
456     return 0;
457 }
458
459 /*
460  * Read one block from a metafile. Interface mirrors bfile.
461  */
462 int mf_read(MFile mf, zint no, int offset, int nbytes, void *buf)
463 {
464     zint rd;
465     int toread;
466
467     zebra_mutex_lock (&mf->mutex);
468     if ((rd = file_position(mf, no, offset)) < 0)
469     {
470         if (rd == -2)
471         {
472             zebra_mutex_unlock (&mf->mutex);
473             return 0;
474         }
475         else
476         {
477             yaz_log (YLOG_FATAL, "mf_read %s internal error", mf->name);
478             exit(1);
479         }
480     }
481     toread = nbytes ? nbytes : mf->blocksize;
482     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
483     {
484         yaz_log (YLOG_FATAL|YLOG_ERRNO, "mf_read: Read failed (%s)",
485               mf->files[mf->cur_file].path);
486         exit(1);
487     }
488     zebra_mutex_unlock (&mf->mutex);
489     if (rd < toread)
490         return 0;
491     else
492         return 1;
493 }
494
495 /*
496  * Write.
497  */
498 int mf_write(MFile mf, zint no, int offset, int nbytes, const void *buf)
499 {
500     zint ps;
501     zint nblocks;
502     int towrite;
503     mf_dir *dp;
504     char tmp[FILENAME_MAX+1];
505     unsigned char dummych = '\xff';
506
507     zebra_mutex_lock (&mf->mutex);
508     if ((ps = file_position(mf, no, offset)) < 0)
509     {
510         yaz_log (YLOG_FATAL, "mf_write %s internal error (1)", mf->name);
511         exit(1);
512     }
513     /* file needs to grow */
514     while (ps >= mf->files[mf->cur_file].blocks)
515     {
516         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
517                        mf->blocksize;
518         /* file overflow - allocate new file */
519         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
520             needed > mf->files[mf->cur_file].dir->avail_bytes)
521         {
522             /* cap off file? */
523             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
524                 mf->blocksize)) > 0)
525             {
526                 yaz_log (YLOG_DEBUG, "Capping off file %s at pos " ZINT_FORMAT,
527                     mf->files[mf->cur_file].path, nblocks);
528                 if ((ps = file_position(mf,
529                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
530                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
531                 {
532                     yaz_log (YLOG_FATAL, "mf_write %s internal error (2)",
533                                  mf->name);
534                     exit(1);
535                 }
536                 yaz_log (YLOG_DEBUG, "ps = " ZINT_FORMAT, ps);
537                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
538                 {
539                     yaz_log (YLOG_ERRNO|YLOG_FATAL, "mf_write %s internal error (3)",
540                                       mf->name);
541                     exit(1);
542                 }
543                 mf->files[mf->cur_file].blocks += nblocks;
544                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
545                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
546                     mf->blocksize;
547             }
548             /* get other bit */
549             yaz_log (YLOG_DEBUG, "Creating new file.");
550             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
551                 dp->avail_bytes < needed; dp = dp->next);
552             if (!dp)
553             {
554                 yaz_log (YLOG_FATAL, "Cannot allocate more space for %s",
555                       mf->name);
556                 exit(1);
557             }
558             mf->files[mf->cur_file].top = (mf->cur_file ?
559                 mf->files[mf->cur_file-1].top : -1) +
560                 mf->files[mf->cur_file].blocks;
561             mf->files[++(mf->cur_file)].top = -1;
562             mf->files[mf->cur_file].dir = dp;
563             mf->files[mf->cur_file].number =
564                 mf->files[mf->cur_file-1].number + 1;
565             mf->files[mf->cur_file].blocks = 0;
566             mf->files[mf->cur_file].bytes = 0;
567             mf->files[mf->cur_file].fd = -1;
568             sprintf(tmp, "%s/%s-" ZINT_FORMAT ".mf", dp->name, mf->name,
569                 mf->files[mf->cur_file].number);
570             mf->files[mf->cur_file].path = xstrdup(tmp);
571             mf->no_files++;
572             /* open new file and position at beginning */
573             if ((ps = file_position(mf, no, offset)) < 0)
574             {
575                 yaz_log (YLOG_FATAL, "mf_write %s internal error (4)",
576                                  mf->name);
577                 exit(1);
578             }   
579         }
580         else
581         {
582             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
583             mf->files[mf->cur_file].blocks += nblocks;
584             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
585             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
586                 mf->files[mf->cur_file].dir->avail_bytes -=
587                 nblocks * mf->blocksize;
588         }
589     }
590     towrite = nbytes ? nbytes : mf->blocksize;
591     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
592     {
593         yaz_log (YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
594                 mf->name, mf->cur_file);
595         exit(1);
596     }
597     zebra_mutex_unlock (&mf->mutex);
598     return 0;
599 }
600
601 /*
602  * Destroy a metafile, unlinking component files. File must be open.
603  */
604 int mf_unlink(MFile mf)
605 {
606     if (mf->open)
607     {
608         mf->unlink_flag = 1;
609     }
610     else
611     {
612         int i;
613         for (i = 0; i<mf->no_files; i++)
614             unlink(mf->files[i].path);
615     }
616     return 0;
617 }
618
619 int mf_area_directory_stat(MFile_area ma, int no, const char **directory,
620                            double *used_bytes, double *max_bytes)
621 {
622     int i;
623     mf_dir *d = ma->dirs;
624     for (i = 0; d && i<no; i++, d = d->next)
625         ;
626     if (!d)
627         return 0;
628     if (directory)
629         *directory = d->name;
630     if (max_bytes)
631     {
632         /* possible loss of data. But it's just statistics and lies */
633         *max_bytes = (double) d->max_bytes;
634     }
635     if (used_bytes)
636     {
637         /* possible loss of data. But it's just statistics and lies */
638         *used_bytes = (double) (d->max_bytes - d->avail_bytes);
639     }
640     return 1;
641 }
642 /*
643  * Local variables:
644  * c-basic-offset: 4
645  * indent-tabs-mode: nil
646  * End:
647  * vim: shiftwidth=4 tabstop=8 expandtab
648  */
649