-
Notifications
You must be signed in to change notification settings - Fork 290
/
minikube.go
80 lines (67 loc) · 2.14 KB
/
minikube.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
package k8s
import (
"bufio"
"bytes"
"context"
"fmt"
"os/exec"
"regexp"
"strings"
"github.com/pkg/errors"
)
// This isn't perfect (because it won't unquote the value right) but
// it's good enough for 99% of cases.
var envMatcher = regexp.MustCompile(`export (\w+)="([^"]+)"`)
type MinikubeClient interface {
DockerEnv(ctx context.Context) (map[string]string, error)
NodeIP(ctx context.Context) (NodeIP, error)
}
type minikubeClient struct {
context KubeContext
}
func ProvideMinikubeClient(context KubeContext) MinikubeClient {
return minikubeClient{context: context}
}
func (mc minikubeClient) cmd(ctx context.Context, args ...string) *exec.Cmd {
args = append([]string{"-p", string(mc.context)}, args...)
return exec.CommandContext(ctx, "minikube", args...)
}
func (mc minikubeClient) DockerEnv(ctx context.Context) (map[string]string, error) {
cmd := mc.cmd(ctx, "docker-env", "--shell", "sh")
output, err := cmd.Output()
if err != nil {
exitErr, isExitErr := err.(*exec.ExitError)
if isExitErr {
// TODO(nick): Maybe we should automatically run minikube start?
return nil, fmt.Errorf("Could not read docker env from minikube.\n"+
"Did you forget to run `minikube start`?\n%s", string(exitErr.Stderr))
}
return nil, errors.Wrap(err, "Could not read docker env from minikube")
}
return dockerEnvFromOutput(output)
}
func dockerEnvFromOutput(output []byte) (map[string]string, error) {
result := make(map[string]string)
scanner := bufio.NewScanner(bytes.NewBuffer(output))
for scanner.Scan() {
line := scanner.Text()
match := envMatcher.FindStringSubmatch(line)
if len(match) > 0 {
result[match[1]] = match[2]
}
}
return result, nil
}
func (mc minikubeClient) NodeIP(ctx context.Context) (NodeIP, error) {
cmd := mc.cmd(ctx, "ip")
out, err := cmd.Output()
if err != nil {
exitErr, isExitErr := err.(*exec.ExitError)
if isExitErr {
return "", errors.Wrapf(exitErr, "Could not read node IP from minikube.\n"+
"Did you forget to run `minikube start`?\n%s", string(exitErr.Stderr))
}
return "", errors.Wrapf(err, "Could not read node IP from minikube")
}
return NodeIP(strings.TrimSpace(string(out))), nil
}