forked from hashicorp/terraform-provider-google
/
resource_endpoints_service.go
321 lines (302 loc) · 10.4 KB
/
resource_endpoints_service.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
package google
import (
"encoding/base64"
"encoding/json"
"errors"
"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/servicemanagement/v1"
)
func resourceEndpointsService() *schema.Resource {
return &schema.Resource{
Create: resourceEndpointsServiceCreate,
Read: resourceEndpointsServiceRead,
Delete: resourceEndpointsServiceDelete,
Update: resourceEndpointsServiceUpdate,
// Migrates protoc_output -> protoc_output_base64.
SchemaVersion: 1,
MigrateState: migrateEndpointsService,
Schema: map[string]*schema.Schema{
"service_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"openapi_config": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"grpc_config", "protoc_output_base64"},
},
"grpc_config": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"protoc_output": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Deprecated: "Please use protoc_output_base64 instead.",
},
"protoc_output_base64": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"project": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"config_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"apis": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"syntax": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"version": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"methods": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"syntax": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"request_type": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"response_type": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"dns_address": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"endpoints": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"address": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func getOpenAPIConfigSource(configText string) servicemanagement.ConfigSource {
// We need to provide a ConfigSource object to the API whenever submitting a
// new config. A ConfigSource contains a ConfigFile which contains the b64
// encoded contents of the file. OpenAPI requires only one file.
configfile := servicemanagement.ConfigFile{
FileContents: base64.StdEncoding.EncodeToString([]byte(configText)),
FileType: "OPEN_API_YAML",
FilePath: "heredoc.yaml",
}
return servicemanagement.ConfigSource{
Files: []*servicemanagement.ConfigFile{&configfile},
}
}
func getGRPCConfigSource(serviceConfig, protoConfig string) servicemanagement.ConfigSource {
// gRPC requires both the file specifying the service and the compiled protobuf,
// but they can be in any order.
ymlConfigfile := servicemanagement.ConfigFile{
FileContents: base64.StdEncoding.EncodeToString([]byte(serviceConfig)),
FileType: "SERVICE_CONFIG_YAML",
FilePath: "heredoc.yaml",
}
protoConfigfile := servicemanagement.ConfigFile{
FileContents: protoConfig,
FileType: "FILE_DESCRIPTOR_SET_PROTO",
FilePath: "api_def.pb",
}
return servicemanagement.ConfigSource{
Files: []*servicemanagement.ConfigFile{&ymlConfigfile, &protoConfigfile},
}
}
func resourceEndpointsServiceCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
// If the service doesn't exist, we'll need to create it, but if it does, it
// will be reused. This is unusual for Terraform, but it causes the behavior
// that users will want and accept. Users of Endpoints are not thinking in
// terms of services, configs, and rollouts - they just want the setup declared
// in their config to happen. The fact that a service may need to be created
// is not interesting to them. Consequently, we create this service if necessary
// so that we can perform the rollout without further disruption, which is the
// action that a user running `terraform apply` is going to want.
serviceName := d.Get("service_name").(string)
servicesService := servicemanagement.NewServicesService(config.clientServiceMan)
_, err = servicesService.Get(serviceName).Do()
if err != nil {
_, err = servicesService.Create(&servicemanagement.ManagedService{ProducerProjectId: project, ServiceName: serviceName}).Do()
if err != nil {
return err
}
}
// Do a rollout using the update mechanism.
err = resourceEndpointsServiceUpdate(d, meta)
if err != nil {
return err
}
d.SetId(serviceName)
return resourceEndpointsServiceRead(d, meta)
}
func resourceEndpointsServiceUpdate(d *schema.ResourceData, meta interface{}) error {
// This update is not quite standard for a terraform resource. Instead of
// using the go client library to send an HTTP request to update something
// serverside, we have to push a new configuration, wait for it to be
// parsed and loaded, then create and push a rollout and wait for that
// rollout to be completed.
// There's a lot of moving parts there, and all of them have knobs that can
// be tweaked if the user is using gcloud. In the interest of simplicity,
// we currently only support full rollouts - anyone trying to do incremental
// rollouts or A/B testing is going to need a more precise tool than this resource.
config := meta.(*Config)
serviceName := d.Get("service_name").(string)
var source servicemanagement.ConfigSource
if openapiConfig, ok := d.GetOk("openapi_config"); ok {
source = getOpenAPIConfigSource(openapiConfig.(string))
} else {
grpcConfig, gok := d.GetOk("grpc_config")
protocOutput, pok := d.GetOk("protoc_output_base64")
// Support conversion from raw file -> base64 until the field is totally removed.
if !pok {
protocOutput, pok = d.GetOk("protoc_output")
if pok {
protocOutput = base64.StdEncoding.EncodeToString([]byte(protocOutput.(string)))
}
}
if gok && pok {
source = getGRPCConfigSource(grpcConfig.(string), protocOutput.(string))
} else {
return errors.New("Could not decypher config - please either set openapi_config or set both grpc_config and protoc_output_base64.")
}
}
configService := servicemanagement.NewServicesConfigsService(config.clientServiceMan)
// The difference between "submit" and "create" is that submit parses the config
// you provide, where "create" requires the config in a pre-parsed format.
// "submit" will be a lot more flexible for users and will always be up-to-date
// with any new features that arise - this is why you provide a YAML config
// instead of providing the config in HCL.
op, err := configService.Submit(serviceName, &servicemanagement.SubmitConfigSourceRequest{ConfigSource: &source}).Do()
if err != nil {
return err
}
s, err := serviceManagementOperationWait(config, op, "Submitting service config.")
if err != nil {
return err
}
var serviceConfig servicemanagement.SubmitConfigSourceResponse
json.Unmarshal(s, &serviceConfig)
// Next, we create a new rollout with the new config value, and wait for it to complete.
rolloutService := servicemanagement.NewServicesRolloutsService(config.clientServiceMan)
rollout := servicemanagement.Rollout{
ServiceName: serviceName,
TrafficPercentStrategy: &servicemanagement.TrafficPercentStrategy{
Percentages: map[string]float64{serviceConfig.ServiceConfig.Id: 100.0},
},
}
op, err = rolloutService.Create(serviceName, &rollout).Do()
if err != nil {
return err
}
_, err = serviceManagementOperationWait(config, op, "Performing service rollout.")
if err != nil {
return err
}
return resourceEndpointsServiceRead(d, meta)
}
func resourceEndpointsServiceDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
servicesService := servicemanagement.NewServicesService(config.clientServiceMan)
op, err := servicesService.Delete(d.Get("service_name").(string)).Do()
if err != nil {
return err
}
_, err = serviceManagementOperationWait(config, op, "Deleting service.")
d.SetId("")
return err
}
func resourceEndpointsServiceRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
servicesService := servicemanagement.NewServicesService(config.clientServiceMan)
service, err := servicesService.GetConfig(d.Get("service_name").(string)).Do()
if err != nil {
return err
}
d.Set("config_id", service.Id)
d.Set("dns_address", service.Name)
d.Set("apis", flattenServiceManagementAPIs(service.Apis))
d.Set("endpoints", flattenServiceManagementEndpoints(service.Endpoints))
return nil
}
func flattenServiceManagementAPIs(apis []*servicemanagement.Api) []map[string]interface{} {
flattened := make([]map[string]interface{}, len(apis))
for i, a := range apis {
flattened[i] = map[string]interface{}{
"name": a.Name,
"version": a.Version,
"syntax": a.Syntax,
"methods": flattenServiceManagementMethods(a.Methods),
}
}
return flattened
}
func flattenServiceManagementMethods(methods []*servicemanagement.Method) []map[string]interface{} {
flattened := make([]map[string]interface{}, len(methods))
for i, m := range methods {
flattened[i] = map[string]interface{}{
"name": m.Name,
"syntax": m.Syntax,
"request_type": m.RequestTypeUrl,
"response_type": m.ResponseTypeUrl,
}
}
return flattened
}
func flattenServiceManagementEndpoints(endpoints []*servicemanagement.Endpoint) []map[string]interface{} {
flattened := make([]map[string]interface{}, len(endpoints))
for i, e := range endpoints {
flattened[i] = map[string]interface{}{
"name": e.Name,
"address": e.Target,
}
}
return flattened
}