-
Notifications
You must be signed in to change notification settings - Fork 20
/
api.go
261 lines (235 loc) · 7.68 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package tencent
import (
"context"
"strconv"
"strings"
"time"
"github.com/galaxy-future/costpilot/tools/limiter"
"github.com/alibabacloud-go/tea/tea"
"github.com/galaxy-future/costpilot/internal/constants/cloud"
"github.com/galaxy-future/costpilot/internal/providers/types"
"github.com/pkg/errors"
billing "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/billing/v20180709"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
monitor "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/monitor/v20180724"
)
type TencentCloud struct {
billingClient *billing.Client
cvmClient *cvm.Client
monitorClient *monitor.Client
}
func New(ak, sk, regionId string) (*TencentCloud, error) {
credential := common.NewCredential(ak, sk)
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = _billingEndpoint
billingClient, err := billing.NewClient(credential, "", cpf)
if err != nil {
return nil, err
}
cvmCP := profile.NewClientProfile()
cvmCP.HttpProfile.Endpoint = _cvmEndPoint
cvmClient, err := cvm.NewClient(credential, regionId, cvmCP)
if err != nil {
return nil, err
}
monitorCP := profile.NewClientProfile()
monitorCP.HttpProfile.Endpoint = _monitorEndPoint
monitorClient, err := monitor.NewClient(credential, regionId, monitorCP)
if err != nil {
return nil, err
}
return &TencentCloud{
billingClient: billingClient,
cvmClient: cvmClient,
monitorClient: monitorClient,
}, nil
}
// ProviderType
func (*TencentCloud) ProviderType() cloud.Provider {
return cloud.TencentCloud
}
// QueryAccountBill
func (p *TencentCloud) QueryAccountBill(_ context.Context, param types.QueryAccountBillRequest) (types.DataInQueryAccountBill, error) {
var (
needNum int64 = 0
offset uint64 = 0
)
request := billing.NewDescribeBillDetailRequest()
request.NeedRecordNum = &needNum
request.Limit = &_maxPageSize
request.Offset = &offset
request.NeedRecordNum = common.Int64Ptr(1) // 1 for needing total ,0 for not
// 根据不同的账单周期粒度组装数据
switch param.Granularity {
case types.Monthly:
request.Month = ¶m.BillingCycle
case types.Daily:
beginTime, endTime, err := parseDateStartEndTime(param.BillingDate)
if err != nil {
return types.DataInQueryAccountBill{}, err
}
request.BeginTime = &beginTime
request.EndTime = &endTime
default:
return types.DataInQueryAccountBill{}, errors.New("Unknown Granularity")
}
// 分页直到获取全部
var allBillList []*billing.BillDetail
for {
limiter := limiter.Limiters.GetLimiter(p.ProviderType().String()+"-"+"DescribeBillDetail", 3)
limiter.Take()
response, err := p.billingClient.DescribeBillDetail(request)
if err != nil {
return types.DataInQueryAccountBill{}, err
}
if response == nil || response.Response == nil || response.Response.Total == nil {
break
}
totalCount := response.Response.Total
if len(allBillList) == 0 {
allBillList = make([]*billing.BillDetail, 0, *totalCount)
}
allBillList = append(allBillList, response.Response.DetailSet...)
if uint64(len(allBillList)) >= *totalCount {
break
}
offset += _maxPageSize
request.Offset = &offset
}
itemList, err := convQueryAccountBill(param, allBillList)
if err != nil {
return types.DataInQueryAccountBill{}, err
}
return types.DataInQueryAccountBill{
BillingCycle: param.BillingCycle,
TotalCount: len(itemList),
Items: types.ItemsInQueryAccountBill{Item: itemList},
}, nil
}
func convQueryAccountBill(param types.QueryAccountBillRequest, billList []*billing.BillDetail) ([]types.AccountBillItem, error) {
if billList == nil {
return nil, errors.New("invalid bill list")
}
if len(billList) == 0 {
return []types.AccountBillItem{}, nil
}
billingItem := make([]types.AccountBillItem, 0)
costMap := make(map[string]float64)
checkMap := make(map[string]bool)
var totalCost float64
currency := convCurrency(tea.StringValue(billList[0].ComponentSet[0].PriceUnit))
for _, item := range billList {
costMap[tea.StringValue(item.BusinessCodeName)+tea.StringValue(item.PayModeName)] += sumComponentSet(item.ComponentSet)
}
if param.IsGroupByProduct {
for _, item := range billList {
if checkMap[tea.StringValue(item.BusinessCodeName)+tea.StringValue(item.PayModeName)] {
continue
}
temp := types.AccountBillItem{
PipCode: types.PipCode(tea.StringValue(item.BusinessCode)),
ProductName: tea.StringValue(item.BusinessCodeName),
BillingDate: "",
SubscriptionType: convSubscriptionType(tea.StringValue(item.PayModeName)),
Currency: currency,
PretaxAmount: costMap[tea.StringValue(item.BusinessCodeName)+tea.StringValue(item.PayModeName)],
}
if param.Granularity == types.Daily {
temp.BillingDate = param.BillingDate
}
billingItem = append(billingItem, temp)
checkMap[tea.StringValue(item.BusinessCodeName)+tea.StringValue(item.PayModeName)] = true
}
return billingItem, nil
}
for _, cost := range costMap {
totalCost += cost
}
temp := types.AccountBillItem{
Currency: currency,
PretaxAmount: totalCost,
}
if param.Granularity == types.Daily {
temp.BillingDate = param.BillingDate
}
billingItem = append(billingItem, temp)
return billingItem, nil
}
func convPipCode(bizCode *string) types.PipCode {
return types.PipCode(*bizCode)
}
func convPretaxAmount(price *string) float64 {
if price == nil {
return 0
}
priceFloat, _ := strconv.ParseFloat(*price, 64)
return priceFloat
}
func convPayTime2YM(payTime *string) (string, error) {
if payTime == nil {
return "", errors.New("PayTime empty")
}
t, err := time.ParseInLocation("2006-01-02 15:04:05", *payTime, time.Local)
if err != nil {
return "", err
}
return t.Format("2006-01-02"), nil
}
func parseDateStartEndTime(date string) (string, string, error) {
if date == "" {
return "", "", errors.New("date empty")
}
t, err := time.ParseInLocation("2006-01-02", date, time.Local)
if err != nil {
return "", "", err
}
dateFormatted := t.Format("2006-01-02")
return dateFormatted + " 00:00:00", dateFormatted + " 23:59:59", nil
}
func sumComponentSet(componentSet []*billing.BillDetailComponent) (result float64) {
for _, v := range componentSet {
result += convPretaxAmount(v.RealCost)
}
return
}
func convSubscriptionType(subscriptionType string) cloud.SubscriptionType {
switch subscriptionType {
case "包年包月":
return cloud.PrePaid
case "按量计费":
return cloud.PostPaid
}
return "undefined"
}
func convCurrency(priceUnit string) (currency string) {
strs := strings.Split(priceUnit, "/")
if len(strs) == 0 {
return
}
switch strs[0] {
case "元":
currency = "CNY"
case "刀":
currency = "USD"
}
return
}
func (p *TencentCloud) DescribeMetricList(ctx context.Context, param types.DescribeMetricListRequest) (types.DescribeMetricList, error) {
// TODO implement me
return types.DescribeMetricList{}, nil
}
func (p *TencentCloud) DescribeRegions(ctx context.Context, param types.DescribeRegionsRequest) (types.DescribeRegions, error) {
// TODO implement me
return types.DescribeRegions{}, nil
}
func (p *TencentCloud) DescribeInstanceBill(ctx context.Context, param types.DescribeInstanceBillRequest, isAll bool) (types.DescribeInstanceBill, error) {
return types.DescribeInstanceBill{}, nil
}
func (p *TencentCloud) QueryAvailableInstances(ctx context.Context, param types.QueryAvailableInstancesRequest) (types.QueryAvailableInstances, error) {
return types.QueryAvailableInstances{}, nil
}
func (p *TencentCloud) DescribeInstances(ctx context.Context, param types.DescribeInstancesRequest) (types.DescribeInstances, error) {
return types.DescribeInstances{}, nil
}