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

atlanticwave-sdx / sdx-controller / 16000231024

01 Jul 2025 01:07PM UTC coverage: 55.53% (-0.8%) from 56.324%
16000231024

push

github

web-flow
Merge pull request #474 from atlanticwave-sdx/bump-pce-dev8

Bump pce to dev8

1200 of 2161 relevant lines covered (55.53%)

1.11 hits per line

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

53.9
/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
        elif connection["status"] == str(
×
78
            ConnectionStateMachine.State.UNDER_PROVISIONING
79
        ):
80
            connection, _ = connection_state_machine(
×
81
                connection, ConnectionStateMachine.State.DOWN
82
            )
83
            connection, _ = connection_state_machine(
×
84
                connection, ConnectionStateMachine.State.DELETED
85
            )
86
        else:
87
            connection, _ = connection_state_machine(
×
88
                connection, ConnectionStateMachine.State.DELETED
89
            )
90

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

93
        connection_handler.remove_connection(current_app.te_manager, service_id)
2✔
94
        db_instance.mark_deleted(MongoCollections.CONNECTIONS, f"{service_id}")
2✔
95
        db_instance.mark_deleted(MongoCollections.BREAKDOWNS, f"{service_id}")
2✔
96
    except Exception as e:
×
97
        logger.info(f"Delete failed (connection id: {service_id}): {e}")
×
98
        return f"Failed, reason: {e}", 500
×
99

100
    return "OK", 200
2✔
101

102

103
def get_connection_by_id(service_id):
2✔
104
    """
105
    Find connection by ID.
106

107
    :param service_id: ID of connection that needs to be fetched
108
    :type service_id: str
109

110
    :rtype: Connection
111
    """
112

113
    value = get_connection_status(db_instance, service_id)
2✔
114

115
    if not value:
2✔
116
        return "Connection not found", 404
2✔
117

118
    return value
2✔
119

120

121
def get_connections():  # noqa: E501
2✔
122
    """List all connections
123

124
    connection details # noqa: E501
125

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

140

141
def place_connection(body):
2✔
142
    """
143
    Place an connection request from the SDX-Controller.
144

145
    :param body: order placed for creating a connection
146
    :type body: dict | bytes
147

148
    :rtype: Connection
149
    """
150
    logger.info(f"Placing connection: {body}")
2✔
151
    if not connexion.request.is_json:
2✔
152
        return "Request body must be JSON", 400
×
153

154
    body = connexion.request.get_json()
2✔
155
    logger.info(f"Gathered connexion JSON: {body}")
2✔
156

157
    logger.info("Placing connection. Saving to database.")
2✔
158

159
    service_id = body.get("id")
2✔
160

161
    if service_id is None:
2✔
162
        service_id = str(uuid.uuid4())
2✔
163
        body["id"] = service_id
2✔
164
        logger.info(f"Request has no ID. Generated ID: {service_id}")
2✔
165

166
    body["status"] = str(ConnectionStateMachine.State.REQUESTED)
2✔
167

168
    # used in lc_message_handler to count the oxp success response
169
    body["oxp_success_count"] = 0
2✔
170

171
    conn_status = ConnectionStateMachine.State.UNDER_PROVISIONING
2✔
172
    body, _ = connection_state_machine(body, conn_status)
2✔
173

174
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
2✔
175

176
    logger.info(
2✔
177
        f"Handling request {service_id} with te_manager: {current_app.te_manager}"
178
    )
179
    reason, code = connection_handler.place_connection(current_app.te_manager, body)
2✔
180

181
    if code // 100 != 2:
2✔
182
        conn_status = ConnectionStateMachine.State.REJECTED
2✔
183
        db_instance.update_field_in_json(
2✔
184
            MongoCollections.CONNECTIONS,
185
            service_id,
186
            "status",
187
            str(conn_status),
188
        )
189
    logger.info(
2✔
190
        f"place_connection result: ID: {service_id} reason='{reason}', code={code}"
191
    )
192

193
    response = {
2✔
194
        "service_id": service_id,
195
        "status": parse_conn_status(str(conn_status)),
196
        "reason": reason,
197
    }
198

199
    # # TODO: our response is supposed to be shaped just like request
200
    # # ('#/components/schemas/connection'), and in that case the below
201
    # # code would be a quick implementation.
202
    # #
203
    # # https://github.com/atlanticwave-sdx/sdx-controller/issues/251
204
    # response = body
205

206
    # response["id"] = service_id
207
    # response["status"] = "success" if code == 2xx else "failure"
208
    # response["reason"] = reason # `reason` is not present in schema though.
209

210
    return response, code
2✔
211

212

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

216
     # noqa: E501
217

218
    :param service_id: ID of l2vpn connection that needs to be changed
219
    :type service_id: dict | bytes'
220
    :param body:
221
    :type body: dict | bytes
222

223
    :rtype: Connection
224
    """
225
    body = db_instance.get_value_from_db(MongoCollections.CONNECTIONS, f"{service_id}")
×
226
    if not body:
×
227
        return "Connection not found", 404
×
228

229
    if not connexion.request.is_json:
×
230
        return "Request body must be JSON", 400
×
231

232
    new_body = connexion.request.get_json()
×
233

234
    logger.info(f"Gathered connexion JSON: {new_body}")
×
235

236
    body.update(new_body)
×
237

238
    body, _ = connection_state_machine(body, ConnectionStateMachine.State.MODIFYING)
×
239

240
    body["oxp_success_count"] = 0
×
241

242
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
×
243

244
    try:
×
245
        logger.info("Removing connection")
×
246
        # Get roll back connection before removing connection
247
        rollback_conn_body = body
×
248
        remove_conn_reason, remove_conn_code = connection_handler.remove_connection(
×
249
            current_app.te_manager, service_id
250
        )
251

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

264
        logger.info(f"Removed connection: {service_id}")
×
265
    except Exception as e:
×
266
        logger.info(f"Delete failed (connection id: {service_id}): {e}")
×
267
        return f"Failed, reason: {e}", 500
×
268

269
    logger.info(
×
270
        f"Placing new connection {service_id} with te_manager: {current_app.te_manager}"
271
    )
272

273
    body, _ = connection_state_machine(
×
274
        body, ConnectionStateMachine.State.UNDER_PROVISIONING
275
    )
276
    db_instance.add_key_value_pair_to_db(MongoCollections.CONNECTIONS, service_id, body)
×
277
    reason, code = connection_handler.place_connection(current_app.te_manager, body)
×
278

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

292
    logger.info(
×
293
        f"Failed to place new connection. ID: {service_id} reason='{reason}', code={code}"
294
    )
295
    logger.info("Rolling back to old connection.")
×
296

297
    if not rollback_conn_body:
×
298
        response = {
×
299
            "service_id": service_id,
300
            "status": parse_conn_status(body["status"]),
301
            "reason": f"Failure, unable to rollback to last successful L2VPN: {reason}",
302
        }
303
        return response, code
×
304

305
    # because above placement failed, so re-place the original connection request.
306
    conn_request = rollback_conn_body
×
307
    conn_request["id"] = service_id
×
308

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

324
    response = {
×
325
        "service_id": service_id,
326
        "reason": f"Failure, rolled back to last successful L2VPN: {reason}",
327
        "status": parse_conn_status(conn_request["status"]),
328
    }
329
    return response, code
×
330

331

332
def get_archived_connections_by_id(service_id):
2✔
333
    """
334
    List archived connection by ID.
335

336
    :param service_id: ID of connection that needs to be fetched
337
    :type service_id: str
338

339
    :rtype: Connection
340
    """
341

342
    value = get_connection_status(db_instance, service_id)
×
343

344
    if not value:
×
345
        return "Connection not found", 404
×
346

347
    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