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