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