/
main.go
336 lines (288 loc) · 8.52 KB
/
main.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package main
import (
"bytes"
"image"
"image/color"
"image/draw"
"image/png"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/apex/log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/costexplorer"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
)
var (
dataCache *cache.Cache
cacheLock sync.Mutex
)
func generateFaviconHandler(c *gin.Context) {
// Generate the favicon image
faviconImage, err := generateFavicon()
if err != nil {
c.String(http.StatusInternalServerError, "Failed to generate favicon")
return
}
// Create a buffer to write the favicon image
faviconBuffer := new(bytes.Buffer)
// Encode the favicon image as PNG format
err = png.Encode(faviconBuffer, faviconImage)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to encode favicon")
return
}
// Set the response header for the favicon
c.Header("Content-Type", "image/x-icon")
// Write the favicon image buffer to the response
c.Writer.WriteHeader(http.StatusOK)
c.Writer.Write(faviconBuffer.Bytes())
}
func generateFavicon() (image.Image, error) {
// Create a new image for the favicon with a transparent background
faviconImage := image.NewRGBA(image.Rect(0, 0, 16, 16))
// Set the color for the golden circle
goldenColor := color.RGBA{R: 255, G: 215, B: 0, A: 255}
// Draw a filled golden circle on the favicon image
drawCircle(faviconImage, 8, 8, 7, goldenColor)
return faviconImage, nil
}
func drawCircle(img draw.Image, x, y, radius int, col color.RGBA) {
// Iterate over the pixels in the circle and set the color
for i := x - radius; i < x+radius; i++ {
for j := y - radius; j < y+radius; j++ {
if (i-x)*(i-x)+(j-y)*(j-y) < radius*radius {
img.Set(i, j, col)
}
}
}
}
func getWeeklyCost(c *gin.Context) {
// Check if data is present in the cache
cacheLock.Lock()
cachedData, found := dataCache.Get("previous-four-weeks-data")
cacheLock.Unlock()
if found {
c.JSON(http.StatusOK, cachedData)
return
}
// Set up an AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String(os.Getenv("AWS_DEFAULT_REGION")),
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create AWS session"})
return
}
svc := costexplorer.New(sess)
// Calculate the start and end dates for the previous 4 weeks
end := time.Now().AddDate(0, 0, -1) // End at yesterday
start := end.AddDate(0, 0, -27) // Start 4 weeks before yesterday
// Make the API call to retrieve the cost and usage data
input := &costexplorer.GetCostAndUsageInput{
TimePeriod: &costexplorer.DateInterval{
Start: aws.String(start.Format("2006-01-02")),
End: aws.String(end.Format("2006-01-02")),
},
Granularity: aws.String("DAILY"),
Metrics: []*string{aws.String("BlendedCost")},
GroupBy: []*costexplorer.GroupDefinition{
{
Type: aws.String("DIMENSION"),
Key: aws.String("SERVICE"),
},
},
Filter: &costexplorer.Expression{
And: []*costexplorer.Expression{
{
Dimensions: &costexplorer.DimensionValues{
Key: aws.String("RECORD_TYPE"),
Values: []*string{aws.String("Usage")},
},
},
{
Not: &costexplorer.Expression{
Dimensions: &costexplorer.DimensionValues{
Key: aws.String("USAGE_TYPE"),
Values: []*string{aws.String("Credit"), aws.String("Refund")},
},
},
},
},
},
}
log.Info("getWeeklyCost: requesting data to AWS")
output, err := svc.GetCostAndUsage(input)
if err != nil {
response := gin.H{
"error": "Failed to retrieve cost and usage data",
"start": start.String(),
"end": end.String(),
}
if os.Getenv("GIN_MODE") != "release" {
response["exception"] = err.Error()
}
c.JSON(http.StatusInternalServerError, response)
return
}
log.Debugf("getWeeklyCost: GetCostAndUsage output: %+v", output)
// Process the API response and build the result
result := make(map[string]map[string]float64)
categories := make(map[string]bool)
// Retrieve all unique categories
for _, dayData := range output.ResultsByTime {
for _, group := range dayData.Groups {
category := *group.Keys[0]
categories[category] = true
}
}
// Initialize categories for each day with 0 values
for _, dayData := range output.ResultsByTime {
day := *dayData.TimePeriod.Start
result[day] = make(map[string]float64)
for category := range categories {
result[day][category] = 0
}
}
// Update the result with actual data
for _, dayData := range output.ResultsByTime {
day := *dayData.TimePeriod.Start
for _, group := range dayData.Groups {
category := *group.Keys[0]
amountFloat, err := strconv.ParseFloat(*group.Metrics["BlendedCost"].Amount, 64)
if err == nil {
result[day][category] = amountFloat
}
}
}
// Cache the result
cacheLock.Lock()
dataCache.Set("previous-four-weeks-data", result, cache.DefaultExpiration)
cacheLock.Unlock()
c.JSON(http.StatusOK, result)
}
func getMonthlyCost(c *gin.Context) {
// Check if data is present in the cache
cacheLock.Lock()
cachedData, found := dataCache.Get("monthly-cost")
cacheLock.Unlock()
if found {
c.JSON(http.StatusOK, cachedData)
return
}
// Set up an AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String(os.Getenv("AWS_DEFAULT_REGION")),
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create AWS session"})
return
}
svc := costexplorer.New(sess)
// Calculate the start and end dates for the previous year
now := time.Now()
end := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).Add(-time.Nanosecond)
start := end.AddDate(0, -11, 0)
// Make the API call to retrieve the cost and usage data
input := &costexplorer.GetCostAndUsageInput{
TimePeriod: &costexplorer.DateInterval{
Start: aws.String(start.Format("2006-01-02")),
End: aws.String(end.Format("2006-01-02")),
},
Granularity: aws.String("MONTHLY"),
Metrics: []*string{aws.String("BlendedCost")},
GroupBy: []*costexplorer.GroupDefinition{
{
Type: aws.String("DIMENSION"),
Key: aws.String("SERVICE"),
},
},
Filter: &costexplorer.Expression{
And: []*costexplorer.Expression{
{
Dimensions: &costexplorer.DimensionValues{
Key: aws.String("RECORD_TYPE"),
Values: []*string{aws.String("Usage")},
},
},
{
Not: &costexplorer.Expression{
Dimensions: &costexplorer.DimensionValues{
Key: aws.String("USAGE_TYPE"),
Values: []*string{aws.String("Credit"), aws.String("Refund")},
},
},
},
},
},
}
log.Info("getMonthlyCost: requesting data to AWS")
output, err := svc.GetCostAndUsage(input)
if err != nil {
response := gin.H{
"error": "Failed to retrieve cost and usage data",
"start": start.String(),
"end": end.String(),
}
if os.Getenv("GIN_MODE") != "release" {
response["exception"] = err.Error()
}
c.JSON(http.StatusInternalServerError, response)
return
}
log.Debugf("GetCostAndUsage output: %+v", output)
// Process the API response and build the result
result := make(map[string]map[string]float64)
categories := make(map[string]bool)
// Retrieve all unique categories
for _, dayData := range output.ResultsByTime {
for _, group := range dayData.Groups {
category := *group.Keys[0]
categories[category] = true
}
}
// Initialize categories for each day with 0 values
for _, dayData := range output.ResultsByTime {
day := *dayData.TimePeriod.Start
result[day] = make(map[string]float64)
for category := range categories {
result[day][category] = 0
}
}
// Update the result with actual data
for _, dayData := range output.ResultsByTime {
day := *dayData.TimePeriod.Start
for _, group := range dayData.Groups {
category := *group.Keys[0]
amountFloat, err := strconv.ParseFloat(*group.Metrics["BlendedCost"].Amount, 64)
if err == nil {
result[day][category] = amountFloat
}
}
}
// Cache the result
cacheLock.Lock()
dataCache.Set("monthly-cost", result, cache.DefaultExpiration)
cacheLock.Unlock()
c.JSON(http.StatusOK, result)
}
func main() {
dataCache = cache.New(24*time.Hour, 24*time.Hour)
// Set the log level based on the GIN_MODE environment variable
if os.Getenv("GIN_MODE") == "release" {
log.SetLevel(log.InfoLevel)
} else {
log.SetLevel(log.DebugLevel)
}
r := gin.Default()
r.GET("/monthly-cost.json", getMonthlyCost)
r.GET("/weekly-cost.json", getWeeklyCost)
r.GET("/favicon.ico", generateFaviconHandler)
r.Use(static.Serve("/", static.LocalFile("./public", true)))
r.Run(":8080")
}