Passed
Pull Request — master (#198)
by Vinicius
03:52
created

ELineController.bootstrap_indexes()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
"""ELineController."""
2
# pylint: disable=unnecessary-lambda,invalid-name
3 1
import os
4 1
from datetime import datetime
5 1
from typing import Dict, Optional
6
7 1
import pymongo
8 1
from pymongo.collection import ReturnDocument
9 1
from pymongo.errors import AutoReconnect
10 1
from tenacity import retry_if_exception_type, stop_after_attempt, wait_random
11
12 1
from kytos.core import log
13 1
from kytos.core.db import Mongo
14 1
from kytos.core.retry import before_sleep, for_all_methods, retries
15 1
from napps.kytos.mef_eline.db.models import EVCBaseDoc
16
17
18 1
@for_all_methods(
19
    retries,
20
    stop=stop_after_attempt(
21
        int(os.environ.get("MONGO_AUTO_RETRY_STOP_AFTER_ATTEMPT", "3"))
22
    ),
23
    wait=wait_random(
24
        min=int(os.environ.get("MONGO_AUTO_RETRY_WAIT_RANDOM_MIN", "1")),
25
        max=int(os.environ.get("MONGO_AUTO_RETRY_WAIT_RANDOM_MAX", "1")),
26
    ),
27
    before_sleep=before_sleep,
28
    retry=retry_if_exception_type((AutoReconnect,)),
29
)
30 1
class ELineController:
31
    """E-Line Controller"""
32
33 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...
34 1
        self.mongo = get_mongo()
35 1
        self.db_client = self.mongo.client
36 1
        self.db = self.db_client[self.mongo.db_name]
37
38 1
    def bootstrap_indexes(self) -> None:
39
        """Bootstrap mef_eline relaeted indexes."""
40 1
        index_tuples = [
41
            ("evcs", [("circuit_scheduler.id", pymongo.ASCENDING)]),
42
        ]
43 1
        for collection, keys in index_tuples:
44 1
            if self.mongo.bootstrap_index(collection, keys):
45 1
                log.info(
46
                    f"Created DB index {keys}, collection: {collection}"
47
                )
48
49 1
    def get_circuits(self) -> Dict:
50
        """Get all circuits from database."""
51 1
        circuits = self.db.evcs.aggregate(
52
            [
53
                {"$sort": {"_id": 1}},
54
                {"$project": EVCBaseDoc.projection()},
55
            ]
56
        )
57 1
        return {"circuits": {value["id"]: value for value in circuits}}
58
59 1
    def get_circuit(self, circuit_id: str) -> Optional[Dict]:
60
        """Get a circuit."""
61
        return self.db.evcs.find_one({"_id": circuit_id},
62
                                     EVCBaseDoc.projection())
63
64 1
    def upsert_evc(self, evc: Dict) -> Optional[Dict]:
65
        """Update or insert an EVC"""
66 1
        utc_now = datetime.utcnow()
67 1
        model = EVCBaseDoc(
68
            **{
69
                **evc,
70
                **{"_id": evc["id"], "updated_at": utc_now}
71
            }
72
        )
73 1
        updated = self.db.evcs.find_one_and_update(
74
            {"_id": evc["id"]},
75
            {
76
                "$set": model.dict(exclude={"inserted_at"}, exclude_none=True),
77
                "$setOnInsert": {"inserted_at": utc_now},
78
            },
79
            return_document=ReturnDocument.AFTER,
80
            upsert=True,
81
        )
82
        return updated
83