blob: c7f8b2736c30703769695d93f0102216bdddcddd [file] [log] [blame]
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +02001# Copyright (C) 2012, 2013 Holger Hans Peter Freyther
Kata7185c62013-04-04 17:31:13 +02002# Copyright (C) 2013 Katerina Barone-Adesi
3# This program is free software: you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation, either version 2 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16#
17# VTY helper code for OpenBSC
18#
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +020019import re
Kata7185c62013-04-04 17:31:13 +020020import socket
21
Kata8ee6bb2013-04-05 17:06:30 +020022"""VTYInteract: interact with an osmocom vty
23
24Specify a VTY to connect to, and run commands on it.
25Connections will be reestablished as necessary.
26Methods: __init__, command, enabled_command, verify, w_verify"""
27
Kata7185c62013-04-04 17:31:13 +020028
29class VTYInteract(object):
Kata8ee6bb2013-04-05 17:06:30 +020030 """__init__(self, name, host, port):
31
32 name is the name the vty prints for commands, ie OpenBSC
33 host is the hostname to connect to
34 port is the port to connect on"""
Kata7185c62013-04-04 17:31:13 +020035 def __init__(self, name, host, port):
36 self.name = name
37 self.host = host
38 self.port = port
39
40 self.socket = None
Jacob Erlbeck41b0d302013-08-30 18:28:05 +020041 self.norm_end = re.compile('\r\n%s(?:\(([\w-]*)\))?> $' % self.name)
42 self.priv_end = re.compile('\r\n%s(?:\(([\w-]*)\))?# $' % self.name)
43 self.last_node = ''
Kata7185c62013-04-04 17:31:13 +020044
45 def _close_socket(self):
46 self.socket.close()
47 self.socket = None
48
49 def _is_end(self, text, ends):
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +020050 """
51 >>> vty = VTYInteract('OsmoNAT', 'localhost', 9999)
52 >>> end = [vty.norm_end, vty.priv_end]
53
54 Simple test
55 >>> text1 = 'abc\\r\\nOsmoNAT> '
56 >>> vty._is_end(text1, end)
57 11
58
59 Simple test with the enabled node
60 >>> text2 = 'abc\\r\\nOsmoNAT# '
61 >>> vty._is_end(text2, end)
62 11
63
64 Now the more complicated one
65 >>> text3 = 'abc\\r\\nOsmoNAT(config)# '
66 >>> vty._is_end(text3, end)
67 19
68
69 Now the more complicated one
70 >>> text4 = 'abc\\r\\nOsmoNAT(config-nat)# '
71 >>> vty._is_end(text4, end)
72 23
73
74 Now the more complicated one
75 >>> text5 = 'abc\\r\\nmoo'
76 >>> vty._is_end(text5, end)
77 0
Jacob Erlbeck41b0d302013-08-30 18:28:05 +020078
79 Check for node name extraction
80 >>> text6 = 'abc\\r\\nOsmoNAT(config-nat)# '
81 >>> vty._is_end(text6, end)
82 23
83 >>> vty.node()
84 'config-nat'
85
86 Check for empty node name extraction
87 >>> text7 = 'abc\\r\\nOsmoNAT# '
88 >>> vty._is_end(text7, end)
89 11
90 >>> vty.node() is None
91 True
92
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +020093 """
Jacob Erlbeck41b0d302013-08-30 18:28:05 +020094 self.last_node = None
Kata7185c62013-04-04 17:31:13 +020095 for end in ends:
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +020096 match = end.search(text)
97 if match:
Jacob Erlbeck41b0d302013-08-30 18:28:05 +020098 self.last_node = match.group(1)
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +020099 return match.end() - match.start()
100 return 0
Kata7185c62013-04-04 17:31:13 +0200101
102 def _common_command(self, request, close=False, ends=None):
103 if not ends:
104 ends = [self.norm_end, self.priv_end]
105 if not self.socket:
106 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
107 self.socket.setblocking(1)
108 self.socket.connect((self.host, self.port))
109 self.socket.recv(4096)
110
111 # Now send the command
112 self.socket.send("%s\r" % request)
113 res = ""
114 end = ""
115
116 # Unfortunately, timeout and recv don't always play nicely
117 while True:
118 data = self.socket.recv(4096)
119 res = "%s%s" % (res, data)
120 if not res: # yes, this is ugly
121 raise IOError("Failed to read data (did the app crash?)")
122 end = self._is_end(res, ends)
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +0200123 if end > 0:
Kata7185c62013-04-04 17:31:13 +0200124 break
125
126 if close:
127 self._close_socket()
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +0200128 return res[len(request) + 2: -end]
Kata7185c62013-04-04 17:31:13 +0200129
130 # There's no close parameter, as close=True makes this useless
131 def enable(self):
132 self.command("enable")
133
134 """Run a command on the vty"""
Kata8ee6bb2013-04-05 17:06:30 +0200135
Kata7185c62013-04-04 17:31:13 +0200136 def command(self, request, close=False):
137 return self._common_command(request, close)
138
139 """Run enable, followed by another command"""
140 def enabled_command(self, request, close=False):
141 self.enable()
142 return self._common_command(request, close)
143
144 """Verify, ignoring leading/trailing whitespace"""
145 # inspired by diff -w, though not identical
146 def w_verify(self, command, results, close=False, loud=True):
147 return self.verify(command, results, close, loud, lambda x: x.strip())
148
149 """Verify that a command has the expected results
150
151 command = the command to verify
152 results = the expected results [line1, line2, ...]
153 close = True to close the socket after running the verify
154 loud = True to show what was expected and what actually happend, stdout
155 f = A function to run over the expected and actual results, before compare
156
157 Returns True iff the expected and actual results match"""
158 def verify(self, command, results, close=False, loud=True, f=None):
159 res = self.command(command, close).split('\r\n')
160 if f:
161 res = map(f, res)
162 results = map(f, results)
163
164 if loud:
165 if res != results:
166 print "Rec: %s\nExp: %s" % (res, results)
167
168 return res == results
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +0200169
Jacob Erlbeck41b0d302013-08-30 18:28:05 +0200170 def node(self):
171 return self.last_node
172
Holger Hans Peter Freyther99bbea72013-06-25 08:17:59 +0200173if __name__ == "__main__":
174 import doctest
175 doctest.testmod()