Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
212 lines (180 loc) · 6.1 KB
/
Copy pathmain.go
File metadata and controls
212 lines (180 loc) · 6.1 KB
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
package main
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/arafato/cf-nuke/config"
"github.com/arafato/cf-nuke/infrastructure"
_ "github.com/arafato/cf-nuke/resources"
"github.com/arafato/cf-nuke/types"
"github.com/arafato/cf-nuke/utils"
"github.com/arafato/cf-nuke/version"
"github.com/spf13/cobra"
)
// Global flags that can be used across commands
var (
configFile string
key string
accountId string
user string
mode string
noDryRun bool
shortVersion bool
)
var rootCmd = &cobra.Command{
Use: "cf-nuke",
Short: "cf-nuke removes every resource from your cloudflare account",
Long: `A tool which removes every resource from an cloudflare account. Use it with caution, since it cannot distinguish between production and non-production.`,
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version of cf-nuke",
Run: func(cmd *cobra.Command, args []string) {
if shortVersion {
version.PrintShort(os.Stdout)
} else {
version.Print(os.Stdout)
}
},
}
var nukeCmd = &cobra.Command{
Use: "nuke",
Short: "Execute nuke operation",
Long: `Nuke command performs destructive operations based on the provided configuration.
Use with caution and review the dry-run output before executing.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
mode, _ := cmd.Flags().GetString("mode")
if mode != "token" && mode != "account" {
return fmt.Errorf("invalid mode '%s', must be 'token' or 'account'", mode)
}
if mode == "account" {
user, _ := cmd.Flags().GetString("user")
if user == "" {
return fmt.Errorf("--user flag is required when --mode is 'account'")
}
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
executeNuke()
},
}
var listCmd = &cobra.Command{
Use: "list",
Short: "List all supported resource types",
Long: "List all resources types that are currently supported by this version of cf-nuke.",
Run: func(cmd *cobra.Command, args []string) {
collectors := infrastructure.ListCollectors()
for _, name := range collectors {
fmt.Println(name)
}
},
}
func init() {
rootCmd.AddCommand(nukeCmd)
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(listCmd)
versionCmd.Flags().BoolVar(&shortVersion, "short", false, "Print short version string")
nukeCmd.Flags().StringVarP(&mode, "mode", "m", "", "The mode of operation ('token' or 'account')")
nukeCmd.Flags().StringVarP(&configFile, "config", "c", "", "Path to configuration file (required)")
nukeCmd.Flags().StringVarP(&key, "key", "k", "", "Key for operation (required)")
nukeCmd.Flags().StringVarP(&accountId, "account-id", "a", "", "Cloudflare account id (required)")
nukeCmd.Flags().BoolVar(&noDryRun, "no-dry-run", false, "Execute without dry run")
nukeCmd.Flags().StringVarP(&user, "user", "u", "", "The user identifier (required only for 'account' mode)")
nukeCmd.MarkFlagRequired("config")
nukeCmd.MarkFlagRequired("account-id")
nukeCmd.MarkFlagRequired("key")
}
func executeNuke() {
config, err := config.LoadConfig(configFile)
if err != nil {
log.Fatalf("Error loading configuration: %v", err)
os.Exit(1)
}
creds := &types.Credentials{
AccountID: accountId,
APIKey: key,
User: user,
Mode: types.Mode(mode), // this is safe due to pre-check in PreRunE
}
resources, scanDuration := utils.SpinWhile("Scanning Cloudflare account...", func() types.Resources {
creds.S3AccessKeyID, creds.S3AccessSecret, err = utils.CreateTemporaryR2Token(creds)
time.Sleep(3 * time.Second)
if err != nil {
log.Fatalf("Error creating temporary S3/R2 token: %v", err)
os.Exit(1)
}
// Fetch zones for zone-level collectors (excluding filtered zones)
zones, err := utils.FetchZones(creds, config.Zones.Excludes)
if err != nil {
log.Fatalf("Error fetching zones: %v", err)
os.Exit(1)
}
return infrastructure.ProcessCollection(creds, zones)
})
infrastructure.FilterCollection(resources, config)
visibleCount := resources.VisibleCount()
fmt.Printf("Scan completed in %s: Found %d resources in total in account %s: To be removed %d, Filtered %d\n", formatDuration(scanDuration), visibleCount, accountId, resources.NumOf(types.Ready), resources.NumOf(types.Filtered))
utils.PrettyPrintStatus(resources)
// Flush logs to file and print summary if there were warnings/errors
logger := utils.GetLogger()
if logger.HasEntries() {
if err := logger.Flush(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to write log file: %v\n", err)
}
logger.PrintSummary()
}
if !noDryRun {
fmt.Println("Dry run complete.")
} else {
fmt.Println("Executing actual nuke operation... do you really want to continue (yes/no)?")
var confirm string
fmt.Scanln(&confirm)
if confirm != "yes" {
err := utils.DeleteTemporaryR2Token(creds, resources)
if err != nil {
fmt.Println("Failed to delete temporary account token for R2/S3 operations:", err)
}
fmt.Println("Nuke operation aborted.")
return
}
fmt.Println("Nuke operation confirmed.")
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
// Start printer goroutine BEFORE removal to show progress during the operation
wg.Add(1)
go utils.PrintStatusWithContext(&wg, ctx, resources)
if err := infrastructure.RemoveCollection(ctx, resources); err != nil {
log.Printf("Error removing resources: %v", err)
}
// Cancel printer after removal completes, then wait for it to finish
cancel()
wg.Wait()
// Print any resources that failed to delete with their error messages
utils.PrintFailedResources(resources)
fmt.Println("Process finished.")
}
err = utils.DeleteTemporaryR2Token(creds, resources)
if err != nil {
fmt.Println("Failed to delete temporary account token for R2/S3 operations:", err)
}
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// formatDuration formats a duration as "30s" or "1m30s" style
func formatDuration(d time.Duration) string {
d = d.Round(time.Second)
m := d / time.Minute
s := (d % time.Minute) / time.Second
if m > 0 {
return fmt.Sprintf("%dm%ds", m, s)
}
return fmt.Sprintf("%ds", s)
}