Version 1.3.50.
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* $Id: mfile.c,v 1.52.2.4 2006-12-05 21:14:38 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003
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 #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 int file_position(MFile mf, int pos, int offset)
136 {
137     int off = 0, c = mf->cur_file, ps;
138
139     if ((c > 0 && pos <= mf->files[c-1].top) ||
140         (c < mf->no_files -1 && pos > mf->files[c].top))
141     {
142         c = 0;
143         while (c + 1 < mf->no_files && mf->files[c].top < pos)
144         {
145             off += mf->files[c].blocks;
146             c++;
147         }
148         assert(c < mf->no_files);
149     }
150     else
151         off = c ? (mf->files[c-1].top + 1) : 0;
152     if (mf->files[c].fd < 0)
153     {
154         if ((mf->files[c].fd = open(mf->files[c].path,
155                                     mf->wr ?
156                                         (O_BINARY|O_RDWR|O_CREAT) :
157                                         (O_BINARY|O_RDONLY), 0666)) < 0)
158         {
159             if (!mf->wr && errno == ENOENT && off == 0)
160                 return -2;
161             yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to open %s", mf->files[c].path);
162              return -1;
163         }
164     }
165     ps = pos - off;
166     if (mfile_seek(mf->files[c].fd, ps * (mfile_off_t) mf->blocksize + offset,
167         SEEK_SET) < 0)
168     {
169         yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to seek in %s", mf->files[c].path);
170         yaz_log(YLOG_WARN, "pos=%d off=%d blocksize=%d offset=%d",
171                        pos, off, mf->blocksize, offset);
172         return -1;
173     }
174     mf->cur_file = c;
175     return ps;
176 }
177
178 static int cmp_part_file(const void *p1, const void *p2)
179 {
180     return ((part_file *)p1)->number - ((part_file *)p2)->number;
181 }
182
183 /*
184  * Create a new area, cotaining metafiles in directories.
185  * Find the part-files in each directory, and inventory the existing metafiles.
186  */
187 MFile_area mf_init(const char *name, const char *spec, const char *base)
188 {
189     MFile_area ma = (MFile_area) xmalloc(sizeof(*ma));
190     mf_dir *dirp;
191     meta_file *meta_f;
192     part_file *part_f = 0;
193     DIR *dd;
194     struct dirent *dent;
195     int fd, number;
196     char metaname[FILENAME_MAX+1], tmpnam[FILENAME_MAX+1];
197     
198     yaz_log(YLOG_DEBUG, "mf_init(%s)", name);
199     strcpy(ma->name, name);
200     ma->mfiles = 0;
201     ma->dirs = 0;
202     if (scan_areadef(ma, spec, base) < 0)
203     {
204         yaz_log(YLOG_WARN, "Failed to access description of '%s'", name);
205         return 0;
206     }
207     /* look at each directory */
208     for (dirp = ma->dirs; dirp; dirp = dirp->next)
209     {
210         if (!(dd = opendir(dirp->name)))
211         {
212             yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to open directory %s",
213                                      dirp->name);
214             return 0;
215         }
216         /* look at each file */
217         while ((dent = readdir(dd)))
218         {
219             int len = strlen(dent->d_name);
220             const char *cp = strrchr (dent->d_name, '-');
221             if (strchr (".-", *dent->d_name))
222                 continue;
223             if (len < 5 || !cp || strcmp (dent->d_name + len - 3, ".mf"))
224                 continue;
225             number = atoi(cp+1);
226             memcpy (metaname, dent->d_name, cp - dent->d_name);
227             metaname[ cp - dent->d_name] = '\0';
228
229             for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
230             {
231                 /* known metafile */
232                 if (!strcmp(meta_f->name, metaname))
233                 {
234                     part_f = &meta_f->files[meta_f->no_files++];
235                     break;
236                 }
237             }
238             /* new metafile */
239             if (!meta_f)
240             {
241                 meta_f = (meta_file *) xmalloc(sizeof(*meta_f));
242                 zebra_mutex_init (&meta_f->mutex);
243                 meta_f->ma = ma;
244                 meta_f->next = ma->mfiles;
245                 meta_f->open = 0;
246                 meta_f->cur_file = -1;
247                 ma->mfiles = meta_f;
248                 strcpy(meta_f->name, metaname);
249                 part_f = &meta_f->files[0];
250                 meta_f->no_files = 1;
251             }
252             part_f->number = number;
253             part_f->dir = dirp;
254             part_f->fd = -1;
255             sprintf(tmpnam, "%s/%s", dirp->name, dent->d_name);
256             part_f->path = xstrdup(tmpnam);
257             /* get size */
258             if ((fd = open(part_f->path, O_BINARY|O_RDONLY)) < 0)
259             {
260                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to access %s",
261                       dent->d_name);
262                 return 0;
263             }
264             if ((part_f->bytes = mfile_seek(fd, 0, SEEK_END)) < 0)
265             {
266                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to seek in %s",
267                       dent->d_name);
268                 return 0;
269             }
270 #ifndef WIN32
271             fsync(fd);
272 #endif
273             close(fd);
274             if (dirp->max_bytes >= 0)
275                 dirp->avail_bytes -= part_f->bytes;
276         }
277         closedir(dd);
278     }
279     for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
280     {
281         yaz_log(YLOG_DEBUG, "mf_init: %s consists of %d part(s)", meta_f->name,
282               meta_f->no_files);
283         qsort(meta_f->files, meta_f->no_files, sizeof(part_file),
284               cmp_part_file);
285     }
286     return ma;
287 }
288
289 void mf_destroy(MFile_area ma)
290 {
291     mf_dir *dp;
292
293     if (!ma)
294         return;
295     dp = ma->dirs;
296     while (dp)
297     {
298         mf_dir *d = dp;
299         dp = dp->next;
300         xfree (d);
301     }
302     mf_reset(ma, 0);
303     xfree (ma);
304 }
305
306 void mf_reset(MFile_area ma, int unlink_flag)
307 {
308     meta_file *meta_f;
309
310     if (!ma)
311         return;
312     meta_f = ma->mfiles;
313     while (meta_f)
314     {
315         int i;
316         meta_file *m = meta_f;
317
318         meta_f = meta_f->next;
319
320         assert (!m->open);
321         for (i = 0; i<m->no_files; i++)
322         {
323             if (unlink_flag)
324                 unlink (m->files[i].path);
325             xfree (m->files[i].path);
326         }
327         zebra_mutex_destroy (&m->mutex);
328         xfree (m);
329     }
330     ma->mfiles = 0;
331 }
332
333 /*
334  * Open a metafile.
335  */
336 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
337 {
338     meta_file *mnew;
339     int i;
340     char tmp[FILENAME_MAX+1];
341     mf_dir *dp;
342
343     yaz_log(YLOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
344          wflag ? "RW" : "RDONLY");
345     assert (ma);
346     for (mnew = ma->mfiles; mnew; mnew = mnew->next)
347         if (!strcmp(name, mnew->name))
348         {
349             if (mnew->open)
350                 abort();
351             else
352                 break;
353         }
354     if (!mnew)
355     {
356         mnew = (meta_file *) xmalloc(sizeof(*mnew));
357         strcpy(mnew->name, name);
358         /* allocate one, empty file */
359         zebra_mutex_init (&mnew->mutex);
360         mnew->no_files = 1;
361         mnew->files[0].bytes = 0;
362         mnew->files[0].blocks = 0;
363         mnew->files[0].top = -1;
364         mnew->files[0].number = 0;
365         mnew->files[0].fd = -1;
366         mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
367         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
368             mnew->min_bytes_creat; dp = dp->next);
369         if (!dp)
370         {
371             yaz_log(YLOG_FATAL, "Insufficient space for new mfile.");
372             return 0;
373         }
374         mnew->files[0].dir = dp;
375         sprintf(tmp, "%s/%s-%d.mf", dp->name, mnew->name, 0);
376         mnew->files[0].path = xstrdup(tmp);
377         mnew->ma = ma;
378         mnew->next = ma->mfiles;
379         ma->mfiles = mnew;
380     }
381     else
382     {
383         for (i = 0; i < mnew->no_files; i++)
384         {
385             if (mnew->files[i].bytes % block_size)
386                 mnew->files[i].bytes += block_size - mnew->files[i].bytes %
387                     block_size;
388             mnew->files[i].blocks = (int) (mnew->files[i].bytes / block_size);
389         }
390         assert(!mnew->open);
391     }
392     mnew->blocksize = block_size;
393     mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
394     mnew->wr=wflag;
395     mnew->cur_file = 0;
396     mnew->open = 1;
397
398     for (i = 0; i < mnew->no_files; i++)
399     {
400         mnew->files[i].blocks = (int)(mnew->files[i].bytes / mnew->blocksize);
401         if (i == mnew->no_files - 1)
402             mnew->files[i].top = -1;
403         else
404             mnew->files[i].top =
405                 i ? (mnew->files[i-1].top + mnew->files[i].blocks)
406                 : (mnew->files[i].blocks - 1);
407     }
408     return mnew;
409 }
410
411 /*
412  * Close a metafile.
413  */
414 int mf_close(MFile mf)
415 {
416     int i;
417
418     yaz_log(YLOG_DEBUG, "mf_close(%s)", mf->name);
419     assert(mf->open);
420     for (i = 0; i < mf->no_files; i++)
421     {
422         if (mf->files[i].fd >= 0)
423         {
424 #ifndef WIN32
425             fsync(mf->files[i].fd);
426 #endif
427             close(mf->files[i].fd);
428             mf->files[i].fd = -1;
429         }
430     }
431     mf->open = 0;
432     return 0;
433 }
434
435 /*
436  * Read one block from a metafile. Interface mirrors bfile.
437  */
438 int mf_read(MFile mf, int no, int offset, int nbytes, void *buf)
439 {
440     int rd, toread;
441
442     zebra_mutex_lock (&mf->mutex);
443     if ((rd = file_position(mf, no, offset)) < 0)
444     {
445         if (rd == -2)
446         {
447             zebra_mutex_unlock (&mf->mutex);
448             return 0;
449         }
450         else
451         {
452             yaz_log(YLOG_FATAL, "mf_read %s internal error", mf->name);
453             exit(1);
454         }
455     }
456     toread = nbytes ? nbytes : mf->blocksize;
457     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
458     {
459         yaz_log(YLOG_FATAL|YLOG_ERRNO, "mf_read: Read failed (%s)",
460               mf->files[mf->cur_file].path);
461         exit(1);
462     }
463     zebra_mutex_unlock (&mf->mutex);
464     if (rd < toread)
465         return 0;
466     else
467         return 1;
468 }
469
470 /*
471  * Write.
472  */
473 int mf_write(MFile mf, int no, int offset, int nbytes, const void *buf)
474 {
475     int ps, nblocks, towrite;
476     mf_dir *dp;
477     char tmp[FILENAME_MAX+1];
478     unsigned char dummych = '\xff';
479
480     zebra_mutex_lock (&mf->mutex);
481     if ((ps = file_position(mf, no, offset)) < 0)
482     {
483         yaz_log(YLOG_FATAL, "mf_write %s internal error (1)", mf->name);
484         exit(1);
485     }
486     /* file needs to grow */
487     while (ps >= mf->files[mf->cur_file].blocks)
488     {
489         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
490                        mf->blocksize;
491         /* file overflow - allocate new file */
492         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
493             needed > mf->files[mf->cur_file].dir->avail_bytes)
494         {
495             /* cap off file? */
496             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
497                 mf->blocksize)) > 0)
498             {
499                 yaz_log(YLOG_DEBUG, "Capping off file %s at pos %d",
500                     mf->files[mf->cur_file].path, nblocks);
501                 if ((ps = file_position(mf,
502                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
503                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
504                 {
505                     yaz_log(YLOG_FATAL, "mf_write %s internal error (2)",
506                                  mf->name);
507                     exit(1);
508                 }
509                 yaz_log(YLOG_DEBUG, "ps = %d", ps);
510                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
511                 {
512                     yaz_log(YLOG_ERRNO|YLOG_FATAL, "mf_write %s internal error (3)",
513                                       mf->name);
514                     exit(1);
515                 }
516                 mf->files[mf->cur_file].blocks += nblocks;
517                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
518                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
519                     mf->blocksize;
520             }
521             /* get other bit */
522             yaz_log(YLOG_DEBUG, "Creating new file.");
523             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
524                 dp->avail_bytes < needed; dp = dp->next);
525             if (!dp)
526             {
527                 yaz_log(YLOG_FATAL, "Cannot allocate more space for %s",
528                       mf->name);
529                 exit(1);
530             }
531             mf->files[mf->cur_file].top = (mf->cur_file ?
532                 mf->files[mf->cur_file-1].top : -1) +
533                 mf->files[mf->cur_file].blocks;
534             mf->files[++(mf->cur_file)].top = -1;
535             mf->files[mf->cur_file].dir = dp;
536             mf->files[mf->cur_file].number =
537                 mf->files[mf->cur_file-1].number + 1;
538             mf->files[mf->cur_file].blocks = 0;
539             mf->files[mf->cur_file].bytes = 0;
540             mf->files[mf->cur_file].fd = -1;
541             sprintf(tmp, "%s/%s-%d.mf", dp->name, mf->name,
542                 mf->files[mf->cur_file].number);
543             mf->files[mf->cur_file].path = xstrdup(tmp);
544             mf->no_files++;
545             /* open new file and position at beginning */
546             if ((ps = file_position(mf, no, offset)) < 0)
547             {
548                 yaz_log(YLOG_FATAL, "mf_write %s internal error (4)",
549                                  mf->name);
550                 exit(1);
551             }   
552         }
553         else
554         {
555             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
556             mf->files[mf->cur_file].blocks += nblocks;
557             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
558             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
559                 mf->files[mf->cur_file].dir->avail_bytes -=
560                 nblocks * mf->blocksize;
561         }
562     }
563     towrite = nbytes ? nbytes : mf->blocksize;
564     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
565     {
566         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
567                 mf->name, mf->cur_file);
568         exit(1);
569     }
570     zebra_mutex_unlock (&mf->mutex);
571     return 0;
572 }
573