-
Notifications
You must be signed in to change notification settings - Fork 151
/
custom_docker_helper.go
249 lines (218 loc) · 6.87 KB
/
custom_docker_helper.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
package registry
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"text/template"
"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-sdk-go/scw"
)
type emptyRequest struct{}
type registrySetupDockerHelperArgs struct {
Path string
}
func registryInstallDockerHelperCommand() *core.Command {
return &core.Command{
Short: `Install a local Docker credential helper`,
Long: `This command will install the Docker credential helper for your account.
It will create a new script named docker-credential-scw.
This script will be called each time Docker needs the credentials and will return the correct credentials.
It avoid running docker login commands.
`,
Namespace: "registry",
Resource: "install-docker-helper",
ArgsType: reflect.TypeOf(registrySetupDockerHelperArgs{}),
ArgSpecs: []*core.ArgSpec{
{
Name: "path",
Short: "Directory in which the Docker helper will be installed. This directory should be in your $PATH",
Default: core.DefaultValueSetter("/usr/local/bin"),
ValidateFunc: func(argSpec *core.ArgSpec, value interface{}) error {
stat, err := os.Stat(value.(string))
if err != nil || !stat.IsDir() {
return fmt.Errorf("%s is not a directory", value)
}
return nil
},
},
},
Run: registrySetupDockerHelperRun,
}
}
func registrySetupDockerHelperRun(ctx context.Context, argsI interface{}) (i interface{}, e error) {
// TODO add windows support
if runtime.GOOS == "windows" {
return nil, core.WindowIsNotSupportedError()
}
binaryName := core.ExtractBinaryName(ctx)
scriptDirArg := argsI.(*registrySetupDockerHelperArgs).Path
tpl, err := template.New("script").Parse(helperScriptTemplate)
if err != nil {
return nil, err
}
helperScriptPath := filepath.Join(scriptDirArg, fmt.Sprintf("docker-credential-%s", binaryName))
buf := bytes.Buffer{}
tplData := map[string]string{
"BinaryName": binaryName,
}
if profileName := core.ExtractProfileName(ctx); profileName != scw.DefaultProfileName {
tplData["ProfileName"] = core.ExtractProfileName(ctx)
}
err = tpl.Execute(&buf, tplData)
if err != nil {
return nil, err
}
helperScriptContent := buf.String()
// Warning
_, _ = interactive.Println("To enable the Docker credential helper we need to create the file " + helperScriptPath + " with the following lines:\n")
_, _ = interactive.Println(helperScriptContent)
// Early exit if user disagrees
_, _ = interactive.Println()
continueInstallation, err := interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{
Ctx: ctx,
Prompt: "Do you want to proceed with these changes?",
DefaultValue: true,
})
if err != nil {
return nil, err
}
if !continueInstallation {
return nil, fmt.Errorf("installation cancelled")
}
err = writeHelperScript(helperScriptPath, helperScriptContent)
if err != nil {
return nil, fmt.Errorf("failed to write helper script: %s", err)
}
var registries []string
for _, region := range scw.AllRegions {
registries = append(registries, getRegistryEndpoint(region))
}
err = setupDockerConfigFile(ctx, registries, binaryName)
if err != nil {
return nil, fmt.Errorf("failed to write docker config file: %s", err)
}
_, _ = interactive.Println()
_, err = exec.LookPath(fmt.Sprintf("docker-credential-%s", binaryName))
if err != nil {
_, _ = interactive.Println(fmt.Sprintf("docker-credential-%s is not present in your $PATH, you should add %s to your $PATH to make it work.", binaryName, path.Dir(helperScriptPath)))
_, _ = interactive.Println(fmt.Sprintf("You can add it by adding `export PATH=$PATH:%s` to your `.bashrc`, `.fishrc` or `.zshrc`", path.Dir(helperScriptPath)))
} else {
_, _ = interactive.PrintlnWithoutIndent("Docker credential helper successfully installed.")
_, _ = interactive.PrintlnWithoutIndent("The Docker credential helper will now take care of the authentication for you.")
_, _ = interactive.PrintlnWithoutIndent("You don't have to login to your registries anymore.")
}
return &core.SuccessResult{}, nil
}
const helperScriptTemplate = `#!/bin/sh
{{ if .ProfileName -}}
PROFILE_NAME="{{ .ProfileName }}"
if [[ ! -z "$SCW_PROFILE" ]]
then
PROFILE_NAME="$SCW_PROFILE"
fi
{{ end -}}
{{ .BinaryName }}{{ if .ProfileName }} --profile $PROFILE_NAME{{ end }} registry docker-helper "$@"
`
type registryDockerHelperGetResponse struct {
Secret string `json:"Secret"`
Username string `json:"Username"`
}
func registryDockerHelperGetCommand() *core.Command {
return &core.Command{
Hidden: true,
Namespace: "registry",
Resource: "docker-helper",
Verb: "get",
ArgsType: reflect.TypeOf(emptyRequest{}),
Run: registryDockerHelperGetRun,
}
}
func registryDockerHelperGetRun(ctx context.Context, _ interface{}) (i interface{}, e error) {
var serverURL string
serverURL, err := bufio.NewReader(core.ExtractStdin(ctx)).ReadString('\n')
if err != nil && err != io.EOF {
return nil, err
}
serverURL = strings.TrimRight(serverURL, "\n")
serverFound := false
for _, region := range scw.AllRegions {
if serverURL == getRegistryEndpoint(region) {
serverFound = true
break
}
}
if !serverFound {
return nil, fmt.Errorf("endpoint %s does not exist", serverURL)
}
client := core.ExtractClient(ctx)
secretKey, ok := client.GetSecretKey()
if !ok {
return nil, fmt.Errorf("could not get secret key")
}
raw, err := json.Marshal(registryDockerHelperGetResponse{
Username: "scaleway",
Secret: secretKey,
})
if err != nil {
return nil, err
}
return core.RawResult(raw), nil
}
func registryDockerHelperStoreCommand() *core.Command {
return &core.Command{
Hidden: true,
Namespace: "registry",
Resource: "docker-helper",
Verb: "store",
ArgsType: reflect.TypeOf(emptyRequest{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
return nil, nil
},
}
}
func registryDockerHelperEraseCommand() *core.Command {
return &core.Command{
Hidden: true,
Namespace: "registry",
Resource: "docker-helper",
Verb: "erase",
ArgsType: reflect.TypeOf(emptyRequest{}),
ArgSpecs: []*core.ArgSpec{
{},
},
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
return nil, nil
},
}
}
func registryDockerHelperListCommand() *core.Command {
return &core.Command{
Hidden: true,
Namespace: "registry",
Resource: "docker-helper",
Verb: "list",
ArgsType: reflect.TypeOf(emptyRequest{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
registryEndpoints := make(map[string]string)
for _, region := range scw.AllRegions {
registryEndpoints[getRegistryEndpoint(region)] = "scaleway"
}
raw, err := json.Marshal(registryEndpoints)
if err != nil {
return nil, err
}
return core.RawResult(raw), nil
},
}
}