-
Notifications
You must be signed in to change notification settings - Fork 9
/
attachdocker.go
250 lines (207 loc) · 6.83 KB
/
attachdocker.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
// 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"
"fmt"
"net"
"path/filepath"
"strings"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/context/docker"
"github.com/docker/cli/cli/context/store"
cliflags "github.com/docker/cli/cli/flags"
"github.com/muesli/reflow/wordwrap"
"github.com/spf13/cobra"
"namespacelabs.dev/foundation/framework/rpcerrors/multierr"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/colors"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnapi"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
)
func newDockerAttachCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "attach-context",
Short: "Configures a Docker context that uses an ephemeral environment.",
Args: cobra.NoArgs,
}
name := cmd.Flags().String("name", "", "The name of the context that is created; by default it will be nsc-{id}.")
use := cmd.Flags().Bool("use", false, "If true, set the new context as the default.")
stateDir := cmd.Flags().String("state", "", "If set, stores the proxy socket in this directory.")
toCluster := cmd.Flags().String("to", "", "Attaches a context to the specified cluster.")
new := cmd.Flags().Bool("new", false, "If set, creates a new cluster.")
machineType := cmd.Flags().String("machine_type", "", "Specify the machine type.")
background := cmd.Flags().Bool("background", false, "If set, attach in the background.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
if !*new && *toCluster == "" {
return fnerrors.New("one of --new or --to is required")
} else if *new && *toCluster != "" {
return fnerrors.New("only one of --new or --to may be specified")
}
dockerCli, err := command.NewDockerCli()
if err != nil {
return err
}
if err := dockerCli.Initialize(cliflags.NewClientOptions()); err != nil {
return err
}
if *name != "" {
if err := store.ValidateContextName(*name); err != nil {
return err
}
}
cluster, err := ensureDockerCluster(ctx, *toCluster, *machineType, *background)
if err != nil {
return err
}
state, err := ensureStateDir(*stateDir, "docker/"+cluster.ClusterId)
if err != nil {
return err
}
eg := executor.New(ctx, "docker")
sockPath := filepath.Join(state, "docker.sock")
if *background {
if err := setupBackgroundProxy(ctx, cluster.ClusterId, "docker", sockPath, ""); err != nil {
return err
}
} else {
eg.Go(func(ctx context.Context) error {
// if *new {
// defer func() {
// _ = api.Endpoint.ReleaseKubernetesCluster.Do(ctx, api.ReleaseKubernetesClusterRequest{
// ClusterId: cluster.ClusterId,
// }, nil)
// }()
// }
_, err := runUnixSocketProxy(ctx, cluster.ClusterId, unixSockProxyOpts{
SocketPath: sockPath,
Kind: "docker",
Blocking: true,
Connect: func(ctx context.Context) (net.Conn, error) {
token, err := fnapi.FetchToken(ctx)
if err != nil {
return nil, err
}
return connectToDocker(ctx, token, cluster)
},
})
return err
})
}
ctxName := *name
if ctxName == "" {
ctxName = "nsc-" + cluster.ClusterId
}
eg.Go(func(ctx context.Context) error {
s := dockerCli.ContextStore()
md := store.Metadata{
Endpoints: map[string]interface{}{
docker.DockerEndpoint: docker.EndpointMeta{
Host: "unix://" + sockPath,
},
},
Metadata: command.DockerContext{
Description: fmt.Sprintf("Namespace-managed Docker environment (hosted on %s)", cluster.ClusterId),
},
Name: ctxName,
}
if err := s.CreateOrUpdate(md); err != nil {
return err
}
console.SetStickyContent(ctx, "docker", dockerBanner(ctx, ctxName, *use, *background))
was := dockerCli.CurrentContext()
if !*background {
eg.Go(func(ctx context.Context) error {
<-ctx.Done() // Wait for cancelation.
removeErr := s.Remove(ctxName)
if *use {
if err := updateContext(dockerCli, was, func(current string) bool {
return current == ctxName
}); err != nil {
return multierr.New(removeErr, err)
}
}
return removeErr
})
}
if *use {
if err := updateContext(dockerCli, ctxName, nil); err != nil {
return err
}
}
return nil
})
return eg.Wait()
})
return cmd
}
func dockerBanner(ctx context.Context, ctxName string, use, background bool) string {
w := wordwrap.NewWriter(80)
style := colors.Ctx(ctx)
fmt.Fprintf(w, "Attached Docker Context: %s\n\n", ctxName)
if use {
fmt.Fprintf(w, "You can use the context directly:\n\n")
fmt.Fprintf(w, " $ docker run --rm -it ubuntu\n")
fmt.Fprintln(w)
} else {
fmt.Fprintf(w, "You can use the context by passing `--context %s` to `docker`:\n\n", ctxName)
fmt.Fprintf(w, " $ docker --context %s run --rm -it ubuntu\n", ctxName)
fmt.Fprintln(w)
}
fmt.Fprintf(w, "Or by setting the environment variable DOCKER_CONTEXT:\n\n")
fmt.Fprintf(w, " $ export DOCKER_CONTEXT=%q\n", ctxName)
fmt.Fprintf(w, " $ docker run --rm -it ubuntu\n")
if !background {
fmt.Fprintln(w)
fmt.Fprintln(w, style.Comment.Apply("Exiting will remove the context configuration."))
}
_ = w.Close()
return strings.TrimSpace(w.String())
}
func updateContext(dockerCli *command.DockerCli, ctxName string, shouldUpdate func(string) bool) error {
dockerConfig := dockerCli.ConfigFile()
if shouldUpdate == nil {
shouldUpdate = func(current string) bool {
return current != ctxName
}
}
// Avoid updating the config-file if nothing changed. This also prevents
// creating the file and config-directory if the default is used and
// no config-file existed yet.
if shouldUpdate(dockerConfig.CurrentContext) {
dockerConfig.CurrentContext = ctxName
if err := dockerConfig.Save(); err != nil {
return err
}
}
return nil
}
func ensureDockerCluster(ctx context.Context, specified, machineType string, background bool) (*api.KubernetesCluster, error) {
if specified != "" {
resp, err := api.EnsureCluster(ctx, api.Methods, specified)
if err != nil {
return nil, err
}
return resp.Cluster, nil
}
featuresList := []string{"EXP_DISABLE_KUBERNETES"}
resp, err := api.CreateAndWaitCluster(ctx, api.Methods, api.CreateClusterOpts{
Purpose: "Docker environment",
Features: featuresList,
KeepAtExit: background,
MachineType: machineType,
WaitClusterOpts: api.WaitClusterOpts{
CreateLabel: "Creating Docker environment",
WaitForService: "buildkit",
WaitKind: "buildcluster",
},
})
if err != nil {
return nil, err
}
return resp.Cluster, nil
}