Skip to content

Commit

Permalink
prevent the apply of the same config many times.
Browse files Browse the repository at this point in the history
  • Loading branch information
darius BERNARD committed Feb 28, 2017
1 parent 3686472 commit 1a25445
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
7 changes: 7 additions & 0 deletions dynamic_logging/models.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import datetime
import hashlib
import json
import logging
import logging.config
Expand Down Expand Up @@ -165,6 +166,12 @@ def config(self, val):
}
self.config_json = json.dumps(res)

def get_hash(self):
h = hashlib.sha256()
h.update((u'%s' % self.pk).encode('utf-8'))
h.update(self.config_json.encode('utf-8'))
return h.digest()

def apply(self, trigger=None):
"""
apply the current config to the global logging system.
Expand Down
12 changes: 10 additions & 2 deletions dynamic_logging/scheduler.py
Expand Up @@ -29,6 +29,8 @@ def __init__(self):
"""
:type: Trigger
"""
self.current_config_hash = None

self.start_thread = True
"""
a bool to prevent the threads to start, for testing purpose
Expand Down Expand Up @@ -220,8 +222,14 @@ def wake(self, trigger, date):
self.set_next_wake(next_trigger, at)

def apply(self, trigger):
logger.debug('applying %s', trigger, extra={'trigger': trigger, 'config': trigger.config.config_json})
trigger.apply()
hash_config = trigger.config.get_hash()
if self.current_config_hash == hash_config:
logger.debug("not applying currently active config %s", trigger,
extra={'trigger': trigger, 'config': trigger.config.config_json})
else:
logger.debug('applying %s', trigger, extra={'trigger': trigger, 'config': trigger.config.config_json})
trigger.apply()
self.current_config_hash = hash_config
self.current_trigger = trigger
self.trigger_applied.set()

Expand Down
16 changes: 16 additions & 0 deletions dynamic_logging/tests.py
Expand Up @@ -670,6 +670,22 @@ def test_loggers_creation(self):
},
})

def test_apply_by_scheduler_same_config(self):
called = []

c = Config(name="lol", config_json='{}')
t = Trigger(name='lol', config=c, start_date=None, end_date=None)
c.apply = lambda tt: called.append(tt)
main_scheduler.apply(t)
self.assertEqual(called, [t])
main_scheduler.apply(t)
self.assertEqual(called, [t])
c.config_json = ''
main_scheduler.apply(t)
self.assertEqual(called, [t, t])
main_scheduler.apply(t)
self.assertEqual(called, [t, t])


class TestTag(TestCase):
def test_display_config_current_auto(self):
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Expand Up @@ -4,4 +4,5 @@ sphinx
tox
isort
flake8
pika
-r test_requirements.txt

0 comments on commit 1a25445

Please sign in to comment.