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