forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxier.go
116 lines (96 loc) · 2.38 KB
/
proxier.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
// Copyright 2021 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package proxy
import (
"net"
"net/url"
"github.com/juju/errors"
"k8s.io/client-go/rest"
"github.com/DavinZhang/juju/caas/kubernetes"
proxyerrors "github.com/DavinZhang/juju/proxy/errors"
)
type Proxier struct {
config ProxierConfig
tunnel *kubernetes.Tunnel
restConfig rest.Config
}
type ProxierConfig struct {
APIHost string `yaml:"api-host"`
CAData string `yaml:"ca-cert"`
Namespace string `yaml:"namespace"`
RemotePort string `yaml:"remote-port"`
Service string `yaml:"service"`
ServiceAccountToken string `yaml:"service-account-token"`
}
const (
ProxierTypeKey = "kubernetes-port-forward"
)
func (p *Proxier) Host() string {
return "localhost"
}
func NewProxier(config ProxierConfig) *Proxier {
return &Proxier{
config: config,
restConfig: rest.Config{
BearerToken: config.ServiceAccountToken,
Host: config.APIHost,
TLSClientConfig: rest.TLSClientConfig{
CAData: []byte(config.CAData),
},
},
}
}
func NewProxierConfig() *ProxierConfig {
return &ProxierConfig{}
}
func NewProxierFromRawConfig(rawConf interface{}) (*Proxier, error) {
conf, valid := rawConf.(*ProxierConfig)
if !valid {
return nil, errors.NewNotValid(nil, "config is not of type *ProxierConfig")
}
return NewProxier(*conf), nil
}
// SetAPIHost updates the proxy info to use a different host address.
func (p *Proxier) SetAPIHost(host string) {
p.restConfig.Host = host
p.config.APIHost = host
}
func (p *Proxier) MarshalYAML() (interface{}, error) {
return &p.config, nil
}
func (p *Proxier) Port() string {
return p.tunnel.LocalPort
}
func (p *Proxier) Start() (err error) {
tunnel, err := kubernetes.NewTunnelForConfig(
&p.restConfig,
kubernetes.TunnelKindServices,
p.config.Namespace,
p.config.Service,
p.config.RemotePort,
)
if err != nil {
return errors.Trace(err)
}
p.tunnel = tunnel
defer func() {
err = errors.Annotate(err, "connecting k8s proxy")
}()
err = p.tunnel.ForwardPort()
urlErr, ok := errors.Cause(err).(*url.Error)
if !ok {
return err
}
if _, ok = urlErr.Err.(*net.OpError); !ok {
return err
}
return proxyerrors.NewProxyConnectError(err, p.Type())
}
func (p *Proxier) Stop() {
if p.tunnel != nil {
p.tunnel.Close()
}
}
func (p *Proxier) Type() string {
return ProxierTypeKey
}