blob: cd8d34ad76d7de83039918745a4e8fb4740ee11c [file] [log] [blame]
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -07001#! /usr/bin/env python
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -07002# -*- Mode: python; py-indent-offset: 4; tab-width: 8; -*-
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -07003
4"""
5onoscli : ONOS-specific Command Line Interface
6
7Usage:
8 # Running the CLI in interactive mode:
9 $ ./onoscli
10
11 # Running multiple CLI commands in batch mode
12 $ cat commands.txt | ./onoscli
13
14 # Running a single command from the system command-line
15 $ ./onoscli -c show switch all
16
17 # Run the following command for additional help
18 $ ./onoscli -h
19"""
20
21#
22# INSTALLATION NOTES: MUST install Python cmd2 module. E.g., on Ubuntu:
23# sudo apt-get install python-cmd2
Pavlin Radoslavova9b78582014-06-06 15:41:32 -070024# On older Ubuntu installations (e.g., Ubuntu-12.04 or Ubuntu-13.04), install
25# also:
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -070026# sudo apt-get install python-pyparsing
27#
28
29#
30# ADDING A NEW CLI COMMAND:
31# 1. Add the appropriate Command entry (or entries) inside array
32# OnosCli.init_commands.
33# See the comments for init_commands for details.
34# 2. Add the appropriate callback (inside class OnosCli) for the CLI command
35#
36#
37
38import sys
39import argparse
40import json
41from optparse import make_option
42import urllib2
43from urllib2 import URLError, HTTPError
44import cmd2
45from cmd2 import Cmd
46from cmd2 import options
47
48
49class Command():
50 "Command node. A hierarchy of nodes are organized in a command tree."
51
52 def __init__(self, name, help, callback=None, add_parser_args=None):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -070053 """name: a string with the full command name
54 help: the help string for the command
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -070055 callback: the method to be called if the command is executed
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -070056 add_parser_args: the parser arguments to add to the command: a dictionary of argparse arguments"""
57 # Normalize the name by removing extra spaces
58 self.split_name = name.split() # List of the words in the name
59 self.name = ' '.join(self.split_name) # Normalized name
60 self.last_subname = self.split_name[-1] # Last word in the name
61 self.parent_name = ' '.join(self.split_name[:-1]) # Name of parent command
62 self.help = help # THe help string
63 self.callback = callback # The command callback
64 self.add_parser_args = add_parser_args # Parser arguments to add
65 self.parent = None # The parent Command
66 self.children = [] # The children Command entries
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -070067
68
69class OnosCli(Cmd):
70 "The main ONOS CLI class"
71
72 # Setup generic CLI fields
73 intro = "Welcome to the ONOS CLI. Type help or ? to list commands.\n"
74 prompt = "(onos) "
75 settable = Cmd.settable + "prompt CLI prompt"
76
77 # Setup ONOS-specific fields
78 onos_ip = "127.0.0.1"
79 settable = settable + "onos_ip ONOS IP address"
80 onos_port = 8080
81 settable = settable + "onos_port ONOS REST port number"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -070082 output_format = "json" # Valid values: json, text
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -070083 settable = settable + "output_format The output format: `text` or `json`"
84
85 # Collection of commands sorted by the level in the CLI command hierarchy
86 commands = []
87 # Commands, parsers and subparsers keyed by the command name
88 commands_dict = {}
89 parsers_dict = {}
90 subparsers_dict = {}
91
92 def __init__(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -070093 Cmd.__init__(self)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -070094
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -070095 #
96 # An array of the ONOS-specific CLI commands.
97 # Each entry is a Command instance, and must have at least
98 # two arguments:
99 # * Command name as typed on the CLI. E.g.:
100 # "show intent"
101 # * Command help description. E.g.:
102 # "Show intents"
103 #
104 # Executable commands should have a third Command argument, which is
105 # the name of the method to be called when the command is executed.
106 # The method will be called with the (argparse) parsed arguments
107 # for that command.
108 #
109 # If an executable command takes arguments, those should be described
110 # in the Command's fourth argument. It is a list of pairs:
111 # [
112 # ("--argument-name1", dict(...)),
113 # ("--argument-name2", dict(...)),
114 # ...
115 # ]
116 # where the first entry in the pair is the argument name, and the
117 # second entry in the pair is a dictionary with argparse-specific
118 # description of the argument.
119 #
120 init_commands = [
121 Command("delete", "Delete command"),
122 #
123 Command("delete intent",
124 """Delete high-level intents
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700125 Usage:
126 delete intent --intent-id INTENT_ID Delete a high-level intent
127 delete intent --all Delete all high-level intents
128 Arguments:
129 --intent-id INTENT_ID The Intent ID (an integer)
130 --all Delete all high-level intents""",
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700131 self.delete_intent,
132 [
133 ("--intent-id", dict(required=False, type=int)),
134 ("--all", dict(required=False, action='store_true'))
135 ]
136 ),
137 #
138 Command("set", "Set command"),
139 #
140 Command("set intent",
141 """Set a high-level intent
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700142 Usage:
143 set intent <ARGS>
144 Arguments:
145 --intent-id INTENT_ID The Intent ID (an integer) (REQUIRED)
146 --src-dpid SRC_DPID Source Switch DPID (REQUIRED)
147 --src-port SRC_PORT Source Switch Port (REQUIRED)
148 --dst-dpid DST_DPID Destination Switch DPID (REQUIRED)
149 --dst-port DST_PORT Destination Switch Port (REQUIRED)
150 --match-src-mac MATCH_SRC_MAC Matching Source MAC Address (REQUIRED)
151 --match-dst-mac MATCH_DST_MAC Matching Destination MAC Address (REQUIRED)""",
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700152 self.set_intent,
153 [
154 ("--intent-id", dict(required=True, type=int)),
155 ("--src-dpid", dict(required=True)),
156 ("--src-port", dict(required=True, type=int)),
157 ("--dst-dpid", dict(required=True)),
158 ("--dst-port", dict(required=True, type=int)),
159 ("--match-src-mac", dict(required=True)),
160 ("--match-dst-mac", dict(required=True))
161 ]),
162 #
163 Command("show", "Show command"),
164 #
Pavlin Radoslavov308337c2014-06-11 10:25:44 -0700165 Command("show host", "Show hosts"),
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700166 #
Pavlin Radoslavov308337c2014-06-11 10:25:44 -0700167 Command("show host all", "Show all hosts", self.show_host_all),
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700168 #
169 Command("show intent", "Show intents"),
170 #
171 Command("show intent high",
172 """Show all high-level intents
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700173 show intent high --intent-id INTENT_ID Show a high-level intent""",
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700174 self.show_intent_high,
175 [
176 ("--intent-id", dict(required=False, type=int))
177 ]
178 ),
179 #
180 Command("show intent low",
181 """Show all low-level intents
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700182 show intent low --intent-id INTENT_ID Show a low-level intent""",
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700183 self.show_intent_low,
184 [
185 ("--intent-id", dict(required=False))
186 ]
187 ),
188 #
189 Command("show link", "Show links"),
190 #
191 Command("show link all", "Show all links", self.show_link_all),
192 #
Ray Milkey4d238292014-07-03 11:07:33 -0700193 Command("show metrics", "Show ONOS metrics"),
194 #
195 Command("show metrics all", "Show all ONOS metrics", self.show_metrics_all),
196 #
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700197 Command("show path", "Show a path"),
198 #
199 Command("show path shortest",
200 """Show a shortest path
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700201 Usage:
202 show path shortest --src-dpid SRC_DPID --dst-dpid DST_DPID
203 Arguments:
204 --src-dpid SRC_DPID Source Switch DPID
205 --dst-dpid DST_DPID Destination Switch DPID""",
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700206 self.show_path_shortest,
207 [
208 ("--src-dpid", dict(required=True)),
209 ("--dst-dpid", dict(required=True))
210 ]),
211 #
212 Command("show switch", "Show switches"),
213 #
214 Command("show switch all", "Show all switches", self.show_switch_all),
215 #
216 Command("show topology", "Show network topology"),
217 #
218 Command("show topology all", "Show whole network topology", self.show_topology_all)
219 ]
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700220
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700221 # Sort the commands by the level in the CLI command hierarchy
222 self.commands = sorted(init_commands, key = lambda c: len(c.name.split()))
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700223
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700224 # Create a dictionary with all commands: name -> Command
225 for c in self.commands:
226 self.commands_dict[c.name] = c
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700227
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700228 # Create a tree with all commands
229 for c in self.commands:
230 if c.parent_name:
231 pc = self.commands_dict[c.parent_name]
232 pc.children.append(c)
233 c.parent = pc
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700234
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700235 # Create the parsers and the sub-parsers
236 for c in self.commands:
237 # Add a parser
238 parser = None
239 if c.parent is None:
240 # Add a top-level parser
241 parser = argparse.ArgumentParser(description=c.help,
242 prog=c.name,
243 add_help=False)
244 else:
245 # Add a parser from the parent's subparser
246 parent_subparser = self.subparsers_dict[c.parent_name]
247 parser = parent_subparser.add_parser(c.last_subname,
248 help=c.help,
249 add_help=False)
250 self.parsers_dict[c.name] = parser
251 # Add a sub-parser
252 if c.children:
253 subparser = parser.add_subparsers(help=c.help)
254 self.subparsers_dict[c.name] = subparser
255 # Setup the callback
256 if c.callback is not None:
257 parser.set_defaults(func=c.callback)
258 # Init the argument parser
259 if c.add_parser_args is not None:
260 for a in c.add_parser_args:
261 (p1, p2) = a
262 parser.add_argument(p1, **p2)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700263
264 def delete_intent(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700265 "CLI command callback: delete intent"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700266
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700267 url = ""
268 if args.all:
269 # Delete all intents
270 url = "http://%s:%s/wm/onos/intent/high" % (self.onos_ip, self.onos_port)
271 else:
272 if args.intent_id is None:
273 print "*** Unknown syntax:"
274 self.help_delete()
275 return;
276 # Delete an intent
277 url = "http://%s:%s/wm/onos/intent/high/%s" % (self.onos_ip, self.onos_port, args.intent_id)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700278
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700279 result = delete_json(url)
280 # NOTE: No need to print the response
281 # if len(result) != 0:
282 # self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700283
284 def set_intent(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700285 "CLI command callback: set intent"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700286
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700287 intents = []
288 oper = {}
289 # Create the POST payload
290 oper['intentId'] = args.intent_id
Pavlin Radoslavova9b78582014-06-06 15:41:32 -0700291 oper['intentType'] = 'SHORTEST_PATH' # XXX: Hardcoded
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700292 oper['staticPath'] = False # XXX: Hardcoded
293 oper['srcSwitchDpid'] = args.src_dpid
294 oper['srcSwitchPort'] = args.src_port
295 oper['dstSwitchDpid'] = args.dst_dpid
296 oper['dstSwitchPort'] = args.dst_port
297 oper['matchSrcMac'] = args.match_src_mac
298 oper['matchDstMac'] = args.match_dst_mac
299 intents.append(oper)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700300
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700301 url = "http://%s:%s/wm/onos/intent/high" % (self.onos_ip, self.onos_port)
302 result = post_json(url, intents)
303 # NOTE: No need to print the response
304 # if len(result) != 0:
305 # self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700306
Pavlin Radoslavov308337c2014-06-11 10:25:44 -0700307 def show_host_all(self, args):
308 "CLI command callback: show host all"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700309
Pavlin Radoslavov308337c2014-06-11 10:25:44 -0700310 url = "http://%s:%s/wm/onos/topology/hosts" % (self.onos_ip, self.onos_port)
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700311 result = get_json(url)
312 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700313
314 def show_intent_high(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700315 "CLI command callback: show intent high"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700316
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700317 if args.intent_id is None:
318 # Show all intents
319 url = "http://%s:%s/wm/onos/intent/high" % (self.onos_ip, self.onos_port)
320 else:
321 # Show a single intent
322 url = "http://%s:%s/wm/onos/intent/high/%s" % (self.onos_ip, self.onos_port, args.intent_id)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700323
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700324 result = get_json(url)
325 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700326
327 def show_intent_low(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700328 "CLI command callback: show intent low"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700329
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700330 if args.intent_id is None:
331 # Show all intents
332 url = "http://%s:%s/wm/onos/intent/low" % (self.onos_ip, self.onos_port)
333 else:
334 # Show a single intent
335 url = "http://%s:%s/wm/onos/intent/low/%s" % (self.onos_ip, self.onos_port, args.intent_id)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700336
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700337 result = get_json(url)
338 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700339
340 def show_link_all(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700341 "CLI command callback: show link all"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700342
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700343 url = "http://%s:%s/wm/onos/topology/links" % (self.onos_ip, self.onos_port)
344 result = get_json(url)
345 #
346 if (self.output_format == "json"):
347 self.print_json_result(result)
348 else:
349 # NOTE: The code below is for demo purpose only how to
350 # decode and print the links in text format. It will be
351 # reimplemented in the future.
352 links = result
353 print "# src_dpid src_port -> dst_dpid dst_port"
354 for v in sorted(links, key=lambda x: x['src-switch']):
355 if v.has_key('dst-switch'):
356 dst_dpid = str(v['dst-switch'])
357 if v.has_key('src-switch'):
358 src_dpid = str(v['src-switch'])
359 if v.has_key('src-port'):
360 src_port = str(v['src-port'])
361 if v.has_key('dst-port'):
362 dst_port = str(v['dst-port'])
363 self.print_result("%s %s -> %s %s" % (src_dpid, src_port, dst_dpid, dst_port))
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700364
Ray Milkey4d238292014-07-03 11:07:33 -0700365 def show_metrics_all(self, args):
366 "CLI command callback: show metrics all"
367
368 url = "http://%s:%s/wm/onos/metrics" % (self.onos_ip, self.onos_port)
369 result = get_json(url)
370 #
371 self.print_json_result(result)
372
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700373 def show_path_shortest(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700374 "CLI command callback: show path shortest"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700375
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700376 url = "http://%s:%s/wm/onos/intent/path/switch/%s/shortest-path/%s" % (self.onos_ip, self.onos_port, args.src_dpid, args.dst_dpid)
377 result = get_json(url)
378 #
379 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700380
381 def show_switch_all(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700382 "CLI command callback: show switch all"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700383
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700384 url = "http://%s:%s/wm/onos/topology/switches" % (self.onos_ip, self.onos_port)
385 result = get_json(url)
386 #
387 self.print_json_result(result)
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700388
389 def show_topology_all(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700390 "CLI command callback: show topology all"
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700391
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700392 url = "http://%s:%s/wm/onos/topology" % (self.onos_ip, self.onos_port)
393 result = get_json(url)
394 #
395 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700396
397 #
398 # Implement "delete" top-level command
399 #
400 def do_delete(self, arg):
401 "Top-level 'delete' command"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700402 self.impl_do_command('delete', arg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700403 def complete_delete(self, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700404 "Completion of top-level 'delete' command"
405 return self.impl_complete_command('delete', text, line, begidx, endidx)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700406 def help_delete(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700407 "Help for top-level 'delete' command"
408 self.impl_help_command('delete')
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700409
410 #
411 # Implement "set" top-level command
412 #
413 def do_set(self, arg):
414 "Top-level 'set' command"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700415 self.impl_do_command('set', arg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700416 def complete_set(self, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700417 "Completion of top-level 'set' command"
418 return self.impl_complete_command('set', text, line, begidx, endidx)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700419 def help_set(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700420 "Help for top-level 'set' command"
421 self.impl_help_command('set')
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700422
423 #
424 # Implement "show" top-level command
425 #
426 def do_show(self, arg):
427 "Top-level 'show' command"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700428 self.impl_do_command('show', arg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700429 def complete_show(self, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700430 "Completion of top-level 'show' command"
431 return self.impl_complete_command('show', text, line, begidx, endidx)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700432 def help_show(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700433 "Help for top-level 'show' command"
434 self.impl_help_command('show')
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700435
436 #
437 # Implement the "do_something" top-level command execution
438 #
439 def impl_do_command(self, root_name, arg):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700440 "Implementation of top-level 'do_something' command execution"
441 parser = self.parsers_dict[root_name]
442 parsed_args = parser.parse_args(arg.split())
443 parsed_args.func(parsed_args)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700444
445 #
446 # Implement the "complete_something" top-level command completion
447 #
448 def impl_complete_command(self, root_name, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700449 "Implementation of top-level 'complete_something' command completion"
450 root_command = self.commands_dict[root_name]
451 subtree_commands = self.collect_subtree_commands(root_command)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700452
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700453 #
454 # Loop through the commands and add their portion
455 # of the sub-name to the list of completions.
456 #
457 # NOTE: We add a command only if it has a callback.
458 #
459 completions = []
460 for c in subtree_commands:
461 if c.callback is None:
462 continue
463 name = c.split_name[len(root_command.split_name):]
464 completions.append(' '.join(name))
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700465
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700466 mline = line.partition(" ")[2]
467 offs = len(mline) - len(text)
468 return [s[offs:] for s in completions if s.startswith(mline)]
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700469
470 #
471 # Implement the "help_something" top-level command help
472 #
473 def impl_help_command(self, root_name):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700474 "Implementation of top-level 'help_something' command help"
475 root_command = self.commands_dict[root_name]
476 subtree_commands = self.collect_subtree_commands(root_command)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700477
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700478 #
479 # Loop through the commands and print the help for each command.
480 # NOTE: We add a command only if it has a callback.
481 #
482 print "Help for the `%s` command:" % (root_name)
483 for c in subtree_commands:
484 if c.callback is None:
485 continue
486 print " {0:30}{1:30}".format(c.name, c.help)
487 # if c.init_arg_parser is not None:
488 # parser = self.parsers_dict[c.name]
489 # parser.print_help()
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700490
491 #
492 # Traverse (breadth-first) a subtree and return all nodes except the
493 # root node.
494 #
495 def collect_subtree_commands(self, root_command):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700496 """Collect a subtree of commands.
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700497 Traverses (breadth-first) a subtree of commands and returns
498 all nodes except the root node."""
499
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700500 commands = []
501 subtree_commands = []
502 commands.append(root_command)
503 # Use breadth-first to traverse the subtree
504 while commands:
505 pc = commands.pop(0)
506 for c in pc.children:
507 commands.append(c)
508 subtree_commands.append(c)
509 return subtree_commands
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700510
511 def log_debug(self, msg):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700512 """Log debug information.
513 msg: the message to log
514 Use the following CLI commands to enable/disable debugging:
515 paramset debug true
516 paramset debug false
517 """
518 if self.debug:
519 print "%s" % (msg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700520
521 def print_json_result(self, json_result):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700522 """Print JSON result."""
523 if len(json_result) == 0:
524 return
525 result = json.dumps(json_result, indent=4)
526 self.print_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700527
528 def print_result(self, result):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700529 """Print parsed result."""
530 print "%s" % (result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700531
532 #
533 # Implementation of the "paramshow" CLI command.
534 #
535 # NOTE: The do_paramshow implementation below is copied from
536 # the cmd2.do_show() implementation
537 #
538 @options([make_option('-l', '--long', action="store_true",
539 help="describe function of parameter")])
540 def do_paramshow(self, arg, opts):
541 '''Shows value of a parameter.'''
542 param = arg.strip().lower()
543 result = {}
544 maxlen = 0
545 for p in self.settable:
546 if (not param) or p.startswith(param):
547 result[p] = '%s: %s' % (p, str(getattr(self, p)))
548 maxlen = max(maxlen, len(result[p]))
549 if result:
550 for p in sorted(result):
551 if opts.long:
552 self.poutput('%s # %s' % (result[p].ljust(maxlen), self.settable[p]))
553 else:
554 self.poutput(result[p])
555 else:
556 raise NotImplementedError("Parameter '%s' not supported (type 'show' for list of parameters)." % param)
557
558 #
559 # Implementation of the "paramset" CLI command.
560 #
561 #
562 # NOTE: The do_paramset implementation below is copied from
563 # the cmd2.do_set() implementation (with minor modifications).
564 #
565 def do_paramset(self, arg):
566 '''
567 Sets a cmd2 parameter. Accepts abbreviated parameter names so long
568 as there is no ambiguity. Call without arguments for a list of
569 settable parameters with their values.'''
570
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700571 class NotSettableError(Exception):
572 pass
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700573
574 try:
575 statement, paramName, val = arg.parsed.raw.split(None, 2)
576 val = val.strip()
577 paramName = paramName.strip().lower()
578 if paramName not in self.settable:
579 hits = [p for p in self.settable if p.startswith(paramName)]
580 if len(hits) == 1:
581 paramName = hits[0]
582 else:
583 return self.do_paramshow(paramName)
584 currentVal = getattr(self, paramName)
585 if (val[0] == val[-1]) and val[0] in ("'", '"'):
586 val = val[1:-1]
587 else:
588 val = cmd2.cast(currentVal, val)
589 setattr(self, paramName, val)
590 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val))
591 if currentVal != val:
592 try:
593 onchange_hook = getattr(self, '_onchange_%s' % paramName)
594 onchange_hook(old=currentVal, new=val)
595 except AttributeError:
596 pass
597 except (ValueError, AttributeError, NotSettableError) as exc:
598 self.do_paramshow(arg)
599
600
601def get_json(url):
602 """Make a REST GET call and return the JSON result
603 url: the URL to call"""
604
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700605 parsed_result = []
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700606 try:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700607 response = urllib2.urlopen(url)
608 result = response.read()
609 response.close()
610 if len(result) != 0:
611 parsed_result = json.loads(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700612 except HTTPError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700613 print "ERROR:"
614 print " REST GET URL: %s" % url
615 # NOTE: exc.fp contains the object with the response payload
616 error_payload = json.loads(exc.fp.read())
617 print " REST Error Code: %s" % (error_payload['code'])
618 print " REST Error Summary: %s" % (error_payload['summary'])
619 print " REST Error Description: %s" % (error_payload['formattedDescription'])
620 print " HTTP Error Code: %s" % exc.code
621 print " HTTP Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700622 except URLError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700623 print "ERROR:"
624 print " REST GET URL: %s" % url
625 print " URL Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700626 return parsed_result
627
628def post_json(url, data):
629 """Make a REST POST call and return the JSON result
630 url: the URL to call
631 data: the data to POST"""
632
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700633 parsed_result = []
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700634 data_json = json.dumps(data)
635 try:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700636 request = urllib2.Request(url, data_json)
637 request.add_header("Content-Type", "application/json")
638 response = urllib2.urlopen(request)
639 result = response.read()
640 response.close()
641 if len(result) != 0:
642 parsed_result = json.loads(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700643 except HTTPError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700644 print "ERROR:"
645 print " REST POST URL: %s" % url
646 # NOTE: exc.fp contains the object with the response payload
647 error_payload = json.loads(exc.fp.read())
648 print " REST Error Code: %s" % (error_payload['code'])
649 print " REST Error Summary: %s" % (error_payload['summary'])
650 print " REST Error Description: %s" % (error_payload['formattedDescription'])
651 print " HTTP Error Code: %s" % exc.code
652 print " HTTP Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700653 except URLError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700654 print "ERROR:"
655 print " REST POST URL: %s" % url
656 print " URL Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700657 return parsed_result
658
659def delete_json(url):
660 """Make a REST DELETE call and return the JSON result
661 url: the URL to call"""
662
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700663 parsed_result = []
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700664 try:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700665 request = urllib2.Request(url)
666 request.get_method = lambda: 'DELETE'
667 response = urllib2.urlopen(request)
668 result = response.read()
669 response.close()
670 if len(result) != 0:
671 parsed_result = json.loads(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700672 except HTTPError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700673 print "ERROR:"
674 print " REST DELETE URL: %s" % url
675 # NOTE: exc.fp contains the object with the response payload
676 error_payload = json.loads(exc.fp.read())
677 print " REST Error Code: %s" % (error_payload['code'])
678 print " REST Error Summary: %s" % (error_payload['summary'])
679 print " REST Error Description: %s" % (error_payload['formattedDescription'])
680 print " HTTP Error Code: %s" % exc.code
681 print " HTTP Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700682 except URLError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700683 print "ERROR:"
684 print " REST DELETE URL: %s" % url
685 print " URL Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700686 return parsed_result
687
688if __name__ == '__main__':
689 onosCli = OnosCli()
690
691 # Setup the parser
692 parser = argparse.ArgumentParser()
693 parser.add_argument('-c', '--command', nargs=argparse.REMAINDER,
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700694 help="Run arguments to the end of the line as a CLI command")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700695 parser.add_argument('--onos-ip',
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700696 help="Set the ONOS IP address (for REST calls)")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700697 parser.add_argument('--onos-port',
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700698 help="Set the ONOS port number (for REST calls)")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700699 parser.add_argument('-t', '--test', nargs='+',
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700700 help="Test against transcript(s) in FILE (wildcards OK)")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700701
702 # Parse the arguments
703 parsed_args = parser.parse_args()
704 if parsed_args.onos_ip:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700705 onosCli.onos_ip = parsed_args.onos_ip
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700706 if parsed_args.onos_port:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700707 onosCli.onos_port = parsed_args.onos_port
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700708 #
709 # NOTE: We have to reset the command-line options so the Cmd2 parser
710 # doesn't process them again.
711 #
712 sys.argv = [sys.argv[0]]
713
714 # Run the CLI as appropriate
715 if parsed_args.test:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700716 # Run CLI Transcript Tests
717 onosCli.runTranscriptTests(parsed_args.test)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700718 elif parsed_args.command:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700719 # Run arguments as a CLI command
720 command_line = ' '.join(parsed_args.command)
721 onosCli.onecmd(command_line)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700722 else:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700723 # Run interactive CLI
724 onosCli.cmdloop()