Skip to content

Add network traffic condition with 'meter name' #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ def list_by_billing_account(self):
)

@staticmethod
def get_retail_price(meter_id: str):
url = f"https://prices.azure.com/api/retail/prices?$filter=priceType eq 'Consumption' and meterId eq '{meter_id}'"
def get_retail_price(meter_id: str, currency: str = "USD"):
url = f"https://prices.azure.com/api/retail/prices?currencyCode={currency}&$filter=priceType eq 'Consumption' and meterId eq '{meter_id}'"
try:
response = requests.get(url=url)
return response.json()
Expand Down
65 changes: 31 additions & 34 deletions src/cloudforet/cost_analysis/manager/cost_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,9 @@ def _get_additional_info(self, result: dict, options: dict, tenant_id: str = Non
if result.get("productname"):
additional_info["Product Name"] = result["productname"]

if result.get("productid") != "" and result.get("productid"):
additional_info["Product Id"] = result["productid"]

if result.get("customername") != "" and result.get("customername"):
additional_info["Customer Name"] = result["customername"]

Expand All @@ -328,9 +331,10 @@ def _get_additional_info(self, result: dict, options: dict, tenant_id: str = Non
if result.get("pricingmodel") in ["Reservation", "SavingsPlan"]:
meter_id = result.get("meterid")
product_id = result.get("productid")
currency = result.get("billingcurrency", "USD")
if not self.retail_price_map.get(f"{meter_id}:{product_id}"):
unit_price = self._get_unit_price_from_meter_id(
meter_id, product_id
meter_id, product_id, currency
)
self.retail_price_map[f"{meter_id}:{product_id}"] = unit_price

Expand Down Expand Up @@ -437,21 +441,6 @@ def _make_credit_data(
return credits_data

billed_date = _start.strftime("%Y-%m-%d")
adjustment_details = result.get("adjustment_details", []) or []

for adjustment_detail in adjustment_details:
credit_data = {
"cost": adjustment_detail.get("value", 0.0) or 0.0,
"product": "Credit",
"billed_date": billed_date,
"additional_info": {
"Service Family": "Microsoft.Consumption/adjustments",
"Adjustment Name": adjustment_detail.get("name"),
},
}
if billing_tenant_id:
credit_data["additional_info"]["Billing Tenant Id"] = billing_tenant_id
credits_data.append(credit_data)

credit_data = {
"cost": -(result.get("utilized", 0.0) or 0.0),
Expand All @@ -463,6 +452,7 @@ def _make_credit_data(
}
if billing_tenant_id:
credit_data["additional_info"]["Billing Tenant Id"] = billing_tenant_id

credits_data.append(credit_data)
return credits_data

Expand Down Expand Up @@ -518,9 +508,6 @@ def _get_aggregate_data(
else:
aggregate_data["Saved Cost"] = 0.0

if exchange_rate := result.get("exchange_rate"):
additional_info["Exchange Rate"] = exchange_rate

else:
aggregate_data["Actual Cost"] = cost_in_billing_currency

Expand All @@ -535,35 +522,38 @@ def _get_saved_cost(self, result: dict, cost: float) -> float:
quantity = self._convert_str_to_float_format(result.get("quantity", 0.0))

if not self.retail_price_map.get(f"{meter_id}:{product_id}"):
unit_price = self._get_unit_price_from_meter_id(meter_id, product_id)
unit_price = self._get_unit_price_from_meter_id(
meter_id, product_id, currency
)
self.retail_price_map[f"{meter_id}:{product_id}"] = unit_price

unit_price = self.retail_price_map[f"{meter_id}:{product_id}"]

if currency != "USD" and quantity > 0:
cost_in_billing_currency = self._convert_str_to_float_format(
result.get("costinbillingcurrency", 0.0)
)
cost_in_pricing_currency = self._convert_str_to_float_format(
result.get("costinpricingcurrency", 0.0)
)
# if currency != "USD" and quantity > 0:
# cost_in_billing_currency = self._convert_str_to_float_format(
# result.get("costinbillingcurrency", 0.0)
# )
# cost_in_pricing_currency = self._convert_str_to_float_format(
# result.get("costinpricingcurrency", 0.0)
# )

if cost_in_pricing_currency == 0 or cost_in_billing_currency == 0:
exchange_rate = 0
else:
exchange_rate = cost_in_billing_currency / cost_in_pricing_currency
# if cost_in_pricing_currency == 0 or cost_in_billing_currency == 0:
# exchange_rate = 0
# else:
# exchange_rate = cost_in_billing_currency / cost_in_pricing_currency

retail_cost = exchange_rate * quantity * unit_price
if retail_cost:
saved_cost = retail_cost - cost
result["exchange_rate"] = exchange_rate

return saved_cost

def _get_unit_price_from_meter_id(self, meter_id: str, product_id: str) -> float:
def _get_unit_price_from_meter_id(
self, meter_id: str, product_id: str, currency: str = None
) -> float:
unit_price = 0.0
try:
response = self.azure_cm_connector.get_retail_price(meter_id)
response = self.azure_cm_connector.get_retail_price(meter_id, currency)
items = response.get("Items", [])

for item in items:
Expand Down Expand Up @@ -833,6 +823,13 @@ def _set_network_traffic_cost(
additional_info["Usage Type Details"] = "Transfer Out"
else:
additional_info["Usage Type Details"] = "Transfer Etc"
elif "Data Transfer" in meter_name:
if "Data Transfer In" in meter_name:
additional_info["Usage Type Details"] = "Transfer In"
elif "Data Transfer Out" in meter_name:
additional_info["Usage Type Details"] = "Transfer Out"
else:
additional_info["Usage Type Details"] = "Transfer Etc"

return additional_info

Expand Down
21 changes: 20 additions & 1 deletion src/cloudforet/cost_analysis/manager/data_source_manager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging

from spaceone.core.error import ERROR_INVALID_ARGUMENT
from spaceone.core.manager import BaseManager
from cloudforet.cost_analysis.connector.azure_cost_mgmt_connector import (
AzureCostMgmtConnector,
Expand Down Expand Up @@ -61,6 +62,7 @@
"Exchange Rate": {"name": "Exchange Rate", "visible": False},
"Billing Tenant Id": {"name": "Billing Tenant Id", "visible": True},
"Adjustment Name": {"name": "Adjustment Name", "visible": False},
"Product Id": {"name": "Product Id", "visible": False},
}

_METADATA_INFO_ADDITIONAL_INFO_MPA = {
Expand All @@ -84,6 +86,8 @@ def init_response(options: dict, domain_id: str) -> dict:
"supported_secret_types(list)": [],
"currency(str)": "KRW",
"use_account_routing(bool)": False,
"exclude_license_cost(bool)": False,
"include_credit_cost(bool)": False,
"cost_info(dict)": {
"name" :"PayAsYouGo",
"unit" :"KRW"
Expand All @@ -97,7 +101,8 @@ def init_response(options: dict, domain_id: str) -> dict:
"additional_info(dict)": {
"Subscription Name": {
"name": "Subscription Name",
"visible": True
"visible": True,
"enums": ["","",...]
}
}
}
Expand All @@ -115,6 +120,8 @@ def init_response(options: dict, domain_id: str) -> dict:
"additional_info": _DEFAULT_METADATA_ADDITIONAL_INFO,
}

_check_options(options)

if options.get("account_agreement_type") == "MicrosoftPartnerAgreement":
plugin_metadata["additional_info"].update(
_METADATA_INFO_ADDITIONAL_INFO_MPA
Expand Down Expand Up @@ -159,3 +166,15 @@ def verify_plugin(self, options, secret_data, schema):
"AzureCostMgmtConnector"
)
azure_cm_connector.create_session(options, secret_data, schema)


def _check_options(options: dict):
if account_agreement_type := options.get("account_agreement_type"):
if options["account_agreement_type"] not in [
"MicrosoftPartnerAgreement",
"EnterpriseAgreement",
"MicrosoftCustomerAgreement",
]:
raise ERROR_INVALID_ARGUMENT(
key="options.account_agreement_type", value=account_agreement_type
)
Loading