Change in osmo-gsm-tester[master]: add osmo_vty.py

This is merely a historical archive of years 2008-2021, before the migration to mailman3.

A maintained and still updated list archive can be found at https://lists.osmocom.org/hyperkitty/list/gerrit-log@lists.osmocom.org/.

neels gerrit-no-reply at lists.osmocom.org
Thu Dec 3 23:56:18 UTC 2020


neels has uploaded this change for review. ( https://gerrit.osmocom.org/c/osmo-gsm-tester/+/21504 )


Change subject: add osmo_vty.py
......................................................................

add osmo_vty.py

To trigger manual handovers, I need a VTY interface. The non-trivial
parts of this are copied from osmo-python-tests osmo_interact_vty.py.

Will be used in the upcoming handover_2G test suite in
I0b2671304165a1aaae2b386af46fbd8b098e3bd8.

Change-Id: I7c17b143b7c690b8c4105ee7c6272670046fa91d
---
A src/osmo_gsm_tester/obj/osmo_vty.py
1 file changed, 181 insertions(+), 0 deletions(-)



  git pull ssh://gerrit.osmocom.org:29418/osmo-gsm-tester refs/changes/04/21504/1

diff --git a/src/osmo_gsm_tester/obj/osmo_vty.py b/src/osmo_gsm_tester/obj/osmo_vty.py
new file mode 100644
index 0000000..88deb61
--- /dev/null
+++ b/src/osmo_gsm_tester/obj/osmo_vty.py
@@ -0,0 +1,181 @@
+# osmo_gsm_tester: VTY connection
+#
+# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
+#
+# Author: Neels Hofmeyr <neels at hofmeyr.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import socket
+import struct
+import re
+import time
+
+from ..core import log
+
+class VtyInterfaceExn(Exception):
+    pass
+
+class OsmoVty(log.Origin):
+
+    def __init__(self, host, port, prompt=None):
+        super().__init__(log.C_BUS, 'Vty', host=host, port=port)
+        self.host = host
+        self.port = port
+        self.sck = None
+        self.prompt = prompt
+        self.re_prompt = None
+        self.this_node = None
+        self.this_prompt_char = None
+        self.last_node = None
+        self.last_prompt_char = None
+
+    def connect(self):
+        attempts = 10;
+        while True:
+            try:
+                self.dbg('Connecting')
+                self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+                self.sck.connect((self.host, self.port))
+            except ConnectionRefusedError:
+                attempts -= 1
+                if attempts < 1:
+                    raise
+                self.dbg('Connection Refused, trying again (attempts left: %d)' % attempts)
+                time.sleep(3)
+                continue
+            break
+
+        self.sck.setblocking(1)
+
+        # read first prompt
+        # (copied from https://git.osmocom.org/python/osmo-python-tests/tree/osmopy/osmo_interact/vty.py)
+        self.this_node = None
+        self.this_prompt_char = '>' # slight cheat for initial prompt char
+        self.last_node = None
+        self.last_prompt_char = None
+
+        data = self.sck.recv(4096)
+        if not self.prompt:
+            b = data
+            b = b[b.rfind(b'\n') + 1:]
+            while b and (b[0] < ord('A') or b[0] > ord('z')):
+                b = b[1:]
+            prompt_str = b.decode('utf-8')
+            if '>' in prompt_str:
+                self.prompt = prompt_str[:prompt_str.find('>')]
+            self.dbg(prompt=self.prompt)
+        if not self.prompt:
+            raise VtyInterfaceExn('Could not find application name; needed to decode prompts.'
+                    ' Initial data was: %r' % data)
+        self.re_prompt = re.compile('^%s(?:\(([\w-]*)\))?([#>]) (.*)$' % self.prompt)
+
+    def disconnect(self):
+        self.dbg('Disconnecting')
+        if self.sck is not None:
+            self.sck.close()
+
+    def _command(self, command_str, timeout=10, strict=True):
+        # (copied from https://git.osmocom.org/python/osmo-python-tests/tree/osmopy/osmo_interact/vty.py)
+        self.dbg('Sending', command_str=command_str)
+        self.sck.send(command_str.encode())
+
+        waited_since = time.time()
+        received_lines = []
+        last_line = ''
+
+        while True:
+            new_data = self.sck.recv(4096).decode('utf-8')
+
+            last_line = "%s%s" % (last_line, new_data)
+
+            if last_line:
+                # Separate the received response into lines.
+                # But note: the VTY logging currently separates with '\n\r', not '\r\n',
+                # see _vty_output() in libosmocore logging_vty.c.
+                # So we need to jump through hoops to not separate 'abc\n\rdef' as
+                # [ 'abc', '', 'def' ]; but also not to convert '\r\n\r\n' to '\r\n\n' ('\r{\r\n}\n')
+                # Simplest is to just drop all the '\r' and only care about the '\n'.
+                last_line = last_line.replace('\r', '')
+                lines = last_line.splitlines()
+                if last_line.endswith('\n'):
+                    received_lines.extend(lines)
+                    last_line = ""
+                else:
+                    # if pkt buffer ends in the middle of a line, we need to keep
+                    # last non-finished line:
+                    received_lines.extend(lines[:-1])
+                    last_line = lines[-1]
+
+            match = self.re_prompt.match(last_line)
+            if not match:
+                if time.time() - waited_since > timeout:
+                    raise IOError("Failed to read data (did the app crash?)")
+                time.sleep(.1)
+                continue
+
+            self.last_node = self.this_node
+            self.last_prompt_char = self.this_prompt_char
+            self.this_node = match.group(1) or None
+            self.this_prompt_char = match.group(2)
+            break
+
+        # expecting to have received the command we sent as echo, remove it
+        clean_command_str = command_str.strip()
+        if clean_command_str.endswith('?'):
+            clean_command_str = clean_command_str[:-1]
+        if received_lines and received_lines[0] == clean_command_str:
+            received_lines = received_lines[1:]
+        if len(received_lines) > 1:
+            self.dbg('Received\n|', '\n| '.join(received_lines), '\n')
+        elif len(received_lines) == 1:
+            self.dbg('Received', repr(received_lines[0]))
+
+        if received_lines == ['% Unknown command.']:
+            errmsg = 'VTY reports unknown command: %r' % command_str
+            if strict:
+                raise VtyInterfaceExn(errmsg)
+            else:
+                self.log('ignoring error:', errmsg)
+
+        return received_lines
+
+    def cmd(self, command_str, timeout=10, strict=True):
+        # (copied from https://git.osmocom.org/python/osmo-python-tests/tree/osmopy/osmo_interact/vty.py)
+        command_str = command_str or '\r'
+        if command_str[-1] not in '?\r\t':
+            command_str = command_str + '\r'
+
+        received_lines = self._command(command_str, timeout, strict)
+
+        # send escape to cancel the '?' command line
+        if command_str[-1] == '?':
+            self._command('\x03', timeout)
+
+        return received_lines
+
+    def cmds(self, *cmds, timeout=10, strict=True):
+        responses = []
+        for cmd in cmds:
+            responses.append(self.cmd(cmd, timeout, strict))
+        return responses
+
+    def __enter__(self):
+        self.connect()
+        return self
+
+    def __exit__(self, *exc_info):
+        self.disconnect()
+
+# vim: expandtab tabstop=4 shiftwidth=4

-- 
To view, visit https://gerrit.osmocom.org/c/osmo-gsm-tester/+/21504
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings

Gerrit-Project: osmo-gsm-tester
Gerrit-Branch: master
Gerrit-Change-Id: I7c17b143b7c690b8c4105ee7c6272670046fa91d
Gerrit-Change-Number: 21504
Gerrit-PatchSet: 1
Gerrit-Owner: neels <nhofmeyr at sysmocom.de>
Gerrit-MessageType: newchange
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osmocom.org/pipermail/gerrit-log/attachments/20201203/91588f97/attachment.htm>


More information about the gerrit-log mailing list