-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf_app_helpers.go
237 lines (215 loc) · 7.67 KB
/
cf_app_helpers.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
package cloudfoundry
import (
"fmt"
"time"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant"
"code.cloudfoundry.org/cli/resources"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/terraform-providers/terraform-provider-cloudfoundry/cloudfoundry/common"
"github.com/terraform-providers/terraform-provider-cloudfoundry/cloudfoundry/managers"
)
// GetServiceBindingFromList returns the service credential binding and whether it's in the list
func GetServiceBindingFromList(guid string, bindings []resources.ServiceCredentialBinding) (resources.ServiceCredentialBinding, bool) {
for _, binding := range bindings {
if binding.ServiceInstanceGUID == guid {
return binding, true
}
}
return resources.ServiceCredentialBinding{}, false
}
// ReorderBindings -
func ReorderBindings(bindings []resources.ServiceCredentialBinding, currentBindings []interface{}) []resources.ServiceCredentialBinding {
finalBindings := make([]resources.ServiceCredentialBinding, 0)
for _, currentBinding := range currentBindings {
if currentBinding == nil {
continue
}
item := currentBinding.(map[string]interface{})
if binding, ok := GetServiceBindingFromList(item["service_instance"].(string), bindings); ok {
finalBindings = append(finalBindings, binding)
}
}
for _, binding := range bindings {
if _, ok := GetServiceBindingFromList(binding.ServiceInstanceGUID, finalBindings); ok {
continue
}
finalBindings = append(finalBindings, binding)
}
return finalBindings
}
// RemoveStaleEnviromentVariables :
// Remove stale/externally set environment variables
func RemoveStaleEnviromentVariables(d *schema.ResourceData, session *managers.Session, appGUID string, currentEnv map[string]interface{}) error {
var staleVars []string
var vv map[string]interface{}
if v, ok := d.GetOk("environment"); ok {
vv = v.(map[string]interface{})
}
for s := range currentEnv {
found := false
for k := range vv {
if k == s {
found = true
break
}
}
if !found {
staleVars = append(staleVars, s)
}
}
if len(staleVars) > 0 {
env := make(map[string]interface{})
for _, e := range staleVars {
env[e] = nil
}
_, _, err := session.BitsManager.UpdateAppEnvironment(appGUID, env)
return err
}
return nil
}
// UnmapOldRoutes :
// unmap old routes / externally mapped routes
func UnmapOldRoutes(d *schema.ResourceData, client *ccv3.Client) error {
oldRoutes, newRoutes := d.GetChange("routes")
// getListMapChanges returns the routes to remove and the new routes to be added
// new routes are handled later so we only remove deleted routes here
remove, _ := getListMapChanges(oldRoutes, newRoutes, func(source, item map[string]interface{}) bool {
return source["route"] == item["route"] && source["port"] == item["port"]
})
for _, r := range remove {
// r contains route_id and port but port is always 0 as we don't support appPort in v3
// Get list of destinations for each route to remove and delete the destination with matching app GUID
routeGUID := r["route"].(string)
destinations, _, err := client.GetRouteDestinations(routeGUID)
if err != nil {
return err
}
// Loop through the list of destinations to find the one with matching appGUID
for _, destination := range destinations {
if destination.App.GUID == d.Id() {
_, err := client.UnmapRoute(routeGUID, destination.GUID)
// If the destination is not found, we continue instead of raising the error
if err != nil && !IsErrNotFound(err) {
return err
}
}
}
}
return nil
}
// UnbindServiceInstances :
// Unbind service instances that weren't set
func UnbindServiceInstances(d *schema.ResourceData, client *ccv3.Client) error {
oldBindings, newBindings := d.GetChange("service_binding")
// getListMapChanges returns the service credential bindings to remove and new ones to be added
// new service credential bindings are handled later so we only remove deleted ones here
remove, _ := getListMapChanges(oldBindings, newBindings, func(source, item map[string]interface{}) bool {
matchID := source["service_instance"] == item["service_instance"]
if !matchID {
return false
}
// if binding parameters are different, delete the binding
isDiff, err := isDiffAppParamsBinding(source, item)
if err != nil {
panic(err)
}
return !isDiff
})
for _, r := range remove {
// r contains service_instance_id and params as map[string]interface{} or params_json as string
// We simply get all service credential bindings between this app and the service instance then delete
bindings, _, err := client.GetServiceCredentialBindings(
ccv3.Query{
Key: ccv3.AppGUIDFilter,
Values: []string{d.Id()},
},
ccv3.Query{
Key: ccv3.QueryKey("service_instance_guids"),
Values: []string{r["service_instance"].(string)},
},
)
if err != nil {
return err
}
for _, binding := range bindings {
// Delete service binding
jobURL, _, err := client.DeleteServiceCredentialBinding(binding.GUID)
if err != nil {
return err
}
// Poll for service binding deletion
err = common.PollingWithTimeout(func() (bool, error) {
job, _, err := client.GetJob(jobURL)
if err != nil {
return true, err
}
// Stop polling and return error if job failed
if job.State == constant.JobFailed {
return true, fmt.Errorf(
"Delete service binding failed, reason: %+v",
job.Errors(),
)
}
if job.State == constant.JobComplete {
return true, nil
}
// Last operation initial or inprogress or job not completed, continue polling
return false, nil
}, 5*time.Second, 2*time.Minute)
if err != nil {
return err
}
}
}
return nil
}
// func IsAppCodeChange(d ResourceChanger) bool {
// return d.HasChange("path") || d.HasChange("source_code_hash")
// }
// func IsAppUpdateOnly(d ResourceChanger) bool {
// if IsAppCodeChange(d) || IsAppRestageNeeded(d) || IsAppRestartNeeded(d) {
// return false
// }
// return d.HasChange("name") || d.HasChange("instances") ||
// d.HasChange("enable_ssh") || d.HasChange("stopped")
// }
// func IsAppRestageNeeded(d ResourceChanger) bool {
// return d.HasChange("buildpack") || d.HasChange("stack") ||
// d.HasChange("service_binding") || d.HasChange("environment")
// }
// func IsAppRestartNeeded(d ResourceChanger) bool {
// return d.HasChange("memory") || d.HasChange("disk_quota") ||
// d.HasChange("command") || d.HasChange("health_check_http_endpoint") ||
// d.HasChange("docker_image") || d.HasChange("health_check_type") ||
// d.HasChange("environment")
// }
// func isDiffAppParamsBinding(oldBinding, currentBinding map[string]interface{}) (bool, error) {
// if len(oldBinding["params"].(map[string]interface{})) != len(currentBinding["params"].(map[string]interface{})) {
// return true, nil
// }
// if len(oldBinding["params"].(map[string]interface{})) > 0 {
// oldParams := oldBinding["params"].(map[string]interface{})
// currentParams := currentBinding["params"].(map[string]interface{})
// return reflect.DeepEqual(oldParams, currentParams), nil
// }
// oldJson := oldBinding["params_json"].(string)
// currentJson := oldBinding["params_json"].(string)
// if oldJson == "" && currentJson == "" {
// return false, nil
// }
// if oldJson == "" && currentJson != "" || oldJson != "" && currentJson == "" {
// return true, nil
// }
// var oldParams map[string]interface{}
// var currentParams map[string]interface{}
// err := json.Unmarshal([]byte(oldJson), &oldParams)
// if err != nil {
// return false, err
// }
// err = json.Unmarshal([]byte(currentJson), ¤tParams)
// if err != nil {
// return false, err
// }
// return reflect.DeepEqual(oldParams, currentParams), nil
// }