forked from kubernetes/minikube
/
cluster.go
769 lines (671 loc) · 22.1 KB
/
cluster.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/*
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 cluster
import (
"bytes"
"crypto"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/docker/machine/drivers/virtualbox"
"github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/engine"
"github.com/docker/machine/libmachine/host"
"github.com/docker/machine/libmachine/state"
"github.com/golang/glog"
download "github.com/jimmidyson/go-download"
"github.com/pkg/browser"
"github.com/pkg/errors"
kubeapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/minikube/pkg/minikube/assets"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/sshutil"
"k8s.io/minikube/pkg/util"
)
var (
certs = []string{"ca.crt", "ca.key", "apiserver.crt", "apiserver.key"}
)
const fileScheme = "file"
//This init function is used to set the logtostderr variable to false so that INFO level log info does not clutter the CLI
//INFO lvl logging is displayed due to the kubernetes api calling flag.Set("logtostderr", "true") in its init()
//see: https://github.com/kubernetes/kubernetes/blob/master/pkg/util/logs/logs.go#L32-34
func init() {
flag.Set("logtostderr", "false")
}
// StartHost starts a host VM.
func StartHost(api libmachine.API, config MachineConfig) (*host.Host, error) {
exists, err := api.Exists(constants.MachineName)
if err != nil {
return nil, errors.Wrapf(err, "Error checking if host exists: %s", constants.MachineName)
}
if !exists {
return createHost(api, config)
}
glog.Infoln("Machine exists!")
h, err := api.Load(constants.MachineName)
if err != nil {
return nil, errors.Wrap(err, "Error loading existing host. Please try running [minikube delete], then run [minikube start] again.")
}
s, err := h.Driver.GetState()
glog.Infoln("Machine state: ", s)
if err != nil {
return nil, errors.Wrap(err, "Error getting state for host")
}
if s != state.Running {
if err := h.Driver.Start(); err != nil {
return nil, errors.Wrapf(err, "Error starting stopped host")
}
if err := api.Save(h); err != nil {
return nil, errors.Wrapf(err, "Error saving started host")
}
}
if err := h.ConfigureAuth(); err != nil {
return nil, &util.RetriableError{Err: errors.Wrap(err, "Error configuring auth on host")}
}
return h, nil
}
// StopHost stops the host VM.
func StopHost(api libmachine.API) error {
host, err := api.Load(constants.MachineName)
if err != nil {
return errors.Wrapf(err, "Error loading host: %s", constants.MachineName)
}
if err := host.Stop(); err != nil {
return errors.Wrapf(err, "Error stopping host: %s", constants.MachineName)
}
return nil
}
// DeleteHost deletes the host VM.
func DeleteHost(api libmachine.API) error {
host, err := api.Load(constants.MachineName)
if err != nil {
return errors.Wrapf(err, "Error deleting host: %s", constants.MachineName)
}
m := util.MultiError{}
m.Collect(host.Driver.Remove())
m.Collect(api.Remove(constants.MachineName))
return m.ToError()
}
// GetHostStatus gets the status of the host VM.
func GetHostStatus(api libmachine.API) (string, error) {
dne := "Does Not Exist"
exists, err := api.Exists(constants.MachineName)
if err != nil {
return "", errors.Wrapf(err, "Error checking that api exists for: ", constants.MachineName)
}
if !exists {
return dne, nil
}
host, err := api.Load(constants.MachineName)
if err != nil {
return "", errors.Wrapf(err, "Error loading api for: ", constants.MachineName)
}
s, err := host.Driver.GetState()
if s.String() == "" {
return dne, nil
}
if err != nil {
return "", errors.Wrap(err, "Error getting host state")
}
return s.String(), nil
}
// GetLocalkubeStatus gets the status of localkube from the host VM.
func GetLocalkubeStatus(api libmachine.API) (string, error) {
host, err := CheckIfApiExistsAndLoad(api)
if err != nil {
return "", err
}
s, err := host.RunSSHCommand(localkubeStatusCommand)
if err != nil {
return "", err
}
s = strings.TrimSpace(s)
if state.Running.String() == s {
return state.Running.String(), nil
} else if state.Stopped.String() == s {
return state.Stopped.String(), nil
} else {
return "", fmt.Errorf("Error: Unrecognize output from GetLocalkubeStatus: %s", s)
}
}
type sshAble interface {
RunSSHCommand(string) (string, error)
}
// MachineConfig contains the parameters used to start a cluster.
type MachineConfig struct {
MinikubeISO string
Memory int
CPUs int
DiskSize int
VMDriver string
DockerEnv []string // Each entry is formatted as KEY=VALUE.
InsecureRegistry []string
RegistryMirror []string
HostOnlyCIDR string // Only used by the virtualbox driver
HypervVirtualSwitch string
KvmNetwork string // Only used by the KVM driver
}
// KubernetesConfig contains the parameters used to configure the VM Kubernetes.
type KubernetesConfig struct {
KubernetesVersion string
NodeIP string
ContainerRuntime string
NetworkPlugin string
ExtraOptions util.ExtraOptionSlice
}
// StartCluster starts a k8s cluster on the specified Host.
func StartCluster(h sshAble, kubernetesConfig KubernetesConfig) error {
startCommand, err := GetStartCommand(kubernetesConfig)
if err != nil {
return errors.Wrapf(err, "Error generating start command: %s", err)
}
commands := []string{stopCommand, startCommand}
for _, cmd := range commands {
glog.Infoln(cmd)
output, err := h.RunSSHCommand(cmd)
glog.Infoln(output)
if err != nil {
return errors.Wrapf(err, "Error running ssh command: %s", cmd)
}
}
return nil
}
func UpdateCluster(h sshAble, d drivers.Driver, config KubernetesConfig) error {
client, err := sshutil.NewSSHClient(d)
if err != nil {
return errors.Wrap(err, "Error creating new ssh client")
}
// transfer localkube from cache/asset to vm
if localkubeURIWasSpecified(config) {
lCacher := localkubeCacher{config}
if err = lCacher.updateLocalkubeFromURI(client); err != nil {
return errors.Wrap(err, "Error updating localkube from uri")
}
} else {
if err = updateLocalkubeFromAsset(client); err != nil {
return errors.Wrap(err, "Error updating localkube from asset")
}
}
fileAssets := []assets.CopyableFile{}
assets.AddMinikubeAddonsDirToAssets(&fileAssets)
// merge files to copy
var copyableFiles []assets.CopyableFile
for _, addonBundle := range assets.Addons {
if isEnabled, err := addonBundle.IsEnabled(); err == nil && isEnabled {
for _, addon := range addonBundle.Assets {
copyableFiles = append(copyableFiles, addon)
}
} else if err != nil {
return err
}
}
copyableFiles = append(copyableFiles, fileAssets...)
// transfer files to vm
for _, copyableFile := range copyableFiles {
if err := sshutil.TransferFile(copyableFile, client); err != nil {
return err
}
}
return nil
}
func localkubeURIWasSpecified(config KubernetesConfig) bool {
// see if flag is different than default -> it was passed by user
return config.KubernetesVersion != constants.DefaultKubernetesVersion
}
// SetupCerts gets the generated credentials required to talk to the APIServer.
func SetupCerts(d drivers.Driver) error {
localPath := constants.Minipath
ipStr, err := d.GetIP()
if err != nil {
return errors.Wrap(err, "Error getting ip from driver")
}
glog.Infoln("Setting up certificates for IP: %s", ipStr)
ip := net.ParseIP(ipStr)
caCert := filepath.Join(localPath, "ca.crt")
caKey := filepath.Join(localPath, "ca.key")
publicPath := filepath.Join(localPath, "apiserver.crt")
privatePath := filepath.Join(localPath, "apiserver.key")
if err := GenerateCerts(caCert, caKey, publicPath, privatePath, ip); err != nil {
return errors.Wrap(err, "Error generating certs")
}
client, err := sshutil.NewSSHClient(d)
if err != nil {
return errors.Wrap(err, "Error creating new ssh client")
}
for _, cert := range certs {
p := filepath.Join(localPath, cert)
data, err := ioutil.ReadFile(p)
if err != nil {
return errors.Wrapf(err, "Error reading file: %s", p)
}
perms := "0644"
if strings.HasSuffix(cert, ".key") {
perms = "0600"
}
if err := sshutil.Transfer(bytes.NewReader(data), len(data), util.DefaultCertPath, cert, perms, client); err != nil {
return errors.Wrapf(err, "Error transferring data: %s", string(data))
}
}
return nil
}
func engineOptions(config MachineConfig) *engine.Options {
o := engine.Options{
Env: config.DockerEnv,
InsecureRegistry: config.InsecureRegistry,
RegistryMirror: config.RegistryMirror,
}
return &o
}
func createVirtualboxHost(config MachineConfig) drivers.Driver {
d := virtualbox.NewDriver(constants.MachineName, constants.Minipath)
d.Boot2DockerURL = config.GetISOFileURI()
d.Memory = config.Memory
d.CPU = config.CPUs
d.DiskSize = int(config.DiskSize)
d.HostOnlyCIDR = config.HostOnlyCIDR
return d
}
func (m *MachineConfig) CacheMinikubeISOFromURL() error {
options := download.FileOptions{
Mkdirs: download.MkdirAll,
Options: download.Options{
ProgressBars: &download.ProgressBarOptions{
MaxWidth: 80,
},
},
}
// Validate the ISO if it was the default URL, before writing it to disk.
if m.MinikubeISO == constants.DefaultIsoUrl {
options.Checksum = constants.DefaultIsoShaUrl
options.ChecksumHash = crypto.SHA256
}
fmt.Println("Downloading Minikube ISO")
if err := download.ToFile(m.MinikubeISO, m.GetISOCacheFilepath(), options); err != nil {
return errors.Wrap(err, "Error downloading Minikube ISO")
}
return nil
}
func (m *MachineConfig) ShouldCacheMinikubeISO() bool {
// store the miniube-iso inside the .minikube dir
urlObj, err := url.Parse(m.MinikubeISO)
if err != nil {
return false
}
if urlObj.Scheme == fileScheme {
return false
}
if m.IsMinikubeISOCached() {
return false
}
return true
}
func (m *MachineConfig) GetISOCacheFilepath() string {
return filepath.Join(constants.Minipath, "cache", "iso", filepath.Base(m.MinikubeISO))
}
func (m *MachineConfig) GetISOFileURI() string {
urlObj, err := url.Parse(m.MinikubeISO)
if err != nil {
return m.MinikubeISO
}
if urlObj.Scheme == fileScheme {
return m.MinikubeISO
}
isoPath := filepath.Join(constants.Minipath, "cache", "iso", filepath.Base(m.MinikubeISO))
// As this is a file URL there should be no backslashes regardless of platform running on.
return "file://" + filepath.ToSlash(isoPath)
}
func (m *MachineConfig) IsMinikubeISOCached() bool {
if _, err := os.Stat(m.GetISOCacheFilepath()); os.IsNotExist(err) {
return false
}
return true
}
func createHost(api libmachine.API, config MachineConfig) (*host.Host, error) {
var driver interface{}
if config.ShouldCacheMinikubeISO() {
if err := config.CacheMinikubeISOFromURL(); err != nil {
return nil, errors.Wrap(err, "Error attempting to cache minikube iso from url")
}
}
switch config.VMDriver {
case "virtualbox":
driver = createVirtualboxHost(config)
case "vmwarefusion":
driver = createVMwareFusionHost(config)
case "kvm":
driver = createKVMHost(config)
case "xhyve":
driver = createXhyveHost(config)
case "hyperv":
driver = createHypervHost(config)
default:
glog.Exitf("Unsupported driver: %s\n", config.VMDriver)
}
data, err := json.Marshal(driver)
if err != nil {
return nil, errors.Wrap(err, "Error marshalling json")
}
h, err := api.NewHost(config.VMDriver, data)
if err != nil {
return nil, errors.Wrap(err, "Error creating new host")
}
h.HostOptions.AuthOptions.CertDir = constants.Minipath
h.HostOptions.AuthOptions.StorePath = constants.Minipath
h.HostOptions.EngineOptions = engineOptions(config)
if err := api.Create(h); err != nil {
// Wait for all the logs to reach the client
time.Sleep(2 * time.Second)
return nil, errors.Wrap(err, "Error creating host")
}
if err := api.Save(h); err != nil {
return nil, errors.Wrap(err, "Error attempting to save")
}
return h, nil
}
// GetHostDockerEnv gets the necessary docker env variables to allow the use of docker through minikube's vm
func GetHostDockerEnv(api libmachine.API) (map[string]string, error) {
host, err := CheckIfApiExistsAndLoad(api)
if err != nil {
return nil, errors.Wrap(err, "Error checking that api exists and loading it")
}
ip, err := host.Driver.GetIP()
if err != nil {
return nil, errors.Wrap(err, "Error getting ip from host")
}
tcpPrefix := "tcp://"
port := "2376"
envMap := map[string]string{
"DOCKER_TLS_VERIFY": "1",
"DOCKER_HOST": tcpPrefix + net.JoinHostPort(ip, port),
"DOCKER_CERT_PATH": constants.MakeMiniPath("certs"),
}
return envMap, nil
}
// GetHostLogs gets the localkube logs of the host VM.
func GetHostLogs(api libmachine.API) (string, error) {
host, err := CheckIfApiExistsAndLoad(api)
if err != nil {
return "", errors.Wrap(err, "Error checking that api exists and loading it")
}
s, err := host.RunSSHCommand(logsCommand)
if err != nil {
return "", err
}
return s, nil
}
func CheckIfApiExistsAndLoad(api libmachine.API) (*host.Host, error) {
exists, err := api.Exists(constants.MachineName)
if err != nil {
return nil, errors.Wrapf(err, "Error checking that api exists for: ", constants.MachineName)
}
if !exists {
return nil, errors.Errorf("Machine does not exist for api.Exists(%s)", constants.MachineName)
}
host, err := api.Load(constants.MachineName)
if err != nil {
return nil, errors.Wrapf(err, "Error loading api for: ", constants.MachineName)
}
return host, nil
}
func CreateSSHShell(api libmachine.API, args []string) error {
host, err := CheckIfApiExistsAndLoad(api)
if err != nil {
return errors.Wrap(err, "Error checking if api exist and loading it")
}
currentState, err := host.Driver.GetState()
if err != nil {
return errors.Wrap(err, "Error getting state of host")
}
if currentState != state.Running {
return errors.Errorf("Error: Cannot run ssh command: Host %q is not running", constants.MachineName)
}
client, err := host.CreateSSHClient()
if err != nil {
return errors.Wrap(err, "Error creating ssh client")
}
return client.Shell(strings.Join(args, " "))
}
type ipPort struct {
IP string
Port int32
}
func GetServiceURLsForService(api libmachine.API, namespace, service string, t *template.Template) ([]string, error) {
host, err := CheckIfApiExistsAndLoad(api)
if err != nil {
return nil, errors.Wrap(err, "Error checking if api exist and loading it")
}
ip, err := host.Driver.GetIP()
if err != nil {
return nil, errors.Wrap(err, "Error getting ip from host")
}
client, err := GetKubernetesClient()
if err != nil {
return nil, err
}
return getServiceURLsWithClient(client, ip, namespace, service, t)
}
func getServiceURLsWithClient(client *unversioned.Client, ip, namespace, service string, t *template.Template) ([]string, error) {
if t == nil {
return nil, errors.New("Error, attempted to generate service url with nil --format template")
}
ports, err := getServicePorts(client, namespace, service)
if err != nil {
return nil, err
}
urls := []string{}
for _, port := range ports {
var doc bytes.Buffer
err = t.Execute(&doc, ipPort{ip, port})
if err != nil {
return nil, err
}
u, err := url.Parse(doc.String())
if err != nil {
return nil, err
}
urls = append(urls, u.String())
}
return urls, nil
}
type serviceGetter interface {
Get(name string) (*kubeapi.Service, error)
List(kubeapi.ListOptions) (*kubeapi.ServiceList, error)
}
func getServicePorts(client *unversioned.Client, namespace, service string) ([]int32, error) {
services := client.Services(namespace)
return getServicePortsFromServiceGetter(services, service)
}
type MissingNodePortError struct {
service *kubeapi.Service
}
func (e MissingNodePortError) Error() string {
return fmt.Sprintf("Service %s/%s does not have a node port. To have one assigned automatically, the service type must be NodePort or LoadBalancer, but this service is of type %s.", e.service.Namespace, e.service.Name, e.service.Spec.Type)
}
func getServiceFromServiceGetter(services serviceGetter, service string) (*kubeapi.Service, error) {
svc, err := services.Get(service)
if err != nil {
return nil, fmt.Errorf("Error getting %s service: %s", service, err)
}
return svc, nil
}
func getServicePortsFromServiceGetter(services serviceGetter, service string) ([]int32, error) {
svc, err := getServiceFromServiceGetter(services, service)
if err != nil {
return nil, err
}
var nodePorts []int32
if len(svc.Spec.Ports) > 0 {
for _, port := range svc.Spec.Ports {
if port.NodePort > 0 {
nodePorts = append(nodePorts, port.NodePort)
}
}
}
if len(nodePorts) == 0 {
return nil, MissingNodePortError{svc}
}
return nodePorts, nil
}
func GetKubernetesClient() (*unversioned.Client, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
config, err := kubeConfig.ClientConfig()
if err != nil {
return nil, fmt.Errorf("Error creating kubeConfig: %s", err)
}
client, err := unversioned.New(config)
if err != nil {
return nil, errors.Wrap(err, "Error creating new client from kubeConfig.ClientConfig()")
}
return client, nil
}
// EnsureMinikubeRunningOrExit checks that minikube has a status available and that
// that the status is `Running`, otherwise it will exit
func EnsureMinikubeRunningOrExit(api libmachine.API, exitStatus int) {
s, err := GetHostStatus(api)
if err != nil {
glog.Errorln("Error getting machine status:", err)
os.Exit(1)
}
if s != state.Running.String() {
fmt.Fprintln(os.Stdout, "minikube is not currently running so the service cannot be accessed")
os.Exit(exitStatus)
}
}
type ServiceURL struct {
Namespace string
Name string
URLs []string
}
type ServiceURLs []ServiceURL
func GetServiceURLs(api libmachine.API, namespace string, t *template.Template) (ServiceURLs, error) {
host, err := CheckIfApiExistsAndLoad(api)
if err != nil {
return nil, err
}
ip, err := host.Driver.GetIP()
if err != nil {
return nil, err
}
client, err := GetKubernetesClient()
if err != nil {
return nil, err
}
getter := client.Services(namespace)
svcs, err := getter.List(kubeapi.ListOptions{})
if err != nil {
return nil, err
}
var serviceURLs []ServiceURL
for _, svc := range svcs.Items {
urls, err := getServiceURLsWithClient(client, ip, svc.Namespace, svc.Name, t)
if err != nil {
if _, ok := err.(MissingNodePortError); ok {
serviceURLs = append(serviceURLs, ServiceURL{Namespace: svc.Namespace, Name: svc.Name})
continue
}
return nil, err
}
serviceURLs = append(serviceURLs, ServiceURL{Namespace: svc.Namespace, Name: svc.Name, URLs: urls})
}
return serviceURLs, nil
}
// CheckService waits for the specified service to be ready by returning an error until the service is up
// The check is done by polling the endpoint associated with the service and when the endpoint exists, returning no error->service-online
func CheckService(namespace string, service string) error {
client, err := GetKubernetesClient()
if err != nil {
return &util.RetriableError{Err: err}
}
endpoints := client.Endpoints(namespace)
if err != nil {
return &util.RetriableError{Err: err}
}
endpoint, err := endpoints.Get(service)
if err != nil {
return &util.RetriableError{Err: err}
}
return checkEndpointReady(endpoint)
}
func checkEndpointReady(endpoint *kubeapi.Endpoints) error {
const notReadyMsg = "Waiting, endpoint for service is not ready yet...\n"
if len(endpoint.Subsets) == 0 {
fmt.Fprintf(os.Stderr, notReadyMsg)
return &util.RetriableError{Err: errors.New("Endpoint for service is not ready yet")}
}
for _, subset := range endpoint.Subsets {
if len(subset.Addresses) == 0 {
fmt.Fprintf(os.Stderr, notReadyMsg)
return &util.RetriableError{Err: errors.New("No endpoints for service are ready yet")}
}
}
return nil
}
func WaitAndMaybeOpenService(api libmachine.API, namespace string, service string, urlTemplate *template.Template, urlMode bool, https bool) {
if err := util.RetryAfter(20, func() error { return CheckService(namespace, service) }, 6*time.Second); err != nil {
fmt.Fprintf(os.Stderr, "Could not find finalized endpoint being pointed to by %s: %s\n", service, err)
os.Exit(1)
}
urls, err := GetServiceURLsForService(api, namespace, service, urlTemplate)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, "Check that minikube is running and that you have specified the correct namespace (-n flag).")
os.Exit(1)
}
for _, url := range urls {
if https {
url = strings.Replace(url, "http", "https", 1)
}
if urlMode || !strings.HasPrefix(url, "http") {
fmt.Fprintln(os.Stdout, url)
} else {
fmt.Fprintln(os.Stdout, "Opening kubernetes service "+namespace+"/"+service+" in default browser...")
browser.OpenURL(url)
}
}
}
func GetServiceListByLabel(namespace string, key string, value string) (*kubeapi.ServiceList, error) {
client, err := GetKubernetesClient()
if err != nil {
return &kubeapi.ServiceList{}, &util.RetriableError{Err: err}
}
services := client.Services(namespace)
if err != nil {
return &kubeapi.ServiceList{}, &util.RetriableError{Err: err}
}
return getServiceListFromServicesByLabel(services, key, value)
}
func getServiceListFromServicesByLabel(services unversioned.ServiceInterface, key string, value string) (*kubeapi.ServiceList, error) {
selector := labels.SelectorFromSet(labels.Set(map[string]string{key: value}))
serviceList, err := services.List(kubeapi.ListOptions{LabelSelector: selector})
if err != nil {
return &kubeapi.ServiceList{}, &util.RetriableError{Err: err}
}
if len(serviceList.Items) == 0 {
return &kubeapi.ServiceList{}, &util.RetriableError{Err: err}
}
return serviceList, nil
}