backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / cmd / of_config_cli.py
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
4 # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 #    http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18
19 # a simple command line OF-CONFIG client
20 #
21 # a usage example:
22 #     % PYTHONPATH=. ./bin/of_config_cli \
23 #      --peers=sw1=localhost:1830:username:password
24 #     (Cmd) raw_get sw1
25
26 from __future__ import print_function
27
28 import cmd
29 import sys
30
31 import lxml.etree as ET
32 from ncclient.operations.rpc import RPCError
33
34 from ryu import cfg
35 from ryu.lib import of_config
36 from ryu.lib.of_config import capable_switch
37 import ryu.lib.of_config.classes as ofc
38
39
40 CONF = cfg.CONF
41 CONF.register_cli_opts([
42     cfg.ListOpt('peers', default=[], help='list of peers')
43 ])
44
45
46 class Peer(capable_switch.OFCapableSwitch):
47     def __init__(self, name, host, port, username, password):
48         self._name = name
49         super(Peer, self).__init__(
50             host=host, port=port, username=username, password=password,
51             unknown_host_cb=lambda host, fingeprint: True)
52
53
54 peers = {}
55
56
57 def add_peer(name, host, port, username, password):
58     peers[name] = Peer(name, host, port, username, password)
59
60
61 def et_tostring_pp(tree):
62     # pretty_print is an lxml feature, not available in ElementTree
63     try:
64         return ET.tostring(tree, pretty_print=True)
65     except TypeError:
66         return ET.tostring(tree)
67
68
69 def validate(tree):
70     schema = ET.XMLSchema(file=of_config.OF_CONFIG_1_1_1_XSD)
71     if not schema(tree):
72         print(schema.error_log)
73
74
75 class Cmd(cmd.Cmd):
76     def __init__(self, *args, **kwargs):
77         self._in_onecmd = False
78         cmd.Cmd.__init__(self, *args, **kwargs)
79
80     def _request(self, line, f):
81         args = line.split()
82         try:
83             peer = args[0]
84         except:
85             print("argument error")
86             return
87         try:
88             p = peers[peer]
89         except KeyError:
90             print("unknown peer %s" % peer)
91             return
92         try:
93             f(p, args[1:])
94         except RPCError as e:
95             print("RPC Error %s" % e)
96         except EOFError:
97             print("disconnected")
98
99     def _complete_peer(self, text, line, _begidx, _endidx):
100         if len((line + 'x').split()) >= 3:
101             return []
102         return [name for name in peers if name.startswith(text)]
103
104     def do_list_cap(self, line):
105         """list_cap <peer>
106         """
107
108         def f(p, args):
109             for i in p.netconf.server_capabilities:
110                 print(i)
111
112         self._request(line, f)
113
114     def do_raw_get(self, line):
115         """raw_get <peer>
116         """
117
118         def f(p, args):
119             result = p.raw_get()
120             tree = ET.fromstring(result)
121             validate(tree)
122             print(et_tostring_pp(tree))
123
124         self._request(line, f)
125
126     def do_raw_get_config(self, line):
127         """raw_get_config <peer> <source>
128         """
129
130         def f(p, args):
131             try:
132                 source = args[0]
133             except:
134                 print("argument error")
135                 return
136             result = p.raw_get_config(source)
137             tree = ET.fromstring(result)
138             validate(tree)
139             print(et_tostring_pp(tree))
140
141         self._request(line, f)
142
143     def do_get(self, line):
144         """get <peer>
145         eg. get sw1
146         """
147
148         def f(p, args):
149             print(p.get())
150
151         self._request(line, f)
152
153     def do_commit(self, line):
154         """commit <peer>
155         eg. commit sw1
156         """
157
158         def f(p, args):
159             print(p.commit())
160
161         self._request(line, f)
162
163     def do_discard(self, line):
164         """discard <peer>
165         eg. discard sw1
166         """
167
168         def f(p, args):
169             print(p.discard_changes())
170
171         self._request(line, f)
172
173     def do_get_config(self, line):
174         """get_config <peer> <source>
175         eg. get_config sw1 startup
176         """
177
178         def f(p, args):
179             try:
180                 source = args[0]
181             except:
182                 print("argument error")
183                 return
184             print(p.get_config(source))
185
186         self._request(line, f)
187
188     def do_delete_config(self, line):
189         """delete_config <peer> <source>
190         eg. delete_config sw1 startup
191         """
192
193         def f(p, args):
194             try:
195                 source = args[0]
196             except:
197                 print("argument error")
198                 return
199             print(p.delete_config(source))
200
201         self._request(line, f)
202
203     def do_copy_config(self, line):
204         """copy_config <peer> <source> <target>
205         eg. copy_config sw1 running startup
206         """
207
208         def f(p, args):
209             try:
210                 source, target = args
211             except:
212                 print("argument error")
213                 return
214             print(p.copy_config(source, target))
215
216         self._request(line, f)
217
218     def do_list_port(self, line):
219         """list_port <peer>
220         """
221
222         def f(p, args):
223             o = p.get()
224             for p in o.resources.port:
225                 print('%s %s %s' % (p.resource_id, p.name, p.number))
226
227         self._request(line, f)
228
229     _port_settings = [
230         'admin-state',
231         'no-forward',
232         'no-packet-in',
233         'no-receive',
234     ]
235
236     def do_get_port_config(self, line):
237         """get_config_port <peer> <source> <port>
238         eg. get_port_config sw1 running LogicalSwitch7-Port2
239         """
240
241         def f(p, args):
242             try:
243                 source, port = args
244             except:
245                 print("argument error")
246                 return
247             o = p.get_config(source)
248             for p in o.resources.port:
249                 if p.resource_id != port:
250                     continue
251                 print(p.resource_id)
252                 conf = p.configuration
253                 for k in self._port_settings:
254                     try:
255                         v = getattr(conf, k)
256                     except AttributeError:
257                         continue
258                     print('%s %s' % (k, v))
259
260         self._request(line, f)
261
262     def do_set_port_config(self, line):
263         """set_port_config <peer> <target> <port> <key> <value>
264         eg. set_port_config sw1 running LogicalSwitch7-Port2 admin-state down
265         eg. set_port_config sw1 running LogicalSwitch7-Port2 no-forward false
266         """
267
268         def f(p, args):
269             try:
270                 target, port, key, value = args
271             except:
272                 print("argument error")
273                 print(args)
274                 return
275
276             # get switch id
277             o = p.get()
278             capable_switch_id = o.id
279
280             try:
281                 capable_switch = ofc.OFCapableSwitchType(
282                     id=capable_switch_id,
283                     resources=ofc.OFCapableSwitchResourcesType(
284                         port=[
285                             ofc.OFPortType(
286                                 resource_id=port,
287                                 configuration=ofc.OFPortConfigurationType(
288                                     **{key: value}))
289                         ]
290                     )
291                 )
292             except TypeError:
293                 print("argument error")
294                 return
295             try:
296                 p.edit_config(target, capable_switch)
297             except Exception as e:
298                 print(e)
299
300         self._request(line, f)
301
302     def do_list_queue(self, line):
303         """list_queue <peer>
304         """
305
306         def f(p, args):
307             o = p.get()
308             if o.resources.queue:
309                 for q in o.resources.queue:
310                     print('%s %s' % (q.resource_id, q.port))
311
312         self._request(line, f)
313
314     _queue_settings = [
315         'max-rate',
316         'min-rate',
317         'experimenter',
318     ]
319
320     def do_get_queue_config(self, line):
321         """get_queue_port <peer> <source> <queue>
322         eg. get_queue_config sw1 running LogicalSwitch7-Port1-Queue922
323         """
324
325         def f(p, args):
326             try:
327                 source, queue = args
328             except:
329                 print("argument error")
330                 return
331             o = p.get_config(source)
332             for q in o.resources.queue:
333                 if q.resource_id != queue:
334                     continue
335                 print(q.resource_id)
336                 conf = q.properties
337                 for k in self._queue_settings:
338                     try:
339                         v = getattr(conf, k)
340                     except AttributeError:
341                         continue
342                     print('%s %s' % (k, v))
343
344         self._request(line, f)
345
346     def do_set_queue_config(self, line):
347         """set_queue_config <peer> <target> <queue> <key> <value>
348         eg. set_queue_config sw1 running LogicalSwitch7-Port1-Queue922 \
349 max-rate 100
350         """
351
352         def f(p, args):
353             try:
354                 target, queue, key, value = args
355             except:
356                 print("argument error")
357                 print(args)
358                 return
359
360             # get switch id
361             o = p.get()
362             capable_switch_id = o.id
363
364             try:
365                 capable_switch = ofc.OFCapableSwitchType(
366                     id=capable_switch_id,
367                     resources=ofc.OFCapableSwitchResourcesType(
368                         queue=[
369                             ofc.OFQueueType(
370                                 resource_id=queue,
371                                 properties=ofc.OFQueuePropertiesType(
372                                     **{key: value})),
373                         ]
374                     )
375                 )
376             except TypeError:
377                 print("argument error")
378                 return
379             try:
380                 p.edit_config(target, capable_switch)
381             except Exception as e:
382                 print(e)
383
384         self._request(line, f)
385
386     def do_add_queue(self, line):
387         """add_queue <peer> <target> <logical-switch> <queue>
388         eg. add_queue sw1 running LogicalSwitch7 NameOfNewQueue
389         """
390
391         def f(p, args):
392             try:
393                 target, lsw, queue = args
394             except:
395                 print("argument error")
396                 print(args)
397                 return
398
399             # get switch id
400             o = p.get()
401             capable_switch_id = o.id
402
403             try:
404                 capable_switch = ofc.OFCapableSwitchType(
405                     id=capable_switch_id,
406                     resources=ofc.OFCapableSwitchResourcesType(
407                         queue=[
408                             ofc.OFQueueType(resource_id=queue)
409                         ]
410                     ),
411                     logical_switches=ofc.OFCapableSwitchLogicalSwitchesType(
412                         switch=[ofc.OFLogicalSwitchType(
413                             id=lsw,
414                             resources=ofc.OFLogicalSwitchResourcesType(
415                                 queue=[queue])
416                         )]
417                     )
418                 )
419             except TypeError:
420                 print("argument error")
421                 return
422             try:
423                 p.edit_config(target, capable_switch)
424             except Exception as e:
425                 print(e)
426
427         self._request(line, f)
428
429     def do_list_logical_switch(self, line):
430         """list_logical_switch <peer>
431         """
432
433         def f(p, args):
434             o = p.get()
435             for s in o.logical_switches.switch:
436                 print('%s %s' % (s.id, s.datapath_id))
437
438         self._request(line, f)
439
440     def do_show_logical_switch(self, line):
441         """show_logical_switch <peer> <logical switch>
442         """
443
444         def f(p, args):
445             try:
446                 (lsw,) = args
447             except:
448                 print("argument error")
449                 return
450             o = p.get()
451             for s in o.logical_switches.switch:
452                 if s.id != lsw:
453                     continue
454                 print(s.id)
455                 print('datapath-id %s' % s.datapath_id)
456                 if s.resources.queue:
457                     print('queues:')
458                     for q in s.resources.queue:
459                         print('\t %s' % q)
460                 if s.resources.port:
461                     print('ports:')
462                     for p in s.resources.port:
463                         print('\t %s' % p)
464
465         self._request(line, f)
466
467     _lsw_settings = [
468         'lost-connection-behavior',
469     ]
470
471     def do_get_logical_switch_config(self, line):
472         """get_logical_switch_config <peer> <source> <logical switch>
473         """
474
475         def f(p, args):
476             try:
477                 source, lsw = args
478             except:
479                 print("argument error")
480                 return
481             o = p.get_config(source)
482             for l in o.logical_switches.switch:
483                 if l.id != lsw:
484                     continue
485                 print(l.id)
486                 for k in self._lsw_settings:
487                     try:
488                         v = getattr(l, k)
489                     except AttributeError:
490                         continue
491                     print('%s %s' % (k, v))
492
493         self._request(line, f)
494
495     def do_set_logical_switch_config(self, line):
496         """set_logical_switch_config <peer> <logical switch> <key> <value>
497         eg. set_logical_switch_config sw1 running LogicalSwitch7 \
498 lost-connection-behavior failStandaloneMode
499         """
500
501         def f(p, args):
502             try:
503                 target, lsw, key, value = args
504             except:
505                 print("argument error")
506                 return
507
508             # get switch id
509             o = p.get_config(target)
510             capable_switch_id = o.id
511
512             try:
513                 capable_switch = ofc.OFCapableSwitchType(
514                     id=capable_switch_id,
515                     logical_switches=ofc.OFCapableSwitchLogicalSwitchesType(
516                         switch=[ofc.OFLogicalSwitchType(
517                             id=lsw,
518                             **{key: value}
519                         )]
520                     )
521                 )
522             except TypeError:
523                 print("argument error")
524                 return
525             try:
526                 p.edit_config(target, capable_switch)
527             except Exception as e:
528                 print(e)
529
530         self._request(line, f)
531
532     completedefault = _complete_peer
533
534     def complete_EOF(self, _text, _line, _begidx, _endidx):
535         return []
536
537     def do_EOF(self, _line):
538         sys.exit(0)
539
540     def onecmd(self, string):
541         self._in_onecmd = True
542         try:
543             return cmd.Cmd.onecmd(self, string)
544         finally:
545             self._in_onecmd = False
546
547
548 def main(args=None, prog=None):
549     CONF(args=args, prog=prog,
550          project='of-config-cli', version='of-config-cli')
551
552     for p_str in CONF.peers:
553         name, addr = p_str.split('=')
554         host, port, username, password = addr.rsplit(':', 3)
555         add_peer(name, host, port, username, password)
556
557     Cmd().cmdloop()
558
559
560 if __name__ == "__main__":
561     main()