generated from cloudoperators/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy.go
255 lines (223 loc) · 7.57 KB
/
proxy.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
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"sync"
"github.com/go-logr/logr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
greenhouseapis "github.com/cloudoperators/greenhouse/pkg/apis"
greenhousev1alpha1 "github.com/cloudoperators/greenhouse/pkg/apis/greenhouse/v1alpha1"
"github.com/cloudoperators/greenhouse/pkg/clientutil"
)
func NewProxyManager() *ProxyManager {
return &ProxyManager{
clusters: make(map[string]clusterRoutes),
}
}
type ProxyManager struct {
client client.Client
logger logr.Logger
clusters map[string]clusterRoutes
mu sync.RWMutex
}
type clusterRoutes struct {
transport http.RoundTripper
routes map[string]*url.URL
}
// contextClusterKey is used to embed a cluster in the context
type contextClusterKey struct {
}
var apiServerProxyPathRegex = regexp.MustCompile(`/api/v1/namespaces/[^/]+/services/[^/]+/proxy/`)
func (pm *ProxyManager) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx)
var secret = new(v1.Secret)
err := pm.client.Get(ctx, req.NamespacedName, secret)
if client.IgnoreNotFound(err) != nil {
return ctrl.Result{}, err
}
if err != nil || secret.DeletionTimestamp != nil {
//delete cache
logger.Info("Removing deleted cluster from cache")
pm.mu.Lock()
defer pm.mu.Unlock()
delete(pm.clusters, req.Name)
return ctrl.Result{}, nil
}
restClientGetter, err := clientutil.NewRestClientGetterFromSecret(secret, "")
if err != nil {
return ctrl.Result{}, err
}
restConfig, err := restClientGetter.ToRESTConfig()
if err != nil {
return ctrl.Result{}, err
}
pm.mu.Lock()
defer pm.mu.Unlock()
if _, ok := pm.clusters[req.Name]; !ok {
logger.Info("Adding cluster")
} else {
logger.Info("Updating cluster")
}
cls := clusterRoutes{}
if cls.transport, err = rest.TransportFor(restConfig); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to create transport for cluster %s: %w", req.Name, err)
}
cls.routes = make(map[string]*url.URL)
k8sAPIURL, err := url.Parse(restConfig.Host)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to parse api url: %w", err)
}
configs, err := pm.pluginsForCluster(ctx, req.Name, req.Namespace)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get plugins for cluster %s: %w", req.Name, err)
}
for _, cfg := range configs {
for url, svc := range cfg.Status.ExposedServices {
u := *k8sAPIURL //copy URL struct
proto := "http"
if svc.Protocol != nil {
proto = *svc.Protocol
}
u.Path = fmt.Sprintf("/api/v1/namespaces/%s/services/%s:%s:%d/proxy", svc.Namespace, proto, svc.Name, svc.Port)
cls.routes[url] = &u
}
}
pm.clusters[req.Name] = cls
return ctrl.Result{}, nil
}
func (pm *ProxyManager) SetupWithManager(name string, mgr ctrl.Manager) error {
pm.client = mgr.GetClient()
pm.logger = mgr.GetLogger()
return ctrl.NewControllerManagedBy(mgr).
Named(name).
For(&v1.Secret{}, builder.WithPredicates(
clientutil.PredicateFilterBySecretType(greenhouseapis.SecretTypeKubeConfig),
)).
// Watch plugins to be notified about exposed services
Watches(&greenhousev1alpha1.Plugin{}, handler.EnqueueRequestsFromMapFunc(enqueuePluginForCluster)).
Complete(pm)
}
// ReverseProxy returns a reverse proxy that will forward requests to the cluster
func (pm *ProxyManager) ReverseProxy() *httputil.ReverseProxy {
return &httputil.ReverseProxy{
Rewrite: pm.rewrite,
ModifyResponse: pm.modifyResponse,
Transport: pm,
FlushInterval: -1,
ErrorHandler: pm.errorHandler,
}
}
func (pm *ProxyManager) RoundTrip(req *http.Request) (resp *http.Response, err error) {
pm.mu.RLock()
defer pm.mu.RUnlock()
cluster, ok := req.Context().Value(contextClusterKey{}).(string)
if !ok {
return nil, fmt.Errorf("no upstream found for: %s", req.URL.String())
}
cls, ok := pm.clusters[cluster]
if !ok {
return nil, fmt.Errorf("cluster %s not found", cluster)
}
resp, err = cls.transport.RoundTrip(req)
log.FromContext(req.Context()).Info("Forwarded request", "status", resp.StatusCode, "upstream", req.URL.String())
return
}
func (pm *ProxyManager) rewrite(req *httputil.ProxyRequest) {
req.SetXForwarded()
l := pm.logger.WithValues("host", req.In.Host, "url", req.In.URL.String(), "method", req.In.Method)
// inject current logger into context before returning
defer func() {
req.Out = req.Out.WithContext(log.IntoContext(req.Out.Context(), l))
}()
// hostname is expected to have the format $name--$namespace--$cluster.$organisation.$basedomain
name, namespace, cluster, err := SplitHost(req.In.Host)
if err != nil {
return
}
l = l.WithValues("cluster", cluster, "namespace", namespace, "name", name)
pm.mu.RLock()
defer pm.mu.RUnlock()
cls, found := pm.clusters[cluster]
if !found {
return
}
backendURL, found := cls.routes["https://"+req.In.Host]
if !found {
return
}
//set cluster in context
req.Out = req.Out.WithContext(context.WithValue(req.Out.Context(), contextClusterKey{}, cluster))
req.SetURL(backendURL)
}
// modifyResponse strips the k8s API server proxy path prepended to the location header during redirects:
// https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/util/proxy/transport.go#L113
func (pm *ProxyManager) modifyResponse(resp *http.Response) error {
if location := resp.Header.Get("Location"); location != "" {
location = apiServerProxyPathRegex.ReplaceAllString(location, "/")
resp.Header.Set("Location", location)
log.FromContext(resp.Request.Context()).Info("Rewrote location header", "location", location)
}
return nil
}
func (pm *ProxyManager) errorHandler(rw http.ResponseWriter, req *http.Request, err error) {
logger := pm.logger
if l, err := logr.FromContext(req.Context()); err == nil {
logger = l
}
logger.Info("Proxy failure", "err", err)
rw.WriteHeader(http.StatusBadGateway)
}
func (pm *ProxyManager) pluginsForCluster(ctx context.Context, cluster, namespace string) ([]greenhousev1alpha1.Plugin, error) {
plugins := new(greenhousev1alpha1.PluginList)
if err := pm.client.List(ctx, plugins, &client.ListOptions{Namespace: namespace}); err != nil {
return nil, fmt.Errorf("failed to list plugins: %w", err)
}
configs := make([]greenhousev1alpha1.Plugin, 0)
for _, cfg := range plugins.Items {
//ignore deleted configs
if cfg.DeletionTimestamp != nil {
continue
}
if cfg.Spec.ClusterName == cluster {
configs = append(configs, cfg)
}
}
return configs, nil
}
func enqueuePluginForCluster(_ context.Context, o client.Object) []ctrl.Request {
plugin, ok := o.(*greenhousev1alpha1.Plugin)
if !ok {
return nil
}
//ignore plugins not tied to a cluster
if plugin.Spec.ClusterName == "" {
return nil
}
return []ctrl.Request{{NamespacedName: types.NamespacedName{Namespace: plugin.Namespace, Name: plugin.Spec.ClusterName}}}
}
// SplitHost splits a host into its name, namespace and cluster parts
func SplitHost(host string) (name, namespace, cluster string, err error) {
parts := strings.SplitN(host, ".", 2)
if len(parts) < 2 {
return "", "", "", fmt.Errorf("invalid host: %s", host)
}
parts = strings.SplitN(parts[0], "--", 3)
if len(parts) < 3 {
return "", "", "", fmt.Errorf("invalid host: %s", host)
}
return parts[0], parts[1], parts[2], nil
}