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

atlanticwave-sdx / sdx-controller / 11576692286

29 Oct 2024 03:03PM UTC coverage: 56.886% (+0.1%) from 56.777%
11576692286

push

github

web-flow
Merge pull request #346 from atlanticwave-sdx/cleanup-topology-handling-logic

Cleanup topology handling logic

1 of 19 new or added lines in 2 files covered. (5.26%)

2 existing lines in 1 file now uncovered.

1107 of 1946 relevant lines covered (56.89%)

2.28 hits per line

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

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

8
import pika
4✔
9

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

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

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

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

23

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

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

30
        self.connection = pika.BlockingConnection(
4✔
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()
4✔
39
        self.exchange_name = exchange_name
4✔
40

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

44
        self.te_manager = te_manager
4✔
45

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

48
    def on_request(self, ch, method, props, message_body):
4✔
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

61
        ch.basic_publish(
×
62
            exchange=self.exchange_name,
63
            routing_key=props.reply_to,
64
            properties=pika.BasicProperties(correlation_id=props.correlation_id),
65
            body=str(response),
66
        )
67
        ch.basic_ack(delivery_tag=method.delivery_tag)
×
68

69
    def start_consumer(self):
4✔
70
        self.channel.basic_qos(prefetch_count=1)
4✔
71
        self.channel.basic_consume(queue=SUB_QUEUE, on_message_callback=self.on_request)
4✔
72

73
        self.logger.info(" [MQ] Awaiting requests from queue: " + SUB_QUEUE)
4✔
74
        self.channel.start_consuming()
4✔
75

76
    def start_sdx_consumer(self, thread_queue, db_instance):
4✔
77
        HEARTBEAT_ID = 0
4✔
78

79
        rpc = RpcConsumer(thread_queue, "", self.te_manager)
4✔
80
        t1 = threading.Thread(target=rpc.start_consumer, args=(), daemon=True)
4✔
81
        t1.start()
4✔
82

83
        lc_message_handler = LcMessageHandler(db_instance, self.te_manager)
4✔
84
        parse_helper = ParseHelper()
4✔
85

86
        latest_topo = {}
4✔
87
        domain_list = []
4✔
88

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

95
        if domain_list_from_db:
4✔
96
            domain_list = domain_list_from_db["domain_list"]
×
NEW
97
            logger.debug("Domain list already exists in db: ")
×
98
            logger.debug(domain_list)
×
99

100
        if latest_topo_from_db:
4✔
101
            latest_topo = latest_topo_from_db["latest_topo"]
×
NEW
102
            logger.debug("Topology already exists in db: ")
×
103
            logger.debug(latest_topo)
×
104

105
        # If topologies already saved in db, use them to initialize te_manager
106
        if domain_list:
4✔
NEW
107
            for domain in domain_list:
×
NEW
108
                topology = db_instance.read_from_db("topologies", domain)
×
109

NEW
110
                if not topology:
×
NEW
111
                    continue
×
112

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

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

124
            if "Heart Beat" in str(msg):
×
125
                HEARTBEAT_ID += 1
×
126
                logger.debug("Heart beat received. ID: " + str(HEARTBEAT_ID))
×
NEW
127
                continue
×
128

NEW
129
            if not parse_helper.is_json(msg):
×
NEW
130
                continue
×
131

NEW
132
            if "version" not in str(msg):
×
NEW
133
                logger.info("Got message (NO VERSION) from MQ: " + str(msg))
×
134

NEW
135
            lc_message_handler.process_lc_json_msg(
×
136
                msg,
137
                latest_topo,
138
                domain_list,
139
            )
140

141
    def stop_threads(self):
4✔
142
        """
143
        Signal threads that we're ready to stop.
144
        """
145
        logger.info("[MQ] Stopping threads.")
×
146
        self.channel.stop_consuming()
×
147
        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

© 2026 Coveralls, Inc