insert/delete tests in zebrash, transactions...
[idzebra-moved-to-github.git] / index / zebrash.c
1 /* zebrash.c - command-line interface to zebra API 
2  *  $Id: zebrash.c,v 1.11 2003-06-23 14:35:41 heikki Exp $
3  *
4  * Copyrigth 2003 Index Data Aps
5  *
6  */
7  
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h> 
11 #include <ctype.h>
12
13 #if HAVE_READLINE_READLINE_H
14 #include <readline/readline.h> 
15 #endif
16 #if HAVE_READLINE_HISTORY_H
17 #include <readline/history.h>
18 #endif
19
20 #include "zebraapi.h"
21 #include <yaz/log.h>
22
23 #define MAX_NO_ARGS 32
24 #define MAX_OUT_BUFF 4096
25 #define MAX_ARG_LEN 1024
26 #define PROMPT "ZebraSh>"
27 #define DEFAULTCONFIG "./zebra.cfg"
28
29 /**************************************
30  * Global variables (yuck!)
31  */
32
33 ZebraService zs=0;  /* our global handle to zebra */
34 ZebraHandle  zh=0;  /* the current session */
35 /* time being, only one session works */
36
37 /**************************************
38  * Help functions
39  */
40
41  
42 static int split_args( char *line, char** args )
43 { /* splits line into individual null-terminated strings, 
44    * returns pointers to them in args */
45   /* FIXME - do we need to handle quoted args ?? */
46     char *p=line;
47     int i=0;
48     int n=0;
49     args[0]=0; /* by default */
50     while (*p==' ' || *p=='\t' || *p=='\n')
51         p++;
52     while (*p)
53     {
54         while (*p==' ' || *p=='\t' || *p=='\n')
55             p++;
56         if (*p=='#')  /* skip comments */
57             break;  
58         args[i++]=p;
59         args[i]=0;
60         while (*p && *p!=' ' && *p!='\t' && *p!='\n' && *p!='#')
61             p++;
62         *p++='\0';
63     }
64     n=i;
65     while (n<MAX_NO_ARGS)
66         args[n++]=0;
67     return i;
68 }
69
70 static char *defarg( char *arg, char *def )
71 {
72     if (!arg)
73         return def;
74     if (!*arg)
75         return def;
76     return arg;
77 }
78 static int defargint( char *arg, int def )
79 {
80     int v=def;
81     char *a=defarg(arg,0);
82     if (a)
83         sscanf(a," %i", &v);
84     return v;
85 }
86
87 int onecommand( char *line, char *outbuff, const char *prevout); 
88  
89 /**************************************
90  * Simple support commands
91  */
92
93 int cmd_echo( char *args[], char *outbuff)
94 {
95     strcpy(outbuff, args[0]);
96     return 0;
97 }
98  
99 int cmd_quit( char *args[], char *outbuff)
100 {
101     strcpy(outbuff, "bye");
102     return -99; /* special stop signal */
103 }
104
105 /**************************************
106  * Tests for starting and stopping zebra, etc
107  */
108  
109 static int cmd_help( char *args[], char *outbuff); 
110  
111 static int cmd_zebra_start( char *args[], char *outbuff)
112 {
113     char *conf=args[1];
114     if (!conf || !*conf) {
115         strcat(outbuff,"no config file specified, using "
116                DEFAULTCONFIG "\n" );
117         conf=DEFAULTCONFIG;
118     }
119     zs=zebra_start(conf);
120     if (!zs) {
121         strcpy(outbuff, "zebra_start failed" );
122         return 2;
123     }
124     return 0; /* ok */
125 }
126  
127 static int cmd_zebra_stop( char *args[], char *outbuff)
128 {
129     if (!zs)
130         strcat(outbuff,"zebra seems not to have been started, "
131                "stopping anyway\n");
132     zebra_stop(zs);
133     zs=0;
134     return 0; /* ok */
135 }
136
137 static int cmd_zebra_open( char *args[], char *outbuff)
138 {
139     if (!zs)
140         strcat(outbuff,"zebra seems not to have been started, "
141                "trying anyway\n");
142     zh=zebra_open(zs);
143     return 0; /* ok */
144 }
145
146 static int cmd_zebra_close( char *args[], char *outbuff)
147 {
148     if (!zh)
149         strcat(outbuff,"Seems like you have not called zebra_open,"
150                "trying anyway\n");
151     zebra_close(zh);
152     return 0; /* ok */
153 }
154
155 static int cmd_quickstart( char *args[], char *outbuff)
156 {
157     char tmp[128];
158     int rc=0;
159     if (!rc)
160         rc=onecommand("yaz_log_file zebrash.log",outbuff,"");
161     if (!rc)
162         rc=onecommand("yaz_log_prefix ZebraSh", outbuff,"");
163     sprintf(tmp, "yaz_log_level 0x%x", LOG_DEFAULT_LEVEL | LOG_APP);
164     if (!rc)
165         rc=onecommand(tmp,outbuff,"");
166     logf(LOG_APP,"quickstart");
167     if (!rc)
168         rc=onecommand("zebra_start",outbuff,"");
169     if (!rc)
170         rc=onecommand("zebra_open",outbuff,"");
171     if (!rc)
172         rc=onecommand("select_database Default",outbuff,"");
173     return rc;
174 }
175
176 /**************************************
177  * Log file handling
178  */
179
180 static int cmd_yaz_log_file( char *args[], char *outbuff)
181 {
182     char *fn = defarg(args[1],0);
183     char tmp[255];
184     sprintf(tmp, "sending yaz-log to %s\n",fn);
185     strcat(outbuff, tmp);
186     yaz_log_init_file(fn);
187     return 0; /* ok */
188 }
189
190 static int cmd_yaz_log_level( char *args[], char *outbuff)
191 {
192     int  lev = defargint(args[1],LOG_DEFAULT_LEVEL);
193     char tmp[255];
194     sprintf(tmp, "setting yaz-log to level %d (ox%x)\n",lev,lev);
195     strcat(outbuff, tmp);
196     yaz_log_init_level(lev);
197     return 0; /* ok */
198 }
199
200 static int cmd_yaz_log_prefix( char *args[], char *outbuff)
201 {
202     char *pref = defarg(args[1],"ZebraSh");
203     char tmp[255];
204     sprintf(tmp, "setting yaz-log prefix to %s\n",pref);
205     strcat(outbuff, tmp);
206     yaz_log_init_prefix(pref);
207     return 0; /* ok */
208 }
209
210 static int cmd_logf( char *args[], char *outbuff)
211 {
212     int lev = defargint(args[1],0);
213     char tmp[MAX_OUT_BUFF]="";
214     int i=1;
215     if (lev)
216         i=2;
217     else
218         lev=LOG_LOG; /* this is in the default set!*/
219     while (args[i])
220     {
221         strcat(tmp, args[i++]);
222         strcat(tmp, " ");
223     }
224     logf(lev,tmp);
225     return 0; /* ok */
226 }
227  
228 /****************
229  * Error handling 
230  */
231 static int cmd_err ( char *args[], char *outbuff)
232 {
233     char tmp[MAX_OUT_BUFF];
234     sprintf(tmp, "errCode: %d \nerrStr:  %s\nerrAdd:  %s \n",
235             zebra_errCode (zh),
236             zebra_errString (zh),  
237             zebra_errAdd (zh) );
238     strcat(outbuff, tmp);
239     return 0; /* ok */
240 }
241 static int cmd_errcode ( char *args[], char *outbuff)
242 {
243     char tmp[MAX_OUT_BUFF];
244     sprintf(tmp, "errCode: %d \n",
245             zebra_errCode (zh));
246     strcat(outbuff, tmp);
247     return 0; /* ok */
248 }
249 static int cmd_errstr ( char *args[], char *outbuff)
250 {
251     char tmp[MAX_OUT_BUFF];
252     sprintf(tmp, "errStr:  %s\n",
253             zebra_errString (zh));
254     strcat(outbuff, tmp);
255     return 0; /* ok */
256 }
257 static int cmd_erradd ( char *args[], char *outbuff)
258 {
259     char tmp[MAX_OUT_BUFF];
260     sprintf(tmp, "errAdd:  %s \n",
261             zebra_errAdd (zh) ); 
262     strcat(outbuff, tmp);
263     return 0; /* ok */
264 }
265
266 /**************************************
267  * Admin commands
268  */
269
270 static int cmd_init ( char *args[], char *outbuff)
271 {
272     zebra_init(zh);
273     return 0; /* ok */
274 }
275
276 static int cmd_select_database ( char *args[], char *outbuff)
277 {
278     char *db=args[1];
279     if (!db) {
280         db="Default";
281         strcat(outbuff,"Selecting database 'Default'\n");
282     }
283     return zebra_select_database(zh, db);
284 }
285  
286 static int cmd_create_database( char *args[], char *outbuff)
287 {
288     char *db=args[1];
289         int rc;
290     if (!db)
291         db="Default";
292     strcat(outbuff,"Creating database ");
293     strcat(outbuff,db);
294     strcat(outbuff,"\n");
295         
296     return zebra_create_database(zh, db);
297 }
298
299 static int cmd_begin_trans( char *args[], char *outbuff)
300 {
301     int rw=0;
302     if (args[1] && ( (args[1][0]=='1') || (args[1][0]=='w') ))
303         rw=1;
304     return zebra_begin_trans(zh,rw);
305 }
306 static int cmd_end_trans( char *args[], char *outbuff)
307 {
308     return zebra_end_trans(zh);
309 }
310 /*************************************
311  * Inserting and deleting
312  */
313
314 static int cmd_record_insert( char *args[], char *outbuff)
315 {
316     int sysno=0;
317     char buf[MAX_ARG_LEN];
318     int i;
319     int rc;
320     
321     i=1;
322     buf[0]='\0';
323     while (args[i])
324     {
325         strcat(buf, args[i++]);
326         strcat(buf, " ");
327     }
328     rc=zebra_record_insert(zh,buf, strlen(buf), &sysno);
329     if (0==rc)
330     {
331         sprintf(buf,"ok sysno=%d\n",sysno);
332         strcat(outbuff,buf);
333     }
334     return rc;
335 }
336
337
338 static int cmd_exchange_record( char *args[], char *outbuff)
339 {
340     char *base=args[1];
341     char *id = args[2];
342     char *action = args[3];
343     int i=4;
344     int rc;
345     char buf[MAX_ARG_LEN];
346     if (!(base && id && action && args[4] ))
347     {
348         strcat(outbuff,"Missing arguments!\n");
349         onecommand("help exchange_record", outbuff, "");
350         return -90;
351     }
352     while (args[i])
353     {
354         strcat(buf, args[i++]);
355         strcat(buf, " ");
356     }
357     rc=zebra_admin_exchange_record(zh, base, buf, strlen(buf),
358         id, strlen(id), atoi(action));
359     return rc;
360 }
361
362
363 /**************************************)
364  * Command table, parser, and help 
365  */
366
367 struct cmdstruct
368 {
369     char * cmd;
370     char * args;
371     char * explanation;
372     int (*testfunc)(char *args[], char *outbuff);
373 } ;
374
375  
376 struct cmdstruct cmds[] = {
377     /* special cases:
378      *   if text is 0, does not list the command
379      *   if cmd is "", adds the args (and newline) in command listing
380      */
381     { "", "Starting and stopping:", "", 0 },
382     { "zebra_start", 
383       "[configfile]", 
384       "starts the zebra service. You need to call this first\n"
385       "if no configfile is given, assumes " DEFAULTCONFIG, 
386       cmd_zebra_start },
387     { "zebra_stop",   "", 
388       "stops the zebra service", 
389       cmd_zebra_stop },
390     { "zebra_open", "",  
391       "starts a zebra session. Once you have called zebra_start\n"
392       "you can call zebra_open to start working", 
393       cmd_zebra_open },
394     { "zebra_close", "", 
395       "closes a zebra session", 
396       cmd_zebra_close }, 
397     { "quickstart", "[configfile]", 
398       "Does a zebra_start, zebra_open, and sets up the log", 
399       cmd_quickstart }, 
400   
401     { "", "Log file:","", 0},  
402     { "yaz_log_file", 
403       "[filename]",
404       "Directs the log to filename (or stderr)",
405       cmd_yaz_log_file },
406     { "yaz_log_level", 
407       "[level]",
408       "Sets the logging level (or returns to default)",
409       cmd_yaz_log_level },
410     { "yaz_log_prefix", 
411       "[prefix]",
412       "Sets the log prefix",
413       cmd_yaz_log_prefix},    
414     { "logf", 
415       "[level] text...",
416       "writes an entry in the log",
417       cmd_logf},    
418
419     { "", "Error handling:","", 0},
420     { "err",  "",
421       "Displays zebra's error status (code, str, add)",
422       cmd_err},    
423     { "errcode",  "",
424       "Displays zebra's error code",
425       cmd_errcode},    
426     { "errstr",  "",
427       "Displays zebra's error string",
428       cmd_errstr},    
429     { "erradd",  "",
430       "Displays zebra's additional error message",
431       cmd_erradd},    
432   
433     { "", "Admin:","", 0}, 
434     { "init",  "",
435       "Initializes the zebra database, destroying all data in it",
436       cmd_init},    
437     { "select_database",  "basename",
438       "Selects a database",
439       cmd_select_database},    
440     { "create_database", "basename",
441       "Creates a database",
442       cmd_create_database},
443     { "begin_trans", "[rw]",
444       "Begins a transaction. rw=1 means write, otherwise read-only",
445       cmd_begin_trans},
446     { "end_trans","",
447       "Ends a transaction",
448       cmd_end_trans},
449
450     { "","Updating:","",0},
451     { "record_insert","record",
452       "inserts an sgml record into Default",
453       cmd_record_insert},
454     { "exchange_record","database record-id action record",
455       "inserts (1), updates (2), or deletes (3) a record \n"
456       "record-id must be a unique identifier for the record",
457       cmd_exchange_record},
458     { "", "Misc:","", 0}, 
459     { "echo", "string", 
460       "ouputs the string", 
461       cmd_echo },
462     { "quit", "", 
463       "exits the program", 
464       cmd_quit },
465     { "help", "[command]", 
466       "Gives help on command, or lists them all", 
467       cmd_help },
468     { "", "help [command] gives more info on command", "",0 },   
469   
470     {0,0,0,0} /* end marker */
471 };
472  
473 int onecommand( 
474                 char *line,     /* input line */
475                 char *outbuff,  /* output goes here */
476                 const char *prevout) /* prev output, for 'expect' */
477 {
478     int i;
479     char *args[MAX_NO_ARGS];
480     int n;
481     char argbuf[MAX_ARG_LEN];
482     logf(LOG_APP,"%s",line);
483     strncpy(argbuf,line, MAX_ARG_LEN-1);
484     argbuf[MAX_ARG_LEN-1]='\0'; /* just to be sure */
485     n=split_args(argbuf, args);
486
487 #if 0
488     for (i = 0; i <= n; i++)
489     {
490         const char *cp = args[i];
491         printf ("args %d :%s:\n", i, cp ? cp : "<null>");
492     }
493 #endif
494     if (0==n)
495         return -90; /* no command on line, too bad */
496
497     if (0==strcmp(args[0],"expect")) 
498     {
499         char *rest;
500         if (n>1)
501             rest= line + (args[1]-argbuf); /* rest of the line */
502         else
503             return -1; /* need something to expect */
504         printf("expecting '%s'\n",rest); /*!*/
505         if (0==strstr(prevout,rest))
506         {
507             printf( "Failed expectation, '%s' not found\n");
508             exit(9); 
509         }
510         return 0;
511     }
512     for (i=0;cmds[i].cmd;i++)
513         if (0==strcmp(cmds[i].cmd, args[0])) 
514         {
515             if (n>1)
516                 args[0]= line + (args[1]-argbuf); /* rest of the line */
517             else
518                 args[0]=""; 
519             return ((cmds[i].testfunc)(args,outbuff));
520         }
521     strcat(outbuff, "Unknown command '");
522     strcat(outbuff,args[0] );
523     strcat(outbuff,"'. Try help");
524     logf(LOG_APP,"Unknown command");
525     return -90; 
526 }
527  
528 static int cmd_help( char *args[], char *outbuff)
529
530     int i;
531     char tmp[MAX_ARG_LEN];
532     if (args[1]) 
533     { /* help for a single command */ 
534         for (i=0;cmds[i].cmd;i++)
535             if (0==strcmp(cmds[i].cmd, args[1])) 
536             {
537                 strcat(outbuff,cmds[i].cmd);
538                 strcat(outbuff,"  ");
539                 strcat(outbuff,cmds[i].args);
540                 strcat(outbuff,"\n");
541                 strcat(outbuff,cmds[i].explanation);
542                 strcat(outbuff,"\n");
543                 return 0;
544             }
545         strcat(outbuff, "Unknown command ");
546         strcat(outbuff, args[1] );
547     }
548     else 
549     { /* list all commands */
550         strcpy(tmp,"    ");
551         for (i=0;cmds[i].cmd;i++)
552             if (cmds[i].explanation)
553             {
554                 /* sprintf(tmp, "%s %s %s\n",
555                    cmds[i].cmd, cmds[i].args, cmds[i].explanation);
556                 */
557                 strcat(tmp, cmds[i].cmd);
558                 strcat(tmp,"  ");
559                 if (!*cmds[i].cmd)
560                 {
561                     strcat(outbuff, tmp);
562                     strcat(outbuff,"\n");
563                     strcpy(tmp,"    ");
564                     if (*cmds[i].args)
565                     {
566                         strcat(outbuff, cmds[i].args);
567                         strcat(outbuff,"\n");
568                     }
569                 }
570                 if (strlen(tmp)>50)
571                 {
572                     strcat(outbuff,tmp);
573                     strcat(outbuff,"\n");
574                     strcpy(tmp,"    ");
575                 }
576             }
577         strcat(outbuff,tmp);
578     }
579     return 0;
580 }
581  
582 /* If Zebra reports an error after an operation,
583  * append it to the outbuff and log it */
584 static void Zerrors ( char *outbuff)
585 {
586     int ec;
587     char tmp[MAX_OUT_BUFF];
588     if (!zh)
589         return ;
590     ec=zebra_errCode (zh);
591     if (ec)
592     {
593         sprintf(tmp, "   Zebra error %d: %s, (%s)",
594                 ec, zebra_errString (zh),
595                 zebra_errAdd (zh) );
596         strcat(outbuff, tmp);
597         strcat(outbuff, "\n");
598         logf(LOG_APP, tmp);
599         zebra_clearError(zh);
600     }
601 }
602   
603 /************************************** 
604  * The shell
605  */
606  
607 void shell()
608 {
609     int rc=0;
610     char tmp[MAX_ARG_LEN];
611     char outbuff[MAX_OUT_BUFF]="";
612     char prevout[MAX_OUT_BUFF]=""; /* previous output for 'expect' */
613     while (rc!=-99)
614     {
615         char buf[MAX_ARG_LEN];
616 #if HAVE_READLINE_READLINE_H
617         char* line_in;
618         line_in=readline(PROMPT);
619         if (!line_in)
620             break;
621 #if HAVE_READLINE_HISTORY_H
622         if (*line_in)
623             add_history(line_in);
624 #endif
625         if(strlen(line_in) > MAX_ARG_LEN-1) {
626             fprintf(stderr,"Input line too long\n");
627             break;
628         };
629         strcpy(buf,line_in);
630         free (line_in);
631 #else    
632         printf (PROMPT); 
633         fflush (stdout);
634         if (!fgets (buf, MAX_ARG_LEN-1, stdin))
635             break; 
636 #endif 
637         
638         strncpy(prevout, outbuff, MAX_OUT_BUFF);
639         outbuff[0]='\0';
640         rc=onecommand(buf, outbuff, prevout);
641         if (rc==0)
642         {
643             strcat(outbuff, "   OK\n");
644             logf(LOG_APP, "OK");
645         }
646         else if (rc>-90)
647         {
648             sprintf(tmp, "   command returned %d\n",rc);
649             strcat(outbuff,tmp);
650         } 
651         Zerrors(outbuff);
652         printf("%s\n", outbuff);
653     } /* while */
654 } /* shell() */
655   
656  
657 /**************************************
658  * Main 
659  */
660  
661 int main (int argc, char ** args)
662 {
663     shell();
664     return 0;
665 } /* main */