Python oslo_service.loopingcall.FixedIntervalLoopingCall() Examples

The following are 30 code examples of oslo_service.loopingcall.FixedIntervalLoopingCall(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_service.loopingcall , or try the search function .
Example #1
Source File: utils.py    From karbor with Apache License 2.0 6 votes vote down vote up
def status_poll(get_status_func, interval, success_statuses=set(),
                failure_statuses=set(), ignore_statuses=set(),
                ignore_unexpected=False):
    def _poll():
        status = get_status_func()
        if status in success_statuses:
            raise loopingcall.LoopingCallDone(retvalue=True)
        if status in failure_statuses:
            raise loopingcall.LoopingCallDone(retvalue=False)
        if status in ignore_statuses:
            return
        if ignore_unexpected is False:
            raise loopingcall.LoopingCallDone(retvalue=False)

    loop = loopingcall.FixedIntervalLoopingCall(_poll)
    return loop.start(interval=interval, initial_delay=interval).wait() 
Example #2
Source File: lib_base.py    From manila with Apache License 2.0 6 votes vote down vote up
def _start_periodic_tasks(self):

        # Run the task once in the current thread so prevent a race with
        # the first invocation of get_share_stats.
        self._update_ssc_info()

        # Start the task that updates the slow-changing storage service catalog
        ssc_periodic_task = loopingcall.FixedIntervalLoopingCall(
            self._update_ssc_info)
        ssc_periodic_task.start(interval=self.SSC_UPDATE_INTERVAL_SECONDS,
                                initial_delay=self.SSC_UPDATE_INTERVAL_SECONDS)

        # Start the task that logs autosupport (EMS) data to the controller
        ems_periodic_task = loopingcall.FixedIntervalLoopingCall(
            self._handle_ems_logging)
        ems_periodic_task.start(interval=self.AUTOSUPPORT_INTERVAL_SECONDS,
                                initial_delay=0)

        # Start the task that runs other housekeeping tasks, such as deletion
        # of previously soft-deleted storage artifacts.
        housekeeping_periodic_task = loopingcall.FixedIntervalLoopingCall(
            self._handle_housekeeping_tasks)
        housekeeping_periodic_task.start(
            interval=self.HOUSEKEEPING_INTERVAL_SECONDS, initial_delay=0) 
Example #3
Source File: aws_utils.py    From openstack-omni with Apache License 2.0 6 votes vote down vote up
def _create_sec_grp_rules(self, secgrp, rules):
        ingress, egress = self._convert_openstack_rules_to_vpc(rules)
        def _wait_for_state(start_time):
            current_time = time.time()

            if current_time - start_time > self._wait_time_sec:
                raise loopingcall.LoopingCallDone(False)
            try:
                self._refresh_sec_grp_rules(secgrp, ingress, egress)
            except Exception as ex:
                LOG.exception('Error creating security group rules. Retrying.')
                return
            raise loopingcall.LoopingCallDone(True)
        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_state,
                                                     time.time())
        return timer.start(interval=5).wait() 
Example #4
Source File: ec2driver.py    From openstack-omni with Apache License 2.0 6 votes vote down vote up
def _wait_for_image_state(self, ami_id, desired_state):
        """Timer to wait for the image/snapshot to reach a desired state
        :params:ami_id: correspoding image id in Amazon
        :params:desired_state: the desired new state of the image to be in.
        """
        def _wait_for_state():
            """Called at an interval until the AMI image is available."""
            try:
                images = self.ec2_conn.get_all_images(image_ids=[ami_id], owners=None,
                                                      executable_by=None, filters=None, dry_run=None)
                state = images[0].state
                if state == desired_state:
                    LOG.info("Image has changed state to %s." % desired_state)
                    raise loopingcall.LoopingCallDone()
            except boto_exc.EC2ResponseError:
                pass

        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_state)
        timer.start(interval=0.5).wait() 
Example #5
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 6 votes vote down vote up
def test_interval_adjustment(self, elapsed_mock, sleep_mock):
        """Ensure the interval is adjusted to account for task duration."""
        self.num_runs = 3

        second = 1
        smidgen = 0.01

        elapsed_mock.side_effect = [second - smidgen,
                                    second + second,
                                    second + smidgen,
                                    ]
        timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_zero)
        timer.start(interval=1.01).wait()

        expected_calls = [0.02, 0.00, 0.00]
        for i, call in enumerate(sleep_mock.call_args_list):
            expected = expected_calls[i]
            args, kwargs = call
            actual = args[0]
            message = ('Call #%d, expected: %s, actual: %s' %
                       (i, expected, actual))
            self.assertAlmostEqual(expected, actual, message=message) 
Example #6
Source File: service.py    From tacker with Apache License 2.0 6 votes vote down vote up
def start(self):
        self.manager.start()
        self.manager.init_host()
        super(Service, self).start()
        if self.report_interval:
            pulse = loopingcall.FixedIntervalLoopingCall(self.report_state)
            pulse.start(interval=self.report_interval,
                        initial_delay=self.report_interval)
            self.timers.append(pulse)

        if self.periodic_interval:
            if self.periodic_fuzzy_delay:
                initial_delay = random.randint(0, self.periodic_fuzzy_delay)
            else:
                initial_delay = None

            periodic = loopingcall.FixedIntervalLoopingCall(
                self.periodic_tasks)
            periodic.start(interval=self.periodic_interval,
                           initial_delay=initial_delay)
            self.timers.append(periodic)
        self.manager.after_start() 
Example #7
Source File: swift_bank_plugin.py    From karbor with Apache License 2.0 6 votes vote down vote up
def connection(self):
        if not self._connection:
            _connection = self._setup_connection()
            # create container
            try:
                _connection.put_container(self.bank_object_container)
                _connection.put_container(self.bank_leases_container)
            except SwiftConnectionFailed as err:
                LOG.error("bank plugin create container failed.")
                raise exception.CreateContainerFailed(reason=err)
            self._connection = _connection

            # acquire lease
            try:
                self.acquire_lease()
            except exception.AcquireLeaseFailed:
                LOG.error("bank plugin acquire lease failed.")
                raise

            # start renew lease
            renew_lease_loop = loopingcall.FixedIntervalLoopingCall(
                self.renew_lease)
            renew_lease_loop.start(interval=self.lease_renew_window,
                                   initial_delay=self.lease_renew_window)
        return self._connection 
Example #8
Source File: bgp_dragent.py    From neutron-dynamic-routing with Apache License 2.0 6 votes vote down vote up
def __init__(self, host, conf=None):
        super(BgpDrAgentWithStateReport,
              self).__init__(host, conf)
        self.state_rpc = agent_rpc.PluginReportStateAPI(topics.REPORTS)
        self.agent_state = {
            'agent_type': bgp_consts.AGENT_TYPE_BGP_ROUTING,
            'binary': 'neutron-bgp-dragent',
            'configurations': {},
            'host': host,
            'topic': bgp_consts.BGP_DRAGENT,
            'start_flag': True}
        report_interval = cfg.CONF.AGENT.report_interval
        if report_interval:
            self.heartbeat = loopingcall.FixedIntervalLoopingCall(
                self._report_state)
            self.heartbeat.start(interval=report_interval) 
Example #9
Source File: time_trigger_multi_node.py    From karbor with Apache License 2.0 6 votes vote down vote up
def __init__(self, trigger_id, trigger_property, executor):
        super(TimeTrigger, self).__init__(
            trigger_id, trigger_property, executor)

        self._trigger_property = self.check_trigger_definition(
            trigger_property)

        timer = self._get_timer(self._trigger_property)
        first_run_time = self._compute_next_run_time(
            datetime.utcnow(), self._trigger_property['end_time'], timer)
        LOG.debug("first_run_time: %s", first_run_time)

        self._trigger_execution_new(self._id, first_run_time)

        if not self.__class__._loopingcall:
            self.__class__._loopingcall = loopingcall.FixedIntervalLoopingCall(
                self._loop)
            self.__class__._loopingcall.start(
                interval=CONF.trigger_poll_interval,
                stop_on_exception=False,
            )

        self._register() 
Example #10
Source File: ipsec.py    From neutron-vpnaas with Apache License 2.0 6 votes vote down vote up
def __init__(self, vpn_service, host):
        # TODO(pc_m) Replace vpn_service with config arg, once all driver
        # implementations no longer need vpn_service.
        self.conf = vpn_service.conf
        self.host = host
        self.conn = n_rpc.Connection()
        self.context = context.get_admin_context_without_session()
        self.topic = topics.IPSEC_AGENT_TOPIC
        node_topic = '%s.%s' % (self.topic, self.host)

        self.processes = {}
        self.routers = {}
        self.process_status_cache = {}

        self.endpoints = [self]
        self.conn.create_consumer(node_topic, self.endpoints, fanout=False)
        self.conn.consume_in_threads()
        self.agent_rpc = IPsecVpnDriverApi(topics.IPSEC_DRIVER_TOPIC)
        self.process_status_cache_check = loopingcall.FixedIntervalLoopingCall(
            self.report_status, self.context)
        self.process_status_cache_check.start(
            interval=self.conf.ipsec.ipsec_status_check_interval) 
Example #11
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_return_true(self):
        def _raise_it():
            raise loopingcall.LoopingCallDone(True)

        timer = loopingcall.FixedIntervalLoopingCall(_raise_it)
        self.assertTrue(timer.start(interval=0.5).wait()) 
Example #12
Source File: df_bgp_service.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, nb_api):
        super(BGPService, self).__init__()
        self.initialize_driver()
        self.db_store = db_store.get_instance()

        self.nb_api = nb_api

        self.sync = sync.Sync(
            nb_api=self.nb_api,
            update_cb=self.update_model_object,
            delete_cb=self.delete_model_object,
            selective=False,
        )
        self.bgp_pulse = loopingcall.FixedIntervalLoopingCall(
            self.sync_data_from_nb_db) 
Example #13
Source File: df_local_controller.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, chassis_name, nb_api):
        self.db_store = db_store.get_instance()
        self._queue = queue.PriorityQueue()
        # pending_id -> (model, pender_id)
        #       'pending_id' is the ID of the object for which we are waiting.
        #       'model' and 'pender_id' are the model and the ID of the object
        #       which is waiting for the object described by 'pending_id'
        self._pending_objects = collections.defaultdict(set)

        self.chassis_name = chassis_name
        self.nb_api = nb_api
        self.nb_api.set_db_change_callback(self.db_change_callback)
        self.ip = cfg.CONF.df.local_ip
        # Virtual tunnel port support multiple tunnel types together
        self.tunnel_types = cfg.CONF.df.tunnel_types
        self.neutron_notifier = None
        if cfg.CONF.df.enable_neutron_notifier:
            self.neutron_notifier = df_utils.load_driver(
                     cfg.CONF.df.neutron_notifier,
                     df_utils.DF_NEUTRON_NOTIFIER_DRIVER_NAMESPACE)
        self.switch_backend = df_utils.load_driver(
            cfg.CONF.df.switch_backend,
            df_utils.DF_SWITCH_BACKEND_DRIVER_NAMESPACE,
            nb_api, cfg.CONF.df.management_ip)

        self.switch_backend.initialize(self.db_change_callback,
                                       self.neutron_notifier)
        self.topology = None
        self.enable_selective_topo_dist = \
            cfg.CONF.df.enable_selective_topology_distribution
        self._sync = sync.Sync(
            nb_api=self.nb_api,
            update_cb=self.update,
            delete_cb=self.delete,
            selective=self.enable_selective_topo_dist,
        )
        self._sync_pulse = loopingcall.FixedIntervalLoopingCall(
            self._submit_sync_event)

        self.sync_rate_limiter = df_utils.RateLimiter(
                max_rate=1, time_unit=db_common.DB_SYNC_MINIMUM_INTERVAL) 
Example #14
Source File: active_port_detection.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def _periodic_send_arp_request(self):
        """Spawn a thread to periodically to detect active node among
        ports with allowed-address-pairs.
        """
        periodic = loopingcall.FixedIntervalLoopingCall(
            self._send_arp_request_callback)
        periodic.start(interval=self.dection_interval_time) 
Example #15
Source File: service.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def run_status_reporter(callback):
    def report_status():
        try:
            callback()
        except Exception:
            LOG.exception("Failed to report status")
        return True

    timer = loopingcall.FixedIntervalLoopingCall(report_status)
    timer.start(interval=cfg.CONF.df.report_interval) 
Example #16
Source File: heartbeat_emitter.py    From designate with Apache License 2.0 5 votes vote down vote up
def __init__(self, service_name, **kwargs):
        super(HeartbeatEmitter, self).__init__()

        self._status = 'UP'
        self._stats = {}
        self._capabilities = {}

        self._service_name = service_name
        self._hostname = CONF.host

        self._timer = loopingcall.FixedIntervalLoopingCall(
            self._emit_heartbeat
        ) 
Example #17
Source File: redis_mgt.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(RedisMgt, self).__init__()
        self.default_node = None
        self.cluster_nodes = {}
        self.cluster_slots = None
        self.calc_key = redis_calckey.key2slot
        self.master_list = []
        self._loopingcall = loopingcall.FixedIntervalLoopingCall(self.run)
        self.db_callback = None
        self.db_recover_callback = None
        self.subscriber = None
        self.publisher = None 
Example #18
Source File: threadgroup.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def add_timer(self, interval, callback, initial_delay=None,
                  *args, **kwargs):
        """Add a timer with a fixed period.

        .. warning::
            Passing arguments to the callback function is deprecated. Use the
            :func:`add_timer_args` method to pass arguments for the callback
            function.

        :param interval: The minimum period in seconds between calls to the
                         callback function.
        :param callback: The callback function to run when the timer is
                         triggered.
        :param initial_delay: The delay in seconds before first triggering the
                              timer. If not set, the timer is liable to be
                              scheduled immediately.
        :returns: an :class:`oslo_service.loopingcall.FixedIntervalLoopingCall`
                  instance
        """
        if args or kwargs:
            warnings.warn("Calling add_timer() with arguments to the callback "
                          "function is deprecated. Use add_timer_args() "
                          "instead.",
                          DeprecationWarning)
        return self.add_timer_args(interval, callback, args, kwargs,
                                   initial_delay=initial_delay) 
Example #19
Source File: threadgroup.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def add_timer_args(self, interval, callback, args=None, kwargs=None,
                       initial_delay=None, stop_on_exception=True):
        """Add a timer with a fixed period.

        :param interval: The minimum period in seconds between calls to the
                         callback function.
        :param callback: The callback function to run when the timer is
                         triggered.
        :param args: A list of positional args to the callback function.
        :param kwargs: A dict of keyword args to the callback function.
        :param initial_delay: The delay in seconds before first triggering the
                              timer. If not set, the timer is liable to be
                              scheduled immediately.
        :param stop_on_exception: Pass ``False`` to have the timer continue
                                  running even if the callback function raises
                                  an exception.
        :returns: an :class:`oslo_service.loopingcall.FixedIntervalLoopingCall`
                  instance
        """
        args = args or []
        kwargs = kwargs or {}
        pulse = loopingcall.FixedIntervalLoopingCall(callback, *args, **kwargs)
        pulse.start(interval=interval,
                    initial_delay=initial_delay,
                    stop_on_exception=stop_on_exception)
        self.timers.append(pulse)
        return pulse 
Example #20
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_monotonic_timer(self):
        def _raise_it():
            clock = eventlet.hubs.get_hub().clock
            ok = (clock == time.monotonic)
            raise loopingcall.LoopingCallDone(ok)

        timer = loopingcall.FixedIntervalLoopingCall(_raise_it)
        self.assertTrue(timer.start(interval=0.5).wait()) 
Example #21
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_return_false(self):
        def _raise_it():
            raise loopingcall.LoopingCallDone(False)

        timer = loopingcall.FixedIntervalLoopingCall(_raise_it)
        self.assertFalse(timer.start(interval=0.5).wait()) 
Example #22
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_do_not_stop_on_exception(self):
        self.useFixture(fixture.SleepFixture())
        self.num_runs = 2

        timer = loopingcall.FixedIntervalLoopingCall(self._raise_and_then_done)
        res = timer.start(interval=0.5, stop_on_exception=False).wait()
        self.assertFalse(res) 
Example #23
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_no_double_start(self):
        wait_ev = greenthreading.Event()

        def _run_forever_until_set():
            if wait_ev.is_set():
                raise loopingcall.LoopingCallDone(True)

        timer = loopingcall.FixedIntervalLoopingCall(_run_forever_until_set)
        timer.start(interval=0.01)

        self.assertRaises(RuntimeError, timer.start, interval=0.01)

        wait_ev.set()
        timer.wait() 
Example #24
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_no_double_stop(self):
        def _raise_it():
            raise loopingcall.LoopingCallDone(False)

        timer = loopingcall.FixedIntervalLoopingCall(_raise_it)
        timer.start(interval=0.5)

        timer.stop()
        timer.stop() 
Example #25
Source File: test_loopingcall.py    From oslo.service with Apache License 2.0 5 votes vote down vote up
def test_repeat(self):
        self.useFixture(fixture.SleepFixture())
        self.num_runs = 2

        timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_zero)
        self.assertFalse(timer.start(interval=0.5).wait()) 
Example #26
Source File: s3_bank_plugin.py    From karbor with Apache License 2.0 5 votes vote down vote up
def connection(self):
        if not self._connection:
            _connection = self._setup_connection()
            # create bucket
            try:
                _connection.create_bucket(Bucket=self.bank_object_bucket)
                _connection.create_bucket(Bucket=self.bank_leases_bucket)
            except S3ConnectionFailed as err:
                LOG.error("bank plugin create bucket failed.")
                raise exception.CreateBucketrFailed(reason=err)
            self._connection = _connection

            # acquire lease
            try:
                self.acquire_lease()
            except exception.AcquireLeaseFailed:
                LOG.error("bank plugin acquire lease failed.")
                raise

            # start renew lease
            renew_lease_loop = loopingcall.FixedIntervalLoopingCall(
                self.renew_lease
            )
            renew_lease_loop.start(
                interval=self.lease_renew_window,
                initial_delay=self.lease_renew_window
            )
        return self._connection 
Example #27
Source File: instance_failure.py    From masakari with Apache License 2.0 5 votes vote down vote up
def execute(self, instance_uuid):
        def _wait_for_active():
            new_instance = self.novaclient.get_server(self.context,
                                                      instance_uuid)
            vm_state = getattr(new_instance, 'OS-EXT-STS:vm_state')
            if vm_state == 'active':
                raise loopingcall.LoopingCallDone()

        periodic_call = loopingcall.FixedIntervalLoopingCall(
            _wait_for_active)
        try:
            msg = "Confirming instance '%s' vm_state is ACTIVE" % instance_uuid
            self.update_details(msg)

            # add a timeout to the periodic call.
            periodic_call.start(interval=CONF.verify_interval)
            etimeout.with_timeout(CONF.wait_period_after_power_on,
                                  periodic_call.wait)

            msg = "Confirmed instance '%s' vm_state is ACTIVE" % instance_uuid
            self.update_details(msg, 1.0)
        except etimeout.Timeout:
            msg = "Failed to start instance %(instance)s" % {
                'instance': instance_uuid
            }
            self.update_details(msg, 1.0)
            raise exception.InstanceRecoveryFailureException(
                message=msg)
        finally:
            # stop the periodic call, in case of exceptions or Timeout.
            periodic_call.stop() 
Example #28
Source File: opencontrail.py    From zun with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self._vrouter_semaphore = eventlet.semaphore.Semaphore()
        self._vrouter_client = ContrailVRouterApi(
            doconnect=True, semaphore=self._vrouter_semaphore)
        timer = loopingcall.FixedIntervalLoopingCall(self._keep_alive)
        timer.start(interval=2) 
Example #29
Source File: vmops.py    From compute-hyperv with Apache License 2.0 5 votes vote down vote up
def _wait_for_power_off(self, instance_name, time_limit):
        """Waiting for a VM to be in a disabled state.

           :return: True if the instance is shutdown within time_limit,
                    False otherwise.
        """

        desired_vm_states = [os_win_const.HYPERV_VM_STATE_DISABLED]

        def _check_vm_status(instance_name):
            if self._get_vm_state(instance_name) in desired_vm_states:
                raise loopingcall.LoopingCallDone()

        periodic_call = loopingcall.FixedIntervalLoopingCall(_check_vm_status,
                                                             instance_name)

        try:
            # add a timeout to the periodic call.
            periodic_call.start(interval=SHUTDOWN_TIME_INCREMENT)
            etimeout.with_timeout(time_limit, periodic_call.wait)
        except etimeout.Timeout:
            # VM did not shutdown in the expected time_limit.
            return False
        finally:
            # stop the periodic call, in case of exceptions or Timeout.
            periodic_call.stop()

        return True 
Example #30
Source File: manager.py    From networking-l2gw with Apache License 2.0 5 votes vote down vote up
def __init__(self, conf=None):
        super(OVSDBManager, self).__init__(conf)
        self._extract_ovsdb_config(conf)
        self.enable_manager = cfg.CONF.ovsdb.enable_manager
        periodic_interval = self.conf.ovsdb.periodic_interval
        if self.enable_manager:
            self.ovsdb_fd = None
            self._sock_open_connection()
            self.looping_task_ovsdb_states = (
                loopingcall.FixedIntervalLoopingCall(self._send_ovsdb_states))
            self.looping_task_ovsdb_states.start(interval=periodic_interval)
        else:
            self.looping_task = loopingcall.FixedIntervalLoopingCall(
                self._connect_to_ovsdb_server)
            self.looping_task.start(interval=periodic_interval)