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