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