/
run.go
471 lines (428 loc) · 15.1 KB
/
run.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
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 v1
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"github.com/PaddlePaddle/PaddleFlow/pkg/apiserver/common"
"github.com/PaddlePaddle/PaddleFlow/pkg/apiserver/controller/pipeline"
"github.com/PaddlePaddle/PaddleFlow/pkg/apiserver/router/util"
"github.com/PaddlePaddle/PaddleFlow/pkg/common/config"
"github.com/PaddlePaddle/PaddleFlow/pkg/common/logger"
"github.com/PaddlePaddle/PaddleFlow/pkg/metrics"
"github.com/PaddlePaddle/PaddleFlow/pkg/trace_logger"
)
type RunRouter struct{}
func (rr *RunRouter) Name() string {
return "RunRouter"
}
func (rr *RunRouter) AddRouter(r chi.Router) {
log.Info("add run router")
r.Post("/run", rr.createRun)
r.Post("/runjson", rr.createRunByJson)
r.Get("/run", rr.listRun)
r.Get("/run/{runID}", rr.getRunByID)
r.Put("/run/{runID}", rr.updateRun)
r.Delete("/run/{runID}", rr.deleteRun)
}
// createRun
// @Summary 创建运行
// @Description 创建运行
// @Id createRun
// @tags Run
// @Accept json
// @Produce json
// @Param request body run.CreateRunRequest true "创建运行请求"
// @Success 201 {object} run.CreateRunResponse "创建运行响应"
// @Failure 400 {object} common.ErrorResponse "400"
// @Failure 500 {object} common.ErrorResponse "500"
// @Router /run [POST]
func (rr *RunRouter) createRun(w http.ResponseWriter, r *http.Request) {
ctx := common.GetRequestContext(r)
requestId := ctx.RequestID
var createRunInfo pipeline.CreateRunRequest
var err error
if config.GlobalServerConfig.Metrics.Enable {
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
var errCode string
if err != nil {
errCode = strconv.Itoa(common.GetHttpStatusByCode(ctx.ErrorCode))
} else {
errCode = strconv.Itoa(http.StatusOK)
}
metrics.APiDurationSummary.With(
prometheus.Labels{
metrics.ApiNameLabel: "createRun",
metrics.RequestMethodLabel: r.Method,
metrics.ResponseCodeLabel: errCode,
}).Observe(v * 1000)
}))
defer timer.ObserveDuration()
}
if err = common.BindJSON(r, &createRunInfo); err != nil {
ctx.ErrorCode = common.MalformedJSON
logger.LoggerForRequest(&ctx).Errorf(
"create run failed parsing request body:%+v. error:%s", r.Body, err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
// add trace logger
trace_logger.Key(requestId).Infof("creating run for request:%+v", createRunInfo)
// create run
response, err := pipeline.CreateRun(&ctx, &createRunInfo, nil)
if err != nil {
errMsg := fmt.Sprintf(
"create run failed. createRunInfo:%v error:%s", createRunInfo, err.Error())
// if run id has generated, log err msg
if response.RunID != "" {
trace_logger.Key(response.RunID).Errorf(errMsg)
}
logger.LoggerForRequest(&ctx).Errorf(errMsg)
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
trace_logger.Key(response.RunID).Infof("create run complete")
common.Render(w, http.StatusCreated, response)
}
// createRunByJson
// @Summary 通过Json格式的run.yaml创建运行
// @Description 通过Json格式的run.yaml创建运行
// @Id createRunByJson
// @tags Run
// @Accept json
// @Produce json
// @Param request body run.CreateRunByJsonRequest true "创建运行请求"
// @Success 201 {object} run.CreateRunResponse "创建运行响应"
// @Failure 400 {object} common.ErrorResponse "400"
// @Failure 500 {object} common.ErrorResponse "500"
// @Router /runjson [POST]
func (rr *RunRouter) createRunByJson(w http.ResponseWriter, r *http.Request) {
ctx := common.GetRequestContext(r)
var err error
if config.GlobalServerConfig.Metrics.Enable {
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
var errCode string
if err != nil {
errCode = strconv.Itoa(common.GetHttpStatusByCode(ctx.ErrorCode))
} else {
errCode = strconv.Itoa(http.StatusOK)
}
metrics.APiDurationSummary.With(
prometheus.Labels{
metrics.ApiNameLabel: "createRunByJson",
metrics.RequestMethodLabel: r.Method,
metrics.ResponseCodeLabel: errCode,
}).Observe(v * 1000)
}))
defer timer.ObserveDuration()
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
ctx.ErrorCode = common.InvalidHTTPRequest
logger.LoggerForRequest(&ctx).Errorf(
"read body failed. error:%s", err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
// 检查 json 请求体的格式
if !json.Valid(bodyBytes) {
ctx.ErrorCode = common.MalformedJSON
errMsg := "request body json format invalid"
logger.LoggerForRequest(&ctx).Errorf(errMsg)
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, errMsg)
return
}
bodyUnstructured := unstructured.Unstructured{}
if err := bodyUnstructured.UnmarshalJSON(bodyBytes); err != nil && !runtime.IsMissingKind(err) {
// MissingKindErr不影响Json的解析
ctx.ErrorCode = common.MalformedJSON
logger.LoggerForRequest(&ctx).Errorf(
"unmarshal body failed. error:%s", err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
bodyMap := bodyUnstructured.UnstructuredContent()
trace_logger.Key(ctx.RequestID).Infof("creating run by json for request body map:%+v", bodyMap)
// create run
response, err := pipeline.CreateRunByJson(&ctx, bodyMap)
if err != nil {
if response.RunID != "" {
trace_logger.Key(response.RunID).Errorf("create run fail: %s", err)
}
logger.LoggerForRequest(&ctx).Errorf(
"create run by json failed. error:%s", err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
common.Render(w, http.StatusCreated, response)
}
// listRun
// @Summary 获取运行列表
// @Description 获取运行列表
// @Id listRun
// @tags Run
// @Accept json
// @Produce json
// @Param userFilter query string false "(root用户)用户过滤"
// @Param fsFilter query string false "存储过滤"
// @Param runFilter query string false "ID过滤"
// @Param nameFilter query string false "名称过滤"
// @Param maxKeys query int false "每页包含的最大数量,缺省值为50"
// @Param marker query string false "批量获取列表的查询的起始位置,是一个由系统生成的字符串"
// @Success 200 {object} run.ListRunResponse "获取运行列表的响应"
// @Failure 400 {object} common.ErrorResponse "400"
// @Failure 500 {object} common.ErrorResponse "500"
// @Router /run [GET]
func (rr *RunRouter) listRun(w http.ResponseWriter, r *http.Request) {
ctx := common.GetRequestContext(r)
var err error
if config.GlobalServerConfig.Metrics.Enable {
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
var errCode string
if err != nil {
errCode = strconv.Itoa(common.GetHttpStatusByCode(ctx.ErrorCode))
} else {
errCode = strconv.Itoa(http.StatusOK)
}
metrics.APiDurationSummary.With(
prometheus.Labels{
metrics.ApiNameLabel: "listRun",
metrics.RequestMethodLabel: r.Method,
metrics.ResponseCodeLabel: errCode,
}).Observe(v * 1000)
}))
defer timer.ObserveDuration()
}
marker := r.URL.Query().Get(util.QueryKeyMarker)
maxKeys, err := util.GetQueryMaxKeys(&ctx, r)
if err != nil {
common.RenderErrWithMessage(w, ctx.RequestID, common.InvalidURI, err.Error())
return
}
userNames, fsNames := r.URL.Query().Get(util.QueryKeyUserFilter), r.URL.Query().Get(util.QueryKeyFsFilter)
runIDs, names := r.URL.Query().Get(util.QueryKeyRunFilter), r.URL.Query().Get(util.QueryKeyNameFilter)
status := r.URL.Query().Get(util.QueryKeyStatusFilter)
userFilter, fsFilter, runFilter, nameFilter := make([]string, 0), make([]string, 0), make([]string, 0), make([]string, 0)
statusFilter := make([]string, 0)
if userNames != "" {
userFilter = strings.Split(userNames, common.SeparatorComma)
}
if fsNames != "" {
fsFilter = strings.Split(fsNames, common.SeparatorComma)
}
if runIDs != "" {
runFilter = strings.Split(runIDs, common.SeparatorComma)
}
if names != "" {
nameFilter = strings.Split(names, common.SeparatorComma)
}
if status != "" {
statusFilter = strings.Split(status, common.SeparatorComma)
}
logger.LoggerForRequest(&ctx).Debugf(
"user[%s] ListRun marker:[%s] maxKeys:[%d] userFilter:%v fsFilter:%v runFilter:%v nameFilter:%v",
ctx.UserName, marker, maxKeys, userFilter, fsFilter, runFilter, nameFilter)
listRunResponse, err := pipeline.ListRun(&ctx, marker, maxKeys, userFilter, fsFilter, runFilter, nameFilter, statusFilter, nil)
if err != nil {
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
common.Render(w, http.StatusOK, listRunResponse)
}
// getRunByID
// @Summary 获取运行
// @Description 获取运行
// @Id getRunByID
// @tags Run
// @Accept json
// @Produce json
// @Param runID path int true "运行ID"
// @Success 200 {object} models.Run "运行详情"
// @Failure 400 {object} common.ErrorResponse "400"
// @Failure 500 {object} common.ErrorResponse "500"
// @Router /run/{runID} [GET]
func (rr *RunRouter) getRunByID(w http.ResponseWriter, r *http.Request) {
ctx := common.GetRequestContext(r)
var err error
if config.GlobalServerConfig.Metrics.Enable {
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
var errCode string
if err != nil {
errCode = strconv.Itoa(common.GetHttpStatusByCode(ctx.ErrorCode))
} else {
errCode = strconv.Itoa(http.StatusOK)
}
metrics.APiDurationSummary.With(
prometheus.Labels{
metrics.ApiNameLabel: "getRunByID",
metrics.RequestMethodLabel: r.Method,
metrics.ResponseCodeLabel: errCode,
}).Observe(v * 1000)
}))
defer timer.ObserveDuration()
}
runID := chi.URLParam(r, util.ParamKeyRunID)
runInfo, err := pipeline.GetRunByID(&ctx, ctx.UserName, runID)
if err != nil {
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
// 优化RuntimeView结构,使显示结果更友好
runInfo.Runtime = runInfo.RemoveOuterDagView(runInfo.Runtime)
common.Render(w, http.StatusOK, runInfo)
}
// updateRun
// @Summary 修改运行
// @Description 修改运行
// @Id updateRun
// @tags Run
// @Accept json
// @Produce json
// @Param runID path int true "运行ID"
// @Param action query string true "修改动作"
// @Success 200 "修改运行成功"
// @Failure 400 {object} common.ErrorResponse "400"
// @Failure 500 {object} common.ErrorResponse "500"
// @Router /run/{runID} [PUT]
func (rr *RunRouter) updateRun(w http.ResponseWriter, r *http.Request) {
ctx := common.GetRequestContext(r)
var err error
if config.GlobalServerConfig.Metrics.Enable {
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
var errCode string
if err != nil {
errCode = strconv.Itoa(common.GetHttpStatusByCode(ctx.ErrorCode))
} else {
errCode = strconv.Itoa(http.StatusOK)
}
metrics.APiDurationSummary.With(
prometheus.Labels{
metrics.ApiNameLabel: "updateRun",
metrics.RequestMethodLabel: r.Method,
metrics.ResponseCodeLabel: errCode,
}).Observe(v * 1000)
}))
defer timer.ObserveDuration()
}
runID := chi.URLParam(r, util.ParamKeyRunID)
action := r.URL.Query().Get(util.QueryKeyAction)
logger.LoggerForRequest(&ctx).Debugf("StopRun id:%v", runID)
request := pipeline.UpdateRunRequest{}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
err = fmt.Errorf("get body err: %v", err)
common.RenderErrWithMessage(w, ctx.RequestID, common.InvalidHTTPRequest, err.Error())
return
}
if len(bodyBytes) > 0 {
// body为空的话,解析会报错
err = json.Unmarshal(bodyBytes, &request)
if err != nil {
logger.LoggerForRequest(&ctx).Errorf(
"stop run failed to unmarshal body, error:%s", err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, common.MalformedJSON, err.Error())
return
}
}
switch action {
case util.QueryActionStop:
err = pipeline.StopRun(&ctx, ctx.UserName, runID, request)
case util.QueryActionRetry:
runID, err = pipeline.RetryRun(&ctx, runID)
default:
ctx.ErrorCode = common.InvalidURI
err = fmt.Errorf("invalid action[%s] for UpdateRun", action)
common.RenderErrWithMessage(w, ctx.RequestID, common.InvalidArguments, err.Error())
return
}
if err != nil {
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
if action == util.QueryActionRetry {
rsp := pipeline.UpdateRunResponse{RunID: runID}
common.Render(w, http.StatusOK, rsp)
} else {
common.RenderStatus(w, http.StatusOK)
}
}
// deleteRun
// @Summary 删除运行
// @Description 删除运行
// @Id deleteRun
// @tags Run
// @Accept json
// @Produce json
// @Param runID path string true "运行ID"
// @Success 200 {string} string "删除运行的响应码"
// @Failure 400 {object} common.ErrorResponse "400"
// @Failure 500 {object} common.ErrorResponse "500"
// @Router /run/{runID} [DELETE]
func (rr *RunRouter) deleteRun(w http.ResponseWriter, r *http.Request) {
ctx := common.GetRequestContext(r)
var err error
if config.GlobalServerConfig.Metrics.Enable {
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
var errCode string
if err != nil {
errCode = strconv.Itoa(common.GetHttpStatusByCode(ctx.ErrorCode))
} else {
errCode = strconv.Itoa(http.StatusOK)
}
metrics.APiDurationSummary.With(
prometheus.Labels{
metrics.ApiNameLabel: "deleteRun",
metrics.RequestMethodLabel: r.Method,
metrics.ResponseCodeLabel: errCode,
}).Observe(v * 1000)
}))
defer timer.ObserveDuration()
}
runID := chi.URLParam(r, util.ParamKeyRunID)
request := pipeline.DeleteRunRequest{
CheckCache: true, // 默认为true
}
// 不能多次读取r.body,因此没法验证完body长度后再调用BindJson
bodyByte, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.LoggerForRequest(&ctx).Errorf(
"delete run failed to read request body:%+v. error:%s", r.Body, err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, common.InvalidHTTPRequest, err.Error())
return
}
if len(string(bodyByte)) > 0 {
err = json.Unmarshal(bodyByte, &request)
if err != nil {
logger.LoggerForRequest(&ctx).Errorf(
"delete run failed to unmarshal body, error:%s", err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, common.MalformedJSON, err.Error())
return
}
}
err = pipeline.DeleteRun(&ctx, runID, &request)
if err != nil {
ctx.Logging().Errorf("delete run: %s failed. error:%s", runID, err.Error())
common.RenderErrWithMessage(w, ctx.RequestID, ctx.ErrorCode, err.Error())
return
}
common.RenderStatus(w, http.StatusOK)
}