Skip to content

Commit b59a362

Browse files
authored
Merge pull request #70 from FragmentedPacket/50-get-or-create
Add add_or_update to DiffSync class.
2 parents 203d254 + 647d971 commit b59a362

File tree

14 files changed

+700
-108
lines changed

14 files changed

+700
-108
lines changed

diffsync/__init__.py

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ def add_child(self, child: "DiffSyncModel"):
329329
attr_name = self._children[child_type]
330330
childs = getattr(self, attr_name)
331331
if child.get_unique_id() in childs:
332-
raise ObjectAlreadyExists(f"Already storing a {child_type} with unique_id {child.get_unique_id()}")
332+
raise ObjectAlreadyExists(f"Already storing a {child_type} with unique_id {child.get_unique_id()}", child)
333333
childs.append(child.get_unique_id())
334334

335335
def remove_child(self, child: "DiffSyncModel"):
@@ -648,13 +648,17 @@ def add(self, obj: DiffSyncModel):
648648
obj (DiffSyncModel): Object to store
649649
650650
Raises:
651-
ObjectAlreadyExists: if an object with the same uid is already present
651+
ObjectAlreadyExists: if a different object with the same uid is already present.
652652
"""
653653
modelname = obj.get_type()
654654
uid = obj.get_unique_id()
655655

656-
if uid in self._data[modelname]:
657-
raise ObjectAlreadyExists(f"Object {uid} already present")
656+
existing_obj = self._data[modelname].get(uid)
657+
if existing_obj:
658+
if existing_obj is not obj:
659+
raise ObjectAlreadyExists(f"Object {uid} already present", obj)
660+
# Return so we don't have to change anything on the existing object and underlying data
661+
return
658662

659663
if not obj.diffsync:
660664
obj.diffsync = self
@@ -692,6 +696,59 @@ def remove(self, obj: DiffSyncModel, remove_children: bool = False):
692696
# Since this is "cleanup" code, log an error and continue, instead of letting the exception raise
693697
self._log.error(f"Unable to remove child {child_id} of {modelname} {uid} - not found!")
694698

699+
def get_or_instantiate(
700+
self, model: Type[DiffSyncModel], ids: Dict, attrs: Dict = None
701+
) -> Tuple[DiffSyncModel, bool]:
702+
"""Attempt to get the object with provided identifiers or instantiate it with provided identifiers and attrs.
703+
704+
Args:
705+
model (DiffSyncModel): The DiffSyncModel to get or create.
706+
ids (Mapping): Identifiers for the DiffSyncModel to get or create with.
707+
attrs (Mapping, optional): Attributes when creating an object if it doesn't exist. Defaults to None.
708+
709+
Returns:
710+
Tuple[DiffSyncModel, bool]: Provides the existing or new object and whether it was created or not.
711+
"""
712+
created = False
713+
try:
714+
obj = self.get(model, ids)
715+
except ObjectNotFound:
716+
if not attrs:
717+
attrs = {}
718+
obj = model(**ids, **attrs)
719+
# Add the object to diffsync adapter
720+
self.add(obj)
721+
created = True
722+
723+
return obj, created
724+
725+
def update_or_instantiate(self, model: Type[DiffSyncModel], ids: Dict, attrs: Dict) -> Tuple[DiffSyncModel, bool]:
726+
"""Attempt to update an existing object with provided ids/attrs or instantiate it with provided identifiers and attrs.
727+
728+
Args:
729+
model (DiffSyncModel): The DiffSyncModel to get or create.
730+
ids (Dict): Identifiers for the DiffSyncModel to get or create with.
731+
attrs (Dict): Attributes when creating/updating an object if it doesn't exist. Pass in empty dict, if no specific attrs.
732+
733+
Returns:
734+
Tuple[DiffSyncModel, bool]: Provides the existing or new object and whether it was created or not.
735+
"""
736+
created = False
737+
try:
738+
obj = self.get(model, ids)
739+
except ObjectNotFound:
740+
obj = model(**ids, **attrs)
741+
# Add the object to diffsync adapter
742+
self.add(obj)
743+
created = True
744+
745+
# Update existing obj with attrs
746+
for attr, value in attrs.items():
747+
if getattr(obj, attr) != value:
748+
setattr(obj, attr, value)
749+
750+
return obj, created
751+
695752

696753
# DiffSyncModel references DiffSync and DiffSync references DiffSyncModel. Break the typing loop:
697754
DiffSyncModel.update_forward_refs()

diffsync/diff.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def add(self, element: "DiffElement"):
5555
"""
5656
# Note that element.name is usually a DiffSyncModel.shortname() -- i.e., NOT guaranteed globally unique!!
5757
if element.name in self.children[element.type]:
58-
raise ObjectAlreadyExists(f"Already storing a {element.type} named {element.name}")
58+
raise ObjectAlreadyExists(f"Already storing a {element.type} named {element.name}", element)
5959

6060
self.children[element.type][element.name] = element
6161

diffsync/exceptions.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ class ObjectStoreException(Exception):
3939
class ObjectAlreadyExists(ObjectStoreException):
4040
"""Exception raised when trying to store a DiffSyncModel or DiffElement that is already being stored."""
4141

42+
def __init__(self, message, existing_object, *args, **kwargs):
43+
"""Add existing_object to the exception to provide user with existing object."""
44+
self.existing_object = existing_object
45+
super().__init__(message, existing_object, *args, **kwargs)
46+
4247

4348
class ObjectNotFound(ObjectStoreException):
4449
"""Exception raised when trying to access a DiffSyncModel that isn't in storage."""

diffsync/helpers.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ def calculate_diffs(self) -> Diff:
8585

8686
for obj_type in intersection(self.dst_diffsync.top_level, self.src_diffsync.top_level):
8787
diff_elements = self.diff_object_list(
88-
src=self.src_diffsync.get_all(obj_type), dst=self.dst_diffsync.get_all(obj_type),
88+
src=self.src_diffsync.get_all(obj_type),
89+
dst=self.dst_diffsync.get_all(obj_type),
8990
)
9091

9192
for diff_element in diff_elements:
@@ -220,7 +221,10 @@ def diff_object_pair(
220221
return diff_element
221222

222223
def diff_child_objects(
223-
self, diff_element: DiffElement, src_obj: Optional["DiffSyncModel"], dst_obj: Optional["DiffSyncModel"],
224+
self,
225+
diff_element: DiffElement,
226+
src_obj: Optional["DiffSyncModel"],
227+
dst_obj: Optional["DiffSyncModel"],
224228
):
225229
"""For all children of the given DiffSyncModel pair, diff recursively, adding diffs to the given diff_element.
226230

docs/source/examples/index.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ For each example, the complete source code is `available in Github <https://gith
66

77
.. mdinclude:: ../../../examples/01-multiple-data-sources/README.md
88
.. mdinclude:: ../../../examples/02-callback-function/README.md
9-
.. mdinclude:: ../../../examples/03-remote-system/README.md
9+
.. mdinclude:: ../../../examples/03-remote-system/README.md
10+
.. mdinclude:: ../../../examples/04-get-update-instantiate/README.md
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Example 4 - Using get or update helpers
2+
3+
This example aims to expand on [Example 1](https://github.com/networktocode/diffsync/tree/main/examples/01-multiple-data-sources/README.md) that will take advantage of two new helper methods on the `DiffSync` class; `get_or_instantiate` and `update_or_instantiate`.
4+
5+
Both methods act similar to Django's `get_or_create` function to return the object and then a boolean to identify whether the object was created or not. Let's dive into each of them.
6+
7+
## get_or_instantiate
8+
9+
The following arguments are supported: model (`DiffSyncModel`), ids (dictionary), and attrs (dictionary). The `model` and `ids` are used to find an existing object. If the object does not currently exist within the `DiffSync` adapter, it will then use `model`, `ids`, and `attrs` to add the object.
10+
11+
It will then return a tuple that can be unpacked.
12+
13+
```python
14+
obj, created = self.get_or_instantiate(Interface, {"device_name": "test100", "name": "eth0"}, {"description": "Test description"})
15+
```
16+
17+
If the object already exists, `created` will be `False` or else it will return `True` if the object had to be created.
18+
19+
## update_or_instantiate
20+
21+
This helper is similar to `get_or_instantiate`, but it will update an existing object or add a new instance with the provided `ids` and `attrs`. The method does accept the same arguments, but requires `attrs`, whereas `get_or_instantiate` does not.
22+
23+
```python
24+
obj, created = self.update_or_instantiate(Interface, {"device_name": "test100", "name": "eth0"}, {"description": "Test description"})
25+
```
26+
27+
## Example Walkthrough
28+
29+
We can take a look at the data we will be loading into each backend to understand why these helper methods are valuable.
30+
31+
### Example Data
32+
33+
```python
34+
BACKEND_DATA_A = [
35+
{
36+
"name": "nyc-spine1",
37+
"role": "spine",
38+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
39+
"site": "nyc",
40+
},
41+
{
42+
"name": "nyc-spine2",
43+
"role": "spine",
44+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
45+
"site": "nyc",
46+
},
47+
]
48+
```
49+
50+
## Example Load
51+
52+
```python
53+
def load(self):
54+
"""Initialize the BackendA Object by loading some site, device and interfaces from DATA."""
55+
for device_data in BACKEND_DATA_A:
56+
device, instantiated = self.get_or_instantiate(
57+
self.device, {"name": device_data["name"]}, {"role": device_data["role"]}
58+
)
59+
60+
site, instantiated = self.get_or_instantiate(self.site, {"name": device_data["site"]})
61+
if instantiated:
62+
device.add_child(site)
63+
64+
for intf_name, desc in device_data["interfaces"].items():
65+
intf, instantiated = self.update_or_instantiate(
66+
self.interface, {"name": intf_name, "device_name": device_data["name"]}, {"description": desc}
67+
)
68+
if instantiated:
69+
device.add_child(intf)
70+
```
71+
72+
The new methods are helpful due to having devices that are part of the same site. As we iterate over the data and load it into the `DiffSync` adapter, we would have to account for `ObjectAlreadyExists` exceptions when we go to add each duplicate site we encounter within the data or possibly several other models depending how complex the synchronization of data is between backends.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
"""Example of a DiffSync adapter implementation using new helper methods.
2+
3+
Copyright (c) 2021 Network To Code, LLC <info@networktocode.com>
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
"""
17+
18+
from models import Site, Device, Interface
19+
from diffsync import DiffSync
20+
21+
BACKEND_DATA_A = [
22+
{
23+
"name": "nyc-spine1",
24+
"role": "spine",
25+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
26+
"site": "nyc",
27+
},
28+
{
29+
"name": "nyc-spine2",
30+
"role": "spine",
31+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
32+
"site": "nyc",
33+
},
34+
{
35+
"name": "sfo-spine1",
36+
"role": "spine",
37+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
38+
"site": "sfo",
39+
},
40+
{
41+
"name": "sfo-spine2",
42+
"role": "spine",
43+
"interfaces": {"eth0": "TBD", "eth1": "ddd", "eth2": "Interface 2"},
44+
"site": "sfo",
45+
},
46+
]
47+
BACKEND_DATA_B = [
48+
{
49+
"name": "atl-spine1",
50+
"role": "spine",
51+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
52+
"site": "atl",
53+
},
54+
{
55+
"name": "atl-spine2",
56+
"role": "spine",
57+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
58+
"site": "atl",
59+
},
60+
{
61+
"name": "nyc-spine1",
62+
"role": "spine",
63+
"interfaces": {"eth0": "Interface 0/0", "eth1": "Interface 1"},
64+
"site": "nyc",
65+
},
66+
{
67+
"name": "nyc-spine2",
68+
"role": "spine",
69+
"interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"},
70+
"site": "nyc",
71+
},
72+
{"name": "sfo-spine1", "role": "leaf", "interfaces": {"eth0": "Interface 0", "eth1": "Interface 1"}, "site": "sfo"},
73+
{"name": "sfo-spine2", "role": "spine", "interfaces": {"eth0": "TBD", "eth1": "ddd"}, "site": "sfo"},
74+
]
75+
76+
77+
class BackendA(DiffSync):
78+
"""Example of a DiffSync adapter implementation."""
79+
80+
site = Site
81+
device = Device
82+
interface = Interface
83+
84+
top_level = ["device"]
85+
86+
type = "Backend A"
87+
88+
def load(self):
89+
"""Initialize the BackendA Object by loading some site, device and interfaces from DATA."""
90+
for device_data in BACKEND_DATA_A:
91+
device, instantiated = self.get_or_instantiate(
92+
self.device, {"name": device_data["name"]}, {"role": device_data["role"]}
93+
)
94+
95+
site, instantiated = self.get_or_instantiate(self.site, {"name": device_data["site"]})
96+
if instantiated:
97+
device.add_child(site)
98+
99+
for intf_name, desc in device_data["interfaces"].items():
100+
intf, instantiated = self.update_or_instantiate(
101+
self.interface, {"name": intf_name, "device_name": device_data["name"]}, {"description": desc}
102+
)
103+
if instantiated:
104+
device.add_child(intf)
105+
106+
107+
class BackendB(DiffSync):
108+
"""Example of a DiffSync adapter implementation."""
109+
110+
site = Site
111+
device = Device
112+
interface = Interface
113+
114+
top_level = ["device"]
115+
116+
type = "Backend B"
117+
118+
def load(self):
119+
"""Initialize the BackendB Object by loading some site, device and interfaces from DATA."""
120+
for device_data in BACKEND_DATA_B:
121+
device, instantiated = self.get_or_instantiate(
122+
self.device, {"name": device_data["name"]}, {"role": device_data["role"]}
123+
)
124+
125+
site, instantiated = self.get_or_instantiate(self.site, {"name": device_data["site"]})
126+
if instantiated:
127+
device.add_child(site)
128+
129+
for intf_name, desc in device_data["interfaces"].items():
130+
intf, instantiated = self.get_or_instantiate(
131+
self.interface, {"name": intf_name, "device_name": device_data["name"]}, {"description": desc}
132+
)
133+
if instantiated:
134+
device.add_child(intf)

0 commit comments

Comments
 (0)