service_tunnel.go 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
Copyright 2020 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 kic

import (
P
Predrag Rogic 已提交
20
	"context"
21 22
	"fmt"

23 24
	"github.com/pkg/errors"

25 26
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	typed_core "k8s.io/client-go/kubernetes/typed/core/v1"
27 28

	"k8s.io/klog/v2"
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
)

// ServiceTunnel ...
type ServiceTunnel struct {
	sshPort string
	sshKey  string
	v1Core  typed_core.CoreV1Interface
	sshConn *sshConn
}

// NewServiceTunnel ...
func NewServiceTunnel(sshPort, sshKey string, v1Core typed_core.CoreV1Interface) *ServiceTunnel {
	return &ServiceTunnel{
		sshPort: sshPort,
		sshKey:  sshKey,
		v1Core:  v1Core,
	}
}

// Start ...
func (t *ServiceTunnel) Start(svcName, namespace string) ([]string, error) {
P
Predrag Rogic 已提交
50
	svc, err := t.v1Core.Services(namespace).Get(context.Background(), svcName, metav1.GetOptions{})
51
	if err != nil {
52
		return nil, errors.Wrapf(err, "Service %s was not found in %q namespace. You may select another namespace by using 'minikube service %s -n <namespace>", svcName, namespace, svcName)
53 54
	}

55 56
	t.sshConn, err = createSSHConnWithRandomPorts(svcName, t.sshPort, t.sshKey, svc)
	if err != nil {
57
		return nil, errors.Wrap(err, "creating ssh conn")
58
	}
59 60 61 62

	go func() {
		err = t.sshConn.startAndWait()
		if err != nil {
63
			klog.Errorf("error starting ssh tunnel: %v", err)
64 65 66 67
		}
	}()

	urls := make([]string, 0, len(svc.Spec.Ports))
68 69
	for _, port := range t.sshConn.ports {
		urls = append(urls, fmt.Sprintf("http://127.0.0.1:%d", port))
70 71 72 73 74 75 76 77 78
	}

	return urls, nil
}

// Stop ...
func (t *ServiceTunnel) Stop() error {
	err := t.sshConn.stop()
	if err != nil {
79
		return errors.Wrap(err, "stopping ssh tunnel")
80 81 82 83
	}

	return nil
}