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