Debian Codegraph @

pkg/endpoints/discovery/root.go

raw
1 /*
2 Copyright 2017 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package discovery
18
19 import (
20 "context"
21 "net/http"
22 "sync"
23
24 restful "github.com/emicklei/go-restful/v3"
25
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/runtime"
28 "k8s.io/apimachinery/pkg/runtime/schema"
29 utilnet "k8s.io/apimachinery/pkg/util/net"
30 "k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
31 "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
32 )
33
34 // GroupManager is an interface that allows dynamic mutation of the existing webservice to handle
35 // API groups being added or removed.
36 type GroupManager interface {
37 GroupLister
38
39 AddGroup(apiGroup metav1.APIGroup)
40 RemoveGroup(groupName string)
41 ServeHTTP(resp http.ResponseWriter, req *http.Request)
42 WebService() *restful.WebService
43 }
44
45 // GroupLister knows how to list APIGroups for discovery.
46 type GroupLister interface {
47 // Groups returns APIGroups for discovery, filling in ServerAddressByClientCIDRs
48 // based on data in req.
49 Groups(ctx context.Context, req *http.Request) ([]metav1.APIGroup, error)
50 }
51
52 // rootAPIsHandler creates a webservice serving api group discovery.
53 // The list of APIGroups may change while the server is running because additional resources
54 // are registered or removed. It is not safe to cache the values.
55 type rootAPIsHandler struct {
56 // addresses is used to build cluster IPs for discovery.
57 addresses Addresses
58
59 serializer runtime.NegotiatedSerializer
60
61 // Map storing information about all groups to be exposed in discovery response.
62 // The map is from name to the group.
63 lock sync.RWMutex
64 apiGroups map[string]metav1.APIGroup
65 // apiGroupNames preserves insertion order
66 apiGroupNames []string
67 }
68
69 func NewRootAPIsHandler(addresses Addresses, serializer runtime.NegotiatedSerializer) *rootAPIsHandler {
70 // Because in release 1.1, /apis returns response with empty APIVersion, we
71 // use stripVersionNegotiatedSerializer to keep the response backwards
72 // compatible.
73 serializer = stripVersionNegotiatedSerializer{serializer}
74
75 return &rootAPIsHandler{
76 addresses: addresses,
77 serializer: serializer,
78 apiGroups: map[string]metav1.APIGroup{},
79 }
80 }
81
82 func (s *rootAPIsHandler) AddGroup(apiGroup metav1.APIGroup) {
83 s.lock.Lock()
84 defer s.lock.Unlock()
85
86 _, alreadyExists := s.apiGroups[apiGroup.Name]
87
88 s.apiGroups[apiGroup.Name] = apiGroup
89 if !alreadyExists {
90 s.apiGroupNames = append(s.apiGroupNames, apiGroup.Name)
91 }
92 }
93
94 func (s *rootAPIsHandler) RemoveGroup(groupName string) {
95 s.lock.Lock()
96 defer s.lock.Unlock()
97
98 delete(s.apiGroups, groupName)
99 for i := range s.apiGroupNames {
100 if s.apiGroupNames[i] == groupName {
101 s.apiGroupNames = append(s.apiGroupNames[:i], s.apiGroupNames[i+1:]...)
102 break
103 }
104 }
105 }
106
107 func (s *rootAPIsHandler) Groups(ctx context.Context, req *http.Request) ([]metav1.APIGroup, error) {
108 s.lock.RLock()
109 defer s.lock.RUnlock()
110
111 return s.groupsLocked(ctx, req), nil
112 }
113
114 // groupsLocked returns the APIGroupList discovery information for this handler.
115 // The caller must hold the lock before invoking this method to avoid data races.
116 func (s *rootAPIsHandler) groupsLocked(ctx context.Context, req *http.Request) []metav1.APIGroup {
117 clientIP := utilnet.GetClientIP(req)
118 serverCIDR := s.addresses.ServerAddressByClientCIDRs(clientIP)
119
120 orderedGroups := []metav1.APIGroup{}
121 for _, groupName := range s.apiGroupNames {
122 orderedGroups = append(orderedGroups, s.apiGroups[groupName])
123 }
124
125 groups := make([]metav1.APIGroup, len(orderedGroups))
126 for i := range orderedGroups {
127 groups[i] = orderedGroups[i]
128 groups[i].ServerAddressByClientCIDRs = serverCIDR
129 }
130
131 return groups
132 }
133
134 func (s *rootAPIsHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
135 s.lock.RLock()
136 defer s.lock.RUnlock()
137
138 groupList := metav1.APIGroupList{Groups: s.groupsLocked(req.Context(), req)}
139
140 responsewriters.WriteObjectNegotiated(s.serializer, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, resp, req, http.StatusOK, &groupList, false)
141 }
142
143 func (s *rootAPIsHandler) restfulHandle(req *restful.Request, resp *restful.Response) {
144 s.ServeHTTP(resp.ResponseWriter, req.Request)
145 }
146
147 // WebService returns a webservice serving api group discovery.
148 // Note: during the server runtime apiGroups might change.
149 func (s *rootAPIsHandler) WebService() *restful.WebService {
150 mediaTypes, _ := negotiation.MediaTypesForSerializer(s.serializer)
151 ws := new(restful.WebService)
152 ws.Path(APIGroupPrefix)
153 ws.Doc("get available API versions")
154 ws.Route(ws.GET("/").To(s.restfulHandle).
155 Doc("get available API versions").
156 Operation("getAPIVersions").
157 Produces(mediaTypes...).
158 Consumes(mediaTypes...).
159 Writes(metav1.APIGroupList{}))
160 return ws
161 }