-
Notifications
You must be signed in to change notification settings - Fork 78
/
batch.go
83 lines (72 loc) · 2.09 KB
/
batch.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
package handler
import (
"github.com/gin-gonic/gin"
"github.com/juju/errors"
"github.com/loopfz/gadgeto/zesty"
"github.com/ovh/utask"
"github.com/ovh/utask/models/task"
"github.com/ovh/utask/models/tasktemplate"
)
type createBatchIn struct {
TemplateName string `json:"template_name" binding:"required"`
CommonInput map[string]interface{} `json:"common_input"`
Inputs []map[string]interface{} `json:"inputs" binding:"required"`
Comment string `json:"comment"`
WatcherTokens []string `json:"watcher_tokens"`
WatcherUsernames []string `json:"watcher_usernames"`
}
// CreateBatch handles the creation of a collection of tasks based on the same template
// one task is created for each element in the "inputs" slice
// all tasks share a common "batchID" which can be used as a listing filter on /task
func CreateBatch(c *gin.Context, in *createBatchIn) (*task.Batch, error) {
dbp, err := zesty.NewDBProvider(utask.DBName)
if err != nil {
return nil, err
}
tt, err := tasktemplate.LoadFromName(dbp, in.TemplateName)
if err != nil {
return nil, err
}
if err := dbp.Tx(); err != nil {
return nil, err
}
b, err := task.CreateBatch(dbp)
if err != nil {
dbp.Rollback()
return nil, err
}
for _, inp := range in.Inputs {
input, err := conjMap(in.CommonInput, inp)
if err != nil {
dbp.Rollback()
return nil, err
}
_, err = transactionTaskCreate(c, dbp, tt, in.WatcherUsernames, input, b, in.Comment, nil)
if err != nil {
dbp.Rollback()
return nil, err
}
}
if err := dbp.Commit(); err != nil {
dbp.Rollback()
return nil, err
}
return b, nil
}
func conjMap(common, particular map[string]interface{}) (map[string]interface{}, error) {
conj := make(map[string]interface{})
if particular != nil {
for key, value := range particular {
conj[key] = value
}
}
if common != nil {
for key, value := range common {
if _, ok := conj[key]; ok {
return nil, errors.NewBadRequest(nil, "Conflicting keys in input maps")
}
conj[key] = value
}
}
return conj, nil
}