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 293 294 295
|
/*
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 handler3
import (
"bytes"
"crypto/sha512"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"sync"
"time"
openapi_v3 "github.com/google/gnostic-models/openapiv3"
"github.com/google/uuid"
"github.com/munnerz/goautoneg"
"google.golang.org/protobuf/proto"
"k8s.io/klog/v2"
"k8s.io/kube-openapi/pkg/cached"
"k8s.io/kube-openapi/pkg/common"
"k8s.io/kube-openapi/pkg/spec3"
)
const (
subTypeProtobufDeprecated = "com.github.proto-openapi.spec.v3@v1.0+protobuf"
subTypeProtobuf = "com.github.proto-openapi.spec.v3.v1.0+protobuf"
subTypeJSON = "json"
)
// OpenAPIV3Discovery is the format of the Discovery document for OpenAPI V3
// It maps Discovery paths to their corresponding URLs with a hash parameter included
type OpenAPIV3Discovery struct {
Paths map[string]OpenAPIV3DiscoveryGroupVersion `json:"paths"`
}
// OpenAPIV3DiscoveryGroupVersion includes information about a group version and URL
// for accessing the OpenAPI. The URL includes a hash parameter to support client side caching
type OpenAPIV3DiscoveryGroupVersion struct {
// Path is an absolute path of an OpenAPI V3 document in the form of /openapi/v3/apis/apps/v1?hash=014fbff9a07c
ServerRelativeURL string `json:"serverRelativeURL"`
}
func ToV3ProtoBinary(json []byte) ([]byte, error) {
document, err := openapi_v3.ParseDocument(json)
if err != nil {
return nil, err
}
return proto.Marshal(document)
}
type timedSpec struct {
spec []byte
lastModified time.Time
}
// This type is protected by the lock on OpenAPIService.
type openAPIV3Group struct {
specCache cached.LastSuccess[*spec3.OpenAPI]
pbCache cached.Value[timedSpec]
jsonCache cached.Value[timedSpec]
}
func newOpenAPIV3Group() *openAPIV3Group {
o := &openAPIV3Group{}
o.jsonCache = cached.Transform[*spec3.OpenAPI](func(spec *spec3.OpenAPI, etag string, err error) (timedSpec, string, error) {
if err != nil {
return timedSpec{}, "", err
}
json, err := json.Marshal(spec)
if err != nil {
return timedSpec{}, "", err
}
return timedSpec{spec: json, lastModified: time.Now()}, computeETag(json), nil
}, &o.specCache)
o.pbCache = cached.Transform(func(ts timedSpec, etag string, err error) (timedSpec, string, error) {
if err != nil {
return timedSpec{}, "", err
}
proto, err := ToV3ProtoBinary(ts.spec)
if err != nil {
return timedSpec{}, "", err
}
return timedSpec{spec: proto, lastModified: ts.lastModified}, etag, nil
}, o.jsonCache)
return o
}
func (o *openAPIV3Group) UpdateSpec(openapi cached.Value[*spec3.OpenAPI]) {
o.specCache.Store(openapi)
}
// OpenAPIService is the service responsible for serving OpenAPI spec. It has
// the ability to safely change the spec while serving it.
type OpenAPIService struct {
// Mutex protects the schema map.
mutex sync.Mutex
v3Schema map[string]*openAPIV3Group
discoveryCache cached.LastSuccess[timedSpec]
}
func computeETag(data []byte) string {
if data == nil {
return ""
}
return fmt.Sprintf("%X", sha512.Sum512(data))
}
func constructServerRelativeURL(gvString, etag string) string {
u := url.URL{Path: path.Join("/openapi/v3", gvString)}
query := url.Values{}
query.Set("hash", etag)
u.RawQuery = query.Encode()
return u.String()
}
// NewOpenAPIService builds an OpenAPIService starting with the given spec.
func NewOpenAPIService() *OpenAPIService {
o := &OpenAPIService{}
o.v3Schema = make(map[string]*openAPIV3Group)
// We're not locked because we haven't shared the structure yet.
o.discoveryCache.Store(o.buildDiscoveryCacheLocked())
return o
}
func (o *OpenAPIService) buildDiscoveryCacheLocked() cached.Value[timedSpec] {
caches := make(map[string]cached.Value[timedSpec], len(o.v3Schema))
for gvName, group := range o.v3Schema {
caches[gvName] = group.jsonCache
}
return cached.Merge(func(results map[string]cached.Result[timedSpec]) (timedSpec, string, error) {
discovery := &OpenAPIV3Discovery{Paths: make(map[string]OpenAPIV3DiscoveryGroupVersion)}
for gvName, result := range results {
if result.Err != nil {
return timedSpec{}, "", result.Err
}
discovery.Paths[gvName] = OpenAPIV3DiscoveryGroupVersion{
ServerRelativeURL: constructServerRelativeURL(gvName, result.Etag),
}
}
j, err := json.Marshal(discovery)
if err != nil {
return timedSpec{}, "", err
}
return timedSpec{spec: j, lastModified: time.Now()}, computeETag(j), nil
}, caches)
}
func (o *OpenAPIService) getSingleGroupBytes(getType string, group string) ([]byte, string, time.Time, error) {
o.mutex.Lock()
defer o.mutex.Unlock()
v, ok := o.v3Schema[group]
if !ok {
return nil, "", time.Now(), fmt.Errorf("Cannot find CRD group %s", group)
}
switch getType {
case subTypeJSON:
ts, etag, err := v.jsonCache.Get()
return ts.spec, etag, ts.lastModified, err
case subTypeProtobuf, subTypeProtobufDeprecated:
ts, etag, err := v.pbCache.Get()
return ts.spec, etag, ts.lastModified, err
default:
return nil, "", time.Now(), fmt.Errorf("Invalid accept clause %s", getType)
}
}
// UpdateGroupVersionLazy adds or updates an existing group with the new cached.
func (o *OpenAPIService) UpdateGroupVersionLazy(group string, openapi cached.Value[*spec3.OpenAPI]) {
o.mutex.Lock()
defer o.mutex.Unlock()
if _, ok := o.v3Schema[group]; !ok {
o.v3Schema[group] = newOpenAPIV3Group()
// Since there is a new item, we need to re-build the cache map.
o.discoveryCache.Store(o.buildDiscoveryCacheLocked())
}
o.v3Schema[group].UpdateSpec(openapi)
}
func (o *OpenAPIService) UpdateGroupVersion(group string, openapi *spec3.OpenAPI) {
o.UpdateGroupVersionLazy(group, cached.Static(openapi, uuid.New().String()))
}
func (o *OpenAPIService) DeleteGroupVersion(group string) {
o.mutex.Lock()
defer o.mutex.Unlock()
delete(o.v3Schema, group)
// Rebuild the merge cache map since the items have changed.
o.discoveryCache.Store(o.buildDiscoveryCacheLocked())
}
func (o *OpenAPIService) HandleDiscovery(w http.ResponseWriter, r *http.Request) {
ts, etag, err := o.discoveryCache.Get()
if err != nil {
klog.Errorf("Error serving discovery: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Etag", strconv.Quote(etag))
w.Header().Set("Content-Type", "application/json")
http.ServeContent(w, r, "/openapi/v3", ts.lastModified, bytes.NewReader(ts.spec))
}
func (o *OpenAPIService) HandleGroupVersion(w http.ResponseWriter, r *http.Request) {
url := strings.SplitAfterN(r.URL.Path, "/", 4)
group := url[3]
decipherableFormats := r.Header.Get("Accept")
if decipherableFormats == "" {
decipherableFormats = "*/*"
}
clauses := goautoneg.ParseAccept(decipherableFormats)
w.Header().Add("Vary", "Accept")
if len(clauses) == 0 {
return
}
accepted := []struct {
Type string
SubType string
ReturnedContentType string
}{
{"application", subTypeJSON, "application/" + subTypeJSON},
{"application", subTypeProtobuf, "application/" + subTypeProtobuf},
{"application", subTypeProtobufDeprecated, "application/" + subTypeProtobuf},
}
for _, clause := range clauses {
for _, accepts := range accepted {
if clause.Type != accepts.Type && clause.Type != "*" {
continue
}
if clause.SubType != accepts.SubType && clause.SubType != "*" {
continue
}
data, etag, lastModified, err := o.getSingleGroupBytes(accepts.SubType, group)
if err != nil {
return
}
// Set Content-Type header in the reponse
w.Header().Set("Content-Type", accepts.ReturnedContentType)
// ETag must be enclosed in double quotes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
w.Header().Set("Etag", strconv.Quote(etag))
if hash := r.URL.Query().Get("hash"); hash != "" {
if hash != etag {
u := constructServerRelativeURL(group, etag)
http.Redirect(w, r, u, 301)
return
}
// The Vary header is required because the Accept header can
// change the contents returned. This prevents clients from caching
// protobuf as JSON and vice versa.
w.Header().Set("Vary", "Accept")
// Only set these headers when a hash is given.
w.Header().Set("Cache-Control", "public, immutable")
// Set the Expires directive to the maximum value of one year from the request,
// effectively indicating that the cache never expires.
w.Header().Set("Expires", time.Now().AddDate(1, 0, 0).Format(time.RFC1123))
}
http.ServeContent(w, r, "", lastModified, bytes.NewReader(data))
return
}
}
w.WriteHeader(406)
return
}
func (o *OpenAPIService) RegisterOpenAPIV3VersionedService(servePath string, handler common.PathHandlerByGroupVersion) error {
handler.Handle(servePath, http.HandlerFunc(o.HandleDiscovery))
handler.HandlePrefix(servePath+"/", http.HandlerFunc(o.HandleGroupVersion))
return nil
}
|