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