virl2_client 2.0.0b5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
examples/demo.ipynb ADDED
@@ -0,0 +1,211 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import urllib3\n",
10
+ "from virl2_client import ClientLibrary\n",
11
+ "\n",
12
+ "urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n",
13
+ "client = ClientLibrary(\"https://192.168.1.1\", \"virl2\", \"virl2\", ssl_verify=False)"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": null,
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "lab = client.create_lab()\n",
23
+ "print(lab.id)"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "r1 = lab.create_node(\"r1\", \"iosv\", 50, 100)"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "execution_count": null,
38
+ "metadata": {},
39
+ "outputs": [],
40
+ "source": [
41
+ "r2 = lab.create_node(\"r2\", \"iosv\", 302, 201)"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "execution_count": null,
47
+ "metadata": {},
48
+ "outputs": [],
49
+ "source": [
50
+ "r3 = lab.create_node(\"r3\", \"iosv\", 200, 400)"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": null,
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "r1_i1 = r1.create_interface()\n",
60
+ "r1_i2 = r1.create_interface()"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "execution_count": null,
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "r2_i1 = r2.create_interface()\n",
70
+ "r2_i2 = r2.create_interface()"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "metadata": {},
77
+ "outputs": [],
78
+ "source": [
79
+ "r3_i1 = r3.create_interface()\n",
80
+ "r3_i2 = r3.create_interface()"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": null,
86
+ "metadata": {},
87
+ "outputs": [],
88
+ "source": [
89
+ "link_1 = lab.create_link(r1_i1, r2_i1)"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "execution_count": null,
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "link_2 = lab.create_link(r2_i2, r3_i1)"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": null,
104
+ "metadata": {},
105
+ "outputs": [],
106
+ "source": [
107
+ "link_3 = lab.create_link(r3_i2, r1_i2)"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": null,
113
+ "metadata": {},
114
+ "outputs": [],
115
+ "source": [
116
+ "lab.remove_link(link_1)"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "execution_count": null,
122
+ "metadata": {},
123
+ "outputs": [],
124
+ "source": [
125
+ "lab.remove_link(link_2)"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "execution_count": null,
131
+ "metadata": {},
132
+ "outputs": [],
133
+ "source": [
134
+ "lab.remove_link(link_3)"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": null,
140
+ "metadata": {},
141
+ "outputs": [],
142
+ "source": [
143
+ "lab.remove_interface(r1_i2)"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": null,
149
+ "metadata": {},
150
+ "outputs": [],
151
+ "source": [
152
+ "lab.remove_node(r1)"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "metadata": {},
159
+ "outputs": [],
160
+ "source": [
161
+ "lab.remove_node(r2)"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": null,
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "lab.remove_node(r3)"
171
+ ]
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "execution_count": null,
176
+ "metadata": {},
177
+ "outputs": [],
178
+ "source": [
179
+ "lab.remove()"
180
+ ]
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "execution_count": null,
185
+ "metadata": {},
186
+ "outputs": [],
187
+ "source": []
188
+ }
189
+ ],
190
+ "metadata": {
191
+ "kernelspec": {
192
+ "display_name": "Python 3",
193
+ "language": "python",
194
+ "name": "python3"
195
+ },
196
+ "language_info": {
197
+ "codemirror_mode": {
198
+ "name": "ipython",
199
+ "version": 3
200
+ },
201
+ "file_extension": ".py",
202
+ "mimetype": "text/x-python",
203
+ "name": "python",
204
+ "nbconvert_exporter": "python",
205
+ "pygments_lexer": "ipython3",
206
+ "version": "3.6.6"
207
+ }
208
+ },
209
+ "nbformat": 4,
210
+ "nbformat_minor": 2
211
+ }
examples/sample.py ADDED
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # Python bindings for the Cisco VIRL 2 Network Simulation Platform
4
+ #
5
+ # This file is part of VIRL 2
6
+ #
7
+ # Copyright 2020 Cisco Systems Inc.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ #
21
+
22
+ from virl2_client import ClientLibrary
23
+
24
+ # setup the connection and clean everything
25
+ cl = ClientLibrary("http://localhost:8001", "virl2", "virl2", allow_http=True)
26
+ cl.wait_for_lld_connected()
27
+
28
+ lab_list = cl.get_lab_list()
29
+ for lab_id in lab_list:
30
+ lab = cl.join_existing_lab(lab_id)
31
+ lab.stop()
32
+ lab.wipe()
33
+ cl.remove_lab(lab_id)
34
+
35
+ lab = cl.create_lab()
36
+ lab_id = "lab_1"
37
+ lab = cl.join_existing_lab(lab_id)
38
+
39
+ s1 = lab.create_node("s1", "server", 50, 100)
40
+ s2 = lab.create_node("s2", "server", 50, 200)
41
+ print(s1, s2)
42
+
43
+ # create a link between s1 and s2, equivalent to
44
+ # s1_i1 = s1.create_interface()
45
+ # s2_i1 = s2.create_interface()
46
+ # lab.create_link(s1_i1, s2_i1)
47
+ lab.connect_two_nodes(s1, s2)
48
+
49
+ # this must remove the link between s1 and s2
50
+ lab.remove_node(s2)
51
+
52
+ lab.sync_states()
53
+ for node in lab.nodes():
54
+ print(node, node.state)
55
+ for iface in node.interfaces:
56
+ print(iface, iface.state)
57
+
58
+ assert [link for link in lab.links() if link.state is not None] == []
@@ -0,0 +1,25 @@
1
+ """
2
+ Python bindings for the Cisco VIRL 2 Network Simulation Platform
3
+
4
+ This file is part of VIRL 2
5
+
6
+ Copyright 2020 Cisco Systems Inc.
7
+
8
+ Licensed under the Apache License, Version 2.0 (the "License");
9
+ you may not use this file except in compliance with the License.
10
+ You may obtain a copy of the License at
11
+
12
+ http://www.apache.org/licenses/LICENSE-2.0
13
+
14
+ Unless required by applicable law or agreed to in writing, software
15
+ distributed under the License is distributed on an "AS IS" BASIS,
16
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ See the License for the specific language governing permissions and
18
+ limitations under the License.
19
+ """
20
+
21
+ # flake8: noqa: F401
22
+
23
+ from .exceptions import InterfaceNotFound, LabNotFound, LinkNotFound, NodeNotFound
24
+ from .virl2_client import ClientLibrary, InitializationError
25
+ from .models.authentication import Context
@@ -0,0 +1,35 @@
1
+ #
2
+ # Python bindings for the Cisco VIRL 2 Network Simulation Platform
3
+ #
4
+ # This file is part of VIRL 2
5
+ #
6
+ # Copyright 2020 Cisco Systems Inc.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ #
20
+
21
+
22
+ class NodeNotFound(Exception):
23
+ pass
24
+
25
+
26
+ class LinkNotFound(Exception):
27
+ pass
28
+
29
+
30
+ class InterfaceNotFound(Exception):
31
+ pass
32
+
33
+
34
+ class LabNotFound(Exception):
35
+ pass
@@ -0,0 +1,32 @@
1
+ #
2
+ # Python bindings for the Cisco VIRL 2 Network Simulation Platform
3
+ #
4
+ # This file is part of VIRL 2
5
+ #
6
+ # Copyright 2020 Cisco Systems Inc.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ #
20
+ """This package contains the VIRL2 client library models for
21
+ labs, nodes, interfaces and links. It also contains classes for
22
+ node and image definition and helper classes for automation
23
+ and authentication."""
24
+
25
+ from .interface import Interface
26
+ from .authentication import Context, TokenAuth
27
+ from .lab import Lab
28
+ from .link import Link
29
+ from .node import Node
30
+ from .node_image_definitions import NodeImageDefinitions
31
+
32
+ __all__ = ("Interface", "Lab", "Link", "Node")
@@ -0,0 +1,111 @@
1
+ #
2
+ # Python bindings for the Cisco VIRL 2 Network Simulation Platform
3
+ #
4
+ # This file is part of VIRL 2
5
+ #
6
+ # Copyright 2020 Cisco Systems Inc.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ #
20
+
21
+ import logging
22
+ import uuid
23
+ from urllib.parse import urljoin, urlparse
24
+
25
+ import requests
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class TokenAuth(requests.auth.AuthBase):
31
+ """
32
+ Inspired by:
33
+ http://docs.python-requests.org/en/v2.9.1/user/authentication/?highlight=AuthBase#new-forms-of-authentication
34
+ """
35
+ def __init__(self, client_library):
36
+ self.client_library = client_library
37
+ self.token = None
38
+
39
+ def __call__(self, request):
40
+ token = self.authenticate()
41
+ request.headers["Authorization"] = "Bearer {}".format(token)
42
+ request.register_hook('response', self.handle_401_unauthorized)
43
+ return request
44
+
45
+ def handle_401_unauthorized(self, resp, **kwargs):
46
+ # ensure that we print the result from the API if something goes wrong.
47
+ # As almost every library call uses "raise_for_status()"
48
+ if resp.status_code != 401:
49
+ if not resp.ok:
50
+ logger.error("API Error: %s", resp.text)
51
+ return resp
52
+
53
+ # reset existing token:
54
+ self.token = None
55
+ # repeat last request that has failed
56
+ token = self.authenticate()
57
+ request = resp.request.copy()
58
+ request.headers["Authorization"] = "Bearer {}".format(token)
59
+ request.deregister_hook('response', self.handle_401_unauthorized)
60
+ new_resp = resp.connection.send(request)
61
+ new_resp.history.append(resp)
62
+ return new_resp
63
+
64
+ def authenticate(self):
65
+ if self.token is not None:
66
+ return self.token
67
+ url = urljoin(self.client_library._base_url, "authenticate")
68
+ parsed_url = urlparse(url)
69
+ if parsed_url.port is not None and parsed_url.port != 443:
70
+ logger.warning("Not using SSL port of 443: %d", parsed_url.port)
71
+ if parsed_url.scheme != "https":
72
+ logger.warning("Not using https scheme: %s", parsed_url.scheme)
73
+ data = {
74
+ "username": self.client_library.username,
75
+ "password": self.client_library.password
76
+ }
77
+ response = self.client_library.session.post(url, json=data, auth=False)
78
+ response.raise_for_status()
79
+ self.token = response.json()
80
+ return self.token
81
+
82
+
83
+ class Context:
84
+ def __init__(self, base_url, requests_session=None, client_uuid=None):
85
+ self._base_url = base_url
86
+ if client_uuid is None:
87
+ self._client_uuid = str(uuid.uuid4())
88
+ else:
89
+ self._client_uuid = client_uuid
90
+ if requests_session is None:
91
+ self._requests_session = requests.Session()
92
+ else:
93
+ self._requests_session = requests_session
94
+
95
+ def __repr__(self):
96
+ return "{}({!r}, {!r}, {!r})".format(self.__class__.__name__,
97
+ self._base_url,
98
+ self._requests_session,
99
+ self._client_uuid)
100
+
101
+ @property
102
+ def base_url(self):
103
+ return self._base_url
104
+
105
+ @property
106
+ def session(self):
107
+ return self._requests_session
108
+
109
+ @property
110
+ def uuid(self):
111
+ return self._client_uuid
@@ -0,0 +1,132 @@
1
+ #
2
+ # Python bindings for the Cisco VIRL 2 Network Simulation Platform
3
+ #
4
+ # This file is part of VIRL 2
5
+ #
6
+ # Copyright 2020 Cisco Systems Inc.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ #
20
+
21
+ import io
22
+ import logging
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class PyatsNotInstalled(Exception):
28
+ pass
29
+
30
+
31
+ class PyatsDeviceNotFound(Exception):
32
+ pass
33
+
34
+
35
+ class ClPyats:
36
+ """Creates a pyATS object that can be used to run commands
37
+ against a device either in exec mode ``show version`` or in
38
+ configuration mode ``interface gi0/0\\\\nno shut``.
39
+
40
+ :param lab: The lab which should be used with pyATS
41
+ :type lab: models.Lab
42
+ :raises PyatsNotInstalled: when pyATS can not be found
43
+ :raises PyatsDeviceNotFound: when the device can not be found
44
+ """
45
+ def __init__(self, lab):
46
+ """Constructor method"""
47
+ self._pyats_installed = False
48
+ self._lab = lab
49
+ try:
50
+ import pyats # noqa: F401
51
+ except ImportError:
52
+ return
53
+ else:
54
+ self._pyats_installed = True
55
+
56
+ self._testbed = None
57
+ self._connections = []
58
+
59
+ def _check_pyats_installed(self):
60
+ if not self._pyats_installed:
61
+ raise PyatsNotInstalled
62
+
63
+ def sync_testbed(self, username, password):
64
+ """Syncs the the testbed from the server. Note that this
65
+ will always fetch the latest topology data from the server.
66
+
67
+ :param username: the username that will be inserted into
68
+ the testbed data
69
+ :type username: str
70
+ :param password: the password that will be inserted into
71
+ the testbed data
72
+ :type password: str
73
+ """
74
+ self._check_pyats_installed()
75
+ from pyats.topology import loader
76
+ testbed_yaml = self._lab.get_pyats_testbed()
77
+ data = loader.load(io.StringIO(testbed_yaml))
78
+ data.devices.terminal_server.connections.cli.username = username
79
+ data.devices.terminal_server.connections.cli.password = password
80
+ self._testbed = data
81
+
82
+ def run_command(self, node_label, command):
83
+ """Run a command on the device in exec mode
84
+
85
+ :param node_label: the label / title of the device
86
+ :type node_label: str
87
+ :param command: the command to be run in exec mode
88
+ :type command: str
89
+ :returns: The output from the device
90
+ :rtype: str
91
+ """
92
+ self._check_pyats_installed()
93
+
94
+ try:
95
+ pyats_device = self._testbed.devices[node_label]
96
+ except KeyError:
97
+ raise PyatsDeviceNotFound(node_label)
98
+
99
+ # TODO: later check if connected
100
+ # TODO: later look at pooling connections
101
+ pyats_device.connect(log_stdout=False)
102
+ self._connections.append(pyats_device)
103
+ return pyats_device.execute(command, log_stdout=False)
104
+
105
+ def run_config_command(self, node_label, command):
106
+ """Run a command on the device in configure mode. pyATS
107
+ handles the change into configure mode automatically.
108
+
109
+ :param node_label: the label / title of the device
110
+ :type node_label: str
111
+ :param command: the command to be run in exec mode
112
+ :type command: str
113
+ :returns: The output from the device
114
+ :rtype: str
115
+ """
116
+ self._check_pyats_installed()
117
+
118
+ try:
119
+ pyats_device = self._testbed.devices[node_label]
120
+ except KeyError:
121
+ raise PyatsDeviceNotFound(node_label)
122
+
123
+ # TODO: later check if connected
124
+ # TODO: later look at pooling connections
125
+ pyats_device.connect(log_stdout=False)
126
+ self._connections.append(pyats_device)
127
+ return pyats_device.configure(command, log_stdout=False)
128
+
129
+ def cleanup(self):
130
+ """cleans up the pyATS connections"""
131
+ for pyats_device in self._connections:
132
+ pyats_device.destroy()