Zebra version corresponds to YAZ version 1.4.
[idzebra-moved-to-github.git] / index / zserver.c
1 /*
2  * Copyright (C) 1995-1997, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: zserver.c,v $
7  * Revision 1.48  1997-09-17 12:19:19  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.47  1997/09/04 13:58:36  adam
12  * New retrieve/extract method tellf (added).
13  * Added O_BINARY for open calls.
14  *
15  * Revision 1.46  1997/07/28 08:30:47  adam
16  * Server returns diagnostic 14 when record doesn't exist.
17  *
18  * Revision 1.45  1996/12/23 15:30:45  adam
19  * Work on truncation.
20  * Bug fix: result sets weren't deleted after server shut down.
21  *
22  * Revision 1.44  1996/12/11 12:08:01  adam
23  * Added better compression.
24  *
25  * Revision 1.43  1996/11/15 15:03:58  adam
26  * Logging of execution speed by using the times(2) call.
27  *
28  * Revision 1.42  1996/11/08  11:10:36  adam
29  * Buffers used during file match got bigger.
30  * Compressed ISAM support everywhere.
31  * Bug fixes regarding masking characters in queries.
32  * Redesigned Regexp-2 queries.
33  *
34  * Revision 1.41  1996/10/29 14:09:56  adam
35  * Use of cisam system - enabled if setting isamc is 1.
36  *
37  * Revision 1.40  1996/06/04 10:19:02  adam
38  * Minor changes - removed include of ctype.h.
39  *
40  * Revision 1.39  1996/05/31  09:07:05  quinn
41  * Work on character-set handling
42  *
43  * Revision 1.38  1996/05/14  11:34:01  adam
44  * Scan support in multiple registers/databases.
45  *
46  * Revision 1.37  1996/05/14  06:16:48  adam
47  * Compact use/set bytes used in search service.
48  *
49  * Revision 1.36  1996/05/01 13:46:37  adam
50  * First work on multiple records in one file.
51  * New option, -offset, to the "unread" command in the filter module.
52  *
53  * Revision 1.35  1996/03/26  16:01:14  adam
54  * New setting lockPath: directory of various lock files.
55  *
56  * Revision 1.34  1996/03/20  09:36:46  adam
57  * Function dict_lookup_grep got extra parameter, init_pos, which marks
58  * from which position in pattern approximate pattern matching should occur.
59  * Approximate pattern matching is used in relevance=re-2.
60  *
61  * Revision 1.33  1996/01/17  14:57:56  adam
62  * Prototype changed for reader functions in extract/retrieve. File
63  *  is identified by 'void *' instead of 'int.
64  *
65  * Revision 1.32  1995/12/11  09:12:58  adam
66  * The rec_get function returns NULL if record doesn't exist - will
67  * happen in the server if the result set records have been deleted since
68  * the creation of the set (i.e. the search).
69  * The server saves a result temporarily if it is 'volatile', i.e. the
70  * set is register dependent.
71  *
72  * Revision 1.31  1995/12/08  16:22:56  adam
73  * Work on update while servers are running. Three lock files introduced.
74  * The servers reload their registers when necessary, but they don't
75  * reestablish result sets yet.
76  *
77  * Revision 1.30  1995/12/07  17:38:48  adam
78  * Work locking mechanisms for concurrent updates/commit.
79  *
80  * Revision 1.29  1995/12/04  14:22:32  adam
81  * Extra arg to recType_byName.
82  * Started work on new regular expression parsed input to
83  * structured records.
84  *
85  * Revision 1.28  1995/11/28  09:09:48  adam
86  * Zebra config renamed.
87  * Use setting 'recordId' to identify record now.
88  * Bug fix in recindex.c: rec_release_blocks was invokeded even
89  * though the blocks were already released.
90  * File traversal properly deletes records when needed.
91  *
92  * Revision 1.27  1995/11/27  13:58:54  adam
93  * New option -t. storeStore data implemented in server.
94  *
95  * Revision 1.26  1995/11/25  10:24:07  adam
96  * More record fields - they are enumerated now.
97  * New options: flagStoreData flagStoreKey.
98  *
99  * Revision 1.25  1995/11/21  15:29:13  adam
100  * Config file 'base' read by default by both indexer and server.
101  *
102  * Revision 1.24  1995/11/20  16:59:47  adam
103  * New update method: the 'old' keys are saved for each records.
104  *
105  * Revision 1.23  1995/11/16  17:00:56  adam
106  * Better logging of rpn query.
107  *
108  * Revision 1.22  1995/11/16  15:34:55  adam
109  * Uses new record management system in both indexer and server.
110  *
111  * Revision 1.21  1995/11/01  16:25:52  quinn
112  * *** empty log message ***
113  *
114  * Revision 1.20  1995/10/27  14:00:12  adam
115  * Implemented detection of database availability.
116  *
117  * Revision 1.19  1995/10/17  18:02:11  adam
118  * New feature: databases. Implemented as prefix to words in dictionary.
119  *
120  * Revision 1.18  1995/10/16  14:03:09  quinn
121  * Changes to support element set names and espec1
122  *
123  * Revision 1.17  1995/10/16  09:32:40  adam
124  * More work on relational op.
125  *
126  * Revision 1.16  1995/10/13  12:26:44  adam
127  * Optimization of truncation.
128  *
129  * Revision 1.15  1995/10/12  12:40:55  adam
130  * Bug fixes in rpn_prox.
131  *
132  * Revision 1.14  1995/10/09  16:18:37  adam
133  * Function dict_lookup_grep got extra client data parameter.
134  *
135  * Revision 1.13  1995/10/06  14:38:00  adam
136  * New result set method: r_score.
137  * Local no (sysno) and score is transferred to retrieveCtrl.
138  *
139  * Revision 1.12  1995/10/06  13:52:06  adam
140  * Bug fixes. Handler may abort further scanning.
141  *
142  * Revision 1.11  1995/10/06  10:43:57  adam
143  * Scan added. 'occurrences' in scan entries not set yet.
144  *
145  * Revision 1.10  1995/10/02  16:43:32  quinn
146  * Set default resulting record type in fetch.
147  *
148  * Revision 1.9  1995/10/02  15:18:52  adam
149  * New member in recRetrieveCtrl: diagnostic.
150  *
151  * Revision 1.8  1995/09/28  09:19:47  adam
152  * xfree/xmalloc used everywhere.
153  * Extract/retrieve method seems to work for text records.
154  *
155  * Revision 1.7  1995/09/27  16:17:32  adam
156  * More work on retrieve.
157  *
158  * Revision 1.6  1995/09/08  08:53:22  adam
159  * Record buffer maintained in server_info.
160  *
161  * Revision 1.5  1995/09/06  16:11:18  adam
162  * Option: only one word key per file.
163  *
164  * Revision 1.4  1995/09/06  10:33:04  adam
165  * More work on present. Some log messages removed.
166  *
167  * Revision 1.3  1995/09/05  15:28:40  adam
168  * More work on search engine.
169  *
170  * Revision 1.2  1995/09/04  12:33:43  adam
171  * Various cleanup. YAZ util used instead.
172  *
173  * Revision 1.1  1995/09/04  09:10:41  adam
174  * More work on index add/del/update.
175  * Merge sort implemented.
176  * Initial work on z39 server.
177  *
178  */
179 #include <stdio.h>
180 #include <assert.h>
181 #include <unistd.h>
182 #include <fcntl.h>
183
184 #include <data1.h>
185 #include <recctrl.h>
186 #include <dmalloc.h>
187
188 #define USE_TIMES 1
189 #ifdef __linux__
190 #define USE_TIMES 1
191 #endif
192
193 #if USE_TIMES
194 #include <sys/times.h>
195 #endif
196 #include "zserver.h"
197
198
199 #if USE_TIMES
200 static struct tms tms1;
201 static struct tms tms2;
202 #endif
203
204 static int register_lock (ZServerInfo *zi)
205 {
206     time_t lastChange;
207     int state = zebraServerLockGetState(zi->res, &lastChange);
208
209     switch (state)
210     {
211     case 'c':
212         state = 1;
213         break;
214     default:
215         state = 0;
216     }
217     zebraServerLock (zi->res, state);
218 #if USE_TIMES
219     times (&tms1);
220 #endif
221     if (zi->registerState == state)
222     {
223         if (zi->registerChange >= lastChange)
224             return 0;
225         logf (LOG_LOG, "Register completely updated since last access");
226     }
227     else if (zi->registerState == -1)
228         logf (LOG_LOG, "Reading register using state %d pid=%ld", state,
229               (long) getpid());
230     else
231         logf (LOG_LOG, "Register has changed state from %d to %d",
232               zi->registerState, state);
233     zi->registerChange = lastChange;
234     if (zi->records)
235     {
236         zebTargetInfo_close (zi->zti, 0);
237         dict_close (zi->dict);
238         if (zi->isam)
239             is_close (zi->isam);
240         if (zi->isamc)
241             isc_close (zi->isamc);
242         rec_close (&zi->records);
243     }
244     bf_cache (zi->bfs, state ? res_get (zi->res, "shadow") : NULL);
245     zi->registerState = state;
246     zi->records = rec_open (zi->bfs, 0);
247     if (!(zi->dict = dict_open (zi->bfs, FNAME_DICT, 40, 0)))
248         return -1;
249     zi->isam = NULL;
250     zi->isamc = NULL;
251     if (res_get_match (zi->res, "isam", "c", NULL))
252     {
253         if (!(zi->isamc = isc_open (zi->bfs, FNAME_ISAMC,
254                                     0, key_isamc_m(zi->res))))
255             return -1;
256
257     }
258     else
259     {
260         if (!(zi->isam = is_open (zi->bfs, FNAME_ISAM, key_compare, 0,
261                                   sizeof (struct it_key), zi->res)))
262             return -1;
263     }
264     zi->zti = zebTargetInfo_open (zi->records, 0);
265     init_charmap (zi->res);
266     return 0;
267 }
268
269 static void register_unlock (ZServerInfo *zi)
270 {
271     static int waitSec = -1;
272
273 #if USE_TIMES
274     times (&tms2);
275     logf (LOG_LOG, "user/system: %ld/%ld",
276                         (long) (tms2.tms_utime - tms1.tms_utime),
277                         (long) (tms2.tms_stime - tms1.tms_stime));
278 #endif
279     if (waitSec == -1)
280     {
281         char *s = res_get (zi->res, "debugRequestWait");
282         if (s)
283             waitSec = atoi (s);
284         else
285             waitSec = 0;
286     }
287     if (waitSec > 0)
288         sleep (waitSec);
289     if (zi->registerState != -1)
290         zebraServerUnlock (zi->registerState);
291 }
292
293 bend_initresult *bend_init (bend_initrequest *q)
294 {
295     bend_initresult *r = odr_malloc (q->stream, sizeof(*r));
296     ZServerInfo *zi = xmalloc (sizeof(*zi));
297     struct statserv_options_block *sob;
298
299     r->errcode = 0;
300     r->errstring = 0;
301     r->handle = zi;
302
303     logf (LOG_DEBUG, "bend_init");
304
305     sob = statserv_getcontrol ();
306     logf (LOG_LOG, "Reading resources from %s", sob->configname);
307     if (!(zi->res = res_open (sob->configname)))
308     {
309         logf (LOG_FATAL, "Cannot open resource `%s'", sob->configname);
310         exit (1);
311     }
312     zi->dh = data1_create ();
313     zi->bfs = bfs_create (res_get (zi->res, "register"));
314     bf_lockDir (zi->bfs, res_get (zi->res, "lockDir"));
315     data1_set_tabpath (zi->dh, res_get(zi->res, "profilePath"));
316     zi->sets = NULL;
317     zi->registerState = -1;  /* trigger open of registers! */
318     zi->registerChange = 0;
319
320     zi->records = NULL;
321     zi->odr = odr_createmem (ODR_ENCODE);
322     zi->registered_sets = NULL;
323     return r;
324 }
325
326 bend_searchresult *bend_search (void *handle, bend_searchrequest *q, int *fd)
327 {
328     ZServerInfo *zi = handle;
329     bend_searchresult *r = odr_malloc (q->stream, sizeof(*r));
330
331     r->errcode = 0;
332     r->errstring = 0;
333     r->hits = 0;
334
335     register_lock (zi);
336     odr_reset (zi->odr);
337     zi->errCode = 0;
338     zi->errString = NULL;
339
340     logf (LOG_LOG, "ResultSet '%s'", q->setname);
341     switch (q->query->which)
342     {
343     case Z_Query_type_1: case Z_Query_type_101:
344         r->errcode = rpn_search (zi, q->query->u.type_1,
345                                 q->num_bases, q->basenames, q->setname,
346                                 &r->hits);
347         r->errstring = zi->errString;
348         break;
349     default:
350         r->errcode = 107;
351     }
352     register_unlock (zi);
353     return r;
354 }
355
356 struct fetch_control {
357     int record_offset;
358     int record_int_pos;
359     char *record_int_buf;
360     int record_int_len;
361     int fd;
362 };
363
364 static int record_ext_read (void *fh, char *buf, size_t count)
365 {
366     struct fetch_control *fc = fh;
367     return read (fc->fd, buf, count);
368 }
369
370 static off_t record_ext_seek (void *fh, off_t offset)
371 {
372     struct fetch_control *fc = fh;
373     return lseek (fc->fd, offset + fc->record_offset, SEEK_SET);
374 }
375
376 static off_t record_ext_tell (void *fh)
377 {
378     struct fetch_control *fc = fh;
379     return lseek (fc->fd, 0, SEEK_CUR) - fc->record_offset;
380 }
381
382 static off_t record_int_seek (void *fh, off_t offset)
383 {
384     struct fetch_control *fc = fh;
385     return (off_t) (fc->record_int_pos = offset);
386 }
387
388 static off_t record_int_tell (void *fh)
389 {
390     struct fetch_control *fc = fh;
391     return (off_t) fc->record_int_pos;
392 }
393
394 static int record_int_read (void *fh, char *buf, size_t count)
395 {
396     struct fetch_control *fc = fh;
397     int l = fc->record_int_len - fc->record_int_pos;
398     if (l <= 0)
399         return 0;
400     l = (l < count) ? l : count;
401     memcpy (buf, fc->record_int_buf + fc->record_int_pos, l);
402     fc->record_int_pos += l;
403     return l;
404 }
405
406 static int record_fetch (ZServerInfo *zi, int sysno, int score, ODR stream,
407                           oid_value input_format, Z_RecordComposition *comp,
408                           oid_value *output_format, char **rec_bufp,
409                           int *rec_lenp, char **basenamep)
410 {
411     Record rec;
412     char *fname, *file_type, *basename;
413     RecType rt;
414     struct recRetrieveCtrl retrieveCtrl;
415     char subType[128];
416     struct fetch_control fc;
417
418     rec = rec_get (zi->records, sysno);
419     if (!rec)
420     {
421         logf (LOG_DEBUG, "rec_get fail on sysno=%d", sysno);
422         return 14;
423     }
424     file_type = rec->info[recInfo_fileType];
425     fname = rec->info[recInfo_filename];
426     basename = rec->info[recInfo_databaseName];
427     *basenamep = odr_malloc (stream, strlen(basename)+1);
428     strcpy (*basenamep, basename);
429
430     if (!(rt = recType_byName (file_type, subType)))
431     {
432         logf (LOG_FATAL|LOG_ERRNO, "Retrieve: Cannot handle type %s", 
433               file_type);
434         exit (1);
435     }
436     logf (LOG_DEBUG, "retrieve localno=%d score=%d", sysno, score);
437     retrieveCtrl.fh = &fc;
438     fc.fd = -1;
439     if (rec->size[recInfo_storeData] > 0)
440     {
441         retrieveCtrl.readf = record_int_read;
442         retrieveCtrl.seekf = record_int_seek;
443         retrieveCtrl.tellf = record_int_tell;
444         fc.record_int_len = rec->size[recInfo_storeData];
445         fc.record_int_buf = rec->info[recInfo_storeData];
446         fc.record_int_pos = 0;
447         logf (LOG_DEBUG, "Internal retrieve. %d bytes", fc.record_int_len);
448     }
449     else 
450     {
451         if ((fc.fd = open (fname, O_BINARY|O_RDONLY)) == -1)
452         {
453             logf (LOG_WARN|LOG_ERRNO, "Retrieve fail; missing file: %s",
454                   fname);
455             rec_rm (&rec);
456             return 14;
457         }
458         memcpy (&fc.record_offset, rec->info[recInfo_offset],
459                 sizeof(fc.record_offset));
460
461         retrieveCtrl.readf = record_ext_read;
462         retrieveCtrl.seekf = record_ext_seek;
463         retrieveCtrl.tellf = record_ext_tell;
464
465         record_ext_seek (retrieveCtrl.fh, 0);
466     }
467     retrieveCtrl.subType = subType;
468     retrieveCtrl.localno = sysno;
469     retrieveCtrl.score = score;
470     retrieveCtrl.odr = stream;
471     retrieveCtrl.input_format = retrieveCtrl.output_format = input_format;
472     retrieveCtrl.comp = comp;
473     retrieveCtrl.diagnostic = 0;
474     retrieveCtrl.dh = zi->dh;
475     (*rt->retrieve)(&retrieveCtrl);
476     *output_format = retrieveCtrl.output_format;
477     *rec_bufp = retrieveCtrl.rec_buf;
478     *rec_lenp = retrieveCtrl.rec_len;
479     if (fc.fd != -1)
480         close (fc.fd);
481     rec_rm (&rec);
482
483     return retrieveCtrl.diagnostic;
484 }
485
486 bend_fetchresult *bend_fetch (void *handle, bend_fetchrequest *q, int *num)
487 {
488     ZServerInfo *zi = handle;
489     bend_fetchresult *r = odr_malloc (q->stream, sizeof(*r));
490     int positions[2];
491     ZServerSetSysno *records;
492
493     register_lock (zi);
494
495     r->errstring = 0;
496     r->last_in_set = 0;
497     r->basename = "base";
498
499     odr_reset (zi->odr);
500     zi->errCode = 0;
501
502     positions[0] = q->number;
503     records = resultSetSysnoGet (zi, q->setname, 1, positions);
504     if (!records)
505     {
506         logf (LOG_DEBUG, "resultSetRecordGet, error");
507         r->errcode = 13;
508         register_unlock (zi);
509         return r;
510     }
511     if (!records[0].sysno)
512     {
513         r->errcode = 13;
514         logf (LOG_DEBUG, "Out of range. pos=%d", q->number);
515         register_unlock (zi);
516         return r;
517     }
518     r->errcode = record_fetch (zi, records[0].sysno,
519                               records[0].score, q->stream, q->format,
520                               q->comp, &r->format, &r->record, &r->len,
521                               &r->basename);
522     resultSetSysnoDel (zi, records, 1);
523     register_unlock (zi);
524     return r;
525 }
526
527 bend_deleteresult *bend_delete (void *handle, bend_deleterequest *q, int *num)
528 {
529     ZServerInfo *zi = handle;
530     register_lock (zi);
531     register_unlock (zi);
532     return 0;
533 }
534
535 bend_scanresult *bend_scan (void *handle, bend_scanrequest *q, int *num)
536 {
537     ZServerInfo *zi = handle;
538     bend_scanresult *r = odr_malloc (q->stream, sizeof(*r));
539     int status;
540
541     register_lock (zi);
542     odr_reset (zi->odr);
543     zi->errCode = 0;
544     zi->errString = 0;
545
546     r->term_position = q->term_position;
547     r->num_entries = q->num_entries;
548     r->errcode = rpn_scan (zi, q->term,
549                           q->attributeset,
550                           q->num_bases, q->basenames,
551                           &r->term_position,
552                           &r->num_entries, &r->entries, &status);
553     r->errstring = zi->errString;
554     r->status = status;
555     register_unlock (zi);
556     return r;
557 }
558
559 void bend_close (void *handle)
560 {
561     ZServerInfo *zi = handle;
562     if (zi->records)
563     {
564         resultSetDestroy (zi);
565         dict_close (zi->dict);
566         if (zi->isam)
567             is_close (zi->isam);
568         if (zi->isamc)
569             isc_close (zi->isamc);
570         rec_close (&zi->records);
571         register_unlock (zi);
572     }
573     bfs_destroy (zi->bfs);
574     data1_destroy (zi->dh);
575     return;
576 }
577
578 int main (int argc, char **argv)
579 {
580     struct statserv_options_block *sob;
581
582     sob = statserv_getcontrol ();
583     strcpy (sob->configname, FNAME_CONFIG);
584     statserv_setcontrol (sob);
585
586     return statserv_main (argc, argv);
587 }