Esempio n. 1
0
    def test_get_price_of_floatingip_with_unit_price(self):
        product = self.product_fixture.ip_products[0]

        price_ref = self.query_price(product, 1)
        hourly_price = pricing.calculate_price(1, product.unit_price)
        self.assertDecimalEqual(hourly_price, price_ref['unit_price'])

        price_ref = self.query_price(product, 10)
        hourly_price = pricing.calculate_price(10, product.unit_price)
        self.assertDecimalEqual(hourly_price, price_ref['unit_price'])
Esempio n. 2
0
    def test_get_price_of_floatingip_with_unit_price(self):
        product = self.product_fixture.ip_products[0]

        price_ref = self.query_price(product, 1)
        hourly_price = pricing.calculate_price(1, product.unit_price)
        self.assertDecimalEqual(hourly_price, price_ref['unit_price'])

        price_ref = self.query_price(product, 10)
        hourly_price = pricing.calculate_price(10, product.unit_price)
        self.assertDecimalEqual(hourly_price, price_ref['unit_price'])
Esempio n. 3
0
    def process_notification(self, message, state=None):
        payload = get_payload(message)
        LOG.warn('Do action for event: %s, resource_id: %s',
                 message['event_type'], payload['id'])

        self.send_email_notification(message)

        # Generate uuid of an order
        order_id = uuidutils.generate_uuid()

        unit_price = 0
        unit = 'hour'

        # Create subscriptions for this order
        for ext in self.product_items.extensions:
            if ext.name.startswith('suspend'):
                sub = ext.obj.create_subscription(message, order_id,
                                                  type=const.STATE_SUSPEND)
                if sub and state == const.STATE_SUSPEND:
                    price_data = None
                    if 'extra' in sub and sub['extra']:
                        try:
                            extra_data = jsonutils.loads(sub['extra'])
                            price_data = extra_data.get('price', None)
                        except (Exception):
                            LOG.warning('Decode subscription["extra"] failed')

                    unit_price += pricing.calculate_price(
                        sub['quantity'], sub['unit_price'], price_data)
            elif ext.name.startswith('running'):
                sub = ext.obj.create_subscription(message, order_id,
                                                  type=const.STATE_RUNNING)
                if sub and (not state or state == const.STATE_RUNNING):
                    price_data = None
                    if 'extra' in sub and sub['extra']:
                        try:
                            extra_data = jsonutils.loads(sub['extra'])
                            price_data = extra_data.get('price', None)
                        except (Exception):
                            LOG.warning('Decode subscription["extra"] failed')

                    unit_price += pricing.calculate_price(
                        sub['quantity'], sub['unit_price'], price_data)

        # Create an order for this instance
        self.create_order(order_id, unit_price, unit, message, state=state)

        # Notify master, just give master messages it needs
        remarks = 'Floating IP Has Been Created.'
        action_time = message['timestamp']
        if state:
            self.resource_created_again(order_id, action_time, remarks)
        else:
            self.resource_created(order_id, action_time, remarks)
Esempio n. 4
0
    def process_notification(self, message, state=None):
        payload = get_payload(message)
        LOG.warn('Do action for event: %s, resource_id: %s',
                 message['event_type'], payload['id'])

        self.send_email_notification(message)

        # Generate uuid of an order
        order_id = uuidutils.generate_uuid()

        unit_price = 0
        unit = 'hour'

        # Create subscriptions for this order
        for ext in self.product_items.extensions:
            if ext.name.startswith('suspend'):
                sub = ext.obj.create_subscription(message, order_id,
                                                  type=const.STATE_SUSPEND)
                if sub and state == const.STATE_SUSPEND:
                    price_data = None
                    if 'extra' in sub and sub['extra']:
                        try:
                            extra_data = jsonutils.loads(sub['extra'])
                            price_data = extra_data.get('price', None)
                        except (Exception):
                            LOG.warning('Decode subscription["extra"] failed')

                    unit_price += pricing.calculate_price(
                        sub['quantity'], sub['unit_price'], price_data)
            elif ext.name.startswith('running'):
                sub = ext.obj.create_subscription(message, order_id,
                                                  type=const.STATE_RUNNING)
                if sub and (not state or state == const.STATE_RUNNING):
                    price_data = None
                    if 'extra' in sub and sub['extra']:
                        try:
                            extra_data = jsonutils.loads(sub['extra'])
                            price_data = extra_data.get('price', None)
                        except (Exception):
                            LOG.warning('Decode subscription["extra"] failed')

                    unit_price += pricing.calculate_price(
                        sub['quantity'], sub['unit_price'], price_data)

        # Create an order for this instance
        self.create_order(order_id, unit_price, unit, message, state=state)

        # Notify master, just give master messages it needs
        remarks = 'Floating IP Has Been Created.'
        action_time = message['timestamp']
        if state:
            self.resource_created_again(order_id, action_time, remarks)
        else:
            self.resource_created(order_id, action_time, remarks)
Esempio n. 5
0
 def test_get_price_of_two_products(self):
     quantity = 1
     product1 = self.product_fixture.instance_products[0]
     product2 = self.product_fixture.instance_products[1]
     price1 = pricing.calculate_price(quantity, product1.unit_price)
     price2 = pricing.calculate_price(quantity, product2.unit_price)
     purchase1 = self.build_purchase(
         product1.name, product1.service, product1.region_id, quantity)
     purchase2 = self.build_purchase(
         product2.name, product2.service, product2.region_id, quantity)
     query_url = self.build_price_query_url([purchase1, purchase2])
     resp = self.get(query_url, headers=self.admin_headers)
     price_ref = resp.json_body
     self.assertDecimalEqual(price1 + price2, price_ref['unit_price'])
Esempio n. 6
0
 def test_get_price_of_two_products(self):
     quantity = 1
     product1 = self.product_fixture.instance_products[0]
     product2 = self.product_fixture.instance_products[1]
     price1 = pricing.calculate_price(quantity, product1.unit_price)
     price2 = pricing.calculate_price(quantity, product2.unit_price)
     purchase1 = self.build_purchase(product1.name, product1.service,
                                     product1.region_id, quantity)
     purchase2 = self.build_purchase(product2.name, product2.service,
                                     product2.region_id, quantity)
     query_url = self.build_price_query_url([purchase1, purchase2])
     resp = self.get(query_url, headers=self.admin_headers)
     price_ref = resp.json_body
     self.assertDecimalEqual(price1 + price2, price_ref['unit_price'])
Esempio n. 7
0
    def _test_volume_create_unit_price(self, size, volume_type=None, is_segmented_price=False):
        if is_segmented_price:
            product = self._set_product_volume_to_segmented_price(volume_type)
            extra = jsonutils.loads(product.extra)
            price = pricing.calculate_price(size, product.unit_price, extra["price"])
        else:
            product = self._get_product_by_volume_type(volume_type)
            price = pricing.calculate_price(size, product.unit_price)

        resource_id = self._create_volume(volume_type, size, self.project_id)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context, resource_id)
        self.assertDecimalEqual(price, order.unit_price)

        bill = self.dbconn.get_latest_bill(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(price, bill.unit_price)
Esempio n. 8
0
    def _test_volume_resize_end(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # original size
        resource_id = self._create_volume(volume_type, self.size, self.project_id, timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context, resource_id)
        bill1 = self.dbconn.get_latest_bill(self.admin_req_context, order.order_id)

        # change to new size
        payload = self.build_volume_payload(volume_type, self.new_size, self.project_id, volume_id=resource_id)
        message = self.build_notification_message(self.user_id, self.event_resized, payload, timestamp=end_time)
        handle = volume.VolumeResizeEnd()
        handle.process_notification(message)

        price = pricing.calculate_price(self.new_size, product.unit_price)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(price, order.unit_price)

        subs_list = list(self.dbconn.get_subscriptions_by_order_id(self.admin_req_context, order.order_id))
        self.assertEqual(1, len(subs_list))
        for subs in subs_list:
            self.assertEqual(self.new_size, subs.quantity)

        bill1 = self.dbconn.get_bill(self.admin_req_context, bill1.bill_id)
        self.assertEqual(self.datetime_to_str(end_time), self.datetime_to_str(bill1.end_time))
        bill2 = self.dbconn.get_latest_bill(self.admin_req_context, order.order_id)
        self.assertEqual(self.datetime_to_str(end_time), self.datetime_to_str(bill2.start_time))
        self.assertDecimalEqual(price, bill2.unit_price)
Esempio n. 9
0
    def get_unit_price(self, order_id, message):
        """Get unit price of this resource

        As the resource has subscribed to the product, so we should
        calculate price from the subscriptions instead of the product.
        """
        c = self.get_collection(message)
        product = self.gclient.get_product(c.product_name, c.service,
                                           c.region_id)

        if not product:
            return 0

        subs = self.gclient.get_subscriptions(order_id,
                                              product_id=product['product_id'])
        if subs:
            sub = subs[0]
        else:
            LOG.warn("The order %s has no subscriptions" % order_id)
            return 0

        if 'extra' in sub:
            price_data = pricing.get_price_data(sub['unit_price'])
        else:
            price_data = None

        return pricing.calculate_price(c.resource_volume, price_data)
Esempio n. 10
0
    def _test_volume_create_end(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        price = pricing.calculate_price(self.size, product.unit_price)
        start_time = self.utcnow()

        resource_id = self._create_volume(volume_type,
                                          self.size,
                                          self.project_id,
                                          timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context,
                                                     resource_id)
        self.assertDecimalEqual(price, order.unit_price)

        subs_list = list(
            self.dbconn.get_subscriptions_by_order_id(self.admin_req_context,
                                                      order.order_id))
        self.assertEqual(1, len(subs_list))
        for subs in subs_list:
            self.assertEqual(gring_const.STATE_RUNNING, subs.type)
            self.assertEqual(self.size, subs.quantity)
            subs_product = self.dbconn.get_product(self.admin_req_context,
                                                   subs.product_id)
            self.assertEqual(product.name, subs_product.name)

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertEqual(resource_id, bill.resource_id)
        self.assertEqual(self.datetime_to_str(start_time),
                         self.datetime_to_str(bill.start_time))
        self.assertDecimalEqual(price, bill.unit_price)
Esempio n. 11
0
    def get_unit_price(self, order_id, message):
        """Get unit price of this resource

        As the resource has subscribed to the product, so we should
        calculate price from the subscriptions instead of the product.
        """
        c = self.get_collection(message)
        product = self.gclient.get_product(
            c.product_name, c.service, c.region_id)

        if not product:
            return 0

        subs = self.gclient.get_subscriptions(order_id,
                                              product_id=product['product_id'])
        if subs:
            sub = subs[0]
        else:
            LOG.warn("The order %s has no subscriptions" % order_id)
            return 0

        if 'extra' in sub:
            price_data = pricing.get_price_data(sub['unit_price'])
        else:
            price_data = None

        return pricing.calculate_price(
            c.resource_volume, price_data)
Esempio n. 12
0
    def _test_volume_change_unit_price_with_again_event(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # original size
        resource_id = self._create_volume(volume_type, self.size, self.project_id, timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context, resource_id)

        # change to new size
        expected_price = pricing.calculate_price(self.new_size, product.unit_price)
        payload = self.build_volume_payload(volume_type, self.new_size, self.project_id, volume_id=resource_id)
        vol = cinder.Volume(
            id=payload["volume_id"],
            name=payload["display_name"],
            resource_type="volume",
            size=payload["size"],
            type=payload["volume_type"],
            project_id=payload["tenant_id"],
            user_id=payload["user_id"],
        )
        message = vol.to_message()
        handle = volume.VolumeCreateEnd()
        handle.change_unit_price(message, gring_const.STATE_RUNNING, order.order_id)

        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(expected_price, order.unit_price)

        subs_list = list(self.dbconn.get_subscriptions_by_order_id(self.admin_req_context, order.order_id))
        for subs in subs_list:
            self.assertEqual(self.new_size, subs.quantity)
Esempio n. 13
0
    def test_fipset_get_unit_price_with_again_event(self):
        rate_limit = 10240
        quantity = pricing.rate_limit_to_unit(rate_limit)
        expected_price = pricing.calculate_price(
            quantity, self.product.unit_price)

        payload = self.build_floatingipset_payload(
            self.fipset, rate_limit, self.admin_account.project_id)
        payload = payload['floatingipset']
        fipset = neutron.FloatingIpSet(
            id=payload['id'], name=payload['uos:name'],
            size=payload['rate_limit'], project_id=payload['tenant_id'],
            providers=payload['uos:service_provider'],
            resource_type=gring_const.RESOURCE_FLOATINGIPSET,
            status=payload['status'], is_reserved=True)
        message = fipset.to_message()

        handle = floatingip.FloatingIpCreateEnd()
        handle.process_notification(message)

        resource_id = payload['id']
        order = self.dbconn.get_order_by_resource_id(
            self.admin_req_context, resource_id)

        price = handle.get_unit_price(order.order_id,
                                      message,
                                      gring_const.STATE_RUNNING)
        self.assertDecimalEqual(expected_price, price)
Esempio n. 14
0
    def test_floatingip_create_end(self):
        product = self.product_fixture.ip_products[0]
        rate_limit = 1024
        quantity = pricing.rate_limit_to_unit(rate_limit)
        price = pricing.calculate_price(quantity, product.unit_price)
        project_id = self.admin_account.project_id
        start_time = self.utcnow()

        resource_id = self.create_floatingip(
            rate_limit, project_id, timestamp=start_time)

        order = self.dbconn.get_order_by_resource_id(
            self.admin_req_context, resource_id)
        self.assertDecimalEqual(price, order.unit_price)
        subs_list = list(self.dbconn.get_subscriptions_by_order_id(
            self.admin_req_context, order.order_id))
        self.assertEqual(1, len(subs_list))
        for subs in subs_list:
            self.assertEqual(gring_const.STATE_RUNNING, subs.type)
            self.assertEqual(quantity, subs.quantity)

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertEqual(resource_id, bill.resource_id)
        self.assertEqual(self.datetime_to_str(start_time),
                         self.datetime_to_str(bill.start_time))
        self.assertDecimalEqual(price, bill.unit_price)
Esempio n. 15
0
    def test_floatingip_change_unit_price(self):
        product = self.product_fixture.ip_products[0]
        project_id = self.admin_account.project_id
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # rate_limit = 1024
        rate_limit = 1024
        resource_id = self.create_floatingip(
            rate_limit, project_id, timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(
            self.admin_req_context, resource_id)

        # change rate_limit to 1024 * 11
        rate_limit = 1024 * 11
        quantity = pricing.rate_limit_to_unit(rate_limit)
        expected_price = pricing.calculate_price(quantity, product.unit_price)
        payload = self.build_floatingip_payload(
            self.floating_ip_address, rate_limit, project_id, id=resource_id)
        message = self.build_notification_message(
            self.admin_account.user_id, self.event_resized, payload,
            timestamp=end_time)
        handle = floatingip.FloatingIpCreateEnd()
        handle.change_unit_price(
            message, gring_const.STATE_RUNNING, order.order_id)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(expected_price, order.unit_price)
        subs_list = list(self.dbconn.get_subscriptions_by_order_id(
            self.admin_req_context, order.order_id))
        for subs in subs_list:
            self.assertEqual(quantity, subs.quantity)
Esempio n. 16
0
    def get_all(self, purchase):
        """Get price of a group of products."""

        if purchase.bill_method not in ['hour', 'month', 'year']:
            err = 'Should specify bill_method among hour, month and year'
            raise exception.InvalidParameterValue(err=err)

        if not isinstance(purchase.bill_period, int):
            purchase.bill_period = 1

        conn = pecan.request.db_conn

        unit_price = quantize_decimal(0)
        unit = purchase.bill_method

        for p in purchase.purchases:
            if all([p.product_id, p.quantity]):
                try:
                    product = conn.get_product(request.context, p.product_id)
                except exception.ProductIdNotFound:
                    LOG.warn("Product %s not found" % p.product_id)
                    raise
            elif all([p.product_name, p.service, p.region_id, p.quantity]):
                filters = dict(name=p.product_name,
                               service=p.service,
                               region_id=p.region_id)
                products = list(conn.get_products(
                    request.context, filters=filters))
                if len(products) == 0:
                    LOG.error('Product %s of region %s not found',
                              p.product_name, p.region_id)
                    raise exception.ProductNameNotFound(
                        product_name=p.product_name)
                product = products[0]
            else:
                err = "Every purchase item should specify product_name, "\
                      "service, region_id and quantity or "\
                      "product_id and quantity."
                raise exception.MissingRequiredParams(reason=err)
            try:
                if product.unit_price:
                    unit_price_data = jsonutils.loads(product.unit_price)
                    price_data = pricing.get_price_data(unit_price_data,
                                                        unit)
                else:
                    price_data = None

                unit_price += pricing.calculate_price(
                    p.quantity, price_data)
            except (Exception) as e:
                LOG.error('Calculate price of product %s failed, %s',
                          p.product_name, e)
                raise e
        total_price = unit_price * purchase.bill_period
        return models.Price.transform(unit_price=unit_price,
                                      unit=unit,
                                      total_price=total_price)
Esempio n. 17
0
    def test_calculate_price_using_unit_price(self):
        unit_price = '0.2'

        quantity_list = [1, 2]
        expected_list = ['0.2', '0.4']

        for q, p in zip(quantity_list, expected_list):
            price = pricing.calculate_price(q, unit_price)
            self.assertEqual(self.quantize(p), price)
Esempio n. 18
0
 def _test_floatingip_created_unit_price(rate_limit):
     price = pricing.calculate_price(
         pricing.rate_limit_to_unit(rate_limit), product.unit_price)
     resource_id = self.create_floatingip(rate_limit, project_id)
     order = self.dbconn.get_order_by_resource_id(
         self.admin_req_context, resource_id)
     self.assertDecimalEqual(price, order.unit_price)
     bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                        order.order_id)
     self.assertDecimalEqual(price, bill.unit_price)
Esempio n. 19
0
    def get_all(self, purchase):
        """Get price of a group of products."""

        if purchase.bill_method not in ['hour', 'month', 'year']:
            err = 'Should specify bill_method among hour, month and year'
            raise exception.InvalidParameterValue(err=err)

        if not isinstance(purchase.bill_period, int):
            purchase.bill_period = 1

        conn = pecan.request.db_conn

        unit_price = quantize_decimal(0)
        unit = purchase.bill_method

        for p in purchase.purchases:
            if all([p.product_id, p.quantity]):
                try:
                    product = conn.get_product(request.context, p.product_id)
                except exception.ProductIdNotFound:
                    LOG.warn("Product %s not found" % p.product_id)
                    raise
            elif all([p.product_name, p.service, p.region_id, p.quantity]):
                filters = dict(name=p.product_name,
                               service=p.service,
                               region_id=p.region_id)
                products = list(
                    conn.get_products(request.context, filters=filters))
                if len(products) == 0:
                    LOG.error('Product %s of region %s not found',
                              p.product_name, p.region_id)
                    raise exception.ProductNameNotFound(
                        product_name=p.product_name)
                product = products[0]
            else:
                err = "Every purchase item should specify product_name, "\
                      "service, region_id and quantity or "\
                      "product_id and quantity."
                raise exception.MissingRequiredParams(reason=err)
            try:
                if product.unit_price:
                    unit_price_data = jsonutils.loads(product.unit_price)
                    price_data = pricing.get_price_data(unit_price_data, unit)
                else:
                    price_data = None

                unit_price += pricing.calculate_price(p.quantity, price_data)
            except (Exception) as e:
                LOG.error('Calculate price of product %s failed, %s',
                          p.product_name, e)
                raise e
        total_price = unit_price * purchase.bill_period
        return models.Price.transform(unit_price=unit_price,
                                      unit=unit,
                                      total_price=total_price)
Esempio n. 20
0
    def test_calculate_price_using_base_price_and_segmented_price(self):
        unit_price = '0.2'
        price_data = test_utils.PricingTestMixin.build_segmented_price_data(
            '5.0', [[10, '0.1'], [4, '0.2'], [0, '0.3']])

        quantity_list = [1, 4, 5, 10, 11]
        expected_list = ['5.3', '6.2', '6.4', '7.4', '7.5']

        for q, p in zip(quantity_list, expected_list):
            price = pricing.calculate_price(q, unit_price, price_data)
            self.assertEqual(self.quantize(p), price)
Esempio n. 21
0
    def _test_volume_create_unit_price(self,
                                       size,
                                       volume_type=None,
                                       is_segmented_price=False):
        if is_segmented_price:
            product = self._set_product_volume_to_segmented_price(volume_type)
            extra = jsonutils.loads(product.extra)
            price = pricing.calculate_price(size, product.unit_price,
                                            extra['price'])
        else:
            product = self._get_product_by_volume_type(volume_type)
            price = pricing.calculate_price(size, product.unit_price)

        resource_id = self._create_volume(volume_type, size, self.project_id)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context,
                                                     resource_id)
        self.assertDecimalEqual(price, order.unit_price)

        bill = self.dbconn.get_latest_bill(self.admin_req_context,
                                           order.order_id)
        self.assertDecimalEqual(price, bill.unit_price)
Esempio n. 22
0
    def _test_volume_get_unit_price(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        expected_price = pricing.calculate_price(self.size, product.unit_price)

        payload = self.build_volume_payload(volume_type, self.size, self.project_id)
        message = self.build_notification_message(self.user_id, self.event_created, payload)
        handle = volume.VolumeCreateEnd()
        handle.process_notification(message)

        resource_id = payload["volume_id"]
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context, resource_id)

        price = handle.get_unit_price(order.order_id, message, gring_const.STATE_RUNNING)
        self.assertDecimalEqual(expected_price, price)
Esempio n. 23
0
    def get_unit_price(self, env, body, method):
        """Get product unit price"""
        collection = self.get_collection(env, body)
        product = self.gclient.get_product(collection.product_name,
                                           collection.service,
                                           collection.region_id)
        if product:
            if 'extra' in product:
                price_data = pricing.get_price_data(product['extra'], method)
            else:
                price_data = None

            return pricing.calculate_price(
                collection.resource_volume, product['unit_price'], price_data)
        else:
            return 0
Esempio n. 24
0
    def test_get_price_of_product_with_nonzero_index(self):
        product = self.product_fixture.ip_products[0]
        quantity = 1
        purchase = self.build_purchase(
            product.name, product.service, product.region_id, quantity)
        price = pricing.calculate_price(quantity, product.unit_price)
        query_vars = ['purchase.bill_method=hour']
        for k, v in six.iteritems(purchase):
            query_vars.append('purchase.purchases[1].%s=%s' % (k, v))

        query_parts = '&'.join(query_vars)
        LOG.debug(query_parts)
        query_url = self.price_path + '?' + query_parts
        resp = self.get(query_url, headers=self.admin_headers)
        price_ref = resp.json_body
        LOG.debug(price_ref)
        self.assertDecimalEqual(price, price_ref['unit_price'])
Esempio n. 25
0
    def _test_volume_resize_end(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # original size
        resource_id = self._create_volume(volume_type,
                                          self.size,
                                          self.project_id,
                                          timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context,
                                                     resource_id)
        bill1 = self.dbconn.get_latest_bill(self.admin_req_context,
                                            order.order_id)

        # change to new size
        payload = self.build_volume_payload(volume_type,
                                            self.new_size,
                                            self.project_id,
                                            volume_id=resource_id)
        message = self.build_notification_message(self.user_id,
                                                  self.event_resized,
                                                  payload,
                                                  timestamp=end_time)
        handle = volume.VolumeResizeEnd()
        handle.process_notification(message)

        price = pricing.calculate_price(self.new_size, product.unit_price)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(price, order.unit_price)

        subs_list = list(
            self.dbconn.get_subscriptions_by_order_id(self.admin_req_context,
                                                      order.order_id))
        self.assertEqual(1, len(subs_list))
        for subs in subs_list:
            self.assertEqual(self.new_size, subs.quantity)

        bill1 = self.dbconn.get_bill(self.admin_req_context, bill1.bill_id)
        self.assertEqual(self.datetime_to_str(end_time),
                         self.datetime_to_str(bill1.end_time))
        bill2 = self.dbconn.get_latest_bill(self.admin_req_context,
                                            order.order_id)
        self.assertEqual(self.datetime_to_str(end_time),
                         self.datetime_to_str(bill2.start_time))
        self.assertDecimalEqual(price, bill2.unit_price)
Esempio n. 26
0
    def test_get_price_of_product_with_nonzero_index(self):
        product = self.product_fixture.ip_products[0]
        quantity = 1
        purchase = self.build_purchase(product.name, product.service,
                                       product.region_id, quantity)
        price = pricing.calculate_price(quantity, product.unit_price)
        query_vars = ['purchase.bill_method=hour']
        for k, v in six.iteritems(purchase):
            query_vars.append('purchase.purchases[1].%s=%s' % (k, v))

        query_parts = '&'.join(query_vars)
        LOG.debug(query_parts)
        query_url = self.price_path + '?' + query_parts
        resp = self.get(query_url, headers=self.admin_headers)
        price_ref = resp.json_body
        LOG.debug(price_ref)
        self.assertDecimalEqual(price, price_ref['unit_price'])
Esempio n. 27
0
    def get_unit_price(self, env, body, method):
        """Get product unit price"""
        collection = self.get_collection(env, body)
        product = self.gclient.get_product(collection.product_name,
                                           collection.service,
                                           collection.region_id)
        if product:
            if 'unit_price' in product:
                price_data = pricing.get_price_data(product['unit_price'],
                                                    method)
            else:
                price_data = None

            return pricing.calculate_price(collection.resource_volume,
                                           price_data)
        else:
            return 0
Esempio n. 28
0
    def _test_volume_get_unit_price(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        expected_price = pricing.calculate_price(self.size, product.unit_price)

        payload = self.build_volume_payload(volume_type, self.size,
                                            self.project_id)
        message = self.build_notification_message(self.user_id,
                                                  self.event_created, payload)
        handle = volume.VolumeCreateEnd()
        handle.process_notification(message)

        resource_id = payload['volume_id']
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context,
                                                     resource_id)

        price = handle.get_unit_price(order.order_id, message,
                                      gring_const.STATE_RUNNING)
        self.assertDecimalEqual(expected_price, price)
Esempio n. 29
0
    def test_floatingip_resize_end(self):
        product = self.product_fixture.ip_products[0]
        project_id = self.admin_account.project_id
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # rate_limit = 1024
        rate_limit = 1024
        resource_id = self.create_floatingip(
            rate_limit, project_id, timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(
            self.admin_req_context, resource_id)
        bill1 = self.dbconn.get_latest_bill(self.admin_req_context,
                                            order.order_id)

        # change rate_limit to 1024 * 11
        rate_limit = 1024 * 11
        quantity = pricing.rate_limit_to_unit(rate_limit)
        payload = self.build_floatingip_payload(
            self.floating_ip_address, rate_limit, project_id, id=resource_id)
        message = self.build_notification_message(
            self.admin_account.user_id, self.event_resized, payload,
            timestamp=end_time)
        handle = floatingip.FloatingIpResizeEnd()
        handle.process_notification(message)

        price = pricing.calculate_price(quantity, product.unit_price)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(price, order.unit_price)
        subs_list = list(self.dbconn.get_subscriptions_by_order_id(
            self.admin_req_context, order.order_id))
        self.assertEqual(1, len(subs_list))
        for subs in subs_list:
            self.assertEqual(quantity, subs.quantity)

        bill1 = self.dbconn.get_bill(self.admin_req_context, bill1.bill_id)
        self.assertEqual(self.datetime_to_str(end_time),
                         self.datetime_to_str(bill1.end_time))
        bill2 = self.dbconn.get_latest_bill(self.admin_req_context,
                                            order.order_id)
        self.assertEqual(self.datetime_to_str(end_time),
                         self.datetime_to_str(bill2.start_time))
        self.assertDecimalEqual(price, bill2.unit_price)
Esempio n. 30
0
    def _test_volume_change_unit_price_with_again_event(
            self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # original size
        resource_id = self._create_volume(volume_type,
                                          self.size,
                                          self.project_id,
                                          timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context,
                                                     resource_id)

        # change to new size
        expected_price = pricing.calculate_price(self.new_size,
                                                 product.unit_price)
        payload = self.build_volume_payload(volume_type,
                                            self.new_size,
                                            self.project_id,
                                            volume_id=resource_id)
        vol = cinder.Volume(id=payload['volume_id'],
                            name=payload['display_name'],
                            resource_type='volume',
                            size=payload['size'],
                            type=payload['volume_type'],
                            project_id=payload['tenant_id'],
                            user_id=payload['user_id'])
        message = vol.to_message()
        handle = volume.VolumeCreateEnd()
        handle.change_unit_price(message, gring_const.STATE_RUNNING,
                                 order.order_id)

        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(expected_price, order.unit_price)

        subs_list = list(
            self.dbconn.get_subscriptions_by_order_id(self.admin_req_context,
                                                      order.order_id))
        for subs in subs_list:
            self.assertEqual(self.new_size, subs.quantity)
Esempio n. 31
0
    def test_update_product_with_segmented_price_and_reset(self):
        product = self.product_fixture.ip_products[0]
        quantity = 11
        resource_type = gring_const.RESOURCE_FLOATINGIP
        order_id = self.new_order_id()
        user_id = self.admin_account.user_id
        project_id = self.admin_account.project_id

        running_subs = self.create_subs_in_db(product, quantity,
                                              gring_const.STATE_RUNNING,
                                              order_id, project_id, user_id)
        order = self.create_order_in_db(running_subs.unit_price,
                                        running_subs.unit,
                                        user_id,
                                        project_id,
                                        resource_type,
                                        running_subs.type,
                                        order_id=order_id)

        price_data = self.build_segmented_price_data(
            '0.0000', [[10, '0.1'], [4, '0.2'], [0, '0.3']])
        extra = {'price': price_data}
        body = {
            'extra': jsonutils.dumps(extra),
            'reset': True,
        }
        query_url = self.build_product_query_url(product.product_id)
        self.put(query_url,
                 headers=self.admin_headers,
                 body=body,
                 expected_status=200)

        expected_price = pricing.calculate_price(quantity, product.unit_price,
                                                 price_data)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        subs = list(
            self.dbconn.get_subscriptions_by_order_id(self.admin_req_context,
                                                      order.order_id))
        for sub in subs:
            self.assertEqual(extra, jsonutils.loads(sub.extra))
        self.assertDecimalEqual(expected_price, order.unit_price)
Esempio n. 32
0
    def _test_volume_create_end(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        price = pricing.calculate_price(self.size, product.unit_price)
        start_time = self.utcnow()

        resource_id = self._create_volume(volume_type, self.size, self.project_id, timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context, resource_id)
        self.assertDecimalEqual(price, order.unit_price)

        subs_list = list(self.dbconn.get_subscriptions_by_order_id(self.admin_req_context, order.order_id))
        self.assertEqual(1, len(subs_list))
        for subs in subs_list:
            self.assertEqual(gring_const.STATE_RUNNING, subs.type)
            self.assertEqual(self.size, subs.quantity)
            subs_product = self.dbconn.get_product(self.admin_req_context, subs.product_id)
            self.assertEqual(product.name, subs_product.name)

        bill = self.dbconn.get_latest_bill(self.admin_req_context, order.order_id)
        self.assertEqual(resource_id, bill.resource_id)
        self.assertEqual(self.datetime_to_str(start_time), self.datetime_to_str(bill.start_time))
        self.assertDecimalEqual(price, bill.unit_price)
Esempio n. 33
0
    def test_fipset_change_unit_price_with_again_event(self):
        project_id = self.admin_account.project_id
        end_time = self.utcnow()
        start_time = end_time - datetime.timedelta(hours=1)

        # rate_limit = 1024
        rate_limit = 1024
        resource_id = self.create_floatingipset(
            rate_limit, project_id, timestamp=start_time)
        order = self.dbconn.get_order_by_resource_id(
            self.admin_req_context, resource_id)

        # change rate_limit to 1024 * 11
        rate_limit = 1024 * 11
        quantity = pricing.rate_limit_to_unit(rate_limit)
        expected_price = pricing.calculate_price(
            quantity, self.product.unit_price)

        payload = self.build_floatingipset_payload(
            self.fipset, rate_limit, self.admin_account.project_id)
        payload = payload['floatingipset']
        fipset = neutron.FloatingIpSet(
            id=payload['id'], name=payload['uos:name'],
            size=payload['rate_limit'], project_id=payload['tenant_id'],
            providers=payload['uos:service_provider'],
            resource_type=gring_const.RESOURCE_FLOATINGIPSET,
            status=payload['status'], is_reserved=True)
        message = fipset.to_message()

        handle = floatingip.FloatingIpCreateEnd()
        handle.change_unit_price(
            message, gring_const.STATE_RUNNING, order.order_id)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        self.assertDecimalEqual(expected_price, order.unit_price)
        subs_list = list(self.dbconn.get_subscriptions_by_order_id(
            self.admin_req_context, order.order_id))
        for subs in subs_list:
            self.assertEqual(quantity, subs.quantity)
Esempio n. 34
0
    def _test_volume_get_unit_price_with_again_event(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        expected_price = pricing.calculate_price(self.size, product.unit_price)

        payload = self.build_volume_payload(volume_type, self.size, self.project_id)
        vol = cinder.Volume(
            id=payload["volume_id"],
            name=payload["display_name"],
            resource_type="volume",
            size=payload["size"],
            type=payload["volume_type"],
            project_id=payload["tenant_id"],
            user_id=payload["user_id"],
        )
        message = vol.to_message()
        handle = volume.VolumeCreateEnd()
        handle.process_notification(message)

        resource_id = payload["volume_id"]
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context, resource_id)

        price = handle.get_unit_price(order.order_id, message, gring_const.STATE_RUNNING)
        self.assertDecimalEqual(expected_price, price)
Esempio n. 35
0
    def test_floatingip_get_unit_price(self):
        product = self.product_fixture.ip_products[0]
        rate_limit = 10240
        quantity = pricing.rate_limit_to_unit(rate_limit)
        expected_price = pricing.calculate_price(quantity, product.unit_price)

        payload = self.build_floatingip_payload(
            self.floating_ip_address, rate_limit,
            self.admin_account.project_id)
        message = self.build_notification_message(
            self.admin_account.user_id, self.event_created, payload)

        handle = floatingip.FloatingIpCreateEnd()
        handle.process_notification(message)

        resource_id = payload['floatingip']['id']
        order = self.dbconn.get_order_by_resource_id(
            self.admin_req_context, resource_id)

        price = handle.get_unit_price(order.order_id,
                                      message,
                                      gring_const.STATE_RUNNING)
        self.assertDecimalEqual(expected_price, price)
Esempio n. 36
0
    def test_update_product_with_segmented_price_and_reset(self):
        product = self.product_fixture.ip_products[0]
        quantity = 11
        resource_type = gring_const.RESOURCE_FLOATINGIP
        order_id = self.new_order_id()
        user_id = self.admin_account.user_id
        project_id = self.admin_account.project_id

        running_subs = self.create_subs_in_db(
            product, quantity, gring_const.STATE_RUNNING,
            order_id, project_id, user_id
        )
        order = self.create_order_in_db(
            running_subs.unit_price, running_subs.unit,
            user_id, project_id, resource_type,
            running_subs.type, order_id=order_id
        )

        price_data = self.build_segmented_price_data(
            '0.0000', [[10, '0.1'], [4, '0.2'], [0, '0.3']])
        extra = {'price': price_data}
        body = {
            'extra': jsonutils.dumps(extra),
            'reset': True,
        }
        query_url = self.build_product_query_url(product.product_id)
        self.put(query_url, headers=self.admin_headers,
                 body=body, expected_status=200)

        expected_price = pricing.calculate_price(
            quantity, product.unit_price, price_data)
        order = self.dbconn.get_order(self.admin_req_context, order.order_id)
        subs = list(self.dbconn.get_subscriptions_by_order_id(
            self.admin_req_context, order.order_id))
        for sub in subs:
            self.assertEqual(extra, jsonutils.loads(sub.extra))
        self.assertDecimalEqual(expected_price, order.unit_price)
Esempio n. 37
0
    def _test_volume_get_unit_price_with_again_event(self, volume_type=None):
        product = self._get_product_by_volume_type(volume_type)
        expected_price = pricing.calculate_price(self.size, product.unit_price)

        payload = self.build_volume_payload(volume_type, self.size,
                                            self.project_id)
        vol = cinder.Volume(id=payload['volume_id'],
                            name=payload['display_name'],
                            resource_type='volume',
                            size=payload['size'],
                            type=payload['volume_type'],
                            project_id=payload['tenant_id'],
                            user_id=payload['user_id'])
        message = vol.to_message()
        handle = volume.VolumeCreateEnd()
        handle.process_notification(message)

        resource_id = payload['volume_id']
        order = self.dbconn.get_order_by_resource_id(self.admin_req_context,
                                                     resource_id)

        price = handle.get_unit_price(order.order_id, message,
                                      gring_const.STATE_RUNNING)
        self.assertDecimalEqual(expected_price, price)