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

atlanticwave-sdx / sdx-controller / 13204339783

07 Feb 2025 04:54PM UTC coverage: 55.423% (-0.1%) from 55.567%
13204339783

Pull #411

github

web-flow
Merge 5ca8513b9 into 2a492f0bc
Pull Request #411: Better error handling

2 of 11 new or added lines in 2 files covered. (18.18%)

20 existing lines in 1 file now uncovered.

1119 of 2019 relevant lines covered (55.42%)

1.11 hits per line

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

57.14
/sdx_controller/messaging/rpc_queue_consumer.py
1
#!/usr/bin/env python
2
import json
2✔
3
import logging
2✔
4
import os
2✔
5
import threading
2✔
6
from queue import Queue
2✔
7

8
import pika
2✔
9

10
from sdx_controller.handlers.lc_message_handler import LcMessageHandler
2✔
11
from sdx_controller.utils.parse_helper import ParseHelper
2✔
12

13
MQ_HOST = os.getenv("MQ_HOST")
2✔
14
MQ_PORT = os.getenv("MQ_PORT") or 5672
2✔
15
MQ_USER = os.getenv("MQ_USER") or "guest"
2✔
16
MQ_PASS = os.getenv("MQ_PASS") or "guest"
2✔
17

18
# subscribe to the corresponding queue
19
SUB_QUEUE = os.getenv("SUB_QUEUE")
2✔
20

21
logger = logging.getLogger(__name__)
2✔
22

23

24
class RpcConsumer(object):
2✔
25
    def __init__(self, thread_queue, exchange_name, te_manager):
2✔
26
        self.logger = logging.getLogger(__name__)
2✔
27

28
        self.logger.info(f"[MQ] Using amqp://{MQ_USER}@{MQ_HOST}:{MQ_PORT}")
2✔
29

30
        self.connection = pika.BlockingConnection(
2✔
31
            pika.ConnectionParameters(
32
                host=MQ_HOST,
33
                port=MQ_PORT,
34
                credentials=pika.PlainCredentials(username=MQ_USER, password=MQ_PASS),
35
            )
36
        )
37

38
        self.channel = self.connection.channel()
2✔
39
        self.exchange_name = exchange_name
2✔
40

41
        self.channel.queue_declare(queue=SUB_QUEUE)
2✔
42
        self._thread_queue = thread_queue
2✔
43

44
        self.te_manager = te_manager
2✔
45

46
        self._exit_event = threading.Event()
2✔
47

48
    def on_request(self, ch, method, props, message_body):
2✔
49
        response = message_body
×
50
        self._thread_queue.put(message_body)
×
51

52
        self.connection = pika.BlockingConnection(
×
53
            pika.ConnectionParameters(
54
                host=MQ_HOST,
55
                port=MQ_PORT,
56
                credentials=pika.PlainCredentials(username=MQ_USER, password=MQ_PASS),
57
            )
58
        )
59
        self.channel = self.connection.channel()
×
60

NEW
61
        try:
×
NEW
62
            ch.basic_publish(
×
63
                exchange=self.exchange_name,
64
                routing_key=props.reply_to,
65
                properties=pika.BasicProperties(correlation_id=props.correlation_id),
66
                body=str(response),
67
            )
NEW
68
            ch.basic_ack(delivery_tag=method.delivery_tag)
×
NEW
69
        except Exception as err:
×
NEW
70
            self.logger.info(f"[MQ] encountered error when publishing: {err}")
×
71

72
    def start_consumer(self):
2✔
73
        self.channel.basic_qos(prefetch_count=1)
2✔
74
        self.channel.basic_consume(queue=SUB_QUEUE, on_message_callback=self.on_request)
2✔
75

76
        self.logger.info(" [MQ] Awaiting requests from queue: " + SUB_QUEUE)
2✔
77
        self.channel.start_consuming()
2✔
78

79
    def start_sdx_consumer(self, thread_queue, db_instance):
2✔
80
        HEARTBEAT_ID = 0
2✔
81

82
        rpc = RpcConsumer(thread_queue, "", self.te_manager)
2✔
83
        t1 = threading.Thread(target=rpc.start_consumer, args=(), daemon=True)
2✔
84
        t1.start()
2✔
85

86
        lc_message_handler = LcMessageHandler(db_instance, self.te_manager)
2✔
87
        parse_helper = ParseHelper()
2✔
88

89
        latest_topo = {}
2✔
90
        domain_list = []
2✔
91

92
        # This part reads from DB when SDX controller initially starts.
93
        # It looks for domain_list, if already in DB,
94
        # Then use the existing ones from DB.
95
        domain_list_from_db = db_instance.read_from_db("domains", "domain_list")
2✔
96
        latest_topo_from_db = db_instance.read_from_db("topologies", "latest_topo")
2✔
97

98
        if domain_list_from_db:
2✔
99
            domain_list = domain_list_from_db["domain_list"]
×
100
            logger.debug("Domain list already exists in db: ")
×
101
            logger.debug(domain_list)
×
102

103
        if latest_topo_from_db:
2✔
104
            latest_topo = latest_topo_from_db["latest_topo"]
×
105
            logger.debug("Topology already exists in db: ")
×
106
            logger.debug(latest_topo)
×
107

108
        # If topologies already saved in db, use them to initialize te_manager
109
        if domain_list:
2✔
110
            for domain in domain_list:
×
111
                topology = db_instance.read_from_db("topologies", domain)
×
112

113
                if not topology:
×
114
                    continue
×
115

116
                # Get the actual thing minus the Mongo ObjectID.
117
                topology = topology[domain]
×
118
                topo_json = json.loads(topology)
×
119
                self.te_manager.add_topology(topo_json)
×
120
                logger.debug(f"Read {domain}: {topology}")
×
121

122
        while not self._exit_event.is_set():
2✔
123
            # Queue.get() will block until there's an item in the queue.
124
            msg = thread_queue.get()
2✔
125
            logger.debug("MQ received message:" + str(msg))
×
126

127
            if "Heart Beat" in str(msg):
×
128
                HEARTBEAT_ID += 1
×
129
                logger.debug("Heart beat received. ID: " + str(HEARTBEAT_ID))
×
130
                continue
×
131

132
            if not parse_helper.is_json(msg):
×
133
                continue
×
134

135
            if "version" not in str(msg):
×
136
                logger.info("Got message (NO VERSION) from MQ: " + str(msg))
×
137

138
            lc_message_handler.process_lc_json_msg(
×
139
                msg,
140
                latest_topo,
141
                domain_list,
142
            )
143

144
    def stop_threads(self):
2✔
145
        """
146
        Signal threads that we're ready to stop.
147
        """
148
        logger.info("[MQ] Stopping threads.")
×
149
        self.channel.stop_consuming()
×
150
        self._exit_event.set()
×
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