-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathlab.py
1906 lines (1631 loc) · 64.8 KB
/
lab.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# This file is part of VIRL 2
# Copyright (c) 2019-2024, Cisco Systems, Inc.
# All rights reserved.
#
# Python bindings for the Cisco VIRL 2 Network Simulation Platform
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import json
import logging
import time
import warnings
from typing import TYPE_CHECKING, Any, Iterable
from httpx import HTTPStatusError
from ..exceptions import (
AnnotationNotFound,
ElementAlreadyExists,
InterfaceNotFound,
InvalidAnnotationType,
LabNotFound,
LinkNotFound,
NodeNotFound,
VirlException,
)
from ..utils import check_stale, get_url_from_template, locked
from ..utils import property_s as property
from .annotation import (
Annotation,
AnnotationEllipse,
AnnotationLine,
AnnotationRectangle,
AnnotationText,
)
from .cl_pyats import ClPyats
from .interface import Interface
from .link import Link
from .node import Node
if TYPE_CHECKING:
import httpx
from .annotation import AnnotationType
from .resource_pools import ResourcePool, ResourcePoolManagement
_LOGGER = logging.getLogger(__name__)
class Lab:
_URL_TEMPLATES = {
"lab": "labs/{lab_id}",
"nodes": "labs/{lab_id}/nodes?{CONFIG_MODE}",
"nodes_populated": "labs/{lab_id}/nodes?populate_interfaces=true&{CONFIG_MODE}",
"nodes_operational": "labs/{lab_id}/nodes?data=true&operational=true"
"&exclude_configurations=true",
"links": "labs/{lab_id}/links",
"interfaces": "labs/{lab_id}/interfaces",
"simulation_stats": "labs/{lab_id}/simulation_stats",
"lab_element_state": "labs/{lab_id}/lab_element_state",
"check_if_converged": "labs/{lab_id}/check_if_converged",
"start": "labs/{lab_id}/start",
"stop": "labs/{lab_id}/stop",
"state": "labs/{lab_id}/state",
"wipe": "labs/{lab_id}/wipe",
"events": "labs/{lab_id}/events",
"build_configurations": "build_configurations?lab_id={lab_id}",
"topology": "labs/{lab_id}/topology",
"pyats_testbed": "labs/{lab_id}/pyats_testbed",
"layer3_addresses": "labs/{lab_id}/layer3_addresses",
"download": "labs/{lab_id}/download",
"groups": "labs/{lab_id}/groups",
"connector_mappings": "labs/{lab_id}/connector_mappings",
"resource_pools": "labs/{lab_id}/resource_pools",
"annotations": "labs/{lab_id}/annotations",
}
def __init__(
self,
title: str | None,
lab_id: str,
session: httpx.Client,
username: str,
password: str,
auto_sync: bool = True,
auto_sync_interval: float = 1.0,
wait: bool = True,
wait_max_iterations: int = 500,
wait_time: int = 5,
hostname: str | None = None,
resource_pool_manager: ResourcePoolManagement | None = None,
) -> None:
"""
A VIRL2 lab network topology.
:param title: Name or title of the lab.
:param lab_id: Lab ID.
:param session: The httpx-based HTTP client for this session with the server.
:param username: Username of the user to authenticate.
:param password: Password of the user to authenticate.
:param auto_sync: A flag indicating whether local changes should be
automatically synced to the server.
:param auto_sync_interval: Interval in seconds for automatic syncing.
:param wait: A flag indicating whether to wait for convergence on the backend.
:param wait_max_iterations: Maximum number of iterations for convergence.
:param wait_time: Time in seconds to sleep between convergence calls
on the backend.
:param hostname: Hostname/IP and port for pyATS console terminal server.
:param resource_pool_manager: ResourcePoolManagement object shared
with parent ClientLibrary.
:raises VirlException: If the lab object is created without
a resource pool manager.
"""
self.username = username
self.password = password
self._title = title
self._description = ""
self._notes = ""
self._id = lab_id
self._session = session
self._owner = username
self._state = None
self._nodes: dict[str, Node] = {}
"""
Dictionary containing all nodes in the lab.
It maps node identifier to `models.Node`.
"""
self._links: dict[str, Link] = {}
"""
Dictionary containing all links in the lab.
It maps link identifier to `models.Link`.
"""
self._interfaces: dict[str, Interface] = {}
"""
Dictionary containing all interfaces in the lab.
It maps interface identifier to `models.Interface`.
"""
self._annotations: dict[str, Annotation] = {}
"""
Dictionary containing all annotations in the lab.
It maps annotation identifier to `models.Annotation`.
"""
self.events: list = []
self.pyats = ClPyats(self, hostname)
self.auto_sync = auto_sync
self.auto_sync_interval = auto_sync_interval
self._last_sync_statistics_time = 0.0
self._last_sync_state_time = 0.0
self._last_sync_l3_address_time = 0.0
self._last_sync_topology_time = 0.0
self._last_sync_operational_time = 0.0
self._initialized = False
self.wait_for_convergence = wait
self.wait_max_iterations = wait_max_iterations
self.wait_time = wait_time
if resource_pool_manager is None:
raise VirlException(
f"Lab object for lab {title or lab_id} cannot be created "
"because it is missing a resource pool manager."
)
self._resource_pool_manager = resource_pool_manager
self._resource_pools = []
self._stale = False
self._synced_configs = True
def __len__(self):
return len(self._nodes)
def __str__(self):
return f"Lab: {self._title}{' (STALE)' if self._stale else ''}"
def __repr__(self):
return "{}({!r}, {!r}, {!r}, {!r}, {!r}, {!r})".format(
self.__class__.__name__,
self._title,
self._id,
self._session.base_url.path,
self.auto_sync,
self.auto_sync_interval,
self.wait_for_convergence,
)
def _url_for(self, endpoint, **kwargs):
"""
Generate the URL for a given API endpoint.
:param endpoint: The desired endpoint.
:param **kwargs: Keyword arguments used to format the URL.
:returns: The formatted URL.
"""
kwargs["lab_id"] = self._id
return get_url_from_template(endpoint, self._URL_TEMPLATES, kwargs)
def need_to_wait(self, local_wait: bool | None) -> bool:
"""
Check if waiting is required.
If `local_wait` is `None`, return the value of `wait_for_convergence`.
If `local_wait` is not a boolean, raise a `ValueError`.
:param local_wait: Local wait flag.
:returns: True if waiting is required, False otherwise.
:raises ValueError: If `local_wait` is not a boolean or None.
"""
if local_wait is None:
return self.wait_for_convergence
if not isinstance(local_wait, bool):
raise ValueError
return local_wait
@check_stale
@locked
def sync_statistics_if_outdated(self) -> None:
"""Sync statistics if they are outdated."""
timestamp = time.time()
if (
self.auto_sync
and timestamp - self._last_sync_statistics_time > self.auto_sync_interval
):
self.sync_statistics()
@check_stale
@locked
def sync_states_if_outdated(self) -> None:
"""Sync states if they are outdated."""
timestamp = time.time()
if (
self.auto_sync
and timestamp - self._last_sync_state_time > self.auto_sync_interval
):
self.sync_states()
@check_stale
@locked
def sync_l3_addresses_if_outdated(self) -> None:
"""Sync L3 addresses if they are outdated."""
timestamp = time.time()
if (
self.auto_sync
and timestamp - self._last_sync_l3_address_time > self.auto_sync_interval
):
self.sync_layer3_addresses()
@check_stale
@locked
def sync_topology_if_outdated(self, exclude_configurations=True) -> None:
"""Sync the topology if it is outdated."""
timestamp = time.time()
if not (exclude_configurations or self._synced_configs):
self._sync_topology(exclude_configurations=False)
elif (
self.auto_sync
and timestamp - self._last_sync_topology_time > self.auto_sync_interval
):
self._sync_topology(exclude_configurations=exclude_configurations)
self._synced_configs = not exclude_configurations
@check_stale
@locked
def sync_operational_if_outdated(self) -> None:
"""Sync the operational data if it is outdated."""
timestamp = time.time()
if (
self.auto_sync
and timestamp - self._last_sync_operational_time > self.auto_sync_interval
):
self.sync_operational()
@property
def id(self) -> str:
"""Return the ID of the lab (a 6 digit hex string)."""
return self._id
@property
def title(self) -> str | None:
"""Return the title of the lab."""
self.sync_topology_if_outdated()
return self._title
@title.setter
def title(self, value: str) -> None:
"""Set the title of the lab."""
self._set_property("title", value)
@property
def notes(self) -> str:
"""Return the notes of the lab."""
self.sync_topology_if_outdated()
return self._notes
@notes.setter
def notes(self, value: str) -> None:
"""Set the notes of the lab."""
self._set_property("notes", value)
@property
def description(self) -> str:
"""Return the description of the lab."""
self.sync_topology_if_outdated()
return self._description
@description.setter
def description(self, value: str) -> None:
"""Set the description of the lab."""
self._set_property("description", value)
@check_stale
@locked
def _set_property(self, prop: str, value: Any):
"""
Set the value of a lab property both locally and on the server.
:param prop: The name of the property.
:param value: The new value of the property.
"""
url = self._url_for("lab")
self._session.patch(url, json={prop: value})
setattr(self, f"_{prop}", value)
@property
def owner(self) -> str:
"""Return the owner of the lab."""
self.sync_topology_if_outdated()
return self._owner
@property
def resource_pools(self) -> list[ResourcePool]:
"""Return the list of resource pools this lab's nodes belong to."""
self.sync_operational_if_outdated()
return self._resource_pools
def nodes(self) -> list[Node]:
"""
Return the list of nodes in the lab.
:returns: A list of Node objects.
"""
self.sync_topology_if_outdated()
return list(self._nodes.values())
def links(self) -> list[Link]:
"""
Return the list of links in the lab.
:returns: A list of Link objects.
"""
self.sync_topology_if_outdated()
return list(self._links.values())
def interfaces(self) -> list[Interface]:
"""
Return the list of interfaces in the lab.
:returns: A list of Interface objects.
"""
self.sync_topology_if_outdated()
return list(self._interfaces.values())
def annotations(self) -> list[AnnotationType]:
"""
Return the list of annotations in the lab.
:returns: A list of Annotation objects.
"""
self.sync_topology_if_outdated()
return list(self._annotations.values())
@property
@locked
def statistics(self) -> dict:
"""
Return lab statistics.
:returns: A dictionary with stats of the lab.
"""
return {
"nodes": len(self._nodes),
"links": len(self._links),
"interfaces": len(self._interfaces),
"annotations": len(self._annotations),
}
def get_node_by_id(self, node_id: str) -> Node:
"""
Return the node identified by the ID.
:param node_id: ID of the node to be returned.
:returns: A Node object.
:raises NodeNotFound: If the node is not found.
"""
self.sync_topology_if_outdated()
try:
return self._nodes[node_id]
except KeyError:
raise NodeNotFound(node_id)
def get_node_by_label(self, label: str) -> Node:
"""
Return the node identified by the label.
:param label: Label of the node to be returned.
:returns: A Node object.
:raises NodeNotFound: If the node is not found.
"""
self.sync_topology_if_outdated()
for node in self._nodes.values():
if node.label == label:
return node
raise NodeNotFound(label)
def get_interface_by_id(self, interface_id: str) -> Interface:
"""
Return the interface identified by the ID.
:param interface_id: ID of the interface to be returned.
:returns: An Interface object.
:raises InterfaceNotFound: If the interface is not found.
"""
self.sync_topology_if_outdated()
try:
return self._interfaces[interface_id]
except KeyError:
raise InterfaceNotFound(interface_id)
def get_link_by_id(self, link_id: str) -> Link:
"""
Return the link identified by the ID.
:param link_id: ID of the link to be returned.
:returns: A Link object.
:raises LinkNotFound: If the link is not found.
"""
self.sync_topology_if_outdated()
try:
return self._links[link_id]
except KeyError:
raise LinkNotFound(link_id)
@staticmethod
def get_link_by_nodes(node1: Node, node2: Node) -> Link:
"""
DEPRECATED: Use `Node.get_link_to()` to get one link
or `Node.get_links_to()` to get all links.
(Reason: redundancy)
Return ONE of the links identified by two node objects.
:param node1: The first node.
:param node2: The second node.
:returns: One of links between the nodes.
:raises LinkNotFound: If no such link exists.
"""
warnings.warn(
"'Lab.get_link_by_nodes()' is deprecated. "
"Use 'Node.get_link_to()' or 'Node.get_links_to()' instead.",
DeprecationWarning,
)
if not (links := node1.get_links_to(node2)):
raise LinkNotFound
return links[0]
@staticmethod
def get_link_by_interfaces(iface1: Interface, iface2: Interface) -> Link | None:
"""
DEPRECATED: Use `Interface.get_link_to()` instead.
(Reason: redundancy)
Return the link identified by two interface objects.
:param iface1: The first interface.
:param iface2: The second interface.
:returns: The link between the interfaces.
:raises LinkNotFound: If no such link exists.
"""
warnings.warn(
"'Lab.get_link_by_interfaces()' is deprecated. "
"Use 'Interface.get_link_to()' instead.",
DeprecationWarning,
)
if (link := iface1.link) is not None and iface2 in link.interfaces:
return link
raise LinkNotFound
def get_annotation_by_id(self, annotation_id: str) -> AnnotationType:
"""
Return the annotation identified by the ID.
:param annotation_id: ID of the annotation to be returned
:returns: An Annotation object.
:raises AnnotationNotFound: If annotation is not found.
"""
self.sync_topology_if_outdated()
try:
return self._annotations[annotation_id]
except KeyError:
raise AnnotationNotFound(annotation_id)
def find_nodes_by_tag(self, tag: str) -> list[Node]:
"""
Return the nodes identified by the given tag.
:param tag: The tag by which to search.
:returns: A list of nodes.
"""
self.sync_topology_if_outdated()
return [node for node in self.nodes() if tag in node.tags()]
@check_stale
@locked
def create_node(
self,
label: str,
node_definition: str,
x: int = 0,
y: int = 0,
wait: bool | None = None,
populate_interfaces: bool = False,
**kwargs,
) -> Node:
"""
Create a node in the lab with the given parameters.
:param label: Label.
:param node_definition: Node definition.
:param x: The X coordinate.
:param y: The Y coordinate.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
:param populate_interfaces: Automatically create a pre-defined number
of interfaces on node creation.
:returns: A Node object.
"""
try:
self.get_node_by_label(label)
_LOGGER.warning(f"Node with label {label} already exists.")
except NodeNotFound:
pass
if populate_interfaces:
url = self._url_for("nodes_populated")
else:
url = self._url_for("nodes")
kwargs["label"] = label
kwargs["node_definition"] = node_definition
kwargs["x"] = x
kwargs["y"] = y
result: dict[str, str] = self._session.post(url, json=kwargs).json()
node_id: str = result["id"]
# if add node to an empty lab, then consider it "initialized" for sync purposes
if not self._initialized:
self._initialized = True
if self.need_to_wait(wait):
self.wait_until_lab_converged()
for key in ("image_definition", "configuration"):
if key not in kwargs:
kwargs[key] = None
kwargs["resource_pool"] = None
kwargs.pop("compute_id", None)
node = self._create_node_local(node_id, **kwargs)
return node
def add_node_local(self, *args, **kwargs):
"""
DEPRECATED: Use `.create_node()` instead.
(Reason: only creates a node in the client, which is not useful;
if really needed, use `._create_node_local()`)
Creates a node in the client, but not on the server.
"""
warnings.warn(
"'Lab.add_node_local' is deprecated. You probably want .create_node "
"instead. (If you really want to create a node locally only, "
"use '._create_node_local()'.)",
DeprecationWarning,
)
return self._create_node_local(*args, **kwargs)
@locked
def _create_node_local(
self,
node_id: str,
label: str,
node_definition: str,
image_definition: str | None,
configuration: list[dict[str, str]] | str | None,
x: int,
y: int,
ram: int | None = None,
cpus: int | None = None,
cpu_limit: int | None = None,
data_volume: int | None = None,
boot_disk_size: int | None = None,
hide_links: bool = False,
tags: list | None = None,
compute_id: str | None = None,
resource_pool: ResourcePool | None = None,
parameters: dict = {},
pinned_compute_id: str | None = None,
) -> Node:
"""Helper function to add a node to the client library."""
if tags is None:
tags = []
node = Node(
self,
node_id,
label,
node_definition,
image_definition,
configuration,
x,
y,
ram,
cpus,
cpu_limit,
data_volume,
boot_disk_size,
hide_links,
tags,
resource_pool,
parameters,
pinned_compute_id,
)
if compute_id is not None:
node._compute_id = compute_id
self._nodes[node.id] = node
return node
@check_stale
@locked
def remove_node(self, node: Node | str, wait: bool | None = None) -> None:
"""
Remove a node from the lab.
If you have a node object, you can also simply do::
node.remove()
:param node: The node object or ID.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
"""
if isinstance(node, str):
node = self.get_node_by_id(node)
node._remove_on_server()
self._remove_node_local(node)
if self.need_to_wait(wait):
self.wait_until_lab_converged()
_LOGGER.debug(f"{node._id} node removed from lab {self._id}")
@locked
def _remove_node_local(self, node: Node) -> None:
"""Helper function to remove a node from the client library."""
for iface in tuple(self._interfaces.values()):
if iface._node is node:
self._remove_interface_local(iface)
try:
del self._nodes[node._id]
node._stale = True
except KeyError:
# element may already have been deleted on server,
# and removed locally due to auto-sync
pass
@locked
def remove_nodes(self, wait: bool | None = None) -> None:
"""
Remove all nodes from the lab.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
"""
# Use case - user was assigned one lab, wants to reset work;
# can't delete lab, so removing all nodes is the only option
for node in list(self._nodes.values()):
self.remove_node(node, wait=False)
if self.need_to_wait(wait):
self.wait_until_lab_converged()
_LOGGER.debug(f"all nodes removed from lab {self._id}")
@check_stale
@locked
def remove_link(self, link: Link | str, wait: bool | None = None) -> None:
"""
Remove a link from the lab.
If you have a link object, you can also simply do::
link.remove()
:param link: The link object or ID.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
"""
if isinstance(link, str):
link = self.get_link_by_id(link)
link._remove_on_server()
self._remove_link_local(link)
if self.need_to_wait(wait):
self.wait_until_lab_converged()
_LOGGER.debug(f"link {link._id} removed from lab {self._id}")
@locked
def _remove_link_local(self, link: Link) -> None:
"""Helper function to remove a link from the client library."""
try:
del self._links[link._id]
link._stale = True
except KeyError:
# element may already have been deleted on server,
# and removed locally due to auto-sync
pass
@check_stale
@locked
def remove_interface(
self, iface: Interface | str, wait: bool | None = None
) -> None:
"""
Remove an interface from the lab.
If you have an interface object, you can also simply do::
interface.remove()
:param iface: The interface object or ID.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
"""
if isinstance(iface, str):
iface = self.get_interface_by_id(iface)
iface._remove_on_server()
self._remove_interface_local(iface)
if self.need_to_wait(wait):
self.wait_until_lab_converged()
_LOGGER.debug(f"interface {iface._id} removed from lab {self._id}")
@locked
def _remove_interface_local(self, iface: Interface) -> None:
"""Helper function to remove an interface from the client library."""
for link in tuple(self._links.values()):
if iface in link.interfaces:
self._remove_link_local(link)
break
try:
del self._interfaces[iface._id]
iface._stale = True
except KeyError:
# element may already have been deleted on server, and removed
# locally due to auto-sync
pass
@check_stale
@locked
def remove_annotation(
self,
annotation: Annotation | str,
) -> None:
"""
Remove an annotation from the lab.
If you have an annotation object, you can also simply do::
annotation.remove()
:param annotation: The annotation object or ID.
"""
if isinstance(annotation, str):
annotation = self.get_annotation_by_id(annotation)
annotation._remove_on_server()
self._remove_annotation_local(annotation)
_LOGGER.debug("%s annotation removed from lab %s", annotation._id, self._id)
@locked
def _remove_annotation_local(self, annotation: Annotation) -> None:
"""Helper function to remove an annotation from the client library."""
try:
del self._annotations[annotation._id]
annotation._stale = True
except KeyError:
# element may already have been deleted on server,
# and removed locally due to auto-sync
pass
@locked
def remove_annotations(self) -> None:
"""Remove all annotations from the lab."""
for ann in list(self._annotations.values()):
self.remove_annotation(ann)
_LOGGER.debug("all nodes removed from lab %s", self._id)
@check_stale
@locked
def create_link(
self, i1: Interface | str, i2: Interface | str, wait: bool | None = None
) -> Link:
"""
Create a link between two interfaces.
:param i1: The first interface object or ID.
:param i2: The second interface object or ID.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
:returns: The created link.
"""
if isinstance(i1, str):
i1 = self.get_interface_by_id(i1)
if isinstance(i2, str):
i2 = self.get_interface_by_id(i2)
url = self._url_for("links")
data = {
"src_int": i1.id,
"dst_int": i2.id,
}
response = self._session.post(url, json=data)
result = response.json()
link_id = result["id"]
label = result.get("label")
if self.need_to_wait(wait):
self.wait_until_lab_converged()
link = self._create_link_local(i1, i2, link_id, label)
return link
@check_stale
@locked
def _create_link_local(
self, i1: Interface, i2: Interface, link_id: str, label: str | None = None
) -> Link:
"""Helper function to create a link in the client library."""
link = Link(self, link_id, i1, i2, label)
self._links[link_id] = link
return link
@check_stale
@locked
def connect_two_nodes(self, node1: Node, node2: Node) -> Link:
"""
Connect two nodes within a lab.
:param node1: The first node object.
:param node2: The second node object.
:returns: The created link.
"""
iface1 = node1.next_available_interface() or node1.create_interface()
iface2 = node2.next_available_interface() or node2.create_interface()
return self.create_link(iface1, iface2)
@check_stale
@locked
def create_interface(
self, node: Node | str, slot: int | None = None, wait: bool | None = None
) -> Interface:
"""
Create an interface in the next available slot, or, if a slot is specified,
in all available slots up to and including the specified slot.
:param node: The node on which the interface is created.
:param slot: The slot number to create the interface in.
:param wait: A flag indicating whether to wait for convergence.
If left at the default value, the lab's wait property is used instead.
:returns: The newly created interface.
"""
if isinstance(node, str):
node = self.get_node_by_id(node)
url = self._url_for("interfaces")
payload: dict[str, str | int] = {"node": node.id}
if slot is not None:
payload["slot"] = slot
result = self._session.post(url, json=payload).json()
if isinstance(result, dict):
# in case API returned just one interface, pack it into a list:
result = [result]
if self.need_to_wait(wait):
self.wait_until_lab_converged()
desired_interface: Interface | None = None
for iface in result:
lab_interface = self._create_interface_local(
iface_id=iface["id"],
label=iface["label"],
node=node,
slot=iface["slot"],
)
if slot == iface["slot"] or slot is None:
desired_interface = lab_interface
if desired_interface is None:
# Shouldn't happen, but type checkers complain about desired_interface
# possibly being None otherwise
raise InterfaceNotFound
return desired_interface
@check_stale
@locked
def _create_interface_local(
self,
iface_id: str,
label: str,
node: Node,
slot: int | None,
iface_type: str = "physical",
) -> Interface:
"""Helper function to create an interface in the client library."""
if iface_id not in self._interfaces:
iface = Interface(iface_id, node, label, slot, iface_type)
self._interfaces[iface_id] = iface
else: # update the interface if it already exists:
iface = self._interfaces[iface_id]
iface._node = node
iface._label = label
iface._slot = slot
iface._type = iface_type
return iface
@check_stale
@locked
def create_annotation(self, annotation_type: str, **kwargs) -> AnnotationType:
"""
Create a lab annotation.
:param type: Type of the annotation (rectangle, ellipse, line or text).
:returns: The created annotation.
"""
url = self._url_for("annotations")
# create POST json with default annotation property values
# override some values by new, expected ones
annotation_data = Annotation.get_default_property_values(annotation_type)
for ppty, value in kwargs.items():
annotation_data[ppty] = value
annotation_data["type"] = annotation_type
response = self._session.post(url, json=annotation_data)
res_annotation = response.json()
# after adding an annotation to an empty lab, consider it "initialized"
if not self._initialized:
self._initialized = True
annotation = self._create_annotation_local(
res_annotation["id"],
annotation_type,
**res_annotation,
)
return annotation
@check_stale
@locked
def _create_annotation_local(
self, annotation_id: str, _type: str, **kwargs
) -> AnnotationType:
"""Helper function to create a link in the client library."""
if _type == "rectangle":
annotation_class = AnnotationRectangle
elif _type == "ellipse":
annotation_class = AnnotationEllipse
elif _type == "line":
annotation_class = AnnotationLine
elif _type == "text":
annotation_class = AnnotationText
else:
raise InvalidAnnotationType
annotation = annotation_class(self, annotation_id, annotation_data=kwargs)