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