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

atlanticwave-sdx / sdx-controller / 14780769409

01 May 2025 06:13PM UTC coverage: 56.167% (+0.02%) from 56.145%
14780769409

Pull #453

github

web-flow
Merge d5a142fdd into 208f19319
Pull Request #453: Save raw JSON to MongoDB

52 of 101 new or added lines in 7 files covered. (51.49%)

6 existing lines in 3 files now uncovered.

1184 of 2108 relevant lines covered (56.17%)

1.12 hits per line

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

55.88
/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✔
UNCOV
71
            connection["status"] = str(ConnectionStateMachine.State.DELETED)
×
72
        else:
73
            connection, _ = connection_state_machine(
2✔
74
                connection, ConnectionStateMachine.State.DOWN
75
            )
76
            connection, _ = connection_state_machine(
2✔
77
                connection, ConnectionStateMachine.State.DELETED
78
            )
79

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

82
        connection_handler.remove_connection(current_app.te_manager, service_id)
2✔
83
        db_instance.mark_deleted(MongoCollections.CONNECTIONS, f"{service_id}")
2✔
84
        db_instance.mark_deleted(MongoCollections.BREAKDOWNS, f"{service_id}")
2✔
85
    except Exception as e:
×
86
        logger.info(f"Delete failed (connection id: {service_id}): {e}")
×
87
        return f"Failed, reason: {e}", 500
×
88

89
    return "OK", 200
2✔
90

91

92
def get_connection_by_id(service_id):
2✔
93
    """
94
    Find connection by ID.
95

96
    :param service_id: ID of connection that needs to be fetched
97
    :type service_id: str
98

99
    :rtype: Connection
100
    """
101

102
    value = get_connection_status(db_instance, service_id)
2✔
103

104
    if not value:
2✔
105
        return "Connection not found", 404
2✔
106

107
    return value
2✔
108

109

110
def get_connections():  # noqa: E501
2✔
111
    """List all connections
112

113
    connection details # noqa: E501
114

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

129

130
def place_connection(body):
2✔
131
    """
132
    Place an connection request from the SDX-Controller.
133

134
    :param body: order placed for creating a connection
135
    :type body: dict | bytes
136

137
    :rtype: Connection
138
    """
139
    logger.info(f"Placing connection: {body}")
2✔
140
    if not connexion.request.is_json:
2✔
141
        return "Request body must be JSON", 400
×
142

143
    body = connexion.request.get_json()
2✔
144
    logger.info(f"Gathered connexion JSON: {body}")
2✔
145

146
    logger.info("Placing connection. Saving to database.")
2✔
147

148
    service_id = body.get("id")
2✔
149

150
    if service_id is None:
2✔
151
        service_id = str(uuid.uuid4())
2✔
152
        body["id"] = service_id
2✔
153
        logger.info(f"Request has no ID. Generated ID: {service_id}")
2✔
154

155
    body["status"] = str(ConnectionStateMachine.State.REQUESTED)
2✔
156

157
    # used in lc_message_handler to count the oxp success response
158
    body["oxp_success_count"] = 0
2✔
159

160
    conn_status = ConnectionStateMachine.State.UNDER_PROVISIONING
2✔
161
    body, _ = connection_state_machine(body, conn_status)
2✔
162

163
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
2✔
164

165
    logger.info(
2✔
166
        f"Handling request {service_id} with te_manager: {current_app.te_manager}"
167
    )
168
    reason, code = connection_handler.place_connection(current_app.te_manager, body)
2✔
169

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

182
    response = {
2✔
183
        "service_id": service_id,
184
        "status": parse_conn_status(str(conn_status)),
185
        "reason": reason,
186
    }
187

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

195
    # response["id"] = service_id
196
    # response["status"] = "success" if code == 2xx else "failure"
197
    # response["reason"] = reason # `reason` is not present in schema though.
198

199
    return response, code
2✔
200

201

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

205
     # noqa: E501
206

207
    :param service_id: ID of l2vpn connection that needs to be changed
208
    :type service_id: dict | bytes'
209
    :param body:
210
    :type body: dict | bytes
211

212
    :rtype: Connection
213
    """
NEW
214
    body = db_instance.get_value_from_db(MongoCollections.CONNECTIONS, f"{service_id}")
×
NEW
215
    if not body:
×
UNCOV
216
        return "Connection not found", 404
×
217

218
    if not connexion.request.is_json:
×
219
        return "Request body must be JSON", 400
×
220

221
    new_body = connexion.request.get_json()
×
222

223
    logger.info(f"Gathered connexion JSON: {new_body}")
×
224

225
    body.update(new_body)
×
226

227
    body, _ = connection_state_machine(body, ConnectionStateMachine.State.MODIFYING)
×
228

229
    body["oxp_success_count"] = 0
×
230

NEW
231
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
×
232

233
    try:
×
234
        logger.info("Removing connection")
×
235
        # Get roll back connection before removing connection
NEW
236
        rollback_conn_body = body
×
237
        remove_conn_reason, remove_conn_code = connection_handler.remove_connection(
×
238
            current_app.te_manager, service_id
239
        )
240

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

253
        logger.info(f"Removed connection: {service_id}")
×
254
    except Exception as e:
×
255
        logger.info(f"Delete failed (connection id: {service_id}): {e}")
×
256
        return f"Failed, reason: {e}", 500
×
257

258
    logger.info(
×
259
        f"Placing new connection {service_id} with te_manager: {current_app.te_manager}"
260
    )
261

262
    body, _ = connection_state_machine(
×
263
        body, ConnectionStateMachine.State.UNDER_PROVISIONING
264
    )
NEW
265
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
×
UNCOV
266
    reason, code = connection_handler.place_connection(current_app.te_manager, body)
×
267

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

281
    logger.info(
×
282
        f"Failed to place new connection. ID: {service_id} reason='{reason}', code={code}"
283
    )
284
    logger.info("Rolling back to old connection.")
×
285

286
    if not rollback_conn_body:
×
287
        response = {
×
288
            "service_id": service_id,
289
            "status": parse_conn_status(body["status"]),
290
            "reason": f"Failure, unable to rollback to last successful L2VPN: {reason}",
291
        }
292
        return response, code
×
293

294
    # because above placement failed, so re-place the original connection request.
295
    conn_request = json.loads(rollback_conn_body[service_id])
×
296
    conn_request["id"] = service_id
×
297

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

313
    response = {
×
314
        "service_id": service_id,
315
        "reason": f"Failure, rolled back to last successful L2VPN: {reason}",
316
        "status": parse_conn_status(conn_request["status"]),
317
    }
318
    return response, code
×
319

320

321
def get_archived_connections_by_id(service_id):
2✔
322
    """
323
    List archived connection by ID.
324

325
    :param service_id: ID of connection that needs to be fetched
326
    :type service_id: str
327

328
    :rtype: Connection
329
    """
330

331
    value = get_connection_status(db_instance, service_id)
×
332

333
    if not value:
×
334
        return "Connection not found", 404
×
335

336
    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

© 2026 Coveralls, Inc