blob: 260b6535ca994b6c0f0932a14f5a38db19ddf7dc [file] [log] [blame]
Zsolt Harasztid036b7e2016-12-23 15:36:01 -08001#!/usr/bin/env python
2#
3# Copyright 2016 the original author or authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18"""
19Device level CLI commands
20"""
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -040021from optparse import make_option
22from cmd2 import Cmd, options
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080023from simplejson import dumps
24
Zsolt Haraszti85f12852016-12-24 08:30:58 -080025from cli.table import print_pb_as_table, print_pb_list_as_table
Lydia Fang01f2e852017-06-28 17:24:58 -070026from cli.utils import print_flows, pb2dict, enum2name
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080027from voltha.protos import third_party
28
29_ = third_party
Lydia Fang01f2e852017-06-28 17:24:58 -070030from voltha.protos import voltha_pb2, common_pb2
Sergio Slobodrian3ba3d562017-04-21 10:07:56 -040031import sys
Lydia Fang01f2e852017-06-28 17:24:58 -070032import json
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -040033from google.protobuf.json_format import MessageToDict
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080034
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -040035# Since proto3 won't send fields that are set to 0/false/"" any object that
36# might have those values set in them needs to be replicated here such that the
Sergio Slobodrian3ba3d562017-04-21 10:07:56 -040037# fields can be adequately
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080038
Chip Boling825764b2018-08-17 16:17:07 -050039
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080040class DeviceCli(Cmd):
41
khenaidoo108f05c2017-07-06 11:15:29 -040042 def __init__(self, device_id, get_stub):
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080043 Cmd.__init__(self)
khenaidoo108f05c2017-07-06 11:15:29 -040044 self.get_stub = get_stub
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080045 self.device_id = device_id
46 self.prompt = '(' + self.colorize(
47 self.colorize('device {}'.format(device_id), 'red'), 'bold') + ') '
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -040048 self.pm_config_last = None
49 self.pm_config_dirty = False
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080050
Zsolt Haraszti9b485fb2016-12-26 23:11:15 -080051 def cmdloop(self):
52 self._cmdloop()
53
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080054 def get_device(self, depth=0):
khenaidoo108f05c2017-07-06 11:15:29 -040055 stub = self.get_stub()
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080056 res = stub.GetDevice(voltha_pb2.ID(id=self.device_id),
57 metadata=(('get-depth', str(depth)), ))
58 return res
59
Zsolt Haraszti80175202016-12-24 00:17:51 -080060 do_exit = Cmd.do_quit
Zsolt Harasztid036b7e2016-12-23 15:36:01 -080061
Sergio Slobodrian6e9fb692017-03-17 14:46:33 -040062 def do_quit(self, line):
63 if self.pm_config_dirty:
64 self.poutput("Uncommited changes for " + \
65 self.colorize(
66 self.colorize("perf_config,", "blue"),
67 "bold") + " please either " + self.colorize(
68 self.colorize("commit", "blue"), "bold") + \
69 " or " + self.colorize(
70 self.colorize("reset", "blue"), "bold") + \
71 " your changes using " + \
72 self.colorize(
73 self.colorize("perf_config", "blue"), "bold"))
74 return False
75 else:
76 return self._STOP_AND_EXIT
77
Zsolt Haraszti80175202016-12-24 00:17:51 -080078 def do_show(self, line):
79 """Show detailed device information"""
Zsolt Haraszti85f12852016-12-24 08:30:58 -080080 print_pb_as_table('Device {}'.format(self.device_id),
Sergio Slobodriana95f99b2017-03-21 10:22:47 -040081 self.get_device(depth=-1))
Zsolt Haraszti85f12852016-12-24 08:30:58 -080082
83 def do_ports(self, line):
84 """Show ports of device"""
85 device = self.get_device(depth=-1)
86 omit_fields = {
87 }
88 print_pb_list_as_table('Device ports:', device.ports,
89 omit_fields, self.poutput)
Zsolt Haraszti80175202016-12-24 00:17:51 -080090
Sergio Slobodrian3ba3d562017-04-21 10:07:56 -040091 def complete_perf_config(self, text, line, begidx, endidx):
92 sub_cmds = {"show", "set", "commit", "reset"}
93 sub_opts = {"-f", "-e", "-d", "-o"}
94 # Help the interpreter complete the paramters.
95 completions = []
96 if not self.pm_config_last:
97 device = self.get_device(depth=-1)
98 self.pm_config_last = device.pm_configs
99 m_names = [d.name for d in self.pm_config_last.metrics]
100 cur_cmd = line.strip().split(" ")
101 try:
102 if not text and len(cur_cmd) == 1:
103 completions = ("show", "set", "commit", "reset")
104 elif len(cur_cmd) == 2:
105 if "set" == cur_cmd[1]:
106 completions = [d for d in sub_opts]
107 else:
108 completions = [d for d in sub_cmds if d.startswith(text)]
109 elif len(cur_cmd) > 2 and cur_cmd[1] == "set":
110 if cur_cmd[len(cur_cmd)-1] == "-":
111 completions = [list(d)[1] for d in sub_opts]
112 elif cur_cmd[len(cur_cmd)-1] == "-f":
113 completions = ("\255","Please enter a sampling frequency in 10ths of a second")
114 elif cur_cmd[len(cur_cmd)-2] == "-f":
115 completions = [d for d in sub_opts]
116 elif cur_cmd[len(cur_cmd)-1] in {"-e","-d","-o"}:
117 if self.pm_config_last.grouped:
118 pass
119 else:
120 completions = [d.name for d in self.pm_config_last.metrics]
121 elif cur_cmd[len(cur_cmd)-2] in {"-e","-d"}:
122 if text and text not in m_names:
123 completions = [d for d in m_names if d.startswith(text)]
124 else:
125 completions = [d for d in sub_opts]
126 elif cur_cmd[len(cur_cmd)-2] == "-o":
127 if cur_cmd[len(cur_cmd)-1] in [d.name for d in self.pm_config_last.metrics]:
128 completions = ("\255","Please enter a sampling frequency in 10ths of a second")
129 else:
130 completions = [d for d in m_names if d.startswith(text)]
131 elif cur_cmd[len(cur_cmd)-3] == "-o":
132 completions = [d for d in sub_opts]
133 except:
134 e = sys.exc_info()
135 print(e)
136 return completions
137
138
Sergio Slobodrian6e9fb692017-03-17 14:46:33 -0400139 def help_perf_config(self):
140 self.poutput(
141'''
Sergio Slobodrian57979ec2017-03-21 22:32:17 -0400142perf_config [show | set | commit | reset] [-f <default frequency>] [{-e <metric/group
143 name>}] [{-d <metric/group name>}] [{-o <metric/group name> <override
144 frequency>}]
Sergio Slobodrian038bd3c2017-03-22 15:53:25 -0400145
Sergio Slobodrian3fb99b32017-03-22 22:18:21 -0400146show: displays the performance configuration of the device
Sergio Slobodrian57979ec2017-03-21 22:32:17 -0400147set: changes the parameters specified with -e, -d, and -o
148reset: reverts any changes made since the last commit
149commit: commits any changes made which applies them to the device.
150
151-e: enable collection of the specified metric, more than one -e may be
152 specified.
Sergio Slobodrian3fb99b32017-03-22 22:18:21 -0400153-d: disable collection of the specified metric, more than on -d may be
Sergio Slobodrian57979ec2017-03-21 22:32:17 -0400154 specified.
Sergio Slobodrianec6e3912017-04-02 11:46:55 -0400155-o: override the collection frequency of the specified metric, more than one -o
Sergio Slobodrian57979ec2017-03-21 22:32:17 -0400156 may be specified. Note that -o isn't valid unless
Sergio Slobodrian3fb99b32017-03-22 22:18:21 -0400157 frequency_override is set to True for the device.
Sergio Slobodrian57979ec2017-03-21 22:32:17 -0400158
Sergio Slobodrian6e9fb692017-03-17 14:46:33 -0400159Changes made by set are held locally until a commit or reset command is issued.
160A commit command will write the configuration to the device and it takes effect
Chip Boling825764b2018-08-17 16:17:07 -0500161immediately. The reset command will undo any changes since the start of the
Sergio Slobodrian6e9fb692017-03-17 14:46:33 -0400162device session.
163
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400164If grouped is true then the -d, -e and -o commands refer to groups and not
Sergio Slobodrian6e9fb692017-03-17 14:46:33 -0400165individual metrics.
166'''
167 )
168
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400169 @options([
170 make_option('-f', '--default_freq', action="store", dest='default_freq',
171 type='long', default=None),
172 make_option('-e', '--enable', action='append', dest='enable',
173 default=None),
174 make_option('-d', '--disable', action='append', dest='disable',
175 default=None),
Chip Boling825764b2018-08-17 16:17:07 -0500176 make_option('-o', '--override', action='append', dest='override',
Sergio Slobodrian6e9fb692017-03-17 14:46:33 -0400177 nargs=2, default=None, type='string'),
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400178 ])
179 def do_perf_config(self, line, opts):
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400180 """Show and set the performance monitoring configuration of the device"""
181
182 device = self.get_device(depth=-1)
183 if not self.pm_config_last:
184 self.pm_config_last = device.pm_configs
185
186 # Ensure that a valid sub-command was provided
187 if line.strip() not in {"set", "show", "commit", "reset", ""}:
Chip Boling825764b2018-08-17 16:17:07 -0500188 self.poutput(self.colorize('Error: ', 'red') +
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400189 self.colorize(self.colorize(line.strip(), 'blue'),
190 'bold') + ' is not recognized')
191 return
192
193 # Ensure no options are provided when requesting to view the config
194 if line.strip() == "show" or line.strip() == "":
195 if opts.default_freq or opts.enable or opts.disable:
196 self.poutput(opts.disable)
Chip Boling825764b2018-08-17 16:17:07 -0500197 self.poutput(self.colorize('Error: ', 'red') + 'use ' +
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400198 self.colorize(self.colorize('"set"', 'blue'),
199 'bold') + ' to change settings')
200 return
201
Chip Boling825764b2018-08-17 16:17:07 -0500202 if line.strip() == "set": # Set the supplied values
203 metric_list = set()
204 if opts.enable is not None:
205 metric_list |= {metric for metric in opts.enable}
206 if opts.disable is not None:
207 metric_list |= {metric for metric in opts.disable}
208 if opts.override is not None:
209 metric_list |= {metric for metric, _ in opts.override}
210
211 # The default frequency
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400212 if opts.default_freq:
213 self.pm_config_last.default_freq = opts.default_freq
214 self.pm_config_dirty = True
215
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400216 # Field or group visibility
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400217 if self.pm_config_last.grouped:
218 for g in self.pm_config_last.groups:
219 if opts.enable:
220 if g.group_name in opts.enable:
221 g.enabled = True
222 self.pm_config_dirty = True
Chip Boling825764b2018-08-17 16:17:07 -0500223 metric_list.discard(g.group_name)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400224 for g in self.pm_config_last.groups:
225 if opts.disable:
226 if g.group_name in opts.disable:
227 g.enabled = False
228 self.pm_config_dirty = True
Chip Boling825764b2018-08-17 16:17:07 -0500229 metric_list.discard(g.group_name)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400230 else:
231 for m in self.pm_config_last.metrics:
232 if opts.enable:
233 if m.name in opts.enable:
234 m.enabled = True
235 self.pm_config_dirty = True
Chip Boling825764b2018-08-17 16:17:07 -0500236 metric_list.discard(m.name)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400237 for m in self.pm_config_last.metrics:
238 if opts.disable:
239 if m.name in opts.disable:
240 m.enabled = False
241 self.pm_config_dirty = True
Chip Boling825764b2018-08-17 16:17:07 -0500242 metric_list.discard(m.name)
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400243
Chip Boling825764b2018-08-17 16:17:07 -0500244 # Frequency overrides.
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400245 if opts.override:
246 if self.pm_config_last.freq_override:
247 oo = dict()
248 for o in opts.override:
249 oo[o[0]] = o[1]
250 if self.pm_config_last.grouped:
251 for g in self.pm_config_last.groups:
252 if g.group_name in oo:
253 try:
254 g.group_freq = int(oo[g.group_name])
255 except ValueError:
256 self.poutput(self.colorize('Warning: ',
Chip Boling825764b2018-08-17 16:17:07 -0500257 'yellow') +
258 self.colorize(oo[g.group_name],
259 'blue') +
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400260 " is not an integer... ignored")
261 del oo[g.group_name]
262 self.pm_config_dirty = True
Chip Boling825764b2018-08-17 16:17:07 -0500263 metric_list.discard(g.group_name)
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400264 else:
265 for m in self.pm_config_last.metrics:
266 if m.name in oo:
267 try:
268 m.sample_freq = int(oo[m.name])
269 except ValueError:
270 self.poutput(self.colorize('Warning: ',
Chip Boling825764b2018-08-17 16:17:07 -0500271 'yellow') +
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400272 self.colorize(oo[m.name],
Chip Boling825764b2018-08-17 16:17:07 -0500273 'blue') +
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400274 " is not an integer... ignored")
275 del oo[m.name]
276 self.pm_config_dirty = True
Chip Boling825764b2018-08-17 16:17:07 -0500277 metric_list.discard(m.name)
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400278
279 # If there's anything left the input was typoed
280 if self.pm_config_last.grouped:
281 field = 'group'
282 else:
283 field = 'metric'
284 for o in oo:
Chip Boling825764b2018-08-17 16:17:07 -0500285 self.poutput(self.colorize('Warning: ', 'yellow') +
286 'the parameter' + ' ' +
287 self.colorize(o, 'blue') + ' is not ' +
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400288 'a ' + field + ' name... ignored')
289 if oo:
290 return
291
Chip Boling825764b2018-08-17 16:17:07 -0500292 else: # Frequency overrides not enabled
293 self.poutput(self.colorize('Error: ', 'red') +
294 'Individual overrides are only ' +
295 'supported if ' +
296 self.colorize('freq_override', 'blue') +
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400297 ' is set to ' + self.colorize('True', 'blue'))
298 return
Chip Boling825764b2018-08-17 16:17:07 -0500299
300 if len(metric_list):
301 metric_name_list = ", ".join(str(metric) for metric in metric_list)
302 self.poutput(self.colorize('Error: ', 'red') +
303 'Metric/Metric Group{} '.format('s' if len(metric_list) > 1 else '') +
304 self.colorize(metric_name_list, 'blue') +
305 ' {} not found'.format('were' if len(metric_list) > 1 else 'was'))
306 return
307
Sergio Slobodrian4236ade2017-03-17 22:01:20 -0400308 self.poutput("Success")
309 return
310
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400311 elif line.strip() == "commit" and self.pm_config_dirty:
khenaidoo108f05c2017-07-06 11:15:29 -0400312 stub = self.get_stub()
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400313 stub.UpdateDevicePmConfigs(self.pm_config_last)
314 self.pm_config_last = self.get_device(depth=-1).pm_configs
315 self.pm_config_dirty = False
Chip Boling825764b2018-08-17 16:17:07 -0500316
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400317 elif line.strip() == "reset" and self.pm_config_dirty:
318 self.pm_config_last = self.get_device(depth=-1).pm_configs
319 self.pm_config_dirty = False
320
321 omit_fields = {'groups', 'metrics', 'id'}
322 print_pb_as_table('PM Config:', self.pm_config_last, omit_fields,
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400323 self.poutput,show_nulls=True)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400324 if self.pm_config_last.grouped:
325 #self.poutput("Supported metric groups:")
326 for g in self.pm_config_last.groups:
327 if self.pm_config_last.freq_override:
328 omit_fields = {'metrics'}
329 else:
330 omit_fields = {'group_freq','metrics'}
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400331 print_pb_as_table('', g, omit_fields, self.poutput,
332 show_nulls=True)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400333 if g.enabled:
334 state = 'enabled'
335 else:
336 state = 'disabled'
337 print_pb_list_as_table(
Sergio Slobodriana4b89c02017-04-03 12:48:36 -0400338 'Metric group {} is {}'.format(g.group_name,state),
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400339 g.metrics, {'enabled', 'sample_freq'}, self.poutput,
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400340 dividers=100, show_nulls=True)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400341 else:
342 if self.pm_config_last.freq_override:
343 omit_fields = {}
344 else:
345 omit_fields = {'sample_freq'}
346 print_pb_list_as_table('Supported metrics:', self.pm_config_last.metrics,
Sergio Slobodrian038bd3c2017-03-22 15:53:25 -0400347 omit_fields, self.poutput, dividers=100,
348 show_nulls=True)
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400349
Zsolt Haraszti80175202016-12-24 00:17:51 -0800350 def do_flows(self, line):
Zsolt Harasztid036b7e2016-12-23 15:36:01 -0800351 """Show flow table for device"""
352 device = pb2dict(self.get_device(-1))
353 print_flows(
354 'Device',
355 self.device_id,
356 type=device['type'],
357 flows=device['flows']['items'],
ntoorchi42256462019-05-30 15:49:59 -0700358 groups=device['flow_groups']['items'],
359 fields_to_omit=['table_id', 'goto-table']
Zsolt Harasztid036b7e2016-12-23 15:36:01 -0800360 )
361
ggowdru236bd952017-06-20 20:32:55 -0700362 def do_images(self, line):
363 """Show software images on the device"""
364 device = self.get_device(depth=-1)
365 omit_fields = {}
366 print_pb_list_as_table('Software Images:', device.images.image,
367 omit_fields, self.poutput, show_nulls=True)
368
Lydia Fang01f2e852017-06-28 17:24:58 -0700369 @options([
370 make_option('-u', '--url', action='store', dest='url',
371 help="URL to get sw image"),
372 make_option('-n', '--name', action='store', dest='name',
373 help="Image name"),
374 make_option('-c', '--crc', action='store', dest='crc',
375 help="CRC code to verify with", default=0),
376 make_option('-v', '--version', action='store', dest='version',
377 help="Image version", default=0),
lcui33d6a8e2018-08-28 12:51:38 -0700378 make_option('-d', '--dir', action='store', dest='dir',
379 help="local directory"),
Lydia Fang01f2e852017-06-28 17:24:58 -0700380 ])
381 def do_img_dnld_request(self, line, opts):
382 """
383 Request image download to a device
384 """
385 device = self.get_device(depth=-1)
386 self.poutput('device_id {}'.format(device.id))
387 self.poutput('name {}'.format(opts.name))
388 self.poutput('url {}'.format(opts.url))
389 self.poutput('crc {}'.format(opts.crc))
390 self.poutput('version {}'.format(opts.version))
lcui33d6a8e2018-08-28 12:51:38 -0700391 self.poutput('local dir {}'.format(opts.dir))
Lydia Fang01f2e852017-06-28 17:24:58 -0700392 try:
393 device_id = device.id
394 if device_id and opts.name and opts.url:
395 kw = dict(id=device_id)
396 kw['name'] = opts.name
397 kw['url'] = opts.url
398 else:
399 self.poutput('Device ID and URL are needed')
400 raise Exception('Device ID and URL are needed')
lcui33d6a8e2018-08-28 12:51:38 -0700401 if opts.dir:
402 kw['local_dir'] = opts.dir
Lydia Fang01f2e852017-06-28 17:24:58 -0700403 except Exception as e:
404 self.poutput('Error request img dnld {}. Error:{}'.format(device_id, e))
405 return
406 kw['crc'] = long(opts.crc)
407 kw['image_version'] = opts.version
408 response = None
409 try:
410 request = voltha_pb2.ImageDownload(**kw)
411 stub = self.get_stub()
412 response = stub.DownloadImage(request)
413 except Exception as e:
414 self.poutput('Error download image {}. Error:{}'.format(kw['id'], e))
415 return
416 name = enum2name(common_pb2.OperationResp,
417 'OperationReturnCode', response.code)
418 self.poutput('response: {}'.format(name))
419 self.poutput('{}'.format(response))
420
421 @options([
422 make_option('-n', '--name', action='store', dest='name',
423 help="Image name"),
424 ])
425 def do_img_dnld_status(self, line, opts):
426 """
427 Get a image download status
428 """
429 device = self.get_device(depth=-1)
430 self.poutput('device_id {}'.format(device.id))
431 self.poutput('name {}'.format(opts.name))
432 try:
433 device_id = device.id
434 if device_id and opts.name:
435 kw = dict(id=device_id)
436 kw['name'] = opts.name
437 else:
438 self.poutput('Device ID, Image Name are needed')
439 raise Exception('Device ID, Image Name are needed')
440 except Exception as e:
441 self.poutput('Error get img dnld status {}. Error:{}'.format(device_id, e))
442 return
443 status = None
444 try:
445 img_dnld = voltha_pb2.ImageDownload(**kw)
446 stub = self.get_stub()
447 status = stub.GetImageDownloadStatus(img_dnld)
448 except Exception as e:
449 self.poutput('Error get img dnld status {}. Error:{}'.format(device_id, e))
450 return
451 fields_to_omit = {
452 'crc',
453 'local_dir',
454 }
455 try:
456 print_pb_as_table('ImageDownload Status:', status, fields_to_omit, self.poutput)
457 except Exception, e:
458 self.poutput('Error {}. Error:{}'.format(device_id, e))
459
460 def do_img_dnld_list(self, line):
461 """
462 List all image download records for a given device
463 """
464 device = self.get_device(depth=-1)
465 device_id = device.id
466 self.poutput('Get all img dnld records {}'.format(device_id))
467 try:
468 stub = self.get_stub()
469 img_dnlds = stub.ListImageDownloads(voltha_pb2.ID(id=device_id))
470 except Exception, e:
471 self.poutput('Error list img dnlds {}. Error:{}'.format(device_id, e))
472 return
473 fields_to_omit = {
474 'crc',
475 'local_dir',
476 }
477 try:
478 print_pb_list_as_table('ImageDownloads:', img_dnlds.items, fields_to_omit, self.poutput)
479 except Exception, e:
480 self.poutput('Error {}. Error:{}'.format(device_id, e))
481
482
483 @options([
484 make_option('-n', '--name', action='store', dest='name',
485 help="Image name"),
486 ])
487 def do_img_dnld_cancel(self, line, opts):
488 """
489 Cancel a requested image download
490 """
491 device = self.get_device(depth=-1)
492 self.poutput('device_id {}'.format(device.id))
493 self.poutput('name {}'.format(opts.name))
494 device_id = device.id
495 try:
496 if device_id and opts.name:
497 kw = dict(id=device_id)
498 kw['name'] = opts.name
499 else:
500 self.poutput('Device ID, Image Name are needed')
501 raise Exception('Device ID, Image Name are needed')
502 except Exception as e:
503 self.poutput('Error cancel sw dnld {}. Error:{}'.format(device_id, e))
504 return
505 response = None
506 try:
507 img_dnld = voltha_pb2.ImageDownload(**kw)
508 stub = self.get_stub()
509 img_dnld = stub.GetImageDownload(img_dnld)
510 response = stub.CancelImageDownload(img_dnld)
511 except Exception as e:
512 self.poutput('Error cancel sw dnld {}. Error:{}'.format(device_id, e))
513 return
514 name = enum2name(common_pb2.OperationResp,
515 'OperationReturnCode', response.code)
516 self.poutput('response: {}'.format(name))
517 self.poutput('{}'.format(response))
518
Scott Bakerd3190952018-09-04 15:47:28 -0700519 def help_simulate_alarm(self):
520 self.poutput(
521'''
522simulate_alarm <alarm_name> [-b <bit rate>] [-c] [-d <drift>] [-e <eqd>]
523 [-i <interface id>] [-o <onu device id>] [-p <port type name>]
524
525<name> is the name of the alarm to raise. Other rguments are alarm specific
526and only have meaning in the context of a particular alarm. Below is a list
527of the alarms that may be raised:
528
529simulate_alarm los -i <interface_id> -p <port_type_name>
530simulate_alarm dying_gasp -i <interface_id> -o <onu_device_id>
531simulate_alarm onu_los -i <interface_id> -o <onu_device_id>
532simulate_alarm onu_lopc_miss -i <interface_id> -o <onu_device_id>
533simulate_alarm onu_lopc_mic -i <interface_id> -o <onu_device_id>
534simulate_alarm onu_lob -i <interface_id> -o <onu_device_id>
535simulate_alarm onu_signal_degrade -i <interface_id> -o <onu_device_id>
536 -b <bit_rate>
537simulate_alarm onu_drift_of_window -i <interface_id>
538 -o <onu_device_id> -d <drift> -e <eqd>
539simulate_alarm onu_signal_fail -i <interface_id> -o <onu_device_id>
540 -b <bit_rate>
541simulate_alarm onu_activation -i <interface_id> -o <onu_device_id>
542simulate_alarm onu_startup -i <interface_id> -o <onu_device_id>
543simulate_alarm onu_discovery -i <interface_id> -s <onu_serial_number>
544
545If the -c option is specified then the alarm will be cleared. By default,
546it will be raised. Note that only some alarms can be cleared.
547'''
548 )
549
550 @options([
551 make_option('-c', '--clear', action='store_true', default=False,
552 help="Clear alarm instead of raising"),
553 make_option('-b', '--inverse_bit_error_rate', action='store', dest='inverse_bit_error_rate',
554 help="Inverse bit error rate", default=0, type="int"),
555 make_option('-d', '--drift', action='store', dest='drift',
556 help="Drift", default=0, type="int"),
557 make_option('-e', '--new_eqd', action='store', dest='new_eqd',
558 help="New EQD", default=0, type="int"),
559 make_option('-i', '--intf_id', action='store', dest='intf_id',
560 help="Interface ID", default=""),
561 make_option('-o', '--onu_device_id', action='store', dest='onu_device_id',
562 help="ONU device ID", default=""),
563 make_option('-p', '--port_type_name', action='store', dest='port_type_name',
564 help="Port type name", default=""),
565 make_option('-s', '--onu_serial_number', action='store', dest='onu_serial_number',
566 help="ONU Serial Number", default=""),
567 ])
568 def do_simulate_alarm(self, line, opts):
569 indicator = line
570 device = self.get_device(depth=-1)
571 device_id = device.id
572
573 alarm_args = {"los": ["intf_id", "port_type_name"],
574 "dying_gasp": ["intf_id", "onu_device_id"],
575 "onu_los": ["intf_id", "onu_device_id"],
576 "onu_lopc_miss": ["intf_id", "onu_device_id"],
577 "onu_lopc_mic": ["intf_id", "onu_device_id"],
578 "onu_lob": ["intf_id", "onu_device_id"],
579 "onu_signal_degrade": ["intf_id", "onu_device_id", "inverse_bit_error_rate"],
580 "onu_drift_of_window": ["intf_id", "onu_device_id", "drift", "new_eqd"],
581 "onu_signal_fail": ["intf_id", "onu_device_id", "inverse_bit_error_rate"],
582 "onu_activation": ["intf_id", "onu_device_id"],
583 "onu_startup": ["intf_id", "onu_device_id"],
584 "onu_discovery": ["intf_id", "onu_serial_number"]
585 }
586 try:
587 if indicator not in alarm_args:
588 self.poutput("Unknown alarm indicator %s. Valid choices are %s." % (indicator,
589 ", ".join(alarm_args.keys())))
590 raise Exception("Unknown alarm indicator %s" % indicator)
591
592 for arg_name in alarm_args[indicator]:
593 if not getattr(opts, arg_name):
594 self.poutput("Option %s is required for alarm %s. See help." % (arg_name, indicator))
595 raise Exception("Option %s is required for alarm %s" % (arg_name, indicator))
596
597 # TODO: check for required arguments
598 kw = dict(id=device_id)
599
600 kw["indicator"] = indicator
601 kw["intf_id"] = opts.intf_id
602 kw["onu_device_id"] = opts.onu_device_id
603 kw["port_type_name"] = opts.port_type_name
604 kw["inverse_bit_error_rate"] = opts.inverse_bit_error_rate
605 kw["drift"] = opts.drift
606 kw["new_eqd"] = opts.new_eqd
607 kw["onu_serial_number"] = opts.onu_serial_number
608
609 if opts.clear:
610 kw["operation"] = voltha_pb2.SimulateAlarmRequest.CLEAR
611 else:
612 kw["operation"] = voltha_pb2.SimulateAlarmRequest.RAISE
613 except Exception as e:
614 self.poutput('Error simulate alarm {}. Error:{}'.format(device_id, e))
615 return
616 response = None
617 try:
618 simulate_alarm = voltha_pb2.SimulateAlarmRequest(**kw)
619 stub = self.get_stub()
620 response = stub.SimulateAlarm(simulate_alarm)
621 except Exception as e:
622 self.poutput('Error simulate alarm {}. Error:{}'.format(kw['id'], e))
623 return
624 name = enum2name(common_pb2.OperationResp,
625 'OperationReturnCode', response.code)
626 self.poutput('response: {}'.format(name))
627 self.poutput('{}'.format(response))
628
Lydia Fang01f2e852017-06-28 17:24:58 -0700629 @options([
630 make_option('-n', '--name', action='store', dest='name',
631 help="Image name"),
632 make_option('-s', '--save', action='store', dest='save_config',
633 help="Save Config", default="True"),
634 make_option('-d', '--dir', action='store', dest='local_dir',
635 help="Image on device location"),
636 ])
637 def do_img_activate(self, line, opts):
638 """
639 Activate an image update on device
640 """
641 device = self.get_device(depth=-1)
642 device_id = device.id
643 try:
644 if device_id and opts.name and opts.local_dir:
645 kw = dict(id=device_id)
646 kw['name'] = opts.name
647 kw['local_dir'] = opts.local_dir
648 else:
649 self.poutput('Device ID, Image Name, and Location are needed')
650 raise Exception('Device ID, Image Name, and Location are needed')
651 except Exception as e:
652 self.poutput('Error activate image {}. Error:{}'.format(device_id, e))
653 return
654 kw['save_config'] = json.loads(opts.save_config.lower())
655 self.poutput('activate image update {} {} {} {}'.format( \
656 kw['id'], kw['name'],
657 kw['local_dir'], kw['save_config']))
658 response = None
659 try:
660 img_dnld = voltha_pb2.ImageDownload(**kw)
661 stub = self.get_stub()
662 img_dnld = stub.GetImageDownload(img_dnld)
663 response = stub.ActivateImageUpdate(img_dnld)
664 except Exception as e:
665 self.poutput('Error activate image {}. Error:{}'.format(kw['id'], e))
666 return
667 name = enum2name(common_pb2.OperationResp,
668 'OperationReturnCode', response.code)
669 self.poutput('response: {}'.format(name))
670 self.poutput('{}'.format(response))
671
672 @options([
673 make_option('-n', '--name', action='store', dest='name',
674 help="Image name"),
675 make_option('-s', '--save', action='store', dest='save_config',
676 help="Save Config", default="True"),
677 make_option('-d', '--dir', action='store', dest='local_dir',
678 help="Image on device location"),
679 ])
680 def do_img_revert(self, line, opts):
681 """
682 Revert an image update on device
683 """
684 device = self.get_device(depth=-1)
685 device_id = device.id
686 try:
687 if device_id and opts.name and opts.local_dir:
688 kw = dict(id=device_id)
689 kw['name'] = opts.name
690 kw['local_dir'] = opts.local_dir
691 else:
692 self.poutput('Device ID, Image Name, and Location are needed')
693 raise Exception('Device ID, Image Name, and Location are needed')
694 except Exception as e:
695 self.poutput('Error revert image {}. Error:{}'.format(device_id, e))
696 return
697 kw['save_config'] = json.loads(opts.save_config.lower())
698 self.poutput('revert image update {} {} {} {}'.format( \
699 kw['id'], kw['name'],
700 kw['local_dir'], kw['save_config']))
701 response = None
702 try:
703 img_dnld = voltha_pb2.ImageDownload(**kw)
704 stub = self.get_stub()
705 img_dnld = stub.GetImageDownload(img_dnld)
706 response = stub.RevertImageUpdate(img_dnld)
707 except Exception as e:
708 self.poutput('Error revert image {}. Error:{}'.format(kw['id'], e))
709 return
710 name = enum2name(common_pb2.OperationResp,
711 'OperationReturnCode', response.code)
712 self.poutput('response: {}'.format(name))
713 self.poutput('{}'.format(response))