|
| 1 | +import CloudGraph from '@cloudgraph/sdk' |
| 2 | +import { BigQuery, RowMetadata } from '@google-cloud/bigquery' |
| 3 | +import * as _ from 'lodash' |
| 4 | +import { GLOBAL_REGION } from '../../config/constants' |
| 5 | +import gcpLoggerText from '../../properties/logger' |
| 6 | +import { GcpServiceInput } from '../../types' |
| 7 | +import { generateGcpErrorLog, initTestEndpoint } from '../../utils' |
| 8 | +import { |
| 9 | + createDiffSecs, |
| 10 | + getCurrentDayOfMonth, |
| 11 | + getDaysAgo, |
| 12 | + getFirstDayOfMonth, |
| 13 | +} from '../../utils/dateutils' |
| 14 | +import { |
| 15 | + formatAmmountAndUnit, |
| 16 | + getCurrency, |
| 17 | + getTotalCost, |
| 18 | + RawGcpTotalCost, |
| 19 | + totalCostQuery, |
| 20 | + totalCostGroupByServiceQuery, |
| 21 | +} from './utils' |
| 22 | + |
| 23 | +const lt = { ...gcpLoggerText } |
| 24 | +const { logger } = CloudGraph |
| 25 | +const serviceName = 'Billing' |
| 26 | +const apiEndpoint = initTestEndpoint(serviceName) |
| 27 | + |
| 28 | +export interface costInterface { |
| 29 | + cost?: number |
| 30 | + currency?: string |
| 31 | + formattedCost?: string |
| 32 | +} |
| 33 | + |
| 34 | +export interface RawGcpBilling { |
| 35 | + totalCostLast30Days: costInterface |
| 36 | + totalCostMonthToDate: costInterface |
| 37 | + monthToDateDailyAverage: { [key: string]: costInterface } |
| 38 | + last30DaysDailyAverage: { [key: string]: costInterface } |
| 39 | + monthToDate: { [key: string]: costInterface } |
| 40 | + last30Days: { [key: string]: costInterface } |
| 41 | + individualData: { [key: string]: costInterface } |
| 42 | +} |
| 43 | + |
| 44 | +export const listBillingData = async ( |
| 45 | + client: BigQuery, |
| 46 | + projectId: string, |
| 47 | + billings: RawGcpTotalCost[], |
| 48 | + billingAccountId: string, |
| 49 | + dataset: string, |
| 50 | + groupBy?: boolean, |
| 51 | + startDate?: string, |
| 52 | + endDate?: string |
| 53 | +): Promise<void> => |
| 54 | + new Promise<void>(async resolve => { |
| 55 | + try { |
| 56 | + const billingTable = `${projectId}.${dataset}.gcp_billing_export_resource_v1_${billingAccountId}` |
| 57 | + |
| 58 | + let sqlQuery = '' |
| 59 | + if (groupBy) { |
| 60 | + sqlQuery = totalCostGroupByServiceQuery(billingTable, startDate, endDate) |
| 61 | + } else { |
| 62 | + sqlQuery = totalCostQuery(billingTable, startDate, endDate) |
| 63 | + } |
| 64 | + |
| 65 | + const options = { |
| 66 | + query: sqlQuery, |
| 67 | + } |
| 68 | + |
| 69 | + // Run the query |
| 70 | + const [rows] = await client.query(options) |
| 71 | + |
| 72 | + if (!_.isEmpty(rows)) { |
| 73 | + billings.push(...rows) |
| 74 | + } |
| 75 | + } catch (error) { |
| 76 | + generateGcpErrorLog(serviceName, 'bigQuery:getTotalCost', error) |
| 77 | + } |
| 78 | + |
| 79 | + resolve() |
| 80 | + }) |
| 81 | + |
| 82 | +export default async ({ |
| 83 | + config, |
| 84 | +}: GcpServiceInput): Promise<{ |
| 85 | + [region: string]: RawGcpBilling[] |
| 86 | +}> => { |
| 87 | + const startDate = new Date() |
| 88 | + const region = GLOBAL_REGION |
| 89 | + const results: RawGcpBilling = { |
| 90 | + totalCostLast30Days: {}, |
| 91 | + totalCostMonthToDate: {}, |
| 92 | + monthToDateDailyAverage: {}, |
| 93 | + last30DaysDailyAverage: {}, |
| 94 | + monthToDate: {}, |
| 95 | + last30Days: {}, |
| 96 | + individualData: {}, |
| 97 | + } |
| 98 | + const resultPromises = [] |
| 99 | + const { |
| 100 | + projectId, |
| 101 | + billing: { billingAccountId, bigQueryDataset }, |
| 102 | + } = config |
| 103 | + |
| 104 | + try { |
| 105 | + const client = new BigQuery({ ...config, apiEndpoint }) |
| 106 | + |
| 107 | + const listAggregateFinOpsData = async ({ |
| 108 | + resolve, |
| 109 | + type, |
| 110 | + groupBy = true, |
| 111 | + individualData = false, |
| 112 | + timePeriod: TimePeriod, |
| 113 | + }: { |
| 114 | + resolve: () => void |
| 115 | + type: string |
| 116 | + groupBy?: boolean |
| 117 | + individualData?: boolean |
| 118 | + timePeriod: { Start: string; End: string } |
| 119 | + }): Promise<void> => { |
| 120 | + logger.debug(lt.queryingAggregateFinOpsDataForRegion(region, type)) |
| 121 | + const billingData: RowMetadata[] = [] |
| 122 | + |
| 123 | + await listBillingData( |
| 124 | + client, |
| 125 | + projectId, |
| 126 | + billingData, |
| 127 | + billingAccountId, |
| 128 | + bigQueryDataset, |
| 129 | + groupBy, |
| 130 | + TimePeriod.Start, |
| 131 | + TimePeriod.End |
| 132 | + ) |
| 133 | + |
| 134 | + if (_.isEmpty(billingData)) { |
| 135 | + logger.debug(lt.unableToFindFinOpsAggregateData) |
| 136 | + return resolve() |
| 137 | + } |
| 138 | + |
| 139 | + if (groupBy || individualData) { |
| 140 | + const services = _.groupBy(billingData, u => u.service) |
| 141 | + Object.keys(services).map(name => { |
| 142 | + const serviceUsages = services[name] |
| 143 | + const currency = getCurrency(serviceUsages) |
| 144 | + const cost = getTotalCost(serviceUsages) |
| 145 | + const costData = { |
| 146 | + cost, |
| 147 | + currency, |
| 148 | + formattedCost: formatAmmountAndUnit({ |
| 149 | + Amount: cost, |
| 150 | + Unit: currency, |
| 151 | + }), |
| 152 | + } |
| 153 | + if (individualData) { |
| 154 | + results.individualData[name] = costData |
| 155 | + } else { |
| 156 | + results[type][name] = costData |
| 157 | + } |
| 158 | + }) |
| 159 | + } else { |
| 160 | + const currency = getCurrency(billingData) |
| 161 | + const cost = getTotalCost(billingData) |
| 162 | + results[type] = { |
| 163 | + cost, |
| 164 | + currency, |
| 165 | + formattedCost: formatAmmountAndUnit({ |
| 166 | + Amount: cost, |
| 167 | + Unit: currency, |
| 168 | + }), |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + resolve() |
| 173 | + } |
| 174 | + |
| 175 | + /** |
| 176 | + * Now we make 4 queries to the api in order to get aggregate pricing data sliced in various ways |
| 177 | + */ |
| 178 | + |
| 179 | + const today = new Date().toLocaleDateString('en-ca') |
| 180 | + const startOfMonth = getFirstDayOfMonth() |
| 181 | + |
| 182 | + const commonArgs = { |
| 183 | + timePeriod: { |
| 184 | + Start: getDaysAgo(60), // TODO: change to 30 !!! |
| 185 | + End: today, |
| 186 | + }, |
| 187 | + } |
| 188 | + |
| 189 | + /** |
| 190 | + * Breakdown by service types and spend for last 30 days |
| 191 | + */ |
| 192 | + const last30DaysData = new Promise<void>(resolve => |
| 193 | + listAggregateFinOpsData({ |
| 194 | + ...commonArgs, |
| 195 | + resolve, |
| 196 | + type: 'last30Days', |
| 197 | + }) |
| 198 | + ) |
| 199 | + resultPromises.push(last30DaysData) |
| 200 | + |
| 201 | + /** |
| 202 | + * Breakdown by service types and spend since the beginning of the month |
| 203 | + */ |
| 204 | + if (!(today === startOfMonth)) { |
| 205 | + const monthToDateData = new Promise<void>(resolve => |
| 206 | + listAggregateFinOpsData({ |
| 207 | + resolve, |
| 208 | + type: 'monthToDate', |
| 209 | + timePeriod: { |
| 210 | + Start: startOfMonth, |
| 211 | + End: today, |
| 212 | + }, |
| 213 | + }) |
| 214 | + ) |
| 215 | + resultPromises.push(monthToDateData) |
| 216 | + } |
| 217 | + |
| 218 | + /** |
| 219 | + * The single total cost of everything in the last 30 days |
| 220 | + */ |
| 221 | + const totalCostLast30Days = new Promise<void>(resolve => |
| 222 | + listAggregateFinOpsData({ |
| 223 | + ...commonArgs, |
| 224 | + resolve, |
| 225 | + type: 'totalCostLast30Days', |
| 226 | + groupBy: false, |
| 227 | + }) |
| 228 | + ) |
| 229 | + resultPromises.push(totalCostLast30Days) |
| 230 | + |
| 231 | + /** |
| 232 | + * The single total cost of everything in the current month |
| 233 | + */ |
| 234 | + if (!(today === startOfMonth)) { |
| 235 | + const totalCostMonthToDate = new Promise<void>(resolve => |
| 236 | + listAggregateFinOpsData({ |
| 237 | + resolve, |
| 238 | + type: 'totalCostMonthToDate', |
| 239 | + groupBy: false, |
| 240 | + timePeriod: { |
| 241 | + Start: startOfMonth, |
| 242 | + End: today, |
| 243 | + }, |
| 244 | + }) |
| 245 | + ) |
| 246 | + resultPromises.push(totalCostMonthToDate) |
| 247 | + } |
| 248 | + |
| 249 | + const individualDataPromise = new Promise<void>(resolve => |
| 250 | + listAggregateFinOpsData({ |
| 251 | + resolve, |
| 252 | + type: 'individualData', |
| 253 | + individualData: true, |
| 254 | + timePeriod: { |
| 255 | + Start: getDaysAgo(1), // i.e. get the daily cost |
| 256 | + End: today, |
| 257 | + }, |
| 258 | + }) |
| 259 | + ) |
| 260 | + resultPromises.push(individualDataPromise) |
| 261 | + |
| 262 | + await Promise.all(resultPromises) |
| 263 | + |
| 264 | + /** |
| 265 | + * Create Daily Averages |
| 266 | + */ |
| 267 | + |
| 268 | + const createDailyAverage = ({ |
| 269 | + days, |
| 270 | + resultMonthlyData, |
| 271 | + resultAverageData, |
| 272 | + }): void[] => |
| 273 | + Object.keys(resultMonthlyData).map(service => { |
| 274 | + const { cost: aggregateCost, currency } = resultMonthlyData[service] |
| 275 | + const cost = parseFloat((aggregateCost / days).toFixed(10)) |
| 276 | + results[resultAverageData][service] = { |
| 277 | + cost, |
| 278 | + currency, |
| 279 | + formattedCost: formatAmmountAndUnit({ Amount: cost, Unit: currency }), |
| 280 | + } |
| 281 | + }) |
| 282 | + |
| 283 | + if (!_.isEmpty(results.monthToDate)) { |
| 284 | + createDailyAverage({ |
| 285 | + days: parseInt(getCurrentDayOfMonth(), 10), |
| 286 | + resultMonthlyData: results.monthToDate, |
| 287 | + resultAverageData: 'monthToDateDailyAverage', |
| 288 | + }) |
| 289 | + } |
| 290 | + if (!_.isEmpty(results.last30Days)) { |
| 291 | + createDailyAverage({ |
| 292 | + days: 30, |
| 293 | + resultMonthlyData: results.last30Days, |
| 294 | + resultAverageData: 'last30DaysDailyAverage', |
| 295 | + }) |
| 296 | + } |
| 297 | + |
| 298 | + logger.debug(lt.doneFetchingAggregateFinOpsData(createDiffSecs(startDate))) |
| 299 | + return { [region]: [results] } |
| 300 | + } catch (e) { |
| 301 | + logger.error(e) |
| 302 | + } |
| 303 | + |
| 304 | + logger.debug(lt.doneFetchingAggregateFinOpsData(createDiffSecs(startDate))) |
| 305 | + return { [region]: [results] } |
| 306 | +} |
0 commit comments