-
Notifications
You must be signed in to change notification settings - Fork 303
/
script.go
271 lines (230 loc) · 5.66 KB
/
script.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
package demo
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"github.com/pkg/errors"
"github.com/windmilleng/tilt/internal/engine"
"github.com/windmilleng/tilt/internal/hud"
"github.com/windmilleng/tilt/internal/k8s"
"github.com/windmilleng/tilt/internal/logger"
"github.com/windmilleng/tilt/internal/model"
"github.com/windmilleng/tilt/internal/store"
"github.com/windmilleng/tilt/internal/tiltfile"
"golang.org/x/sync/errgroup"
"k8s.io/api/core/v1"
)
type RepoBranch string
// Runs the demo script
type Script struct {
hud hud.HeadsUpDisplay
upper engine.Upper
store *store.Store
env k8s.Env
kClient k8s.Client
branch RepoBranch
readTiltfileCh chan string
podMonitor *podMonitor
}
func NewScript(upper engine.Upper, hud hud.HeadsUpDisplay, kClient k8s.Client,
env k8s.Env, st *store.Store, branch RepoBranch) Script {
s := Script{
upper: upper,
hud: hud,
env: env,
kClient: kClient,
branch: branch,
readTiltfileCh: make(chan string),
podMonitor: &podMonitor{},
store: st,
}
st.AddSubscriber(s.podMonitor)
return s
}
type podMonitor struct {
hasBuildError bool
hasPodRestart bool
healthy bool
mu sync.Mutex
}
func (m *podMonitor) OnChange(ctx context.Context, st store.RStore) {
m.mu.Lock()
defer m.mu.Unlock()
state := st.RLockState()
defer st.RUnlockState()
m.hasPodRestart = false
m.hasBuildError = false
m.healthy = true
if len(state.ManifestStates) == 0 {
m.healthy = false
}
for _, ms := range state.ManifestStates {
pod := ms.MostRecentPod()
if pod.Phase != v1.PodRunning {
m.healthy = false
}
if pod.ContainerRestarts > 0 {
m.hasPodRestart = true
m.healthy = false
}
if ms.LastBuild().Error != nil {
m.hasBuildError = true
m.healthy = false
}
if state.CurrentlyBuilding != "" || len(ms.PendingFileChanges) > 0 {
m.healthy = false
}
}
}
func (m *podMonitor) waitUntilPodsReady(ctx context.Context) error {
return m.waitUntilCond(ctx, func() bool {
return m.healthy
})
}
func (m *podMonitor) waitUntilBuildError(ctx context.Context) error {
return m.waitUntilCond(ctx, func() bool {
return m.hasBuildError
})
}
func (m *podMonitor) waitUntilPodRestart(ctx context.Context) error {
return m.waitUntilCond(ctx, func() bool {
return m.hasPodRestart
})
}
func (m *podMonitor) waitUntilCond(ctx context.Context, f func() bool) error {
for {
m.mu.Lock()
cond := f()
m.mu.Unlock()
if cond {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(100 * time.Millisecond):
}
}
}
func (s Script) Run(ctx context.Context) error {
if !s.env.IsLocalCluster() {
_, _ = fmt.Fprintf(os.Stderr, "tilt demo mode only supports Docker For Mac or Minikube\n")
_, _ = fmt.Fprintf(os.Stderr, "check your current cluster with:\n")
_, _ = fmt.Fprintf(os.Stderr, "\nkubectl config get-contexts\n\n")
return nil
}
l := engine.NewLogActionLogger(ctx, s.store.Dispatch)
out := l.Writer(logger.InfoLvl)
ctx = logger.WithLogger(ctx, l)
ctx, cancel := context.WithCancel(ctx)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
defer cancel()
return s.hud.Run(ctx, s.upper.Dispatch, hud.DefaultRefreshInterval)
})
g.Go(func() error {
defer cancel()
return s.runSteps(ctx, out)
})
g.Go(func() error {
defer cancel()
var dir string
select {
case dir = <-s.readTiltfileCh:
case <-ctx.Done():
return ctx.Err()
}
tfPath := filepath.Join(dir, tiltfile.FileName)
manifests, _, _, err := tiltfile.Load(ctx, tfPath, nil)
if err != nil {
return err
}
defer s.cleanUp(newBackgroundContext(ctx), manifests)
initAction := engine.InitAction{
WatchMounts: true,
Manifests: manifests,
TiltfilePath: tfPath,
}
return s.upper.Init(ctx, initAction)
})
return g.Wait()
}
func newBackgroundContext(ctx context.Context) context.Context {
l := logger.Get(ctx)
return logger.WithLogger(context.Background(), l)
}
func (s Script) cleanUp(ctx context.Context, manifests []model.Manifest) {
if manifests == nil {
return
}
entities, err := engine.ParseYAMLFromManifests(manifests...)
if err != nil {
logger.Get(ctx).Infof("Parsing entities: %v", err)
return
}
err = s.kClient.Delete(ctx, entities)
if err != nil {
logger.Get(ctx).Infof("Deleting entities: %v", err)
}
}
func (s Script) runSteps(ctx context.Context, out io.Writer) error {
tmpDir, err := ioutil.TempDir("", "tiltdemo")
if err != nil {
return errors.Wrap(err, "demo.runSteps")
}
defer func() {
_ = os.RemoveAll(tmpDir)
}()
for _, step := range steps {
if step.ChangeBranch && s.branch == "" {
continue
}
err := s.hud.SetNarrationMessage(ctx, step.Narration)
if err != nil {
return err
}
if step.Command != "" {
cmd := exec.CommandContext(ctx, "sh", "-c", step.Command)
cmd.Stdout = out
cmd.Stderr = out
cmd.Dir = tmpDir
err := cmd.Run()
if err != nil {
return errors.Wrap(err, "demo.runSteps")
}
} else if step.CreateManifests {
s.readTiltfileCh <- tmpDir
} else if step.ChangeBranch {
cmd := exec.CommandContext(ctx, "git", "checkout", string(s.branch))
cmd.Stdout = out
cmd.Stderr = out
cmd.Dir = tmpDir
err := cmd.Run()
if err != nil {
return errors.Wrap(err, "demo.runSteps")
}
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(Pause):
}
if step.WaitForHealthy {
_ = s.podMonitor.waitUntilPodsReady(ctx)
continue
} else if step.WaitForBuildError {
_ = s.podMonitor.waitUntilBuildError(ctx)
continue
} else if step.WaitForPodRestart {
_ = s.podMonitor.waitUntilPodRestart(ctx)
continue
}
}
return nil
}