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