statestore.py 11.5 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
#
#  engine
#
#  Playout Daemon for autoradio project
#
#
#  Copyright (C) 2017-2018 Gottfried Gaisbauer <gottfried.gaisbauer@servus.at>
#
#  This file is part of engine.
#
#  engine is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  any later version.
#
#  engine is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with engine. If not, see <http://www.gnu.org/licenses/>.
#
24
25
26
27

import redis
import time
import datetime
28
import simplejson
29
30
import re
import uuid
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45

class RedisStateStore(object):

    """Store and get Reports from redis"""

    def __init__(self, **redis_kwargs):
        """The default connection parameters are: host='localhost', port=6379, db=0"""
        self.db= redis.Redis()
        self.channel = '*'
        self.section = '*'
        self.separator = '_'
        self.daily = False

    # ------------------------------------------------------------------------------------------ #
46
    def set_channel(self, channel):
47
48
49
50
51
52
53
54
        """
        Kanal setzen
        @type channel: string
        @param channel: Kanal
        """
        self.channel = channel

    # ------------------------------------------------------------------------------------------ #
55
    def set_section(self, section):
56
57
58
59
60
61
62
63
        """
        Sektion setzen
        @type section: string
        @param section: Sektion
        """
        self.section = section

    # ------------------------------------------------------------------------------------------ #
64
    def set_alive_state(self):
65
66
67
        """
        Alive Funktion - alle 20 Sekunden melden, dass man noch am Leben ist
        """
68
        self.set_state('alive', 'Hi', 21)
69
70

    # ------------------------------------------------------------------------------------------ #
71
    def get_alive_state(self, channel):
72
73
74
75
76
77
78
        """
        Alive Status eines Channels ermitteln
        @type channel:  string
        @param channel: der Channel
        @rtype: string/None
        @return: Ein String, oder None, bei negativem Ergebnis
        """
79
        return self.get_state('alive', channel)
80
81

    # ------------------------------------------------------------------------------------------ #
82
    def set_state(self, name, value, expires=None, channel=None):
83
84
85
86
87
88
89
90
91
92
93
94
        """
        Setzt einen Status
        @type name: string
        @param name: Name des state
        @type value: string
        @param value: Wert
        @type channel: string
        @param channel: Kanal (optional)
        """
        if not channel:
            channel = self.channel

95
        key = self.__create_key__(channel + 'State', name)
96
97
98
99
100

        if value == "":
            self.db.delete(key)
        else:
            # publish on channel
101
            message = simplejson.dumps({'eventname':name, 'value': value})
102
103
104
105
106
107
108
            self.db.publish(channel + 'Publish', message)
            # store in database
            self.db.set(key, value)
            if(expires):
                self.db.expire(key, 21)

    # ------------------------------------------------------------------------------------------ #
109
    def get_state(self, name, channel):
110
111
112
113
114
115
116
        """
        Holt einen Status
        @type name: string
        @param name: Name des state
        @type channel: string
        @param channel: Kanal (optional)
        """
117
        key = self.__create_key__(channel + 'State', name)
118
119
120
        return self.db.get(key)

    # ------------------------------------------------------------------------------------------ #
121
    def queue_add_event(self, eventtime, name, value, channel=None):
122
123
124
125
126
127
128
129
130
131
132
133
134
        """
        Kündigt einen Event an
        @type eventtime: string
        @param eventtime: Datum und Zeit des events
        @type name: string
        @param name: Name des Events
        @type value: dict
        @param value: Werte
        @type channel: string
        @param channel: Kanal (optional)
        """
        timeevent = datetime.datetime.strptime(eventtime[0:16],"%Y-%m-%dT%H:%M")
        expire = int(time.mktime(timeevent.timetuple()) - time.time()) + 60
135
        self.__set_event__(name, eventtime, value, 'Evqueue', 'evqueue', expire, channel)
136
137

    # ------------------------------------------------------------------------------------------ #
138
    def queue_remove_events(self, name=None, channel=None):
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
        """
        Löscht Events
        @type name: string
        @param name: Name des Events
        @type channel: string
        @param channel: Kanal (optional)
        """
        query = channel + 'Evqueue_' if channel else '*Evqueue_'
        query = query + '*_' + name  if name else query + '*_*'

        keys = self.db.keys(query)

        for delkey in keys:
            self.db.delete(delkey)

    # ------------------------------------------------------------------------------------------ #
155
    def fire_event(self, name, value, channel=None):
156
157
158
159
160
161
162
163
164
165
        """
        Feuert einen Event
        @type name: string
        @param name: Name des Events
        @type value: dict
        @param value: Werte
        @type channel: string
        @param channel: Kanal (optional)
        """
        eventtime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M")
166
        self.__set_event__(name, eventtime, value, 'Event', 'events', 60, channel)
167
168

    # ------------------------------------------------------------------------------------------ #
169
    def __set_event__(self, name, eventtime, value, type, namespace, expire, channel=None):
170
171
172
173
174
175
176
177
178
179
180
181
182
        """
        Feuert einen Event
        @type eventtime: string
        @param eventtime: Datum und Zeit des events
        @type value: dict
        @param value: Werte
        @type channel: string
        @param channel: Kanal (optional)
        """
        if not channel:
            channel = self.channel

        timeevent = datetime.datetime.strptime(eventtime[0:16],"%Y-%m-%dT%H:%M")
183
        key = self.__create_key__(channel + type, eventtime, name)
184
185
186
187
188
189
190
191

        value['starts'] = eventtime[0:16]
        value['eventchannel'] = channel
        value['eventname'] = name
        self.db.hset(key, namespace, value)
        self.db.expire(key, expire)

    # ------------------------------------------------------------------------------------------ #
192
    def get_event_queue(self, name=None, channel=None):
193
194
195
196
197
198
199
200
201
202
203
        """
        Holt events eines Kanals
        @type channel: string
        @param channel: Kanal (optional)
        @rtype: list
        @return: Liste der Events
        """
        query = channel + 'Evqueue_' if channel else '*Evqueue_'
        query = query + '*_' + name  if name else query + '*_*'
        keys = self.db.keys(query)
        keys.sort()
204
        entries = self.__get_entries__(keys, 'evqueue')
205
206
207
        return entries

    # ------------------------------------------------------------------------------------------ #
208
    def get_events(self, name=None, channel=None):
209
210
211
212
213
214
215
216
217
218
219
        """
        Holt events eines Kanals
        @type channel: string
        @param channel: Kanal (optional)
        @rtype: list
        @return: Liste der Events
        """
        query = channel + 'Event_' if channel else '*Event_'
        query = query + '*_' + name  if name else query + '*_*'
        keys = self.db.keys(query)
        keys.sort()
220
        entries = self.__get_entries__(keys, 'events')
221
222
223
        return entries

    # ------------------------------------------------------------------------------------------ #
224
    def get_next_event(self, name=None, channel=None):
225
226
227
228
229
230
231
        """
        Holt den aktuellsten Event
        @type channel: string
        @param channel: Kanal (optional)
        @rtype: dict/boolean
        @return: ein Event oder False
        """
232
        events = self.get_event_queue(name, channel)
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        if len(events) > 0:
            result = events.pop(0)
        else:
            result = False

        return result

    # ------------------------------------------------------------------------------------------ #
    def store(self, level, value):
        """
        Hash speichern
        @type level: string
        @param level: der errorlevel
        @type value: dict
        @param value: Werte als dict
        """
        microtime = str(time.time())
        value['microtime'] = microtime
        value['level'] = level
252
        key = self.__create_key__(self.channel, self.section, level, microtime, str(uuid.uuid1()))
253
254
255
256
        self.db.hset(key, self.channel, value)
        self.db.expire(key, 864000)

    # ------------------------------------------------------------------------------------------ #
257
    def __get_keys__(self, level ='*'):
258
259
260
261
262
263
264
        """
        Redis-Keys nach Suchkriterium ermitteln
        @type level: string
        @param level: einen Errorlevel filtern
        @rtype: list
        @return: Die Keys auf die das Suchkriterium zutrifft
        """
265
        key = self.__create_key__(self.channel, self.section, level)
266
267
268
269
270
        microtime = str(time.time())
        search = microtime[0:4] + '*' if self.daily else '*'
        return self.db.keys(key + self.separator + '*')

    # ------------------------------------------------------------------------------------------ #
271
    def __create_key__(self, *args):
272
273
274
275
276
277
278
        """
        Key erschaffen - beliebig viele Argumente
        @rtype: string
        @return: Der key
        """
        return self.separator.join(args)

279
    def get_entries(self, level ='*'):
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        """
        Liste von Hashs nach Suchkriterium erhalten
        @type level: string
        @param level: einen Errorlevel filtern
        @rtype: list
        @return: Redis Hashs
        """
        def tsort(x,y):

            if float(x.split('_',4)[3]) > float(y.split('_',4)[3]):
                return 1
            elif float(x.split('_',4)[3]) < float(y.split('_',4)[3]):
                return -1
            else:
                return 0

296
        keys = self.__get_keys__(level)
297
298

        keys.sort(tsort)
299
        entries = self.__get_entries__(keys, self.channel)
300
301
302
303
        entries = sorted(entries, key=lambda k: k['microtime'], reverse=True)
        return entries

    # ------------------------------------------------------------------------------------------ #
304
    def __get_entries__(self, keys, channel):
305
306
307
        entries = []
        for key in keys:
            entry = self.db.hget(key,channel)
308
            entry = simplejson.dumps(entry.decode('utf-8'))
309
310
311
312
313

            if not (entry is None):
                try:
                    entry = entry.decode('utf-8').replace('None','"None"')
                    entry =  re.sub("########[^]]*########", lambda x:x.group(0).replace('\"','').replace('\'',''),entry.replace("\\\"","########").replace("\\'","++++++++").replace("'",'"').replace('u"','"').replace('"{','{').replace('}"','}')).replace("########","\"")
314
                    entry = simplejson.loads(entry)
315
316
317
318
319
320
                    entry['key'] = key
                    entries.append(entry)
                except:
                    pass

        return entries
321
322
323
324
325

    # ------------------------------------------------------------------------------------------ #
    def publish(self, channel, message):
        subscriber_count = self.db.execute_command('PUBSUB', 'NUMSUB', channel)

326
327
        if channel.lower().find("reply") < 0 and subscriber_count[1] == 0:
            raise Exception("No subscriber! Is Aura daemon running?")
328
329
330

        self.db.publish(channel, message)