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

atlanticwave-sdx / sdx-controller / 14672778579

25 Apr 2025 08:17PM UTC coverage: 56.051% (-0.09%) from 56.145%
14672778579

Pull #453

github

web-flow
Merge 63a6fd14f into 03aa84af5
Pull Request #453: Assign oxp_success_count to 0 only if it does not exist

30 of 54 new or added lines in 4 files covered. (55.56%)

1 existing line in 1 file now uncovered.

1181 of 2107 relevant lines covered (56.05%)

1.12 hits per line

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

54.74
/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
    conn_status = ConnectionStateMachine.State.UNDER_PROVISIONING
2✔
158
    body, _ = connection_state_machine(
2✔
159
        body, conn_status
160
    )
161

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

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

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

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

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

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

198
    return response, code
2✔
199

200

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

204
     # noqa: E501
205

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

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

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

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

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

NEW
224
    body = value[service_id]
×
225
    body.update(new_body)
×
226

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

NEW
229
    if "oxp_success_count" not in body:
×
NEW
230
        body["oxp_success_count"] = 0
×
231

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

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

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

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

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

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

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

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

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

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

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

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

321

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

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

329
    :rtype: Connection
330
    """
331

332
    value = get_connection_status(db_instance, service_id)
×
333

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

337
    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