Passed
Pull Request — master (#84)
by Vinicius
02:47
created

build.controllers   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 314
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 40
eloc 195
dl 0
loc 314
ccs 112
cts 112
cp 1
rs 9.2
c 0
b 0
f 0

31 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.add_interface_metadata() 0 8 1
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.add_link_metadata() 0 8 1
A TopoController.delete_link_metadata_key() 0 5 1
A TopoController.get_switches() 0 9 1
A TopoController.delete_switch_metadata_key() 0 5 1
A TopoController._update_interface() 0 14 2
A TopoController.activate_interface() 0 3 1
A TopoController.enable_interface_lldp() 0 3 1
A TopoController.enable_link() 0 3 1
A TopoController._update_link() 0 4 1
A TopoController.disable_link() 0 3 1
A TopoController._set_updated_at() 0 7 2
A TopoController.enable_interface() 0 4 1
B TopoController.bulk_upsert_interface_details() 0 31 5
A TopoController.delete_interface_metadata_key() 0 6 1
A TopoController.upsert_switch() 0 16 1
A TopoController.get_interfaces() 0 11 1
A TopoController.deactivate_interface() 0 4 1
A TopoController.upsert_link() 0 46 1
A TopoController.get_interfaces_details() 0 7 1
A TopoController.disable_interface_lldp() 0 3 1

How to fix   Complexity   

Complexity

Complex classes like build.controllers often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 enable_interface_lldp(self, interface_id: str) -> Optional[dict]:
159
        """Try to enable LLDP one interface."""
160 1
        return self._update_interface(interface_id, {"$set": {"lldp": True}})
161
162 1
    def disable_interface_lldp(self, interface_id: str) -> Optional[dict]:
163
        """Try to disable LLDP one interface."""
164 1
        return self._update_interface(interface_id, {"$set": {"lldp": False}})
165
166 1
    def add_interface_metadata(
167
        self, interface_id: str, metadata: dict
168
    ) -> Optional[dict]:
169
        """Try to find an interface and add to its metadata."""
170 1
        update_expr = {
171
            "$set": {f"metadata.{k}": v for k, v in metadata.items()}
172
        }
173 1
        return self._update_interface(interface_id, update_expr)
174
175 1
    def delete_interface_metadata_key(
176
        self, interface_id: str, key: str
177
    ) -> Optional[dict]:
178
        """Try to find an interface and delete a metadata key."""
179 1
        return self._update_interface(
180
            interface_id, {"$unset": {f"metadata.{key}": ""}}
181
        )
182
183 1
    def _update_interface(
184
        self, interface_id: str, update_expr: dict
185
    ) -> Optional[dict]:
186
        """Try to update one interface and its embedded object on links."""
187 1
        self._set_updated_at(update_expr)
188 1
        interfaces_expression = {}
189 1
        for operator, values in update_expr.items():
190 1
            interfaces_expression[operator] = {
191
                f"interfaces.$.{k}": v for k, v in values.items()
192
            }
193 1
        return self.db.switches.find_one_and_update(
194
            {"interfaces.id": interface_id},
195
            interfaces_expression,
196
            return_document=ReturnDocument.AFTER,
197
        )
198
199 1
    def upsert_link(self, link_id: str, link_dict: dict) -> dict:
200
        """Update or insert a Link."""
201 1
        utc_now = datetime.utcnow()
202
203 1
        endpoint_a = link_dict.get("endpoint_a")
204 1
        endpoint_b = link_dict.get("endpoint_b")
205 1
        model = LinkDoc(
206
            **{
207
                **link_dict,
208
                **{
209
                    "updated_at": utc_now,
210
                    "_id": link_id,
211
                    "endpoints": [endpoint_a, endpoint_b],
212
                },
213
            }
214
        )
215 1
        updated = self.db.links.find_one_and_update(
216
            {"_id": link_id},
217
            {
218
                "$set": model.dict(exclude={"inserted_at"}),
219
                "$setOnInsert": {"inserted_at": utc_now},
220
            },
221
            return_document=ReturnDocument.AFTER,
222
            upsert=True,
223
        )
224 1
        self.db.switches.find_one_and_update(
225
            {"interfaces.id": endpoint_a},
226
            {
227
                "$set": {
228
                    "interfaces.$.link_id": link_id,
229
                    "interfaces.$.link_side": "endpoint_a",
230
                    "updated_at": utc_now,
231
                }
232
            },
233
        )
234 1
        self.db.switches.find_one_and_update(
235
            {"interfaces.id": endpoint_b},
236
            {
237
                "$set": {
238
                    "interfaces.$.link_id": link_id,
239
                    "interfaces.$.link_side": "endpoint_b",
240
                    "updated_at": utc_now,
241
                }
242
            },
243
        )
244 1
        return updated
245
246 1
    def _update_link(self, link_id: str, update_expr: dict) -> Optional[dict]:
247
        """Try to find one link and update it given an update expression."""
248 1
        self._set_updated_at(update_expr)
249 1
        return self.db.links.find_one_and_update({"_id": link_id}, update_expr)
250
251 1
    def enable_link(self, link_id: str) -> Optional[dict]:
252
        """Try to find one link and enable it."""
253 1
        return self._update_link(link_id, {"$set": {"enabled": True}})
254
255 1
    def disable_link(self, link_id: str) -> Optional[dict]:
256
        """Try to find one link and disable it."""
257 1
        return self._update_link(link_id, {"$set": {"enabled": False}})
258
259 1
    def add_link_metadata(
260
        self, link_id: str, metadata: dict
261
    ) -> Optional[dict]:
262
        """Try to find link and add to its metadata."""
263 1
        update_expr = {
264
            "$set": {f"metadata.{k}": v for k, v in metadata.items()}
265
        }
266 1
        return self._update_link(link_id, update_expr)
267
268 1
    def delete_link_metadata_key(
269
        self, link_id: str, key: str
270
    ) -> Optional[dict]:
271
        """Try to find a link and delete a metadata key."""
272 1
        return self._update_link(link_id, {"$unset": {f"metadata.{key}": ""}})
273
274 1
    def bulk_upsert_interface_details(
275
        self, ids_details: List[Tuple[str, dict]]
276
    ) -> Optional[dict]:
277
        """Update or insert interfaces details."""
278 1
        utc_now = datetime.utcnow()
279 1
        ops = []
280 1
        for _id, detail_dict in ids_details:
281 1
            ops.append(
282
                UpdateOne(
283
                    {"_id": _id},
284
                    {
285
                        "$set": InterfaceDetailDoc(
286
                            **{
287
                                **detail_dict,
288
                                **{
289
                                    "updated_at": utc_now,
290
                                    "_id": _id,
291
                                },
292
                            }
293
                        ).dict(exclude={"inserted_at"}),
294
                        "$setOnInsert": {"inserted_at": utc_now},
295
                    },
296
                    upsert=True,
297
                ),
298
            )
299
300 1
        with self.interface_details_lock:
301 1
            with self.db_client.start_session() as session:
302 1
                with session.start_transaction():
303 1
                    return self.db.interface_details.bulk_write(
304
                        ops, ordered=False, session=session
305
                    )
306
307 1
    def get_interfaces_details(
308
        self, interface_ids: List[str]
309
    ) -> Optional[dict]:
310
        """Try to get interfaces details given a list of interface ids."""
311 1
        return self.db.interface_details.aggregate(
312
            [
313
                {"$match": {"_id": {"$in": interface_ids}}},
314
            ]
315
        )
316