forked from heroku/terraform-provider-heroku
/
resource_heroku_slug.go
425 lines (363 loc) · 10.5 KB
/
resource_heroku_slug.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package heroku
import (
"context"
"crypto/sha256"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"regexp"
"strings"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform/helper/schema"
"github.com/heroku/heroku-go/v3"
)
func resourceHerokuSlug() *schema.Resource {
return &schema.Resource{
Create: resourceHerokuSlugCreate,
Read: resourceHerokuSlugRead,
Delete: resourceHerokuSlugDelete,
CustomizeDiff: resourceHerokuSlugCustomizeDiff,
Importer: &schema.ResourceImporter{
State: resourceHerokuSlugImport,
},
Schema: map[string]*schema.Schema{
"app": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
// Local tarball to be uploaded after slug creation
"file_path": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// https:// URL of tarball to upload into slug
"file_url": {
Type: schema.TypeString,
ConflictsWith: []string{"file_path"},
Optional: true,
ForceNew: true,
ValidateFunc: validateFileUrl,
},
"blob": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"method": {
Type: schema.TypeString,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"buildpack_provided_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"checksum": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"commit": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"commit_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"process_types": {
Type: schema.TypeSet,
Required: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeMap,
},
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
// Create/argument: either a name or UUID.
// Read/attribute: name of the stack.
"stack": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"stack_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceHerokuSlugImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(*Config).Api
app, slugID, err := parseCompositeID(d.Id())
if err != nil {
return nil, err
}
slug, err := client.SlugInfo(context.Background(), app, slugID)
if err != nil {
return nil, err
}
d.SetId(slug.ID)
d.Set("app", app)
setSlugState(d, slug)
return []*schema.ResourceData{d}, nil
}
func resourceHerokuSlugCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Config).Api
app := getAppName(d)
// Build up our creation options
opts := heroku.SlugCreateOpts{}
if pt, ok := d.GetOk("process_types"); ok {
ptSet := pt.(*schema.Set)
opts.ProcessTypes = make(map[string]string)
for _, v := range ptSet.List() {
for kk, vv := range v.(map[string]interface{}) {
opts.ProcessTypes[kk] = vv.(string)
}
}
}
if v, ok := d.GetOk("buildpack_provided_description"); ok {
opts.BuildpackProvidedDescription = heroku.String(v.(string))
}
// Only file_path or file_url will be set, because of ConflictsWith.
var filePath string
// Simply use the configured file path
if v, ok := d.GetOk("file_path"); ok {
filePath = v.(string)
}
// Download the slug archive to a unique file path and clean it up
// after uploading to Heroku platform.
if v, ok := d.GetOk("file_url"); ok {
fileUrl := v.(string)
newUuid, err := uuid.GenerateUUID()
if err != nil {
return err
}
filePath = fmt.Sprintf("slug-%s.tgz", newUuid)
err = downloadSlug(fileUrl, filePath)
if err != nil {
return err
}
defer cleanupSlugFile(filePath)
}
// Require a file path by validating this programmatically.
// (ConflictsWith cannot be used with Required)
if filePath == "" {
return fmt.Errorf("Error creating slug: requires either `file_path` or `file_url` attribute")
}
if v, ok := d.GetOk("checksum"); ok {
// Use specified checksum when its set
opts.Checksum = heroku.String(v.(string))
} else {
// Optionally capture the checksum (really sha256 hash) of the slug file.
if filePath != "" {
checksum, err := checksumSlug(filePath)
if err != nil {
return err
}
log.Printf("[DEBUG] Slug checksum: %s", checksum)
opts.Checksum = heroku.String(checksum)
}
}
if v, ok := d.GetOk("commit"); ok {
opts.Commit = heroku.String(v.(string))
}
if v, ok := d.GetOk("commit_description"); ok {
opts.CommitDescription = heroku.String(v.(string))
}
if v, ok := d.GetOk("stack"); ok {
opts.Stack = heroku.String(v.(string))
}
slug, err := client.SlugCreate(context.TODO(), app, opts)
if err != nil {
return fmt.Errorf("Error creating slug: %s opts %+v", err, opts)
}
// Optionally upload slug before setting ID, so that an upload failure
// causes a resource creation error, is not saved in state.
if filePath != "" {
err := uploadSlug(filePath, slug.Blob.Method, slug.Blob.URL)
if err != nil {
return err
}
}
d.SetId(slug.ID)
setSlugState(d, slug)
log.Printf("[INFO] Created slug ID: %s", d.Id())
return nil
}
func resourceHerokuSlugRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Config).Api
app := getAppName(d)
slug, err := client.SlugInfo(context.TODO(), app, d.Id())
if err != nil {
return fmt.Errorf("Error retrieving slug: %s", err)
}
setSlugState(d, slug)
return nil
}
// A no-op method as there is no DELETE slug in Heroku Platform API.
func resourceHerokuSlugDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[INFO] There is no DELETE for slug resource so this is a no-op. Slug will be removed from state.")
return nil
}
func resourceHerokuSlugCustomizeDiff(diff *schema.ResourceDiff, v interface{}) error {
// Detect changes to the content of local slug archive.
if v, ok := diff.GetOk("file_path"); ok {
filePath := v.(string)
realChecksum, err := checksumSlug(filePath)
if err == nil {
oldChecksum, newChecksum := diff.GetChange("checksum")
log.Printf("[DEBUG] Diffing slug: old '%s', new '%s', real '%s'", oldChecksum, newChecksum, realChecksum)
if newChecksum != realChecksum {
if err := diff.SetNew("checksum", realChecksum); err != nil {
return fmt.Errorf("Error updating slug archive checksum: %s", err)
}
if err := diff.ForceNew("checksum"); err != nil {
return fmt.Errorf("Error forcing new slug resource: %s", err)
}
}
}
}
return nil
}
func downloadSlug(httpUrl, destinationFilePath string) error {
log.Printf("[DEBUG] Downloading slug from %s", httpUrl)
httpClient := &http.Client{}
req, err := http.NewRequest("GET", httpUrl, nil)
if err != nil {
return fmt.Errorf("Error creating slug download request: %s (%s)", err, httpUrl)
}
log.Printf("[DEBUG] Download slug request: %+v", req)
res, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("Error downloading slug: %s (%s)", err, httpUrl)
}
b, err := httputil.DumpResponse(res, true)
if err == nil {
// generate debug output if it's available
log.Printf("[DEBUG] Slug download response: %s", b)
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode > 299 {
return fmt.Errorf("Unsuccessful HTTP response from slug download: %s (%s)", res.Status, httpUrl)
}
slugFile, err := os.Create(destinationFilePath)
if err != nil {
return fmt.Errorf("Error creating slug file: %s (%s)", err, destinationFilePath)
}
defer slugFile.Close()
io.Copy(slugFile, res.Body)
return nil
}
func uploadSlug(filePath, httpMethod, httpUrl string) error {
method := strings.ToUpper(httpMethod)
log.Printf("[DEBUG] Uploading slug '%s' to %s %s", filePath, method, httpUrl)
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("Error opening slug file_path: %s", err)
}
stat, err := file.Stat()
if err != nil {
return fmt.Errorf("Error stating slug file_path: %s", err)
}
defer file.Close()
httpClient := &http.Client{}
req, err := http.NewRequest(method, httpUrl, file)
if err != nil {
return fmt.Errorf("Error creating slug upload request: %s", err)
}
req.ContentLength = stat.Size()
log.Printf("[DEBUG] Upload slug request: %+v", req)
res, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("Error uploading slug: %s", err)
}
b, err := httputil.DumpResponse(res, true)
if err == nil {
// generate debug output if it's available
log.Printf("[DEBUG] Slug upload response: %s", b)
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode > 299 {
return fmt.Errorf("Unsuccessful HTTP response from slug upload: %s", res.Status)
}
return nil
}
func checksumSlug(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("Error opening slug file_path: %s", err)
}
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", fmt.Errorf("Error reading slug for checksum: %s", err)
}
file.Close()
checksum := fmt.Sprintf("SHA256:%x", hash.Sum(nil))
if err != nil {
return "", fmt.Errorf("Error generating slug checksum: %s", err)
}
return checksum, nil
}
func setSlugState(d *schema.ResourceData, slug *heroku.Slug) error {
blob := []map[string]string{{
"method": slug.Blob.Method,
"url": slug.Blob.URL,
}}
if err := d.Set("blob", blob); err != nil {
log.Printf("[WARN] Error setting blob: %s", err)
}
d.Set("buildpack_provided_description", slug.BuildpackProvidedDescription)
d.Set("checksum", slug.Checksum)
d.Set("commit", slug.Commit)
d.Set("commit_description", slug.CommitDescription)
processTypes := []map[string]string{slug.ProcessTypes}
if err := d.Set("process_types", processTypes); err != nil {
log.Printf("[WARN] Error setting process_types: %s", err)
}
d.Set("size", slug.Size)
d.Set("stack_id", slug.Stack.ID)
d.Set("stack", slug.Stack.Name)
return nil
}
func cleanupSlugFile(filePath string) {
if filePath != "" {
err := os.Remove(filePath)
if err != nil {
log.Printf("[WARN] Error cleaning-up downloaded slug: %s (%s)", err, filePath)
}
}
}
func validateFileUrl(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value == "" {
return
}
pattern := `^https://`
if !regexp.MustCompile(pattern).MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q must be a secure URL, start with `https://`. Value is %q",
k, value))
}
return
}