Bug fix: prev_name buffer possibly too small; allocated in key_file_init.
[idzebra-moved-to-github.git] / index / kinput.c
1 /*
2  * Copyright (C) 1994-1995, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: kinput.c,v $
7  * Revision 1.16  1996-04-09 10:05:20  adam
8  * Bug fix: prev_name buffer possibly too small; allocated in key_file_init.
9  *
10  * Revision 1.15  1996/03/21  14:50:09  adam
11  * File update uses modify-time instead of change-time.
12  *
13  * Revision 1.14  1996/02/07  14:06:37  adam
14  * Better progress report during register merge.
15  * New command: clean - removes temporary shadow files.
16  *
17  * Revision 1.13  1996/02/05  12:30:00  adam
18  * Logging reduced a bit.
19  * The remaining running time is estimated during register merge.
20  *
21  * Revision 1.12  1995/12/06  17:49:19  adam
22  * Uses dict_delete now.
23  *
24  * Revision 1.11  1995/12/06  16:06:43  adam
25  * Better diagnostics. Work on 'real' dictionary deletion.
26  *
27  * Revision 1.10  1995/12/06  12:41:22  adam
28  * New command 'stat' for the index program.
29  * Filenames can be read from stdin by specifying '-'.
30  * Bug fix/enhancement of the transformation from terms to regular
31  * expressons in the search engine.
32  *
33  * Revision 1.9  1995/10/10  12:24:39  adam
34  * Temporary sort files are compressed.
35  *
36  * Revision 1.8  1995/10/04  16:57:19  adam
37  * Key input and merge sort in one pass.
38  *
39  * Revision 1.7  1995/10/02  15:18:52  adam
40  * New member in recRetrieveCtrl: diagnostic.
41  *
42  * Revision 1.6  1995/09/29  15:51:56  adam
43  * First work on multi-way read.
44  *
45  * Revision 1.5  1995/09/29  14:01:43  adam
46  * Bug fixes.
47  *
48  * Revision 1.4  1995/09/28  14:22:57  adam
49  * Sort uses smaller temporary files.
50  *
51  * Revision 1.3  1995/09/06  16:11:17  adam
52  * Option: only one word key per file.
53  *
54  * Revision 1.2  1995/09/04  12:33:42  adam
55  * Various cleanup. YAZ util used instead.
56  *
57  * Revision 1.1  1995/09/04  09:10:37  adam
58  * More work on index add/del/update.
59  * Merge sort implemented.
60  * Initial work on z39 server.
61  *
62  */
63
64 #include <fcntl.h>
65 #include <unistd.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <stdio.h>
69 #include <ctype.h>
70 #include <assert.h>
71
72 #include "index.h"
73
74 #define KEY_SIZE (1+sizeof(struct it_key))
75 #define INP_NAME_MAX 8192
76 #define INP_BUF_START 60000
77 #define INP_BUF_ADD  400000
78
79 static int no_diffs   = 0;
80 static int no_updates = 0;
81 static int no_deletions = 0;
82 static int no_insertions = 0;
83 static int no_iterations = 0;
84
85 struct key_file {
86     int   no;            /* file no */
87     off_t offset;        /* file offset */
88     unsigned char *buf;  /* buffer block */
89     size_t buf_size;     /* number of read bytes in block */
90     size_t chunk;        /* number of bytes allocated */
91     size_t buf_ptr;      /* current position in buffer */
92     char *prev_name;     /* last word read */
93     int   sysno;         /* last sysno */
94     int   seqno;         /* last seqno */
95     off_t length;        /* length of file */
96                          /* handler invoked in each read */
97     void (*readHandler)(struct key_file *keyp, void *rinfo);
98     void *readInfo;
99 };
100
101 void getFnameTmp (char *fname, int no)
102 {
103     sprintf (fname, TEMP_FNAME, no);
104 }
105
106 void key_file_chunk_read (struct key_file *f)
107 {
108     int nr = 0, r, fd;
109     char fname[1024];
110     getFnameTmp (fname, f->no);
111     fd = open (fname, O_RDONLY);
112     if (fd == -1)
113     {
114         logf (LOG_FATAL|LOG_ERRNO, "cannot open %s", fname);
115         exit (1);
116     }
117     if (!f->length)
118     {
119         if ((f->length = lseek (fd, 0L, SEEK_END)) == (off_t) -1)
120         {
121             logf (LOG_FATAL|LOG_ERRNO, "cannot seek %s", fname);
122             exit (1);
123         }
124     }
125     if (lseek (fd, f->offset, SEEK_SET) == -1)
126     {
127         logf (LOG_FATAL|LOG_ERRNO, "cannot seek %s", fname);
128         exit (1);
129     }
130     while (f->chunk - nr > 0)
131     {
132         r = read (fd, f->buf + nr, f->chunk - nr);
133         if (r <= 0)
134             break;
135         nr += r;
136     }
137     if (r == -1)
138     {
139         logf (LOG_FATAL|LOG_ERRNO, "read of %s", fname);
140         exit (1);
141     }
142     f->buf_size = nr;
143     f->buf_ptr = 0;
144     if (f->readHandler)
145         (*f->readHandler)(f, f->readInfo);
146     close (fd);
147 }
148
149 struct key_file *key_file_init (int no, int chunk)
150 {
151     struct key_file *f;
152
153     f = xmalloc (sizeof(*f));
154     f->sysno = 0;
155     f->seqno = 0;
156     f->no = no;
157     f->chunk = chunk;
158     f->offset = 0;
159     f->length = 0;
160     f->readHandler = NULL;
161     f->buf = xmalloc (f->chunk);
162     f->prev_name = xmalloc (512);
163     *f->prev_name = '\0';
164     key_file_chunk_read (f);
165     return f;
166 }
167
168 int key_file_getc (struct key_file *f)
169 {
170     if (f->buf_ptr < f->buf_size)
171         return f->buf[(f->buf_ptr)++];
172     if (f->buf_size < f->chunk)
173         return EOF;
174     f->offset += f->buf_size;
175     key_file_chunk_read (f);
176     if (f->buf_ptr < f->buf_size)
177         return f->buf[(f->buf_ptr)++];
178     else
179         return EOF;
180 }
181
182 int key_file_decode (struct key_file *f)
183 {
184     int c, d;
185
186     c = key_file_getc (f);
187     switch (c & 192) 
188     {
189     case 0:
190         d = c;
191         break;
192     case 64:
193         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
194         break;
195     case 128:
196         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
197         d = (d << 8) + (key_file_getc (f) & 0xff);
198         break;
199     case 192:
200         d = ((c&63) << 8) + (key_file_getc (f) & 0xff);
201         d = (d << 8) + (key_file_getc (f) & 0xff);
202         d = (d << 8) + (key_file_getc (f) & 0xff);
203         break;
204     }
205     return d;
206 }
207
208 int key_file_read (struct key_file *f, char *key)
209 {
210     int i, d, c;
211     struct it_key itkey;
212
213     c = key_file_getc (f);
214     if (c == 0)
215     {
216         strcpy (key, f->prev_name);
217         i = 1+strlen (key);
218     }
219     else if (c == EOF)
220         return 0;
221     else
222     {
223         i = 0;
224         key[i++] = c;
225         while ((key[i++] = key_file_getc (f)))
226             ;
227         strcpy (f->prev_name, key);
228         f->sysno = 0;
229     }
230     d = key_file_decode (f);
231     key[i++] = d & 1;
232     d = d >> 1;
233     itkey.sysno = d + f->sysno;
234     if (d) 
235     {
236         f->sysno = itkey.sysno;
237         f->seqno = 0;
238     }
239     d = key_file_decode (f);
240     itkey.seqno = d + f->seqno;
241     f->seqno = itkey.seqno;
242     memcpy (key + i, &itkey, sizeof(struct it_key));
243     return i + sizeof (struct it_key);
244 }
245
246 struct heap_info {
247     struct {
248         struct key_file **file;
249         char   **buf;
250     } info;
251     int    heapnum;
252     int    *ptr;
253     int    (*cmp)(const void *p1, const void *p2);
254 };
255
256 struct heap_info *key_heap_init (int nkeys,
257                                  int (*cmp)(const void *p1, const void *p2))
258 {
259     struct heap_info *hi;
260     int i;
261
262     hi = xmalloc (sizeof(*hi));
263     hi->info.file = xmalloc (sizeof(*hi->info.file) * (1+nkeys));
264     hi->info.buf = xmalloc (sizeof(*hi->info.buf) * (1+nkeys));
265     hi->heapnum = 0;
266     hi->ptr = xmalloc (sizeof(*hi->ptr) * (1+nkeys));
267     hi->cmp = cmp;
268     for (i = 0; i<= nkeys; i++)
269     {
270         hi->ptr[i] = i;
271         hi->info.buf[i] = xmalloc (768);
272     }
273     return hi;
274 }
275
276 static void key_heap_swap (struct heap_info *hi, int i1, int i2)
277 {
278     int swap;
279
280     swap = hi->ptr[i1];
281     hi->ptr[i1] = hi->ptr[i2];
282     hi->ptr[i2] = swap;
283 }
284
285
286 static void key_heap_delete (struct heap_info *hi)
287 {
288     int cur = 1, child = 2;
289
290     assert (hi->heapnum > 0);
291
292     key_heap_swap (hi, 1, hi->heapnum);
293     hi->heapnum--;
294     while (child <= hi->heapnum) {
295         if (child < hi->heapnum &&
296             (*hi->cmp)(&hi->info.buf[hi->ptr[child]],
297                        &hi->info.buf[hi->ptr[child+1]]) > 0)
298             child++;
299         if ((*hi->cmp)(&hi->info.buf[hi->ptr[cur]],
300                        &hi->info.buf[hi->ptr[child]]) > 0)
301         {            
302             key_heap_swap (hi, cur, child);
303             cur = child;
304             child = 2*cur;
305         }
306         else
307             break;
308     }
309 }
310
311 static void key_heap_insert (struct heap_info *hi, const char *buf, int nbytes,
312                              struct key_file *kf)
313 {
314     int cur, parent;
315
316     cur = ++(hi->heapnum);
317     memcpy (hi->info.buf[hi->ptr[cur]], buf, nbytes);
318     hi->info.file[hi->ptr[cur]] = kf;
319
320     parent = cur/2;
321     while (parent && (*hi->cmp)(&hi->info.buf[hi->ptr[parent]],
322                                 &hi->info.buf[hi->ptr[cur]]) > 0)
323     {
324         key_heap_swap (hi, cur, parent);
325         cur = parent;
326         parent = cur/2;
327     }
328 }
329
330 static int heap_read_one (struct heap_info *hi, char *name, char *key)
331 {
332     int n, r;
333     char rbuf[512];
334     struct key_file *kf;
335
336     if (!hi->heapnum)
337         return 0;
338     n = hi->ptr[1];
339     strcpy (name, hi->info.buf[n]);
340     kf = hi->info.file[n];
341     r = strlen(name);
342     memcpy (key, hi->info.buf[n] + r+1, KEY_SIZE);
343     key_heap_delete (hi);
344     if ((r = key_file_read (kf, rbuf)))
345         key_heap_insert (hi, rbuf, r, kf);
346     no_iterations++;
347     return 1;
348 }
349
350 int heap_inp (Dict dict, ISAM isam, struct heap_info *hi)
351 {
352     char *info;
353     char next_name[INP_NAME_MAX+1];
354     char cur_name[INP_NAME_MAX+1];
355     int key_buf_size = INP_BUF_START;
356     int key_buf_ptr;
357     char *next_key;
358     char *key_buf;
359     int more;
360     
361     next_key = xmalloc (KEY_SIZE);
362     key_buf = xmalloc (key_buf_size * (KEY_SIZE));
363     more = heap_read_one (hi, cur_name, key_buf);
364     while (more)                   /* EOF ? */
365     {
366         int nmemb;
367         key_buf_ptr = KEY_SIZE;
368         while (1)
369         {
370             if (!(more = heap_read_one (hi, next_name, next_key)))
371                 break;
372             if (*next_name && strcmp (next_name, cur_name))
373                 break;
374             memcpy (key_buf + key_buf_ptr, next_key, KEY_SIZE);
375             key_buf_ptr += KEY_SIZE;
376             if (key_buf_ptr+KEY_SIZE >= key_buf_size)
377             {
378                 char *new_key_buf;
379                 new_key_buf = xmalloc (key_buf_size + INP_BUF_ADD);
380                 memcpy (new_key_buf, key_buf, key_buf_size);
381                 key_buf_size += INP_BUF_ADD;
382                 xfree (key_buf);
383                 key_buf = new_key_buf;
384             }
385         }
386         no_diffs++;
387         nmemb = key_buf_ptr / KEY_SIZE;
388         assert (nmemb*KEY_SIZE == key_buf_ptr);
389         if ((info = dict_lookup (dict, cur_name)))
390         {
391             ISAM_P isam_p, isam_p2;
392             logf (LOG_DEBUG, "updating %s", cur_name);
393             memcpy (&isam_p, info+1, sizeof(ISAM_P));
394             isam_p2 = is_merge (isam, isam_p, nmemb, key_buf);
395             if (!isam_p2)
396             {
397                 no_deletions++;
398                 if (!dict_delete (dict, cur_name))
399                     abort ();
400             }
401             else 
402             {
403                 no_updates++;
404                 if (isam_p2 != isam_p)
405                     dict_insert (dict, cur_name, sizeof(ISAM_P), &isam_p2);
406             }
407         }
408         else
409         {
410             ISAM_P isam_p;
411             logf (LOG_DEBUG, "inserting %s", cur_name);
412             no_insertions++;
413             isam_p = is_merge (isam, 0, nmemb, key_buf);
414             dict_insert (dict, cur_name, sizeof(ISAM_P), &isam_p);
415         }
416         memcpy (key_buf, next_key, KEY_SIZE);
417         strcpy (cur_name, next_name);
418     }
419     return 0;
420 }
421
422 struct progressInfo {
423     time_t   startTime;
424     time_t   lastTime;
425     off_t    totalBytes;
426     off_t    totalOffset;
427 };
428
429 void progressFunc (struct key_file *keyp, void *info)
430 {
431     struct progressInfo *p = info;
432     time_t now, remaining;
433
434     if (keyp->buf_size <= 0 || p->totalBytes <= 0)
435         return ;
436     time (&now);
437
438     if (now >= p->lastTime+10)
439     {
440         p->lastTime = now;
441         remaining = (now - p->startTime)*
442             ((double) p->totalBytes/p->totalOffset - 1.0);
443         if (remaining <= 130)
444             logf (LOG_LOG, "Merge %2.1f%% completed; %ld seconds remaining",
445                  (100.0*p->totalOffset) / p->totalBytes, (long) remaining);
446         else
447             logf (LOG_LOG, "Merge %2.1f%% completed; %ld minutes remaining",
448                  (100.0*p->totalOffset) / p->totalBytes, (long) remaining/60);
449     }
450     p->totalOffset += keyp->buf_size;
451 }
452
453 void key_input (const char *dict_fname, const char *isam_fname,
454                 int nkeys, int cache)
455                 
456 {
457     Dict dict;
458     ISAM isam;
459     struct key_file **kf;
460     char rbuf[1024];
461     int i, r;
462     struct heap_info *hi;
463     struct progressInfo progressInfo;
464
465     if (nkeys < 0)
466     {
467         char fname[1024];
468         nkeys = 0;
469         while (1)
470         {
471             getFnameTmp (fname, nkeys+1);
472             if (access (fname, R_OK) == -1)
473                 break;
474             nkeys++;
475         }
476         if (!nkeys)
477             return ;
478     }
479     dict = dict_open (dict_fname, cache, 1);
480     if (!dict)
481     {
482         logf (LOG_FATAL, "dict_open fail of `%s'", dict_fname);
483         exit (1);
484     }
485     isam = is_open (isam_fname, key_compare, 1, sizeof(struct it_key));
486     if (!isam)
487     {
488         logf (LOG_FATAL, "is_open fail of `%s'", isam_fname);
489         exit (1);
490     }
491
492     kf = xmalloc ((1+nkeys) * sizeof(*kf));
493     progressInfo.totalBytes = 0;
494     progressInfo.totalOffset = 0;
495     time (&progressInfo.startTime);
496     time (&progressInfo.lastTime);
497     for (i = 1; i<=nkeys; i++)
498     {
499         kf[i] = key_file_init (i, 32768);
500         kf[i]->readHandler = progressFunc;
501         kf[i]->readInfo = &progressInfo;
502         progressInfo.totalBytes += kf[i]->length;
503         progressInfo.totalOffset += kf[i]->buf_size;
504     }
505     hi = key_heap_init (nkeys, key_qsort_compare);
506     for (i = 1; i<=nkeys; i++)
507         if ((r = key_file_read (kf[i], rbuf)))
508             key_heap_insert (hi, rbuf, r, kf[i]);
509     heap_inp (dict, isam, hi);
510
511     dict_close (dict);
512     is_close (isam);
513     
514     for (i = 1; i<=nkeys; i++)
515     {
516         getFnameTmp (rbuf, i);
517         unlink (rbuf);
518     }
519     logf (LOG_LOG, "Iterations . . .%7d", no_iterations);
520     logf (LOG_LOG, "Distinct words .%7d", no_diffs);
521     logf (LOG_LOG, "Updates. . . . .%7d", no_updates);
522     logf (LOG_LOG, "Deletions. . . .%7d", no_deletions);
523     logf (LOG_LOG, "Insertions . . .%7d", no_insertions);
524 }
525
526