29ad2f4dc8513735e7cb9e2a07e7226c5938e694
[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.62 2002-07-15 11:50:45 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 "index.h"
20 #include <charmap.h>
21
22 static Res zebra_open_res (ZebraHandle zh);
23 static void zebra_close_res (ZebraHandle zh);
24
25 static void zebra_chdir (ZebraService zh)
26 {
27     const char *dir = res_get (zh->global_res, "chdir");
28     if (!dir)
29         return;
30     logf (LOG_DEBUG, "chdir %s", dir);
31 #ifdef WIN32
32     _chdir(dir);
33 #else
34     chdir (dir);
35 #endif
36 }
37
38 static void zebra_flush_reg (ZebraHandle zh)
39 {
40     zebraExplain_flush (zh->reg->zei, zh);
41     
42     extract_flushWriteKeys (zh);
43     zebra_index_merge (zh);
44 }
45
46 static struct zebra_register *zebra_register_open (ZebraService zs, 
47                                                    const char *name,
48                                                    int rw, int useshadow,
49                                                    Res res,
50                                                    const char *reg_path);
51 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
52
53 ZebraHandle zebra_open (ZebraService zs)
54 {
55     ZebraHandle zh;
56
57     if (!zs)
58         return 0;
59
60     zh = (ZebraHandle) xmalloc (sizeof(*zh));
61     yaz_log (LOG_LOG, "zebra_open zs=%p returns %p", zs, zh);
62
63     zh->service = zs;
64     zh->reg = 0;          /* no register attached yet */
65     zh->sets = 0;
66     zh->destroyed = 0;
67     zh->errCode = 0;
68     zh->errString = 0;
69     zh->res = 0;
70
71     zh->reg_name = xstrdup ("");
72     zh->path_reg = 0;
73     zh->num_basenames = 0;
74     zh->basenames = 0;
75
76     zh->trans_no = 0;
77
78     zh->lock_normal = 0;
79     zh->lock_shadow = 0;
80
81     zh->admin_databaseName = 0;
82
83     zh->shadow_enable = 1;
84
85     zebra_mutex_cond_lock (&zs->session_lock);
86
87     zh->next = zs->sessions;
88     zs->sessions = zh;
89
90     zebra_mutex_cond_unlock (&zs->session_lock);
91
92     return zh;
93 }
94
95 ZebraService zebra_start (const char *configName)
96 {
97     Res res;
98
99     yaz_log (LOG_LOG, "zebra_start %s", configName);
100
101     if (!(res = res_open (configName, 0)))
102         yaz_log (LOG_WARN, "Cannot read resources `%s'", configName);
103     else
104     {
105         ZebraService zh = xmalloc (sizeof(*zh));
106
107         yaz_log (LOG_LOG, "Read resources `%s'", configName);
108         
109         zh->global_res = res;
110         zh->configName = xstrdup(configName);
111         zh->sessions = 0;
112         
113         zebra_chdir (zh);
114         
115         zebra_mutex_cond_init (&zh->session_lock);
116         if (!res_get (zh->global_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,
125                                 res_get (zh->global_res, "passwd"));
126         }
127         zh->path_root = res_get (zh->global_res, "root");
128         return zh;
129     }
130     return 0;
131 }
132
133 static
134 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
135                                             int rw, int useshadow, Res res,
136                                             const char *reg_path)
137 {
138     struct zebra_register *reg;
139     int record_compression = REC_COMPRESS_NONE;
140     char *recordCompression = 0;
141
142     reg = xmalloc (sizeof(*reg));
143
144     assert (name);
145     reg->name = xstrdup (name);
146
147     reg->seqno = 0;
148     reg->last_val = 0;
149
150     assert (res);
151
152     yaz_log (LOG_LOG, "zebra_register_open rw = %d useshadow=%d p=%p",
153              rw, useshadow, reg);
154
155     reg->dh = data1_create ();
156     if (!reg->dh)
157         return 0;
158     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
159     if (!reg->bfs)
160     {
161         data1_destroy(reg->dh);
162         return 0;
163     }
164     if (useshadow)
165         bf_cache (reg->bfs, res_get (res, "shadow"));
166     data1_set_tabpath (reg->dh, res_get(res, "profilePath"));
167     data1_set_tabroot (reg->dh, reg_path);
168     reg->recTypes = recTypes_init (reg->dh);
169     recTypes_default_handlers (reg->recTypes);
170
171     reg->zebra_maps = zebra_maps_open (res, reg_path);
172     reg->rank_classes = NULL;
173
174     reg->key_buf = 0;
175
176     reg->keys.buf_max = 0;
177     reg->keys.buf = 0;
178
179     reg->records = 0;
180     reg->dict = 0;
181     reg->sortIdx = 0;
182     reg->isams = 0;
183     reg->matchDict = 0;
184     reg->isam = 0;
185     reg->isamc = 0;
186     reg->isamd = 0;
187     reg->isamb = 0;
188     reg->zei = 0;
189     reg->matchDict = 0;
190     
191     zebraRankInstall (reg, rank1_class);
192
193     recordCompression = res_get_def (res, "recordCompression", "none");
194     if (!strcmp (recordCompression, "none"))
195         record_compression = REC_COMPRESS_NONE;
196     if (!strcmp (recordCompression, "bzip2"))
197         record_compression = REC_COMPRESS_BZIP2;
198
199     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
200     {
201         logf (LOG_WARN, "rec_open");
202         return 0;
203     }
204     if (rw)
205     {
206         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
207     }
208     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
209     {
210         logf (LOG_WARN, "dict_open");
211         return 0;
212     }
213     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
214     {
215         logf (LOG_WARN, "sortIdx_open");
216         return 0;
217     }
218     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
219     {
220         struct ISAMS_M_s isams_m;
221         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
222                                       key_isams_m(res, &isams_m))))
223         {
224             logf (LOG_WARN, "isams_open");
225             return 0;
226         }
227     }
228     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
229     {
230         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
231                                   sizeof (struct it_key), res)))
232         {
233             logf (LOG_WARN, "is_open");
234             return 0;
235         }
236     }
237     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
238     {
239         struct ISAMC_M_s isamc_m;
240         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
241                                     rw, key_isamc_m(res, &isamc_m))))
242         {
243             logf (LOG_WARN, "isc_open");
244             return 0;
245         }
246     }
247     if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
248     {
249         struct ISAMD_M_s isamd_m;
250         
251         if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
252                                       rw, key_isamd_m(res, &isamd_m))))
253         {
254             logf (LOG_WARN, "isamd_open");
255             return 0;
256         }
257     }
258     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
259     {
260         struct ISAMC_M_s isamc_m;
261         
262         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
263                                        rw, key_isamc_m(res, &isamc_m), 0)))
264         {
265             logf (LOG_WARN, "isamb_open");
266             return 0;
267         }
268     }
269     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
270     {
271         struct ISAMC_M_s isamc_m;
272         
273         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
274                                        rw, key_isamc_m(res, &isamc_m), 1)))
275         {
276             logf (LOG_WARN, "isamb_open");
277             return 0;
278         }
279     }
280     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
281     {
282         struct ISAMC_M_s isamc_m;
283         
284         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
285                                        rw, key_isamc_m(res, &isamc_m), -1)))
286         {
287             logf (LOG_WARN, "isamb_open");
288             return 0;
289         }
290     }
291     reg->zei = zebraExplain_open (reg->records, reg->dh,
292                                   res, rw, reg,
293                                   explain_extract);
294     if (!reg->zei)
295     {
296         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
297         return 0;
298     }
299     reg->active = 2;
300     yaz_log (LOG_LOG, "zebra_register_open ok p=%p", reg);
301     return reg;
302 }
303
304 void zebra_admin_shutdown (ZebraHandle zh)
305 {
306     zebra_mutex_cond_lock (&zh->service->session_lock);
307     zh->service->stop_flag = 1;
308     zebra_mutex_cond_unlock (&zh->service->session_lock);
309 }
310
311 void zebra_admin_start (ZebraHandle zh)
312 {
313     ZebraService zs = zh->service;
314     zh->errCode = 0;
315     zebra_mutex_cond_lock (&zs->session_lock);
316     zebra_mutex_cond_unlock (&zs->session_lock);
317 }
318
319 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
320 {
321     yaz_log(LOG_LOG, "zebra_register_close p=%p", reg);
322     reg->stop_flag = 0;
323     zebra_chdir (zs);
324     if (reg->records)
325     {
326         zebraExplain_close (reg->zei);
327         dict_close (reg->dict);
328         if (reg->matchDict)
329             dict_close (reg->matchDict);
330         sortIdx_close (reg->sortIdx);
331         if (reg->isams)
332             isams_close (reg->isams);
333         if (reg->isam)
334             is_close (reg->isam);
335         if (reg->isamc)
336             isc_close (reg->isamc);
337         if (reg->isamd)
338             isamd_close (reg->isamd);
339         if (reg->isamb)
340             isamb_close (reg->isamb);
341         rec_close (&reg->records);
342     }
343
344     recTypes_destroy (reg->recTypes);
345     zebra_maps_close (reg->zebra_maps);
346     zebraRankDestroy (reg);
347     bfs_destroy (reg->bfs);
348     data1_destroy (reg->dh);
349
350     xfree (reg->key_buf);
351     xfree (reg->name);
352     xfree (reg);
353     yaz_log (LOG_LOG, "zebra_register_close 2");
354 }
355
356 void zebra_stop(ZebraService zs)
357 {
358     if (!zs)
359         return ;
360     yaz_log (LOG_LOG, "zebra_stop");
361
362     zebra_mutex_cond_lock (&zs->session_lock);
363     while (zs->sessions)
364     {
365         zebra_close (zs->sessions);
366     }
367         
368     zebra_mutex_cond_unlock (&zs->session_lock);
369
370     zebra_mutex_cond_destroy (&zs->session_lock);
371
372     if (zs->passwd_db)
373         passwd_db_close (zs->passwd_db);
374
375     res_close (zs->global_res);
376     xfree (zs->configName);
377     xfree (zs->path_root);
378     xfree (zs);
379 }
380
381 void zebra_close (ZebraHandle zh)
382 {
383     ZebraService zs;
384     struct zebra_session **sp;
385
386     if (!zh)
387         return;
388
389     zs = zh->service;
390     yaz_log (LOG_LOG, "zebra_close zh=%p", zh);
391     if (!zh)
392         return ;
393     resultSetDestroy (zh, -1, 0, 0);
394
395
396     if (zh->reg)
397         zebra_register_close (zh->service, zh->reg);
398     zebra_close_res (zh);
399
400     xfree (zh->admin_databaseName);
401     zebra_mutex_cond_lock (&zs->session_lock);
402     zebra_lock_destroy (zh->lock_normal);
403     zebra_lock_destroy (zh->lock_shadow);
404     sp = &zs->sessions;
405     while (1)
406     {
407         assert (*sp);
408         if (*sp == zh)
409         {
410             *sp = (*sp)->next;
411             break;
412         }
413         sp = &(*sp)->next;
414     }
415 //    if (!zs->sessions && zs->stop_flag)
416 //      zebra_register_deactivate(zs);
417     zebra_mutex_cond_unlock (&zs->session_lock);
418     xfree (zh->reg_name);
419     xfree (zh);
420 }
421
422 struct map_baseinfo {
423     ZebraHandle zh;
424     NMEM mem;
425     int num_bases;
426     char **basenames;
427     int new_num_bases;
428     char **new_basenames;
429     int new_num_max;
430 };
431
432 static Res zebra_open_res (ZebraHandle zh)
433 {
434     Res res = 0;
435     char fname[512];
436     if (zh->path_reg)
437     {
438         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
439         res = res_open (fname, zh->service->global_res);
440         if (!res)
441             res = zh->service->global_res;
442     }
443     else if (*zh->reg_name == 0)
444     {
445         res = zh->service->global_res;
446     }
447     else
448     {
449         yaz_log (LOG_WARN, "no register root specified");
450         return 0;  /* no path for register - fail! */
451     }
452     return res;
453 }
454
455 static void zebra_close_res (ZebraHandle zh)
456 {
457     if (zh->res != zh->service->global_res)
458         res_close (zh->res);
459     zh->res = 0;
460 }
461
462 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
463 {
464     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
465         return 0;
466     if (!zh->res)
467     {
468         assert (zh->reg == 0);
469         assert (*zh->reg_name == 0);
470     }
471     else
472     {
473         if (zh->reg)
474         {
475             resultSetInvalidate (zh);
476             zebra_register_close (zh->service, zh->reg);
477             zh->reg = 0;
478         }
479         zebra_close_res(zh);
480     }
481     xfree (zh->reg_name);
482     zh->reg_name = xstrdup (new_reg);
483
484     xfree (zh->path_reg);
485     zh->path_reg = 0;
486     if (zh->service->path_root)
487     {
488         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
489                                 strlen(zh->reg_name) + 3);
490         strcpy (zh->path_reg, zh->service->path_root);
491         if (*zh->reg_name)
492         {
493             strcat (zh->path_reg, "/");
494             strcat (zh->path_reg, zh->reg_name);
495         }
496     }
497     zh->res = zebra_open_res (zh);
498     
499     if (zh->lock_normal)
500         zebra_lock_destroy (zh->lock_normal);
501     zh->lock_normal = 0;
502
503     if (zh->lock_shadow)
504         zebra_lock_destroy (zh->lock_shadow);
505     zh->lock_shadow = 0;
506
507     if (zh->res)
508     {
509         char fname[512];
510         const char *lock_area  =res_get (zh->res, "lockDir");
511         
512         if (!lock_area && zh->path_reg)
513             res_put (zh->res, "lockDir", zh->path_reg);
514         sprintf (fname, "norm.%s.LCK", zh->reg_name);
515         zh->lock_normal =
516             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
517         
518         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
519         zh->lock_shadow =
520             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
521
522     }
523     return 1;
524 }
525
526 void map_basenames_func (void *vp, const char *name, const char *value)
527 {
528     struct map_baseinfo *p = (struct map_baseinfo *) vp;
529     int i, no;
530     char fromdb[128], todb[8][128];
531     
532     no =
533         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
534                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
535                 todb[5], todb[6], todb[7]);
536     if (no < 2)
537         return ;
538     no--;
539     for (i = 0; i<p->num_bases; i++)
540         if (p->basenames[i] && !strcmp (p->basenames[i], fromdb))
541         {
542             p->basenames[i] = 0;
543             for (i = 0; i < no; i++)
544             {
545                 if (p->new_num_bases == p->new_num_max)
546                     return;
547                 p->new_basenames[(p->new_num_bases)++] = 
548                     nmem_strdup (p->mem, todb[i]);
549             }
550             return;
551         }
552 }
553
554 void map_basenames (ZebraHandle zh, ODR stream,
555                     int *num_bases, char ***basenames)
556 {
557     struct map_baseinfo info;
558     struct map_baseinfo *p = &info;
559     int i;
560
561     info.zh = zh;
562     info.num_bases = *num_bases;
563     info.basenames = *basenames;
564     info.new_num_max = 128;
565     info.new_num_bases = 0;
566     info.new_basenames = (char **)
567         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
568     info.mem = stream->mem;
569
570     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
571     
572     for (i = 0; i<p->num_bases; i++)
573         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
574         {
575             p->new_basenames[(p->new_num_bases)++] = 
576                 nmem_strdup (p->mem, p->basenames[i]);
577         }
578     *num_bases = info.new_num_bases;
579     *basenames = info.new_basenames;
580     for (i = 0; i<*num_bases; i++)
581         logf (LOG_LOG, "base %s", (*basenames)[i]);
582 }
583
584 int zebra_select_database (ZebraHandle zh, const char *basename)
585 {
586     return zebra_select_databases (zh, 1, &basename);
587 }
588
589 int zebra_select_databases (ZebraHandle zh, int num_bases,
590                             const char **basenames)
591 {
592     int i;
593     const char *cp;
594     int len = 0;
595     char *new_reg = 0;
596     
597     if (num_bases < 1)
598     {
599         zh->errCode = 23;
600         return -1;
601     }
602     for (i = 0; i < zh->num_basenames; i++)
603         xfree (zh->basenames[i]);
604     xfree (zh->basenames);
605     
606     zh->num_basenames = num_bases;
607     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
608     for (i = 0; i < zh->num_basenames; i++)
609         zh->basenames[i] = xstrdup (basenames[i]);
610
611     cp = strrchr(basenames[0], '/');
612     if (cp)
613     {
614         len = cp - basenames[0];
615         new_reg = xmalloc (len + 1);
616         memcpy (new_reg, basenames[0], len);
617         new_reg[len] = '\0';
618     }
619     else
620         new_reg = xstrdup ("");
621     for (i = 1; i<num_bases; i++)
622     {
623         const char *cp1;
624
625         cp1 = strrchr (basenames[i], '/');
626         if (cp)
627         {
628             if (!cp1)
629             {
630                 zh->errCode = 23;
631                 return -1;
632             }
633             if (len != cp1 - basenames[i] ||
634                 memcmp (basenames[i], new_reg, len))
635             {
636                 zh->errCode = 23;
637                 return -1;
638             }
639         }
640         else
641         {
642             if (cp1)
643             {
644                 zh->errCode = 23;
645                 return -1;
646             }
647         }
648     }
649     zebra_select_register (zh, new_reg);
650     xfree (new_reg);
651     if (!zh->res)
652     {
653         zh->errCode = 109;
654         return -1;
655     }
656     return 0;
657 }
658
659 void zebra_search_rpn (ZebraHandle zh, ODR decode, ODR stream,
660                        Z_RPNQuery *query, const char *setname, int *hits)
661 {
662     zh->hits = 0;
663     *hits = 0;
664
665     if (zebra_begin_read (zh))
666         return;
667     resultSetAddRPN (zh, decode, stream, query, 
668                      zh->num_basenames, zh->basenames, setname);
669
670     zebra_end_read (zh);
671
672     *hits = zh->hits;
673 }
674
675 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
676                              const char *setname, Z_RecordComposition *comp,
677                              oid_value input_format, int num_recs,
678                              ZebraRetrievalRecord *recs)
679 {
680     ZebraPosSet poset;
681     int i, *pos_array;
682
683     if (!zh->res)
684     {
685         zh->errCode = 30;
686         zh->errString = odr_strdup (stream, setname);
687         return;
688     }
689     
690     zh->errCode = 0;
691
692     if (zebra_begin_read (zh))
693         return;
694
695     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
696     for (i = 0; i<num_recs; i++)
697         pos_array[i] = recs[i].position;
698     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
699     if (!poset)
700     {
701         logf (LOG_DEBUG, "zebraPosSetCreate error");
702         zh->errCode = 30;
703         zh->errString = nmem_strdup (stream->mem, setname);
704     }
705     else
706     {
707         for (i = 0; i<num_recs; i++)
708         {
709             if (poset[i].term)
710             {
711                 recs[i].errCode = 0;
712                 recs[i].format = VAL_SUTRS;
713                 recs[i].len = strlen(poset[i].term);
714                 recs[i].buf = poset[i].term;
715                 recs[i].base = poset[i].db;
716             }
717             else if (poset[i].sysno)
718             {
719                 recs[i].errCode =
720                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
721                                         stream, input_format, comp,
722                                         &recs[i].format, &recs[i].buf,
723                                         &recs[i].len,
724                                         &recs[i].base);
725                 recs[i].errString = NULL;
726             }
727             else
728             {
729                 char num_str[20];
730
731                 sprintf (num_str, "%d", pos_array[i]);  
732                 zh->errCode = 13;
733                 zh->errString = odr_strdup (stream, num_str);
734                 break;
735             }
736         }
737         zebraPosSetDestroy (zh, poset, num_recs);
738     }
739     zebra_end_read (zh);
740     xfree (pos_array);
741 }
742
743 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
744                  oid_value attributeset,
745                  int *position, int *num_entries, ZebraScanEntry **entries,
746                  int *is_partial)
747 {
748     if (zebra_begin_read (zh))
749     {
750         *entries = 0;
751         *num_entries = 0;
752         return;
753     }
754     rpn_scan (zh, stream, zapt, attributeset,
755               zh->num_basenames, zh->basenames, position,
756               num_entries, entries, is_partial);
757     zebra_end_read (zh);
758 }
759
760 void zebra_sort (ZebraHandle zh, ODR stream,
761                  int num_input_setnames, const char **input_setnames,
762                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
763                  int *sort_status)
764 {
765     if (zebra_begin_read (zh))
766         return;
767     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
768                    output_setname, sort_sequence, sort_status);
769     zebra_end_read(zh);
770 }
771
772 int zebra_deleleResultSet(ZebraHandle zh, int function,
773                           int num_setnames, char **setnames,
774                           int *statuses)
775 {
776     int i, status;
777     if (zebra_begin_read(zh))
778         return Z_DeleteStatus_systemProblemAtTarget;
779     switch (function)
780     {
781     case Z_DeleteRequest_list:
782         resultSetDestroy (zh, num_setnames, setnames, statuses);
783         break;
784     case Z_DeleteRequest_all:
785         resultSetDestroy (zh, -1, 0, statuses);
786         break;
787     }
788     zebra_end_read (zh);
789     status = Z_DeleteStatus_success;
790     for (i = 0; i<num_setnames; i++)
791         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
792             status = statuses[i];
793     return status;
794 }
795
796 int zebra_errCode (ZebraHandle zh)
797 {
798     return zh->errCode;
799 }
800
801 const char *zebra_errString (ZebraHandle zh)
802 {
803     return diagbib1_str (zh->errCode);
804 }
805
806 char *zebra_errAdd (ZebraHandle zh)
807 {
808     return zh->errString;
809 }
810
811 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
812 {
813     ZebraService zs = zh->service;
814     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
815     {
816         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
817         return 0;
818     }
819
820     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
821     return 1;
822 }
823
824 void zebra_admin_import_begin (ZebraHandle zh, const char *database)
825 {
826     zebra_begin_trans (zh);
827     xfree (zh->admin_databaseName);
828     zh->admin_databaseName = xstrdup(database);
829 }
830
831 void zebra_admin_import_end (ZebraHandle zh)
832 {
833     zebra_end_trans (zh);
834 }
835
836 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
837 {
838     int sysno;
839     int i;
840     for (i = 0; i<segment->num_segmentRecords; i++)
841     {
842         Z_NamePlusRecord *npr = segment->segmentRecords[i];
843         const char *databaseName = npr->databaseName;
844
845         if (!databaseName)
846             databaseName = zh->admin_databaseName;
847         printf ("--------------%d--------------------\n", i);
848         if (npr->which == Z_NamePlusRecord_intermediateFragment)
849         {
850             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
851             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
852             {
853                 Odr_oct *oct = fragment->u.notExternallyTagged;
854                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
855                         oct->buf);
856                 
857                 sysno = 0;
858                 extract_rec_in_mem (zh, "grs.sgml",
859                                     oct->buf, oct->len,
860                                     databaseName,
861                                     0 /* delete_flag */,
862                                     0 /* test_mode */,
863                                     &sysno /* sysno */,
864                                     1 /* store_keys */,
865                                     1 /* store_data */,
866                                     0 /* match criteria */);
867             }
868         }
869     }
870 }
871
872 void zebra_admin_create (ZebraHandle zh, const char *database)
873 {
874     ZebraService zs;
875
876     zebra_begin_trans (zh);
877
878     zs = zh->service;
879     /* announce database */
880     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
881                                   /* explainDatabase */))
882     {
883         zh->errCode = 224;
884         zh->errString = "Database already exist";
885     }
886     zebra_end_trans (zh);
887 }
888
889 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
890                        const char *input_str, int input_len,
891                        char *output_str, int output_len)
892 {
893     WRBUF wrbuf;
894     if (!zh->reg->zebra_maps)
895         return -1;
896     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
897                           input_str, input_len);
898     if (!wrbuf)
899         return -2;
900     if (wrbuf_len(wrbuf) >= output_len)
901         return -3;
902     if (wrbuf_len(wrbuf))
903         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
904     output_str[wrbuf_len(wrbuf)] = '\0';
905     return wrbuf_len(wrbuf);
906 }
907
908
909 void zebra_set_state (ZebraHandle zh, int val, int seqno)
910 {
911     char state_fname[256];
912     char *fname;
913     long p = getpid();
914     FILE *f;
915
916     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
917     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
918     f = fopen (fname, "w");
919
920     yaz_log (LOG_LOG, "%c %d %ld", val, seqno, p);
921     fprintf (f, "%c %d %ld\n", val, seqno, p);
922     fclose (f);
923     xfree (fname);
924 }
925
926 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
927 {
928     char state_fname[256];
929     char *fname;
930     FILE *f;
931
932     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
933     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
934     f = fopen (fname, "r");
935     *val = 'o';
936     *seqno = 0;
937
938     if (f)
939     {
940         fscanf (f, "%c %d", val, seqno);
941         fclose (f);
942     }
943     xfree (fname);
944 }
945
946 int zebra_begin_read (ZebraHandle zh)
947 {
948     int dirty = 0;
949     char val;
950     int seqno;
951
952     assert (zh->res);
953
954     (zh->trans_no)++;
955
956     if (zh->trans_no != 1)
957     {
958         zebra_flush_reg (zh);
959         return 0;
960     }
961 #if HAVE_SYS_TIMES_H
962     times (&zh->tms1);
963 #endif
964     if (!zh->res)
965     {
966         (zh->trans_no)--;
967         zh->errCode = 109;
968         return -1;
969     }
970     zebra_get_state (zh, &val, &seqno);
971     if (val == 'd')
972         val = 'o';
973
974     if (!zh->reg)
975         dirty = 1;
976     else if (seqno != zh->reg->seqno)
977     {
978         yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
979                  seqno, zh->reg->seqno);
980         dirty = 1;
981     }
982     else if (zh->reg->last_val != val)
983     {
984         yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
985                  val, zh->reg->last_val);
986         dirty = 1;
987     }
988     if (!dirty)
989         return 0;
990
991     if (val == 'c')
992         zebra_lock_r (zh->lock_shadow);
993     else
994         zebra_lock_r (zh->lock_normal);
995     
996     if (zh->reg)
997         zebra_register_close (zh->service, zh->reg);
998     zh->reg = zebra_register_open (zh->service, zh->reg_name,
999                                    0, val == 'c' ? 1 : 0,
1000                                    zh->res, zh->path_reg);
1001     if (!zh->reg)
1002     {
1003         zh->errCode = 109;
1004         return -1;
1005     }
1006     zh->reg->last_val = val;
1007     zh->reg->seqno = seqno;
1008
1009     return 0;
1010 }
1011
1012 void zebra_end_read (ZebraHandle zh)
1013 {
1014     (zh->trans_no)--;
1015
1016     if (zh->trans_no != 0)
1017         return;
1018
1019 #if HAVE_SYS_TIMES_H
1020     times (&zh->tms2);
1021     logf (LOG_LOG, "user/system: %ld/%ld",
1022                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1023                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1024
1025 #endif
1026
1027     zebra_unlock (zh->lock_normal);
1028     zebra_unlock (zh->lock_shadow);
1029 }
1030
1031 void zebra_begin_trans (ZebraHandle zh)
1032 {
1033     int pass;
1034     int seqno = 0;
1035     char val = '?';
1036     const char *rval = 0;
1037
1038     assert (zh->res);
1039
1040     (zh->trans_no++);
1041     if (zh->trans_no != 1)
1042     {
1043         return;
1044     }
1045     
1046     yaz_log (LOG_LOG, "zebra_begin_trans");
1047
1048     zh->records_inserted = 0;
1049     zh->records_updated = 0;
1050     zh->records_deleted = 0;
1051     zh->records_processed = 0;
1052
1053 #if HAVE_SYS_TIMES_H
1054     times (&zh->tms1);
1055 #endif
1056     
1057     /* lock */
1058     if (zh->shadow_enable)
1059         rval = res_get (zh->res, "shadow");
1060
1061     for (pass = 0; pass < 2; pass++)
1062     {
1063         if (rval)
1064         {
1065             zebra_lock_r (zh->lock_normal);
1066             zebra_lock_w (zh->lock_shadow);
1067         }
1068         else
1069         {
1070             zebra_lock_w (zh->lock_normal);
1071             zebra_lock_w (zh->lock_shadow);
1072         }
1073         
1074         zebra_get_state (zh, &val, &seqno);
1075         if (val == 'c')
1076         {
1077             yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1078             zebra_unlock (zh->lock_shadow);
1079             zebra_unlock (zh->lock_normal);
1080             zebra_commit (zh);
1081             continue;
1082         }
1083         else if (val == 'd')
1084         {
1085             if (rval)
1086             {
1087                 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1088                                          zh->path_reg);
1089                 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1090                 bf_commitClean (bfs, rval);
1091                 bfs_destroy (bfs);
1092             }
1093             else
1094             {
1095                 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1096             }
1097         }
1098         break;
1099     }
1100     if (pass == 2)
1101     {
1102         yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1103         abort();
1104         return;
1105     }
1106     zebra_set_state (zh, 'd', seqno);
1107
1108     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1109                                    1, rval ? 1 : 0, zh->res,
1110                                    zh->path_reg);
1111
1112     zh->reg->seqno = seqno;
1113 }
1114
1115 void zebra_end_trans (ZebraHandle zh)
1116 {
1117     char val;
1118     int seqno;
1119     const char *rval;
1120
1121     zh->trans_no--;
1122     if (zh->trans_no != 0)
1123         return;
1124
1125     yaz_log (LOG_LOG, "zebra_end_trans");
1126     rval = res_get (zh->res, "shadow");
1127
1128     zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1129
1130     zebra_flush_reg (zh);
1131
1132     zebra_register_close (zh->service, zh->reg);
1133     zh->reg = 0;
1134
1135     
1136     yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1137              zh->records_processed, zh->records_inserted,
1138              zh->records_updated, zh->records_deleted);
1139
1140     zebra_get_state (zh, &val, &seqno);
1141     if (val != 'd')
1142     {
1143         BFiles bfs = bfs_create (rval, zh->path_reg);
1144         yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1145         bf_commitClean (bfs, rval);
1146         bfs_destroy (bfs);
1147     }
1148     if (!rval)
1149         seqno++;
1150     zebra_set_state (zh, 'o', seqno);
1151
1152     zebra_unlock (zh->lock_shadow);
1153     zebra_unlock (zh->lock_normal);
1154
1155 #if HAVE_SYS_TIMES_H
1156     times (&zh->tms2);
1157     logf (LOG_LOG, "user/system: %ld/%ld",
1158                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1159                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1160
1161 #endif
1162 }
1163
1164 void zebra_repository_update (ZebraHandle zh)
1165 {
1166     zebra_begin_trans (zh);
1167     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1168     repositoryUpdate (zh);    
1169     zebra_end_trans (zh);
1170 }
1171
1172 void zebra_repository_delete (ZebraHandle zh)
1173 {
1174     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1175     repositoryDelete (zh);
1176 }
1177
1178 void zebra_repository_show (ZebraHandle zh)
1179 {
1180     repositoryShow (zh);
1181 }
1182
1183 int zebra_commit (ZebraHandle zh)
1184 {
1185     int seqno;
1186     char val;
1187     const char *rval;
1188     BFiles bfs;
1189
1190     if (!zh->res)
1191     {
1192         zh->errCode = 109;
1193         return -1;
1194     }
1195     rval = res_get (zh->res, "shadow");    
1196     if (!rval)
1197     {
1198         logf (LOG_WARN, "Cannot perform commit");
1199         logf (LOG_WARN, "No shadow area defined");
1200         return 0;
1201     }
1202
1203     zebra_lock_w (zh->lock_normal);
1204     zebra_lock_r (zh->lock_shadow);
1205
1206     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1207
1208     zebra_get_state (zh, &val, &seqno);
1209
1210     if (rval && *rval)
1211         bf_cache (bfs, rval);
1212     if (bf_commitExists (bfs))
1213     {
1214         zebra_set_state (zh, 'c', seqno);
1215
1216         logf (LOG_LOG, "commit start");
1217         bf_commitExec (bfs);
1218 #ifndef WIN32
1219         sync ();
1220 #endif
1221         logf (LOG_LOG, "commit clean");
1222         bf_commitClean (bfs, rval);
1223         seqno++;
1224         zebra_set_state (zh, 'o', seqno);
1225     }
1226     else
1227     {
1228         logf (LOG_LOG, "nothing to commit");
1229     }
1230     bfs_destroy (bfs);
1231
1232     zebra_unlock (zh->lock_shadow);
1233     zebra_unlock (zh->lock_normal);
1234     return 0;
1235 }
1236
1237 int zebra_init (ZebraHandle zh)
1238 {
1239     const char *rval;
1240     BFiles bfs = 0;
1241
1242     if (!zh->res)
1243     {
1244         zh->errCode = 109;
1245         return -1;
1246     }
1247     rval = res_get (zh->res, "shadow");
1248
1249     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1250                       zh->path_reg);
1251     if (rval && *rval)
1252         bf_cache (bfs, rval);
1253     
1254     bf_reset (bfs);
1255     bfs_destroy (bfs);
1256     zebra_set_state (zh, 'o', 0);
1257     return 0;
1258 }
1259
1260 int zebra_compact (ZebraHandle zh)
1261 {
1262     BFiles bfs;
1263     if (!zh->res)
1264     {
1265         zh->errCode = 109;
1266         return -1;
1267     }
1268     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1269     inv_compact (bfs);
1270     bfs_destroy (bfs);
1271     return 0;
1272 }
1273
1274 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1275 {
1276     int sysno = 0;
1277     zebra_begin_trans (zh);
1278     extract_rec_in_mem (zh, "grs.sgml",
1279                         buf, len,
1280                         "Default",  /* database */
1281                         0 /* delete_flag */,
1282                         0 /* test_mode */,
1283                         &sysno /* sysno */,
1284                         1 /* store_keys */,
1285                         1 /* store_data */,
1286                         0 /* match criteria */);
1287     zebra_end_trans (zh);
1288     return sysno;
1289 }
1290
1291 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1292 {
1293     memcpy (&zh->rGroup, rg, sizeof(*rg));
1294 }
1295
1296 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1297 {
1298     *code = zh->errCode;
1299     *addinfo = zh->errString;
1300 }
1301
1302 void zebra_shadow_enable (ZebraHandle zh, int value)
1303 {
1304     zh->shadow_enable = value;
1305 }
1306