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