Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[show] Add bgpraw to show run all #2537

Merged
merged 9 commits into from
Jan 14, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions show/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ def run_command(command, display_cmd=False, return_cmd=False):
if rc != 0:
sys.exit(rc)

def get_cmd_output(cmd):
proc = subprocess.Popen(cmd, text=True, stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
click.echo("Command failed '{}': {}".format(cmd, stderr))
raise click.Abort()
return stdout

# Lazy global class instance for SONiC interface name to alias conversion
iface_alias_converter = lazy_object_proxy.Proxy(lambda: clicommon.InterfaceAliasConverter())

Expand Down Expand Up @@ -1383,8 +1391,20 @@ def runningconfiguration():
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def all(verbose):
"""Show full running configuration"""
cmd = "sonic-cfggen -d --print-data"
run_command(cmd, display_cmd=verbose)
cmd = ['sonic-cfggen', '-d', '--print-data']
stdout = get_cmd_output(cmd)
wen587 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

@qiluo-msft qiluo-msft Jan 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stdout

suggest function return (stdout, rc). After calling this function, check rc first. #Closed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@qiluo-msft If we follow the original behavior, we don't need to check the rc. As it will be empty string by default if rc is non-zero.

def run_command(command, display_cmd=False, return_cmd=False):
    if display_cmd:
        click.echo(click.style("Command: ", fg='cyan') + click.style(command, fg='green'))

    # No conversion needed for intfutil commands as it already displays
    # both SONiC interface name and alias name for all interfaces.
    if clicommon.get_interface_naming_mode() == "alias" and not command.startswith("intfutil"):
        clicommon.run_command_in_alias_mode(command)
        raise sys.exit(0)

    proc = subprocess.Popen(command, shell=True, text=True, stdout=subprocess.PIPE)

    while True:
        if return_cmd:
            output = proc.communicate()[0]                   <===============
            return output


try:
output = json.loads(stdout)
except Exception as e:
wen587 marked this conversation as resolved.
Show resolved Hide resolved
click.echo("Failed to load output '{}':{}".format(cmd, e))
raise click.Abort()

if 'bgpraw' in output or not multi_asic.is_multi_asic():
bgpraw_cmd = [constants.RVTYSH_COMMAND, '-c', 'show running-config']
bgpraw = get_cmd_output(bgpraw_cmd)
Copy link
Contributor

@qiluo-msft qiluo-msft Jan 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bgpraw

return (stdout, rc). After calling this function, check rc first. If rc non zero, output['bgpraw'] should be empty string. #Closed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above, it will be empty string by default if rc is non-zero.

output['bgpraw'] = bgpraw
wen587 marked this conversation as resolved.
Show resolved Hide resolved
click.echo(json.dumps(output, indent=4))
wen587 marked this conversation as resolved.
Show resolved Hide resolved


# 'acl' subcommand ("show runningconfiguration acl")
Expand Down
66 changes: 66 additions & 0 deletions tests/show_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import os
import sys
import show.main as show
from click.testing import CliRunner
from unittest import mock
from unittest.mock import call, MagicMock

test_path = os.path.dirname(os.path.abspath(__file__))
modules_path = os.path.dirname(test_path)
sys.path.insert(0, test_path)
sys.path.insert(0, modules_path)

class TestCommonFunc(object):
@classmethod
def setup_class(cls):
print("SETUP")
os.environ["UTILITIES_UNIT_TESTING"] = "1"

def test_get_cmd_output(self):
with mock.patch('show.main.subprocess.Popen',
mock.MagicMock()) as mock_popen:
mock_proc = MagicMock()
mock_proc.communicate = MagicMock(return_value=(None, None))
mock_proc.returncode = 1
mock_popen.return_value = mock_proc
result = CliRunner().invoke(show.cli.commands['runningconfiguration'].commands['all'], [])
assert result.exit_code != 0
assert "Aborted" in result.output

@classmethod
def teardown_class(cls):
print("TEARDOWN")
os.environ["PATH"] = os.pathsep.join(os.environ["PATH"].split(os.pathsep)[:-1])
os.environ["UTILITIES_UNIT_TESTING"] = "0"


class TestShowRunAllCommands(object):
@classmethod
def setup_class(cls):
print("SETUP")
os.environ["UTILITIES_UNIT_TESTING"] = "1"

def test_show_runningconfiguration_all_json_loads_failure(self):
def get_cmd_output_side_effect(*args, **kwargs):
return ""
with mock.patch('show.main.get_cmd_output',
mock.MagicMock(side_effect=get_cmd_output_side_effect)) as mock_get_cmd_output:
result = CliRunner().invoke(show.cli.commands['runningconfiguration'].commands['all'], [])
assert result.exit_code != 0

def test_show_runningconfiguration_all(self):
def get_cmd_output_side_effect(*args, **kwargs):
return "{}"
with mock.patch('show.main.get_cmd_output',
mock.MagicMock(side_effect=get_cmd_output_side_effect)) as mock_get_cmd_output:
result = CliRunner().invoke(show.cli.commands['runningconfiguration'].commands['all'], [])
assert mock_get_cmd_output.call_count == 2
assert mock_get_cmd_output.call_args_list == [
call(['sonic-cfggen', '-d', '--print-data']),
call(['rvtysh', '-c', 'show running-config'])]

@classmethod
def teardown_class(cls):
print("TEARDOWN")
os.environ["PATH"] = os.pathsep.join(os.environ["PATH"].split(os.pathsep)[:-1])
os.environ["UTILITIES_UNIT_TESTING"] = "0"