000_retire_metadata.unset_interface_metadata()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nop 2
dl 0
loc 13
rs 9.95
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
from functools import partial
5
import sys
6
import os
7
8
from kytos.core.db import Mongo
9
from pymongo.collection import Collection
10
11
def unset_collection_metadata(type: str, collection: Collection, metadata_fields: list[str]) -> None:
12
    """Unset switch or link metadata"""
13
    print(
14
        f"Trying to $unset {type} metadata[{'|'.join(metadata_fields)}]..."
15
    )
16
    db = mongo.client[mongo.db_name]
0 ignored issues
show
introduced by
The variable mongo does not seem to be defined in case __name__ == "__main__" on line 44 is False. Are you sure this can never be the case?
Loading history...
17
    res = collection.update_many(
18
        {},
19
        {
20
            "$unset": {
21
                f"metadata.{field}": 1
22
                for field in metadata_fields
23
            }
24
        },
25
    )
26
    print(f"Modified {res.modified_count} {type} objects")
27
28
def unset_interface_metadata(switches: Collection, metadata_fields: list[str]) -> None:
29
    """Unset interface metadata"""
30
    print(f"Trying to $unset interface metadata[{'|'.join(metadata_fields)}]...")
31
    res = switches.update_many(
32
        {},
33
        {
34
            "$unset": {
35
                f"interfaces.$[].metadata.{field}": 1
36
                for field in metadata_fields
37
            }
38
        },
39
    )
40
    print(f"Modified {res.modified_count} switches objects")
41
42
43
44
if __name__ == "__main__":
45
    mongo = Mongo()
46
    db = mongo.client[mongo.db_name]
47
    cmds = {
48
        "retire_link_metadata": partial(
49
            unset_collection_metadata,
50
            "link",
51
            db["links"]
52
        ),
53
        "retire_switch_metadata": partial(
54
            unset_collection_metadata,
55
            "switch",
56
            db["switches"]
57
        ),
58
        "retire_interface_metadata": partial(
59
            unset_interface_metadata,
60
            db["switches"]
61
        ),
62
    }
63
    try:
64
        cmd = os.environ["CMD"]
65
        command = cmds[cmd]
66
    except KeyError:
67
        print(
68
            f"Please set the 'CMD' env var. \nIt has to be one of these: {list(cmds.keys())}"
69
        )
70
        sys.exit(1)
71
    try:
72
        retire_metadata = os.environ["RETIRE_METADATA"].split(":")
73
    except KeyError:
74
        print(
75
            "Please set the 'RETIRE_METADATA' env var. \n"
76
            "It should be a ':' separated list of metadata variables to retire."
77
        )
78
        sys.exit(1)
79
        
80
    command(retire_metadata)
81
    
82