-
Notifications
You must be signed in to change notification settings - Fork 290
/
convert.go
341 lines (290 loc) · 9.56 KB
/
convert.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
package webview
import (
"context"
"sort"
"strings"
"github.com/golang/protobuf/ptypes"
"github.com/tilt-dev/tilt/internal/k8s"
"github.com/tilt-dev/tilt/pkg/apis"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/tilt-dev/tilt/internal/cloud/cloudurl"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/pkg/logger"
"github.com/tilt-dev/tilt/pkg/model"
"github.com/tilt-dev/tilt/pkg/model/logstore"
proto_webview "github.com/tilt-dev/tilt/pkg/webview"
)
// We call the main session the Tiltfile session, for compatibility
// with the other Session API.
const UISessionName = "Tiltfile"
// Create the complete snapshot of the webview.
func CompleteView(ctx context.Context, client ctrlclient.Client, st store.RStore) (*proto_webview.View, error) {
ret := &proto_webview.View{}
session := &v1alpha1.UISession{}
err := client.Get(ctx, types.NamespacedName{Name: UISessionName}, session)
if err != nil && !apierrors.IsNotFound(err) {
return nil, err
}
if err == nil {
ret.UiSession = session
}
resourceList := &v1alpha1.UIResourceList{}
err = client.List(ctx, resourceList)
if err != nil {
return nil, err
}
for _, item := range resourceList.Items {
item := item
ret.UiResources = append(ret.UiResources, &item)
}
buttonList := &v1alpha1.UIButtonList{}
err = client.List(ctx, buttonList)
if err != nil {
return nil, err
}
for _, item := range buttonList.Items {
item := item
ret.UiButtons = append(ret.UiButtons, &item)
}
s := st.RLockState()
defer st.RUnlockState()
logList, err := s.LogStore.ToLogList(0)
if err != nil {
return nil, err
}
ret.LogList = logList
// We grandfather in TiltStartTime from the old protocol,
// because it tells the UI to reload.
start, err := ptypes.TimestampProto(s.TiltStartTime)
if err != nil {
return nil, err
}
ret.TiltStartTime = start
ret.IsComplete = true
sortUIResources(ret.UiResources, s.ManifestDefinitionOrder)
return ret, nil
}
// Create a view that only contains logs since the given checkpoint.
func LogUpdate(st store.RStore, checkpoint logstore.Checkpoint) (*proto_webview.View, error) {
ret := &proto_webview.View{}
s := st.RLockState()
defer st.RUnlockState()
logList, err := s.LogStore.ToLogList(checkpoint)
if err != nil {
return nil, err
}
ret.LogList = logList
// We grandfather in TiltStartTime from the old protocol,
// because it tells the UI to reload.
start, err := ptypes.TimestampProto(s.TiltStartTime)
if err != nil {
return nil, err
}
ret.TiltStartTime = start
return ret, nil
}
func sortUIResources(resources []*v1alpha1.UIResource, order []model.ManifestName) {
resourceOrder := make(map[string]int, len(order))
for i, name := range order {
resourceOrder[name.String()] = i
}
resourceOrder[store.TiltfileManifestName.String()] = -1
sort.Slice(resources, func(i, j int) bool {
objI := resources[i]
objJ := resources[j]
orderI, hasI := resourceOrder[objI.Name]
orderJ, hasJ := resourceOrder[objJ.Name]
if !hasI {
orderI = 1000
}
if !hasJ {
orderJ = 1000
}
if orderI != orderJ {
return orderI < orderJ
}
return objI.Name < objJ.Name
})
}
// Converts EngineState into the public data model representation, a UISession.
func ToUISession(s store.EngineState) *v1alpha1.UISession {
ret := &v1alpha1.UISession{
ObjectMeta: metav1.ObjectMeta{
Name: UISessionName,
},
Status: v1alpha1.UISessionStatus{},
}
status := &(ret.Status)
status.NeedsAnalyticsNudge = NeedsNudge(s)
status.RunningTiltBuild = v1alpha1.TiltBuild{
Version: s.TiltBuildInfo.Version,
CommitSHA: s.TiltBuildInfo.CommitSHA,
Dev: s.TiltBuildInfo.Dev,
Date: s.TiltBuildInfo.Date,
}
status.SuggestedTiltVersion = s.SuggestedTiltVersion
status.FeatureFlags = []v1alpha1.UIFeatureFlag{}
for k, v := range s.Features {
status.FeatureFlags = append(status.FeatureFlags, v1alpha1.UIFeatureFlag{
Name: k,
Value: v,
})
}
sort.Slice(status.FeatureFlags, func(i, j int) bool {
return status.FeatureFlags[i].Name < status.FeatureFlags[j].Name
})
status.TiltCloudUsername = s.CloudStatus.Username
status.TiltCloudTeamName = s.CloudStatus.TeamName
status.TiltCloudSchemeHost = cloudurl.URL(s.CloudAddress).String()
status.TiltCloudTeamID = s.TeamID
if s.FatalError != nil {
status.FatalError = s.FatalError.Error()
}
status.VersionSettings = v1alpha1.VersionSettings{
CheckUpdates: s.VersionSettings.CheckUpdates,
}
status.TiltStartTime = metav1.NewTime(s.TiltStartTime)
status.TiltfileKey = s.TiltfilePath
return ret
}
// Converts an EngineState into a list of UIResources.
// The order of the list is non-deterministic.
func ToUIResourceList(state store.EngineState) ([]*v1alpha1.UIResource, error) {
ret := make([]*v1alpha1.UIResource, 0, len(state.ManifestTargets)+1)
ret = append(ret, TiltfileResourceProtoView(state))
for i, mt := range state.Targets() {
// Skip manifests that don't come from the tiltfile.
if mt.Manifest.Source != model.ManifestSourceTiltfile {
continue
}
r, err := toUIResource(mt, state)
if err != nil {
return nil, err
}
// The Tiltfile has Order -1, all "normal" resources have Order >= 1
r.Status.Order = int32(i + 1)
ret = append(ret, r)
}
return ret, nil
}
// Converts a ManifestTarget into the public data model representation,
// a UIResource.
func toUIResource(mt *store.ManifestTarget, s store.EngineState) (*v1alpha1.UIResource, error) {
ms := mt.State
endpoints := store.ManifestTargetEndpoints(mt)
bh := ToBuildsTerminated(ms.BuildHistory, s.LogStore)
lastDeploy := metav1.NewMicroTime(ms.LastSuccessfulDeployTime)
cb := ToBuildRunning(ms.CurrentBuild)
specs, err := ToAPITargetSpecs(mt.Manifest.TargetSpecs())
if err != nil {
return nil, err
}
// NOTE(nick): Right now, the UX is designed to show the output exactly one
// pod. A better UI might summarize the pods in other ways (e.g., show the
// "most interesting" pod that's crash looping, or show logs from all pods
// at once).
hasPendingChanges, pendingBuildSince := ms.HasPendingChanges()
labels := mt.Manifest.Labels
name := mt.Manifest.Name
r := &v1alpha1.UIResource{
ObjectMeta: metav1.ObjectMeta{
Name: name.String(),
Labels: labels,
},
Status: v1alpha1.UIResourceStatus{
LastDeployTime: lastDeploy,
BuildHistory: bh,
PendingBuildSince: metav1.NewMicroTime(pendingBuildSince),
CurrentBuild: cb,
EndpointLinks: ToAPILinks(endpoints),
Specs: specs,
TriggerMode: int32(mt.Manifest.TriggerMode),
HasPendingChanges: hasPendingChanges,
Queued: s.ManifestInTriggerQueue(name),
},
}
err = populateResourceInfoView(mt, r)
if err != nil {
return nil, err
}
return r, nil
}
func TiltfileResourceProtoView(s store.EngineState) *v1alpha1.UIResource {
ltfb := s.TiltfileState.LastBuild()
ctfb := s.TiltfileState.CurrentBuild
pctfb := ToBuildRunning(ctfb)
history := []v1alpha1.UIBuildTerminated{}
if !ltfb.Empty() {
history = append(history, ToBuildTerminated(ltfb, s.LogStore))
}
tr := &v1alpha1.UIResource{
ObjectMeta: metav1.ObjectMeta{
Name: store.TiltfileManifestName.String(),
},
Status: v1alpha1.UIResourceStatus{
CurrentBuild: pctfb,
BuildHistory: history,
RuntimeStatus: v1alpha1.RuntimeStatusNotApplicable,
UpdateStatus: s.TiltfileState.UpdateStatus(model.TriggerModeAuto),
Order: -1,
},
}
start := metav1.NewMicroTime(ctfb.StartTime)
finish := metav1.NewMicroTime(ltfb.FinishTime)
if !ctfb.Empty() {
tr.Status.PendingBuildSince = start
} else {
tr.Status.LastDeployTime = finish
}
return tr
}
func populateResourceInfoView(mt *store.ManifestTarget, r *v1alpha1.UIResource) error {
r.Status.UpdateStatus = mt.UpdateStatus()
r.Status.RuntimeStatus = v1alpha1.RuntimeStatusNotApplicable
if mt.Manifest.PodReadinessMode() == model.PodReadinessIgnore {
return nil
}
if mt.Manifest.IsDC() {
dcState := mt.State.DCRuntimeState()
r.Status.RuntimeStatus = v1alpha1.RuntimeStatus(dcState.RuntimeStatus())
return nil
}
if mt.Manifest.IsLocal() {
lState := mt.State.LocalRuntimeState()
r.Status.LocalResourceInfo = &v1alpha1.UIResourceLocal{PID: int64(lState.PID), IsTest: mt.Manifest.LocalTarget().IsTest}
r.Status.RuntimeStatus = v1alpha1.RuntimeStatus(lState.RuntimeStatus())
return nil
}
if mt.Manifest.IsK8s() {
kState := mt.State.K8sRuntimeState()
pod := kState.MostRecentPod()
podID := k8s.PodID(pod.Name)
r.Status.K8sResourceInfo = &v1alpha1.UIResourceKubernetes{
PodName: pod.Name,
PodCreationTime: pod.CreatedAt,
PodUpdateStartTime: apis.NewTime(kState.UpdateStartTime[k8s.PodID(pod.Name)]),
PodStatus: pod.Status,
PodStatusMessage: strings.Join(pod.Errors, "\n"),
AllContainersReady: store.AllPodContainersReady(pod),
PodRestarts: kState.VisiblePodContainerRestarts(podID),
DisplayNames: mt.Manifest.K8sTarget().DisplayNames,
}
r.Status.RuntimeStatus = v1alpha1.RuntimeStatus(kState.RuntimeStatus())
return nil
}
panic("Unrecognized manifest type (not one of: k8s, DC, local)")
}
func LogSegmentToEvent(seg *proto_webview.LogSegment, spans map[string]*proto_webview.LogSpan) store.LogAction {
span, ok := spans[seg.SpanId]
if !ok {
// nonexistent span, ignore
return store.LogAction{}
}
// TODO(maia): actually get level (just spoofing for now)
spoofedLevel := logger.InfoLvl
return store.NewLogAction(model.ManifestName(span.ManifestName), logstore.SpanID(seg.SpanId), spoofedLevel, seg.Fields, []byte(seg.Text))
}