Skip to content

Commit

Permalink
[fast-reboot-filter-routes.py] Remove click and improve error reporti…
Browse files Browse the repository at this point in the history
…ng (#3030)

* [fast-reboot-filter-routes.py] Remove click and improve error reporting

1. Removed click usage from a script since there is no active click
context therefore we saw these error messages:

```
ERR fast-reboot-filter-routes: Got an exception There is no active click context.: Traceback: Traceback (most recent call last):#12  File "/usr/local/bin/fast-reboot-filter-routes.py", line 18, in get_connected_routes#012    output, ret = clicommon.run_command(cmd, return_cmd=True)#12  File "/usr/local/lib/python3.9/dist-packages/utilities_common/cli.py", line 545, in run_command#012    proc = subprocess.Popen(command, shell=shell, text=True, stdout=subprocess.PIPE)#12  File "/usr/lib/python3.9/subprocess.py", line 951, in __init__#012    self._execute_child(args, executable, preexec_fn, close_fds,#12  File "/usr/lib/python3.9/subprocess.py", line 1823, in _execute_child#012    raise child_exception_type(errno_num, err_msg, err_filename)#012FileNotFoundError: [Errno 2] No such file or directory: 'sudo vtysh -c "show ip route connected json"'#12#012During handling of the above exception, another exception occurred:#12#012Traceback (most recent call last):#12  File "/usr/local/lib/python3.9/dist-packages/click/globals.py", line 23, in get_current_context#012    return getattr(_local, 'stack')[-1]#012AttributeError: '_thread._local' object has no attribute 'stack'#12#012During handling of the above exception, another exception occurred:#12#012Traceback (most recent call last):#12  File "/usr/local/bin/fast-reboot-filter-routes.py", line 79, in <module>#12    res = main()#12  File "/usr/local/bin/fast-reboot-filter-routes.py", line 70, in main#012    connected_routes = get_connected_routes()#12  File "/usr/local/bin/fast-reboot-filter-routes.py", line 27, in get_connected_routes#012    ctx = click.get_current_context()#12  File "/usr/local/lib/python3.9/dist-packages/click/globals.py", line 26, in get_current_context#012    raise RuntimeError('There is no active click context.')#012RuntimeError: There is no active click context.
```

2. Improved error reporting so that when an error occurs when we run a
command it will report it via terminal and syslog:

stdout:
```
Failed to execute sudo vtysh -c show ip route connected jsson: % Unknown command: show ip route connected jsson
```

syslog:
```
Oct 17 11:53:10.620788 arc-switch1025 ERR fast-reboot-filter-routes: Got an exception: Failed to execute sudo vtysh -c show ip route connected jsson: % Unknown command: show ip route connected jsson: Traceback: Traceback (most recent call last):#12  File "/home/admin/fast-reboot-filter-routes.py", line 73, in <module>#12    res = main()#12  File "/home/admin/fast-reboot-filter-routes.py", line 64, in main#012    connected_routes = get_connected_routes()#12  File "/home/admin/fast-reboot-filter-routes.py", line 18, in get_connected_routes#012    raise Exception("Failed to execute {}: {}".format(" ".join(cmd), output.rstrip('\n')))#012Exception: Failed to execute sudo vtysh -c show ip route connected jsson: % Unknown command: show ip route connected jsson
```

Signed-off-by: Stepan Blyschak <stepanb@nvidia.com>

* add a test for command failure

Signed-off-by: Stepan Blyschak <stepanb@nvidia.com>

* Increase coverage

Signed-off-by: Stepan Blyschak <stepanb@nvidia.com>

---------

Signed-off-by: Stepan Blyschak <stepanb@nvidia.com>
  • Loading branch information
stepanblyschak authored and StormLiangMS committed Nov 19, 2023
1 parent 7d793ea commit e434069
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
23 changes: 9 additions & 14 deletions scripts/fast-reboot-filter-routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,21 @@
import utilities_common.cli as clicommon
import syslog
import traceback
import click
from swsscommon.swsscommon import ConfigDBConnector

ROUTE_IDX = 1

def get_connected_routes():
cmd = ['sudo', 'vtysh', '-c', "show ip route connected json"]
connected_routes = []
try:
output, ret = clicommon.run_command(cmd, return_cmd=True)
if ret != 0:
click.echo(output.rstrip('\n'))
sys.exit(ret)
if output is not None:
route_info = json.loads(output)
for route in route_info.keys():
connected_routes.append(route)
except Exception:
ctx = click.get_current_context()
ctx.fail("Unable to get connected routes from bgp")

output, ret = clicommon.run_command(cmd, return_cmd=True)
if ret != 0:
raise Exception("Failed to execute {}: {}".format(" ".join(cmd), output.rstrip('\n')))
if output is not None:
route_info = json.loads(output)
for route in route_info.keys():
connected_routes.append(route)

return connected_routes

def get_route(db, route):
Expand Down Expand Up @@ -81,6 +75,7 @@ def main():
syslog.syslog(syslog.LOG_NOTICE, "SIGINT received. Quitting")
res = 1
except Exception as e:
print(e)
syslog.syslog(syslog.LOG_ERR, "Got an exception %s: Traceback: %s" % (str(e), traceback.format_exc()))
res = 2
finally:
Expand Down
11 changes: 9 additions & 2 deletions tests/fast_reboot_filter_routes_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ def setup(self):

@patch('utilities_common.cli.run_command')
def test_get_connected_routes(self, mock_run_command):
mock_run_command.return_value = (None, 0)
mock_run_command.return_value = ('{"1.1.0.0/16": {}}', 0)
output = fast_reboot_filter_routes.get_connected_routes()
mock_run_command.assert_called_with(['sudo', 'vtysh', '-c', "show ip route connected json"], return_cmd=True)
assert output == []
assert output == ['1.1.0.0/16']

@patch('utilities_common.cli.run_command')
def test_get_connected_routes_command_failed(self, mock_run_command):
mock_run_command.return_value = ('{"1.1.0.0/16": {}}', 1)
with pytest.raises(Exception):
fast_reboot_filter_routes.get_connected_routes()
mock_run_command.assert_called_with(['sudo', 'vtysh', '-c', "show ip route connected json"], return_cmd=True)

def teardown(self):
print("TEAR DOWN")

0 comments on commit e434069

Please sign in to comment.