/
run.go
518 lines (433 loc) · 15.9 KB
/
run.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cluster
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
composecli "github.com/compose-spec/compose-go/cli"
"github.com/google/go-containerregistry/pkg/name"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/timestamppb"
"gopkg.in/yaml.v3"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/colors"
"namespacelabs.dev/foundation/internal/fnapi"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
"namespacelabs.dev/foundation/internal/providers/nscloud/ctl"
"namespacelabs.dev/foundation/internal/providers/nscloud/endpoint"
"namespacelabs.dev/foundation/std/tasks"
"namespacelabs.dev/go-ids"
)
func NewRunCmd() *cobra.Command {
run := &cobra.Command{
Use: "run",
Short: "Starts a container in an ephemeral environment, optionally exporting ports for public serving.",
Args: cobra.ArbitraryArgs,
}
machineType := run.Flags().String("machine_type", "", "Specify the machine type.")
image := run.Flags().String("image", "", "Which image to run.")
requestedName := run.Flags().String("name", "", "If no name is specified, one is generated.")
exportedPorts := run.Flags().Int32SliceP("publish", "p", nil, "Publish the specified ports.")
output := run.Flags().StringP("output", "o", "plain", "One of plain or json.")
on := run.Flags().String("on", "", "Run the container in the specified container, instead of creating a new one.")
env := run.Flags().StringToStringP("env", "e", map[string]string{}, "Pass these additional environment variables to the container.")
devmode := run.Flags().Bool("development", false, "If true, enables a few development facilities, including making containers optional.")
wait := run.Flags().Bool("wait", false, "Wait for the container to start running.")
features := run.Flags().StringSlice("features", nil, "A set of features to attach to the instance.")
ingressRules := run.Flags().StringToString("ingress", map[string]string{}, "Specify ingress rules for ports; specify * to apply rules to any port; separate each rule with ;.")
duration := run.Flags().Duration("duration", 0, "For how long to run the ephemeral environment.")
labels := run.Flags().StringToString("label", nil, "Create the environment with a set of labels.")
internalExtra := run.Flags().String("internal_extra", "", "Internal creation details.")
enableDocker := run.Flags().Bool("enable_docker", false, "If set to true, instructs the platform to also setup docker in the container.")
forwardNscState := run.Flags().Bool("forward_nsc_state", false, "If set to true, instructs the platform to forward nsc state into the container.")
exposeNscBins := run.Flags().Bool("expose_nsc_bins", false, "If set to true, exposes Namespace managed nsc binaries to the container.")
network := run.Flags().String("network", "", "The network setting to start the container with.")
experimental := run.Flags().String("experimental", "", "A set of experimental settings to pass during creation.")
instanceExperimental := run.Flags().String("instance_experimental", "", "A set of experimental instance settings to pass during creation.")
userSshey := run.Flags().String("ssh_key", "", "Injects the specified ssh public key in the created instance.")
run.Flags().MarkHidden("label")
run.Flags().MarkHidden("internal_extra")
run.Flags().MarkHidden("enable_docker")
run.Flags().MarkHidden("forward_nsc_state")
run.Flags().MarkHidden("network")
run.Flags().MarkHidden("experimental")
run.Flags().MarkHidden("instance_experimental")
run.Flags().MarkHidden("expose_nsc_bins")
run.Flags().MarkHidden("ssh_key")
run.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
name := *requestedName
if *image == "" {
return fnerrors.New("--image is required")
}
if name == "" {
name = generateNameFromImage(*image)
}
if *on != "" {
if *devmode {
return fnerrors.New("--development can only be set when creating an environment (i.e. it can't be set when --on is specified)")
}
if *machineType != "" {
return fnerrors.New("--machine_type can only be set when creating an environment (i.e. it can't be set when --on is specified)")
}
if *duration > 0 {
return fnerrors.New("--duration can only be set when creating an environment (i.e. it can't be set when --on is specified)")
}
}
opts := CreateContainerOpts{
Name: name,
Image: *image,
Args: args,
Env: *env,
Features: *features,
Labels: *labels,
InternalExtra: *internalExtra,
EnableDocker: *enableDocker,
ForwardNscState: *forwardNscState,
ExposeNscBins: *exposeNscBins,
Network: *network,
}
if keys, err := parseAuthorizedKeys(*userSshey); err != nil {
return err
} else {
opts.AuthorizedSshKeys = keys
}
if *experimental != "" {
if err := json.Unmarshal([]byte(*experimental), &opts.Experimental); err != nil {
return fnerrors.New("failed to parse: %w", err)
}
}
if *instanceExperimental != "" {
if err := json.Unmarshal([]byte(*instanceExperimental), &opts.InstanceExperimental); err != nil {
return fnerrors.New("failed to parse: %w", err)
}
}
if *instanceExperimental != "" {
var m any
if err := json.Unmarshal([]byte(*instanceExperimental), &m); err != nil {
return fnerrors.New("failed to parse: %w", err)
}
opts.InstanceExperimental = m
}
exported, err := fillInIngressRules(*exportedPorts, *ingressRules)
if err != nil {
return err
}
opts.ExportedPorts = exported
resp, err := CreateContainerInstance(ctx, *machineType, *duration, *on, *devmode, opts)
if err != nil {
return err
}
if *wait {
clusterId := *on
if clusterId == "" {
clusterId = resp.ClusterId
}
if err := ctl.WaitContainers(ctx, clusterId, resp.Container); err != nil {
return err
}
}
// This needs to handle the case both of when a cluster is created, and
// when StartContainers are called.
return PrintCreateContainersResult(ctx, *output, resp)
})
return run
}
func fillInIngressRules(ports []int32, ingressRules map[string]string) ([]exportContainerPort, error) {
var exported []exportContainerPort
matched := map[string]struct{}{}
for _, p := range ports {
portKey := fmt.Sprintf("%d", p)
rules, ok := ingressRules[portKey]
if !ok {
rules = ingressRules["*"]
} else {
matched[portKey] = struct{}{}
}
x := exportContainerPort{
ContainerPort: p,
}
if rules != "" {
for _, ruleSpec := range strings.Split(rules, ";") {
rule, err := parseRule(ruleSpec)
if err != nil {
return nil, err
}
x.HttpIngressRules = append(x.HttpIngressRules, rule)
}
}
exported = append(exported, x)
}
for k := range ingressRules {
if _, ok := matched[k]; ok || k == "*" {
continue
}
return nil, fnerrors.New("specified ingress rule for port %q which is not exported", k)
}
return exported, nil
}
func NewRunComposeCmd() *cobra.Command {
run := &cobra.Command{
Use: "run-compose",
Short: "Starts a set of containers in an ephemeral environment.",
Args: cobra.NoArgs,
Hidden: true,
}
output := run.Flags().StringP("output", "o", "plain", "one of plain or json")
dir := run.Flags().String("dir", "", "If not specified, loads the compose project from the current working directory.")
devmode := run.Flags().Bool("development", false, "If true, enables a few development facilities, including making containers optional.")
wait := run.Flags().Bool("wait", false, "Wait for all containers to start running.")
run.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
resp, err := createCompose(ctx, *dir, *devmode)
if err != nil {
return err
}
if *wait {
if err := ctl.WaitContainers(ctx, resp.ClusterId, resp.Container); err != nil {
return err
}
}
return PrintCreateContainersResult(ctx, *output, resp)
})
return run
}
type CreateContainerOpts struct {
Name string
Image string
Args []string
Env map[string]string
Flags []string
ExportedPorts []exportContainerPort
Features []string
Labels map[string]string
InternalExtra string
EnableDocker bool
ForwardNscState bool
ExposeNscBins bool
Network string
Experimental any
InstanceExperimental any
AuthorizedSshKeys []string
}
type exportContainerPort struct {
ContainerPort int32
HttpIngressRules []*api.ContainerPort_HttpMatchRule
}
func CreateContainerInstance(ctx context.Context, machineType string, duration time.Duration, target string, devmode bool, opts CreateContainerOpts) (*api.CreateContainersResponse, error) {
container := &api.ContainerRequest{
Name: opts.Name,
Image: opts.Image,
Args: opts.Args,
Env: opts.Env,
Flag: []string{"TERMINATE_ON_EXIT"},
Network: opts.Network,
Experimental: opts.Experimental,
}
if opts.EnableDocker {
container.DockerSockPath = "/var/run/docker.sock"
}
if opts.ForwardNscState {
container.NscStatePath = "/var/run/nsc"
}
if opts.ExposeNscBins {
container.ExposeNscBins = "/nsc/bin"
}
for _, port := range opts.ExportedPorts {
container.ExportPort = append(container.ExportPort, &api.ContainerPort{
Proto: "tcp",
Port: port.ContainerPort,
HttpMatchRule: port.HttpIngressRules,
})
}
var labels []*api.LabelEntry
for key, value := range opts.Labels {
labels = append(labels, &api.LabelEntry{Name: key, Value: value})
}
if target == "" {
const label = "Creating container environment"
resp, err := tasks.Return(ctx, tasks.Action("nscloud.create-containers").HumanReadablef(label), func(ctx context.Context) (*api.CreateContainersResponse, error) {
req := api.CreateContainersRequest{
MachineType: machineType,
Container: []*api.ContainerRequest{container},
DevelopmentMode: devmode,
Label: labels,
Feature: opts.Features,
InternalExtra: opts.InternalExtra,
Experimental: opts.InstanceExperimental,
AuthorizedSshKeys: opts.AuthorizedSshKeys,
}
if duration > 0 {
req.Deadline = timestamppb.New(time.Now().Add(duration))
}
var response api.CreateContainersResponse
if err := api.Methods.CreateContainers.Do(ctx, req, endpoint.ResolveRegionalEndpoint, fnapi.DecodeJSONResponse(&response)); err != nil {
return nil, err
}
return &response, nil
})
if err != nil {
return nil, err
}
if _, err := api.WaitClusterReady(ctx, api.Methods, resp.ClusterId, api.WaitClusterOpts{
CreateLabel: label,
}); err != nil {
return nil, err
}
return resp, nil
}
return tasks.Return(ctx, tasks.Action("nscloud.start-containers").HumanReadablef("Starting containers"),
func(ctx context.Context) (*api.CreateContainersResponse, error) {
var response api.StartContainersResponse
if err := api.Methods.StartContainers.Do(ctx, api.StartContainersRequest{
Id: target,
Container: []*api.ContainerRequest{container},
}, endpoint.ResolveRegionalEndpoint, fnapi.DecodeJSONResponse(&response)); err != nil {
return nil, err
}
return &api.CreateContainersResponse{
Container: response.Container,
}, nil
})
}
func parseRule(spec string) (*api.ContainerPort_HttpMatchRule, error) {
parts := strings.SplitN(spec, ":", 3)
rule, err := parseEffect(parts[len(parts)-1])
if err != nil {
return nil, err
}
switch len(parts) {
case 1:
// Apply to all paths and methods
case 2:
// All methods: [path]: [spec]
rule.Match = &api.ContainerPort_HttpMatch{Path: parts[0]}
case 3:
// [methods]:[path]:[spec]
rule.Match = &api.ContainerPort_HttpMatch{Method: parseMethods(parts[0]), Path: parts[1]}
}
return rule, nil
}
func parseMethods(spec string) []string {
var methods []string
parts := strings.Split(spec, ",")
for _, p := range parts {
methods = append(methods, strings.ToUpper(p))
}
return methods
}
func parseEffect(spec string) (*api.ContainerPort_HttpMatchRule, error) {
parts := strings.Split(spec, ",")
x := &api.ContainerPort_HttpMatchRule{}
for _, p := range parts {
switch strings.ToLower(p) {
case "noauth":
x.DoesNotRequireAuth = true
default:
return nil, fnerrors.New("unrecognized rule %q", p)
}
}
return x, nil
}
func PrintCreateContainersResult(ctx context.Context, output string, resp *api.CreateContainersResponse) error {
switch output {
case "json":
d := json.NewEncoder(console.Stdout(ctx))
d.SetIndent("", " ")
if err := d.Encode(createOutput{
ClusterId: resp.ClusterId,
ClusterUrl: resp.ClusterUrl,
Container: resp.Container,
}); err != nil {
return fnerrors.InternalError("failed to encode countainer creation output as JSON output: %w", err)
}
default:
if output != "" && output != "plain" {
fmt.Fprintf(console.Warnings(ctx), "unsupported output %q, defaulting to plain\n", output)
}
// ClusterId is not set when `--on` is used.
if resp.ClusterId != "" {
printNewEnv(ctx, resp.ClusterId, resp.ClusterUrl)
}
for _, ctr := range resp.Container {
fmt.Fprintf(console.Stdout(ctx), "\n Started %q\n", ctr.Name)
if len(ctr.ExportedPort) > 0 {
fmt.Fprintln(console.Stdout(ctx))
for _, port := range ctr.ExportedPort {
fmt.Fprintf(console.Stdout(ctx), " Exported %d/%s as https://%s\n", port.ContainerPort, port.Proto, port.IngressFqdn)
}
}
}
fmt.Fprintln(console.Stdout(ctx))
}
return nil
}
func printNewEnv(ctx context.Context, clusterID, clusterURL string) {
style := colors.Ctx(ctx)
stdout := console.Stdout(ctx)
fmt.Fprintf(stdout, "\n Created new ephemeral environment! ID: %s\n", clusterID)
fmt.Fprintf(stdout, "\n %s %s\n", style.Comment.Apply("More at:"), clusterURL)
}
func createCompose(ctx context.Context, dir string, devmode bool) (*api.CreateContainersResponse, error) {
var optionsFn []composecli.ProjectOptionsFn
optionsFn = append(optionsFn,
composecli.WithOsEnv,
// composecli.WithEnvFile(o.EnvFile),
composecli.WithConfigFileEnv,
composecli.WithDefaultConfigPath,
composecli.WithDotEnv,
// composecli.WithName(o.Project),
)
if dir != "" {
optionsFn = append(optionsFn, composecli.WithWorkingDirectory(dir))
}
projectOptions, err := composecli.NewProjectOptions(nil, optionsFn...)
if err != nil {
return nil, err
}
project, err := composecli.ProjectFromOptions(projectOptions)
if err != nil {
return nil, err
}
projectYAML, err := yaml.Marshal(project)
if err != nil {
return nil, err
}
resp, err := tasks.Return(ctx, tasks.Action("nscloud.create-containers"), func(ctx context.Context) (*api.CreateContainersResponse, error) {
var response api.CreateContainersResponse
if err := api.Methods.CreateContainers.Do(ctx, api.CreateContainersRequest{
Compose: []*api.ComposeRequest{{Contents: projectYAML}},
DevelopmentMode: devmode,
}, endpoint.ResolveRegionalEndpoint, fnapi.DecodeJSONResponse(&response)); err != nil {
return nil, err
}
return &response, nil
})
if err != nil {
return nil, err
}
if _, err := api.WaitClusterReady(ctx, api.Methods, resp.ClusterId, api.WaitClusterOpts{}); err != nil {
return nil, err
}
return resp, nil
}
func generateNameFromImage(image string) string {
if tag, err := name.NewTag(image); err == nil {
p := strings.Split(tag.RepositoryStr(), "/")
last := p[len(p)-1]
if len(last) < 16 {
return fmt.Sprintf("%s-%s", last, ids.NewRandomBase32ID(3))
}
}
return ids.NewRandomBase32ID(6)
}
type createOutput struct {
ClusterId string `json:"cluster_id,omitempty"`
ClusterUrl string `json:"cluster_url,omitempty"`
Container []*api.Container `json:"container,omitempty"`
IngressDomain string `json:"ingress_domain,omitempty"`
}