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