-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathconnector.go
More file actions
231 lines (209 loc) · 6.5 KB
/
connector.go
File metadata and controls
231 lines (209 loc) · 6.5 KB
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
package apiserver
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/kube-openapi/pkg/common"
"k8s.io/kube-openapi/pkg/validation/spec"
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana-app-sdk/logging"
"github.com/grafana/grafana-app-sdk/resource"
)
type CustomRoute struct {
Path string
Handler func(context.Context, app.CustomRouteResponseWriter, *app.CustomRouteRequest) error
}
type ResourceCallOptions struct {
metav1.TypeMeta
// Path is the URL path to use for the current proxy request
Path string
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceCallOptions) DeepCopyInto(out *ResourceCallOptions) {
*out = *in
out.TypeMeta = in.TypeMeta
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceCallOptions.
func (in *ResourceCallOptions) DeepCopy() *ResourceCallOptions {
if in == nil {
return nil
}
out := new(ResourceCallOptions)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ResourceCallOptions) DeepCopyObject() runtime.Object {
c := in.DeepCopy()
return c
}
var (
_ = rest.Connecter(&SubresourceConnector{})
_ = rest.StorageMetadata(&SubresourceConnector{})
)
type SubresourceConnectorResponseObject struct {
Object any
MIMETypes []string
}
type SubresourceConnector struct {
Route CustomRoute
Kind resource.Kind
// Methods is a map of uppercase HTTP methods (ex. GET, PUT) to their response types
Methods map[string]SubresourceConnectorResponseObject
}
func (*SubresourceConnector) New() runtime.Object {
return &ResourceCallOptions{}
}
func (*SubresourceConnector) Destroy() {
}
func (r *SubresourceConnector) ConnectMethods() []string {
methods := make([]string, 0, len(r.Methods))
for method := range r.Methods {
methods = append(methods, method)
}
return methods
}
func (*SubresourceConnector) NewConnectOptions() (runtime.Object, bool, string) {
return &ResourceCallOptions{}, false, ""
}
func (r *SubresourceConnector) ProducesObject(verb string) any {
resp := r.Methods[strings.ToUpper(verb)]
return resp.Object
}
func (r *SubresourceConnector) ProducesMIMETypes(verb string) []string {
resp := r.Methods[strings.ToUpper(verb)]
if len(resp.MIMETypes) == 0 {
return []string{"application/json"} // TODO: default to text/plain instead?
}
return resp.MIMETypes
}
func (r *SubresourceConnector) Connect(ctx context.Context, id string, opts runtime.Object, _ rest.Responder) (http.Handler, error) {
resourceCallOpts, ok := opts.(*ResourceCallOptions)
if !ok {
return nil, fmt.Errorf("invalid options object: %#v", opts)
}
logging.FromContext(ctx).Debug("Creating subresource connector", "id", id, "opts", resourceCallOpts)
// TODO: map instead?
info, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, errors.New("unable to retrieve request info from context")
}
identifier := resource.FullIdentifier{
Name: info.Name,
Namespace: info.Namespace,
Group: info.APIGroup,
Version: info.APIVersion,
Kind: r.Kind.Kind(),
}
return &handlerWrapper{
id: identifier,
handler: r.Route.Handler,
urlToPath: func(u *url.URL) string {
path := u.Path
// Index from GV
idx := strings.Index(path, r.Kind.GroupVersionKind().GroupVersion().String())
if idx == -1 {
return path
}
path = path[idx+len(r.Kind.GroupVersionKind().GroupVersion().String())+1:]
// Split up the path into segments
parts := strings.Split(path, "/")
// Check for namespaces/cluster
if r.Kind.Scope() == resource.ClusterScope {
if len(parts) <= 2 {
return ""
}
return strings.Join(parts[2:], "/")
}
if len(parts) <= 4 {
return ""
}
return strings.Join(parts[4:], "/")
},
}, nil
}
type handlerWrapper struct {
id resource.FullIdentifier
handler func(context.Context, app.CustomRouteResponseWriter, *app.CustomRouteRequest) error
urlToPath func(u *url.URL) string
}
func (h *handlerWrapper) ServeHTTP(w http.ResponseWriter, req *http.Request) {
err := h.handler(req.Context(), w, &app.CustomRouteRequest{
ResourceIdentifier: h.id,
Path: h.urlToPath(req.URL),
URL: req.URL,
Method: req.Method,
Headers: req.Header,
Body: req.Body,
})
if err != nil {
j, e := json.Marshal(err)
if e != nil {
logging.FromContext(req.Context()).Error("unable to marshal error JSON", "error", err)
w.WriteHeader(http.StatusInternalServerError)
}
if cast, ok := err.(apierrors.APIStatus); ok {
w.WriteHeader(int(cast.Status().Code))
} else {
w.WriteHeader(http.StatusInternalServerError)
}
_, e = w.Write(j)
if e != nil {
sanitizedPath := strings.ReplaceAll(req.URL.Path, "\n", "")
sanitizedPath = strings.ReplaceAll(sanitizedPath, "\r", "")
logging.FromContext(req.Context()).Error("unable to write response", "error", err, "url", sanitizedPath)
}
}
}
// CovertURLValuesToResourceCallOptions reads from the input *url.Values and assigns fields in the out *ResourceCallOptions
func CovertURLValuesToResourceCallOptions(in *url.Values, out *ResourceCallOptions, s conversion.Scope) error {
if values, ok := map[string][]string(*in)["path"]; ok && len(values) > 0 {
if err := runtime.Convert_Slice_string_To_string(&values, &out.Path, s); err != nil {
return err
}
} else {
out.Path = ""
}
return nil
}
func GetResourceCallOptionsOpenAPIDefinition() map[string]common.OpenAPIDefinition {
return map[string]common.OpenAPIDefinition{
"github.com/grafana/grafana-app-sdk/k8s/apiserver.ResourceCallOptions": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ExternalNameFoo defines model for ExternalNameFoo.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
},
},
"path": {
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
},
},
},
}
}