-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.py
215 lines (171 loc) · 5.94 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""
Inspired in the mininet CLI.
"""
import subprocess
from cmd import Cmd
from os import isatty
from select import poll, POLLIN
import select
import sys
import os
import atexit
class RSVPCLI( Cmd ):
"Simple command-line interface to talk to nodes."
prompt = 'rsvp-menu> '
def __init__( self, controller, stdin=sys.stdin, script=None,
*args, **kwargs ):
self.controller = controller
# Local variable bindings for py command
self.locals = { 'controller': controller }
# Attempt to handle input
self.inPoller = poll()
self.inPoller.register( stdin )
self.inputFile = script
Cmd.__init__( self, *args, stdin=stdin, **kwargs )
self.hello_msg()
if self.inputFile:
self.do_source( self.inputFile )
return
self.initReadline()
self.run()
readlineInited = False
def hello_msg(self):
"""
"""
print('======================================================================')
print('Welcome to the RSVP CLI')
print('======================================================================')
print('You can now make reservations for your hosts in the network.')
print('To add a reservation run:')
print('add_reservation <src> <dst> <duration> <bw>')
print('')
print('To delete a reservation run: ')
print('del_reservation <src> <dst>')
print('')
@classmethod
def initReadline( cls ):
"Set up history if readline is available"
# Only set up readline once to prevent multiplying the history file
if cls.readlineInited:
return
cls.readlineInited = True
try:
from readline import ( read_history_file, write_history_file,
set_history_length )
except ImportError:
pass
else:
history_path = os.path.expanduser( '~/.rsvp_controller_history' )
if os.path.isfile( history_path ):
read_history_file( history_path )
set_history_length( 1000 )
atexit.register( lambda: write_history_file( history_path ) )
def run( self ):
"Run our cmdloop(), catching KeyboardInterrupt"
while True:
try:
if self.isatty():
subprocess.call( 'stty echo sane intr ^C',shell=True)
self.cmdloop()
break
except KeyboardInterrupt:
# Output a message - unless it's also interrupted
# pylint: disable=broad-except
try:
print( '\nInterrupt\n' )
except Exception:
pass
# pylint: enable=broad-except
def emptyline( self ):
"Don't repeat last command when you hit return."
pass
def getLocals( self ):
"Local variable bindings for py command"
self.locals.update( self.mn )
return self.locals
helpStr = (
'To add a reservation run:\n'
'add_reservation <src> <dst> <duration> <bw>\n'
'\n'
'To delete a reservation run: \n'
'del_reservation <src> <dst>\n'
''
)
def do_help( self, line ):
"Describe available CLI commands."
Cmd.do_help( self, line )
if line == '':
print( self.helpStr )
def do_exit( self, _line ):
"Exit"
assert self # satisfy pylint and allow override
return 'exited by user command'
def do_quit( self, line ):
"Exit"
return self.do_exit( line )
def do_EOF( self, line ):
"Exit"
print( '\n' )
return self.do_exit( line )
def isatty( self ):
"Is our standard input a tty?"
return isatty( self.stdin.fileno() )
"""
RSVP COMMANDS
"""
def do_add_reservation(self, line=""):
"""Adds a reservation using mpls.
add_reservation <src> <dst> <duration> <bw>
"""
# geta rguments
args = line.split()
# defaults
duration = 9999
bw = 1
if len(args) < 2:
print("Not enough args!")
return
elif len(args) == 2:
src, dst = args
elif len(args) == 3:
src, dst, duration = args
elif len(args) == 4:
src, dst, duration, bw = args
else:
print("Too many args!")
return
# casts
duration = float(duration)
bw = float(bw)
# add entry
res = self.controller.add_reservation(src, dst, duration, bw)
def do_del_reservation(self, line=""):
"""Deletes a reservation"""
# gets arguments
args = line.split()
if len(args) < 2:
print("Not enough args!")
return
elif len(args) == 2:
src, dst = args[:2]
else:
print("Too many args!")
return
# add entry
res = self.controller.del_reservation(src, dst)
def do_del_all_reservations(self, line =""):
"""Deletes all the reservations"""
res = self.controller.del_all_reservations()
def do_print_reservations(self, line = ""):
"""Prints current reservations"""
print("Current Reservations:")
print("---------------------")
for i, ((src, dst), data) in enumerate(self.controller.current_reservations.items()):
print("{:>3} {}->{} : {}, bw:{}, timeout:{}".format(i, src, dst,
"->".join(data['path']), data['bw'], data["timeout"] ))
def do_print_link_capacity(self, line=""):
"""Prints current link capacities"""
print("Current Link Capacities:")
print("---------------------")
for edge, bw in self.controller.links_capacity.items():
print("{} -> {}".format(edge, bw))