• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

atlanticwave-sdx / sdx-controller / 15905001540

26 Jun 2025 02:43PM UTC coverage: 56.324% (-0.3%) from 56.629%
15905001540

push

github

web-flow
Merge pull request #471 from atlanticwave-sdx/fix/470-avoid-load-latest-topo

Avoid loading LATEST_TOPOLOGY into TEManager

1 of 1 new or added line in 1 file covered. (100.0%)

7 existing lines in 2 files now uncovered.

1189 of 2111 relevant lines covered (56.32%)

1.13 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

54.68
/sdx_controller/controllers/l2vpn_controller.py
1
import json
2✔
2
import logging
2✔
3
import os
2✔
4
import uuid
2✔
5

6
import connexion
2✔
7
from flask import current_app
2✔
8
from sdx_datamodel.connection_sm import ConnectionStateMachine
2✔
9
from sdx_datamodel.constants import MongoCollections
2✔
10

11
from sdx_controller.handlers.connection_handler import (
2✔
12
    ConnectionHandler,
13
    connection_state_machine,
14
    get_connection_status,
15
    parse_conn_status,
16
)
17
from sdx_controller.models.l2vpn_service_id_body import L2vpnServiceIdBody  # noqa: E501
2✔
18
from sdx_controller.utils.db_utils import DbUtils
2✔
19

20
LOG_FORMAT = (
2✔
21
    "%(levelname) -10s %(asctime)s %(name) -30s %(funcName) "
22
    "-35s %(lineno) -5d: %(message)s"
23
)
24
logger = logging.getLogger(__name__)
2✔
25
logging.getLogger("pika").setLevel(logging.WARNING)
2✔
26
logger.setLevel(logging.getLevelName(os.getenv("LOG_LEVEL", "DEBUG")))
2✔
27

28
# Get DB connection and tables set up.
29
db_instance = DbUtils()
2✔
30
db_instance.initialize_db()
2✔
31
connection_handler = ConnectionHandler(db_instance)
2✔
32

33

34
def delete_connection(service_id):
2✔
35
    """
36
    Delete connection order by ID.
37

38
    :param service_id: ID of the connection that needs to be
39
        deleted
40
    :type service_id: str
41

42
    :rtype: None
43
    """
44
    logger.info(
2✔
45
        f"Handling delete (service id: {service_id}) "
46
        f"with te_manager: {current_app.te_manager}"
47
    )
48

49
    # # Looking up by UUID do not seem work yet.  Will address in
50
    # # https://github.com/atlanticwave-sdx/sdx-controller/issues/252.
51
    #
52
    # value = db_instance.read_from_db(f"{service_id}")
53
    # print(f"value: {value}")
54
    # if not value:
55
    #     return "Not found", 404
56

57
    try:
2✔
58
        # TODO: pce's unreserve_vlan() method silently returns even if the
59
        # service_id is not found.  This should in fact be an error.
60
        #
61
        # https://github.com/atlanticwave-sdx/pce/issues/180
62
        connection = db_instance.get_value_from_db(
2✔
63
            MongoCollections.CONNECTIONS, f"{service_id}"
64
        )
65

66
        if not connection:
2✔
67
            return "Did not find connection", 404
2✔
68

69
        logger.info(f"connection: {connection} {type(connection)}")
2✔
70
        if connection.get("status") is None:
2✔
71
            logger.error("Missing field: status is not in connection.")
×
72
            connection["status"] = str(ConnectionStateMachine.State.DELETED)
×
73
        elif connection["status"] == str(ConnectionStateMachine.State.UP):
2✔
74
            connection, _ = connection_state_machine(
2✔
75
                connection, ConnectionStateMachine.State.DELETED
76
            )
77
        else:
UNCOV
78
            connection, _ = connection_state_machine(
×
79
                connection, ConnectionStateMachine.State.DOWN
80
            )
UNCOV
81
            connection, _ = connection_state_machine(
×
82
                connection, ConnectionStateMachine.State.DELETED
83
            )
84

85
        logger.info(f"Removing connection: {service_id} {connection.get('status')}")
2✔
86

87
        connection_handler.remove_connection(current_app.te_manager, service_id)
2✔
88
        db_instance.mark_deleted(MongoCollections.CONNECTIONS, f"{service_id}")
2✔
89
        db_instance.mark_deleted(MongoCollections.BREAKDOWNS, f"{service_id}")
2✔
90
    except Exception as e:
×
91
        logger.info(f"Delete failed (connection id: {service_id}): {e}")
×
92
        return f"Failed, reason: {e}", 500
×
93

94
    return "OK", 200
2✔
95

96

97
def get_connection_by_id(service_id):
2✔
98
    """
99
    Find connection by ID.
100

101
    :param service_id: ID of connection that needs to be fetched
102
    :type service_id: str
103

104
    :rtype: Connection
105
    """
106

107
    value = get_connection_status(db_instance, service_id)
2✔
108

109
    if not value:
2✔
110
        return "Connection not found", 404
2✔
111

112
    return value
2✔
113

114

115
def get_connections():  # noqa: E501
2✔
116
    """List all connections
117

118
    connection details # noqa: E501
119

120
    :rtype: Connection
121
    """
122
    values = db_instance.get_all_entries_in_collection(MongoCollections.CONNECTIONS)
2✔
123
    if not values:
2✔
124
        return "No connection was found", 404
2✔
125
    return_values = {}
2✔
126
    for connection in values:
2✔
127
        service_id = next(iter(connection))
2✔
128
        logger.info(f"service_id: {service_id}")
2✔
129
        connection_status = get_connection_status(db_instance, service_id)
2✔
130
        if connection_status:
2✔
131
            return_values[service_id] = connection_status.get(service_id)
2✔
132
    return return_values
2✔
133

134

135
def place_connection(body):
2✔
136
    """
137
    Place an connection request from the SDX-Controller.
138

139
    :param body: order placed for creating a connection
140
    :type body: dict | bytes
141

142
    :rtype: Connection
143
    """
144
    logger.info(f"Placing connection: {body}")
2✔
145
    if not connexion.request.is_json:
2✔
146
        return "Request body must be JSON", 400
×
147

148
    body = connexion.request.get_json()
2✔
149
    logger.info(f"Gathered connexion JSON: {body}")
2✔
150

151
    logger.info("Placing connection. Saving to database.")
2✔
152

153
    service_id = body.get("id")
2✔
154

155
    if service_id is None:
2✔
156
        service_id = str(uuid.uuid4())
2✔
157
        body["id"] = service_id
2✔
158
        logger.info(f"Request has no ID. Generated ID: {service_id}")
2✔
159

160
    body["status"] = str(ConnectionStateMachine.State.REQUESTED)
2✔
161

162
    # used in lc_message_handler to count the oxp success response
163
    body["oxp_success_count"] = 0
2✔
164

165
    conn_status = ConnectionStateMachine.State.UNDER_PROVISIONING
2✔
166
    body, _ = connection_state_machine(body, conn_status)
2✔
167

168
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
2✔
169

170
    logger.info(
2✔
171
        f"Handling request {service_id} with te_manager: {current_app.te_manager}"
172
    )
173
    reason, code = connection_handler.place_connection(current_app.te_manager, body)
2✔
174

175
    if code // 100 != 2:
2✔
176
        conn_status = ConnectionStateMachine.State.REJECTED
2✔
177
        db_instance.update_field_in_json(
2✔
178
            MongoCollections.CONNECTIONS,
179
            service_id,
180
            "status",
181
            str(conn_status),
182
        )
183
    logger.info(
2✔
184
        f"place_connection result: ID: {service_id} reason='{reason}', code={code}"
185
    )
186

187
    response = {
2✔
188
        "service_id": service_id,
189
        "status": parse_conn_status(str(conn_status)),
190
        "reason": reason,
191
    }
192

193
    # # TODO: our response is supposed to be shaped just like request
194
    # # ('#/components/schemas/connection'), and in that case the below
195
    # # code would be a quick implementation.
196
    # #
197
    # # https://github.com/atlanticwave-sdx/sdx-controller/issues/251
198
    # response = body
199

200
    # response["id"] = service_id
201
    # response["status"] = "success" if code == 2xx else "failure"
202
    # response["reason"] = reason # `reason` is not present in schema though.
203

204
    return response, code
2✔
205

206

207
def patch_connection(service_id, body=None):  # noqa: E501
2✔
208
    """Edit and change an existing L2vpn connection by ID from the SDX-Controller
209

210
     # noqa: E501
211

212
    :param service_id: ID of l2vpn connection that needs to be changed
213
    :type service_id: dict | bytes'
214
    :param body:
215
    :type body: dict | bytes
216

217
    :rtype: Connection
218
    """
219
    body = db_instance.get_value_from_db(MongoCollections.CONNECTIONS, f"{service_id}")
×
220
    if not body:
×
221
        return "Connection not found", 404
×
222

223
    if not connexion.request.is_json:
×
224
        return "Request body must be JSON", 400
×
225

226
    new_body = connexion.request.get_json()
×
227

228
    logger.info(f"Gathered connexion JSON: {new_body}")
×
229

230
    body.update(new_body)
×
231

232
    body, _ = connection_state_machine(body, ConnectionStateMachine.State.MODIFYING)
×
233

234
    body["oxp_success_count"] = 0
×
235

236
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
×
237

238
    try:
×
239
        logger.info("Removing connection")
×
240
        # Get roll back connection before removing connection
241
        rollback_conn_body = body
×
242
        remove_conn_reason, remove_conn_code = connection_handler.remove_connection(
×
243
            current_app.te_manager, service_id
244
        )
245

246
        if remove_conn_code // 100 != 2:
×
247
            body, _ = connection_state_machine(body, ConnectionStateMachine.State.DOWN)
×
248
            db_instance.add_key_value_pair_to_db(
×
249
                MongoCollections.CONNECTIONS, service_id, body
250
            )
251
            response = {
×
252
                "service_id": service_id,
253
                "status": parse_conn_status(body["status"]),
254
                "reason": f"Failure to modify L2VPN during removal: {remove_conn_reason}",
255
            }
256
            return response, remove_conn_code
×
257

258
        logger.info(f"Removed connection: {service_id}")
×
259
    except Exception as e:
×
260
        logger.info(f"Delete failed (connection id: {service_id}): {e}")
×
261
        return f"Failed, reason: {e}", 500
×
262

263
    logger.info(
×
264
        f"Placing new connection {service_id} with te_manager: {current_app.te_manager}"
265
    )
266

267
    body, _ = connection_state_machine(
×
268
        body, ConnectionStateMachine.State.UNDER_PROVISIONING
269
    )
270
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
×
271
    reason, code = connection_handler.place_connection(current_app.te_manager, body)
×
272

273
    if code // 100 == 2:
×
274
        # Service created successfully
275
        code = 201
×
276
        logger.info(f"Placed: ID: {service_id} reason='{reason}', code={code}")
×
277
        response = {
×
278
            "service_id": service_id,
279
            "status": parse_conn_status(body["status"]),
280
            "reason": reason,
281
        }
282
        return response, code
×
283
    else:
284
        body, _ = connection_state_machine(body, ConnectionStateMachine.State.DOWN)
×
285

286
    logger.info(
×
287
        f"Failed to place new connection. ID: {service_id} reason='{reason}', code={code}"
288
    )
289
    logger.info("Rolling back to old connection.")
×
290

291
    if not rollback_conn_body:
×
292
        response = {
×
293
            "service_id": service_id,
294
            "status": parse_conn_status(body["status"]),
295
            "reason": f"Failure, unable to rollback to last successful L2VPN: {reason}",
296
        }
297
        return response, code
×
298

299
    # because above placement failed, so re-place the original connection request.
300
    conn_request = rollback_conn_body
×
301
    conn_request["id"] = service_id
×
302

303
    try:
×
304
        rollback_conn_reason, rollback_conn_code = connection_handler.place_connection(
×
305
            current_app.te_manager, conn_request
306
        )
307
        if rollback_conn_code // 100 == 2:
×
308
            db_instance.add_key_value_pair_to_db(
×
309
                MongoCollections.CONNECTIONS, service_id, conn_request
310
            )
311
        logger.info(
×
312
            f"Roll back connection result: ID: {service_id} reason='{rollback_conn_reason}', code={rollback_conn_code}"
313
        )
314
    except Exception as e:
×
315
        logger.info(f"Rollback failed (connection id: {service_id}): {e}")
×
316
        return f"Rollback failed, reason: {e}", 500
×
317

318
    response = {
×
319
        "service_id": service_id,
320
        "reason": f"Failure, rolled back to last successful L2VPN: {reason}",
321
        "status": parse_conn_status(conn_request["status"]),
322
    }
323
    return response, code
×
324

325

326
def get_archived_connections_by_id(service_id):
2✔
327
    """
328
    List archived connection by ID.
329

330
    :param service_id: ID of connection that needs to be fetched
331
    :type service_id: str
332

333
    :rtype: Connection
334
    """
335

336
    value = get_connection_status(db_instance, service_id)
×
337

338
    if not value:
×
339
        return "Connection not found", 404
×
340

341
    return value
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc