/
sandbox.go
262 lines (232 loc) · 6.38 KB
/
sandbox.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
package sandbox
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"html/template"
"net/mail"
"net/url"
"strings"
"time"
"github.com/cloudfoundry-community/go-cfclient"
"gopkg.in/gomail.v2"
)
// SMTPOptions describes configation for sending mail via SMTP
type SMTPOptions struct {
SMTPHost string `envconfig:"smtp_host" required:"true"`
SMTPPort int `envconfig:"smtp_port" default:"587"`
SMTPUser string `envconfig:"smtp_user" required:"true"`
SMTPPass string `envconfig:"smtp_pass" required:"true"`
SMTPCert string `envconfig:"smtp_cert"`
}
// ListRecipients get a list of recipient emails from space roles
func ListRecipients(userGUIDs map[string]bool, roles []cfclient.SpaceRole) (addresses, developers, managers []string) {
addresses = []string{}
developers = []string{}
managers = []string{}
for _, role := range roles {
if _, ok := userGUIDs[role.Guid]; !ok {
continue
}
if _, err := mail.ParseAddress(role.Username); err == nil {
addresses = append(addresses, role.Username)
}
for _, roleType := range role.SpaceRoles {
if roleType == "space_developer" {
developers = append(developers, role.Guid)
} else if roleType == "space_manager" {
managers = append(managers, role.Guid)
}
}
}
return
}
// PurgeSpace deletes a space; if the delete fails, it deletes all applications within the space
func PurgeSpace(client *cfclient.Client, space cfclient.Space) error {
spaceErr := client.DeleteSpace(space.Guid, true, false)
if spaceErr != nil {
query := url.Values(map[string][]string{"q": []string{fmt.Sprintf("space_guid:%s", space.Guid)}})
apps, err := client.ListAppsByQuery(query)
if err != nil {
return err
}
for _, app := range apps {
if err := client.DeleteApp(app.Guid); err != nil {
return err
}
}
return spaceErr
}
return nil
}
// RenderTemplate renders a template to string
func RenderTemplate(tmpl *template.Template, data map[string]interface{}) (string, error) {
buf := bytes.Buffer{}
if err := tmpl.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
// SendMail sends email via SMTP
func SendMail(
opts SMTPOptions,
sender string,
subject string,
body string,
recipients []string,
) error {
if len(recipients) == 0 {
return nil
}
d := gomail.NewDialer(opts.SMTPHost, opts.SMTPPort, opts.SMTPUser, opts.SMTPPass)
if opts.SMTPCert != "" {
pool := x509.NewCertPool()
pool.AppendCertsFromPEM([]byte(opts.SMTPCert))
d.TLSConfig = &tls.Config{
ServerName: opts.SMTPHost,
RootCAs: pool,
}
}
s, err := d.Dial()
if err != nil {
return err
}
m := gomail.NewMessage()
m.SetHeaders(map[string][]string{
"From": {sender},
"Subject": {subject},
"To": recipients,
})
m.SetBody("text/html", body)
return gomail.Send(s, m)
}
// ListSandboxOrgs lists all sandbox organizations
func ListSandboxOrgs(client *cfclient.Client, prefix string) ([]cfclient.Org, error) {
sandboxes := []cfclient.Org{}
orgs, err := client.ListOrgs()
if err != nil {
return sandboxes, err
}
for _, org := range orgs {
if strings.HasPrefix(org.Name, prefix) {
sandboxes = append(sandboxes, org)
}
}
return sandboxes, nil
}
// ListOrgResources fetches apps, service instances, and spaces within an organization
func ListOrgResources(
client *cfclient.Client,
org cfclient.Org,
) (
spaces []cfclient.Space,
apps []cfclient.App,
instances []cfclient.ServiceInstance,
err error,
) {
query := url.Values(map[string][]string{"q": []string{"organization_guid:" + org.Guid}})
apps, err = client.ListAppsByQuery(query)
if err != nil {
return
}
instances, err = client.ListServiceInstancesByQuery(query)
if err != nil {
return
}
spaces, err = client.OrgSpaces(org.Guid)
if err != nil {
return
}
return
}
// GetFirstResource gets the creation timestamp of the earliest-created resource in a space
func GetFirstResource(
space cfclient.Space,
apps []cfclient.App,
instances []cfclient.ServiceInstance,
) (time.Time, error) {
groupedApps := groupAppsBySpace(apps)
groupedInstances := groupInstancesBySpace(instances)
var firstResource time.Time
for _, app := range groupedApps[space.Guid] {
createdAt, err := time.Parse(time.RFC3339Nano, app.CreatedAt)
if err != nil {
return firstResource, err
}
if firstResource.IsZero() || createdAt.Before(firstResource) {
firstResource = createdAt
}
}
for _, instance := range groupedInstances[space.Guid] {
createdAt, err := time.Parse(time.RFC3339Nano, instance.CreatedAt)
if err != nil {
return firstResource, err
}
if firstResource.IsZero() || createdAt.Before(firstResource) {
firstResource = createdAt
}
}
return firstResource, nil
}
// SpaceDetails describes a space and its first resource creation time
type SpaceDetails struct {
Timestamp time.Time
Space cfclient.Space
}
// ListPurgeSpaces identifies spaces that will be notified or purged
func ListPurgeSpaces(
spaces []cfclient.Space,
apps []cfclient.App,
instances []cfclient.ServiceInstance,
now time.Time,
notifyThreshold int,
purgeThreshold int,
timeStartsAt time.Time,
) (
toNotify []SpaceDetails,
toPurge []SpaceDetails,
err error,
) {
var firstResource time.Time
for _, space := range spaces {
firstResource, err = GetFirstResource(space, apps, instances)
if err != nil {
return
}
if firstResource.IsZero() {
continue
}
if timeStartsAt.After(firstResource) {
firstResource = timeStartsAt
}
firstResource := firstResource.Truncate(24 * time.Hour)
delta := int(now.Sub(firstResource).Hours() / 24)
if delta >= purgeThreshold {
toPurge = append(toPurge, SpaceDetails{firstResource, space})
} else if delta >= notifyThreshold {
toNotify = append(toNotify, SpaceDetails{firstResource, space})
}
}
return
}
func groupAppsBySpace(apps []cfclient.App) map[string][]cfclient.App {
grouped := map[string][]cfclient.App{}
for _, app := range apps {
if _, ok := grouped[app.SpaceGuid]; !ok {
grouped[app.SpaceGuid] = []cfclient.App{}
}
grouped[app.SpaceGuid] = append(grouped[app.SpaceGuid], app)
}
return grouped
}
func groupInstancesBySpace(instances []cfclient.ServiceInstance) map[string][]cfclient.ServiceInstance {
grouped := map[string][]cfclient.ServiceInstance{}
for _, instance := range instances {
if _, ok := grouped[instance.SpaceGuid]; !ok {
grouped[instance.SpaceGuid] = []cfclient.ServiceInstance{}
}
grouped[instance.SpaceGuid] = append(grouped[instance.SpaceGuid], instance)
}
return grouped
}