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