Work on new API. Locking system re-implemented
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /*
2  * Copyright (C) 1995-2002, Index Data
3  * All rights reserved.
4  *
5  * $Id: zebraapi.c,v 1.45 2002-02-20 17:30:01 adam Exp $
6  */
7
8 #include <assert.h>
9 #include <stdio.h>
10 #ifdef WIN32
11 #include <io.h>
12 #include <process.h>
13 #include <direct.h>
14 #else
15 #include <unistd.h>
16 #endif
17
18 #include <yaz/diagbib1.h>
19 #include "zserver.h"
20 #include <charmap.h>
21
22 static void zebra_chdir (ZebraService zh)
23 {
24     const char *dir = res_get (zh->res, "chdir");
25     if (!dir)
26         return;
27     logf (LOG_DEBUG, "chdir %s", dir);
28 #ifdef WIN32
29     _chdir(dir);
30 #else
31     chdir (dir);
32 #endif
33 }
34
35 static void zebra_flush_reg (ZebraHandle zh)
36 {
37     if (zh->service->matchDict)
38         dict_close (zh->service->matchDict);
39     zh->service->matchDict = 0;
40     zebraExplain_flush (zh->service->zei, 1, zh);
41     
42     extract_flushWriteKeys (zh);
43     zebra_index_merge (zh);
44 }
45
46
47 static int zebra_register_activate (ZebraHandle zh, int rw, int useshadow);
48 static int zebra_register_deactivate (ZebraHandle zh);
49
50 static int zebra_begin_read (ZebraHandle zh);
51 static void zebra_end_read (ZebraHandle zh);
52
53 ZebraHandle zebra_open (ZebraService zs)
54 {
55     ZebraHandle zh;
56
57     assert (zs);
58     if (zs->stop_flag)
59         return 0;
60
61     zh = (ZebraHandle) xmalloc (sizeof(*zh));
62     yaz_log (LOG_LOG, "zebra_open zs=%p returns %p", zs, zh);
63
64     zh->service = zs;
65     zh->sets = 0;
66     zh->destroyed = 0;
67     zh->errCode = 0;
68     zh->errString = 0;
69
70     zh->trans_no = 0;
71     zh->seqno = 0;
72     zh->last_val = 0;
73
74     zh->lock_normal = zebra_lock_create ("norm.LCK", 0);
75     zh->lock_shadow = zebra_lock_create ("shadow.LCK", 0);
76
77     zh->key_buf = 0;
78     zh->admin_databaseName = 0;
79
80     zh->keys.buf_max = 0;
81     zh->keys.buf = 0;
82
83     zebra_mutex_cond_lock (&zs->session_lock);
84
85     zh->next = zs->sessions;
86     zs->sessions = zh;
87
88     zebra_mutex_cond_unlock (&zs->session_lock);
89
90     return zh;
91 }
92
93
94 ZebraService zebra_start (const char *configName)
95 {
96     ZebraService zh = xmalloc (sizeof(*zh));
97
98     yaz_log (LOG_LOG, "zebra_start %s", configName);
99
100     zh->configName = xstrdup(configName);
101     zh->sessions = 0;
102     zh->stop_flag = 0;
103     zh->active = 1;
104
105     zh->registerState = -1;
106     zh->registerChange = 0;
107
108     if (!(zh->res = res_open (zh->configName)))
109     {
110         logf (LOG_WARN, "Failed to read resources `%s'", zh->configName);
111 //      return zh;
112     }
113     zebra_chdir (zh);
114
115     zebra_mutex_cond_init (&zh->session_lock);
116     if (!res_get (zh->res, "passwd"))
117         zh->passwd_db = NULL;
118     else
119     {
120         zh->passwd_db = passwd_db_open ();
121         if (!zh->passwd_db)
122             logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
123         else
124             passwd_db_file (zh->passwd_db, res_get (zh->res, "passwd"));
125     }
126
127     return zh;
128 }
129
130 static int zebra_register_activate (ZebraHandle zh, int rw, int useshadow)
131 {
132     ZebraService zs = zh->service;
133     int record_compression = REC_COMPRESS_NONE;
134     char *recordCompression = 0;
135
136     yaz_log (LOG_LOG, "zebra_open_register_activate rw = %d useshadow=%d",
137              rw, useshadow);
138
139     zs->dh = data1_create ();
140     if (!zs->dh)
141         return -1;
142     zs->bfs = bfs_create (res_get (zs->res, "register"));
143     if (!zs->bfs)
144     {
145         data1_destroy(zs->dh);
146         return -1;
147     }
148     bf_lockDir (zs->bfs, res_get (zs->res, "lockDir"));
149     if (useshadow)
150         bf_cache (zs->bfs, res_get (zs->res, "shadow"));
151     data1_set_tabpath (zs->dh, res_get(zs->res, "profilePath"));
152     zs->recTypes = recTypes_init (zs->dh);
153     recTypes_default_handlers (zs->recTypes);
154
155     zs->records = NULL;
156     zs->zebra_maps = zebra_maps_open (zs->res);
157     zs->rank_classes = NULL;
158
159     zs->records = 0;
160     zs->dict = 0;
161     zs->sortIdx = 0;
162     zs->isams = 0;
163 #if ZMBOL
164     zs->isam = 0;
165     zs->isamc = 0;
166     zs->isamd = 0;
167 #endif
168     zs->zei = 0;
169     
170     zebraRankInstall (zs, rank1_class);
171
172     recordCompression = res_get_def (zh->service->res,
173                                      "recordCompression", "none");
174     if (!strcmp (recordCompression, "none"))
175         record_compression = REC_COMPRESS_NONE;
176     if (!strcmp (recordCompression, "bzip2"))
177         record_compression = REC_COMPRESS_BZIP2;
178
179     if (!(zs->records = rec_open (zs->bfs, rw, record_compression)))
180     {
181         logf (LOG_WARN, "rec_open");
182         return -1;
183     }
184     if (!(zs->dict = dict_open (zs->bfs, FNAME_DICT, 80, rw, 0)))
185     {
186         logf (LOG_WARN, "dict_open");
187         return -1;
188     }
189     if (!(zs->sortIdx = sortIdx_open (zs->bfs, rw)))
190     {
191         logf (LOG_WARN, "sortIdx_open");
192         return -1;
193     }
194     if (res_get_match (zs->res, "isam", "s", ISAM_DEFAULT))
195     {
196         struct ISAMS_M_s isams_m;
197         if (!(zs->isams = isams_open (zs->bfs, FNAME_ISAMS, rw,
198                                       key_isams_m(zs->res, &isams_m))))
199         {
200             logf (LOG_WARN, "isams_open");
201             return -1;
202         }
203     }
204 #if ZMBOL
205     else if (res_get_match (zs->res, "isam", "i", ISAM_DEFAULT))
206     {
207         if (!(zs->isam = is_open (zs->bfs, FNAME_ISAM, key_compare, rw,
208                                   sizeof (struct it_key), zs->res)))
209         {
210             logf (LOG_WARN, "is_open");
211             return -1;
212         }
213     }
214     else if (res_get_match (zs->res, "isam", "c", ISAM_DEFAULT))
215     {
216         struct ISAMC_M_s isamc_m;
217         if (!(zs->isamc = isc_open (zs->bfs, FNAME_ISAMC,
218                                     rw, key_isamc_m(zs->res, &isamc_m))))
219         {
220             logf (LOG_WARN, "isc_open");
221             return -1;
222         }
223     }
224     else if (res_get_match (zs->res, "isam", "d", ISAM_DEFAULT))
225     {
226         struct ISAMD_M_s isamd_m;
227         
228         if (!(zs->isamd = isamd_open (zs->bfs, FNAME_ISAMD,
229                                       rw, key_isamd_m(zs->res, &isamd_m))))
230         {
231             logf (LOG_WARN, "isamd_open");
232             return -1;
233         }
234     }
235 #endif
236     zs->zei = zebraExplain_open (zs->records, zs->dh,
237                                  zs->res, rw, zh,
238                                  explain_extract);
239     if (!zs->zei)
240     {
241         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
242         return -1;
243     }
244     zs->active = 2;
245     yaz_log (LOG_LOG, "zebra_register_activate ok");
246     return 0;
247 }
248
249 void zebra_admin_shutdown (ZebraHandle zh)
250 {
251     zebra_mutex_cond_lock (&zh->service->session_lock);
252     zh->service->stop_flag = 1;
253     if (!zh->service->sessions)
254         zebra_register_deactivate(zh);
255     zh->service->active = 0;
256     zebra_mutex_cond_unlock (&zh->service->session_lock);
257 }
258
259 void zebra_admin_start (ZebraHandle zh)
260 {
261     ZebraService zs = zh->service;
262     zh->errCode = 0;
263     zebra_mutex_cond_lock (&zs->session_lock);
264     if (!zs->stop_flag)
265         zh->service->active = 1;
266     zebra_mutex_cond_unlock (&zs->session_lock);
267 }
268
269 static int zebra_register_deactivate (ZebraHandle zh)
270 {
271     ZebraService zs = zh->service;
272     zs->stop_flag = 0;
273     if (zs->active <= 1)
274     {
275         yaz_log(LOG_LOG, "zebra_register_deactivate (ignored since active=%d)",
276                 zs->active);
277         return 0;
278     }
279     yaz_log(LOG_LOG, "zebra_register_deactivate");
280     zebra_chdir (zs);
281     if (zs->records)
282     {
283         zebraExplain_close (zs->zei, 0);
284         dict_close (zs->dict);
285         sortIdx_close (zs->sortIdx);
286         if (zs->isams)
287             isams_close (zs->isams);
288 #if ZMBOL
289         if (zs->isam)
290             is_close (zs->isam);
291         if (zs->isamc)
292             isc_close (zs->isamc);
293         if (zs->isamd)
294             isamd_close (zs->isamd);
295 #endif
296         rec_close (&zs->records);
297     }
298     resultSetInvalidate (zh);
299
300     recTypes_destroy (zs->recTypes);
301     zebra_maps_close (zs->zebra_maps);
302     zebraRankDestroy (zs);
303     bfs_destroy (zs->bfs);
304     data1_destroy (zs->dh);
305
306     if (zs->passwd_db)
307         passwd_db_close (zs->passwd_db);
308     zs->active = 1;
309     return 0;
310 }
311
312 void zebra_stop(ZebraService zs)
313 {
314     if (!zs)
315         return ;
316     yaz_log (LOG_LOG, "zebra_stop");
317
318     zebra_mutex_cond_lock (&zs->session_lock);
319     while (zs->sessions)
320     {
321         zebra_register_deactivate(zs->sessions);
322         zebra_close (zs->sessions);
323     }
324         
325     zebra_mutex_cond_unlock (&zs->session_lock);
326
327     zebra_mutex_cond_destroy (&zs->session_lock);
328
329     res_close (zs->res);
330     xfree (zs->configName);
331     xfree (zs);
332 }
333
334 void zebra_close (ZebraHandle zh)
335 {
336     ZebraService zs;
337     struct zebra_session **sp;
338
339     if (!zh)
340         return;
341
342     zs = zh->service;
343     yaz_log (LOG_LOG, "zebra_close zh=%p", zh);
344     if (!zh)
345         return ;
346     resultSetDestroy (zh, -1, 0, 0);
347
348     if (zh->key_buf)
349     {
350         xfree (zh->key_buf);
351         zh->key_buf = 0;
352     }
353     
354     xfree (zh->admin_databaseName);
355     zebra_mutex_cond_lock (&zs->session_lock);
356     zebra_lock_destroy (zh->lock_normal);
357     zebra_lock_destroy (zh->lock_shadow);
358     sp = &zs->sessions;
359     while (1)
360     {
361         assert (*sp);
362         if (*sp == zh)
363         {
364             *sp = (*sp)->next;
365             break;
366         }
367         sp = &(*sp)->next;
368     }
369 //    if (!zs->sessions && zs->stop_flag)
370 //      zebra_register_deactivate(zs);
371     zebra_mutex_cond_unlock (&zs->session_lock);
372     xfree (zh);
373 }
374
375 struct map_baseinfo {
376     ZebraHandle zh;
377     NMEM mem;
378     int num_bases;
379     char **basenames;
380     int new_num_bases;
381     char **new_basenames;
382     int new_num_max;
383 };
384         
385 void map_basenames_func (void *vp, const char *name, const char *value)
386 {
387     struct map_baseinfo *p = (struct map_baseinfo *) vp;
388     int i, no;
389     char fromdb[128], todb[8][128];
390     
391     no =
392         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
393                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
394                 todb[5], todb[6], todb[7]);
395     if (no < 2)
396         return ;
397     no--;
398     for (i = 0; i<p->num_bases; i++)
399         if (p->basenames[i] && !strcmp (p->basenames[i], fromdb))
400         {
401             p->basenames[i] = 0;
402             for (i = 0; i < no; i++)
403             {
404                 if (p->new_num_bases == p->new_num_max)
405                     return;
406                 p->new_basenames[(p->new_num_bases)++] = 
407                     nmem_strdup (p->mem, todb[i]);
408             }
409             return;
410         }
411 }
412
413 void map_basenames (ZebraHandle zh, ODR stream,
414                     int *num_bases, char ***basenames)
415 {
416     struct map_baseinfo info;
417     struct map_baseinfo *p = &info;
418     int i;
419
420     info.zh = zh;
421     info.num_bases = *num_bases;
422     info.basenames = *basenames;
423     info.new_num_max = 128;
424     info.new_num_bases = 0;
425     info.new_basenames = (char **)
426         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
427     info.mem = stream->mem;
428
429     res_trav (zh->service->res, "mapdb", &info, map_basenames_func);
430     
431     for (i = 0; i<p->num_bases; i++)
432         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
433         {
434             p->new_basenames[(p->new_num_bases)++] = 
435                 nmem_strdup (p->mem, p->basenames[i]);
436         }
437     *num_bases = info.new_num_bases;
438     *basenames = info.new_basenames;
439     for (i = 0; i<*num_bases; i++)
440         logf (LOG_LOG, "base %s", (*basenames)[i]);
441 }
442
443 void zebra_search_rpn (ZebraHandle zh, ODR stream, ODR decode,
444                        Z_RPNQuery *query, int num_bases, char **basenames, 
445                        const char *setname)
446 {
447     zh->hits = 0;
448     if (zebra_begin_read (zh))
449         return;
450     map_basenames (zh, stream, &num_bases, &basenames);
451     resultSetAddRPN (zh, stream, decode, query, num_bases, basenames, setname);
452
453     zebra_end_read (zh);
454
455     logf(LOG_APP,"SEARCH:%d:",zh->hits);
456 }
457
458 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
459                              const char *setname, Z_RecordComposition *comp,
460                              oid_value input_format, int num_recs,
461                              ZebraRetrievalRecord *recs)
462 {
463     ZebraPosSet poset;
464     int i, *pos_array;
465
466     if (zebra_begin_read (zh))
467         return;
468
469     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
470     for (i = 0; i<num_recs; i++)
471         pos_array[i] = recs[i].position;
472     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
473     if (!poset)
474     {
475         logf (LOG_DEBUG, "zebraPosSetCreate error");
476         zh->errCode = 30;
477         zh->errString = nmem_strdup (stream->mem, setname);
478     }
479     else
480     {
481         for (i = 0; i<num_recs; i++)
482         {
483             if (poset[i].term)
484             {
485                 recs[i].errCode = 0;
486                 recs[i].format = VAL_SUTRS;
487                 recs[i].len = strlen(poset[i].term);
488                 recs[i].buf = poset[i].term;
489                 recs[i].base = poset[i].db;
490             }
491             else if (poset[i].sysno)
492             {
493                 recs[i].errCode =
494                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
495                                         stream, input_format, comp,
496                                         &recs[i].format, &recs[i].buf,
497                                         &recs[i].len,
498                                         &recs[i].base);
499                 recs[i].errString = NULL;
500             }
501             else
502             {
503                 char num_str[20];
504
505                 sprintf (num_str, "%d", pos_array[i]);  
506                 zh->errCode = 13;
507                 zh->errString = nmem_strdup (stream->mem, num_str);
508                 break;
509             }
510         }
511         zebraPosSetDestroy (zh, poset, num_recs);
512     }
513     zebra_end_read (zh);
514     xfree (pos_array);
515 }
516
517 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
518                  oid_value attributeset,
519                  int num_bases, char **basenames,
520                  int *position, int *num_entries, ZebraScanEntry **entries,
521                  int *is_partial)
522 {
523     if (zebra_begin_read (zh))
524     {
525         *entries = 0;
526         *num_entries = 0;
527         return;
528     }
529     map_basenames (zh, stream, &num_bases, &basenames);
530     rpn_scan (zh, stream, zapt, attributeset,
531               num_bases, basenames, position,
532               num_entries, entries, is_partial);
533     zebra_end_read (zh);
534 }
535
536 void zebra_sort (ZebraHandle zh, ODR stream,
537                  int num_input_setnames, const char **input_setnames,
538                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
539                  int *sort_status)
540 {
541     if (zebra_begin_read (zh))
542         return;
543     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
544                    output_setname, sort_sequence, sort_status);
545     zebra_end_read(zh);
546 }
547
548 int zebra_deleleResultSet(ZebraHandle zh, int function,
549                           int num_setnames, char **setnames,
550                           int *statuses)
551 {
552     int i, status;
553     if (zebra_begin_read(zh))
554         return Z_DeleteStatus_systemProblemAtTarget;
555     switch (function)
556     {
557     case Z_DeleteRequest_list:
558         resultSetDestroy (zh, num_setnames, setnames, statuses);
559         break;
560     case Z_DeleteRequest_all:
561         resultSetDestroy (zh, -1, 0, statuses);
562         break;
563     }
564     zebra_end_read (zh);
565     status = Z_DeleteStatus_success;
566     for (i = 0; i<num_setnames; i++)
567         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
568             status = statuses[i];
569     return status;
570 }
571
572 int zebra_errCode (ZebraHandle zh)
573 {
574     return zh->errCode;
575 }
576
577 const char *zebra_errString (ZebraHandle zh)
578 {
579     return diagbib1_str (zh->errCode);
580 }
581
582 char *zebra_errAdd (ZebraHandle zh)
583 {
584     return zh->errString;
585 }
586
587 int zebra_hits (ZebraHandle zh)
588 {
589     return zh->hits;
590 }
591
592 int zebra_auth (ZebraService zh, const char *user, const char *pass)
593 {
594     if (!zh->passwd_db || !passwd_db_auth (zh->passwd_db, user, pass))
595     {
596         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
597         return 0;
598     }
599
600     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
601     return 1;
602 }
603
604 void zebra_admin_import_begin (ZebraHandle zh, const char *database)
605 {
606     zebra_begin_trans (zh);
607     xfree (zh->admin_databaseName);
608     zh->admin_databaseName = xstrdup(database);
609 }
610
611 void zebra_admin_import_end (ZebraHandle zh)
612 {
613     zebra_end_trans (zh);
614 }
615
616 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
617 {
618     int sysno;
619     int i;
620     if (zh->service->active < 2)
621         return;
622     for (i = 0; i<segment->num_segmentRecords; i++)
623     {
624         Z_NamePlusRecord *npr = segment->segmentRecords[i];
625         const char *databaseName = npr->databaseName;
626
627         if (!databaseName)
628             databaseName = zh->admin_databaseName;
629         printf ("--------------%d--------------------\n", i);
630         if (npr->which == Z_NamePlusRecord_intermediateFragment)
631         {
632             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
633             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
634             {
635                 Odr_oct *oct = fragment->u.notExternallyTagged;
636                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
637                         oct->buf);
638                 
639                 sysno = 0;
640                 extract_rec_in_mem (zh, "grs.sgml",
641                                     oct->buf, oct->len,
642                                     databaseName,
643                                     0 /* delete_flag */,
644                                     0 /* test_mode */,
645                                     &sysno /* sysno */,
646                                     1 /* store_keys */,
647                                     1 /* store_data */,
648                                     0 /* match criteria */);
649             }
650         }
651     }
652 }
653
654 void zebra_admin_create (ZebraHandle zh, const char *database)
655 {
656     ZebraService zs;
657
658     zebra_begin_trans (zh);
659
660     zs = zh->service;
661     /* announce database */
662     if (zebraExplain_newDatabase (zh->service->zei, database, 0 
663                                   /* explainDatabase */))
664     {
665         zh->errCode = 224;
666         zh->errString = "Database already exist";
667     }
668     zebra_end_trans (zh);
669 }
670
671 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
672                        const char *input_str, int input_len,
673                        char *output_str, int output_len)
674 {
675     WRBUF wrbuf;
676     if (!zh->service->zebra_maps)
677         return -1;
678     wrbuf = zebra_replace(zh->service->zebra_maps, reg_id, "",
679                           input_str, input_len);
680     if (!wrbuf)
681         return -2;
682     if (wrbuf_len(wrbuf) >= output_len)
683         return -3;
684     if (wrbuf_len(wrbuf))
685         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
686     output_str[wrbuf_len(wrbuf)] = '\0';
687     return wrbuf_len(wrbuf);
688 }
689
690
691 void zebra_set_state (int val, int seqno)
692 {
693     long p = getpid();
694     FILE *f = fopen ("state.LCK", "w");
695     fprintf (f, "%c %d %ld\n", val, seqno, p);
696     fclose (f);
697 }
698
699 void zebra_get_state (char *val, int *seqno)
700 {
701     FILE *f = fopen ("state.LCK", "r");
702
703     *val = 'o';
704     *seqno = 0;
705
706     if (f)
707     {
708         fscanf (f, "%c %d", val, seqno);
709         fclose (f);
710     }
711 }
712
713 static int zebra_begin_read (ZebraHandle zh)
714 {
715     int dirty = 0;
716     char val;
717     int seqno;
718
719     zebra_flush_reg (zh);
720
721     (zh->trans_no)++;
722
723     if (zh->trans_no != 1)
724         return 0;
725
726     zebra_get_state (&val, &seqno);
727     if (val == 'd')
728         val = 'o';
729     if (seqno != zh->seqno)
730     {
731         yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d", seqno, zh->seqno);
732         dirty = 1;
733     }
734     else if (zh->last_val != val)
735     {
736         yaz_log (LOG_LOG, "reopen last cur/old %d/%d", val, zh->last_val);
737         dirty = 1;
738     }
739     if (!dirty)
740         return 0;
741
742     if (val == 'c')
743         zebra_lock_r (zh->lock_shadow);
744     else
745         zebra_lock_r (zh->lock_normal);
746     
747     zh->last_val = val;
748     zh->seqno = seqno;
749
750     zebra_register_deactivate (zh);
751
752     zebra_register_activate (zh, 0, val == 'c' ? 1 : 0);
753     return 0;
754 }
755
756 static void zebra_end_read (ZebraHandle zh)
757 {
758     (zh->trans_no)--;
759
760     if (zh->trans_no != 0)
761         return;
762
763     zebra_unlock (zh->lock_normal);
764     zebra_unlock (zh->lock_shadow);
765 }
766
767 void zebra_begin_trans (ZebraHandle zh)
768 {
769     int pass;
770     int seqno = 0;
771     char val = '?';
772     const char *rval;
773
774     (zh->trans_no++);
775     if (zh->trans_no != 1)
776     {
777         return;
778     }
779
780     yaz_log (LOG_LOG, "zebra_begin_trans");
781 #if HAVE_SYS_TIMES_H
782     times (&zh->tms1);
783 #endif
784
785     /* lock */
786     rval = res_get (zh->service->res, "shadow");
787
788     for (pass = 0; pass < 2; pass++)
789     {
790         if (rval)
791         {
792             zebra_lock_r (zh->lock_normal);
793             zebra_lock_w (zh->lock_shadow);
794         }
795         else
796         {
797             zebra_lock_w (zh->lock_normal);
798             zebra_lock_w (zh->lock_shadow);
799         }
800         
801         zebra_get_state (&val, &seqno);
802         if (val == 'c')
803         {
804             yaz_log (LOG_LOG, "previous transaction didn't finish commit");
805             zebra_unlock (zh->lock_shadow);
806             zebra_unlock (zh->lock_normal);
807             zebra_commit (zh);
808             continue;
809         }
810         else if (val == 'd')
811         {
812             if (rval)
813             {
814                 BFiles bfs = bfs_create (res_get (zh->service->res, "shadow"));
815                 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
816                 bf_commitClean (bfs, rval);
817                 bfs_destroy (bfs);
818             }
819             else
820             {
821                 yaz_log (LOG_WARN, "your previous transaction didn't finish");
822             }
823         }
824         break;
825     }
826     if (pass == 2)
827     {
828         yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
829         abort();
830         return;
831     }
832     zebra_set_state ('d', seqno);
833
834     zebra_register_activate (zh, 1, rval ? 1 : 0);
835     zh->service->matchDict = dict_open (zh->service->bfs, GMATCH_DICT,
836                                         50, 1, 0);
837     zh->seqno = seqno;
838 }
839
840 void zebra_end_trans (ZebraHandle zh)
841 {
842     char val;
843     int seqno;
844     const char *rval;
845
846     zh->trans_no--;
847     if (zh->trans_no != 0)
848         return;
849
850     yaz_log (LOG_LOG, "zebra_end_trans");
851     rval = res_get (zh->service->res, "shadow");
852
853     zebra_flush_reg (zh);
854
855     zebra_register_deactivate (zh);
856
857     zebra_get_state (&val, &seqno);
858     if (val != 'd')
859     {
860         BFiles bfs = bfs_create (res_get (zh->service->res, "shadow"));
861         bf_commitClean (bfs, rval);
862         bfs_destroy (bfs);
863     }
864     if (!rval)
865         seqno++;
866     zebra_set_state ('o', seqno);
867
868     zebra_unlock (zh->lock_shadow);
869     zebra_unlock (zh->lock_normal);
870
871 #if HAVE_SYS_TIMES_H
872     times (&zh->tms2);
873     logf (LOG_LOG, "user/system: %ld/%ld",
874                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
875                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
876
877 #endif
878 }
879
880 void zebra_repository_update (ZebraHandle zh)
881 {
882     zebra_begin_trans (zh);
883     logf (LOG_LOG, "updating %s", zh->rGroup.path);
884     repositoryUpdate (zh);    
885     zebra_end_trans (zh);
886 }
887
888 void zebra_repository_delete (ZebraHandle zh)
889 {
890     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
891     repositoryDelete (zh);
892 }
893
894 void zebra_repository_show (ZebraHandle zh)
895 {
896     repositoryShow (zh);
897 }
898
899 void zebra_commit (ZebraHandle zh)
900 {
901     int seqno;
902     char val;
903     const char *rval = res_get (zh->service->res, "shadow");
904     BFiles bfs;
905
906     if (!rval)
907     {
908         logf (LOG_WARN, "Cannot perform commit");
909         logf (LOG_WARN, "No shadow area defined");
910         return;
911     }
912
913     zebra_lock_w (zh->lock_normal);
914     zebra_lock_r (zh->lock_shadow);
915
916     bfs = bfs_create (res_get (zh->service->res, "register"));
917
918     zebra_get_state (&val, &seqno);
919
920     if (rval && *rval)
921         bf_cache (bfs, rval);
922     if (bf_commitExists (bfs))
923     {
924         zebra_set_state ('c', seqno);
925
926         logf (LOG_LOG, "commit start");
927         bf_commitExec (bfs);
928 #ifndef WIN32
929         sync ();
930 #endif
931         logf (LOG_LOG, "commit clean");
932         bf_commitClean (bfs, rval);
933         seqno++;
934         zebra_set_state ('o', seqno);
935     }
936     else
937     {
938         logf (LOG_LOG, "nothing to commit");
939     }
940     bfs_destroy (bfs);
941
942     zebra_unlock (zh->lock_shadow);
943     zebra_unlock (zh->lock_normal);
944 }
945
946 void zebra_init (ZebraHandle zh)
947 {
948     const char *rval = res_get (zh->service->res, "shadow");
949     BFiles bfs = 0;
950
951     bfs = bfs_create (res_get (zh->service->res, "register"));
952     if (rval && *rval)
953         bf_cache (bfs, rval);
954     
955     bf_reset (bfs);
956     bfs_destroy (bfs);
957     zebra_set_state ('o', 0);
958 }
959
960 void zebra_compact (ZebraHandle zh)
961 {
962     BFiles bfs = bfs_create (res_get (zh->service->res, "register"));
963     inv_compact (bfs);
964     bfs_destroy (bfs);
965 }
966
967 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
968 {
969     int sysno = 0;
970     zebra_begin_trans (zh);
971     extract_rec_in_mem (zh, "grs.sgml",
972                         buf, len,
973                         "Default",  /* database */
974                         0 /* delete_flag */,
975                         0 /* test_mode */,
976                         &sysno /* sysno */,
977                         1 /* store_keys */,
978                         1 /* store_data */,
979                         0 /* match criteria */);
980     zebra_end_trans (zh);
981     return sysno;
982 }