Happy new year
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1994-2009 Index Data
3
4 Zebra is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #include <sys/types.h>
21 #include <fcntl.h>
22 #ifdef WIN32
23 #include <io.h>
24 #endif
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <direntz.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <assert.h>
33 #include <errno.h>
34
35 #include <zebra-lock.h>
36 #include <idzebra/util.h>
37 #include <yaz/yaz-util.h>
38 #include "mfile.h"
39
40 static int scan_areadef(MFile_area ma, const char *ad, const char *base)
41 {
42     /*
43      * If no definition is given, use current directory, unlimited.
44      */
45     char dirname[FILENAME_MAX+1]; 
46     mf_dir **dp = &ma->dirs, *dir = *dp;
47
48     if (!ad)
49         ad = ".:-1b";
50     for (;;)
51     {
52         const char *ad0 = ad;
53         int i = 0, fact = 1, multi;
54         mfile_off_t size = 0;
55
56         while (*ad == ' ' || *ad == '\t')
57             ad++;
58         if (!*ad)
59             break;
60         if (!yaz_is_abspath(ad) && base)
61         {
62             strcpy(dirname, base);
63             i = strlen(dirname);
64             dirname[i++] = '/';
65         }
66         while (*ad)
67         {
68             if (*ad == ':' && strchr("+-0123456789", ad[1]))
69                 break;
70             if (i < FILENAME_MAX)
71                 dirname[i++] = *ad;
72             ad++;
73         }
74         dirname[i] = '\0';
75         if (*ad++ != ':')
76         {
77             yaz_log(YLOG_WARN, "Missing colon after path: %s", ad0);
78             return -1;
79         }
80         if (i == 0)
81         {
82             yaz_log(YLOG_WARN, "Empty path: %s", ad0);
83             return -1;
84         }
85         while (*ad == ' ' || *ad == '\t')
86             ad++;
87         if (*ad == '-')
88         {
89             fact = -1;
90             ad++;
91         }
92         else if (*ad == '+')
93             ad++;
94         size = 0;
95         if (*ad < '0' || *ad > '9')
96         {
97             yaz_log(YLOG_FATAL, "Missing size after path: %s", ad0);
98             return -1;
99         }
100         size = 0;
101         while (*ad >= '0' && *ad <= '9')
102             size = size*10 + (*ad++ - '0');
103         switch (*ad)
104         {
105         case 'B': case 'b': multi = 1; break;
106         case 'K': case 'k': multi = 1024; break;
107         case 'M': case 'm': multi = 1048576; break;
108         case 'G': case 'g': multi = 1073741824; break;
109         case '\0':
110             yaz_log(YLOG_FATAL, "Missing unit: %s", ad0);
111             return -1;
112         default:
113             yaz_log(YLOG_FATAL, "Illegal unit: %c in %s", *ad, ad0);
114             return -1;
115         }
116         ad++;
117         *dp = dir = (mf_dir *) xmalloc(sizeof(mf_dir));
118         dir->next = 0;
119         strcpy(dir->name, dirname);
120         dir->max_bytes = dir->avail_bytes = fact * size * multi;
121         dp = &dir->next;
122     }
123     return 0;
124 }
125
126 /** \brief position within metafile (perform seek)
127     \param mf metafile handle
128     \param pos block position
129     \param offset offset within block
130     \retval 0 OK
131     \retval -1 ERROR
132     \retval -2 OK, but file does not created (read-only)
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             {
162                 /* we can't open it for reading. But not really an error */
163                 return -2;
164             }
165             yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to open %s", mf->files[c].path);
166             return -1;
167         }
168     }
169     ps = pos - off;
170     if (mfile_seek(mf->files[c].fd, ps *(mfile_off_t) mf->blocksize + offset,
171         SEEK_SET) < 0)
172     {
173         yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to seek in %s", mf->files[c].path);
174         yaz_log(YLOG_WARN, "pos=" ZINT_FORMAT " off=" ZINT_FORMAT " blocksize=%d offset=%d",
175                        pos, off, mf->blocksize, offset);
176         return -1;
177     }
178     mf->cur_file = c;
179     return ps;
180 }
181
182 static int cmp_part_file(const void *p1, const void *p2)
183 {
184     zint d = ((part_file *)p1)->number - ((part_file *)p2)->number;
185     if (d > 0)
186         return 1;
187     if (d < 0)
188         return -1;
189     return 0;
190 }
191
192 MFile_area mf_init(const char *name, const char *spec, const char *base,
193                    int only_shadow_files)
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         mf_destroy(ma);
212         return 0;
213     }
214     /* look at each directory */
215     for (dirp = ma->dirs; dirp; dirp = dirp->next)
216     {
217         if (!(dd = opendir(dirp->name)))
218         {
219             yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to open directory %s",
220                     dirp->name);
221             mf_destroy(ma);
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             /* only files such as file-i-0.mf and file-i-b-0.mf, bug #739 */
238             if (only_shadow_files && cp[-2] != '-')
239                 continue;
240             if (!only_shadow_files && cp[-2] == '-')
241                 continue;
242             for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
243             {
244                 /* known metafile */
245                 if (!strcmp(meta_f->name, metaname))
246                 {
247                     part_f = &meta_f->files[meta_f->no_files++];
248                     break;
249                 }
250             }
251             /* new metafile */
252             if (!meta_f)
253             {
254                 meta_f = (meta_file *) xmalloc(sizeof(*meta_f));
255                 zebra_mutex_init(&meta_f->mutex);
256                 meta_f->ma = ma;
257                 meta_f->next = ma->mfiles;
258                 meta_f->open = 0;
259                 meta_f->cur_file = -1;
260                 ma->mfiles = meta_f;
261                 strcpy(meta_f->name, metaname);
262                 part_f = &meta_f->files[0];
263                 meta_f->no_files = 1;
264             }
265             part_f->number = number;
266             part_f->dir = dirp;
267             part_f->fd = -1;
268             sprintf(tmpnam, "%s/%s", dirp->name, dent->d_name);
269             part_f->path = xstrdup(tmpnam);
270             /* get size */
271             if ((fd = open(part_f->path, O_BINARY|O_RDONLY)) < 0)
272             {
273                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to access %s",
274                       dent->d_name);
275                 closedir(dd);
276                 mf_destroy(ma);
277                 return 0;
278             }
279             if ((part_f->bytes = mfile_seek(fd, 0, SEEK_END)) < 0)
280             {
281                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to seek in %s",
282                       dent->d_name);
283                 close(fd);
284                 closedir(dd);
285                 mf_destroy(ma);
286                 return 0;
287             }
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             break;
367         }
368     if (!mnew)
369     {
370         mnew = (meta_file *) xmalloc(sizeof(*mnew));
371         strcpy(mnew->name, name);
372         /* allocate one, empty file */
373         zebra_mutex_init(&mnew->mutex);
374         mnew->no_files = 1;
375         mnew->files[0].bytes = 0;
376         mnew->files[0].blocks = 0;
377         mnew->files[0].top = -1;
378         mnew->files[0].number = 0;
379         mnew->files[0].fd = -1;
380         mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
381         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
382             mnew->min_bytes_creat; dp = dp->next);
383         if (!dp)
384         {
385             yaz_log(YLOG_FATAL, "Insufficient space for file %s", name);
386             xfree(mnew);
387             return 0;
388         }
389         mnew->files[0].dir = dp;
390         sprintf(tmp, "%s/%s-%d.mf", dp->name, mnew->name, 0);
391         mnew->files[0].path = xstrdup(tmp);
392         mnew->ma = ma;
393         mnew->next = ma->mfiles;
394         ma->mfiles = mnew;
395     }
396     else
397     {
398         for (i = 0; i < mnew->no_files; i++)
399         {
400             if (mnew->files[i].bytes % block_size)
401                 mnew->files[i].bytes += block_size - mnew->files[i].bytes %
402                     block_size;
403             mnew->files[i].blocks = (int) (mnew->files[i].bytes / block_size);
404         }
405         assert(!mnew->open);
406     }
407     mnew->blocksize = block_size;
408     mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
409     mnew->wr=wflag;
410     mnew->cur_file = 0;
411     mnew->open = 1;
412
413     for (i = 0; i < mnew->no_files; i++)
414     {
415         mnew->files[i].blocks = (int)(mnew->files[i].bytes / mnew->blocksize);
416         if (i == mnew->no_files - 1)
417             mnew->files[i].top = -1;
418         else
419             mnew->files[i].top =
420                 i ? (mnew->files[i-1].top + mnew->files[i].blocks)
421                 : (mnew->files[i].blocks - 1);
422     }
423     return mnew;
424 }
425
426 int mf_close(MFile mf)
427 {
428     int i;
429
430     yaz_log(YLOG_DEBUG, "mf_close(%s)", mf->name);
431     assert(mf->open);
432     for (i = 0; i < mf->no_files; i++)
433     {
434         if (mf->files[i].fd >= 0)
435         {
436 #ifndef WIN32
437             if (mf->wr)
438                 fsync(mf->files[i].fd);
439 #endif
440             close(mf->files[i].fd);
441             mf->files[i].fd = -1;
442         }
443     }
444     mf->open = 0;
445     return 0;
446 }
447
448 int mf_read(MFile mf, zint no, int offset, int nbytes, void *buf)
449 {
450     zint rd;
451     int toread;
452
453     zebra_mutex_lock(&mf->mutex);
454     if ((rd = file_position(mf, no, offset)) < 0)
455     {
456         if (rd == -2)
457         {
458             zebra_mutex_unlock(&mf->mutex);
459             return 0;
460         }
461         else
462         {
463             yaz_log(YLOG_FATAL, "mf_read2 %s internal error", mf->name);
464             return -1;
465         }
466     }
467     toread = nbytes ? nbytes : mf->blocksize;
468     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
469     {
470         yaz_log(YLOG_FATAL|YLOG_ERRNO, "mf_read2: Read failed (%s)",
471               mf->files[mf->cur_file].path);
472         return -1;
473     }
474     zebra_mutex_unlock(&mf->mutex);
475     if (rd < toread)
476         return 0;
477     else
478         return 1;
479 }
480
481 int mf_write(MFile mf, zint no, int offset, int nbytes, const void *buf)
482 {
483     int ret = 0;
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 error (1)", mf->name);
495         ret = -1;
496         goto out;
497     }
498     /* file needs to grow */
499     while (ps >= mf->files[mf->cur_file].blocks)
500     {
501         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
502                        mf->blocksize;
503         /* file overflow - allocate new file */
504         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
505             needed > mf->files[mf->cur_file].dir->avail_bytes)
506         {
507             /* cap off file? */
508             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
509                 mf->blocksize)) > 0)
510             {
511                 yaz_log(YLOG_DEBUG, "Capping off file %s at pos " ZINT_FORMAT,
512                     mf->files[mf->cur_file].path, nblocks);
513                 if ((ps = file_position(mf,
514                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
515                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
516                 {
517                     yaz_log(YLOG_FATAL, "mf_write: %s error (2)",
518                                  mf->name);
519                     ret = -1;
520                     goto out;
521                 }
522                 yaz_log(YLOG_DEBUG, "ps = " ZINT_FORMAT, ps);
523                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
524                 {
525                     yaz_log(YLOG_ERRNO|YLOG_FATAL, "mf_write: %s error (3)",
526                                       mf->name);
527                     ret = -1;
528                     goto out;
529                 }
530                 mf->files[mf->cur_file].blocks += nblocks;
531                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
532                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
533                     mf->blocksize;
534             }
535             /* get other bit */
536             yaz_log(YLOG_DEBUG, "Creating new file.");
537             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
538                 dp->avail_bytes < needed; dp = dp->next);
539             if (!dp)
540             {
541                 yaz_log(YLOG_FATAL, "mf_write: %s error (4) no more space",
542                         mf->name);
543                 for (dp = mf->ma->dirs; dp ; dp = dp->next) {
544                     yaz_log(YLOG_FATAL,"%s: max=" ZINT_FORMAT 
545                            " used=" ZINT_FORMAT " available=" ZINT_FORMAT, 
546                         dp->name, (zint)dp->max_bytes, 
547                         (zint)(dp->max_bytes - dp->avail_bytes), (zint)dp->avail_bytes );
548                 }
549                 yaz_log(YLOG_FATAL,"Adjust the limits in your zebra.cfg");
550                 ret = -1;
551                 goto out;
552             }
553             mf->files[mf->cur_file].top = (mf->cur_file ?
554                                            mf->files[mf->cur_file-1].top : -1) +
555                 mf->files[mf->cur_file].blocks;
556             mf->files[++(mf->cur_file)].top = -1;
557             mf->files[mf->cur_file].dir = dp;
558             mf->files[mf->cur_file].number =
559                 mf->files[mf->cur_file-1].number + 1;
560             mf->files[mf->cur_file].blocks = 0;
561             mf->files[mf->cur_file].bytes = 0;
562             mf->files[mf->cur_file].fd = -1;
563             sprintf(tmp, "%s/%s-" ZINT_FORMAT ".mf", dp->name, mf->name,
564                 mf->files[mf->cur_file].number);
565             mf->files[mf->cur_file].path = xstrdup(tmp);
566             mf->no_files++;
567             /* open new file and position at beginning */
568             if ((ps = file_position(mf, no, offset)) < 0)
569             {
570                 yaz_log(YLOG_FATAL, "mf_write: %s error (5)", mf->name);
571                 ret = -1;
572                 goto out;
573             }   
574         }
575         else
576         {
577             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
578             mf->files[mf->cur_file].blocks += nblocks;
579             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
580             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
581                 mf->files[mf->cur_file].dir->avail_bytes -=
582                 nblocks * mf->blocksize;
583         }
584     }
585     towrite = nbytes ? nbytes : mf->blocksize;
586     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
587     {
588         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
589                 mf->name, mf->cur_file);
590         ret = -1;
591     }
592  out:
593     zebra_mutex_unlock(&mf->mutex);
594     return ret;
595 }
596
597 /** \brief metafile area statistics 
598     \param ma metafile area handle
599     \param no area number (0=first, 1=second, ..)
600     \param directory holds directory upon completion (if non-NULL)
601     \param used_bytes holds used bytes upon completion (if non-NULL)
602     \param max_bytes holds max size bytes upon completion (if non-NULL)
603     \retval 0 area number does not exist
604     \retval 1 area number exists (and directory,used_bytes,.. are set)
605 */
606 int mf_area_directory_stat(MFile_area ma, int no, const char **directory,
607                            double *used_bytes, double *max_bytes)
608 {
609     int i;
610     mf_dir *d = ma->dirs;
611     for (i = 0; d && i<no; i++, d = d->next)
612         ;
613     if (!d)
614         return 0;
615     if (directory)
616         *directory = d->name;
617     if (max_bytes)
618     {
619         /* possible loss of data. But it's just statistics and lies */
620         *max_bytes = (double) d->max_bytes;
621     }
622     if (used_bytes)
623     {
624         /* possible loss of data. But it's just statistics and lies */
625         *used_bytes = (double) (d->max_bytes - d->avail_bytes);
626     }
627     return 1;
628 }
629 /*
630  * Local variables:
631  * c-basic-offset: 4
632  * indent-tabs-mode: nil
633  * End:
634  * vim: shiftwidth=4 tabstop=8 expandtab
635  */
636