Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
60 changes: 40 additions & 20 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,50 +16,70 @@

import importlib
import sys
import types

from absl import app
from absl import flags

import tcli.tcli_lib as tcli


flags.DEFINE_string(
'cmds', None, """
'cmds',
None,
"""
Commands (newline separated) to send to devices in the target list.
'Prompting' commands, commands that request further input from the
user before completing are discouraged and will fail.
Examples to avoid: telnet, ping, reload.
Shortname: 'C'.""", short_name='C')
Shortname: 'C'.""",
short_name='C',
)
flags.DEFINE_boolean(
'interactive', False, """
'interactive',
False,
"""
TCLI runs in interactive mode. This is the default if no cmds are supplied.'
Shortname: 'I'.""", short_name='I')
# Defaults to inventory_csv.py which contains canned data for testing.
flags.DEFINE_string('accessor_file', 'accessor_canned',
'Name of the module that implements SendRequests.')
# Defaults to inventory_csv.py which contains canned data for testing.
flags.DEFINE_string('inventory_file', 'inventory_csv',
'Name of the module that implements the Inventory class.')
Shortname: 'I'.""",
short_name='I',
)
flags.DEFINE_string(
'accessor_file',
'accessor_canned',
'Name of the module that implements SendRequests.',
)
flags.DEFINE_string(
'inventory_file',
'inventory_csv',
'Name of the module that implements the Inventory class.',
)
FLAGS = flags.FLAGS


def main(_):
def _ParseFlags(argv: list[str]) -> list[str]:
"""Pre-loads accessor and inventory modules before parsing all CLI flags."""
FLAGS(argv, known_only=True)
# Replace the generic Accessor function with the site specific one.
tcli.accessor = importlib.import_module(f'tcli.{FLAGS.accessor_file}')
# Replace the generic Inventory class with the site specific one.
tcli.inventory = importlib.import_module(f'tcli.{FLAGS.inventory_file}')
return app.parse_flags_with_usage(argv)


def main(_):
try:
# If no commands supplied via flags then assume interactive mode.
interactive = FLAGS.interactive or not FLAGS.cmds
interactive = FLAGS.interactive or not FLAGS.cmds
tcli_singleton = tcli.TCLI(interactive, FLAGS.cmds)
except (EOFError, tcli.TcliCmdError,
tcli.inventory.AuthError, tcli.inventory.InventoryError,
ValueError) as error_message:
except (
EOFError,
tcli.TcliCmdError,
tcli.inventory.AuthError,
tcli.inventory.InventoryError,
ValueError,
) as error_message:
print('%s' % error_message, file=sys.stderr)
sys.exit(1)

if not tcli_singleton.interactive:
del tcli_singleton
sys.exit(0)

# Interactive prompt, setup Tab completion
Expand All @@ -75,9 +95,9 @@ def main(_):
except KeyboardInterrupt:
continue
except EOFError:
del tcli_singleton
sys.exit(0)


if __name__ == '__main__':
app.run(main)
app.run(main, flags_parser=_ParseFlags)

18 changes: 12 additions & 6 deletions tcli/accessor_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,21 @@
# permissions and limitations under the License.

"""Sends commands to devices via callbacks."""
import typing

from collections.abc import Callable

# pylint: disable=g-importing-member
from tcli.inventory_base import CmdRequest
from tcli.inventory_base import Response

DEADLINE = None


# pylint: disable=unused-argument
def SendRequests(
requests_callbacks: list[tuple[CmdRequest, typing.Callable]],
deadline: float | None=DEADLINE) -> None:
requests_callbacks: list[tuple[CmdRequest, Callable[[Response], None]]],
deadline: float | None = DEADLINE,
) -> None:
"""Submits command requests to device manager.

Submit the command requests to the device manager for resolution.
Expand All @@ -34,10 +39,11 @@ def SendRequests(
is to be executed by the device manager.

Args:
requests_callbacks: List of tuples.
Each tuple pairs a request object with a callback function.
requests_callbacks: List of tuples. Each tuple pairs a request object with a
callback function.
deadline: An optional int, the deadline to set when sending the request.

Returns:
None
"""
raise NotImplementedError
raise NotImplementedError
53 changes: 37 additions & 16 deletions tcli/accessor_canned.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,26 @@
"""Sends commands to devices via callbacks."""

import asyncio
from collections.abc import Callable
import os
import typing

from tcli import accessor_base as accessor
from tcli import inventory_base as inventory

DEADLINE = accessor.DEADLINE
## CHANGEME
## Where we store the canned responses.
DEFAULT_RESPONSE_DIRECTORY = os.path.join(
os.path.dirname(__file__), 'testdata', 'device_output')
DEFAULT_RESPONSE_DIRECTORY = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'testdata', 'device_output')
)


def SendRequests(
requests_callbacks:list[tuple[accessor.CmdRequest, typing.Callable]],
deadline: float | None=DEADLINE) -> None:
requests_callbacks: list[
tuple[accessor.CmdRequest, Callable[[inventory.Response], None]]
],
deadline: float | None = DEADLINE,
) -> None:
"""Submits command requests to device manager.

Submit the command requests to the device manager for resolution.
Expand All @@ -41,28 +45,45 @@ def SendRequests(
is to be executed by the device manager.

Args:
requests_callbacks: List of tuples.
Each tuple pairs a request object with a callback function.
requests_callbacks: List of tuples. Each tuple pairs a request object with a
callback function.
deadline: An optional int, the deadline to set when sending the request.

Returns:
None
"""

for (request, callback) in requests_callbacks:
del deadline
for request, callback in requests_callbacks:
asyncio.run(_ReadCannedResult(request, callback))


async def _ReadCannedResult(
request: inventory.CmdRequest, callback: typing.Callable) -> None:
request: inventory.CmdRequest,
callback: Callable[[inventory.Response], None],
) -> None:
"""Reads canned result from local file."""

data, error = '', ''
file_name = request.target + '_' + request.command.replace(' ', '_')
file_path = os.path.join(DEFAULT_RESPONSE_DIRECTORY, file_name)
file_path = os.path.abspath(
os.path.join(DEFAULT_RESPONSE_DIRECTORY, file_name)
)
try:
with open(file_path) as fp:
if not file_path.startswith(DEFAULT_RESPONSE_DIRECTORY + os.sep):
raise OSError('Invalid file path outside response directory.')
with open(file_path, encoding='utf-8') as fp:
data = fp.read()
except IOError:
error = ('Failure to retrieve response from device "%s",'
' for command "%s".' % (request.target, request.command))
callback(inventory.Response(uid=request.uid, device_name=request.target,
command=request.command, data=data, error=error))
error = (
'Failure to retrieve response from device "%s", for command "%s".'
% (request.target, request.command)
)
callback(
inventory.Response(
uid=request.uid,
device_name=request.target,
command=request.command,
data=data,
error=error,
)
)
72 changes: 50 additions & 22 deletions tcli/accessor_canned_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,61 +12,89 @@
# implied. See the License for the specific language governing
# permissions and limitations under the License.

"""Tests for tcli.accessor_files."""
"""Unit tests for the canned file accessor module."""

import os
import unittest

from unittest import mock

from tcli import accessor_canned as accessor
from tcli import inventory_base as inventory


class UnitTestCannedFileAccessor(unittest.TestCase):
"""Test the CSV inventory class."""

def testSendRequests(self):
"""Tests command requests are pulled from file."""
class requestObject(inventory.CmdRequest):

class RequestObject(inventory.CmdRequest):
uid = 0

def __init__(self, target, command):
self.target = target
self.command = command
self.uid += requestObject.uid
self.uid += RequestObject.uid

# Invalid target or command results in error.
target = 'bogus'
command = 'show version'
request = requestObject(target, command)
request = RequestObject(target, command)
callback = mock.MagicMock()

accessor.SendRequests([(request, callback),])
accessor.SendRequests([
(request, callback),
])
callback.assert_called_with(
inventory.Response(
uid=0, device_name=target, command=command, data='',
error='Failure to retrieve response from device '
+ f'"{target}", for command "{command}".'
)
inventory.Response(
uid=0,
device_name=target,
command=command,
data='',
error='Failure to retrieve response from device '
+ f'"{target}", for command "{command}".',
)
)

# Result is pulled from file for valid device and command.
target = 'device_a'
request = requestObject(target, command)
file_result = os.path.join(accessor.DEFAULT_RESPONSE_DIRECTORY,
f'{target}_{command}'.replace(' ', '_'))
request = RequestObject(target, command)
file_result = os.path.join(
accessor.DEFAULT_RESPONSE_DIRECTORY,
f'{target}_{command}'.replace(' ', '_'),
)
with open(file_result) as fp:
data = fp.read()
callback = mock.MagicMock()

accessor.SendRequests([(request, callback),])
accessor.SendRequests([
(request, callback),
])
callback.assert_called_with(
inventory.Response(
uid=0, device_name=target, command=command,
data=data,
error=''
)
inventory.Response(
uid=0, device_name=target, command=command, data=data, error=''
)
)

# Path traversal attempts are rejected.
traversal_target = '../../etc'
traversal_command = 'passwd'
traversal_request = RequestObject(traversal_target, traversal_command)
callback = mock.MagicMock()
accessor.SendRequests([(traversal_request, callback)])
callback.assert_called_with(
inventory.Response(
uid=0,
device_name=traversal_target,
command=traversal_command,
data='',
error=(
'Failure to retrieve response from device '
f'"{traversal_target}", for command "{traversal_command}".'
),
)
)


if __name__ == '__main__':
unittest.main()
unittest.main()
Loading
Loading