Whamcloud - gitweb
- Added lctl.c which is basically ptlctl/obdctl/debugctl all
[fs/lustre-release.git] / lustre / utils / parser.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Copyright (C) 2001 Cluster File Systems, Inc.
5  *
6  *   This file is part of Lustre, http://www.sf.net/projects/lustre/
7  *
8  *   Lustre is free software; you can redistribute it and/or
9  *   modify it under the terms of version 2 of the GNU General Public
10  *   License as published by the Free Software Foundation.
11  *
12  *   Lustre is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with Lustre; if not, write to the Free Software
19  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <stddef.h>
27 #include <sys/param.h>
28 #include <assert.h>
29
30 #define READLINE_LIBRARY
31 #include <readline/readline.h>
32
33 //extern char **completion_matches __P((char *, rl_compentry_func_t *));
34 extern void using_history(void);
35 extern void stifle_history(int);
36 extern void add_history(char *);
37
38 #include "parser.h"
39
40 static command_t * top_level;           /* Top level of commands, initialized by
41                                     * InitParser                              */
42 static command_t * match_tbl;           /* Command completion against this table */
43 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser      */
44 static int done;                   /* Set to 1 if user types exit or quit   */
45
46
47 /* static functions */
48 static char *skipwhitespace(char *s);
49 static char *skiptowhitespace(char *s);
50 static command_t *find_cmd(char *name, command_t cmds[], char **next);
51 static int process(char *s, char **next, command_t *lookup, command_t **result, char **prev);
52 static char *command_generator(const char *text, int state);
53 static char **command_completion(char *text, int start, int end);
54 static void print_commands(char *str, command_t *table);
55
56 static char * skipwhitespace(char * s) 
57 {
58         char * t;
59         int    len;
60
61         len = (int)strlen(s);
62         for (t = s; t <= s + len && isspace(*t); t++);
63         return(t);
64 }
65
66
67 static char * skiptowhitespace(char * s) 
68 {
69         char * t;
70
71         for (t = s; *t && !isspace(*t); t++);
72         return(t);
73 }
74
75 static int line2args(char *line, char **argv, int maxargs)
76 {
77         char *arg;
78         int i = 0; 
79     
80         arg = strtok(line, " \t");
81         if ( arg ) {
82                 argv[i] = arg;
83                 i++;
84         } else 
85                 return 0;
86
87         while( (arg = strtok(NULL, " \t")) && (i <= maxargs)) {
88                 argv[i] = arg;
89                 i++;
90         }
91         return i;
92 }
93
94 /* find a command -- return it if unique otherwise print alternatives */
95 static command_t *Parser_findargcmd(char *name, command_t cmds[])
96 {
97         command_t *cmd;
98
99         for (cmd = cmds; cmd->pc_name; cmd++) {
100                 if (strcmp(name, cmd->pc_name) == 0)
101                         return cmd;
102         }
103         return NULL;
104 }
105
106 int Parser_execarg(int argc, char **argv, command_t cmds[])
107 {
108         command_t *cmd;
109
110         cmd = Parser_findargcmd(argv[0], cmds);
111         if ( cmd ) {
112                 return (cmd->pc_func)(argc, argv);
113         } else {
114                 printf("Try interactive use without arguments or use one of:\n");
115                 for (cmd = cmds; cmd->pc_name; cmd++)
116                         printf("\"%s\" ", cmd->pc_name);
117                 printf("\nas argument.\n");
118         }
119         return -1;
120 }
121
122 /* returns the command_t * (NULL if not found) corresponding to a
123    _partial_ match with the first token in name.  It sets *next to
124    point to the following token. Does not modify *name. */
125 static command_t * find_cmd(char * name, command_t cmds[], char ** next) 
126 {
127         int    i, len;
128     
129         if (!cmds || !name ) 
130                 return NULL;
131     
132         /* This sets name to point to the first non-white space character,
133            and next to the first whitespace after name, len to the length: do
134            this with strtok*/
135         name = skipwhitespace(name);
136         *next = skiptowhitespace(name);
137         len = *next - name;
138         if (len == 0) 
139                 return NULL;
140
141         for (i = 0; cmds[i].pc_name; i++) {
142                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
143                         *next = skipwhitespace(*next);
144                         return(&cmds[i]);
145                 }
146         }
147         return NULL;
148 }
149
150 /* Recursively process a command line string s and find the command
151    corresponding to it. This can be ambiguous, full, incomplete,
152    non-existent. */
153 static int process(char *s, char ** next, command_t *lookup,
154                    command_t **result, char **prev)
155 {
156         *result = find_cmd(s, lookup, next);
157         *prev = s; 
158
159         /* non existent */
160         if ( ! *result ) 
161                 return CMD_NONE;
162
163         /* found entry: is it ambigous, i.e. not exact command name and
164            more than one command in the list matches.  Note that find_cmd
165            points to the first ambiguous entry */
166         if ( strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name)) &&
167              find_cmd(s, (*result) + 1, next)) 
168                 return CMD_AMBIG;
169
170         /* found a unique command: component or full? */
171         if ( (*result)->pc_func ) {
172                 return CMD_COMPLETE;
173         } else {
174                 if ( *next == '\0' ) {
175                         return CMD_INCOMPLETE;
176                 } else {
177                         return process(*next, next, (*result)->pc_sub_cmd, result, prev);
178                 }
179         }
180 }
181
182 static char * command_generator(const char * text, int state) 
183 {
184         static int index,
185                 len;
186         char       *name;
187
188         /* Do we have a match table? */
189         if (!match_tbl) 
190                 return NULL;
191     
192         /* If this is the first time called on this word, state is 0 */
193         if (!state) {
194                 index = 0;
195                 len = (int)strlen(text);
196         }
197
198         /* Return the next name in the command list that paritally matches test */
199         while ( (name = (match_tbl + index)->pc_name) ) {
200                 index++;
201
202                 if (strncasecmp(name, text, len) == 0) {
203                         return(strdup(name));
204                 }
205         }
206
207         /* No more matches */
208         return NULL;
209 }
210
211 /* probably called by readline */
212 static char **command_completion(char * text, int start, int end) 
213 {
214         command_t         * table;
215         char        * pos;
216
217         match_tbl = top_level;
218         for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
219              table;
220              table = find_cmd(pos, match_tbl, &pos)) {
221
222                 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
223         }
224
225         return(completion_matches(text, command_generator));
226 }
227
228 /* take a string and execute the function or print help */
229 int execute_line(char * line)
230 {
231         command_t         *cmd, *ambig;
232         char *prev;
233         char *next, *tmp;
234         char *argv[MAXARGS];
235         int         i;
236         int rc = 0;
237
238         switch( process(line, &next, top_level, &cmd, &prev) ) {
239         case CMD_AMBIG:
240                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
241                 while( (ambig = find_cmd(prev, cmd, &tmp)) ) {
242                         fprintf(stderr, "%s ", ambig->pc_name);
243                         cmd = ambig + 1;
244                 }
245                 fprintf(stderr, "\n");
246                 break;
247         case CMD_NONE:
248                 fprintf(stderr, "No such command, type help\n");
249                 break;
250         case CMD_INCOMPLETE:
251                 fprintf(stderr,
252                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
253                         line, line);
254                 fprintf(stderr, "\t");
255                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++) {
256                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
257                 }
258                 fprintf(stderr, "\n");
259                 break;
260         case CMD_COMPLETE:
261                 i = line2args(line, argv, MAXARGS);
262                 rc = (cmd->pc_func)(i, argv);
263
264                 if (rc == CMD_HELP)
265                         fprintf(stderr, "%s\n", cmd->pc_help);
266
267                 break;
268         }
269
270         return rc;
271 }
272
273 /* this is the command execution machine */
274 int Parser_commands(void)
275 {
276         char *line, *s;
277         int rc = 0;
278
279         using_history();
280         stifle_history(HISTORY);
281
282         rl_attempted_completion_function = (CPPFunction *)command_completion;
283         rl_completion_entry_function = (void *)command_generator;
284
285         while(!done) {
286                 line = readline(parser_prompt);
287
288                 if (!line) break;
289
290                 s = skipwhitespace(line);
291
292                 if (*s) {
293                         add_history(s);
294                         rc = execute_line(s);
295                 }
296
297                 free(line);
298         }
299         return rc;
300 }
301
302
303 /* sets the parser prompt */
304 void Parser_init(char * prompt, command_t * cmds) 
305 {
306         done = 0;
307         top_level = cmds;
308         if (parser_prompt) free(parser_prompt);
309         parser_prompt = strdup(prompt);
310 }
311
312 /* frees the parser prompt */
313 void Parser_exit(int argc, char *argv[]) 
314 {
315         done = 1;
316         free(parser_prompt);
317         parser_prompt = NULL;
318 }
319
320 /* convert a string to an integer */
321 int Parser_int(char *s, int *val)
322 {
323         int ret;
324
325         if (*s != '0')
326                 ret = sscanf(s, "%d", val);
327         else if (*(s+1) != 'x')
328                 ret = sscanf(s, "%o", val);
329         else {
330                 s++;
331                 ret = sscanf(++s, "%x", val);
332         }
333
334         return(ret);
335 }
336
337
338 void Parser_qhelp(int argc, char *argv[]) {
339
340         printf("Available commands are:\n");
341
342         print_commands(NULL, top_level);
343         printf("For more help type: help command-name\n");
344 }
345
346 int Parser_help(int argc, char **argv) 
347 {
348         char line[1024];
349         char *next, *prev, *tmp;
350         command_t *result, *ambig;
351         int i;
352
353         if ( argc == 1 ) {
354                 Parser_qhelp(argc, argv);
355                 return 0;
356         }
357
358         line[0]='\0';
359         for ( i = 1 ;  i < argc ; i++ ) {
360                 strcat(line, argv[i]);
361         }
362
363         switch ( process(line, &next, top_level, &result, &prev) ) {
364         case CMD_COMPLETE:
365                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
366                 break;
367         case CMD_NONE:
368                 fprintf(stderr, "%s: Unknown command.\n", line);
369                 break;
370         case CMD_INCOMPLETE:
371                 fprintf(stderr,
372                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
373                         line, line);
374                 fprintf(stderr, "\t");
375                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
376                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
377                 }
378                 fprintf(stderr, "\n");
379                 break;
380         case CMD_AMBIG:
381                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
382                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
383                         fprintf(stderr, "%s ", ambig->pc_name);
384                         result = ambig + 1;
385                 }
386                 fprintf(stderr, "\n");
387                 break;
388         }
389         return 0;
390 }  
391
392
393 void Parser_printhelp(char *cmd)
394 {
395         char *argv[] = { "help", cmd }; 
396         Parser_help(2, argv);
397 }
398
399
400 /*************************************************************************
401  * COMMANDS                                                                 *
402  *************************************************************************/ 
403
404
405 static void print_commands(char * str, command_t * table) {
406         command_t * cmds;
407         char         buf[80];
408
409         for (cmds = table; cmds->pc_name; cmds++) {
410                 if (cmds->pc_func) {
411                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
412                         else printf("\t%s\n", cmds->pc_name);
413                 }
414                 if (cmds->pc_sub_cmd) {
415                         if (str) {
416                                 sprintf(buf, "%s %s", str, cmds->pc_name);
417                                 print_commands(buf, cmds->pc_sub_cmd);
418                         } else {
419                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
420                         }
421                 }
422         }
423 }
424
425 char *Parser_getstr(const char *prompt, const char *deft, char *res, 
426                     size_t len)
427 {
428         char *line = NULL;
429         int size = strlen(prompt) + strlen(deft) + 8;
430         char *theprompt;
431         theprompt = malloc(size);
432         assert(theprompt);
433
434         sprintf(theprompt, "%s [%s]: ", prompt, deft);
435
436         line  = readline(theprompt);
437         free(theprompt);
438
439         if ( line == NULL || *line == '\0' ) {
440                 strncpy(res, deft, len);
441         } else {
442                 strncpy(res, line, len);
443         }
444
445         if ( line ) {
446                 free(line);
447                 return res;
448         } else {
449                 return NULL;
450         }
451 }
452
453 /* get integer from prompt, loop forever to get it */
454 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
455 {
456         int rc;
457         long result;
458         char *line;
459         int size = strlen(prompt) + 40;
460         char *theprompt = malloc(size);
461         assert(theprompt);
462         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
463
464         fflush(stdout);
465
466         do {
467                 line = NULL;
468                 line = readline(theprompt);
469                 if ( !line ) {
470                         fprintf(stdout, "Please enter an integer.\n");
471                         fflush(stdout);
472                         continue;
473                 }
474                 if ( *line == '\0' ) {
475                         free(line);
476                         result =  deft;
477                         break;
478                 }
479                 rc = Parser_arg2int(line, &result, base);
480                 free(line);
481                 if ( rc != 0 ) {
482                         fprintf(stdout, "Invalid string.\n");
483                         fflush(stdout);
484                 } else if ( result > max || result < min ) {
485                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
486                                 min, max);
487                         fflush(stdout);
488                 } else {
489                         break;
490                 }
491         } while ( 1 ) ;
492
493         if (theprompt)
494                 free(theprompt);
495         return result;
496
497 }
498
499 /* get boolean (starting with YyNn; loop forever */
500 int Parser_getbool(const char *prompt, int deft)
501 {
502         int result = 0;
503         char *line;
504         int size = strlen(prompt) + 8;
505         char *theprompt = malloc(size);
506         assert(theprompt);
507
508         fflush(stdout);
509     
510         if ( deft != 0 && deft != 1 ) {
511                 fprintf(stderr, "Error: Parser_getbool given bad default (%d).\n",
512                         deft);
513                 assert ( 0 );
514         }
515         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
516
517         do {
518                 line = NULL;
519                 line = readline(theprompt);
520                 if ( line == NULL ) {
521                         result = deft;
522                         break;
523                 }
524                 if ( *line == '\0' ) {
525                         result = deft;
526                         break;
527                 }
528                 if ( *line == 'y' || *line == 'Y' ) {
529                         result = 1;
530                         break;
531                 }
532                 if ( *line == 'n' || *line == 'N' ) {
533                         result = 0;
534                         break;
535                 }
536                 if ( line ) 
537                         free(line);
538                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
539                 fflush(stdout);
540         } while ( 1 );
541
542         if ( line ) 
543                 free(line);
544         if ( theprompt ) 
545                 free(theprompt);
546         return result;
547 }
548
549 /* parse int out of a string or prompt for it */
550 long Parser_intarg(const char *inp, const char *prompt, int deft,
551                    int min, int max, int base)
552 {
553         long result;
554         int rc; 
555     
556         rc = Parser_arg2int(inp, &result, base);
557
558         if ( rc == 0 ) {
559                 return result;
560         } else {
561                 return Parser_getint(prompt, deft, min, max, base);
562         }
563 }
564
565 /* parse int out of a string or prompt for it */
566 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
567                     char *answer, int len)
568 {
569         if ( inp == NULL || *inp == '\0' ) {
570                 return Parser_getstr(prompt, deft, answer, len);
571         } else 
572                 return inp;
573 }
574
575 /* change a string into a number: return 0 on success. No invalid characters
576    allowed. The processing of base and validity follows strtol(3)*/
577 int Parser_arg2int(const char *inp, long *result, int base)
578 {
579         char *endptr;
580
581         if ( (base !=0) && (base < 2 || base > 36) )
582                 return 1;
583
584         *result = strtol(inp, &endptr, base);
585
586         if ( *inp != '\0' && *endptr == '\0' )
587                 return 0;
588         else 
589                 return 1;
590 }
591
592 /* Convert human readable size string to and int; "1k" -> 1000 */
593 int Parser_size (int *sizep, char *str) {
594         int size;
595         char mod[32];
596
597         switch (sscanf (str, "%d%1[gGmMkK]", &size, mod)) {
598         default:
599                 return (-1);
600
601         case 1:
602                 *sizep = size;
603                 return (0);
604
605         case 2:
606                 switch (*mod) {
607                 case 'g':
608                 case 'G':
609                         *sizep = size << 30;
610                         return (0);
611
612                 case 'm':
613                 case 'M':
614                         *sizep = size << 20;
615                         return (0);
616
617                 case 'k':
618                 case 'K':
619                         *sizep = size << 10;
620                         return (0);
621
622                 default:
623                         *sizep = size;
624                         return (0);
625                 }
626         }
627 }
628
629 /* Convert a string boolean to an int; "enable" -> 1 */
630 int Parser_bool (int *b, char *str) {
631         if (strcasecmp (str, "no") ||
632             strcasecmp (str, "n") ||
633             strcasecmp (str, "off") ||
634             strcasecmp (str, "disable"))
635         {
636                 *b = 0;
637                 return (0);
638         }
639         
640         if (strcasecmp (str, "yes") ||
641             strcasecmp (str, "y") ||
642             strcasecmp (str, "on") ||
643             strcasecmp (str, "enable"))
644         {
645                 *b = 1;
646                 return (0);
647         }
648         
649         return (-1);
650 }
651
652 int Parser_quit(int argc, char **argv)
653 {
654         argc = argc;
655         argv = argv;
656         done = 1;
657         return 0;
658 }