forked from GoogleCloudPlatform/gke-shift-left-cost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (195 loc) · 6.68 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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"github.com/fernandorubbo/k8s-cost-estimator/api"
log "github.com/sirupsen/logrus"
"sigs.k8s.io/yaml"
)
const version = "v0.0.1"
var (
k8sPath = flag.String("k8s", "", "Required. Path to k8s manifests folder")
k8sPrevPath = flag.String("k8s-prev", "", "Optional. Path to the previous K8s manifests folder. Useful to compare prices.")
outputFile = flag.String("output", "", "Optional. Output file path. If not provided, console is used")
environ = flag.String("environ", "LOCAL", "Optional. Where your code is running at. Used to know determine the output file format: GITHUB | GITLAB | LOCAL")
authKey = flag.String("auth-key", "", "Optional. The GCP service account JOSN key filepath. If not provided, default service account is used (Run 'gcloud auth application-default login' to set your user as the default service account)")
configFile = flag.String("config", "", "Optional. The defaults configuration YAML filepath to set: machine family, region and compute resources not provided in k8s manifests")
verbosity = flag.String("v", "panic", "Optional. Verbosity: panic|fatal|error|warn|info|debug|trace. Default panic")
)
func init() {
flag.Parse()
level, err := log.ParseLevel(*verbosity)
exitOnError("Invalid 'verbosity' parameter", err)
if *environ == "GITLAB" {
log.SetFormatter(&log.JSONFormatter{
DisableTimestamp: true,
FieldMap: log.FieldMap{
log.FieldKeyLevel: "severity",
},
})
}
log.SetOutput(os.Stdout)
log.SetLevel(level)
// required flags
validateK8sPath(*k8sPath, "k8s")
}
func main() {
log.Infof("Starting cost estimation (version %s)...", version)
config := readConfigFromFile()
priceCatalog := newGCPPriceCatalog(config)
currentCost := estimateCost(*k8sPath, config, priceCatalog)
if isPreviousPathProvided() {
log.Infof("Comparing current cost against previous version. Paths: '%s' vs '%s'", *k8sPath, *k8sPrevPath)
previousCosts := estimateCost(*k8sPrevPath, config, priceCatalog)
diffCost := currentCost.Subtract(previousCosts)
outputDiff(diffCost)
} else {
output(currentCost.ToMarkdown())
}
log.Info("Finished cost estimation!")
}
func readConfigFromFile() api.CostimatorConfig {
conf := api.ConfigDefaults()
if *configFile != "" {
data, err := ioutil.ReadFile(*configFile)
exitOnError("Unable to read 'config' file", err)
err = yaml.Unmarshal(data, &conf)
exitOnError("Unable to umarshal 'config' file", err)
} else {
log.Debugf("Parameter 'config' not provided. Using default config.")
}
return conf
}
func newGCPPriceCatalog(config api.CostimatorConfig) api.GCPPriceCatalog {
log.Debug("Retriving Price Catalog from GCP...")
credentials := readAuthKeyFromFile()
priceCatalog, err := api.NewGCPPriceCatalog(credentials, config)
exitOnError("Unable to read Pricing Catalog from GCP", err)
return priceCatalog
}
func readAuthKeyFromFile() []byte {
var credentials []byte
if *authKey != "" {
var err error
credentials, err = ioutil.ReadFile(*authKey)
exitOnError("Unable to read auth-key file", err)
} else {
log.Info("auth-key not provided. Using default service account.")
}
return credentials
}
func validateK8sPath(k8sPath string, flag string) {
if !isK8sPathProvided(k8sPath, flag) {
exit(fmt.Sprintf("%s is required", flag))
}
}
func isPreviousPathProvided() bool {
return isK8sPathProvided(*k8sPrevPath, "k8s-prev")
}
func isK8sPathProvided(k8sPath string, flag string) bool {
if k8sPath == "" {
return false
}
f, err := os.Stat(k8sPath)
if os.IsNotExist(err) {
exit(fmt.Sprintf("%s provided does not exists", flag))
}
if !(f.IsDir() || strings.HasSuffix(f.Name(), ".yaml") || strings.HasSuffix(f.Name(), ".yml")) {
exit(fmt.Sprintf("%s provided must be a folder or a yaml file", flag))
}
return true
}
func estimateCost(path string, conf api.CostimatorConfig, pc api.GCPPriceCatalog) api.Cost {
log.Infof("Estimating monthly cost for k8s objects in path '%s'...", path)
manifests := api.Manifests{}
err := manifests.LoadObjectsFromPath(path, conf)
if err != nil {
exitOnError(fmt.Sprintf("Unable estimate cost for %s", path), err)
}
return manifests.EstimateCost(pc)
}
func outputDiff(diffCost api.DiffCost) {
output(diffCost.ToMarkdown())
if *outputFile == "" {
return
}
saveDiffFile(diffCost)
}
func output(markdown string) {
fmt.Printf("\n%s\n", markdown)
if *outputFile == "" {
return
}
switch strings.ToUpper(*environ) {
case "GITHUB":
log.Debugf("Saving Github file at '%s'", *outputFile)
saveGithubFile(markdown)
case "GITLAB":
log.Debugf("Saving Gitlab file at '%s'", *outputFile)
saveGithubFile(markdown)
default:
log.Debugf("Saving Markdown file at '%s'", *outputFile)
saveMarkdownFile(markdown)
}
}
func saveDiffFile(diffCost api.DiffCost) {
ext := path.Ext(*outputFile)
diffOutputFile := (*outputFile)[0:len(*outputFile)-len(ext)] + ".diff"
log.Debugf("Saving Diff file at '%s'", diffOutputFile)
f, err := os.Create(diffOutputFile)
exitOnError(fmt.Sprintf("Creating Diff file %s", diffOutputFile), err)
defer f.Close()
pd := diffCost.MonthlyDiffRange.ToPriceDiff()
err = json.NewEncoder(f).Encode(pd)
exitOnError(fmt.Sprintf("Writting Diff file %s", diffOutputFile), err)
}
func saveGithubFile(markdown string) {
type github struct {
Body string `json:"body"`
}
gh := &github{
Body: markdown,
}
f, err := os.Create(*outputFile)
exitOnError(fmt.Sprintf("Creating output file %s", *outputFile), err)
defer f.Close()
err = json.NewEncoder(f).Encode(gh)
exitOnError(fmt.Sprintf("Writting output file %s", *outputFile), err)
}
func saveMarkdownFile(markdown string) {
err := ioutil.WriteFile(*outputFile, []byte(markdown), 0644)
exitOnError(fmt.Sprintf("Writing output file %s", *outputFile), err)
}
func exitOnError(message string, err error) {
if err != nil {
exitWithError(message, err)
}
}
func exitWithError(message string, err error) {
fmt.Printf("\nError: %s\nCause: %+v\n\nSee parameters options below:\n", err, message)
flag.PrintDefaults()
os.Exit(-1)
}
func exit(message string) {
fmt.Printf("\nError: %s\n\nSee parameters options below:\n", message)
flag.PrintDefaults()
os.Exit(-1)
}