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

atlanticwave-sdx / sdx-controller / 14494650169

16 Apr 2025 02:01PM UTC coverage: 56.145% (+0.03%) from 56.114%
14494650169

Pull #447

github

web-flow
Merge c2444ac4e into 940d5782f
Pull Request #447: Adding support for displaying L2VPN status according to spec

4 of 6 new or added lines in 2 files covered. (66.67%)

1 existing line in 1 file now uncovered.

1165 of 2075 relevant lines covered (56.14%)

1.12 hits per line

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

55.47
/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.read_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
            connection["status"] = str(ConnectionStateMachine.State.DELETED)
2✔
72
        else:
73
            connection, _ = connection_state_machine(
×
74
                connection, ConnectionStateMachine.State.DELETED
75
            )
76

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

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

86
    return "OK", 200
2✔
87

88

89
def get_connection_by_id(service_id):
2✔
90
    """
91
    Find connection by ID.
92

93
    :param service_id: ID of connection that needs to be fetched
94
    :type service_id: str
95

96
    :rtype: Connection
97
    """
98

99
    value = get_connection_status(db_instance, service_id)
2✔
100

101
    if not value:
2✔
102
        return "Connection not found", 404
2✔
103

104
    return value
2✔
105

106

107
def get_connections():  # noqa: E501
2✔
108
    """List all connections
109

110
    connection details # noqa: E501
111

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

126

127
def place_connection(body):
2✔
128
    """
129
    Place an connection request from the SDX-Controller.
130

131
    :param body: order placed for creating a connection
132
    :type body: dict | bytes
133

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

140
    body = connexion.request.get_json()
2✔
141
    logger.info(f"Gathered connexion JSON: {body}")
2✔
142

143
    logger.info("Placing connection. Saving to database.")
2✔
144

145
    service_id = body.get("id")
2✔
146

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

152
    body["status"] = str(ConnectionStateMachine.State.REQUESTED)
2✔
153

154
    # used in lc_message_handler to count the oxp success response
155
    body["oxp_success_count"] = 0
2✔
156

157
    body, _ = connection_state_machine(
2✔
158
        body, ConnectionStateMachine.State.UNDER_PROVISIONING
159
    )
160

161
    db_instance.add_key_value_pair_to_db(
2✔
162
        MongoCollections.CONNECTIONS, service_id, json.dumps(body)
163
    )
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
    value = db_instance.read_from_db(MongoCollections.CONNECTIONS, service_id)
2✔
171
    body = json.loads(value[service_id]) if value else body
2✔
172

173
    if code // 100 != 2:
2✔
174
        body["status"] = str(ConnectionStateMachine.State.REJECTED)
2✔
175

176
    db_instance.add_key_value_pair_to_db(
2✔
177
        MongoCollections.CONNECTIONS, service_id, json.dumps(body)
178
    )
179
    logger.info(
2✔
180
        f"place_connection result: ID: {service_id} reason='{reason}', code={code}"
181
    )
182

183
    response = {
2✔
184
        "service_id": service_id,
185
        "status": parse_conn_status(body["status"]),
186
        "reason": reason,
187
    }
188

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

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

200
    return response, code
2✔
201

202

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

206
     # noqa: E501
207

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

213
    :rtype: Connection
214
    """
215
    value = db_instance.read_from_db(MongoCollections.CONNECTIONS, f"{service_id}")
×
216
    if not value:
×
217
        return "Connection not found", 404
×
218

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

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

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

226
    body = json.loads(value[service_id])
×
227
    body.update(new_body)
×
228

229
    body, _ = connection_state_machine(body, ConnectionStateMachine.State.MODIFYING)
×
230
    body["oxp_success_count"] = 0
×
231
    db_instance.add_key_value_pair_to_db(
×
232
        MongoCollections.CONNECTIONS, service_id, json.dumps(body)
233
    )
234

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

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

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

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

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

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

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

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

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

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

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

324

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

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

332
    :rtype: Connection
333
    """
334

335
    value = get_connection_status(db_instance, service_id)
×
336

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

340
    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