示例#1
0
        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.warn(
                            _('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:
                LOG.exception(_('in fixed duration looping call'))
                done.send_exception(*sys.exc_info())
                return
            else:
                done.send(True)
示例#2
0
    def run_periodic_tasks(self, context, raise_on_error=False):
        """Tasks to be run at a periodic interval."""
        idle_for = DEFAULT_INTERVAL
        for task_name, task in self._periodic_tasks:
            full_task_name = '.'.join([self.__class__.__name__, task_name])

            now = timeutils.utcnow()
            spacing = self._periodic_spacing[task_name]
            last_run = self._periodic_last_run[task_name]

            # If a periodic task is _nearly_ due, then we'll run it early
            if spacing is not None and last_run is not None:
                due = last_run + datetime.timedelta(seconds=spacing)
                if not timeutils.is_soon(due, 0.2):
                    idle_for = min(idle_for, timeutils.delta_seconds(now, due))
                    continue

            if spacing is not None:
                idle_for = min(idle_for, spacing)

            LOG.debug(_("Running periodic task %(full_task_name)s"),
                      {"full_task_name": full_task_name})
            self._periodic_last_run[task_name] = timeutils.utcnow()

            try:
                task(self, context)
            except Exception as e:
                if raise_on_error:
                    raise
                LOG.exception(_("Error during %(full_task_name)s: %(e)s"),
                              {"full_task_name": full_task_name, "e": e})
            time.sleep(0)

        return idle_for
示例#3
0
        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.warn(_('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:
                LOG.exception(_('in fixed duration looping call'))
                done.send_exception(*sys.exc_info())
                return
            else:
                done.send(True)
示例#4
0
    def test_close_bill(self):
        self.bill_path = '/v2/bills/close'
        product = self.product_fixture.instance_products[0]
        resource_volume = 1
        resource_type = gring_const.RESOURCE_INSTANCE
        order_id = self.new_order_id()
        user_id = self.admin_account.user_id
        project_id = self.admin_account.project_id

        subs = self.create_subs_in_db(
            product, resource_volume, gring_const.STATE_RUNNING,
            order_id, project_id, user_id,
        )
        order = self.create_order_in_db(
            float(self.quantize(subs.unit_price)), subs.unit, user_id,
            project_id, resource_type, subs.type, order_id=order_id
        )

        start_time = self.utcnow()
        self.dbconn.create_bill(self.admin_req_context, order.order_id,
                                action_time=start_time)

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertBillMatchOrder(bill.as_dict(), order.as_dict())

        timedelta = datetime.timedelta(hours=0.5)
        end_time = start_time + timedelta
        bill_ref = self.new_bill_ref(order.order_id,
                                     self.datetime_to_str(end_time))
        resp = self.put(self.bill_path, headers=self.headers,
                        body=bill_ref, expected_status=200)
        bill_result = resp.json_body
        bill_ref.update({
            'user_id': user_id,
            'project_id': project_id,
            'region_id': order.region_id,
            'resource_id': order.resource_id,
        })
        self.assertNotEqual('-1', bill_result['type'])
        self.assertBillResultEqual(bill_ref, bill_result)

        # now order.status is changing
        order = self.dbconn.get_order(self.admin_req_context, order_id)
        self.assertEqual(gring_const.STATE_CHANGING, order.status)

        # calculate consumption
        total_price = self.quantize(
            float(order.unit_price) * (
                timeutils.delta_seconds(start_time, end_time) / 3600.0
            )
        )

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertBillMatchOrder(bill.as_dict(), order.as_dict())
        self.assertEqual(end_time, bill.end_time)
        self.assertEqual(gring_const.BILL_PAYED, bill.status)
        self.assertPriceEqual(total_price, bill.total_price)
    def run_periodic_tasks(self, context, raise_on_error=False):
        """Tasks to be run at a periodic interval."""
        idle_for = DEFAULT_INTERVAL
        for task_name, task in self._periodic_tasks:
            full_task_name = '.'.join([self.__class__.__name__, task_name])

            now = timeutils.utcnow()
            spacing = self._periodic_spacing[task_name]
            last_run = self._periodic_last_run[task_name]

            # If a periodic task is _nearly_ due, then we'll run it early
            if spacing is not None and last_run is not None:
                due = last_run + datetime.timedelta(seconds=spacing)
                if not timeutils.is_soon(due, 0.2):
                    idle_for = min(idle_for, timeutils.delta_seconds(now, due))
                    continue

            if spacing is not None:
                idle_for = min(idle_for, spacing)

            LOG.debug(_("Running periodic task %(full_task_name)s"),
                      {"full_task_name": full_task_name})
            self._periodic_last_run[task_name] = timeutils.utcnow()

            try:
                task(self, context)
            except Exception as e:
                if raise_on_error:
                    raise
                LOG.exception(_("Error during %(full_task_name)s: %(e)s"), {
                    "full_task_name": full_task_name,
                    "e": e
                })
            time.sleep(0)

        return idle_for
示例#6
0
    def test_close_bill(self):
        self.bill_path = '/v2/bills/close'
        product = self.product_fixture.instance_products[0]
        resource_volume = 1
        resource_type = gring_const.RESOURCE_INSTANCE
        order_id = self.new_order_id()
        user_id = self.admin_account.user_id
        project_id = self.admin_account.project_id

        subs = self.create_subs_in_db(
            product,
            resource_volume,
            gring_const.STATE_RUNNING,
            order_id,
            project_id,
            user_id,
        )
        order = self.create_order_in_db(float(self.quantize(subs.unit_price)),
                                        subs.unit,
                                        user_id,
                                        project_id,
                                        resource_type,
                                        subs.type,
                                        order_id=order_id)

        start_time = self.utcnow()
        self.dbconn.create_bill(self.admin_req_context,
                                order.order_id,
                                action_time=start_time)

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertBillMatchOrder(bill.as_dict(), order.as_dict())

        timedelta = datetime.timedelta(hours=0.5)
        end_time = start_time + timedelta
        bill_ref = self.new_bill_ref(order.order_id,
                                     self.datetime_to_str(end_time))
        resp = self.put(self.bill_path,
                        headers=self.headers,
                        body=bill_ref,
                        expected_status=200)
        bill_result = resp.json_body
        bill_ref.update({
            'user_id': user_id,
            'project_id': project_id,
            'region_id': order.region_id,
            'resource_id': order.resource_id,
        })
        self.assertNotEqual('-1', bill_result['type'])
        self.assertBillResultEqual(bill_ref, bill_result)

        # now order.status is changing
        order = self.dbconn.get_order(self.admin_req_context, order_id)
        self.assertEqual(gring_const.STATE_CHANGING, order.status)

        # calculate consumption
        total_price = self.quantize(
            float(order.unit_price) *
            (timeutils.delta_seconds(start_time, end_time) / 3600.0))

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertBillMatchOrder(bill.as_dict(), order.as_dict())
        self.assertEqual(end_time, bill.end_time)
        self.assertEqual(gring_const.BILL_PAYED, bill.status)
        self.assertPriceEqual(total_price, bill.total_price)