forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook_ui.go
411 lines (339 loc) · 8.84 KB
/
hook_ui.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
package command
import (
"bufio"
"bytes"
"fmt"
"sort"
"strings"
"sync"
"time"
"unicode"
"github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/cli"
"github.com/mitchellh/colorstring"
)
const defaultPeriodicUiTimer = 10 * time.Second
const maxIdLen = 80
type UiHook struct {
terraform.NilHook
Colorize *colorstring.Colorize
Ui cli.Ui
PeriodicUiTimer time.Duration
l sync.Mutex
once sync.Once
resources map[string]uiResourceState
ui cli.Ui
}
// uiResourceState tracks the state of a single resource
type uiResourceState struct {
Name string
ResourceId string
Op uiResourceOp
Start time.Time
DoneCh chan struct{} // To be used for cancellation
done chan struct{} // used to coordinate tests
}
// uiResourceOp is an enum for operations on a resource
type uiResourceOp byte
const (
uiResourceUnknown uiResourceOp = iota
uiResourceCreate
uiResourceModify
uiResourceDestroy
)
func (h *UiHook) PreApply(
n *terraform.InstanceInfo,
s *terraform.InstanceState,
d *terraform.InstanceDiff) (terraform.HookAction, error) {
h.once.Do(h.init)
// if there's no diff, there's nothing to output
if d.Empty() {
return terraform.HookActionContinue, nil
}
id := n.HumanId()
op := uiResourceModify
if d.Destroy {
op = uiResourceDestroy
} else if s.ID == "" {
op = uiResourceCreate
}
var operation string
switch op {
case uiResourceModify:
operation = "Modifying..."
case uiResourceDestroy:
operation = "Destroying..."
case uiResourceCreate:
operation = "Creating..."
case uiResourceUnknown:
return terraform.HookActionContinue, nil
}
attrBuf := new(bytes.Buffer)
// Get all the attributes that are changing, and sort them. Also
// determine the longest key so that we can align them all.
keyLen := 0
dAttrs := d.CopyAttributes()
keys := make([]string, 0, len(dAttrs))
for key, _ := range dAttrs {
// Skip the ID since we do that specially
if key == "id" {
continue
}
keys = append(keys, key)
if len(key) > keyLen {
keyLen = len(key)
}
}
sort.Strings(keys)
// Go through and output each attribute
for _, attrK := range keys {
attrDiff, _ := d.GetAttribute(attrK)
v := attrDiff.New
u := attrDiff.Old
if attrDiff.NewComputed {
v = "<computed>"
}
if attrDiff.Sensitive {
u = "<sensitive>"
v = "<sensitive>"
}
attrBuf.WriteString(fmt.Sprintf(
" %s:%s %#v => %#v\n",
attrK,
strings.Repeat(" ", keyLen-len(attrK)),
u,
v))
}
attrString := strings.TrimSpace(attrBuf.String())
if attrString != "" {
attrString = "\n " + attrString
}
var stateId, stateIdSuffix string
if s != nil && s.ID != "" {
stateId = s.ID
stateIdSuffix = fmt.Sprintf(" (ID: %s)", truncateId(s.ID, maxIdLen))
}
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][bold]%s: %s%s[reset]%s",
id,
operation,
stateIdSuffix,
attrString)))
uiState := uiResourceState{
Name: id,
ResourceId: stateId,
Op: op,
Start: time.Now().Round(time.Second),
DoneCh: make(chan struct{}),
done: make(chan struct{}),
}
h.l.Lock()
h.resources[id] = uiState
h.l.Unlock()
// Start goroutine that shows progress
go h.stillApplying(uiState)
return terraform.HookActionContinue, nil
}
func (h *UiHook) stillApplying(state uiResourceState) {
defer close(state.done)
for {
select {
case <-state.DoneCh:
return
case <-time.After(h.PeriodicUiTimer):
// Timer up, show status
}
var msg string
switch state.Op {
case uiResourceModify:
msg = "Still modifying..."
case uiResourceDestroy:
msg = "Still destroying..."
case uiResourceCreate:
msg = "Still creating..."
case uiResourceUnknown:
return
}
idSuffix := ""
if v := state.ResourceId; v != "" {
idSuffix = fmt.Sprintf("ID: %s, ", truncateId(v, maxIdLen))
}
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][bold]%s: %s (%s%s elapsed)[reset]",
state.Name,
msg,
idSuffix,
time.Now().Round(time.Second).Sub(state.Start),
)))
}
}
func (h *UiHook) PostApply(
n *terraform.InstanceInfo,
s *terraform.InstanceState,
applyerr error) (terraform.HookAction, error) {
id := n.HumanId()
h.l.Lock()
state := h.resources[id]
if state.DoneCh != nil {
close(state.DoneCh)
}
delete(h.resources, id)
h.l.Unlock()
var stateIdSuffix string
if s != nil && s.ID != "" {
stateIdSuffix = fmt.Sprintf(" (ID: %s)", truncateId(s.ID, maxIdLen))
}
var msg string
switch state.Op {
case uiResourceModify:
msg = "Modifications complete"
case uiResourceDestroy:
msg = "Destruction complete"
case uiResourceCreate:
msg = "Creation complete"
case uiResourceUnknown:
return terraform.HookActionContinue, nil
}
if applyerr != nil {
// Errors are collected and printed in ApplyCommand, no need to duplicate
return terraform.HookActionContinue, nil
}
colorized := h.Colorize.Color(fmt.Sprintf(
"[reset][bold]%s: %s%s[reset]",
id, msg, stateIdSuffix))
h.ui.Output(colorized)
return terraform.HookActionContinue, nil
}
func (h *UiHook) PreDiff(
n *terraform.InstanceInfo,
s *terraform.InstanceState) (terraform.HookAction, error) {
return terraform.HookActionContinue, nil
}
func (h *UiHook) PreProvision(
n *terraform.InstanceInfo,
provId string) (terraform.HookAction, error) {
id := n.HumanId()
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][bold]%s: Provisioning with '%s'...[reset]",
id, provId)))
return terraform.HookActionContinue, nil
}
func (h *UiHook) ProvisionOutput(
n *terraform.InstanceInfo,
provId string,
msg string) {
id := n.HumanId()
var buf bytes.Buffer
buf.WriteString(h.Colorize.Color("[reset]"))
prefix := fmt.Sprintf("%s (%s): ", id, provId)
s := bufio.NewScanner(strings.NewReader(msg))
s.Split(scanLines)
for s.Scan() {
line := strings.TrimRightFunc(s.Text(), unicode.IsSpace)
if line != "" {
buf.WriteString(fmt.Sprintf("%s%s\n", prefix, line))
}
}
h.ui.Output(strings.TrimSpace(buf.String()))
}
func (h *UiHook) PreRefresh(
n *terraform.InstanceInfo,
s *terraform.InstanceState) (terraform.HookAction, error) {
h.once.Do(h.init)
id := n.HumanId()
var stateIdSuffix string
// Data resources refresh before they have ids, whereas managed
// resources are only refreshed when they have ids.
if s.ID != "" {
stateIdSuffix = fmt.Sprintf(" (ID: %s)", truncateId(s.ID, maxIdLen))
}
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][bold]%s: Refreshing state...%s",
id, stateIdSuffix)))
return terraform.HookActionContinue, nil
}
func (h *UiHook) PreImportState(
n *terraform.InstanceInfo,
id string) (terraform.HookAction, error) {
h.once.Do(h.init)
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][bold]%s: Importing from ID %q...",
n.HumanId(), id)))
return terraform.HookActionContinue, nil
}
func (h *UiHook) PostImportState(
n *terraform.InstanceInfo,
s []*terraform.InstanceState) (terraform.HookAction, error) {
h.once.Do(h.init)
id := n.HumanId()
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][bold][green]%s: Import complete!", id)))
for _, s := range s {
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[reset][green] Imported %s (ID: %s)",
s.Ephemeral.Type, s.ID)))
}
return terraform.HookActionContinue, nil
}
func (h *UiHook) init() {
if h.Colorize == nil {
panic("colorize not given")
}
if h.PeriodicUiTimer == 0 {
h.PeriodicUiTimer = defaultPeriodicUiTimer
}
h.resources = make(map[string]uiResourceState)
// Wrap the ui so that it is safe for concurrency regardless of the
// underlying reader/writer that is in place.
h.ui = &cli.ConcurrentUi{Ui: h.Ui}
}
// scanLines is basically copied from the Go standard library except
// we've modified it to also fine `\r`.
func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\n'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, dropCR(data[0:i]), nil
}
if i := bytes.IndexByte(data, '\r'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, dropCR(data[0:i]), nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), dropCR(data), nil
}
// Request more data.
return 0, nil, nil
}
// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
if len(data) > 0 && data[len(data)-1] == '\r' {
return data[0 : len(data)-1]
}
return data
}
func truncateId(id string, maxLen int) string {
totalLength := len(id)
if totalLength <= maxLen {
return id
}
if maxLen < 5 {
// We don't shorten to less than 5 chars
// as that would be pointless with ... (3 chars)
maxLen = 5
}
dots := "..."
partLen := maxLen / 2
leftIdx := partLen - 1
leftPart := id[0:leftIdx]
rightIdx := totalLength - partLen - 1
overlap := maxLen - (partLen*2 + len(dots))
if overlap < 0 {
rightIdx -= overlap
}
rightPart := id[rightIdx:]
return leftPart + dots + rightPart
}