Passed
Pull Request — master (#84)
by Vinicius
03:30
created

build.controllers   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 306
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 191
dl 0
loc 306
rs 9.36
c 0
b 0
f 0
ccs 108
cts 108
cp 1
wmc 38

29 Methods

Rating   Name   Duplication   Size   Complexity  
A TopoController.enable_switch() 0 3 1
A TopoController.disable_switch() 0 4 1
A TopoController.deactivate_switch() 0 3 1
A TopoController.bootstrap_indexes() 0 10 3
A TopoController.__init__() 0 6 2
A TopoController.disable_interface() 0 4 1
A TopoController.get_topology() 0 5 1
A TopoController.get_links() 0 9 1
A TopoController.add_switch_metadata() 0 6 1
A TopoController._update_switch() 0 4 1
A TopoController.get_switches() 0 9 1
A TopoController.delete_switch_metadata_key() 0 5 1
A TopoController.activate_interface() 0 3 1
A TopoController._set_updated_at() 0 7 2
A TopoController.enable_interface() 0 4 1
A TopoController.upsert_switch() 0 16 1
A TopoController.get_interfaces() 0 11 1
A TopoController.deactivate_interface() 0 4 1
A TopoController.add_interface_metadata() 0 8 1
A TopoController.add_link_metadata() 0 8 1
A TopoController.delete_link_metadata_key() 0 5 1
A TopoController._update_interface() 0 14 2
A TopoController.enable_link() 0 3 1
A TopoController._update_link() 0 4 1
A TopoController.disable_link() 0 3 1
B TopoController.bulk_upsert_interface_details() 0 31 5
A TopoController.delete_interface_metadata_key() 0 6 1
A TopoController.upsert_link() 0 46 1
A TopoController.get_interfaces_details() 0 7 1
1
"""TopoController."""
2
3
# pylint: disable=invalid-name
4 1
from datetime import datetime
5 1
from threading import Lock
6 1
from typing import List, Optional, Tuple
7
8 1
import pymongo
9 1
from pymongo.collection import ReturnDocument
10 1
from pymongo.operations import UpdateOne
11
12 1
from kytos.core import log
13 1
from kytos.core.db import Mongo
14 1
from napps.kytos.topology.db.models import (InterfaceDetailDoc, LinkDoc,
15
                                            SwitchDoc)
16
17
18 1
class TopoController:
19
    """TopoController."""
20
21 1
    def __init__(self, get_mongo=lambda: Mongo()) -> None:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable Mongo does not seem to be defined.
Loading history...
22
        """Constructor of TopoController."""
23 1
        self.mongo = get_mongo()
24 1
        self.db_client = self.mongo.client
25 1
        self.db = self.db_client[self.mongo.db_name]
26 1
        self.interface_details_lock = Lock()
27
28 1
    def bootstrap_indexes(self) -> None:
29
        """Bootstrap all topology related indexes."""
30 1
        index_tuples = [
31
            ("switches", [("interfaces.id", pymongo.ASCENDING)]),
32
            ("links", [("endpoints.id", pymongo.ASCENDING)]),
33
        ]
34 1
        for collection, keys in index_tuples:
35 1
            if self.mongo.bootstrap_index(collection, keys):
36 1
                log.info(
37
                    f"Created DB index {keys}, "
38
                    f"collection: {collection})"
39
                )
40
41 1
    def get_topology(self) -> dict:
42
        """Get topology from DB."""
43 1
        switches = self.get_switches()
44 1
        links = self.get_links()
45 1
        return {"topology": {**links, **switches}}
46
47 1
    def get_switches(self) -> dict:
48
        """Get switches from DB."""
49 1
        switches = self.db.switches.aggregate(
50
            [
51
                {"$sort": {"_id": 1}},
52
                {"$project": SwitchDoc.projection()},
53
            ]
54
        )
55 1
        return {"switches": {value["id"]: value for value in switches}}
56
57 1
    def get_links(self) -> dict:
58
        """Get links from DB."""
59 1
        links = self.db.links.aggregate(
60
            [
61
                {"$sort": {"_id": 1}},
62
                {"$project": LinkDoc.projection()},
63
            ]
64
        )
65 1
        return {"links": {value["id"]: value for value in links}}
66
67 1
    def get_interfaces(self) -> dict:
68
        """Get interfaces from DB."""
69 1
        interfaces = self.db.switches.aggregate(
70
            [
71
                {"$sort": {"_id": 1}},
72
                {"$project": {"interfaces": 1, "_id": 0}},
73
                {"$unwind": "$interfaces"},
74
                {"$replaceRoot": {"newRoot": "$interfaces"}},
75
            ]
76
        )
77 1
        return {"interfaces": {value["id"]: value for value in interfaces}}
78
79 1
    @staticmethod
80 1
    def _set_updated_at(update_expr: dict) -> None:
81
        """Set updated_at on $set expression."""
82 1
        if "$set" in update_expr:
83 1
            update_expr["$set"].update({"updated_at": datetime.utcnow()})
84
        else:
85 1
            update_expr.update({"$set": {"updated_at": datetime.utcnow()}})
86
87 1
    def _update_switch(self, dpid: str, update_expr: dict) -> Optional[dict]:
88
        """Try to find one switch and update it given an update expression."""
89 1
        self._set_updated_at(update_expr)
90 1
        return self.db.switches.find_one_and_update({"_id": dpid}, update_expr)
91
92 1
    def upsert_switch(self, dpid: str, switch_dict: dict) -> Optional[dict]:
93
        """Update or insert switch."""
94 1
        utc_now = datetime.utcnow()
95 1
        model = SwitchDoc(
96
            **{**switch_dict, **{"_id": dpid, "updated_at": utc_now}}
97
        )
98 1
        updated = self.db.switches.find_one_and_update(
99
            {"_id": dpid},
100
            {
101
                "$set": model.dict(exclude={"inserted_at"}),
102
                "$setOnInsert": {"inserted_at": utc_now},
103
            },
104
            return_document=ReturnDocument.AFTER,
105
            upsert=True,
106
        )
107 1
        return updated
108
109 1
    def enable_switch(self, dpid: str) -> Optional[dict]:
110
        """Try to find one switch and enable it."""
111 1
        return self._update_switch(dpid, {"$set": {"enabled": True}})
112
113 1
    def deactivate_switch(self, dpid: str) -> Optional[dict]:
114
        """Try to find one switch and deactivate it."""
115 1
        return self._update_switch(dpid, {"$set": {"active": False}})
116
117 1
    def disable_switch(self, dpid: str) -> Optional[dict]:
118
        """Try to find one switch and disable it."""
119 1
        return self._update_switch(
120
            dpid, {"$set": {"enabled": False, "interfaces.$[].enabled": False}}
121
        )
122
123 1
    def add_switch_metadata(self, dpid: str, metadata: dict) -> Optional[dict]:
124
        """Try to find a switch and add to its metadata."""
125 1
        update_expr = {
126
            "$set": {f"metadata.{k}": v for k, v in metadata.items()}
127
        }
128 1
        return self._update_switch(dpid, update_expr)
129
130 1
    def delete_switch_metadata_key(
131
        self, dpid: str, key: str
132
    ) -> Optional[dict]:
133
        """Try to find a switch and delete a metadata key."""
134 1
        return self._update_switch(dpid, {"$unset": {f"metadata.{key}": ""}})
135
136 1
    def enable_interface(self, interface_id: str) -> Optional[dict]:
137
        """Try to enable one interface and its embedded object on links."""
138 1
        return self._update_interface(
139
            interface_id, {"$set": {"enabled": True}}
140
        )
141
142 1
    def disable_interface(self, interface_id: str) -> Optional[dict]:
143
        """Try to disable one interface and its embedded object on links."""
144 1
        return self._update_interface(
145
            interface_id, {"$set": {"enabled": False}}
146
        )
147
148 1
    def activate_interface(self, interface_id: str) -> Optional[dict]:
149
        """Try to activate one interface."""
150 1
        return self._update_interface(interface_id, {"$set": {"active": True}})
151
152 1
    def deactivate_interface(self, interface_id: str) -> Optional[dict]:
153
        """Try to deactivate one interface."""
154 1
        return self._update_interface(
155
            interface_id, {"$set": {"active": False}}
156
        )
157
158 1
    def add_interface_metadata(
159
        self, interface_id: str, metadata: dict
160
    ) -> Optional[dict]:
161
        """Try to find an interface and add to its metadata."""
162 1
        update_expr = {
163
            "$set": {f"metadata.{k}": v for k, v in metadata.items()}
164
        }
165 1
        return self._update_interface(interface_id, update_expr)
166
167 1
    def delete_interface_metadata_key(
168
        self, interface_id: str, key: str
169
    ) -> Optional[dict]:
170
        """Try to find an interface and delete a metadata key."""
171 1
        return self._update_interface(
172
            interface_id, {"$unset": {f"metadata.{key}": ""}}
173
        )
174
175 1
    def _update_interface(
176
        self, interface_id: str, update_expr: dict
177
    ) -> Optional[dict]:
178
        """Try to update one interface and its embedded object on links."""
179 1
        self._set_updated_at(update_expr)
180 1
        interfaces_expression = {}
181 1
        for operator, values in update_expr.items():
182 1
            interfaces_expression[operator] = {
183
                f"interfaces.$.{k}": v for k, v in values.items()
184
            }
185 1
        return self.db.switches.find_one_and_update(
186
            {"interfaces.id": interface_id},
187
            interfaces_expression,
188
            return_document=ReturnDocument.AFTER,
189
        )
190
191 1
    def upsert_link(self, link_id: str, link_dict: dict) -> dict:
192
        """Update or insert a Link."""
193 1
        utc_now = datetime.utcnow()
194
195 1
        endpoint_a = link_dict.get("endpoint_a")
196 1
        endpoint_b = link_dict.get("endpoint_b")
197 1
        model = LinkDoc(
198
            **{
199
                **link_dict,
200
                **{
201
                    "updated_at": utc_now,
202
                    "_id": link_id,
203
                    "endpoints": [endpoint_a, endpoint_b],
204
                },
205
            }
206
        )
207 1
        updated = self.db.links.find_one_and_update(
208
            {"_id": link_id},
209
            {
210
                "$set": model.dict(exclude={"inserted_at"}),
211
                "$setOnInsert": {"inserted_at": utc_now},
212
            },
213
            return_document=ReturnDocument.AFTER,
214
            upsert=True,
215
        )
216 1
        self.db.switches.find_one_and_update(
217
            {"interfaces.id": endpoint_a},
218
            {
219
                "$set": {
220
                    "interfaces.$.link_id": link_id,
221
                    "interfaces.$.link_side": "endpoint_a",
222
                    "updated_at": utc_now,
223
                }
224
            },
225
        )
226 1
        self.db.switches.find_one_and_update(
227
            {"interfaces.id": endpoint_b},
228
            {
229
                "$set": {
230
                    "interfaces.$.link_id": link_id,
231
                    "interfaces.$.link_side": "endpoint_b",
232
                    "updated_at": utc_now,
233
                }
234
            },
235
        )
236 1
        return updated
237
238 1
    def _update_link(self, link_id: str, update_expr: dict) -> Optional[dict]:
239
        """Try to find one link and update it given an update expression."""
240 1
        self._set_updated_at(update_expr)
241 1
        return self.db.links.find_one_and_update({"_id": link_id}, update_expr)
242
243 1
    def enable_link(self, link_id: str) -> Optional[dict]:
244
        """Try to find one link and enable it."""
245 1
        return self._update_link(link_id, {"$set": {"enabled": True}})
246
247 1
    def disable_link(self, link_id: str) -> Optional[dict]:
248
        """Try to find one link and disable it."""
249 1
        return self._update_link(link_id, {"$set": {"enabled": False}})
250
251 1
    def add_link_metadata(
252
        self, link_id: str, metadata: dict
253
    ) -> Optional[dict]:
254
        """Try to find link and add to its metadata."""
255 1
        update_expr = {
256
            "$set": {f"metadata.{k}": v for k, v in metadata.items()}
257
        }
258 1
        return self._update_link(link_id, update_expr)
259
260 1
    def delete_link_metadata_key(
261
        self, link_id: str, key: str
262
    ) -> Optional[dict]:
263
        """Try to find a link and delete a metadata key."""
264 1
        return self._update_link(link_id, {"$unset": {f"metadata.{key}": ""}})
265
266 1
    def bulk_upsert_interface_details(
267
        self, ids_details: List[Tuple[str, dict]]
268
    ) -> Optional[dict]:
269
        """Update or insert interfaces details."""
270 1
        utc_now = datetime.utcnow()
271 1
        ops = []
272 1
        for _id, detail_dict in ids_details:
273 1
            ops.append(
274
                UpdateOne(
275
                    {"_id": _id},
276
                    {
277
                        "$set": InterfaceDetailDoc(
278
                            **{
279
                                **detail_dict,
280
                                **{
281
                                    "updated_at": utc_now,
282
                                    "_id": _id,
283
                                },
284
                            }
285
                        ).dict(exclude={"inserted_at"}),
286
                        "$setOnInsert": {"inserted_at": utc_now},
287
                    },
288
                    upsert=True,
289
                ),
290
            )
291
292 1
        with self.interface_details_lock:
293 1
            with self.db_client.start_session() as session:
294 1
                with session.start_transaction():
295 1
                    return self.db.interface_details.bulk_write(
296
                        ops, ordered=False, session=session
297
                    )
298
299 1
    def get_interfaces_details(
300
        self, interface_ids: List[str]
301
    ) -> Optional[dict]:
302
        """Try to get interfaces details given a list of interface ids."""
303 1
        return self.db.interface_details.aggregate(
304
            [
305
                {"$match": {"_id": {"$in": interface_ids}}},
306
            ]
307
        )
308