Removed unused local variables.
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* $Id: mfile.c,v 1.69 2006-10-10 10:19:28 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
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     mf_reset(ma, 0);
311     xfree (ma);
312 }
313
314 void mf_reset(MFile_area ma, int unlink_flag)
315 {
316     meta_file *meta_f;
317
318     if (!ma)
319         return;
320     meta_f = ma->mfiles;
321     while (meta_f)
322     {
323         int i;
324         meta_file *m = meta_f;
325
326         meta_f = meta_f->next;
327
328         assert (!m->open);
329         for (i = 0; i<m->no_files; i++)
330         {
331             if (unlink_flag)
332                 unlink (m->files[i].path);
333             xfree (m->files[i].path);
334         }
335         zebra_mutex_destroy (&m->mutex);
336         xfree (m);
337     }
338     ma->mfiles = 0;
339 }
340
341 /*
342  * Open a metafile.
343  */
344 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
345 {
346     meta_file *mnew;
347     int i;
348     char tmp[FILENAME_MAX+1];
349     mf_dir *dp;
350
351     yaz_log(YLOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
352          wflag ? "RW" : "RDONLY");
353     assert (ma);
354     for (mnew = ma->mfiles; mnew; mnew = mnew->next)
355         if (!strcmp(name, mnew->name))
356         {
357             if (mnew->open)
358                 abort();
359             else
360                 break;
361         }
362     if (!mnew)
363     {
364         mnew = (meta_file *) xmalloc(sizeof(*mnew));
365         strcpy(mnew->name, name);
366         /* allocate one, empty file */
367         zebra_mutex_init (&mnew->mutex);
368         mnew->no_files = 1;
369         mnew->files[0].bytes = 0;
370         mnew->files[0].blocks = 0;
371         mnew->files[0].top = -1;
372         mnew->files[0].number = 0;
373         mnew->files[0].fd = -1;
374         mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
375         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
376             mnew->min_bytes_creat; dp = dp->next);
377         if (!dp)
378         {
379             yaz_log (YLOG_FATAL, "Insufficient space for new mfile.");
380             return 0;
381         }
382         mnew->files[0].dir = dp;
383         sprintf(tmp, "%s/%s-%d.mf", dp->name, mnew->name, 0);
384         mnew->files[0].path = xstrdup(tmp);
385         mnew->ma = ma;
386         mnew->next = ma->mfiles;
387         ma->mfiles = mnew;
388     }
389     else
390     {
391         for (i = 0; i < mnew->no_files; i++)
392         {
393             if (mnew->files[i].bytes % block_size)
394                 mnew->files[i].bytes += block_size - mnew->files[i].bytes %
395                     block_size;
396             mnew->files[i].blocks = (int) (mnew->files[i].bytes / block_size);
397         }
398         assert(!mnew->open);
399     }
400     mnew->blocksize = block_size;
401     mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
402     mnew->wr=wflag;
403     mnew->cur_file = 0;
404     mnew->open = 1;
405
406     for (i = 0; i < mnew->no_files; i++)
407     {
408         mnew->files[i].blocks = (int)(mnew->files[i].bytes / mnew->blocksize);
409         if (i == mnew->no_files - 1)
410             mnew->files[i].top = -1;
411         else
412             mnew->files[i].top =
413                 i ? (mnew->files[i-1].top + mnew->files[i].blocks)
414                 : (mnew->files[i].blocks - 1);
415     }
416     return mnew;
417 }
418
419 /*
420  * Close a metafile.
421  */
422 int mf_close(MFile mf)
423 {
424     int i;
425
426     yaz_log (YLOG_DEBUG, "mf_close(%s)", mf->name);
427     assert(mf->open);
428     for (i = 0; i < mf->no_files; i++)
429     {
430         if (mf->files[i].fd >= 0)
431         {
432 #ifndef WIN32
433             fsync(mf->files[i].fd);
434 #endif
435             close(mf->files[i].fd);
436             mf->files[i].fd = -1;
437         }
438     }
439     mf->open = 0;
440     return 0;
441 }
442
443 /*
444  * Read one block from a metafile. Interface mirrors bfile.
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_read %s internal error", mf->name);
462             exit(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_read: Read failed (%s)",
469               mf->files[mf->cur_file].path);
470         exit(1);
471     }
472     zebra_mutex_unlock (&mf->mutex);
473     if (rd < toread)
474         return 0;
475     else
476         return 1;
477 }
478
479 /*
480  * Write.
481  */
482 int mf_write(MFile mf, zint no, int offset, int nbytes, const void *buf)
483 {
484     zint ps;
485     zint nblocks;
486     int towrite;
487     mf_dir *dp;
488     char tmp[FILENAME_MAX+1];
489     unsigned char dummych = '\xff';
490
491     zebra_mutex_lock (&mf->mutex);
492     if ((ps = file_position(mf, no, offset)) < 0)
493     {
494         yaz_log (YLOG_FATAL, "mf_write %s internal error (1)", mf->name);
495         exit(1);
496     }
497     /* file needs to grow */
498     while (ps >= mf->files[mf->cur_file].blocks)
499     {
500         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
501                        mf->blocksize;
502         /* file overflow - allocate new file */
503         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
504             needed > mf->files[mf->cur_file].dir->avail_bytes)
505         {
506             /* cap off file? */
507             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
508                 mf->blocksize)) > 0)
509             {
510                 yaz_log (YLOG_DEBUG, "Capping off file %s at pos " ZINT_FORMAT,
511                     mf->files[mf->cur_file].path, nblocks);
512                 if ((ps = file_position(mf,
513                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
514                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
515                 {
516                     yaz_log (YLOG_FATAL, "mf_write %s internal error (2)",
517                                  mf->name);
518                     exit(1);
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 internal error (3)",
524                                       mf->name);
525                     exit(1);
526                 }
527                 mf->files[mf->cur_file].blocks += nblocks;
528                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
529                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
530                     mf->blocksize;
531             }
532             /* get other bit */
533             yaz_log (YLOG_DEBUG, "Creating new file.");
534             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
535                 dp->avail_bytes < needed; dp = dp->next);
536             if (!dp)
537             {
538                 yaz_log (YLOG_FATAL, "Cannot allocate more space for %s",
539                       mf->name);
540                 exit(1);
541             }
542             mf->files[mf->cur_file].top = (mf->cur_file ?
543                 mf->files[mf->cur_file-1].top : -1) +
544                 mf->files[mf->cur_file].blocks;
545             mf->files[++(mf->cur_file)].top = -1;
546             mf->files[mf->cur_file].dir = dp;
547             mf->files[mf->cur_file].number =
548                 mf->files[mf->cur_file-1].number + 1;
549             mf->files[mf->cur_file].blocks = 0;
550             mf->files[mf->cur_file].bytes = 0;
551             mf->files[mf->cur_file].fd = -1;
552             sprintf(tmp, "%s/%s-" ZINT_FORMAT ".mf", dp->name, mf->name,
553                 mf->files[mf->cur_file].number);
554             mf->files[mf->cur_file].path = xstrdup(tmp);
555             mf->no_files++;
556             /* open new file and position at beginning */
557             if ((ps = file_position(mf, no, offset)) < 0)
558             {
559                 yaz_log (YLOG_FATAL, "mf_write %s internal error (4)",
560                                  mf->name);
561                 exit(1);
562             }   
563         }
564         else
565         {
566             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
567             mf->files[mf->cur_file].blocks += nblocks;
568             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
569             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
570                 mf->files[mf->cur_file].dir->avail_bytes -=
571                 nblocks * mf->blocksize;
572         }
573     }
574     towrite = nbytes ? nbytes : mf->blocksize;
575     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
576     {
577         yaz_log (YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
578                 mf->name, mf->cur_file);
579         exit(1);
580     }
581     zebra_mutex_unlock (&mf->mutex);
582     return 0;
583 }
584
585 int mf_area_directory_stat(MFile_area ma, int no, const char **directory,
586                            double *used_bytes, double *max_bytes)
587 {
588     int i;
589     mf_dir *d = ma->dirs;
590     for (i = 0; d && i<no; i++, d = d->next)
591         ;
592     if (!d)
593         return 0;
594     if (directory)
595         *directory = d->name;
596     if (max_bytes)
597     {
598         /* possible loss of data. But it's just statistics and lies */
599         *max_bytes = (double) d->max_bytes;
600     }
601     if (used_bytes)
602     {
603         /* possible loss of data. But it's just statistics and lies */
604         *used_bytes = (double) (d->max_bytes - d->avail_bytes);
605     }
606     return 1;
607 }
608 /*
609  * Local variables:
610  * c-basic-offset: 4
611  * indent-tabs-mode: nil
612  * End:
613  * vim: shiftwidth=4 tabstop=8 expandtab
614  */
615