-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathpipeline_upload_server.go
311 lines (272 loc) · 11.4 KB
/
pipeline_upload_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
// Copyright 2018 The Kubeflow 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
//
// https://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 server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/golang/glog"
"github.com/golang/protobuf/jsonpb"
apiv1beta1 "github.com/kubeflow/pipelines/backend/api/v1beta1/go_client"
"github.com/kubeflow/pipelines/backend/src/apiserver/common"
"github.com/kubeflow/pipelines/backend/src/apiserver/model"
"github.com/kubeflow/pipelines/backend/src/apiserver/resource"
"github.com/kubeflow/pipelines/backend/src/common/util"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
authorizationv1 "k8s.io/api/authorization/v1"
)
const (
FormFileKey = "uploadfile"
NameQueryStringKey = "name"
DescriptionQueryStringKey = "description"
NamespaceStringQuery = "namespace"
// Pipeline Id in the query string specifies a pipeline when creating versions.
PipelineKey = "pipelineid"
)
// Metric variables. Please prefix the metric names with pipeline_upload_ or pipeline_version_upload_.
var (
uploadPipelineRequests = promauto.NewCounter(prometheus.CounterOpts{
Name: "pipeline_upload_requests",
Help: "The number of pipeline upload requests",
})
uploadPipelineVersionRequests = promauto.NewCounter(prometheus.CounterOpts{
Name: "pipeline_version_upload_requests",
Help: "The number of pipeline version upload requests",
})
// TODO(jingzhang36): error count and success count.
)
type PipelineUploadServerOptions struct {
CollectMetrics bool `json:"collect_metrics,omitempty"`
// ApiVersion string `default:"v2beta1" json:"api_version,omitempty"`
// DefaultNamespace string `default:"" json:"default_namespace,omitempty"`
}
type PipelineUploadServer struct {
resourceManager *resource.ResourceManager
options *PipelineUploadServerOptions
}
func (s *PipelineUploadServer) UploadPipelineV1(w http.ResponseWriter, r *http.Request) {
s.uploadPipeline("v1beta1", w, r)
}
func (s *PipelineUploadServer) UploadPipeline(w http.ResponseWriter, r *http.Request) {
s.uploadPipeline("v2beta1", w, r)
}
// Creates a pipeline and a pipeline version.
// HTTP multipart endpoint for uploading pipeline file.
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
// This endpoint is not exposed through grpc endpoint, since grpc-gateway can't convert the gRPC
// endpoint to the HTTP endpoint.
// See https://github.com/grpc-ecosystem/grpc-gateway/issues/500
// Thus we create the HTTP endpoint directly and using swagger to auto generate the HTTP client.
func (s *PipelineUploadServer) uploadPipeline(api_version string, w http.ResponseWriter, r *http.Request) {
if s.options.CollectMetrics {
uploadPipelineRequests.Inc()
uploadPipelineVersionRequests.Inc()
}
glog.Infof("Upload pipeline called")
file, header, err := r.FormFile(FormFileKey)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to read pipeline from file"))
return
}
defer file.Close()
pipelineFile, err := ReadPipelineFile(header.Filename, file, common.MaxFileLength)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to read a pipeline spec file"))
return
}
pipelineNamespace := r.URL.Query().Get(NamespaceStringQuery)
pipelineNamespace = s.resourceManager.ReplaceNamespace(pipelineNamespace)
resourceAttributes := &authorizationv1.ResourceAttributes{
Namespace: pipelineNamespace,
Verb: common.RbacResourceVerbCreate,
}
err = s.canUploadVersionedPipeline(r, "", resourceAttributes)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to create a pipeline due to authorization error"))
return
}
fileNameQueryString := r.URL.Query().Get(NameQueryStringKey)
pipelineName := buildPipelineName(fileNameQueryString, header.Filename)
pipeline := &model.Pipeline{
Name: pipelineName,
Description: r.URL.Query().Get(DescriptionQueryStringKey),
Namespace: pipelineNamespace,
}
pipelineVersion := &model.PipelineVersion{
Name: pipeline.Name,
Description: pipeline.Description,
PipelineSpec: string(pipelineFile),
}
w.Header().Set("Content-Type", "application/json")
newPipeline, newPipelineVersion, err := s.resourceManager.CreatePipelineAndPipelineVersion(pipeline, pipelineVersion)
if err != nil {
if util.IsUserErrorCodeMatch(err, codes.AlreadyExists) {
s.writeErrorToResponse(w, http.StatusConflict, util.Wrap(err, "Failed to create a pipeline and a pipeline version. The pipeline already exists."))
return
}
s.writeErrorToResponse(w, http.StatusInternalServerError, util.Wrap(err, "Failed to create a pipeline and a pipeline version"))
return
}
if s.options.CollectMetrics {
pipelineVersionCount.Inc()
}
marshaler := &jsonpb.Marshaler{EnumsAsInts: false, OrigName: true}
if api_version == "v1beta1" {
err = marshaler.Marshal(w, toApiPipelineV1(newPipeline, newPipelineVersion))
} else if api_version == "v2beta1" {
err = marshaler.Marshal(w, toApiPipeline(newPipeline))
} else {
s.writeErrorToResponse(w, http.StatusInternalServerError, util.Wrap(err, "Failed to create a pipeline. Invalid API version"))
return
}
if err != nil {
s.writeErrorToResponse(w, http.StatusInternalServerError, util.Wrap(err, "Failed to create a pipeline due to error marshalling the pipeline"))
return
}
}
func (s *PipelineUploadServer) UploadPipelineVersionV1(w http.ResponseWriter, r *http.Request) {
s.uploadPipelineVersion("v1beta1", w, r)
}
func (s *PipelineUploadServer) UploadPipelineVersion(w http.ResponseWriter, r *http.Request) {
s.uploadPipelineVersion("v2beta1", w, r)
}
// Creates a pipeline version under an existing pipeline.
// HTTP multipart endpoint for uploading pipeline version file.
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
// This endpoint is not exposed through grpc endpoint, since grpc-gateway can't convert the gRPC
// endpoint to the HTTP endpoint.
// See https://github.com/grpc-ecosystem/grpc-gateway/issues/500
// Thus we create the HTTP endpoint directly and using swagger to auto generate the HTTP client.
func (s *PipelineUploadServer) uploadPipelineVersion(api_version string, w http.ResponseWriter, r *http.Request) {
if s.options.CollectMetrics {
uploadPipelineVersionRequests.Inc()
}
glog.Infof("Upload pipeline version called")
file, header, err := r.FormFile(FormFileKey)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to create a pipeline version due to error parsing pipeline spec filename"))
return
}
defer file.Close()
pipelineFile, err := ReadPipelineFile(header.Filename, file, common.MaxFileLength)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to create a pipeline version due to error reading pipeline spec file"))
return
}
pipelineId := r.URL.Query().Get(PipelineKey)
if pipelineId == "" {
s.writeErrorToResponse(w, http.StatusBadRequest, errors.New("Failed to create a pipeline version due to error reading pipeline id"))
return
}
namespace, err := s.resourceManager.FetchNamespaceFromPipelineId(pipelineId)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to create a pipeline version due to error reading namespace"))
return
}
resourceAttributes := &authorizationv1.ResourceAttributes{
Namespace: namespace,
Verb: common.RbacResourceVerbCreate,
}
err = s.canUploadVersionedPipeline(r, pipelineId, resourceAttributes)
if err != nil {
s.writeErrorToResponse(w, http.StatusBadRequest, util.Wrap(err, "Failed to create a pipeline version due to authorization error"))
return
}
w.Header().Set("Content-Type", "application/json")
// If new version's name is not included in query string, use file name.
versionNameQueryString := r.URL.Query().Get(NameQueryStringKey)
pipelineVersionName := buildPipelineName(versionNameQueryString, header.Filename)
newPipelineVersion, err := s.resourceManager.CreatePipelineVersion(
&model.PipelineVersion{
Name: pipelineVersionName,
Description: r.URL.Query().Get(DescriptionQueryStringKey),
PipelineId: pipelineId,
PipelineSpec: string(pipelineFile),
},
)
if err != nil {
if util.IsUserErrorCodeMatch(err, codes.AlreadyExists) {
s.writeErrorToResponse(w, http.StatusConflict, util.Wrap(err, "Failed to create a pipeline version. The pipeline already exists."))
return
}
s.writeErrorToResponse(w, http.StatusInternalServerError, util.Wrap(err, "Failed to create a pipeline version"))
return
}
marshaler := &jsonpb.Marshaler{EnumsAsInts: false, OrigName: true}
if api_version == "v1beta1" {
err = marshaler.Marshal(w, toApiPipelineVersionV1(newPipelineVersion))
} else if api_version == "v2beta1" {
err = marshaler.Marshal(w, toApiPipelineVersion(newPipelineVersion))
} else {
s.writeErrorToResponse(w, http.StatusInternalServerError, util.Wrap(err, "Failed to create a pipeline version. Invalid API version"))
return
}
if err != nil {
s.writeErrorToResponse(w, http.StatusInternalServerError, util.Wrap(err, "Failed to create a pipeline version due to marshalling error"))
return
}
if s.options.CollectMetrics {
pipelineVersionCount.Inc()
}
}
func (s *PipelineUploadServer) canUploadVersionedPipeline(r *http.Request, pipelineId string, resourceAttributes *authorizationv1.ResourceAttributes) error {
if !common.IsMultiUserMode() {
// Skip authorization if not multi-user mode.
return nil
}
if len(pipelineId) > 0 {
namespace, err := s.resourceManager.FetchNamespaceFromPipelineId(pipelineId)
if err != nil {
return util.Wrap(err, "Failed to authorize with the Pipeline ID")
}
if len(resourceAttributes.Namespace) == 0 {
resourceAttributes.Namespace = namespace
}
}
if resourceAttributes.Namespace == "" {
return nil
}
resourceAttributes.Group = common.RbacPipelinesGroup
resourceAttributes.Version = common.RbacPipelinesVersion
resourceAttributes.Resource = common.RbacResourceTypePipelines
ctx := context.Background()
md := metadata.MD{}
for key, values := range r.Header {
md.Set(key, values...)
}
ctx = metadata.NewIncomingContext(ctx, md)
err := s.resourceManager.IsAuthorized(ctx, resourceAttributes)
if err != nil {
return util.Wrap(err, "Authorization Failure")
}
return nil
}
func (s *PipelineUploadServer) writeErrorToResponse(w http.ResponseWriter, code int, err error) {
glog.Errorf("Failed to upload pipelines. Error: %+v", err)
w.WriteHeader(code)
errorResponse := &apiv1beta1.Error{ErrorMessage: err.Error(), ErrorDetails: fmt.Sprintf("%+v", err)}
errBytes, err := json.Marshal(errorResponse)
if err != nil {
w.Write([]byte("Error uploading pipeline"))
}
w.Write(errBytes)
}
func NewPipelineUploadServer(resourceManager *resource.ResourceManager, options *PipelineUploadServerOptions) *PipelineUploadServer {
return &PipelineUploadServer{resourceManager: resourceManager, options: options}
}