-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstart.go
More file actions
232 lines (205 loc) · 6.88 KB
/
start.go
File metadata and controls
232 lines (205 loc) · 6.88 KB
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
package container
import (
"context"
"fmt"
"net/http"
"os"
stdruntime "runtime"
"time"
"github.com/containerd/errdefs"
"github.com/localstack/lstk/internal/api"
"github.com/localstack/lstk/internal/auth"
"github.com/localstack/lstk/internal/config"
"github.com/localstack/lstk/internal/output"
"github.com/localstack/lstk/internal/ports"
"github.com/localstack/lstk/internal/runtime"
)
func Start(ctx context.Context, rt runtime.Runtime, sink output.Sink, platformClient api.PlatformAPI, interactive bool) error {
tokenStorage, err := auth.NewTokenStorage()
if err != nil {
return fmt.Errorf("failed to initialize token storage: %w", err)
}
a := auth.New(sink, platformClient, tokenStorage, interactive)
token, err := a.GetToken(ctx)
if err != nil {
return err
}
cfg, err := config.Get()
if err != nil {
return fmt.Errorf("failed to get config: %w", err)
}
containers := make([]runtime.ContainerConfig, len(cfg.Containers))
for i, c := range cfg.Containers {
image, err := c.Image()
if err != nil {
return err
}
healthPath, err := c.HealthPath()
if err != nil {
return err
}
productName, err := c.ProductName()
if err != nil {
return err
}
env := append(c.Env, "LOCALSTACK_AUTH_TOKEN="+token)
containers[i] = runtime.ContainerConfig{
Image: image,
Name: c.Name(),
Port: c.Port,
HealthPath: healthPath,
Env: env,
Tag: c.Tag,
ProductName: productName,
}
}
containers, err = selectContainersToStart(ctx, rt, sink, containers)
if err != nil {
return err
}
if len(containers) == 0 {
return nil
}
// TODO validate license for tag "latest" without resolving the actual image version,
// and avoid pulling all images first
if err := pullImages(ctx, rt, sink, containers); err != nil {
return err
}
if err := validateLicenses(ctx, rt, sink, platformClient, containers, token); err != nil {
return err
}
return startContainers(ctx, rt, sink, containers)
}
func pullImages(ctx context.Context, rt runtime.Runtime, sink output.Sink, containers []runtime.ContainerConfig) error {
for _, c := range containers {
// Remove any existing stopped container with the same name
if err := rt.Remove(ctx, c.Name); err != nil && !errdefs.IsNotFound(err) {
return fmt.Errorf("failed to remove existing container %s: %w", c.Name, err)
}
output.EmitStatus(sink, "pulling", c.Image, "")
progress := make(chan runtime.PullProgress)
go func() {
for p := range progress {
output.EmitProgress(sink, c.Image, p.LayerID, p.Status, p.Current, p.Total)
}
}()
if err := rt.PullImage(ctx, c.Image, progress); err != nil {
return fmt.Errorf("failed to pull image %s: %w", c.Image, err)
}
}
return nil
}
func validateLicenses(ctx context.Context, rt runtime.Runtime, sink output.Sink, platformClient api.PlatformAPI, containers []runtime.ContainerConfig, token string) error {
for _, c := range containers {
if err := validateLicense(ctx, rt, sink, platformClient, c, token); err != nil {
return err
}
}
return nil
}
func startContainers(ctx context.Context, rt runtime.Runtime, sink output.Sink, containers []runtime.ContainerConfig) error {
for _, c := range containers {
output.EmitStatus(sink, "starting", c.Name, "")
containerID, err := rt.Start(ctx, c)
if err != nil {
return fmt.Errorf("failed to start %s: %w", c.Name, err)
}
output.EmitStatus(sink, "waiting", c.Name, "")
healthURL := fmt.Sprintf("http://localhost:%s%s", c.Port, c.HealthPath)
if err := awaitStartup(ctx, rt, sink, containerID, c.Name, healthURL); err != nil {
return err
}
output.EmitStatus(sink, "ready", c.Name, fmt.Sprintf("containerId: %s", containerID[:12]))
}
return nil
}
func selectContainersToStart(ctx context.Context, rt runtime.Runtime, sink output.Sink, containers []runtime.ContainerConfig) ([]runtime.ContainerConfig, error) {
var filtered []runtime.ContainerConfig
for _, c := range containers {
running, err := rt.IsRunning(ctx, c.Name)
if err != nil && !errdefs.IsNotFound(err) {
return nil, fmt.Errorf("failed to check container status: %w", err)
}
if running {
output.EmitInfo(sink, fmt.Sprintf("%s is already running", c.Name))
continue
}
if err := ports.CheckAvailable(c.Port); err != nil {
configPath, pathErr := config.ConfigFilePath()
if pathErr != nil {
return nil, err
}
return nil, fmt.Errorf("%w\nTo use a different port, edit %s", err, configPath)
}
filtered = append(filtered, c)
}
return filtered, nil
}
func validateLicense(ctx context.Context, rt runtime.Runtime, sink output.Sink, platformClient api.PlatformAPI, containerConfig runtime.ContainerConfig, token string) error {
version := containerConfig.Tag
if version == "" || version == "latest" {
actualVersion, err := rt.GetImageVersion(ctx, containerConfig.Image)
if err != nil {
return fmt.Errorf("could not resolve version from image %s: %w", containerConfig.Image, err)
}
version = actualVersion
}
output.EmitStatus(sink, "validating license", containerConfig.Name, version)
hostname, _ := os.Hostname()
licenseReq := &api.LicenseRequest{
Product: api.ProductInfo{
Name: containerConfig.ProductName,
Version: version,
},
Credentials: api.CredentialsInfo{
Token: token,
},
Machine: api.MachineInfo{
Hostname: hostname,
Platform: stdruntime.GOOS,
PlatformRelease: stdruntime.GOARCH,
},
}
if err := platformClient.GetLicense(ctx, licenseReq); err != nil {
return fmt.Errorf("license validation failed for %s:%s: %w", containerConfig.ProductName, version, err)
}
return nil
}
// awaitStartup polls until one of two outcomes:
// - Success: health endpoint returns 200 (license is valid, LocalStack is ready)
// - Failure: container stops running (e.g., license activation failed), returns error with container logs
//
// TODO: move to Runtime interface if other runtimes (k8s?) need native readiness probes
func awaitStartup(ctx context.Context, rt runtime.Runtime, sink output.Sink, containerID, name, healthURL string) error {
client := &http.Client{Timeout: 2 * time.Second}
for {
running, err := rt.IsRunning(ctx, containerID)
if err != nil {
return fmt.Errorf("failed to check container status: %w", err)
}
if !running {
logs, logsErr := rt.Logs(ctx, containerID, 20)
if logsErr != nil || logs == "" {
return fmt.Errorf("%s exited unexpectedly", name)
}
return fmt.Errorf("%s exited unexpectedly:\n%s", name, logs)
}
resp, err := client.Get(healthURL)
if err == nil && resp.StatusCode == http.StatusOK {
if err := resp.Body.Close(); err != nil {
output.EmitWarning(sink, fmt.Sprintf("failed to close response body: %v", err))
}
return nil
}
if resp != nil {
if err := resp.Body.Close(); err != nil {
output.EmitWarning(sink, fmt.Sprintf("failed to close response body: %v", err))
}
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(1 * time.Second):
}
}
}