blob: 6bfa9d084663db1e1e314143351416fae01f5b29 [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 #
193 Command("show path", "Show a path"),
194 #
195 Command("show path shortest",
196 """Show a shortest path
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700197 Usage:
198 show path shortest --src-dpid SRC_DPID --dst-dpid DST_DPID
199 Arguments:
200 --src-dpid SRC_DPID Source Switch DPID
201 --dst-dpid DST_DPID Destination Switch DPID""",
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700202 self.show_path_shortest,
203 [
204 ("--src-dpid", dict(required=True)),
205 ("--dst-dpid", dict(required=True))
206 ]),
207 #
208 Command("show switch", "Show switches"),
209 #
210 Command("show switch all", "Show all switches", self.show_switch_all),
211 #
212 Command("show topology", "Show network topology"),
213 #
214 Command("show topology all", "Show whole network topology", self.show_topology_all)
215 ]
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700216
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700217 # Sort the commands by the level in the CLI command hierarchy
218 self.commands = sorted(init_commands, key = lambda c: len(c.name.split()))
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700219
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700220 # Create a dictionary with all commands: name -> Command
221 for c in self.commands:
222 self.commands_dict[c.name] = c
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700223
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700224 # Create a tree with all commands
225 for c in self.commands:
226 if c.parent_name:
227 pc = self.commands_dict[c.parent_name]
228 pc.children.append(c)
229 c.parent = pc
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700230
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700231 # Create the parsers and the sub-parsers
232 for c in self.commands:
233 # Add a parser
234 parser = None
235 if c.parent is None:
236 # Add a top-level parser
237 parser = argparse.ArgumentParser(description=c.help,
238 prog=c.name,
239 add_help=False)
240 else:
241 # Add a parser from the parent's subparser
242 parent_subparser = self.subparsers_dict[c.parent_name]
243 parser = parent_subparser.add_parser(c.last_subname,
244 help=c.help,
245 add_help=False)
246 self.parsers_dict[c.name] = parser
247 # Add a sub-parser
248 if c.children:
249 subparser = parser.add_subparsers(help=c.help)
250 self.subparsers_dict[c.name] = subparser
251 # Setup the callback
252 if c.callback is not None:
253 parser.set_defaults(func=c.callback)
254 # Init the argument parser
255 if c.add_parser_args is not None:
256 for a in c.add_parser_args:
257 (p1, p2) = a
258 parser.add_argument(p1, **p2)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700259
260 def delete_intent(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700261 "CLI command callback: delete intent"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700262
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700263 url = ""
264 if args.all:
265 # Delete all intents
266 url = "http://%s:%s/wm/onos/intent/high" % (self.onos_ip, self.onos_port)
267 else:
268 if args.intent_id is None:
269 print "*** Unknown syntax:"
270 self.help_delete()
271 return;
272 # Delete an intent
273 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 -0700274
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700275 result = delete_json(url)
276 # NOTE: No need to print the response
277 # if len(result) != 0:
278 # self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700279
280 def set_intent(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700281 "CLI command callback: set intent"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700282
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700283 intents = []
284 oper = {}
285 # Create the POST payload
286 oper['intentId'] = args.intent_id
Pavlin Radoslavova9b78582014-06-06 15:41:32 -0700287 oper['intentType'] = 'SHORTEST_PATH' # XXX: Hardcoded
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700288 oper['staticPath'] = False # XXX: Hardcoded
289 oper['srcSwitchDpid'] = args.src_dpid
290 oper['srcSwitchPort'] = args.src_port
291 oper['dstSwitchDpid'] = args.dst_dpid
292 oper['dstSwitchPort'] = args.dst_port
293 oper['matchSrcMac'] = args.match_src_mac
294 oper['matchDstMac'] = args.match_dst_mac
295 intents.append(oper)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700296
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700297 url = "http://%s:%s/wm/onos/intent/high" % (self.onos_ip, self.onos_port)
298 result = post_json(url, intents)
299 # NOTE: No need to print the response
300 # if len(result) != 0:
301 # self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700302
Pavlin Radoslavov308337c2014-06-11 10:25:44 -0700303 def show_host_all(self, args):
304 "CLI command callback: show host all"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700305
Pavlin Radoslavov308337c2014-06-11 10:25:44 -0700306 url = "http://%s:%s/wm/onos/topology/hosts" % (self.onos_ip, self.onos_port)
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700307 result = get_json(url)
308 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700309
310 def show_intent_high(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700311 "CLI command callback: show intent high"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700312
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700313 if args.intent_id is None:
314 # Show all intents
315 url = "http://%s:%s/wm/onos/intent/high" % (self.onos_ip, self.onos_port)
316 else:
317 # Show a single intent
318 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 -0700319
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700320 result = get_json(url)
321 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700322
323 def show_intent_low(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700324 "CLI command callback: show intent low"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700325
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700326 if args.intent_id is None:
327 # Show all intents
328 url = "http://%s:%s/wm/onos/intent/low" % (self.onos_ip, self.onos_port)
329 else:
330 # Show a single intent
331 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 -0700332
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700333 result = get_json(url)
334 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700335
336 def show_link_all(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700337 "CLI command callback: show link all"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700338
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700339 url = "http://%s:%s/wm/onos/topology/links" % (self.onos_ip, self.onos_port)
340 result = get_json(url)
341 #
342 if (self.output_format == "json"):
343 self.print_json_result(result)
344 else:
345 # NOTE: The code below is for demo purpose only how to
346 # decode and print the links in text format. It will be
347 # reimplemented in the future.
348 links = result
349 print "# src_dpid src_port -> dst_dpid dst_port"
350 for v in sorted(links, key=lambda x: x['src-switch']):
351 if v.has_key('dst-switch'):
352 dst_dpid = str(v['dst-switch'])
353 if v.has_key('src-switch'):
354 src_dpid = str(v['src-switch'])
355 if v.has_key('src-port'):
356 src_port = str(v['src-port'])
357 if v.has_key('dst-port'):
358 dst_port = str(v['dst-port'])
359 self.print_result("%s %s -> %s %s" % (src_dpid, src_port, dst_dpid, dst_port))
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700360
361 def show_path_shortest(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700362 "CLI command callback: show path shortest"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700363
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700364 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)
365 result = get_json(url)
366 #
367 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700368
369 def show_switch_all(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700370 "CLI command callback: show switch all"
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700371
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700372 url = "http://%s:%s/wm/onos/topology/switches" % (self.onos_ip, self.onos_port)
373 result = get_json(url)
374 #
375 self.print_json_result(result)
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700376
377 def show_topology_all(self, args):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700378 "CLI command callback: show topology all"
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700379
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700380 url = "http://%s:%s/wm/onos/topology" % (self.onos_ip, self.onos_port)
381 result = get_json(url)
382 #
383 self.print_json_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700384
385 #
386 # Implement "delete" top-level command
387 #
388 def do_delete(self, arg):
389 "Top-level 'delete' command"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700390 self.impl_do_command('delete', arg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700391 def complete_delete(self, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700392 "Completion of top-level 'delete' command"
393 return self.impl_complete_command('delete', text, line, begidx, endidx)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700394 def help_delete(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700395 "Help for top-level 'delete' command"
396 self.impl_help_command('delete')
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700397
398 #
399 # Implement "set" top-level command
400 #
401 def do_set(self, arg):
402 "Top-level 'set' command"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700403 self.impl_do_command('set', arg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700404 def complete_set(self, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700405 "Completion of top-level 'set' command"
406 return self.impl_complete_command('set', text, line, begidx, endidx)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700407 def help_set(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700408 "Help for top-level 'set' command"
409 self.impl_help_command('set')
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700410
411 #
412 # Implement "show" top-level command
413 #
414 def do_show(self, arg):
415 "Top-level 'show' command"
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700416 self.impl_do_command('show', arg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700417 def complete_show(self, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700418 "Completion of top-level 'show' command"
419 return self.impl_complete_command('show', text, line, begidx, endidx)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700420 def help_show(self):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700421 "Help for top-level 'show' command"
422 self.impl_help_command('show')
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700423
424 #
425 # Implement the "do_something" top-level command execution
426 #
427 def impl_do_command(self, root_name, arg):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700428 "Implementation of top-level 'do_something' command execution"
429 parser = self.parsers_dict[root_name]
430 parsed_args = parser.parse_args(arg.split())
431 parsed_args.func(parsed_args)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700432
433 #
434 # Implement the "complete_something" top-level command completion
435 #
436 def impl_complete_command(self, root_name, text, line, begidx, endidx):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700437 "Implementation of top-level 'complete_something' command completion"
438 root_command = self.commands_dict[root_name]
439 subtree_commands = self.collect_subtree_commands(root_command)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700440
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700441 #
442 # Loop through the commands and add their portion
443 # of the sub-name to the list of completions.
444 #
445 # NOTE: We add a command only if it has a callback.
446 #
447 completions = []
448 for c in subtree_commands:
449 if c.callback is None:
450 continue
451 name = c.split_name[len(root_command.split_name):]
452 completions.append(' '.join(name))
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700453
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700454 mline = line.partition(" ")[2]
455 offs = len(mline) - len(text)
456 return [s[offs:] for s in completions if s.startswith(mline)]
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700457
458 #
459 # Implement the "help_something" top-level command help
460 #
461 def impl_help_command(self, root_name):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700462 "Implementation of top-level 'help_something' command help"
463 root_command = self.commands_dict[root_name]
464 subtree_commands = self.collect_subtree_commands(root_command)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700465
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700466 #
467 # Loop through the commands and print the help for each command.
468 # NOTE: We add a command only if it has a callback.
469 #
470 print "Help for the `%s` command:" % (root_name)
471 for c in subtree_commands:
472 if c.callback is None:
473 continue
474 print " {0:30}{1:30}".format(c.name, c.help)
475 # if c.init_arg_parser is not None:
476 # parser = self.parsers_dict[c.name]
477 # parser.print_help()
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700478
479 #
480 # Traverse (breadth-first) a subtree and return all nodes except the
481 # root node.
482 #
483 def collect_subtree_commands(self, root_command):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700484 """Collect a subtree of commands.
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700485 Traverses (breadth-first) a subtree of commands and returns
486 all nodes except the root node."""
487
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700488 commands = []
489 subtree_commands = []
490 commands.append(root_command)
491 # Use breadth-first to traverse the subtree
492 while commands:
493 pc = commands.pop(0)
494 for c in pc.children:
495 commands.append(c)
496 subtree_commands.append(c)
497 return subtree_commands
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700498
499 def log_debug(self, msg):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700500 """Log debug information.
501 msg: the message to log
502 Use the following CLI commands to enable/disable debugging:
503 paramset debug true
504 paramset debug false
505 """
506 if self.debug:
507 print "%s" % (msg)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700508
509 def print_json_result(self, json_result):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700510 """Print JSON result."""
511 if len(json_result) == 0:
512 return
513 result = json.dumps(json_result, indent=4)
514 self.print_result(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700515
516 def print_result(self, result):
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700517 """Print parsed result."""
518 print "%s" % (result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700519
520 #
521 # Implementation of the "paramshow" CLI command.
522 #
523 # NOTE: The do_paramshow implementation below is copied from
524 # the cmd2.do_show() implementation
525 #
526 @options([make_option('-l', '--long', action="store_true",
527 help="describe function of parameter")])
528 def do_paramshow(self, arg, opts):
529 '''Shows value of a parameter.'''
530 param = arg.strip().lower()
531 result = {}
532 maxlen = 0
533 for p in self.settable:
534 if (not param) or p.startswith(param):
535 result[p] = '%s: %s' % (p, str(getattr(self, p)))
536 maxlen = max(maxlen, len(result[p]))
537 if result:
538 for p in sorted(result):
539 if opts.long:
540 self.poutput('%s # %s' % (result[p].ljust(maxlen), self.settable[p]))
541 else:
542 self.poutput(result[p])
543 else:
544 raise NotImplementedError("Parameter '%s' not supported (type 'show' for list of parameters)." % param)
545
546 #
547 # Implementation of the "paramset" CLI command.
548 #
549 #
550 # NOTE: The do_paramset implementation below is copied from
551 # the cmd2.do_set() implementation (with minor modifications).
552 #
553 def do_paramset(self, arg):
554 '''
555 Sets a cmd2 parameter. Accepts abbreviated parameter names so long
556 as there is no ambiguity. Call without arguments for a list of
557 settable parameters with their values.'''
558
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700559 class NotSettableError(Exception):
560 pass
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700561
562 try:
563 statement, paramName, val = arg.parsed.raw.split(None, 2)
564 val = val.strip()
565 paramName = paramName.strip().lower()
566 if paramName not in self.settable:
567 hits = [p for p in self.settable if p.startswith(paramName)]
568 if len(hits) == 1:
569 paramName = hits[0]
570 else:
571 return self.do_paramshow(paramName)
572 currentVal = getattr(self, paramName)
573 if (val[0] == val[-1]) and val[0] in ("'", '"'):
574 val = val[1:-1]
575 else:
576 val = cmd2.cast(currentVal, val)
577 setattr(self, paramName, val)
578 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val))
579 if currentVal != val:
580 try:
581 onchange_hook = getattr(self, '_onchange_%s' % paramName)
582 onchange_hook(old=currentVal, new=val)
583 except AttributeError:
584 pass
585 except (ValueError, AttributeError, NotSettableError) as exc:
586 self.do_paramshow(arg)
587
588
589def get_json(url):
590 """Make a REST GET call and return the JSON result
591 url: the URL to call"""
592
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700593 parsed_result = []
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700594 try:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700595 response = urllib2.urlopen(url)
596 result = response.read()
597 response.close()
598 if len(result) != 0:
599 parsed_result = json.loads(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700600 except HTTPError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700601 print "ERROR:"
602 print " REST GET URL: %s" % url
603 # NOTE: exc.fp contains the object with the response payload
604 error_payload = json.loads(exc.fp.read())
605 print " REST Error Code: %s" % (error_payload['code'])
606 print " REST Error Summary: %s" % (error_payload['summary'])
607 print " REST Error Description: %s" % (error_payload['formattedDescription'])
608 print " HTTP Error Code: %s" % exc.code
609 print " HTTP Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700610 except URLError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700611 print "ERROR:"
612 print " REST GET URL: %s" % url
613 print " URL Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700614 return parsed_result
615
616def post_json(url, data):
617 """Make a REST POST call and return the JSON result
618 url: the URL to call
619 data: the data to POST"""
620
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700621 parsed_result = []
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700622 data_json = json.dumps(data)
623 try:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700624 request = urllib2.Request(url, data_json)
625 request.add_header("Content-Type", "application/json")
626 response = urllib2.urlopen(request)
627 result = response.read()
628 response.close()
629 if len(result) != 0:
630 parsed_result = json.loads(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700631 except HTTPError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700632 print "ERROR:"
633 print " REST POST URL: %s" % url
634 # NOTE: exc.fp contains the object with the response payload
635 error_payload = json.loads(exc.fp.read())
636 print " REST Error Code: %s" % (error_payload['code'])
637 print " REST Error Summary: %s" % (error_payload['summary'])
638 print " REST Error Description: %s" % (error_payload['formattedDescription'])
639 print " HTTP Error Code: %s" % exc.code
640 print " HTTP Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700641 except URLError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700642 print "ERROR:"
643 print " REST POST URL: %s" % url
644 print " URL Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700645 return parsed_result
646
647def delete_json(url):
648 """Make a REST DELETE call and return the JSON result
649 url: the URL to call"""
650
Pavlin Radoslavovcf2b5532014-05-23 18:12:23 -0700651 parsed_result = []
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700652 try:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700653 request = urllib2.Request(url)
654 request.get_method = lambda: 'DELETE'
655 response = urllib2.urlopen(request)
656 result = response.read()
657 response.close()
658 if len(result) != 0:
659 parsed_result = json.loads(result)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700660 except HTTPError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700661 print "ERROR:"
662 print " REST DELETE URL: %s" % url
663 # NOTE: exc.fp contains the object with the response payload
664 error_payload = json.loads(exc.fp.read())
665 print " REST Error Code: %s" % (error_payload['code'])
666 print " REST Error Summary: %s" % (error_payload['summary'])
667 print " REST Error Description: %s" % (error_payload['formattedDescription'])
668 print " HTTP Error Code: %s" % exc.code
669 print " HTTP Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700670 except URLError as exc:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700671 print "ERROR:"
672 print " REST DELETE URL: %s" % url
673 print " URL Error Reason: %s" % exc.reason
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700674 return parsed_result
675
676if __name__ == '__main__':
677 onosCli = OnosCli()
678
679 # Setup the parser
680 parser = argparse.ArgumentParser()
681 parser.add_argument('-c', '--command', nargs=argparse.REMAINDER,
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700682 help="Run arguments to the end of the line as a CLI command")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700683 parser.add_argument('--onos-ip',
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700684 help="Set the ONOS IP address (for REST calls)")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700685 parser.add_argument('--onos-port',
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700686 help="Set the ONOS port number (for REST calls)")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700687 parser.add_argument('-t', '--test', nargs='+',
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700688 help="Test against transcript(s) in FILE (wildcards OK)")
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700689
690 # Parse the arguments
691 parsed_args = parser.parse_args()
692 if parsed_args.onos_ip:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700693 onosCli.onos_ip = parsed_args.onos_ip
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700694 if parsed_args.onos_port:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700695 onosCli.onos_port = parsed_args.onos_port
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700696 #
697 # NOTE: We have to reset the command-line options so the Cmd2 parser
698 # doesn't process them again.
699 #
700 sys.argv = [sys.argv[0]]
701
702 # Run the CLI as appropriate
703 if parsed_args.test:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700704 # Run CLI Transcript Tests
705 onosCli.runTranscriptTests(parsed_args.test)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700706 elif parsed_args.command:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700707 # Run arguments as a CLI command
708 command_line = ' '.join(parsed_args.command)
709 onosCli.onecmd(command_line)
Pavlin Radoslavovb94817b2014-05-22 21:12:47 -0700710 else:
Pavlin Radoslavov8500fc02014-05-28 14:04:55 -0700711 # Run interactive CLI
712 onosCli.cmdloop()