/
dashboard.go
211 lines (184 loc) · 6.27 KB
/
dashboard.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
/*
Copyright 2016 The Kubernetes Authors 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bufio"
"fmt"
"io"
"net/http"
"os/exec"
"os/user"
"regexp"
"time"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/minikube/pkg/addons"
"k8s.io/minikube/pkg/minikube/assets"
"k8s.io/minikube/pkg/minikube/browser"
"k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/mustload"
"k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/minikube/proxy"
"k8s.io/minikube/pkg/minikube/service"
"k8s.io/minikube/pkg/util/retry"
)
var (
dashboardURLMode bool
// Matches: 127.0.0.1:8001
// TODO(tstromberg): Get kubectl to implement a stable supported output format.
hostPortRe = regexp.MustCompile(`127.0.0.1:\d{4,}`)
)
// dashboardCmd represents the dashboard command
var dashboardCmd = &cobra.Command{
Use: "dashboard",
Short: "Access the kubernetes dashboard running within the minikube cluster",
Long: `Access the kubernetes dashboard running within the minikube cluster`,
Run: func(cmd *cobra.Command, args []string) {
cname := ClusterFlagValue()
co := mustload.Healthy(cname)
for _, n := range co.Config.Nodes {
if err := proxy.ExcludeIP(n.IP); err != nil {
glog.Errorf("Error excluding IP from proxy: %s", err)
}
}
kubectl, err := exec.LookPath("kubectl")
if err != nil {
exit.WithCodeT(exit.NoInput, "kubectl not found in PATH, but is required for the dashboard. Installation guide: https://kubernetes.io/docs/tasks/tools/install-kubectl/")
}
// Check dashboard status before enabling it
dashboardAddon := assets.Addons["dashboard"]
dashboardStatus, _ := dashboardAddon.IsEnabled(cname)
if !dashboardStatus {
// Send status messages to stderr for folks re-using this output.
out.ErrT(out.Enabling, "Enabling dashboard ...")
// Enable the dashboard add-on
err = addons.Set("dashboard", "true", cname)
if err != nil {
exit.WithError("Unable to enable dashboard", err)
}
}
ns := "kubernetes-dashboard"
svc := "kubernetes-dashboard"
out.ErrT(out.Verifying, "Verifying dashboard health ...")
checkSVC := func() error { return service.CheckService(ns, svc) }
if err = retry.Expo(checkSVC, 1*time.Second, time.Minute*5); err != nil {
exit.WithCodeT(exit.Unavailable, "dashboard service is not running: {{.error}}", out.V{"error": err})
}
out.ErrT(out.Launch, "Launching proxy ...")
p, hostPort, err := kubectlProxy(kubectl, cname)
if err != nil {
exit.WithError("kubectl proxy", err)
}
url := dashboardURL(hostPort, ns, svc)
out.ErrT(out.Verifying, "Verifying proxy health ...")
chkURL := func() error { return checkURL(url) }
if err = retry.Expo(chkURL, 1*time.Second, 3*time.Minute); err != nil {
exit.WithCodeT(exit.Unavailable, "{{.url}} is not accessible: {{.error}}", out.V{"url": url, "error": err})
}
//check if current user is root
user, err := user.Current()
if err != nil {
exit.WithError("Unable to get current user", err)
}
if dashboardURLMode || user.Uid == "0" {
out.Ln(url)
} else {
out.T(out.Celebrate, "Opening {{.url}} in your default browser...", out.V{"url": url})
if err = browser.OpenURL(url); err != nil {
exit.WithCodeT(exit.Software, "failed to open browser: {{.error}}", out.V{"error": err})
}
}
glog.Infof("Success! I will now quietly sit around until kubectl proxy exits!")
if err = p.Wait(); err != nil {
glog.Errorf("Wait: %v", err)
}
},
}
// kubectlProxy runs "kubectl proxy", returning host:port
func kubectlProxy(path string, contextName string) (*exec.Cmd, string, error) {
// port=0 picks a random system port
cmd := exec.Command(path, "--context", contextName, "proxy", "--port=0")
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, "", errors.Wrap(err, "cmd stdout")
}
glog.Infof("Executing: %s %s", cmd.Path, cmd.Args)
if err := cmd.Start(); err != nil {
return nil, "", errors.Wrap(err, "proxy start")
}
glog.Infof("Waiting for kubectl to output host:port ...")
reader := bufio.NewReader(stdoutPipe)
var out []byte
for {
r, timedOut, err := readByteWithTimeout(reader, 5*time.Second)
if err != nil {
return cmd, "", fmt.Errorf("readByteWithTimeout: %v", err)
}
if r == byte('\n') {
break
}
if timedOut {
glog.Infof("timed out waiting for input: possibly due to an old kubectl version.")
break
}
out = append(out, r)
}
glog.Infof("proxy stdout: %s", string(out))
return cmd, hostPortRe.FindString(string(out)), nil
}
// readByteWithTimeout returns a byte from a reader or an indicator that a timeout has occurred.
func readByteWithTimeout(r io.ByteReader, timeout time.Duration) (byte, bool, error) {
bc := make(chan byte)
ec := make(chan error)
go func() {
b, err := r.ReadByte()
if err != nil {
ec <- err
} else {
bc <- b
}
close(bc)
close(ec)
}()
select {
case b := <-bc:
return b, false, nil
case err := <-ec:
return byte(' '), false, err
case <-time.After(timeout):
return byte(' '), true, nil
}
}
// dashboardURL generates a URL for accessing the dashboard service
func dashboardURL(proxy string, ns string, svc string) string {
// Reference: https://github.com/kubernetes/dashboard/wiki/Accessing-Dashboard---1.7.X-and-above
return fmt.Sprintf("http://%s/api/v1/namespaces/%s/services/http:%s:/proxy/", proxy, ns, svc)
}
// checkURL checks if a URL returns 200 HTTP OK
func checkURL(url string) error {
resp, err := http.Get(url)
glog.Infof("%s response: %v %+v", url, err, resp)
if err != nil {
return errors.Wrap(err, "checkURL")
}
if resp.StatusCode != http.StatusOK {
return &retry.RetriableError{
Err: fmt.Errorf("unexpected response code: %d", resp.StatusCode),
}
}
return nil
}
func init() {
dashboardCmd.Flags().BoolVar(&dashboardURLMode, "url", false, "Display dashboard URL instead of opening a browser")
}