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