-
Notifications
You must be signed in to change notification settings - Fork 17
/
entry.go
216 lines (189 loc) · 5.71 KB
/
entry.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
package agent
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
_ "net/http/pprof"
"net/url"
"strings"
"time"
"github.com/cockroachdb/cmux"
"github.com/juju/errors"
grpcproxy "github.com/mwitkow/grpc-proxy/proxy"
promapi "github.com/prometheus/client_golang/api"
promapiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/rancher/prometheus-auth/pkg/data"
"github.com/rancher/prometheus-auth/pkg/kube"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"golang.org/x/net/netutil"
"google.golang.org/grpc"
authentication "k8s.io/api/authentication/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func Run(cliContext *cli.Context) {
// enable profiler
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := &agentConfig{
ctx: ctx,
listenAddress: cliContext.String("listen-address"),
readTimeout: cliContext.Duration("read-timeout"),
maxConnections: cliContext.Int("max-connections"),
filterReaderLabelSet: data.NewSet(cliContext.StringSlice("filter-reader-labels")...),
}
proxyURLString := cliContext.String("proxy-url")
if len(proxyURLString) == 0 {
log.Fatal("--agent.proxy-url is blank")
}
proxyURL, err := url.Parse(proxyURLString)
if err != nil {
log.Fatal("Unable to parse agent.proxy-url")
}
cfg.proxyURL = proxyURL
accessTokenPath := "/var/run/secrets/kubernetes.io/serviceaccount/token"
accessTokenBytes, err := ioutil.ReadFile(accessTokenPath)
if err != nil {
log.WithError(err).Fatalf("Failed to read token file %q", accessTokenPath)
}
accessToken := strings.TrimSpace(string(accessTokenBytes))
if len(accessToken) == 0 {
log.Fatalf("Read empty token from file %q", accessTokenPath)
}
cfg.myToken = accessToken
log.Println(cfg)
reader, err := createAgent(cfg)
if err != nil {
log.WithError(err).Fatal("Failed to create agent")
}
if err = reader.serve(); err != nil {
log.WithError(err).Fatal("Failed to serve")
}
}
type agentConfig struct {
ctx context.Context
myToken string
listenAddress string
proxyURL *url.URL
readTimeout time.Duration
maxConnections int
filterReaderLabelSet data.Set
}
func (a *agentConfig) String() string {
sb := &strings.Builder{}
sb.WriteString(fmt.Sprint("listening on ", a.listenAddress))
sb.WriteString(fmt.Sprint(", proxying to ", a.proxyURL.String()))
sb.WriteString(fmt.Sprintf(" with ignoring 'remote reader' labels [%s]", a.filterReaderLabelSet))
sb.WriteString(fmt.Sprintf(", only allow maximum %d connections with %v read timeout", a.maxConnections, a.readTimeout))
sb.WriteString(" .")
return sb.String()
}
type agent struct {
cfg *agentConfig
userInfo authentication.UserInfo
listener net.Listener
namespaces kube.Namespaces
tokens kube.Tokens
remoteAPI promapiv1.API
}
func (a *agent) serve() error {
listenerMux := cmux.New(a.listener)
httpProxy := a.createHTTPProxy()
grpcProxy := a.createGRPCProxy()
errCh := make(chan error)
go func() {
if err := httpProxy.Serve(createHTTPListener(listenerMux)); err != nil {
errCh <- errors.Annotate(err, "failed to start proxy http listener")
}
}()
go func() {
if err := grpcProxy.Serve(createGRPCListener(listenerMux, a.cfg.myToken)); err != nil {
errCh <- errors.Annotate(err, "failed to start proxy grpc listener")
}
}()
go func() {
log.Infof("Start listening for connections on %s", a.cfg.listenAddress)
if err := listenerMux.Serve(); err != nil {
errCh <- errors.Annotatef(err, "failed to listen on %s", a.cfg.listenAddress)
}
}()
select {
case err := <-errCh:
return err
case <-a.cfg.ctx.Done():
grpcProxy.GracefulStop()
httpProxy.Shutdown(a.cfg.ctx)
return nil
}
}
func createAgent(cfg *agentConfig) (*agent, error) {
utilruntime.ReallyCrash = false
utilruntime.PanicHandlers = []func(interface{}){
func(i interface{}) {
if err, ok := i.(error); ok {
log.Error(errors.ErrorStack(err))
} else {
log.Error(i)
}
},
}
utilruntime.ErrorHandlers = []func(err error){
func(err error) {
log.Error(errors.ErrorStack(err))
},
}
listener, err := net.Listen("tcp", cfg.listenAddress)
if err != nil {
return nil, errors.Annotatef(err, "unable to listen on addr %s", cfg.listenAddress)
}
listener = netutil.LimitListener(listener, cfg.maxConnections)
// create Kubernetes client
k8sConfig, err := rest.InClusterConfig()
if err != nil {
return nil, errors.Annotate(err, "unable to create Kubernetes config by InClusterConfig()")
}
k8sClient, err := kubernetes.NewForConfig(k8sConfig)
if err != nil {
return nil, errors.Annotate(err, "unable to new Kubernetes clientSet")
}
// create Prometheus client
promClient, err := promapi.NewClient(promapi.Config{
Address: cfg.proxyURL.String(),
})
if err != nil {
return nil, errors.Annotate(err, "unable to new Prometheus client")
}
// create tokens client and get userInfo
tokens := kube.NewTokens(cfg.ctx, k8sClient)
userInfo, err := tokens.Authenticate(cfg.myToken)
if err != nil {
return nil, errors.Annotate(err, "unable to get userInfo from agent token")
}
return &agent{
cfg: cfg,
userInfo: userInfo,
listener: listener,
namespaces: kube.NewNamespaces(cfg.ctx, k8sClient),
tokens: tokens,
remoteAPI: promapiv1.NewAPI(promClient),
}, nil
}
func (a *agent) createHTTPProxy() *http.Server {
return &http.Server{
Handler: a.httpBackend(),
ReadTimeout: a.cfg.readTimeout,
}
}
func (a *agent) createGRPCProxy() *grpc.Server {
return grpc.NewServer(
grpc.CustomCodec(grpcproxy.Codec()),
grpc.UnknownServiceHandler(a.grpcBackend()),
)
}