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