Passed
Pull Request — master (#202)
by Vinicius
07:54
created

kytos.core.db.Mongo.bootstrap_index()   A

Complexity

Conditions 5

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.675

Importance

Changes 0
Metric Value
cc 5
eloc 15
nop 5
dl 0
loc 20
ccs 7
cts 10
cp 0.7
crap 5.675
rs 9.1832
c 0
b 0
f 0
1
"""DB client."""
2
# pylint: disable=invalid-name,redefined-outer-name,too-many-arguments
3
# pylint: disable=unsubscriptable-object,inconsistent-return-statements
4
5 2
import logging
6 2
import os
7 2
import sys
8 2
import time
9 2
from typing import Optional
10
11 2
import pymongo.helpers
12 2
from pymongo import MongoClient
13 2
from pymongo.errors import AutoReconnect, OperationFailure
14
15 2
from kytos.core.exceptions import KytosDBInitException
16
17 2
LOG = logging.getLogger(__name__)
18
19
20 2
def _log_pymongo_thread_traceback() -> None:
21
    """Log pymongo thread traceback.
22
23
    Originally, it printed out to sys.stderr poluting it when handling
24
    certain asynchronous errors that can happen, with this patched function
25
    it logs to LOG.error instead.
26
    """
27 2
    if sys.stderr:
28 2
        einfo = sys.exc_info()
29 2
        try:
30 2
            LOG.error(einfo)
31
        except IOError:
32
            pass
33
        finally:
34 2
            del einfo
35
36
37 2
if hasattr(pymongo.helpers, "_handle_exception"):
38 2
    pymongo.helpers._handle_exception = _log_pymongo_thread_traceback
39
40
41 2
def mongo_client(
42
    host_seeds=os.environ.get(
43
        "MONGO_HOST_SEEDS", "mongo1:27017,mongo2:27018,mongo3:27019"
44
    ),
45
    username=os.environ.get("MONGO_USERNAME") or "invalid_user",
46
    password=os.environ.get("MONGO_PASSWORD") or "invalid_password",
47
    database=os.environ.get("MONGO_DBNAME") or "napps",
48
    connect=False,
49
    retrywrites=True,
50
    retryreads=True,
51
    readpreference="primaryPreferred",
52
    readconcernlevel="majority",
53
    maxpoolsize=int(os.environ.get("MONGO_MAX_POOLSIZE") or 300),
54
    minpoolsize=int(os.environ.get("MONGO_MIN_POOLSIZE") or 30),
55
    serverselectiontimeoutms=30000,
56
    **kwargs,
57
) -> MongoClient:
58
    """Instantiate a MongoClient instance.
59
60
    MongoClient is thread-safe and has connection-pooling built in. NApps are
61
    supposed to use the Mongo class that wraps a MongoClient. NApps might
62
    use a new MongoClient instance for exceptional cases where a NApp
63
    needs to parametrize differently.
64
    """
65 2
    return MongoClient(
66
        host_seeds.split(","),
67
        username=username,
68
        password=password,
69
        connect=connect,
70
        authsource=database,
71
        retrywrites=retrywrites,
72
        retryreads=retryreads,
73
        readpreference=readpreference,
74
        maxpoolsize=maxpoolsize,
75
        minpoolsize=minpoolsize,
76
        readconcernlevel=readconcernlevel,
77
        serverselectiontimeoutms=serverselectiontimeoutms,
78
        **kwargs,
79
    )
80
81
82 2
class Mongo:
83
    """MongoClient instance for NApps."""
84
85 2
    client = mongo_client(connect=False)
86 2
    db_name = os.environ.get("MONGO_DBNAME") or "napps"
87
88 2
    @classmethod
89 2
    def bootstrap_index(
90
        cls,
91
        collection: str,
92
        index: str,
93
        direction: int,
94
        **kwargs,
95
    ) -> Optional[str]:
96
        """Bootstrap index."""
97 2
        db = cls.client[cls.db_name]
98 2
        indexes = set()
99
100 2
        for value in db[collection].index_information().values():
101
            if "key" in value and isinstance(value["key"], list):
102
                indexes.add(value["key"][0])
103
104 2
        if (index, direction) not in indexes:
105 2
            return db[collection].create_index([(index, direction)], **kwargs)
106
107
        return None
108
109
110 2
def _mongo_conn_wait(mongo_client=mongo_client, retries=10,
111
                     timeout_ms=10000) -> None:
112
    """Try to run 'hello' command on MongoDB and wait for it with retries."""
113 2
    try:
114 2
        client = mongo_client(maxpoolsize=6, minpoolsize=3)
115 2
        LOG.info("Trying to run 'hello' command on MongoDB...")
116 2
        client.db.command("hello")
117 2
        LOG.info("Ran 'hello' command on MongoDB successfully. It's ready!")
118 2
    except (OperationFailure, AutoReconnect) as exc:
119 2
        retries -= 1
120 2
        if retries > 0:
121 2
            time.sleep(max(timeout_ms / 1000, 1))
122 2
            return _mongo_conn_wait(mongo_client, retries, timeout_ms)
123 2
        LOG.error("Maximum retries reached when waiting for MongoDB")
124 2
        raise KytosDBInitException(str(exc), exc)
125
126
127 2
def db_conn_wait(db_backend="mongodb", retries=12, timeout_ms=10000) -> None:
128
    """DB conn wait."""
129 2
    try:
130 2
        LOG.info("Starting DB connection")
131 2
        conn_wait_funcs = {"mongodb": _mongo_conn_wait}
132 2
        return conn_wait_funcs[db_backend](retries=retries,
133
                                           timeout_ms=timeout_ms)
134 2
    except KeyError:
135 2
        client_names = ",".join(list(conn_wait_funcs.keys()))
0 ignored issues
show
introduced by
The variable conn_wait_funcs does not seem to be defined for all execution paths.
Loading history...
136 2
        raise KytosDBInitException(
137
            f"DB backend '{db_backend}' isn't supported."
138
            f" Current supported databases: {client_names}"
139
        )
140