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