Add help to the trmon utility
[trust_router.git] / tr / trmon_main.c
1 /*
2  * Copyright (c) 2012-2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <talloc.h>
38 #include <argp.h>
39
40 #include <mon_internal.h>
41 #include <tr_debug.h>
42 #include <tr_inet_util.h>
43
44
45 /* command-line option setup */
46 static void print_version_info(void)
47 {
48   printf("Moonshot Trust Router Monitoring Client %s\n\n", PACKAGE_VERSION);
49 }
50
51
52 /* argp global parameters */
53 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
54
55 /* doc strings */
56 static const char doc[] =
57     PACKAGE_NAME " - Moonshot Trust Router Monitoring Client"
58                  "\v" /* options list goes here */
59                  "Supported monitoring commands:\n"
60                  "\n"
61                  "  show [<option> ...]\n"
62                  "\n"
63                  "     Show information about the Trust Router's current state.\n"
64                  "\n"
65                  "     Options:\n"
66                  "       version            - current Trust Router software version\n"
67                  "       config_files       - currently loaded configuration files\n"
68                  "       uptime             - time, in seconds, since the Trust Router launched\n"
69                  "       tid_reqs_processed - number of TID requests successfully processed\n"
70                  "       tid_reqs_pending   - number of TID requests currently being processed\n"
71                  "       tid_error_count    - number of TID failed connections\n"
72                  "       routes             - current TID routing table\n"
73                  "       peers              - dynamic Trust Router peer table\n"
74                  "       communities        - community table\n"
75                  "       realms             - known realm table\n"
76                  "       rp_clients         - authorized TID RP clients\n"
77                  "\n"
78                  "    If no options are specified, data for all options will be retrieved.\n";
79
80 static const char arg_doc[]="<server> <port> <command> [<option> ...]"; /* string describing arguments, if any */
81
82 /* define the options here. Fields are:
83  * { long-name, short-name, variable name, options, help description } */
84 static const struct argp_option cmdline_options[] = {
85     { "version", 'v', NULL, 0, "Print version information and exit" },
86     {NULL}
87 };
88
89 #define MAX_OPTIONS 20
90 /* structure for communicating with option parser */
91 struct cmdline_args {
92   char *server;
93   int port;
94   MON_CMD command;
95   MON_OPT_TYPE options[MAX_OPTIONS];
96   unsigned int n_options;
97 };
98
99 /* parser for individual options - fills in a struct cmdline_args */
100 static error_t parse_option(int key, char *arg, struct argp_state *state)
101 {
102   int err = 0;
103
104   /* get a shorthand to the command line argument structure, part of state */
105   struct cmdline_args *arguments=state->input;
106
107   switch (key) {
108     case 'v':
109       print_version_info();
110       exit(0);
111
112     case ARGP_KEY_ARG: /* handle argument (not option) */
113       switch (state->arg_num) {
114         case 0:
115           arguments->server = arg;
116           break;
117
118         case 1:
119           arguments->port=tr_parse_port(arg); /* optional */
120           if (arguments->port < 0) {
121             switch(-(arguments->port)) {
122               case ERANGE:
123                 printf("\nError parsing port (%s): port must be an integer in the range 1 - 65535\n\n", arg);
124                 break;
125
126               default:
127                 printf("\nError parsing port (%s): %s\n\n", arg, strerror(-arguments->port));
128                 break;
129             }
130             argp_usage(state);
131           }
132           break;
133
134         case 2:
135           arguments->command=mon_cmd_from_string(arg);
136           if (arguments->command == MON_CMD_UNKNOWN) {
137             printf("\nUnknown command '%s'\n\n", arg);
138             err = 1;
139           }
140           break;
141
142         default:
143           if (arguments->n_options >= MAX_OPTIONS) {
144             printf("\nToo many command options given, limit is %d\n\n", MAX_OPTIONS);
145             err = 1;
146             break;
147           }
148
149           arguments->options[arguments->n_options] = mon_opt_type_from_string(arg);
150           if (arguments->options[arguments->n_options] == OPT_TYPE_UNKNOWN) {
151             printf("\nUnknown command option '%s'\n\n", arg);
152             err = 1;
153           }
154           arguments->n_options++;
155           break;
156       }
157       break;
158
159     case ARGP_KEY_END: /* no more arguments */
160       if (state->arg_num < 3) {
161         /* not enough arguments encountered */
162         err = 1;
163       }
164       break;
165
166     default:
167       return ARGP_ERR_UNKNOWN;
168   }
169
170   if (err) {
171     argp_usage(state);
172     return EINVAL; /* argp_usage() usually does not return, but just in case */
173   }
174
175   return 0; /* success */
176 }
177
178 /* assemble the argp parser */
179 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc, 0};
180
181 int main(int argc, char *argv[])
182 {
183   TALLOC_CTX *main_ctx=talloc_new(NULL);
184   MONC_INSTANCE *monc = NULL;
185   MON_REQ *req = NULL;
186   MON_RESP *resp = NULL;
187   unsigned int ii;
188
189   struct cmdline_args opts;
190   int retval=1; /* exit with an error status unless this gets set to zero */
191
192   /* parse the command line*/
193   /* set defaults */
194   opts.server = NULL;
195   opts.port = TRP_PORT;
196   opts.command = MON_CMD_UNKNOWN;
197   opts.n_options = 0;
198
199   argp_parse(&argp, argc, argv, 0, 0, &opts);
200
201   /* Use standalone logging */
202   tr_log_open();
203
204   /* set logging levels */
205   talloc_set_log_stderr();
206   tr_log_threshold(LOG_CRIT);
207   tr_console_threshold(LOG_WARNING);
208
209   /* Create a MON client instance */
210   monc = monc_new(main_ctx);
211   if (monc == NULL) {
212     printf("Error allocating client instance.\n");
213     goto cleanup;
214   }
215
216   /* Set-up MON connection */
217   if (0 != monc_open_connection(monc, opts.server, opts.port)) {
218     /* Handle error */
219     printf("Error opening connection to %s:%d.\n", opts.server, opts.port);
220     goto cleanup;
221   };
222
223   req = mon_req_new(main_ctx, opts.command);
224   for (ii=0; ii < opts.n_options; ii++) {
225     if (MON_SUCCESS != mon_req_add_option(req, opts.options[ii])) {
226       printf("Error adding option '%s' to request. Request not sent.\n",
227              mon_opt_type_to_string(opts.options[ii]));
228       goto cleanup;
229     }
230
231   }
232
233   /* Send a MON request and get the response */
234   resp = monc_send_request(main_ctx, monc, req);
235
236   if (resp == NULL) {
237     /* Handle error */
238     printf("Error executing monitoring request.\n");
239     goto cleanup;
240   }
241
242   /* Print the JSON to stdout */
243   json_dumpf(mon_resp_encode(resp), stdout, JSON_INDENT(4));
244   printf("\n");
245
246   /* success */
247   retval = 0;
248
249   /* Clean-up the MON client instance, and exit */
250 cleanup:
251   talloc_free(main_ctx);
252   return retval;
253 }
254