brokers.py 4.73 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

# pylint: disable=global-statement

import logging

from requests.auth import HTTPBasicAuth
from django.db import models
from django.core.cache import cache
from django_mysql.models import JSONField
import pika
from pika.exceptions import ConnectionClosed

LOGGER = logging.getLogger(__name__)
RABBITMQ_CONNECTION = None

def exchanges_default():
    return []

# singleton for simple configs
# https://steelkiwi.com/blog/practical-application-singleton-design-pattern/
class SingletonModel(models.Model):
    class Meta:
        abstract = True

    def set_cache(self):
        cache.set(self.__class__.__name__, self)

    # pylint: disable=invalid-name, arguments-differ
    def save(self, *args, **kwargs):
        self.pk = 1
        super(SingletonModel, self).save(*args, **kwargs)
        self.set_cache()

    @classmethod
    def load(cls):
        if cache.get(cls.__name__) is None:
            obj, created = cls.objects.get_or_create(pk=1)
            if not created:
                obj.set_cache()
        return cache.get(cls.__name__)


# clients are registerred at rabbitmq, when they are assigned to a site
# (because we only then know what services they provide)
class RabbitMQInstance(SingletonModel):
    host = models.CharField(
        max_length=150,
        default='localhost',
    )
    vhost = models.CharField(
        max_length=150,
        default='%2f',
    )
    exchanges = JSONField(
        default=exchanges_default,
        null=True,
        blank=True,
    )
    port = models.IntegerField(
        default=15672,
    )
    username = models.CharField(
        max_length=150,
        default='guest',
    )
    password = models.CharField(
        max_length=150,
        default='guest',
    )

    def __str__(self):
        return self.host

    def msg(self, msg):
        return '[RabbitMQ:{}] {}'.format(self.host, msg)

    @property
    def auth(self):
        return HTTPBasicAuth(
            self.username,
            self.password,
        )

    def _init_exchanges(self, channel):
        channel.exchange_declare(
            exchange='services',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        channel.exchange_declare(
            exchange='groups',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        channel.exchange_declare(
            exchange='sites',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )
        channel.exchange_declare(
            exchange='users',
            durable=True,
            auto_delete=False,
            exchange_type='topic',
        )

    def _init_connection(self):
        global RABBITMQ_CONNECTION
        #LOGGER.debug('Opening new BlockingConnection')
        RABBITMQ_CONNECTION = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=self.host,
                ssl=True,
                heartbeat_interval=60,
            )
        )
        return RABBITMQ_CONNECTION

    @property
    def _connection(self):
        global RABBITMQ_CONNECTION
        if RABBITMQ_CONNECTION is not None:
            if RABBITMQ_CONNECTION.is_open:
                return RABBITMQ_CONNECTION
            elif RABBITMQ_CONNECTION.is_closing:
                RABBITMQ_CONNECTION.close()

        connection = self._init_connection()
        channel = connection.channel()
        self._init_exchanges(connection.channel())
        channel.close()
        RABBITMQ_CONNECTION = connection
        return connection

    @property
    def _channel(self):
        try:
            channel = self._connection.channel()
            channel.confirm_delivery()
            return channel
        except ConnectionClosed:
            # reinitialize the connection
            self._init_connection()
            return self._channel

    def _publish(self, exchange, routing_key, body):
        channel = self._channel
        channel.basic_publish(
            exchange=exchange,
            routing_key=routing_key,
            body=body,
            properties=pika.BasicProperties(
                delivery_mode=1,
            ),
        )
        channel.close()

    # PUBLIC API
    def publish_by_service(self, service, msg):
        self._publish(
            'services',
            service.name,
            msg,
        )

    def publish_by_group(self, group, msg):
        self._publish(
            'groups',
            group.name,
            msg,
        )

    def publish_by_site(self, site, msg):
        self._publish(
            'sites',
            site.name,
            msg,
        )

    def publish_to_user(self, user, msg):
        self._publish(
            'users',
            str(user.id),
            msg,
        )