Zebra with full functionality
[idzebra-moved-to-github.git] / index / kinput.c
1 /*
2  * Copyright (C) 1994-2002, Index Data
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss, Heikki Levanto
5  *
6  * $Id: kinput.c,v 1.48 2002-04-05 08:46:26 adam Exp $
7  *
8  * Bugs
9  *  - Allocates a lot of memory for the merge process, but never releases it.
10  *    Doesn't matter, as the program terminates soon after.  
11  
12  */
13  
14 #include <fcntl.h>
15 #ifdef WIN32
16 #include <io.h>
17 #else
18 #include <unistd.h>
19 #endif
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <assert.h>
24
25 #include "index.h"
26
27 #define KEY_SIZE (1+sizeof(struct it_key))
28 #define INP_NAME_MAX 768
29 #define INP_BUF_START 60000
30 #define INP_BUF_ADD  400000
31
32 static int no_diffs   = 0;
33 static int no_updates = 0;
34 static int no_deletions = 0;
35 static int no_insertions = 0;
36 static int no_iterations = 0;
37
38 struct key_file {
39     int   no;            /* file no */
40     off_t offset;        /* file offset */
41     unsigned char *buf;  /* buffer block */
42     size_t buf_size;     /* number of read bytes in block */
43     size_t chunk;        /* number of bytes allocated */
44     size_t buf_ptr;      /* current position in buffer */
45     char *prev_name;     /* last word read */
46     int   sysno;         /* last sysno */
47     int   seqno;         /* last seqno */
48     off_t length;        /* length of file */
49                          /* handler invoked in each read */
50     void (*readHandler)(struct key_file *keyp, void *rinfo);
51     void *readInfo;
52     Res res;
53 };
54
55 void getFnameTmp (Res res, char *fname, int no)
56 {
57     const char *pre;
58     
59     pre = res_get_def (res, "keyTmpDir", ".");
60     sprintf (fname, "%s/key%d.tmp", pre, no);
61 }
62
63 void extract_get_fname_tmp (ZebraHandle zh, char *fname, int no)
64 {
65     const char *pre;
66     
67     pre = res_get_def (zh->res, "keyTmpDir", ".");
68     sprintf (fname, "%s/key%d.tmp", pre, no);
69 }
70
71 void key_file_chunk_read (struct key_file *f)
72 {
73     int nr = 0, r = 0, fd;
74     char fname[1024];
75     getFnameTmp (f->res, fname, f->no);
76     fd = open (fname, O_BINARY|O_RDONLY);
77
78     f->buf_ptr = 0;
79     f->buf_size = 0;
80     if (fd == -1)
81     {
82         logf (LOG_WARN|LOG_ERRNO, "cannot open %s", fname);
83         return ;
84     }
85     if (!f->length)
86     {
87         if ((f->length = lseek (fd, 0L, SEEK_END)) == (off_t) -1)
88         {
89             logf (LOG_WARN|LOG_ERRNO, "cannot seek %s", fname);
90             close (fd);
91             return ;
92         }
93     }
94     if (lseek (fd, f->offset, SEEK_SET) == -1)
95     {
96         logf (LOG_WARN|LOG_ERRNO, "cannot seek %s", fname);
97         close(fd);
98         return ;
99     }
100     while (f->chunk - nr > 0)
101     {
102         r = read (fd, f->buf + nr, f->chunk - nr);
103         if (r <= 0)
104             break;
105         nr += r;
106     }
107     if (r == -1)
108     {
109         logf (LOG_WARN|LOG_ERRNO, "read of %s", fname);
110         close (fd);
111         return;
112     }
113     f->buf_size = nr;
114     if (f->readHandler)
115         (*f->readHandler)(f, f->readInfo);
116     close (fd);
117 }
118
119 void key_file_destroy (struct key_file *f)
120 {
121     xfree (f->buf);
122     xfree (f->prev_name);
123     xfree (f);
124 }
125
126 struct key_file *key_file_init (int no, int chunk, Res res)
127 {
128     struct key_file *f;
129
130     f = (struct key_file *) xmalloc (sizeof(*f));
131     f->res = res;
132     f->sysno = 0;
133     f->seqno = 0;
134     f->no = no;
135     f->chunk = chunk;
136     f->offset = 0;
137     f->length = 0;
138     f->readHandler = NULL;
139     f->buf = (unsigned char *) xmalloc (f->chunk);
140     f->prev_name = (char *) xmalloc (INP_NAME_MAX);
141     *f->prev_name = '\0';
142     key_file_chunk_read (f);
143     return f;
144 }
145
146 int key_file_getc (struct key_file *f)
147 {
148     if (f->buf_ptr < f->buf_size)
149         return f->buf[(f->buf_ptr)++];
150     if (f->buf_size < f->chunk)
151         return EOF;
152     f->offset += f->buf_size;
153     key_file_chunk_read (f);
154     if (f->buf_ptr < f->buf_size)
155         return f->buf[(f->buf_ptr)++];
156     else
157         return EOF;
158 }
159
160 int key_file_decode (struct key_file *f)
161 {
162     int c, d;
163
164     c = key_file_getc (f);
165     switch (c & 192) 
166     {
167     case 0:
168         d = c;
169         break;
170     case 64:
171         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
172         break;
173     case 128:
174         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
175         d = (d << 8) + (key_file_getc (f) & 0xff);
176         break;
177     case 192:
178         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
179         d = (d << 8) + (key_file_getc (f) & 0xff);
180         d = (d << 8) + (key_file_getc (f) & 0xff);
181         break;
182     }
183     return d;
184 }
185
186 int key_file_read (struct key_file *f, char *key)
187 {
188     int i, d, c;
189     struct it_key itkey;
190
191     c = key_file_getc (f);
192     if (c == 0)
193     {
194         strcpy (key, f->prev_name);
195         i = 1+strlen (key);
196     }
197     else if (c == EOF)
198         return 0;
199     else
200     {
201         i = 0;
202         key[i++] = c;
203         while ((key[i++] = key_file_getc (f)))
204             ;
205         strcpy (f->prev_name, key);
206         f->sysno = 0;
207     }
208     d = key_file_decode (f);
209     key[i++] = d & 1;
210     d = d >> 1;
211     itkey.sysno = d + f->sysno;
212     if (d) 
213     {
214         f->sysno = itkey.sysno;
215         f->seqno = 0;
216     }
217     d = key_file_decode (f);
218     itkey.seqno = d + f->seqno;
219     f->seqno = itkey.seqno;
220     memcpy (key + i, &itkey, sizeof(struct it_key));
221     return i + sizeof (struct it_key);
222 }
223
224 struct heap_info {
225     struct {
226         struct key_file **file;
227         char   **buf;
228     } info;
229     int    heapnum;
230     int    *ptr;
231     int    (*cmp)(const void *p1, const void *p2);
232     Dict dict;
233     ISAMS isams;
234     ISAM isam;
235     ISAMC isamc;
236     ISAMD isamd;
237 };
238
239 struct heap_info *key_heap_init (int nkeys,
240                                  int (*cmp)(const void *p1, const void *p2))
241 {
242     struct heap_info *hi;
243     int i;
244
245     hi = (struct heap_info *) xmalloc (sizeof(*hi));
246     hi->info.file = (struct key_file **)
247         xmalloc (sizeof(*hi->info.file) * (1+nkeys));
248     hi->info.buf = (char **) xmalloc (sizeof(*hi->info.buf) * (1+nkeys));
249     hi->heapnum = 0;
250     hi->ptr = (int *) xmalloc (sizeof(*hi->ptr) * (1+nkeys));
251     hi->cmp = cmp;
252     for (i = 0; i<= nkeys; i++)
253     {
254         hi->ptr[i] = i;
255         hi->info.buf[i] = (char *) xmalloc (INP_NAME_MAX);
256     }
257     return hi;
258 }
259
260 void key_heap_destroy (struct heap_info *hi, int nkeys)
261 {
262     int i;
263     yaz_log (LOG_LOG, "key_heap_destroy");
264     for (i = 0; i<=nkeys; i++)
265         xfree (hi->info.buf[i]);
266     
267     xfree (hi->info.buf);
268     xfree (hi->ptr);
269     xfree (hi->info.file);
270     xfree (hi);
271 }
272
273 static void key_heap_swap (struct heap_info *hi, int i1, int i2)
274 {
275     int swap;
276
277     swap = hi->ptr[i1];
278     hi->ptr[i1] = hi->ptr[i2];
279     hi->ptr[i2] = swap;
280 }
281
282
283 static void key_heap_delete (struct heap_info *hi)
284 {
285     int cur = 1, child = 2;
286
287     assert (hi->heapnum > 0);
288
289     key_heap_swap (hi, 1, hi->heapnum);
290     hi->heapnum--;
291     while (child <= hi->heapnum) {
292         if (child < hi->heapnum &&
293             (*hi->cmp)(&hi->info.buf[hi->ptr[child]],
294                        &hi->info.buf[hi->ptr[child+1]]) > 0)
295             child++;
296         if ((*hi->cmp)(&hi->info.buf[hi->ptr[cur]],
297                        &hi->info.buf[hi->ptr[child]]) > 0)
298         {            
299             key_heap_swap (hi, cur, child);
300             cur = child;
301             child = 2*cur;
302         }
303         else
304             break;
305     }
306 }
307
308 static void key_heap_insert (struct heap_info *hi, const char *buf, int nbytes,
309                              struct key_file *kf)
310 {
311     int cur, parent;
312
313     cur = ++(hi->heapnum);
314     memcpy (hi->info.buf[hi->ptr[cur]], buf, nbytes);
315     hi->info.file[hi->ptr[cur]] = kf;
316
317     parent = cur/2;
318     while (parent && (*hi->cmp)(&hi->info.buf[hi->ptr[parent]],
319                                 &hi->info.buf[hi->ptr[cur]]) > 0)
320     {
321         key_heap_swap (hi, cur, parent);
322         cur = parent;
323         parent = cur/2;
324     }
325 }
326
327 static int heap_read_one (struct heap_info *hi, char *name, char *key)
328 {
329     int n, r;
330     char rbuf[INP_NAME_MAX];
331     struct key_file *kf;
332
333     if (!hi->heapnum)
334         return 0;
335     n = hi->ptr[1];
336     strcpy (name, hi->info.buf[n]);
337     kf = hi->info.file[n];
338     r = strlen(name);
339     memcpy (key, hi->info.buf[n] + r+1, KEY_SIZE);
340     key_heap_delete (hi);
341     if ((r = key_file_read (kf, rbuf)))
342         key_heap_insert (hi, rbuf, r, kf);
343     no_iterations++;
344     return 1;
345 }
346
347 struct heap_cread_info {
348     char prev_name[INP_NAME_MAX];
349     char cur_name[INP_NAME_MAX];
350     char *key;
351     struct heap_info *hi;
352     int mode;
353     int more;
354 };
355       
356 int heap_cread_item (void *vp, char **dst, int *insertMode)
357 {
358     struct heap_cread_info *p = (struct heap_cread_info *) vp;
359     struct heap_info *hi = p->hi;
360
361     if (p->mode == 1)
362     {
363         *insertMode = p->key[0];
364         memcpy (*dst, p->key+1, sizeof(struct it_key));
365         (*dst) += sizeof(struct it_key);
366         p->mode = 2;
367         return 1;
368     }
369     strcpy (p->prev_name, p->cur_name);
370     if (!(p->more = heap_read_one (hi, p->cur_name, p->key)))
371         return 0;
372     if (*p->cur_name && strcmp (p->cur_name, p->prev_name))
373     {
374         p->mode = 1;
375         return 0;
376     }
377     *insertMode = p->key[0];
378     memcpy (*dst, p->key+1, sizeof(struct it_key));
379     (*dst) += sizeof(struct it_key);
380     return 1;
381 }
382
383 int heap_inpc (struct heap_info *hi)
384 {
385     struct heap_cread_info hci;
386     ISAMC_I isamc_i = (ISAMC_I) xmalloc (sizeof(*isamc_i));
387
388     hci.key = (char *) xmalloc (KEY_SIZE);
389     hci.mode = 1;
390     hci.hi = hi;
391     hci.more = heap_read_one (hi, hci.cur_name, hci.key);
392
393     isamc_i->clientData = &hci;
394     isamc_i->read_item = heap_cread_item;
395
396     while (hci.more)
397     {
398         char this_name[INP_NAME_MAX];
399         ISAMC_P isamc_p, isamc_p2;
400         char *dict_info;
401
402         strcpy (this_name, hci.cur_name);
403         assert (hci.cur_name[1]);
404         no_diffs++;
405         if ((dict_info = dict_lookup (hi->dict, hci.cur_name)))
406         {
407             memcpy (&isamc_p, dict_info+1, sizeof(ISAMC_P));
408             isamc_p2 = isc_merge (hi->isamc, isamc_p, isamc_i);
409             if (!isamc_p2)
410             {
411                 no_deletions++;
412                 if (!dict_delete (hi->dict, this_name))
413                     abort();
414             }
415             else 
416             {
417                 no_updates++;
418                 if (isamc_p2 != isamc_p)
419                     dict_insert (hi->dict, this_name,
420                                  sizeof(ISAMC_P), &isamc_p2);
421             }
422         } 
423         else
424         {
425             isamc_p = isc_merge (hi->isamc, 0, isamc_i);
426             no_insertions++;
427             dict_insert (hi->dict, this_name, sizeof(ISAMC_P), &isamc_p);
428         }
429     }
430     xfree (isamc_i);
431     xfree (hci.key);
432     return 0;
433
434
435 int heap_inpd (struct heap_info *hi)
436 {
437     struct heap_cread_info hci;
438     ISAMD_I isamd_i = (ISAMD_I) xmalloc (sizeof(*isamd_i));
439
440     hci.key = (char *) xmalloc (KEY_SIZE);
441     hci.mode = 1;
442     hci.hi = hi;
443     hci.more = heap_read_one (hi, hci.cur_name, hci.key);
444
445     isamd_i->clientData = &hci;
446     isamd_i->read_item = heap_cread_item;
447
448     while (hci.more)
449     {
450         char this_name[INP_NAME_MAX];
451         ISAMD_P isamd_p, isamd_p2;
452         char *dict_info;
453
454         strcpy (this_name, hci.cur_name);
455         assert (hci.cur_name[1]);
456         no_diffs++;
457         if ((dict_info = dict_lookup (hi->dict, hci.cur_name)))
458         {
459             memcpy (&isamd_p, dict_info+1, sizeof(ISAMD_P));
460             isamd_p2 = isamd_append (hi->isamd, isamd_p, isamd_i);
461             if (!isamd_p2)
462             {
463                 no_deletions++;
464                 if (!dict_delete (hi->dict, this_name))
465                     abort();
466             }
467             else 
468             {
469                 no_updates++;
470                 if (isamd_p2 != isamd_p)
471                     dict_insert (hi->dict, this_name,
472                                  sizeof(ISAMD_P), &isamd_p2);
473             }
474         } 
475         else
476         {
477             isamd_p = isamd_append (hi->isamd, 0, isamd_i);
478             no_insertions++;
479             dict_insert (hi->dict, this_name, sizeof(ISAMD_P), &isamd_p);
480         }
481     }
482     xfree (isamd_i);
483     return 0;
484
485
486 int heap_inp (struct heap_info *hi)
487 {
488     char *info;
489     char next_name[INP_NAME_MAX];
490     char cur_name[INP_NAME_MAX];
491     int key_buf_size = INP_BUF_START;
492     int key_buf_ptr;
493     char *next_key;
494     char *key_buf;
495     int more;
496     
497     next_key = (char *) xmalloc (KEY_SIZE);
498     key_buf = (char *) xmalloc (key_buf_size);
499     more = heap_read_one (hi, cur_name, key_buf);
500     while (more)                   /* EOF ? */
501     {
502         int nmemb;
503         key_buf_ptr = KEY_SIZE;
504         while (1)
505         {
506             if (!(more = heap_read_one (hi, next_name, next_key)))
507                 break;
508             if (*next_name && strcmp (next_name, cur_name))
509                 break;
510             memcpy (key_buf + key_buf_ptr, next_key, KEY_SIZE);
511             key_buf_ptr += KEY_SIZE;
512             if (key_buf_ptr+(int) KEY_SIZE >= key_buf_size)
513             {
514                 char *new_key_buf;
515                 new_key_buf = (char *) xmalloc (key_buf_size + INP_BUF_ADD);
516                 memcpy (new_key_buf, key_buf, key_buf_size);
517                 key_buf_size += INP_BUF_ADD;
518                 xfree (key_buf);
519                 key_buf = new_key_buf;
520             }
521         }
522         no_diffs++;
523         nmemb = key_buf_ptr / KEY_SIZE;
524         assert (nmemb * (int) KEY_SIZE == key_buf_ptr);
525         if ((info = dict_lookup (hi->dict, cur_name)))
526         {
527             ISAM_P isam_p, isam_p2;
528             memcpy (&isam_p, info+1, sizeof(ISAM_P));
529             isam_p2 = is_merge (hi->isam, isam_p, nmemb, key_buf);
530             if (!isam_p2)
531             {
532                 no_deletions++;
533                 if (!dict_delete (hi->dict, cur_name))
534                     abort ();
535             }
536             else 
537             {
538                 no_updates++;
539                 if (isam_p2 != isam_p)
540                     dict_insert (hi->dict, cur_name, sizeof(ISAM_P), &isam_p2);
541             }
542         }
543         else
544         {
545             ISAM_P isam_p;
546             no_insertions++;
547             isam_p = is_merge (hi->isam, 0, nmemb, key_buf);
548             dict_insert (hi->dict, cur_name, sizeof(ISAM_P), &isam_p);
549         }
550         memcpy (key_buf, next_key, KEY_SIZE);
551         strcpy (cur_name, next_name);
552     }
553     return 0;
554 }
555
556 int heap_inps (struct heap_info *hi)
557 {
558     struct heap_cread_info hci;
559     ISAMS_I isams_i = (ISAMS_I) xmalloc (sizeof(*isams_i));
560
561     hci.key = (char *) xmalloc (KEY_SIZE);
562     hci.mode = 1;
563     hci.hi = hi;
564     hci.more = heap_read_one (hi, hci.cur_name, hci.key);
565
566     isams_i->clientData = &hci;
567     isams_i->read_item = heap_cread_item;
568
569     while (hci.more)
570     {
571         char this_name[INP_NAME_MAX];
572         ISAMS_P isams_p;
573         char *dict_info;
574
575         strcpy (this_name, hci.cur_name);
576         assert (hci.cur_name[1]);
577         no_diffs++;
578         if (!(dict_info = dict_lookup (hi->dict, hci.cur_name)))
579         {
580             isams_p = isams_merge (hi->isams, isams_i);
581             no_insertions++;
582             dict_insert (hi->dict, this_name, sizeof(ISAMS_P), &isams_p);
583         }
584         else
585         {
586             logf (LOG_FATAL, "isams doesn't support this kind of update");
587             break;
588         }
589     }
590     xfree (isams_i);
591     return 0;
592
593
594 struct progressInfo {
595     time_t   startTime;
596     time_t   lastTime;
597     off_t    totalBytes;
598     off_t    totalOffset;
599 };
600
601 void progressFunc (struct key_file *keyp, void *info)
602 {
603     struct progressInfo *p = (struct progressInfo *) info;
604     time_t now, remaining;
605
606     if (keyp->buf_size <= 0 || p->totalBytes <= 0)
607         return ;
608     time (&now);
609
610     if (now >= p->lastTime+10)
611     {
612         p->lastTime = now;
613         remaining = (time_t) ((now - p->startTime)*
614             ((double) p->totalBytes/p->totalOffset - 1.0));
615         if (remaining <= 130)
616             logf (LOG_LOG, "Merge %2.1f%% completed; %ld seconds remaining",
617                  (100.0*p->totalOffset) / p->totalBytes, (long) remaining);
618         else
619             logf (LOG_LOG, "Merge %2.1f%% completed; %ld minutes remaining",
620                  (100.0*p->totalOffset) / p->totalBytes, (long) remaining/60);
621     }
622     p->totalOffset += keyp->buf_size;
623 }
624
625 #ifndef R_OK
626 #define R_OK 4
627 #endif
628
629 void zebra_index_merge (ZebraHandle zh)
630 {
631     struct key_file **kf;
632     char rbuf[1024];
633     int i, r;
634     struct heap_info *hi;
635     struct progressInfo progressInfo;
636     int nkeys = zh->reg->key_file_no;
637     
638     if (nkeys < 0)
639     {
640         char fname[1024];
641         nkeys = 0;
642         while (1)
643         {
644             extract_get_fname_tmp  (zh, fname, nkeys+1);
645             if (access (fname, R_OK) == -1)
646                 break;
647             nkeys++;
648         }
649         if (!nkeys)
650             return ;
651     }
652     kf = (struct key_file **) xmalloc ((1+nkeys) * sizeof(*kf));
653     progressInfo.totalBytes = 0;
654     progressInfo.totalOffset = 0;
655     time (&progressInfo.startTime);
656     time (&progressInfo.lastTime);
657     for (i = 1; i<=nkeys; i++)
658     {
659         kf[i] = key_file_init (i, 8192, zh->res);
660         kf[i]->readHandler = progressFunc;
661         kf[i]->readInfo = &progressInfo;
662         progressInfo.totalBytes += kf[i]->length;
663         progressInfo.totalOffset += kf[i]->buf_size;
664     }
665     hi = key_heap_init (nkeys, key_qsort_compare);
666     hi->dict = zh->reg->dict;
667     hi->isams = zh->reg->isams;
668     hi->isam = zh->reg->isam;
669     hi->isamc = zh->reg->isamc;
670     hi->isamd = zh->reg->isamd;
671     
672     for (i = 1; i<=nkeys; i++)
673         if ((r = key_file_read (kf[i], rbuf)))
674             key_heap_insert (hi, rbuf, r, kf[i]);
675     if (zh->reg->isams)
676         heap_inps (hi);
677     else if (zh->reg->isamc)
678         heap_inpc (hi);
679     else if (zh->reg->isam)
680         heap_inp (hi);
681     else if (zh->reg->isamd)
682         heap_inpd (hi);
683         
684     for (i = 1; i<=nkeys; i++)
685     {
686         extract_get_fname_tmp  (zh, rbuf, i);
687         unlink (rbuf);
688     }
689     logf (LOG_LOG, "Iterations . . .%7d", no_iterations);
690     logf (LOG_LOG, "Distinct words .%7d", no_diffs);
691     logf (LOG_LOG, "Updates. . . . .%7d", no_updates);
692     logf (LOG_LOG, "Deletions. . . .%7d", no_deletions);
693     logf (LOG_LOG, "Insertions . . .%7d", no_insertions);
694     zh->reg->key_file_no = 0;
695
696     key_heap_destroy (hi, nkeys);
697     for (i = 1; i<=nkeys; i++)
698         key_file_destroy (kf[i]);
699     xfree (kf);
700 }
701
702