forked from Azure/draft-classic
/
up.go
297 lines (258 loc) · 9.21 KB
/
up.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
package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/Azure/go-autorest/autorest"
azurecli "github.com/Azure/go-autorest/autorest/azure/cli"
"github.com/docker/cli/cli/command"
cliconfig "github.com/docker/cli/cli/config"
dockerdebug "github.com/docker/cli/cli/debug"
dockerflags "github.com/docker/cli/cli/flags"
"github.com/docker/cli/opts"
"github.com/docker/go-connections/tlsconfig"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/net/context"
"k8s.io/client-go/rest"
"github.com/Azure/draft/pkg/azure/containerregistry"
"github.com/Azure/draft/pkg/azure/iam"
"github.com/Azure/draft/pkg/builder"
azurecontainerbuilder "github.com/Azure/draft/pkg/builder/azure"
dockercontainerbuilder "github.com/Azure/draft/pkg/builder/docker"
"github.com/Azure/draft/pkg/cmdline"
"github.com/Azure/draft/pkg/draft/draftpath"
"github.com/Azure/draft/pkg/local"
"github.com/Azure/draft/pkg/storage/kube/configmap"
"github.com/Azure/draft/pkg/tasks"
)
const upDesc = `
This command builds a container image using Docker, pushes it to a container registry
and then instructs helm to install the chart, referencing the image just built.
`
const (
ignoreFileName = ".draftignore"
dockerTLSEnvVar = "DOCKER_TLS"
dockerTLSVerifyEnvVar = "DOCKER_TLS_VERIFY"
tasksTOMLFile = ".draft-tasks.toml"
)
var (
dockerCertPath = os.Getenv("DOCKER_CERT_PATH")
autoConnect bool
)
type upCmd struct {
out io.Writer
src string
home draftpath.Home
// storage engine draft should use for storing builds, logs, etc.
storageEngine string
// options common to the docker client and the daemon.
dockerClientOptions *dockerflags.ClientOptions
}
func defaultDockerTLS() bool {
return os.Getenv(dockerTLSEnvVar) != ""
}
func defaultDockerTLSVerify() bool {
return os.Getenv(dockerTLSVerifyEnvVar) != ""
}
func dockerPreRun(opts *dockerflags.ClientOptions) {
dockerflags.SetLogLevel(opts.Common.LogLevel)
if opts.ConfigDir != "" {
cliconfig.SetDir(opts.ConfigDir)
}
if opts.Common.Debug {
dockerdebug.Enable()
}
}
func newUpCmd(out io.Writer) *cobra.Command {
var (
up = &upCmd{
out: out,
dockerClientOptions: dockerflags.NewClientOptions(),
}
runningEnvironment string
f *pflag.FlagSet
)
cmd := &cobra.Command{
Use: "up [path]",
Short: "build and push Docker image, then install the Helm chart, referencing the image just built",
Long: upDesc,
PersistentPreRun: func(c *cobra.Command, args []string) {
rootCmd.PersistentPreRunE(c, args)
up.dockerClientOptions.Common.SetDefaultOptions(f)
dockerPreRun(up.dockerClientOptions)
},
RunE: func(_ *cobra.Command, args []string) (err error) {
if len(args) > 0 {
up.src = args[0]
}
if up.src == "" || up.src == "." {
if up.src, err = os.Getwd(); err != nil {
return err
}
}
up.home = draftpath.Home(homePath())
return up.run(runningEnvironment)
},
}
f = cmd.Flags()
f.StringVarP(&runningEnvironment, environmentFlagName, environmentFlagShorthand, defaultDraftEnvironment(), environmentFlagUsage)
f.BoolVar(&up.dockerClientOptions.Common.Debug, "docker-debug", false, "Enable debug mode")
f.StringVar(&up.dockerClientOptions.Common.LogLevel, "docker-log-level", "info", `Set the logging level ("debug"|"info"|"warn"|"error"|"fatal")`)
f.BoolVar(&up.dockerClientOptions.Common.TLS, "docker-tls", defaultDockerTLS(), "Use TLS; implied by --tlsverify")
f.BoolVar(&up.dockerClientOptions.Common.TLSVerify, fmt.Sprintf("docker-%s", dockerflags.FlagTLSVerify), defaultDockerTLSVerify(), "Use TLS and verify the remote")
f.StringVar(&up.dockerClientOptions.ConfigDir, "docker-config", cliconfig.Dir(), "Location of client config files")
f.BoolVarP(&autoConnect, "auto-connect", "", false, "specifies if draft up should automatically connect to the application")
up.dockerClientOptions.Common.TLSOptions = &tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, dockerflags.DefaultCaFile),
CertFile: filepath.Join(dockerCertPath, dockerflags.DefaultCertFile),
KeyFile: filepath.Join(dockerCertPath, dockerflags.DefaultKeyFile),
}
tlsOptions := up.dockerClientOptions.Common.TLSOptions
f.Var(opts.NewQuotedString(&tlsOptions.CAFile), "docker-tlscacert", "Trust certs signed only by this CA")
f.Var(opts.NewQuotedString(&tlsOptions.CertFile), "docker-tlscert", "Path to TLS certificate file")
f.Var(opts.NewQuotedString(&tlsOptions.KeyFile), "docker-tlskey", "Path to TLS key file")
hostOpt := opts.NewNamedListOptsRef("docker-hosts", &up.dockerClientOptions.Common.Hosts, opts.ValidateHost)
f.Var(hostOpt, "docker-host", "Daemon socket(s) to connect to")
return cmd
}
func (u *upCmd) run(environment string) (err error) {
var (
buildctx *builder.Context
kubeConfig *rest.Config
ctx = context.Background()
bldr = builder.New()
)
bldr.LogsDir = u.home.Logs()
taskList, err := tasks.Load(tasksTOMLFile)
if err != nil {
if err == tasks.ErrNoTaskFile {
debug(err.Error())
} else {
return err
}
} else {
if _, err = taskList.Run(tasks.DefaultRunner, tasks.PreUp, ""); err != nil {
return err
}
}
if buildctx, err = builder.LoadWithEnv(u.src, environment); err != nil {
return fmt.Errorf("failed loading build context with env %q: %v", environment, err)
}
if configuredBuilder, ok := globalConfig[containerBuilder.name]; ok {
buildctx.Env.ContainerBuilder = configuredBuilder
}
// if a registry has been set in their global config but nothing was in draft.toml, use that instead
if reg, ok := globalConfig[registry.name]; ok {
buildctx.Env.Registry = reg
}
if configuredResourceGroup, ok := globalConfig[resourceGroupName.name]; ok {
buildctx.Env.ResourceGroupName = configuredResourceGroup
}
if buildctx.Env.Registry == "" {
// give a way for minikube users (and users who understand what they're doing) a way to opt out
if _, ok := globalConfig[disablePushWarning.name]; !ok {
fmt.Fprintln(u.out, "WARNING: no registry has been set, therefore Draft will not push to a container registry. This can be fixed by running `draft config set registry docker.io/myusername`")
fmt.Fprintln(u.out, "Hint: this warning can be disabled by running `draft config set disable-push-warning 1`")
}
}
var cb builder.ContainerBuilder
switch buildctx.Env.ContainerBuilder {
case "acrbuild":
subscription, err := getSubscriptionFromProfile()
if err != nil {
return fmt.Errorf("Could not retrieve azure profile information: %v", err)
}
token, err := iam.GetToken(iam.AuthGrantType())
if err != nil {
return fmt.Errorf("Could not retrieve adal token: %v", err)
}
auth := autorest.NewBearerAuthorizer(&token)
registriesClient := containerregistry.NewRegistriesClient(subscription.ID)
registriesClient.Authorizer = auth
registriesClient.AddToUserAgent(containerregistry.UserAgent())
buildsClient := containerregistry.NewBuildsClient(subscription.ID)
buildsClient.Authorizer = auth
buildsClient.AddToUserAgent(containerregistry.UserAgent())
cb = &azurecontainerbuilder.Builder{
RegistryClient: registriesClient,
BuildsClient: buildsClient,
AdalToken: token,
Subscription: subscription,
}
default:
// setup docker
cli := &command.DockerCli{}
if err := cli.Initialize(u.dockerClientOptions); err != nil {
return fmt.Errorf("failed to create docker client: %v", err)
}
cb = &dockercontainerbuilder.Builder{
DockerClient: cli,
}
}
bldr.ContainerBuilder = cb
// setup kube
bldr.Kube, kubeConfig, err = getKubeClient(kubeContext)
if err != nil {
return fmt.Errorf("Could not get a kube client: %s", err)
}
bldr.Helm, err = setupHelm(bldr.Kube, kubeConfig, tillerNamespace)
if err != nil {
return fmt.Errorf("Could not get a helm client: %s", err)
}
// setup the storage engine
bldr.Storage = configmap.NewConfigMaps(bldr.Kube.CoreV1().ConfigMaps(tillerNamespace))
progressC := bldr.Up(ctx, buildctx)
cmdline.Display(ctx, buildctx.Env.Name, progressC, cmdline.WithBuildID(bldr.ID))
if buildctx.Env.AutoConnect || autoConnect {
c := newConnectCmd(u.out)
return c.RunE(c, []string{})
}
if err := runPostDeployTasks(taskList, bldr.ID); err != nil {
debug(err.Error())
return nil
}
return nil
}
func runPostDeployTasks(taskList *tasks.Tasks, buildID string) error {
if taskList == nil || len(taskList.PostDeploy) == 0 {
return errors.New("No post deploy tasks to run")
}
app, err := local.DeployedApplication(draftToml, runningEnvironment)
if err != nil {
return err
}
client, _, err := getKubeClient(kubeContext)
if err != nil {
return err
}
names, err := app.GetPodNames(buildID, client)
if err != nil {
return err
}
for _, name := range names {
_, err := taskList.Run(tasks.DefaultRunner, tasks.PostDeploy, name)
if err != nil {
debug("error running task: %v", err)
}
}
return nil
}
func getSubscriptionFromProfile() (azurecli.Subscription, error) {
profilePath, err := azurecli.ProfilePath()
if err != nil {
return azurecli.Subscription{}, err
}
profile, err := azurecli.LoadProfile(profilePath)
if err != nil {
return azurecli.Subscription{}, err
}
for _, sub := range profile.Subscriptions {
if sub.IsDefault {
return sub, nil
}
}
return azurecli.Subscription{}, fmt.Errorf("could not find a default subscription ID from %s", profilePath)
}