Fixed bug #739: Extended service update fails with Alvis filter.
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* $Id: mfile.c,v 1.72 2006-12-03 16:05:13 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 #include <sys/types.h>
24 #include <fcntl.h>
25 #ifdef WIN32
26 #include <io.h>
27 #endif
28 #if HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #include <direntz.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <assert.h>
36 #include <errno.h>
37
38 #include <zebra-lock.h>
39 #include <idzebra/util.h>
40 #include <yaz/yaz-util.h>
41 #include "mfile.h"
42
43 static int scan_areadef(MFile_area ma, const char *ad, const char *base)
44 {
45     /*
46      * If no definition is given, use current directory, unlimited.
47      */
48     char dirname[FILENAME_MAX+1]; 
49     mf_dir **dp = &ma->dirs, *dir = *dp;
50
51     if (!ad)
52         ad = ".:-1b";
53     for (;;)
54     {
55         const char *ad0 = ad;
56         int i = 0, fact = 1, multi;
57         mfile_off_t size = 0;
58
59         while (*ad == ' ' || *ad == '\t')
60             ad++;
61         if (!*ad)
62             break;
63         if (!yaz_is_abspath(ad) && base)
64         {
65             strcpy(dirname, base);
66             i = strlen(dirname);
67             dirname[i++] = '/';
68         }
69         while (*ad)
70         {
71             if (*ad == ':' && strchr("+-0123456789", ad[1]))
72                 break;
73             if (i < FILENAME_MAX)
74                 dirname[i++] = *ad;
75             ad++;
76         }
77         dirname[i] = '\0';
78         if (*ad++ != ':')
79         {
80             yaz_log(YLOG_WARN, "Missing colon after path: %s", ad0);
81             return -1;
82         }
83         if (i == 0)
84         {
85             yaz_log(YLOG_WARN, "Empty path: %s", ad0);
86             return -1;
87         }
88         while (*ad == ' ' || *ad == '\t')
89             ad++;
90         if (*ad == '-')
91         {
92             fact = -1;
93             ad++;
94         }
95         else if (*ad == '+')
96             ad++;
97         size = 0;
98         if (*ad < '0' || *ad > '9')
99         {
100             yaz_log(YLOG_FATAL, "Missing size after path: %s", ad0);
101             return -1;
102         }
103         size = 0;
104         while (*ad >= '0' && *ad <= '9')
105             size = size*10 + (*ad++ - '0');
106         switch (*ad)
107         {
108         case 'B': case 'b': multi = 1; break;
109         case 'K': case 'k': multi = 1024; break;
110         case 'M': case 'm': multi = 1048576; break;
111         case 'G': case 'g': multi = 1073741824; break;
112         case '\0':
113             yaz_log(YLOG_FATAL, "Missing unit: %s", ad0);
114             return -1;
115         default:
116             yaz_log(YLOG_FATAL, "Illegal unit: %c in %s", *ad, ad0);
117             return -1;
118         }
119         ad++;
120         *dp = dir = (mf_dir *) xmalloc(sizeof(mf_dir));
121         dir->next = 0;
122         strcpy(dir->name, dirname);
123         dir->max_bytes = dir->avail_bytes = fact * size * multi;
124         dp = &dir->next;
125     }
126     return 0;
127 }
128
129 /** \brief position within metafile (perform seek)
130     \param mf metafile handle
131     \param pos block position
132     \param offset offset within block
133     \retval 0 OK
134     \retval -1 ERROR
135     \retval -2 OK, but file does not created (read-only)
136 */
137    
138 static zint file_position(MFile mf, zint pos, int offset)
139 {
140     zint off = 0, ps;
141     int c = mf->cur_file;
142
143     if ((c > 0 && pos <= mf->files[c-1].top) ||
144         (c < mf->no_files -1 && pos > mf->files[c].top))
145     {
146         c = 0;
147         while (c + 1 < mf->no_files && mf->files[c].top < pos)
148         {
149             off += mf->files[c].blocks;
150             c++;
151         }
152         assert(c < mf->no_files);
153     }
154     else
155         off = c ? (mf->files[c-1].top + 1) : 0;
156     if (mf->files[c].fd < 0)
157     {
158         if ((mf->files[c].fd = open(mf->files[c].path,
159                                     mf->wr ?
160                                         (O_BINARY|O_RDWR|O_CREAT) :
161                                         (O_BINARY|O_RDONLY), 0666)) < 0)
162         {
163             if (!mf->wr && errno == ENOENT && off == 0)
164             {
165                 /* we can't open it for reading. But not really an error */
166                 return -2;
167             }
168             yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to open %s", mf->files[c].path);
169             return -1;
170         }
171     }
172     ps = pos - off;
173     if (mfile_seek(mf->files[c].fd, ps *(mfile_off_t) mf->blocksize + offset,
174         SEEK_SET) < 0)
175     {
176         yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to seek in %s", mf->files[c].path);
177         yaz_log(YLOG_WARN, "pos=" ZINT_FORMAT " off=" ZINT_FORMAT " blocksize=%d offset=%d",
178                        pos, off, mf->blocksize, offset);
179         return -1;
180     }
181     mf->cur_file = c;
182     return ps;
183 }
184
185 static int cmp_part_file(const void *p1, const void *p2)
186 {
187     zint d = ((part_file *)p1)->number - ((part_file *)p2)->number;
188     if (d > 0)
189         return 1;
190     if (d < 0)
191         return -1;
192     return 0;
193 }
194
195 MFile_area mf_init(const char *name, const char *spec, const char *base,
196                    int only_shadow_files)
197 {
198     MFile_area ma = (MFile_area) xmalloc(sizeof(*ma));
199     mf_dir *dirp;
200     meta_file *meta_f;
201     part_file *part_f = 0;
202     DIR *dd;
203     struct dirent *dent;
204     int fd, number;
205     char metaname[FILENAME_MAX+1], tmpnam[FILENAME_MAX+1];
206     
207     yaz_log(YLOG_DEBUG, "mf_init(%s)", name);
208     strcpy(ma->name, name);
209     ma->mfiles = 0;
210     ma->dirs = 0;
211     if (scan_areadef(ma, spec, base) < 0)
212     {
213         yaz_log(YLOG_WARN, "Failed to access description of '%s'", name);
214         mf_destroy(ma);
215         return 0;
216     }
217     /* look at each directory */
218     for (dirp = ma->dirs; dirp; dirp = dirp->next)
219     {
220         if (!(dd = opendir(dirp->name)))
221         {
222             yaz_log(YLOG_WARN|YLOG_ERRNO, "Failed to open directory %s",
223                     dirp->name);
224             mf_destroy(ma);
225             return 0;
226         }
227         /* look at each file */
228         while ((dent = readdir(dd)))
229         {
230             int len = strlen(dent->d_name);
231             const char *cp = strrchr(dent->d_name, '-');
232             if (strchr(".-", *dent->d_name))
233                 continue;
234             if (len < 5 || !cp || strcmp(dent->d_name + len - 3, ".mf"))
235                 continue;
236             number = atoi(cp+1);
237             memcpy(metaname, dent->d_name, cp - dent->d_name);
238             metaname[ cp - dent->d_name] = '\0';
239
240             /* only files such as file-i-0.mf and file-i-b-0.mf, bug #739 */
241             if (only_shadow_files && cp[-2] != '-')
242                 continue;
243             if (!only_shadow_files && cp[-2] == '-')
244                 continue;
245             for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
246             {
247                 /* known metafile */
248                 if (!strcmp(meta_f->name, metaname))
249                 {
250                     part_f = &meta_f->files[meta_f->no_files++];
251                     break;
252                 }
253             }
254             /* new metafile */
255             if (!meta_f)
256             {
257                 meta_f = (meta_file *) xmalloc(sizeof(*meta_f));
258                 zebra_mutex_init(&meta_f->mutex);
259                 meta_f->ma = ma;
260                 meta_f->next = ma->mfiles;
261                 meta_f->open = 0;
262                 meta_f->cur_file = -1;
263                 ma->mfiles = meta_f;
264                 strcpy(meta_f->name, metaname);
265                 part_f = &meta_f->files[0];
266                 meta_f->no_files = 1;
267             }
268             part_f->number = number;
269             part_f->dir = dirp;
270             part_f->fd = -1;
271             sprintf(tmpnam, "%s/%s", dirp->name, dent->d_name);
272             part_f->path = xstrdup(tmpnam);
273             /* get size */
274             if ((fd = open(part_f->path, O_BINARY|O_RDONLY)) < 0)
275             {
276                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to access %s",
277                       dent->d_name);
278                 closedir(dd);
279                 mf_destroy(ma);
280                 return 0;
281             }
282             if ((part_f->bytes = mfile_seek(fd, 0, SEEK_END)) < 0)
283             {
284                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to seek in %s",
285                       dent->d_name);
286                 close(fd);
287                 closedir(dd);
288                 mf_destroy(ma);
289                 return 0;
290             }
291 #ifndef WIN32
292             fsync(fd);
293 #endif
294             close(fd);
295             if (dirp->max_bytes >= 0)
296                 dirp->avail_bytes -= part_f->bytes;
297         }
298         closedir(dd);
299     }
300     for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
301     {
302         yaz_log(YLOG_DEBUG, "mf_init: %s consists of %d part(s)", meta_f->name,
303               meta_f->no_files);
304         qsort(meta_f->files, meta_f->no_files, sizeof(part_file),
305               cmp_part_file);
306     }
307     return ma;
308 }
309
310 void mf_destroy(MFile_area ma)
311 {
312     mf_dir *dp;
313
314     if (!ma)
315         return;
316     dp = ma->dirs;
317     while (dp)
318     {
319         mf_dir *d = dp;
320         dp = dp->next;
321         xfree(d);
322     }
323     mf_reset(ma, 0);
324     xfree(ma);
325 }
326
327 void mf_reset(MFile_area ma, int unlink_flag)
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         meta_f = meta_f->next;
340
341         assert(!m->open);
342         for (i = 0; i<m->no_files; i++)
343         {
344             if (unlink_flag)
345                 unlink(m->files[i].path);
346             xfree(m->files[i].path);
347         }
348         zebra_mutex_destroy(&m->mutex);
349         xfree(m);
350     }
351     ma->mfiles = 0;
352 }
353
354 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
355 {
356     meta_file *mnew;
357     int i;
358     char tmp[FILENAME_MAX+1];
359     mf_dir *dp;
360
361     yaz_log(YLOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
362          wflag ? "RW" : "RDONLY");
363     assert(ma);
364     for (mnew = ma->mfiles; mnew; mnew = mnew->next)
365         if (!strcmp(name, mnew->name))
366         {
367             if (mnew->open)
368             {
369                 yaz_log(YLOG_WARN, "metafile %s already open", name);
370                 return 0;
371             }
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->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
386         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
387             mnew->min_bytes_creat; dp = dp->next);
388         if (!dp)
389         {
390             yaz_log(YLOG_FATAL, "Insufficient space for file %s", name);
391             xfree(mnew);
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 int mf_close(MFile mf)
432 {
433     int i;
434
435     yaz_log(YLOG_DEBUG, "mf_close(%s)", mf->name);
436     assert(mf->open);
437     for (i = 0; i < mf->no_files; i++)
438     {
439         if (mf->files[i].fd >= 0)
440         {
441 #ifndef WIN32
442             fsync(mf->files[i].fd);
443 #endif
444             close(mf->files[i].fd);
445             mf->files[i].fd = -1;
446         }
447     }
448     mf->open = 0;
449     return 0;
450 }
451
452 int mf_read(MFile mf, zint no, int offset, int nbytes, void *buf)
453 {
454     zint rd;
455     int toread;
456
457     zebra_mutex_lock(&mf->mutex);
458     if ((rd = file_position(mf, no, offset)) < 0)
459     {
460         if (rd == -2)
461         {
462             zebra_mutex_unlock(&mf->mutex);
463             return 0;
464         }
465         else
466         {
467             yaz_log(YLOG_FATAL, "mf_read2 %s internal error", mf->name);
468             return -1;
469         }
470     }
471     toread = nbytes ? nbytes : mf->blocksize;
472     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
473     {
474         yaz_log(YLOG_FATAL|YLOG_ERRNO, "mf_read2: Read failed (%s)",
475               mf->files[mf->cur_file].path);
476         return -1;
477     }
478     zebra_mutex_unlock(&mf->mutex);
479     if (rd < toread)
480         return 0;
481     else
482         return 1;
483 }
484
485 int mf_write(MFile mf, zint no, int offset, int nbytes, const void *buf)
486 {
487     int ret = 0;
488     zint ps;
489     zint nblocks;
490     int towrite;
491     mf_dir *dp;
492     char tmp[FILENAME_MAX+1];
493     unsigned char dummych = '\xff';
494
495     zebra_mutex_lock(&mf->mutex);
496     if ((ps = file_position(mf, no, offset)) < 0)
497     {
498         yaz_log(YLOG_FATAL, "mf_write: %s error (1)", mf->name);
499         ret = -1;
500         goto out;
501     }
502     /* file needs to grow */
503     while (ps >= mf->files[mf->cur_file].blocks)
504     {
505         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
506                        mf->blocksize;
507         /* file overflow - allocate new file */
508         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
509             needed > mf->files[mf->cur_file].dir->avail_bytes)
510         {
511             /* cap off file? */
512             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
513                 mf->blocksize)) > 0)
514             {
515                 yaz_log(YLOG_DEBUG, "Capping off file %s at pos " ZINT_FORMAT,
516                     mf->files[mf->cur_file].path, nblocks);
517                 if ((ps = file_position(mf,
518                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
519                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
520                 {
521                     yaz_log(YLOG_FATAL, "mf_write: %s error (2)",
522                                  mf->name);
523                     ret = -1;
524                     goto out;
525                 }
526                 yaz_log(YLOG_DEBUG, "ps = " ZINT_FORMAT, ps);
527                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
528                 {
529                     yaz_log(YLOG_ERRNO|YLOG_FATAL, "mf_write: %s error (3)",
530                                       mf->name);
531                     ret = -1;
532                     goto out;
533                 }
534                 mf->files[mf->cur_file].blocks += nblocks;
535                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
536                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
537                     mf->blocksize;
538             }
539             /* get other bit */
540             yaz_log(YLOG_DEBUG, "Creating new file.");
541             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
542                 dp->avail_bytes < needed; dp = dp->next);
543             if (!dp)
544             {
545                 yaz_log(YLOG_FATAL, "mf_write: %s error (4) no more space",
546                         mf->name);
547                 ret = -1;
548                 goto out;
549             }
550             mf->files[mf->cur_file].top = (mf->cur_file ?
551                                            mf->files[mf->cur_file-1].top : -1) +
552                 mf->files[mf->cur_file].blocks;
553             mf->files[++(mf->cur_file)].top = -1;
554             mf->files[mf->cur_file].dir = dp;
555             mf->files[mf->cur_file].number =
556                 mf->files[mf->cur_file-1].number + 1;
557             mf->files[mf->cur_file].blocks = 0;
558             mf->files[mf->cur_file].bytes = 0;
559             mf->files[mf->cur_file].fd = -1;
560             sprintf(tmp, "%s/%s-" ZINT_FORMAT ".mf", dp->name, mf->name,
561                 mf->files[mf->cur_file].number);
562             mf->files[mf->cur_file].path = xstrdup(tmp);
563             mf->no_files++;
564             /* open new file and position at beginning */
565             if ((ps = file_position(mf, no, offset)) < 0)
566             {
567                 yaz_log(YLOG_FATAL, "mf_write: %s error (5)", mf->name);
568                 ret = -1;
569                 goto out;
570             }   
571         }
572         else
573         {
574             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
575             mf->files[mf->cur_file].blocks += nblocks;
576             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
577             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
578                 mf->files[mf->cur_file].dir->avail_bytes -=
579                 nblocks * mf->blocksize;
580         }
581     }
582     towrite = nbytes ? nbytes : mf->blocksize;
583     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
584     {
585         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
586                 mf->name, mf->cur_file);
587         ret = -1;
588     }
589  out:
590     zebra_mutex_unlock(&mf->mutex);
591     return ret;
592 }
593
594 /** \brief metafile area statistics 
595     \param ma metafile area handle
596     \param no area number (0=first, 1=second, ..)
597     \param directory holds directory upon completion (if non-NULL)
598     \param used_bytes holds used bytes upon completion (if non-NULL)
599     \param max_bytes holds max size bytes upon completion (if non-NULL)
600     \retval 0 area number does not exist
601     \retval 1 area number exists (and directory,used_bytes,.. are set)
602 */
603 int mf_area_directory_stat(MFile_area ma, int no, const char **directory,
604                            double *used_bytes, double *max_bytes)
605 {
606     int i;
607     mf_dir *d = ma->dirs;
608     for (i = 0; d && i<no; i++, d = d->next)
609         ;
610     if (!d)
611         return 0;
612     if (directory)
613         *directory = d->name;
614     if (max_bytes)
615     {
616         /* possible loss of data. But it's just statistics and lies */
617         *max_bytes = (double) d->max_bytes;
618     }
619     if (used_bytes)
620     {
621         /* possible loss of data. But it's just statistics and lies */
622         *used_bytes = (double) (d->max_bytes - d->avail_bytes);
623     }
624     return 1;
625 }
626 /*
627  * Local variables:
628  * c-basic-offset: 4
629  * indent-tabs-mode: nil
630  * End:
631  * vim: shiftwidth=4 tabstop=8 expandtab
632  */
633