781ec9a80112479667999ba08d0e5690fb1e1c76
[idzebra-moved-to-github.git] / index / kinput.c
1 /*
2  * Copyright (C) 1994-1998, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: kinput.c,v $
7  * Revision 1.27  1998-02-17 10:32:52  adam
8  * Fixed bug: binary files weren't opened with flag b on NT.
9  *
10  * Revision 1.26  1998/01/29 13:39:13  adam
11  * Compress ISAM is default.
12  *
13  * Revision 1.25  1997/09/17 12:19:14  adam
14  * Zebra version corresponds to YAZ version 1.4.
15  * Changed Zebra server so that it doesn't depend on global common_resource.
16  *
17  * Revision 1.24  1997/09/09 13:38:07  adam
18  * Partial port to WIN95/NT.
19  *
20  * Revision 1.23  1997/09/04 13:57:39  adam
21  * Added O_BINARY for open calls.
22  *
23  * Revision 1.22  1997/02/12 20:39:45  adam
24  * Implemented options -f <n> that limits the log to the first <n>
25  * records.
26  * Changed some log messages also.
27  *
28  * Revision 1.21  1996/11/08 11:10:23  adam
29  * Buffers used during file match got bigger.
30  * Compressed ISAM support everywhere.
31  * Bug fixes regarding masking characters in queries.
32  * Redesigned Regexp-2 queries.
33  *
34  * Revision 1.20  1996/11/01 08:58:41  adam
35  * Interface to isamc system now includes update and delete.
36  *
37  * Revision 1.19  1996/10/29 14:09:46  adam
38  * Use of cisam system - enabled if setting isamc is 1.
39  *
40  * Revision 1.18  1996/06/04 10:18:59  adam
41  * Minor changes - removed include of ctype.h.
42  *
43  * Revision 1.17  1996/05/14  15:47:07  adam
44  * Cleanup of various buffer size entities.
45  *
46  * Revision 1.16  1996/04/09  10:05:20  adam
47  * Bug fix: prev_name buffer possibly too small; allocated in key_file_init.
48  *
49  * Revision 1.15  1996/03/21  14:50:09  adam
50  * File update uses modify-time instead of change-time.
51  *
52  * Revision 1.14  1996/02/07  14:06:37  adam
53  * Better progress report during register merge.
54  * New command: clean - removes temporary shadow files.
55  *
56  * Revision 1.13  1996/02/05  12:30:00  adam
57  * Logging reduced a bit.
58  * The remaining running time is estimated during register merge.
59  *
60  * Revision 1.12  1995/12/06  17:49:19  adam
61  * Uses dict_delete now.
62  *
63  * Revision 1.11  1995/12/06  16:06:43  adam
64  * Better diagnostics. Work on 'real' dictionary deletion.
65  *
66  * Revision 1.10  1995/12/06  12:41:22  adam
67  * New command 'stat' for the index program.
68  * Filenames can be read from stdin by specifying '-'.
69  * Bug fix/enhancement of the transformation from terms to regular
70  * expressons in the search engine.
71  *
72  * Revision 1.9  1995/10/10  12:24:39  adam
73  * Temporary sort files are compressed.
74  *
75  * Revision 1.8  1995/10/04  16:57:19  adam
76  * Key input and merge sort in one pass.
77  *
78  * Revision 1.7  1995/10/02  15:18:52  adam
79  * New member in recRetrieveCtrl: diagnostic.
80  *
81  * Revision 1.6  1995/09/29  15:51:56  adam
82  * First work on multi-way read.
83  *
84  * Revision 1.5  1995/09/29  14:01:43  adam
85  * Bug fixes.
86  *
87  * Revision 1.4  1995/09/28  14:22:57  adam
88  * Sort uses smaller temporary files.
89  *
90  * Revision 1.3  1995/09/06  16:11:17  adam
91  * Option: only one word key per file.
92  *
93  * Revision 1.2  1995/09/04  12:33:42  adam
94  * Various cleanup. YAZ util used instead.
95  *
96  * Revision 1.1  1995/09/04  09:10:37  adam
97  * More work on index add/del/update.
98  * Merge sort implemented.
99  * Initial work on z39 server.
100  *
101  */
102
103 #include <fcntl.h>
104 #ifdef WINDOWS
105 #include <io.h>
106 #else
107 #include <unistd.h>
108 #endif
109 #include <stdlib.h>
110 #include <string.h>
111 #include <stdio.h>
112 #include <assert.h>
113
114 #include "index.h"
115
116 #define KEY_SIZE (1+sizeof(struct it_key))
117 #define INP_NAME_MAX 768
118 #define INP_BUF_START 60000
119 #define INP_BUF_ADD  400000
120
121 static int no_diffs   = 0;
122 static int no_updates = 0;
123 static int no_deletions = 0;
124 static int no_insertions = 0;
125 static int no_iterations = 0;
126
127 struct key_file {
128     int   no;            /* file no */
129     off_t offset;        /* file offset */
130     unsigned char *buf;  /* buffer block */
131     size_t buf_size;     /* number of read bytes in block */
132     size_t chunk;        /* number of bytes allocated */
133     size_t buf_ptr;      /* current position in buffer */
134     char *prev_name;     /* last word read */
135     int   sysno;         /* last sysno */
136     int   seqno;         /* last seqno */
137     off_t length;        /* length of file */
138                          /* handler invoked in each read */
139     void (*readHandler)(struct key_file *keyp, void *rinfo);
140     void *readInfo;
141 };
142
143 void getFnameTmp (char *fname, int no)
144 {
145     const char *pre;
146     
147     pre = res_get_def (common_resource, "keyTmpDir", ".");
148     sprintf (fname, "%s/key%d.tmp", pre, no);
149 }
150
151 void key_file_chunk_read (struct key_file *f)
152 {
153     int nr = 0, r, fd;
154     char fname[1024];
155     getFnameTmp (fname, f->no);
156     fd = open (fname, O_BINARY|O_RDONLY);
157     if (fd == -1)
158     {
159         logf (LOG_FATAL|LOG_ERRNO, "cannot open %s", fname);
160         exit (1);
161     }
162     if (!f->length)
163     {
164         if ((f->length = lseek (fd, 0L, SEEK_END)) == (off_t) -1)
165         {
166             logf (LOG_FATAL|LOG_ERRNO, "cannot seek %s", fname);
167             exit (1);
168         }
169     }
170     if (lseek (fd, f->offset, SEEK_SET) == -1)
171     {
172         logf (LOG_FATAL|LOG_ERRNO, "cannot seek %s", fname);
173         exit (1);
174     }
175     while (f->chunk - nr > 0)
176     {
177         r = read (fd, f->buf + nr, f->chunk - nr);
178         if (r <= 0)
179             break;
180         nr += r;
181     }
182     if (r == -1)
183     {
184         logf (LOG_FATAL|LOG_ERRNO, "read of %s", fname);
185         exit (1);
186     }
187     f->buf_size = nr;
188     f->buf_ptr = 0;
189     if (f->readHandler)
190         (*f->readHandler)(f, f->readInfo);
191     close (fd);
192 }
193
194 struct key_file *key_file_init (int no, int chunk)
195 {
196     struct key_file *f;
197
198     f = xmalloc (sizeof(*f));
199     f->sysno = 0;
200     f->seqno = 0;
201     f->no = no;
202     f->chunk = chunk;
203     f->offset = 0;
204     f->length = 0;
205     f->readHandler = NULL;
206     f->buf = xmalloc (f->chunk);
207     f->prev_name = xmalloc (INP_NAME_MAX);
208     *f->prev_name = '\0';
209     key_file_chunk_read (f);
210     return f;
211 }
212
213 int key_file_getc (struct key_file *f)
214 {
215     if (f->buf_ptr < f->buf_size)
216         return f->buf[(f->buf_ptr)++];
217     if (f->buf_size < f->chunk)
218         return EOF;
219     f->offset += f->buf_size;
220     key_file_chunk_read (f);
221     if (f->buf_ptr < f->buf_size)
222         return f->buf[(f->buf_ptr)++];
223     else
224         return EOF;
225 }
226
227 int key_file_decode (struct key_file *f)
228 {
229     int c, d;
230
231     c = key_file_getc (f);
232     switch (c & 192) 
233     {
234     case 0:
235         d = c;
236         break;
237     case 64:
238         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
239         break;
240     case 128:
241         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
242         d = (d << 8) + (key_file_getc (f) & 0xff);
243         break;
244     case 192:
245         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
246         d = (d << 8) + (key_file_getc (f) & 0xff);
247         d = (d << 8) + (key_file_getc (f) & 0xff);
248         break;
249     }
250     return d;
251 }
252
253 int key_file_read (struct key_file *f, char *key)
254 {
255     int i, d, c;
256     struct it_key itkey;
257
258     c = key_file_getc (f);
259     if (c == 0)
260     {
261         strcpy (key, f->prev_name);
262         i = 1+strlen (key);
263     }
264     else if (c == EOF)
265         return 0;
266     else
267     {
268         i = 0;
269         key[i++] = c;
270         while ((key[i++] = key_file_getc (f)))
271             ;
272         strcpy (f->prev_name, key);
273         f->sysno = 0;
274     }
275     d = key_file_decode (f);
276     key[i++] = d & 1;
277     d = d >> 1;
278     itkey.sysno = d + f->sysno;
279     if (d) 
280     {
281         f->sysno = itkey.sysno;
282         f->seqno = 0;
283     }
284     d = key_file_decode (f);
285     itkey.seqno = d + f->seqno;
286     f->seqno = itkey.seqno;
287     memcpy (key + i, &itkey, sizeof(struct it_key));
288     return i + sizeof (struct it_key);
289 }
290
291 struct heap_info {
292     struct {
293         struct key_file **file;
294         char   **buf;
295     } info;
296     int    heapnum;
297     int    *ptr;
298     int    (*cmp)(const void *p1, const void *p2);
299     Dict dict;
300     ISAM isam;
301     ISAMC isamc;
302 };
303
304 struct heap_info *key_heap_init (int nkeys,
305                                  int (*cmp)(const void *p1, const void *p2))
306 {
307     struct heap_info *hi;
308     int i;
309
310     hi = xmalloc (sizeof(*hi));
311     hi->info.file = xmalloc (sizeof(*hi->info.file) * (1+nkeys));
312     hi->info.buf = xmalloc (sizeof(*hi->info.buf) * (1+nkeys));
313     hi->heapnum = 0;
314     hi->ptr = xmalloc (sizeof(*hi->ptr) * (1+nkeys));
315     hi->cmp = cmp;
316     for (i = 0; i<= nkeys; i++)
317     {
318         hi->ptr[i] = i;
319         hi->info.buf[i] = xmalloc (INP_NAME_MAX);
320     }
321     return hi;
322 }
323
324 static void key_heap_swap (struct heap_info *hi, int i1, int i2)
325 {
326     int swap;
327
328     swap = hi->ptr[i1];
329     hi->ptr[i1] = hi->ptr[i2];
330     hi->ptr[i2] = swap;
331 }
332
333
334 static void key_heap_delete (struct heap_info *hi)
335 {
336     int cur = 1, child = 2;
337
338     assert (hi->heapnum > 0);
339
340     key_heap_swap (hi, 1, hi->heapnum);
341     hi->heapnum--;
342     while (child <= hi->heapnum) {
343         if (child < hi->heapnum &&
344             (*hi->cmp)(&hi->info.buf[hi->ptr[child]],
345                        &hi->info.buf[hi->ptr[child+1]]) > 0)
346             child++;
347         if ((*hi->cmp)(&hi->info.buf[hi->ptr[cur]],
348                        &hi->info.buf[hi->ptr[child]]) > 0)
349         {            
350             key_heap_swap (hi, cur, child);
351             cur = child;
352             child = 2*cur;
353         }
354         else
355             break;
356     }
357 }
358
359 static void key_heap_insert (struct heap_info *hi, const char *buf, int nbytes,
360                              struct key_file *kf)
361 {
362     int cur, parent;
363
364     cur = ++(hi->heapnum);
365     memcpy (hi->info.buf[hi->ptr[cur]], buf, nbytes);
366     hi->info.file[hi->ptr[cur]] = kf;
367
368     parent = cur/2;
369     while (parent && (*hi->cmp)(&hi->info.buf[hi->ptr[parent]],
370                                 &hi->info.buf[hi->ptr[cur]]) > 0)
371     {
372         key_heap_swap (hi, cur, parent);
373         cur = parent;
374         parent = cur/2;
375     }
376 }
377
378 static int heap_read_one (struct heap_info *hi, char *name, char *key)
379 {
380     int n, r;
381     char rbuf[INP_NAME_MAX];
382     struct key_file *kf;
383
384     if (!hi->heapnum)
385         return 0;
386     n = hi->ptr[1];
387     strcpy (name, hi->info.buf[n]);
388     kf = hi->info.file[n];
389     r = strlen(name);
390     memcpy (key, hi->info.buf[n] + r+1, KEY_SIZE);
391     key_heap_delete (hi);
392     if ((r = key_file_read (kf, rbuf)))
393         key_heap_insert (hi, rbuf, r, kf);
394     no_iterations++;
395     return 1;
396 }
397
398 struct heap_cread_info {
399     char prev_name[INP_NAME_MAX];
400     char cur_name[INP_NAME_MAX];
401     char *key;
402     struct heap_info *hi;
403     int mode;
404     int more;
405 };
406       
407 int heap_cread_item (void *vp, char **dst, int *insertMode)
408 {
409     struct heap_cread_info *p = vp;
410     struct heap_info *hi = p->hi;
411
412     if (p->mode == 1)
413     {
414         *insertMode = p->key[0];
415         memcpy (*dst, p->key+1, sizeof(struct it_key));
416         (*dst) += sizeof(struct it_key);
417         p->mode = 2;
418         return 1;
419     }
420     strcpy (p->prev_name, p->cur_name);
421     if (!(p->more = heap_read_one (hi, p->cur_name, p->key)))
422         return 0;
423     if (*p->cur_name && strcmp (p->cur_name, p->prev_name))
424     {
425         p->mode = 1;
426         return 0;
427     }
428     *insertMode = p->key[0];
429     memcpy (*dst, p->key+1, sizeof(struct it_key));
430     (*dst) += sizeof(struct it_key);
431     return 1;
432 }
433
434 int heap_inpc (struct heap_info *hi)
435 {
436     struct heap_cread_info hci;
437     ISAMC_I isamc_i = xmalloc (sizeof(*isamc_i));
438
439     hci.key = xmalloc (KEY_SIZE);
440     hci.mode = 1;
441     hci.hi = hi;
442     hci.more = heap_read_one (hi, hci.cur_name, hci.key);
443
444     isamc_i->clientData = &hci;
445     isamc_i->read_item = heap_cread_item;
446
447     while (hci.more)
448     {
449         char this_name[INP_NAME_MAX];
450         ISAMC_P isamc_p, isamc_p2;
451         char *dict_info;
452
453         strcpy (this_name, hci.cur_name);
454         logf (LOG_DEBUG, "inserting %s", 1+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 (&isamc_p, dict_info+1, sizeof(ISAMC_P));
460             isamc_p2 = isc_merge (hi->isamc, isamc_p, isamc_i);
461             if (!isamc_p2)
462             {
463                 no_deletions++;
464                 if (!dict_delete (hi->dict, this_name))
465                     abort();
466             }
467             else 
468             {
469                 no_updates++;
470                 if (isamc_p2 != isamc_p)
471                     dict_insert (hi->dict, this_name,
472                                  sizeof(ISAMC_P), &isamc_p2);
473             }
474         } 
475         else
476         {
477             isamc_p = isc_merge (hi->isamc, 0, isamc_i);
478             no_insertions++;
479             dict_insert (hi->dict, this_name, sizeof(ISAMC_P), &isamc_p);
480         }
481     }
482     xfree (isamc_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 = xmalloc (KEY_SIZE);
498     key_buf = 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+KEY_SIZE >= key_buf_size)
513             {
514                 char *new_key_buf;
515                 new_key_buf = 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*KEY_SIZE == key_buf_ptr);
525         if ((info = dict_lookup (hi->dict, cur_name)))
526         {
527             ISAM_P isam_p, isam_p2;
528             logf (LOG_DEBUG, "updating %s", 1+cur_name);
529             memcpy (&isam_p, info+1, sizeof(ISAM_P));
530             isam_p2 = is_merge (hi->isam, isam_p, nmemb, key_buf);
531             if (!isam_p2)
532             {
533                 no_deletions++;
534                 if (!dict_delete (hi->dict, cur_name))
535                     abort ();
536             }
537             else 
538             {
539                 no_updates++;
540                 if (isam_p2 != isam_p)
541                     dict_insert (hi->dict, cur_name, sizeof(ISAM_P), &isam_p2);
542             }
543         }
544         else
545         {
546             ISAM_P isam_p;
547             logf (LOG_DEBUG, "inserting %s", 1+cur_name);
548             no_insertions++;
549             isam_p = is_merge (hi->isam, 0, nmemb, key_buf);
550             dict_insert (hi->dict, cur_name, sizeof(ISAM_P), &isam_p);
551         }
552         memcpy (key_buf, next_key, KEY_SIZE);
553         strcpy (cur_name, next_name);
554     }
555     return 0;
556 }
557
558 struct progressInfo {
559     time_t   startTime;
560     time_t   lastTime;
561     off_t    totalBytes;
562     off_t    totalOffset;
563 };
564
565 void progressFunc (struct key_file *keyp, void *info)
566 {
567     struct progressInfo *p = info;
568     time_t now, remaining;
569
570     if (keyp->buf_size <= 0 || p->totalBytes <= 0)
571         return ;
572     time (&now);
573
574     if (now >= p->lastTime+10)
575     {
576         p->lastTime = now;
577         remaining = (now - p->startTime)*
578             ((double) p->totalBytes/p->totalOffset - 1.0);
579         if (remaining <= 130)
580             logf (LOG_LOG, "Merge %2.1f%% completed; %ld seconds remaining",
581                  (100.0*p->totalOffset) / p->totalBytes, (long) remaining);
582         else
583             logf (LOG_LOG, "Merge %2.1f%% completed; %ld minutes remaining",
584                  (100.0*p->totalOffset) / p->totalBytes, (long) remaining/60);
585     }
586     p->totalOffset += keyp->buf_size;
587 }
588
589 #ifndef R_OK
590 #define R_OK 4
591 #endif
592
593 void key_input (BFiles bfs, int nkeys, int cache)
594                 
595 {
596     Dict dict;
597     ISAM isam = NULL;
598     ISAMC isamc = NULL;
599     struct key_file **kf;
600     char rbuf[1024];
601     int i, r;
602     struct heap_info *hi;
603     struct progressInfo progressInfo;
604
605     if (nkeys < 0)
606     {
607         char fname[1024];
608         nkeys = 0;
609         while (1)
610         {
611             getFnameTmp (fname, nkeys+1);
612             if (access (fname, R_OK) == -1)
613                 break;
614             nkeys++;
615         }
616         if (!nkeys)
617             return ;
618     }
619     dict = dict_open (bfs, FNAME_DICT, cache, 1);
620     if (!dict)
621     {
622         logf (LOG_FATAL, "dict_open fail");
623         exit (1);
624     }
625     if (!res_get_match (common_resource, "isam", "i", NULL))
626     {
627         isamc = isc_open (bfs,
628                           FNAME_ISAMC, 1, key_isamc_m (common_resource));
629         if (!isamc)
630         {
631             logf (LOG_FATAL, "isc_open fail");
632             exit (1);
633         }
634     }
635     else
636     {
637         isam = is_open (bfs, FNAME_ISAM, key_compare, 1,
638                         sizeof(struct it_key), common_resource);
639         if (!isam)
640         {
641             logf (LOG_FATAL, "is_open fail");
642             exit (1);
643         }
644     }
645     kf = xmalloc ((1+nkeys) * sizeof(*kf));
646     progressInfo.totalBytes = 0;
647     progressInfo.totalOffset = 0;
648     time (&progressInfo.startTime);
649     time (&progressInfo.lastTime);
650     for (i = 1; i<=nkeys; i++)
651     {
652         kf[i] = key_file_init (i, 32768);
653         kf[i]->readHandler = progressFunc;
654         kf[i]->readInfo = &progressInfo;
655         progressInfo.totalBytes += kf[i]->length;
656         progressInfo.totalOffset += kf[i]->buf_size;
657     }
658     hi = key_heap_init (nkeys, key_qsort_compare);
659     hi->dict = dict;
660     hi->isam = isam;
661     hi->isamc = isamc;
662
663     for (i = 1; i<=nkeys; i++)
664         if ((r = key_file_read (kf[i], rbuf)))
665             key_heap_insert (hi, rbuf, r, kf[i]);
666     if (isamc)
667         heap_inpc (hi);
668     else
669         heap_inp (hi);
670     dict_close (dict);
671     if (isam)
672         is_close (isam);
673     if (isamc)
674         isc_close (isamc);
675    
676     for (i = 1; i<=nkeys; i++)
677     {
678         getFnameTmp (rbuf, i);
679         unlink (rbuf);
680     }
681     logf (LOG_LOG, "Iterations . . .%7d", no_iterations);
682     logf (LOG_LOG, "Distinct words .%7d", no_diffs);
683     logf (LOG_LOG, "Updates. . . . .%7d", no_updates);
684     logf (LOG_LOG, "Deletions. . . .%7d", no_deletions);
685     logf (LOG_LOG, "Insertions . . .%7d", no_insertions);
686 }
687
688