Python oslo_utils.timeutils.delta_seconds() Examples

The following are 16 code examples of oslo_utils.timeutils.delta_seconds(). 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_utils.timeutils , or try the search function .
Example #1
Source File: utils.py    From manila with Apache License 2.0 6 votes vote down vote up
def log_enter_exit(func):
    if not CONF.debug:
        return func

    def inner(self, *args, **kwargs):
        LOG.debug("Entering %(cls)s.%(method)s.",
                  {'cls': self.__class__.__name__,
                   'method': func.__name__})
        start = timeutils.utcnow()
        ret = func(self, *args, **kwargs)
        end = timeutils.utcnow()
        LOG.debug("Exiting %(cls)s.%(method)s. "
                  "Spent %(duration)s sec. "
                  "Return %(return)s.",
                  {'cls': self.__class__.__name__,
                   'duration': timeutils.delta_seconds(start, end),
                   'method': func.__name__,
                   'return': ret})
        return ret

    return inner 
Example #2
Source File: scheduling.py    From watcher with Apache License 2.0 6 votes vote down vote up
def get_service_status(self, context, service_id):
        service = objects.Service.get(context, service_id)
        last_heartbeat = (service.last_seen_up or service.updated_at or
                          service.created_at)
        if isinstance(last_heartbeat, str):
            # NOTE(russellb) If this service came in over rpc via
            # conductor, then the timestamp will be a string and needs to be
            # converted back to a datetime.
            last_heartbeat = timeutils.parse_strtime(last_heartbeat)
        else:
            # Objects have proper UTC timezones, but the timeutils comparison
            # below does not (and will fail)
            last_heartbeat = last_heartbeat.replace(tzinfo=None)
        elapsed = timeutils.delta_seconds(last_heartbeat, timeutils.utcnow())
        is_up = abs(elapsed) <= CONF.service_down_time
        if not is_up:
            LOG.warning('Seems service %(name)s on host %(host)s is down. '
                        'Last heartbeat was %(lhb)s. Elapsed time is %(el)s',
                        {'name': service.name,
                         'host': service.host,
                         'lhb': str(last_heartbeat), 'el': str(elapsed)})
            return objects.service.ServiceStatus.FAILED

        return objects.service.ServiceStatus.ACTIVE 
Example #3
Source File: service.py    From watcher with Apache License 2.0 6 votes vote down vote up
def _set_status(self, id):
        service = objects.Service.get(pecan.request.context, id)
        last_heartbeat = (service.last_seen_up or service.updated_at or
                          service.created_at)
        if isinstance(last_heartbeat, six.string_types):
            # NOTE(russellb) If this service came in over rpc via
            # conductor, then the timestamp will be a string and needs to be
            # converted back to a datetime.
            last_heartbeat = timeutils.parse_strtime(last_heartbeat)
        else:
            # Objects have proper UTC timezones, but the timeutils comparison
            # below does not (and will fail)
            last_heartbeat = last_heartbeat.replace(tzinfo=None)
        elapsed = timeutils.delta_seconds(last_heartbeat, timeutils.utcnow())
        is_up = abs(elapsed) <= CONF.service_down_time
        if not is_up:
            LOG.warning('Seems service %(name)s on host %(host)s is down. '
                        'Last heartbeat was %(lhb)s.'
                        'Elapsed time is %(el)s',
                        {'name': service.name,
                         'host': service.host,
                         'lhb': str(last_heartbeat), 'el': str(elapsed)})
            self._status = objects.service.ServiceStatus.FAILED
        else:
            self._status = objects.service.ServiceStatus.ACTIVE 
Example #4
Source File: servicegroup.py    From zun with Apache License 2.0 5 votes vote down vote up
def service_is_up(self, member):
        if not isinstance(member, objects.ZunService):
            raise TypeError
        if member.forced_down:
            return False

        last_heartbeat = (member.last_seen_up or
                          member.updated_at or member.created_at)
        now = timeutils.utcnow()
        elapsed = timeutils.delta_seconds(last_heartbeat, now)
        is_up = abs(elapsed) <= self.service_down_time
        return is_up 
Example #5
Source File: tasks.py    From designate with Apache License 2.0 5 votes vote down vote up
def __call__(self):
        pstart, pend = self._my_range()
        LOG.info(
            "Refreshing zones for shards %(start)s to %(end)s",
            {
                "start": pstart,
                "end": pend
            })

        ctxt = context.DesignateContext.get_admin_context()
        ctxt.all_tenants = True

        # each zone can have a different refresh / expire etc interval defined
        # in the SOA at the source / master servers
        criterion = {
            "type": "SECONDARY"
        }
        for zone in self._iter_zones(ctxt, criterion):
            # NOTE: If the zone isn't transferred yet, ignore it.
            if zone.transferred_at is None:
                continue

            now = timeutils.utcnow(True)

            transferred = timeutils.parse_isotime(zone.transferred_at)
            seconds = timeutils.delta_seconds(transferred, now)
            if seconds > zone.refresh:
                msg = "Zone %(id)s has %(seconds)d seconds since last " \
                      "transfer, executing AXFR"
                LOG.debug(msg, {"id": zone.id, "seconds": seconds})
                self.central_api.xfr_zone(ctxt, zone.id) 
Example #6
Source File: servicegroup.py    From magnum with Apache License 2.0 5 votes vote down vote up
def service_is_up(self, member):
        if not isinstance(member, magnum_service.MagnumService):
            raise TypeError
        if member.forced_down:
            return False

        last_heartbeat = (member.last_seen_up or
                          member.updated_at or member.created_at)
        now = timeutils.utcnow(True)
        elapsed = timeutils.delta_seconds(last_heartbeat, now)
        is_up = abs(elapsed) <= self.service_down_time
        return is_up 
Example #7
Source File: base.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def assert_timestamp_equal(self, first, second, msg=None):
        """Checks that two timestamps are equals.

        This relies on assertAlmostEqual to avoid rounding problem, and only
        checks up the first microsecond values.

        """
        return self.assertAlmostEqual(timeutils.delta_seconds(first, second),
                                      0.0,
                                      places=5, msg=msg) 
Example #8
Source File: health_manager.py    From senlin with Apache License 2.0 5 votes vote down vote up
def chase_up(start_time, interval, name='Poller'):
    """Utility function to check if there are missed intervals.

    :param start_time: A time object representing the starting time.
    :param interval: An integer specifying the time interval in seconds.
    :param name: Name of the caller for identification in logs.
    :returns: Number of seconds to sleep before next round.
    """
    end_time = timeutils.utcnow(True)
    elapsed = timeutils.delta_seconds(start_time, end_time)
    # check if we have missed any intervals?
    missed = int((elapsed - 0.0000001) / interval)
    if missed >= 1:
        LOG.warning("%s missed %s intervals for checking", name, missed)
    return (missed + 1) * interval - elapsed 
Example #9
Source File: base.py    From aodh with Apache License 2.0 5 votes vote down vote up
def assertTimestampEqual(self, first, second, msg=None):
        """Checks that two timestamps are equals.

        This relies on assertAlmostEqual to avoid rounding problem, and only
        checks up the first microsecond values.

        """
        return self.assertAlmostEqual(
            timeutils.delta_seconds(first, second),
            0.0,
            places=5) 
Example #10
Source File: loopingcall.py    From oslo.vmware with Apache License 2.0 5 votes vote down vote up
def start(self, interval, initial_delay=None):
        self._running = True
        done = event.Event()

        def _inner():
            if initial_delay:
                greenthread.sleep(initial_delay)

            try:
                while self._running:
                    start = timeutils.utcnow()
                    self.f(*self.args, **self.kw)
                    end = timeutils.utcnow()
                    if not self._running:
                        break
                    delay = interval - timeutils.delta_seconds(start, end)
                    if delay <= 0:
                        LOG.warning('task run outlasted interval '
                                    'by %s sec',
                                    -delay)
                    greenthread.sleep(delay if delay > 0 else 0)
            except LoopingCallDone as e:
                self.stop()
                done.send(e.retvalue)
            except Exception:
                done.send_exception(*sys.exc_info())
                return
            else:
                done.send(True)

        self.done = done

        greenthread.spawn_n(_inner)
        return self.done


# TODO(mikal): this class name is deprecated in Havana and should be removed
# in the I release 
Example #11
Source File: scheduled_operation_executor.py    From karbor with Apache License 2.0 5 votes vote down vote up
def resume_operation(self, operation_id, **kwargs):
        end_time = kwargs.get('end_time_for_run')
        now = datetime.utcnow()
        if not isinstance(end_time, datetime) or now > end_time:
            return

        window = int(timeutils.delta_seconds(now, end_time))
        param = {
            'operation_id': operation_id,
            'triggered_time': now,
            'expect_start_time': now,
            'window_time': window,
            'run_type': constants.OPERATION_RUN_TYPE_RESUME
        }
        self._execute_operation(operation_id, self._run_operation, param) 
Example #12
Source File: green_thread_executor.py    From karbor with Apache License 2.0 5 votes vote down vote up
def resume_operation(self, operation_id, **kwargs):
        end_time = kwargs.get('end_time_for_run')
        now = datetime.utcnow()
        if not isinstance(end_time, datetime) or now > end_time:
            return

        window = int(timeutils.delta_seconds(now, end_time))
        param = {
            'operation_id': operation_id,
            'triggered_time': now,
            'expect_start_time': now,
            'window_time': window,
            'run_type': constants.OPERATION_RUN_TYPE_RESUME
        }
        self._create_thread(self._run_operation, operation_id, param) 
Example #13
Source File: crontab_time.py    From karbor with Apache License 2.0 5 votes vote down vote up
def get_min_interval(self):
        try:
            t1 = self.compute_next_time(datetime.now())
            t2 = self.compute_next_time(t1)
            return timeutils.delta_seconds(t1, t2)
        except Exception:
            return None 
Example #14
Source File: calendar_time.py    From karbor with Apache License 2.0 5 votes vote down vote up
def get_min_interval(self):
        """Get minimum interval of two adjacent time points

        :return: int(seconds) or None

        """
        try:
            t1 = self.compute_next_time(datetime.now())
            t2 = self.compute_next_time(t1)
            return timeutils.delta_seconds(t1, t2)
        except Exception:
            return None 
Example #15
Source File: time_trigger.py    From karbor with Apache License 2.0 5 votes vote down vote up
def _start(self, first_run_time):
        self._running = True

        now = datetime.utcnow()
        initial_delay = 0 if first_run_time <= now else (
            int(timeutils.delta_seconds(now, first_run_time)))

        self._thread = eventlet.spawn_after(
            initial_delay, self._run, first_run_time)
        self._thread.link(self._on_done) 
Example #16
Source File: test_timeutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_delta_seconds(self):
        before = timeutils.utcnow()
        after = before + datetime.timedelta(days=7, seconds=59,
                                            microseconds=123456)
        self.assertAlmostEquals(604859.123456,
                                timeutils.delta_seconds(before, after))