def create_lock_manager(self): """ Create a new LockManager. Tries to create a Redis LockManager, but falls back to python's internal threading lock implementation. Exits if distributing poller is enabled and a Redis LockManager cannot be created. :return: Instance of LockManager """ try: return LibreNMS.RedisLock( namespace='librenms.lock', host=self.config.redis_host, port=self.config.redis_port, db=self.config.redis_db, password=self.config.redis_pass, unix_socket_path=self.config.redis_socket, sentinel=self.config.redis_sentinel, sentinel_service=self.config.redis_sentinel_service, socket_timeout=self.config.redis_timeout) except ImportError: if self.config.distributed: critical( "ERROR: Redis connection required for distributed polling") critical( "Please install redis-py, either through your os software repository or from PyPI" ) self.exit(2) except Exception as e: if self.config.distributed: critical( "ERROR: Redis connection required for distributed polling") critical("Could not connect to Redis. {}".format(e)) self.exit(2) return LibreNMS.ThreadingLock()
def test_redis_lock(self): if 'redis' not in sys.modules: self.assertTrue(True, 'Skipped Redis tests') else: rc = redis.Redis() rc.delete('lock:redis.lock') # make sure no previous data exists lm = LibreNMS.RedisLock(namespace='lock') thread = threading.Thread(target=self.lock_thread, args=(lm, 'redis.lock', 2, 1)) thread.daemon = True thread.start() sleep(0.05) self.assertFalse(lm.lock('redis.lock', 'main_thread', 1), "Acquired lock when it is held by thread") self.assertFalse(lm.unlock('redis.lock', 'main_thread'), "Unlocked lock main doesn't own") sleep(1.1) self.assertTrue( lm.lock('redis.lock', 'main_thread', 1), "Could not acquire lock previously held by thread") self.assertFalse(lm.lock('redis.lock', 'main_thread', 1), "Relocked an existing lock") self.assertTrue(lm.lock('redis.lock', 'main_thread', 1, True), "Could not re-lock a lock main owns") self.assertTrue(lm.unlock('redis.lock', 'main_thread'), "Could not unlock lock main holds") self.assertFalse(lm.unlock('redis.lock', 'main_thread'), "Unlocked an unlocked lock?")