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