Passed
Pull Request — master (#178)
by
unknown
03:16
created

special_vlan_allocation   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 107
Duplicated Lines 13.08 %

Importance

Changes 0
Metric Value
eloc 80
dl 14
loc 107
rs 10
c 0
b 0
f 0
wmc 17

2 Functions

Rating   Name   Duplication   Size   Complexity  
A aggregate_outdated_interfaces() 0 24 5
D update_database() 0 58 12

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import datetime
2
import sys
3
import os
4
from collections import defaultdict
5
from kytos.core.db import Mongo
6
7
8
def aggregate_outdated_interfaces(mongo: Mongo):
9
    """Aggregate outdated interfaces details"""
10
    db = mongo.client[mongo.db_name]
11
    outdated_intfs = set()
12
    result = db.interface_details.aggregate(
13
        [
14
            {"$project": {
15
                "_id": 0,
16
                "id": 1,
17
                "special_available_tags": 1,
18
            }}
19
        ]
20
    )
21
    for document in result:
22
        if not "special_available_tags" in document:
23
            outdated_intfs.add(document["id"])
24
    
25
    if outdated_intfs:
26
        print(f"There are {len(outdated_intfs)} outdated interface documents"
27
              " which do not have 'special_available_tags' field:")
28
        for intf_id in outdated_intfs:
29
            print(intf_id)
30
    else:
31
        print("All interfaces are updated.")
32
33
def update_database(mongo: Mongo):
34
    db = mongo.client[mongo.db_name]
35
    intfs_documents = db.interface_details.find()
36
    evc_documents = db.evcs.find({"archived": False})
37
38
    tag_by_intf = defaultdict(set)
39
    evc_intf = defaultdict(str)
40
41
    for evc in evc_documents:
42
        tag_a = evc["uni_a"].get("tag")
43
        if tag_a and isinstance(tag_a["value"], str):
44
            intf_id = evc["uni_a"]["interface_id"]
45
            if tag_a["value"] in tag_by_intf[intf_id]:
46
                print(f"Error: Detected duplicated vlan '{tag_a['value']}' TAG"
47
                      f" in EVCs {evc['id']} and {evc_intf[intf_id+tag_a['value']]}"
48
                      f" in interface {intf_id}")
49
                sys.exit(1)
50
            tag_by_intf[intf_id].add(tag_a["value"])
51
            evc_intf[intf_id+tag_a["value"]] = evc["id"]
52
        tag_z = evc["uni_z"].get("tag")
53
54
        if tag_z and isinstance(tag_z["value"], str):
55
            intf_id = evc["uni_z"]["interface_id"]
56
            if tag_z["value"] in tag_by_intf[intf_id]:
57
                print(f"Error: Detected duplicated vlan '{tag_z['value']}' TAG"
58
                      f" in EVCs {evc['id']} and {evc_intf[intf_id+tag_z['value']]}"
59
                      f" in interface {intf_id}")
60
                sys.exit(1)
61
            tag_by_intf[intf_id].add(tag_z["value"])
62
            evc_intf[intf_id+tag_z["value"]] = evc["id"]
63
64
    default_special_vlans = {"untagged", "any"}
65
    intf_count = 0
66
    message_intfs = ""
67
    for intf in intfs_documents:
68
        _id = intf["id"]
69
        current_field = intf.get("special_available_tags", None)
70
        if current_field:
71
            current_field = set(current_field["vlan"])
72
        expected_field = default_special_vlans - tag_by_intf.get(_id, set())
73
        if current_field == expected_field:
74
            continue
75
        db.interface_details.update_one(
76
            {"id": _id},
77
            {
78
                "$set":
79
                {
80
                    "special_available_tags": {"vlan": list(expected_field)}
81
                }
82
            }
83
        )
84
        message_intfs += f"{_id}\n"
85
        intf_count += 1
86
    if intf_count:
87
        print(f"{intf_count} interface was/were updated:")
88
        print(message_intfs)
89
    else:
90
        print("All interfaces are updated already.")
91
92
93 View Code Duplication
if __name__ == "__main__":
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
94
    mongo = Mongo()
95
    cmds = {
96
        "aggregate_outdated_interfaces": aggregate_outdated_interfaces,
97
        "update_database": update_database,
98
    }
99
    try:
100
        cmd = os.environ["CMD"]
101
        cmds[cmd](mongo)
102
    except KeyError:
103
        print(
104
            f"Please set the 'CMD' env var. \nIt has to be one of these: {list(cmds.keys())}"
105
        )
106
        sys.exit(1)
107