f86abad1fee9c25b10d56d5c813cd57d0f733689
[idzebra-moved-to-github.git] / index / zebrash.c
1 /* zebrash.c - command-line interface to zebra API 
2  *  $Id: zebrash.c,v 1.13 2003-06-23 15:38:16 adam 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     if (!db)
290         db="Default";
291     strcat(outbuff,"Creating database ");
292     strcat(outbuff,db);
293     strcat(outbuff,"\n");
294         
295     return zebra_create_database(zh, db);
296 }
297
298 static int cmd_begin_trans( char *args[], char *outbuff)
299 {
300     int rw=0;
301     if (args[1] && ( (args[1][0]=='1') || (args[1][0]=='w') ))
302         rw=1;
303     return zebra_begin_trans(zh,rw);
304 }
305 static int cmd_end_trans( char *args[], char *outbuff)
306 {
307     return zebra_end_trans(zh);
308 }
309 /*************************************
310  * Inserting and deleting
311  */
312
313 static int cmd_record_insert( char *args[], char *outbuff)
314 {
315     int sysno=0;
316     char buf[MAX_ARG_LEN];
317     int i;
318     int rc;
319     
320     i=1;
321     buf[0]='\0';
322     while (args[i])
323     {
324         strcat(buf, args[i++]);
325         strcat(buf, " ");
326     }
327     rc=zebra_record_insert(zh,buf, strlen(buf), &sysno);
328     if (0==rc)
329     {
330         sprintf(buf,"ok sysno=%d\n",sysno);
331         strcat(outbuff,buf);
332     }
333     return rc;
334 }
335
336
337 static int cmd_exchange_record( char *args[], char *outbuff)
338 {
339     char *base=args[1];
340     char *id = args[2];
341     char *action = args[3];
342     int i=4;
343     int rc;
344     char buf[MAX_ARG_LEN];
345     if (!(base && id && action && args[4] ))
346     {
347         strcat(outbuff,"Missing arguments!\n");
348         onecommand("help exchange_record", outbuff, "");
349         return -90;
350     }
351     while (args[i])
352     {
353         strcat(buf, args[i++]);
354         strcat(buf, " ");
355     }
356     rc=zebra_admin_exchange_record(zh, base, buf, strlen(buf),
357         id, strlen(id), atoi(action));
358     return rc;
359 }
360
361
362 /**************************************)
363  * Command table, parser, and help 
364  */
365
366 struct cmdstruct
367 {
368     char * cmd;
369     char * args;
370     char * explanation;
371     int (*testfunc)(char *args[], char *outbuff);
372 } ;
373
374  
375 struct cmdstruct cmds[] = {
376     /* special cases:
377      *   if text is 0, does not list the command
378      *   if cmd is "", adds the args (and newline) in command listing
379      */
380     { "", "Starting and stopping:", "", 0 },
381     { "zebra_start", 
382       "[configfile]", 
383       "starts the zebra service. You need to call this first\n"
384       "if no configfile is given, assumes " DEFAULTCONFIG, 
385       cmd_zebra_start },
386     { "zebra_stop",   "", 
387       "stops the zebra service", 
388       cmd_zebra_stop },
389     { "zebra_open", "",  
390       "starts a zebra session. Once you have called zebra_start\n"
391       "you can call zebra_open to start working", 
392       cmd_zebra_open },
393     { "zebra_close", "", 
394       "closes a zebra session", 
395       cmd_zebra_close }, 
396     { "quickstart", "[configfile]", 
397       "Does a zebra_start, zebra_open, and sets up the log", 
398       cmd_quickstart }, 
399   
400     { "", "Log file:","", 0},  
401     { "yaz_log_file", 
402       "[filename]",
403       "Directs the log to filename (or stderr)",
404       cmd_yaz_log_file },
405     { "yaz_log_level", 
406       "[level]",
407       "Sets the logging level (or returns to default)",
408       cmd_yaz_log_level },
409     { "yaz_log_prefix", 
410       "[prefix]",
411       "Sets the log prefix",
412       cmd_yaz_log_prefix},    
413     { "logf", 
414       "[level] text...",
415       "writes an entry in the log",
416       cmd_logf},    
417
418     { "", "Error handling:","", 0},
419     { "err",  "",
420       "Displays zebra's error status (code, str, add)",
421       cmd_err},    
422     { "errcode",  "",
423       "Displays zebra's error code",
424       cmd_errcode},    
425     { "errstr",  "",
426       "Displays zebra's error string",
427       cmd_errstr},    
428     { "erradd",  "",
429       "Displays zebra's additional error message",
430       cmd_erradd},    
431   
432     { "", "Admin:","", 0}, 
433     { "init",  "",
434       "Initializes the zebra database, destroying all data in it",
435       cmd_init},    
436     { "select_database",  "basename",
437       "Selects a database",
438       cmd_select_database},    
439     { "create_database", "basename",
440       "Creates a database",
441       cmd_create_database},
442     { "begin_trans", "[rw]",
443       "Begins a transaction. rw=1 means write, otherwise read-only",
444       cmd_begin_trans},
445     { "end_trans","",
446       "Ends a transaction",
447       cmd_end_trans},
448
449     { "","Updating:","",0},
450     { "record_insert","record",
451       "inserts an sgml record into Default",
452       cmd_record_insert},
453     { "exchange_record","database record-id action record",
454       "inserts (1), updates (2), or deletes (3) a record \n"
455       "record-id must be a unique identifier for the record",
456       cmd_exchange_record},
457     { "", "Misc:","", 0}, 
458     { "echo", "string", 
459       "ouputs the string", 
460       cmd_echo },
461     { "quit", "", 
462       "exits the program", 
463       cmd_quit },
464     { "help", "[command]", 
465       "Gives help on command, or lists them all", 
466       cmd_help },
467     { "", "help [command] gives more info on command", "",0 },   
468   
469     {0,0,0,0} /* end marker */
470 };
471  
472 int onecommand( 
473                 char *line,     /* input line */
474                 char *outbuff,  /* output goes here */
475                 const char *prevout) /* prev output, for 'expect' */
476 {
477     int i;
478     char *args[MAX_NO_ARGS];
479     int n;
480     char argbuf[MAX_ARG_LEN];
481     logf(LOG_APP,"%s",line);
482     strncpy(argbuf,line, MAX_ARG_LEN-1);
483     argbuf[MAX_ARG_LEN-1]='\0'; /* just to be sure */
484     n=split_args(argbuf, args);
485
486 #if 0
487     for (i = 0; i <= n; i++)
488     {
489         const char *cp = args[i];
490         printf ("args %d :%s:\n", i, cp ? cp : "<null>");
491     }
492 #endif
493     if (0==n)
494         return -90; /* no command on line, too bad */
495
496     if (0==strcmp(args[0],"expect")) 
497     {
498         char *rest;
499         if (n>1)
500             rest= line + (args[1]-argbuf); /* rest of the line */
501         else
502             return -1; /* need something to expect */
503         printf("expecting '%s'\n",rest); /*!*/
504         if (0==strstr(prevout,rest))
505         {
506             printf( "Failed expectation, '%s' not found\n", rest);
507             exit(9); 
508         }
509         return 0;
510     }
511     for (i=0;cmds[i].cmd;i++)
512         if (0==strcmp(cmds[i].cmd, args[0])) 
513         {
514             if (n>1)
515                 args[0]= line + (args[1]-argbuf); /* rest of the line */
516             else
517                 args[0]=""; 
518             return ((cmds[i].testfunc)(args,outbuff));
519         }
520     strcat(outbuff, "Unknown command '");
521     strcat(outbuff,args[0] );
522     strcat(outbuff,"'. Try help");
523     logf(LOG_APP,"Unknown command");
524     return -90; 
525 }
526  
527 static int cmd_help( char *args[], char *outbuff)
528
529     int i;
530     char tmp[MAX_ARG_LEN];
531     if (args[1]) 
532     { /* help for a single command */ 
533         for (i=0;cmds[i].cmd;i++)
534             if (0==strcmp(cmds[i].cmd, args[1])) 
535             {
536                 strcat(outbuff,cmds[i].cmd);
537                 strcat(outbuff,"  ");
538                 strcat(outbuff,cmds[i].args);
539                 strcat(outbuff,"\n");
540                 strcat(outbuff,cmds[i].explanation);
541                 strcat(outbuff,"\n");
542                 return 0;
543             }
544         strcat(outbuff, "Unknown command ");
545         strcat(outbuff, args[1] );
546     }
547     else 
548     { /* list all commands */
549         strcpy(tmp,"    ");
550         for (i=0;cmds[i].cmd;i++)
551             if (cmds[i].explanation)
552             {
553                 /* sprintf(tmp, "%s %s %s\n",
554                    cmds[i].cmd, cmds[i].args, cmds[i].explanation);
555                 */
556                 strcat(tmp, cmds[i].cmd);
557                 strcat(tmp,"  ");
558                 if (!*cmds[i].cmd)
559                 {
560                     strcat(outbuff, tmp);
561                     strcat(outbuff,"\n");
562                     strcpy(tmp,"    ");
563                     if (*cmds[i].args)
564                     {
565                         strcat(outbuff, cmds[i].args);
566                         strcat(outbuff,"\n");
567                     }
568                 }
569                 if (strlen(tmp)>50)
570                 {
571                     strcat(outbuff,tmp);
572                     strcat(outbuff,"\n");
573                     strcpy(tmp,"    ");
574                 }
575             }
576         strcat(outbuff,tmp);
577     }
578     return 0;
579 }
580  
581 /* If Zebra reports an error after an operation,
582  * append it to the outbuff and log it */
583 static void Zerrors ( char *outbuff)
584 {
585     int ec;
586     char tmp[MAX_OUT_BUFF];
587     if (!zh)
588         return ;
589     ec=zebra_errCode (zh);
590     if (ec)
591     {
592         sprintf(tmp, "   Zebra error %d: %s, (%s)",
593                 ec, zebra_errString (zh),
594                 zebra_errAdd (zh) );
595         strcat(outbuff, tmp);
596         strcat(outbuff, "\n");
597         logf(LOG_APP, tmp);
598         zebra_clearError(zh);
599     }
600 }
601   
602 /************************************** 
603  * The shell
604  */
605  
606 void shell()
607 {
608     int rc=0;
609     char tmp[MAX_ARG_LEN];
610     char outbuff[MAX_OUT_BUFF]="";
611     char prevout[MAX_OUT_BUFF]=""; /* previous output for 'expect' */
612     while (rc!=-99)
613     {
614         char buf[MAX_ARG_LEN];
615 #if HAVE_READLINE_READLINE_H
616         char* line_in;
617         line_in=readline(PROMPT);
618         if (!line_in)
619             break;
620 #if HAVE_READLINE_HISTORY_H
621         if (*line_in)
622             add_history(line_in);
623 #endif
624         if(strlen(line_in) > MAX_ARG_LEN-1) {
625             fprintf(stderr,"Input line too long\n");
626             break;
627         };
628         strcpy(buf,line_in);
629         free (line_in);
630 #else    
631         printf (PROMPT); 
632         fflush (stdout);
633         if (!fgets (buf, MAX_ARG_LEN-1, stdin))
634             break; 
635 #endif 
636         
637         strncpy(prevout, outbuff, MAX_OUT_BUFF);
638         outbuff[0]='\0';
639         rc=onecommand(buf, outbuff, prevout);
640         if (rc==0)
641         {
642             strcat(outbuff, "   OK\n");
643             logf(LOG_APP, "OK");
644         }
645         else if (rc>-90)
646         {
647             sprintf(tmp, "   command returned %d\n",rc);
648             strcat(outbuff,tmp);
649         } 
650         Zerrors(outbuff);
651         printf("%s\n", outbuff);
652     } /* while */
653 } /* shell() */
654   
655  
656 /**************************************
657  * Main 
658  */
659  
660 int main (int argc, char ** args)
661 {
662     shell();
663     return 0;
664 } /* main */