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