-
Notifications
You must be signed in to change notification settings - Fork 77
/
aggregator.go
292 lines (250 loc) · 9.25 KB
/
aggregator.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
/*
Copyright 2021 The Kubernetes Authors.
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 aggregator
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"k8s.io/apiserver/pkg/endpoints/metrics"
"k8s.io/apiserver/pkg/server"
"k8s.io/apiserver/pkg/server/mux"
"k8s.io/klog/v2"
v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
"k8s.io/kube-openapi/pkg/common"
"k8s.io/kube-openapi/pkg/handler3"
"k8s.io/kube-openapi/pkg/openapiconv"
v2aggregator "k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator"
)
// SpecProxier proxies OpenAPI V3 requests to their respective APIService
type SpecProxier interface {
AddUpdateAPIService(handler http.Handler, apiService *v1.APIService)
UpdateAPIServiceSpec(apiServiceName string) error
RemoveAPIServiceSpec(apiServiceName string)
GetAPIServiceNames() []string
}
const (
aggregatorUser = "system:aggregator"
specDownloadTimeout = 60 * time.Second
localDelegateChainNamePrefix = "k8s_internal_local_delegation_chain_"
localDelegateChainNamePattern = localDelegateChainNamePrefix + "%010d"
openAPIV2Converter = "openapiv2converter"
)
// IsLocalAPIService returns true for local specs from delegates.
func IsLocalAPIService(apiServiceName string) bool {
return strings.HasPrefix(apiServiceName, localDelegateChainNamePrefix)
}
// GetAPIServiceNames returns the names of APIServices recorded in apiServiceInfo.
// We use this function to pass the names of local APIServices to the controller in this package,
// so that the controller can periodically sync the OpenAPI spec from delegation API servers.
func (s *specProxier) GetAPIServiceNames() []string {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
names := make([]string, 0, len(s.apiServiceInfo))
for key := range s.apiServiceInfo {
names = append(names, key)
}
return names
}
// BuildAndRegisterAggregator registered OpenAPI aggregator handler. This function is not thread safe as it only being called on startup.
func BuildAndRegisterAggregator(downloader Downloader, delegationTarget server.DelegationTarget, pathHandler common.PathHandlerByGroupVersion) (SpecProxier, error) {
s := &specProxier{
apiServiceInfo: map[string]*openAPIV3APIServiceInfo{},
downloader: downloader,
}
i := 1
for delegate := delegationTarget; delegate != nil; delegate = delegate.NextDelegate() {
handler := delegate.UnprotectedHandler()
if handler == nil {
continue
}
apiServiceName := fmt.Sprintf(localDelegateChainNamePattern, i)
localAPIService := v1.APIService{}
localAPIService.Name = apiServiceName
s.AddUpdateAPIService(handler, &localAPIService)
s.UpdateAPIServiceSpec(apiServiceName)
i++
}
handler := handler3.NewOpenAPIService()
s.openAPIV2ConverterHandler = handler
openAPIV2ConverterMux := mux.NewPathRecorderMux(openAPIV2Converter)
s.openAPIV2ConverterHandler.RegisterOpenAPIV3VersionedService("/openapi/v3", openAPIV2ConverterMux)
openAPIV2ConverterAPIService := v1.APIService{}
openAPIV2ConverterAPIService.Name = openAPIV2Converter
s.AddUpdateAPIService(openAPIV2ConverterMux, &openAPIV2ConverterAPIService)
s.register(pathHandler)
return s, nil
}
// AddUpdateAPIService adds or updates the api service. It is thread safe.
func (s *specProxier) AddUpdateAPIService(handler http.Handler, apiservice *v1.APIService) {
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
// If the APIService is being updated, use the existing struct.
if apiServiceInfo, ok := s.apiServiceInfo[apiservice.Name]; ok {
apiServiceInfo.apiService = *apiservice
apiServiceInfo.handler = handler
}
s.apiServiceInfo[apiservice.Name] = &openAPIV3APIServiceInfo{
apiService: *apiservice,
handler: handler,
}
}
func getGroupVersionStringFromAPIService(apiService v1.APIService) string {
if apiService.Spec.Group == "" && apiService.Spec.Version == "" {
return ""
}
return "apis/" + apiService.Spec.Group + "/" + apiService.Spec.Version
}
// UpdateAPIServiceSpec updates all the OpenAPI v3 specs that the APIService serves.
// It is thread safe.
func (s *specProxier) UpdateAPIServiceSpec(apiServiceName string) error {
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
return s.updateAPIServiceSpecLocked(apiServiceName)
}
func (s *specProxier) updateAPIServiceSpecLocked(apiServiceName string) error {
apiService, exists := s.apiServiceInfo[apiServiceName]
if !exists {
return fmt.Errorf("APIService %s does not exist for update", apiServiceName)
}
if !apiService.isLegacyAPIService {
gv, httpStatus, err := s.downloader.OpenAPIV3Root(apiService.handler)
if err != nil {
return err
}
if httpStatus == http.StatusNotFound {
apiService.isLegacyAPIService = true
} else {
s.apiServiceInfo[apiServiceName].discovery = gv
return nil
}
}
newDownloader := v2aggregator.Downloader{}
v2Spec, etag, httpStatus, err := newDownloader.Download(apiService.handler, apiService.etag)
if err != nil {
return err
}
apiService.etag = etag
if httpStatus == http.StatusOK {
v3Spec := openapiconv.ConvertV2ToV3(v2Spec)
s.openAPIV2ConverterHandler.UpdateGroupVersion(getGroupVersionStringFromAPIService(apiService.apiService), v3Spec)
s.updateAPIServiceSpecLocked(openAPIV2Converter)
}
return nil
}
type specProxier struct {
// mutex protects all members of this struct.
rwMutex sync.RWMutex
// OpenAPI V3 specs by APIService name
apiServiceInfo map[string]*openAPIV3APIServiceInfo
// For downloading the OpenAPI v3 specs from apiservices
downloader Downloader
openAPIV2ConverterHandler *handler3.OpenAPIService
}
var _ SpecProxier = &specProxier{}
type openAPIV3APIServiceInfo struct {
apiService v1.APIService
handler http.Handler
discovery *handler3.OpenAPIV3Discovery
// These fields are only used if the /openapi/v3 endpoint is not served by an APIService
// Legacy APIService indicates that an APIService does not support OpenAPI V3, and the OpenAPI V2
// will be downloaded, converted to V3 (lossy), and served by the aggregator
etag string
isLegacyAPIService bool
}
// RemoveAPIServiceSpec removes an api service from the OpenAPI map. If it does not exist, no error is returned.
// It is thread safe.
func (s *specProxier) RemoveAPIServiceSpec(apiServiceName string) {
s.rwMutex.Lock()
defer s.rwMutex.Unlock()
if apiServiceInfo, ok := s.apiServiceInfo[apiServiceName]; ok {
s.openAPIV2ConverterHandler.DeleteGroupVersion(getGroupVersionStringFromAPIService(apiServiceInfo.apiService))
delete(s.apiServiceInfo, apiServiceName)
}
}
func (s *specProxier) getOpenAPIV3Root() handler3.OpenAPIV3Discovery {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
merged := handler3.OpenAPIV3Discovery{
Paths: make(map[string]handler3.OpenAPIV3DiscoveryGroupVersion),
}
for _, apiServiceInfo := range s.apiServiceInfo {
if apiServiceInfo.discovery == nil {
continue
}
for key, item := range apiServiceInfo.discovery.Paths {
merged.Paths[key] = item
}
}
return merged
}
// handleDiscovery is the handler for OpenAPI V3 Discovery
func (s *specProxier) handleDiscovery(w http.ResponseWriter, r *http.Request) {
merged := s.getOpenAPIV3Root()
j, err := json.Marshal(&merged)
if err != nil {
w.WriteHeader(500)
klog.Errorf("failed to created merged OpenAPIv3 discovery response: %s", err.Error())
return
}
http.ServeContent(w, r, "/openapi/v3", time.Now(), bytes.NewReader(j))
}
// handleGroupVersion is the OpenAPI V3 handler for a specified group/version
func (s *specProxier) handleGroupVersion(w http.ResponseWriter, r *http.Request) {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
// TODO: Import this logic from kube-openapi instead of duplicating
// URLs for OpenAPI V3 have the format /openapi/v3/<groupversionpath>
// SplitAfterN with 4 yields ["", "openapi", "v3", <groupversionpath>]
url := strings.SplitAfterN(r.URL.Path, "/", 4)
targetGV := url[3]
for _, apiServiceInfo := range s.apiServiceInfo {
if apiServiceInfo.discovery == nil {
continue
}
for key := range apiServiceInfo.discovery.Paths {
if targetGV == key {
apiServiceInfo.handler.ServeHTTP(w, r)
return
}
}
}
// No group-versions match the desired request
w.WriteHeader(404)
}
// Register registers the OpenAPI V3 Discovery and GroupVersion handlers
func (s *specProxier) register(handler common.PathHandlerByGroupVersion) {
handler.Handle("/openapi/v3", metrics.InstrumentHandlerFunc("GET",
/* group = */ "",
/* version = */ "",
/* resource = */ "",
/* subresource = */ "openapi/v3",
/* scope = */ "",
/* component = */ "",
/* deprecated */ false,
/* removedRelease */ "",
http.HandlerFunc(s.handleDiscovery)))
handler.HandlePrefix("/openapi/v3/", metrics.InstrumentHandlerFunc("GET",
/* group = */ "",
/* version = */ "",
/* resource = */ "",
/* subresource = */ "openapi/v3/",
/* scope = */ "",
/* component = */ "",
/* deprecated */ false,
/* removedRelease */ "",
http.HandlerFunc(s.handleGroupVersion)))
}