-
Notifications
You must be signed in to change notification settings - Fork 524
/
main.go
387 lines (317 loc) · 11 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"bytes"
"context"
"fmt"
"io"
stdLog "log"
"os"
"runtime/debug"
"strings"
"github.com/pkg/errors"
"github.com/pkg/profile"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/infracost/infracost/internal/apiclient"
"github.com/infracost/infracost/internal/clierror"
"github.com/infracost/infracost/internal/config"
"github.com/infracost/infracost/internal/logging"
"github.com/infracost/infracost/internal/ui"
"github.com/infracost/infracost/internal/update"
"github.com/infracost/infracost/internal/version"
)
func init() {
// set the stdlib default logger to flush to discard, this is done as a number of
// Terraform libs use the std logger directly, which impacts Infracost output.
stdLog.SetOutput(io.Discard)
}
func main() {
if os.Getenv("INFRACOST_MEMORY_PROFILE") == "true" {
defer profile.Start(profile.MemProfile, profile.ProfilePath(".")).Stop()
} else if os.Getenv("INFRACOST_CPU_PROFILE") == "true" {
defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop()
}
Run(nil, nil)
err := apiclient.GetPricingAPIClient(nil).FlushCache()
if err != nil {
logging.Logger.Debug().Err(err).Msg("could not flush pricing API cache to filesystem")
}
}
// Run starts the Infracost application with the configured cobra cmds.
// Cmd args and flags are parsed from the cli, but can also be directly injected
// using the modifyCtx and args parameters.
func Run(modifyCtx func(*config.RunContext), args *[]string) {
ctx, err := config.NewRunContextFromEnv(context.Background())
if err != nil {
if err.Error() != "" {
ui.PrintError(ctx.ErrWriter, err.Error())
}
ctx.Exit(1)
}
if modifyCtx != nil {
modifyCtx(ctx)
}
var appErr error
updateMessageChan := make(chan *update.Info)
defer func() {
if appErr != nil {
if v, ok := appErr.(*clierror.PanicError); ok {
handleUnexpectedErr(ctx, v)
} else {
handleCLIError(ctx, appErr)
}
}
unexpectedErr := recover()
if unexpectedErr != nil {
panicErr := clierror.NewPanicError(fmt.Errorf("%s", unexpectedErr), debug.Stack())
handleUnexpectedErr(ctx, panicErr)
}
handleUpdateMessage(updateMessageChan)
if appErr != nil || unexpectedErr != nil {
ctx.Exit(1)
}
}()
startUpdateCheck(ctx, updateMessageChan)
rootCmd := newRootCmd(ctx)
if args != nil {
rootCmd.SetArgs(*args)
}
appErr = rootCmd.Execute()
}
type debugWriter struct {
f *os.File
}
func (d debugWriter) Write(p []byte) (n int, err error) {
p = bytes.Trim(p, " \n\t")
return d.f.Write(append(p, []byte("\n")...))
}
func newRootCmd(ctx *config.RunContext) *cobra.Command {
rootCmd := &cobra.Command{
Use: "infracost",
Version: version.Version,
Short: "Cloud cost estimates for Terraform",
Long: fmt.Sprintf(`Infracost - cloud cost estimates for Terraform
%s
Quick start: https://infracost.io/docs
Add cost estimates to your pull requests: https://infracost.io/cicd`, ui.BoldString("DOCS")),
Example: ` Show cost diff from Terraform directory:
infracost breakdown --path /code --format json --out-file infracost-base.json
# Make Terraform code changes
infracost diff --path /code --compare-to infracost-base.json
Show cost breakdown from Terraform directory:
infracost breakdown --path /code --terraform-var-file my.tfvars`,
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
ctx.ContextValues.SetValue("command", cmd.Name())
ctx.CMD = cmd.Name()
if cmd.Name() == "comment" || (cmd.Parent() != nil && cmd.Parent().Name() == "comment") {
ctx.SetIsInfracostComment()
}
out, _ := cmd.Flags().GetBool("debug-report")
if out {
debugFile := "infracost-debug-report.json"
var f *os.File
var err error
if _, serr := os.Stat(debugFile); serr != nil {
f, err = os.OpenFile(debugFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
} else {
f, err = os.Create(debugFile)
}
if err != nil {
return fmt.Errorf("could not generate debug report file %w", err)
}
_, _ = f.WriteString("[\n")
writer := debugWriter{f: f}
ctx.ErrWriter = writer
ctx.Config.SetLogWriter(writer)
}
err := loadGlobalFlags(ctx, cmd)
if err != nil {
return err
}
loadCloudSettings(ctx)
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
// Show the help
return cmd.Help()
},
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
out, _ := cmd.Flags().GetBool("debug-report")
if out {
if f, ok := ctx.Config.LogWriter().(debugWriter); ok {
_, _ = f.f.WriteString("{\"msg\":\"program finished\"}\n")
_, _ = f.f.WriteString("]")
_ = f.f.Close()
}
}
return nil
},
}
rootCmd.PersistentFlags().Bool("no-color", false, "Turn off colored output")
rootCmd.PersistentFlags().String("log-level", "", "Log level (trace, debug, info, warn, error, fatal)")
rootCmd.PersistentFlags().Bool("debug-report", false, "Generate a debug report file which can be sent to Infracost team")
rootCmd.AddCommand(authCmd(ctx))
rootCmd.AddCommand(registerCmd(ctx))
rootCmd.AddCommand(configureCmd(ctx))
rootCmd.AddCommand(diffCmd(ctx))
rootCmd.AddCommand(breakdownCmd(ctx))
rootCmd.AddCommand(outputCmd(ctx))
rootCmd.AddCommand(uploadCmd(ctx))
rootCmd.AddCommand(commentCmd(ctx))
rootCmd.AddCommand(completionCmd())
rootCmd.AddCommand(figAutocompleteCmd())
rootCmd.AddCommand(newGenerateCommand())
rootCmd.SetUsageTemplate(fmt.Sprintf(`%s{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
%s
{{.NameAndAliases}}{{end}}{{if .HasExample}}
%s
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
%s{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
%s
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
%s
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
%s{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`,
ui.BoldString("USAGE"),
ui.BoldString("ALIAS"),
ui.BoldString("EXAMPLES"),
ui.BoldString("AVAILABLE COMMANDS"),
ui.BoldString("FLAGS"),
ui.BoldString("GLOBAL FLAGS"),
ui.BoldString("ADDITIONAL HELP TOPICS"),
))
rootCmd.SetVersionTemplate("Infracost {{.Version}}\n")
rootCmd.SetOut(ctx.OutWriter)
rootCmd.SetErr(ctx.ErrWriter)
return rootCmd
}
func startUpdateCheck(ctx *config.RunContext, c chan *update.Info) {
go func() {
updateInfo, err := update.CheckForUpdate(ctx)
if err != nil {
logging.Logger.Debug().Err(err).Msg("error checking for Infracost CLI update")
}
c <- updateInfo
close(c)
}()
}
func loadCloudSettings(ctx *config.RunContext) {
if ctx.Config.IsSelfHosted() || (ctx.Config.EnableCloud != nil && !*ctx.Config.EnableCloud) {
return
}
dashboardClient := apiclient.NewDashboardAPIClient(ctx)
result, err := dashboardClient.QueryCLISettings()
if err != nil {
logging.Logger.Debug().Err(err).Msg("Failed to load settings from Infracost Cloud ")
// ignore the error so the command can continue without failing
return
}
logging.Logger.Debug().Str("result", fmt.Sprintf("%+v", result)).Msg("Successfully loaded settings from Infracost Cloud")
ctx.Config.EnableCloudForOrganization = result.CloudEnabled
if result.UsageAPIEnabled && ctx.Config.UsageAPIEndpoint == "" {
ctx.Config.UsageAPIEndpoint = ctx.Config.DashboardAPIEndpoint
logging.Logger.Debug().Msg("Enabled usage API")
}
if result.ActualCostsEnabled && ctx.Config.UsageAPIEndpoint != "" {
ctx.Config.UsageActualCosts = true
logging.Logger.Debug().Msg("Enabled actual costs")
}
if (result.PoliciesAPIEnabled || result.TagsAPIEnabled) && ctx.Config.PolicyV2APIEndpoint == "" {
ctx.Config.PolicyV2APIEndpoint = ctx.Config.DashboardAPIEndpoint
logging.Logger.Debug().Msg("Using default policies V2 endpoint")
}
if result.PoliciesAPIEnabled {
ctx.Config.PoliciesEnabled = true
logging.Logger.Debug().Msg("Enabled policies V2")
}
if result.TagsAPIEnabled {
ctx.Config.TagPoliciesEnabled = true
logging.Logger.Debug().Msg("Enabled tag policies")
}
}
func checkAPIKey(apiKey string, apiEndpoint string, defaultEndpoint string) error {
if apiEndpoint == defaultEndpoint && apiKey == "" {
return fmt.Errorf(
"No INFRACOST_API_KEY environment variable is set.\nWe run a free Cloud Pricing API, to get an API key run %s",
ui.PrimaryString("infracost auth login"),
)
}
return nil
}
var ignoredErrors = []string{
"Policy check failed",
"Governance check failed",
}
func handleCLIError(ctx *config.RunContext, cliErr error) {
if cliErr.Error() != "" {
ui.PrintError(ctx.ErrWriter, cliErr.Error())
}
for _, pattern := range ignoredErrors {
if strings.Contains(cliErr.Error(), pattern) {
return
}
}
err := apiclient.ReportCLIError(ctx, cliErr, true)
if err != nil {
logging.Logger.Debug().Err(err).Msg("error reporting CLI error")
}
}
func handleUnexpectedErr(ctx *config.RunContext, err error) {
ui.PrintUnexpectedErrorStack(err)
err = apiclient.ReportCLIError(ctx, err, false)
if err != nil {
logging.Logger.Debug().Err(err).Msg("error sending unexpected runtime error")
}
}
func handleUpdateMessage(updateMessageChan chan *update.Info) {
updateInfo := <-updateMessageChan
if updateInfo != nil {
msg := fmt.Sprintf("\n%s %s %s → %s\n%s\n",
ui.WarningString("Update:"),
"A new version of Infracost is available:",
ui.PrimaryString(version.Version),
ui.PrimaryString(updateInfo.LatestVersion),
ui.Indent(updateInfo.Cmd, " "),
)
fmt.Fprint(os.Stderr, msg)
}
}
func loadGlobalFlags(ctx *config.RunContext, cmd *cobra.Command) error {
if ctx.IsCIRun() {
ctx.Config.NoColor = true
}
err := ctx.Config.LoadGlobalFlags(cmd)
if err != nil {
return err
}
ctx.ContextValues.SetValue("dashboardEnabled", ctx.Config.EnableDashboard)
ctx.ContextValues.SetValue("cloudEnabled", ctx.IsCloudEnabled())
ctx.ContextValues.SetValue("isDefaultPricingAPIEndpoint", ctx.Config.PricingAPIEndpoint == ctx.Config.DefaultPricingAPIEndpoint)
flagNames := make([]string, 0)
cmd.Flags().Visit(func(f *pflag.Flag) {
flagNames = append(flagNames, f.Name)
})
ctx.ContextValues.SetValue("flags", flagNames)
return nil
}
// saveOutFile saves the output of the command to the file path past in the `--out-file` flag
func saveOutFile(ctx *config.RunContext, cmd *cobra.Command, outFile string, b []byte) error {
return saveOutFileWithMsg(ctx, cmd, outFile, fmt.Sprintf("Output saved to %s", outFile), b)
}
// saveOutFile saves the output of the command to the file path past in the `--out-file` flag
func saveOutFileWithMsg(ctx *config.RunContext, cmd *cobra.Command, outFile, successMsg string, b []byte) error {
err := os.WriteFile(outFile, b, 0644) // nolint:gosec
if err != nil {
return errors.Wrap(err, "Unable to save output")
}
logging.Logger.Info().Msg(successMsg)
return nil
}