86ae6e738ebb16dab2ad6f84c630e3619348bb78
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /* $Id: mfile.c,v 1.73 2006-12-19 13:17:34 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             close(fd);
292             if (dirp->max_bytes >= 0)
293                 dirp->avail_bytes -= part_f->bytes;
294         }
295         closedir(dd);
296     }
297     for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
298     {
299         yaz_log(YLOG_DEBUG, "mf_init: %s consists of %d part(s)", meta_f->name,
300               meta_f->no_files);
301         qsort(meta_f->files, meta_f->no_files, sizeof(part_file),
302               cmp_part_file);
303     }
304     return ma;
305 }
306
307 void mf_destroy(MFile_area ma)
308 {
309     mf_dir *dp;
310
311     if (!ma)
312         return;
313     dp = ma->dirs;
314     while (dp)
315     {
316         mf_dir *d = dp;
317         dp = dp->next;
318         xfree(d);
319     }
320     mf_reset(ma, 0);
321     xfree(ma);
322 }
323
324 void mf_reset(MFile_area ma, int unlink_flag)
325 {
326     meta_file *meta_f;
327
328     if (!ma)
329         return;
330     meta_f = ma->mfiles;
331     while (meta_f)
332     {
333         int i;
334         meta_file *m = meta_f;
335
336         meta_f = meta_f->next;
337
338         assert(!m->open);
339         for (i = 0; i<m->no_files; i++)
340         {
341             if (unlink_flag)
342                 unlink(m->files[i].path);
343             xfree(m->files[i].path);
344         }
345         zebra_mutex_destroy(&m->mutex);
346         xfree(m);
347     }
348     ma->mfiles = 0;
349 }
350
351 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
352 {
353     meta_file *mnew;
354     int i;
355     char tmp[FILENAME_MAX+1];
356     mf_dir *dp;
357
358     yaz_log(YLOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
359          wflag ? "RW" : "RDONLY");
360     assert(ma);
361     for (mnew = ma->mfiles; mnew; mnew = mnew->next)
362         if (!strcmp(name, mnew->name))
363         {
364             if (mnew->open)
365             {
366                 yaz_log(YLOG_WARN, "metafile %s already open", name);
367                 return 0;
368             }
369         }
370     if (!mnew)
371     {
372         mnew = (meta_file *) xmalloc(sizeof(*mnew));
373         strcpy(mnew->name, name);
374         /* allocate one, empty file */
375         zebra_mutex_init(&mnew->mutex);
376         mnew->no_files = 1;
377         mnew->files[0].bytes = 0;
378         mnew->files[0].blocks = 0;
379         mnew->files[0].top = -1;
380         mnew->files[0].number = 0;
381         mnew->files[0].fd = -1;
382         mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
383         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
384             mnew->min_bytes_creat; dp = dp->next);
385         if (!dp)
386         {
387             yaz_log(YLOG_FATAL, "Insufficient space for file %s", name);
388             xfree(mnew);
389             return 0;
390         }
391         mnew->files[0].dir = dp;
392         sprintf(tmp, "%s/%s-%d.mf", dp->name, mnew->name, 0);
393         mnew->files[0].path = xstrdup(tmp);
394         mnew->ma = ma;
395         mnew->next = ma->mfiles;
396         ma->mfiles = mnew;
397     }
398     else
399     {
400         for (i = 0; i < mnew->no_files; i++)
401         {
402             if (mnew->files[i].bytes % block_size)
403                 mnew->files[i].bytes += block_size - mnew->files[i].bytes %
404                     block_size;
405             mnew->files[i].blocks = (int) (mnew->files[i].bytes / block_size);
406         }
407         assert(!mnew->open);
408     }
409     mnew->blocksize = block_size;
410     mnew->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
411     mnew->wr=wflag;
412     mnew->cur_file = 0;
413     mnew->open = 1;
414
415     for (i = 0; i < mnew->no_files; i++)
416     {
417         mnew->files[i].blocks = (int)(mnew->files[i].bytes / mnew->blocksize);
418         if (i == mnew->no_files - 1)
419             mnew->files[i].top = -1;
420         else
421             mnew->files[i].top =
422                 i ? (mnew->files[i-1].top + mnew->files[i].blocks)
423                 : (mnew->files[i].blocks - 1);
424     }
425     return mnew;
426 }
427
428 int mf_close(MFile mf)
429 {
430     int i;
431
432     yaz_log(YLOG_DEBUG, "mf_close(%s)", mf->name);
433     assert(mf->open);
434     for (i = 0; i < mf->no_files; i++)
435     {
436         if (mf->files[i].fd >= 0)
437         {
438 #ifndef WIN32
439             if (mf->wr)
440                 fsync(mf->files[i].fd);
441 #endif
442             close(mf->files[i].fd);
443             mf->files[i].fd = -1;
444         }
445     }
446     mf->open = 0;
447     return 0;
448 }
449
450 int mf_read(MFile mf, zint no, int offset, int nbytes, void *buf)
451 {
452     zint rd;
453     int toread;
454
455     zebra_mutex_lock(&mf->mutex);
456     if ((rd = file_position(mf, no, offset)) < 0)
457     {
458         if (rd == -2)
459         {
460             zebra_mutex_unlock(&mf->mutex);
461             return 0;
462         }
463         else
464         {
465             yaz_log(YLOG_FATAL, "mf_read2 %s internal error", mf->name);
466             return -1;
467         }
468     }
469     toread = nbytes ? nbytes : mf->blocksize;
470     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
471     {
472         yaz_log(YLOG_FATAL|YLOG_ERRNO, "mf_read2: Read failed (%s)",
473               mf->files[mf->cur_file].path);
474         return -1;
475     }
476     zebra_mutex_unlock(&mf->mutex);
477     if (rd < toread)
478         return 0;
479     else
480         return 1;
481 }
482
483 int mf_write(MFile mf, zint no, int offset, int nbytes, const void *buf)
484 {
485     int ret = 0;
486     zint ps;
487     zint nblocks;
488     int towrite;
489     mf_dir *dp;
490     char tmp[FILENAME_MAX+1];
491     unsigned char dummych = '\xff';
492
493     zebra_mutex_lock(&mf->mutex);
494     if ((ps = file_position(mf, no, offset)) < 0)
495     {
496         yaz_log(YLOG_FATAL, "mf_write: %s error (1)", mf->name);
497         ret = -1;
498         goto out;
499     }
500     /* file needs to grow */
501     while (ps >= mf->files[mf->cur_file].blocks)
502     {
503         mfile_off_t needed = (ps - mf->files[mf->cur_file].blocks + 1) *
504                        mf->blocksize;
505         /* file overflow - allocate new file */
506         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
507             needed > mf->files[mf->cur_file].dir->avail_bytes)
508         {
509             /* cap off file? */
510             if ((nblocks = (int) (mf->files[mf->cur_file].dir->avail_bytes /
511                 mf->blocksize)) > 0)
512             {
513                 yaz_log(YLOG_DEBUG, "Capping off file %s at pos " ZINT_FORMAT,
514                     mf->files[mf->cur_file].path, nblocks);
515                 if ((ps = file_position(mf,
516                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
517                     mf->files[mf->cur_file].blocks + nblocks - 1, 0)) < 0)
518                 {
519                     yaz_log(YLOG_FATAL, "mf_write: %s error (2)",
520                                  mf->name);
521                     ret = -1;
522                     goto out;
523                 }
524                 yaz_log(YLOG_DEBUG, "ps = " ZINT_FORMAT, ps);
525                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
526                 {
527                     yaz_log(YLOG_ERRNO|YLOG_FATAL, "mf_write: %s error (3)",
528                                       mf->name);
529                     ret = -1;
530                     goto out;
531                 }
532                 mf->files[mf->cur_file].blocks += nblocks;
533                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
534                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
535                     mf->blocksize;
536             }
537             /* get other bit */
538             yaz_log(YLOG_DEBUG, "Creating new file.");
539             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
540                 dp->avail_bytes < needed; dp = dp->next);
541             if (!dp)
542             {
543                 yaz_log(YLOG_FATAL, "mf_write: %s error (4) no more space",
544                         mf->name);
545                 ret = -1;
546                 goto out;
547             }
548             mf->files[mf->cur_file].top = (mf->cur_file ?
549                                            mf->files[mf->cur_file-1].top : -1) +
550                 mf->files[mf->cur_file].blocks;
551             mf->files[++(mf->cur_file)].top = -1;
552             mf->files[mf->cur_file].dir = dp;
553             mf->files[mf->cur_file].number =
554                 mf->files[mf->cur_file-1].number + 1;
555             mf->files[mf->cur_file].blocks = 0;
556             mf->files[mf->cur_file].bytes = 0;
557             mf->files[mf->cur_file].fd = -1;
558             sprintf(tmp, "%s/%s-" ZINT_FORMAT ".mf", dp->name, mf->name,
559                 mf->files[mf->cur_file].number);
560             mf->files[mf->cur_file].path = xstrdup(tmp);
561             mf->no_files++;
562             /* open new file and position at beginning */
563             if ((ps = file_position(mf, no, offset)) < 0)
564             {
565                 yaz_log(YLOG_FATAL, "mf_write: %s error (5)", mf->name);
566                 ret = -1;
567                 goto out;
568             }   
569         }
570         else
571         {
572             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
573             mf->files[mf->cur_file].blocks += nblocks;
574             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
575             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
576                 mf->files[mf->cur_file].dir->avail_bytes -=
577                 nblocks * mf->blocksize;
578         }
579     }
580     towrite = nbytes ? nbytes : mf->blocksize;
581     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
582     {
583         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Write failed for file %s part %d",
584                 mf->name, mf->cur_file);
585         ret = -1;
586     }
587  out:
588     zebra_mutex_unlock(&mf->mutex);
589     return ret;
590 }
591
592 /** \brief metafile area statistics 
593     \param ma metafile area handle
594     \param no area number (0=first, 1=second, ..)
595     \param directory holds directory upon completion (if non-NULL)
596     \param used_bytes holds used bytes upon completion (if non-NULL)
597     \param max_bytes holds max size bytes upon completion (if non-NULL)
598     \retval 0 area number does not exist
599     \retval 1 area number exists (and directory,used_bytes,.. are set)
600 */
601 int mf_area_directory_stat(MFile_area ma, int no, const char **directory,
602                            double *used_bytes, double *max_bytes)
603 {
604     int i;
605     mf_dir *d = ma->dirs;
606     for (i = 0; d && i<no; i++, d = d->next)
607         ;
608     if (!d)
609         return 0;
610     if (directory)
611         *directory = d->name;
612     if (max_bytes)
613     {
614         /* possible loss of data. But it's just statistics and lies */
615         *max_bytes = (double) d->max_bytes;
616     }
617     if (used_bytes)
618     {
619         /* possible loss of data. But it's just statistics and lies */
620         *used_bytes = (double) (d->max_bytes - d->avail_bytes);
621     }
622     return 1;
623 }
624 /*
625  * Local variables:
626  * c-basic-offset: 4
627  * indent-tabs-mode: nil
628  * End:
629  * vim: shiftwidth=4 tabstop=8 expandtab
630  */
631