forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gc_gke.go
232 lines (183 loc) · 5.25 KB
/
gc_gke.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
package cmd
import (
"io"
"strings"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/jenkins-x/golang-jenkins"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
)
// GetOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type GCGKEOptions struct {
CommonOptions
RevisionHistoryLimit int
jclient gojenkins.JenkinsClient
}
var (
GCGKELong = templates.LongDesc(`
Garbage collect Google Container Engine resources that are not deleted when a delete cluster is performed
This command will generate the gcloud command to run and delete external loadbalancers and persistent disks
that are no longer in use.
`)
GCGKEExample = templates.Examples(`
jx garbage collect gke
jx gc gke
`)
)
type Rules struct {
Rules []Rule
}
type Rule struct {
Name string `json:"name"`
TargetTags []string `json:"targetTags"`
}
// NewCmd s a command object for the "step" command
func NewCmdGCGKE(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &GCGKEOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
}
cmd := &cobra.Command{
Use: "gke",
Short: "garbage collection for gke",
Long: GCGKELong,
Example: GCGKEExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
return cmd
}
// Run implements this command
func (o *GCGKEOptions) Run() error {
dir, err := os.Getwd()
if err != nil {
return err
}
path := util.UrlJoin(dir, "gc_gke.sh")
util.FileExists(path)
os.Remove(path)
message := `
###################################################################################################
#
# WARNING: this command is experimental and the generated script should be executed at the users own risk. We use this
# generated command on the Jenkins X project itself but it has not been tested on other clusters.
#
###################################################################################################
%s
%v
`
log.Warn("This command is experimental and the generated script should be executed at the users own risk\n")
log.Warn("We will generate a script for you to review and execute, this command will not delete any resources by itself\n")
log.Info("It may take a few minutes to create the script\n")
fw, err := o.cleanUpFirewalls()
if err != nil {
return err
}
disks, err := o.cleanUpPersistentDisks()
if err != nil {
return err
}
data := fmt.Sprintf(message, fw, disks)
data = strings.Replace(data, "[", "", -1)
data = strings.Replace(data, "]", "", -1)
err = ioutil.WriteFile("gc_gke.sh", []byte(data), util.DefaultWritePermissions)
log.Info("Script 'gc_gke.sh' created!\n")
return nil
}
func (p *GCGKEOptions) cleanUpFirewalls() (string, error) {
o := CommonOptions{}
data, err := o.getCommandOutput("", "gcloud", "compute", "firewall-rules", "list", "--format", "json")
if err != nil {
return "", err
}
var rules []Rule
err = json.Unmarshal([]byte(data), &rules)
if err != nil {
return "", err
}
out, err := o.getCommandOutput("", "gcloud", "container", "clusters", "list")
if err != nil {
return "", err
}
lines := strings.Split(string(out), "\n")
var existingClusters []string
for _, l := range lines {
if strings.Contains(l, "NAME") {
continue
}
if strings.TrimSpace(l) == "" {
break
}
fields := strings.Fields(l)
existingClusters = append(existingClusters, fields[0])
}
var nameToDelete []string
for _, rule := range rules {
name := strings.TrimPrefix(rule.Name, "gke-")
if !contains(existingClusters, name) {
for _, tagFull := range rule.TargetTags {
tag := strings.TrimPrefix(tagFull, "gke-")
if !contains(existingClusters, tag) {
nameToDelete = append(nameToDelete, rule.Name)
}
}
}
}
if nameToDelete != nil {
args := "gcloud compute firewall-rules delete "
for _, name := range nameToDelete {
args = args + " " + name
}
return args, nil
}
return "# No firewalls found for deletion", nil
}
func (o *GCGKEOptions) cleanUpPersistentDisks() ([]string, error) {
cmd := "gcloud compute zones list | grep -v NAME | awk '{printf $1 \" \"}'"
rs, err := o.getCommandOutput("", "bash", "-c", cmd)
if err != nil {
return nil, err
}
zones := strings.Split(rs, " ")
var line []string
for _, z := range zones {
diskCmd := fmt.Sprintf("gcloud compute disks list --filter=\"NOT users:* AND zone:(%s)\" | grep -v NAME | awk '{printf $1 \" \"}'", z)
diskRs, err := o.getCommandOutput("", "bash", "-c", diskCmd)
if err != nil {
return nil, err
}
disks := strings.Split(diskRs, " ")
for _, d := range disks {
if strings.HasPrefix(d, "gke-") {
line = append(line, fmt.Sprintf("gcloud compute disks delete --zone=%s --quiet %s\n", z, d))
}
}
}
if len(line) == 0 {
line = append(line, "# No disks found for deletion\n")
}
return line, nil
}
func contains(s []string, e string) bool {
for _, a := range s {
if strings.HasPrefix(e, a) {
return true
}
}
return false
}