forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.go
335 lines (291 loc) · 8.04 KB
/
http_server.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package pkger
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"path"
"strings"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/influxdata/influxdb"
pctx "github.com/influxdata/influxdb/context"
kithttp "github.com/influxdata/influxdb/kit/transport/http"
"github.com/influxdata/influxdb/pkg/jsonnet"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
const RoutePrefix = "/api/v2/packages"
// HTTPServer is a server that manages the packages HTTP transport.
type HTTPServer struct {
chi.Router
api *kithttp.API
logger *zap.Logger
svc SVC
}
// NewHTTPServer constructs a new http server.
func NewHTTPServer(log *zap.Logger, svc SVC) *HTTPServer {
svr := &HTTPServer{
api: kithttp.NewAPI(kithttp.WithLog(log)),
logger: log,
svc: svc,
}
r := chi.NewRouter()
r.Use(
middleware.Recoverer,
middleware.RequestID,
middleware.RealIP,
)
{
r.With(middleware.AllowContentType("text/yml", "application/x-yaml", "application/json")).
Post("/", svr.createPkg)
r.With(middleware.SetHeader("Content-Type", "application/json; charset=utf-8")).
Post("/apply", svr.applyPkg)
}
svr.Router = r
return svr
}
// Prefix provides the prefix to this route tree.
func (s *HTTPServer) Prefix() string {
return RoutePrefix
}
type (
// ReqCreatePkg is a request body for the create pkg endpoint.
ReqCreatePkg struct {
OrgIDs []string `json:"orgIDs"`
Resources []ResourceToClone `json:"resources"`
}
// RespCreatePkg is a response body for the create pkg endpoint.
RespCreatePkg []Object
)
func (s *HTTPServer) createPkg(w http.ResponseWriter, r *http.Request) {
encoding := pkgEncoding(r.Header)
var reqBody ReqCreatePkg
if err := s.api.DecodeJSON(r.Body, &reqBody); err != nil {
s.api.Err(w, err)
return
}
defer r.Body.Close()
if len(reqBody.Resources) == 0 && len(reqBody.OrgIDs) == 0 {
s.api.Err(w, &influxdb.Error{
Code: influxdb.EUnprocessableEntity,
Msg: "at least 1 resource or 1 org id must be provided",
})
return
}
opts := []CreatePkgSetFn{
CreateWithExistingResources(reqBody.Resources...),
}
for _, orgIDStr := range reqBody.OrgIDs {
orgID, err := influxdb.IDFromString(orgIDStr)
if err != nil {
continue
}
opts = append(opts, CreateWithAllOrgResources(*orgID))
}
newPkg, err := s.svc.CreatePkg(r.Context(), opts...)
if err != nil {
s.api.Err(w, err)
return
}
resp := RespCreatePkg(newPkg.Objects)
if resp == nil {
resp = []Object{}
}
var enc encoder
switch encoding {
case EncodingYAML:
enc = yaml.NewEncoder(w)
w.Header().Set("Content-Type", "application/x-yaml")
default:
enc = newJSONEnc(w)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
}
s.encResp(w, enc, http.StatusOK, resp)
}
// PkgRemote provides a package via a remote (i.e. a gist). If content type is not
// provided then the service will do its best to discern the content type of the
// contents.
type PkgRemote struct {
URL string `json:"url"`
ContentType string `json:"contentType"`
}
// Encoding returns the encoding type that corresponds to the given content type.
func (p PkgRemote) Encoding() Encoding {
ct := strings.ToLower(p.ContentType)
urlBase := path.Ext(p.URL)
switch {
case ct == "jsonnet" || urlBase == ".jsonnet":
return EncodingJsonnet
case ct == "json" || urlBase == ".json":
return EncodingJSON
case ct == "yml" || ct == "yaml" || urlBase == ".yml" || urlBase == ".yaml":
return EncodingYAML
default:
return EncodingSource
}
}
// ReqApplyPkg is the request body for a json or yaml body for the apply pkg endpoint.
type ReqApplyPkg struct {
DryRun bool `json:"dryRun" yaml:"dryRun"`
OrgID string `json:"orgID" yaml:"orgID"`
Remotes []PkgRemote `json:"remotes" yaml:"remotes"`
RawPkgs []json.RawMessage `json:"packages" yaml:"packages"`
RawPkg json.RawMessage `json:"package" yaml:"package"`
EnvRefs map[string]string `json:"envRefs"`
Secrets map[string]string `json:"secrets"`
}
// Pkgs returns all pkgs associated with the request.
func (r ReqApplyPkg) Pkgs(encoding Encoding) (*Pkg, error) {
var rawPkgs []*Pkg
for _, rem := range r.Remotes {
if rem.URL == "" {
continue
}
pkg, err := Parse(rem.Encoding(), FromHTTPRequest(rem.URL), ValidSkipParseError())
if err != nil {
return nil, &influxdb.Error{
Code: influxdb.EUnprocessableEntity,
Msg: fmt.Sprintf("pkg from url[%s] had an issue: %s", rem.URL, err.Error()),
}
}
rawPkgs = append(rawPkgs, pkg)
}
for i, rawPkg := range append(r.RawPkgs, r.RawPkg) {
if rawPkg == nil {
continue
}
pkg, err := Parse(encoding, FromReader(bytes.NewReader(rawPkg)), ValidSkipParseError())
if err != nil {
return nil, &influxdb.Error{
Code: influxdb.EUnprocessableEntity,
Msg: fmt.Sprintf("pkg [%d] had an issue: %s", i, err.Error()),
}
}
rawPkgs = append(rawPkgs, pkg)
}
return Combine(rawPkgs...)
}
// RespApplyPkg is the response body for the apply pkg endpoint.
type RespApplyPkg struct {
Diff Diff `json:"diff" yaml:"diff"`
Summary Summary `json:"summary" yaml:"summary"`
Errors []ValidationErr `json:"errors,omitempty" yaml:"errors,omitempty"`
}
func (s *HTTPServer) applyPkg(w http.ResponseWriter, r *http.Request) {
var reqBody ReqApplyPkg
encoding, err := decodeWithEncoding(r, &reqBody)
if err != nil {
s.api.Err(w, newDecodeErr(encoding.String(), err))
return
}
orgID, err := influxdb.IDFromString(reqBody.OrgID)
if err != nil {
s.api.Err(w, &influxdb.Error{
Code: influxdb.EConflict,
Msg: fmt.Sprintf("invalid organization ID provided: %q", reqBody.OrgID),
})
return
}
auth, err := pctx.GetAuthorizer(r.Context())
if err != nil {
s.api.Err(w, err)
return
}
userID := auth.GetUserID()
parsedPkg, err := reqBody.Pkgs(encoding)
if err != nil {
s.api.Err(w, &influxdb.Error{
Code: influxdb.EUnprocessableEntity,
Err: err,
})
return
}
sum, diff, err := s.svc.DryRun(r.Context(), *orgID, userID, parsedPkg, ApplyWithEnvRefs(reqBody.EnvRefs))
if IsParseErr(err) {
s.api.Respond(w, http.StatusUnprocessableEntity, RespApplyPkg{
Diff: diff,
Summary: sum,
Errors: convertParseErr(err),
})
return
}
if err != nil {
s.api.Err(w, err)
return
}
// if only a dry run, then we exit before anything destructive
if reqBody.DryRun {
s.api.Respond(w, http.StatusOK, RespApplyPkg{
Diff: diff,
Summary: sum,
})
return
}
sum, err = s.svc.Apply(r.Context(), *orgID, userID, parsedPkg, ApplyWithEnvRefs(reqBody.EnvRefs), ApplyWithSecrets(reqBody.Secrets))
if err != nil && !IsParseErr(err) {
s.api.Err(w, err)
return
}
s.api.Respond(w, http.StatusCreated, RespApplyPkg{
Diff: diff,
Summary: sum,
Errors: convertParseErr(err),
})
}
type encoder interface {
Encode(interface{}) error
}
func decodeWithEncoding(r *http.Request, v interface{}) (Encoding, error) {
encoding := pkgEncoding(r.Header)
var dec interface{ Decode(interface{}) error }
switch encoding {
case EncodingJsonnet:
dec = jsonnet.NewDecoder(r.Body)
case EncodingYAML:
dec = yaml.NewDecoder(r.Body)
default:
dec = json.NewDecoder(r.Body)
}
return encoding, dec.Decode(v)
}
func pkgEncoding(headers http.Header) Encoding {
switch contentType := headers.Get("Content-Type"); contentType {
case "application/x-jsonnet":
return EncodingJsonnet
case "text/yml", "application/x-yaml":
return EncodingYAML
default:
return EncodingJSON
}
}
func newJSONEnc(w io.Writer) encoder {
enc := json.NewEncoder(w)
enc.SetIndent("", "\t")
return enc
}
func (s *HTTPServer) encResp(w http.ResponseWriter, enc encoder, code int, res interface{}) {
w.WriteHeader(code)
if err := enc.Encode(res); err != nil {
s.api.Err(w, &influxdb.Error{
Msg: fmt.Sprintf("unable to marshal; Err: %v", err),
Code: influxdb.EInternal,
Err: err,
})
}
}
func convertParseErr(err error) []ValidationErr {
pErr, ok := err.(ParseError)
if !ok {
return nil
}
return pErr.ValidationErrs()
}
func newDecodeErr(encoding string, err error) *influxdb.Error {
return &influxdb.Error{
Msg: fmt.Sprintf("unable to unmarshal %s", encoding),
Code: influxdb.EInvalid,
Err: err,
}
}