Passed
Push — master ( c84716...0393df )
by Vinicius
04:03 queued 15s
created

001_redeploy_set_queue.redeploy_evc()   A

Complexity

Conditions 4

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nop 1
dl 0
loc 12
rs 9.9
c 0
b 0
f 0
1
import concurrent.futures
2
# Change to False so this script makes changes
3
DRY_RUN = True
4
# Batch size to redeploy EVCs with set_queue
5
BATCH_SIZE = 10
6
7
mef_eline = controller.napps[("kytos", "mef_eline")]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable controller does not seem to be defined.
Loading history...
8
flow_manager = controller.napps[("kytos", "flow_manager")]
9
10
11
def list_cookies_with_set_queue(flow_manager) -> set[int]:
12
    """List unique mef_eline cookies from the flows collection
13
    where the set_queue action is set (incorrectly) as the last action
14
    with output action."""
15
    return set(
16
        map(
17
            lambda doc: int(doc["flow"]["cookie"].to_decimal()),
18
            filter(
19
                lambda doc: len(doc["flow"]["actions"]) > 1
20
                and doc["flow"]["actions"][-1]["action_type"] == "set_queue"
21
                and doc["flow"]["actions"][-2]["action_type"] == "output",
22
                flow_manager.flow_controller.db.flows.find(
23
                    {
24
                        "flow.owner": "mef_eline",
25
                        "flow.actions": {"$elemMatch": {"action_type": "set_queue"}},
26
                    }
27
                ),
28
            ),
29
        )
30
    )
31
32
33
def get_id_from_cookie(cookie) -> str:
34
    """Return the evc id given a cookie value."""
35
    evc_id = cookie & 0xFFFFFFFFFFFFFF
36
    return f"{evc_id:x}".zfill(14)
37
38
39
def redeploy_evc(evc_id):
40
    """Redeploy an EVC."""
41
    import httpx
42
43
    MEF_ELINE_URL = "http://localhost:8181/api/kytos/mef_eline/v2"
44
    url = f"{MEF_ELINE_URL}/evc/{evc_id}/redeploy"
45
    try:
46
        res = httpx.request("PATCH", url, timeout=30)
47
    except httpx.TimeoutException:
48
        print(f"Timeout while enabling EVC {evc_id}")
49
    if res.is_server_error or res.status_code in {424, 404, 409, 400}:
50
        print(f"Error disabling EVC {evc_id}: {res.text}")
51
52
53
dry_run_key = "WILL" if not DRY_RUN else "WOULD"
54
55
print("Checking EVCs with action_type set_queue...")
56
evc_ids = []
57
for cookie in list_cookies_with_set_queue(flow_manager):
58
    evc_ids.append(get_id_from_cookie(cookie))
59
print(f"It {dry_run_key} redeploy {len(evc_ids)} EVCs")
60
61
if not DRY_RUN:
62
    executor = concurrent.futures.ThreadPoolExecutor(BATCH_SIZE, "script:redeploy_evc")
63
    executor.map(redeploy_evc, evc_ids)
64
    executor.shutdown()
65
66
print("Finished!")
67