forked from rexray/rexray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
services_task.go
292 lines (239 loc) · 6.18 KB
/
services_task.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
package services
import (
"encoding/json"
"fmt"
"sync"
"time"
log "github.com/sirupsen/logrus"
gofig "github.com/akutz/gofig/types"
"github.com/akutz/goof"
"github.com/rexray/rexray/libstorage/api/context"
"github.com/rexray/rexray/libstorage/api/types"
"github.com/rexray/rexray/libstorage/api/utils/schema"
)
type task struct {
types.Task
ctx types.Context
runFunc types.TaskRunFunc
storRunFunc types.StorageTaskRunFunc
storService types.StorageService
resultSchema []byte
resultSchemaValidationEnabled bool
done chan int
}
func newTask(ctx types.Context, schema []byte) *task {
t := getTaskService(ctx).taskTrack(ctx)
t.resultSchema = schema
t.done = make(chan int)
return t
}
func newGenericTask(
ctx types.Context,
run types.TaskRunFunc,
schema []byte) *task {
t := newTask(ctx, schema)
t.runFunc = run
return t
}
func newStorageServiceTask(
ctx types.Context,
run types.StorageTaskRunFunc,
svc types.StorageService,
schema []byte) *task {
t := newTask(ctx, schema)
t.storRunFunc = run
t.storService = svc
return t
}
func execTask(t *task) {
defer func() {
t.CompleteTime = time.Now().Unix()
if t.Error != nil {
t.ctx.Error(t.Error)
t.State = types.TaskStateError
} else {
t.State = types.TaskStateSuccess
}
close(t.done)
t.ctx.Debug("task completed")
}()
t.State = types.TaskStateRunning
t.StartTime = time.Now().Unix()
t.ctx.Info("executing task")
if t.storRunFunc != nil && t.storService != nil {
t.Result, t.Error = t.storRunFunc(t.ctx, t.storService)
} else if t.runFunc != nil {
t.Result, t.Error = t.runFunc(t.ctx)
} else {
t.Error = goof.New("invalid task")
}
if t.Error != nil {
return
}
if t.Result == nil {
t.ctx.Debug("skipping response schema validation; result == nil")
return
}
if t.resultSchema == nil {
t.ctx.Debug("skipping response schema validation; schema == nil")
return
}
if !t.resultSchemaValidationEnabled {
t.ctx.Debug("skipping response schema validation; disabled")
return
}
var buf []byte
if buf, t.Error = json.Marshal(t.Result); t.Error != nil {
return
}
t.Error = schema.Validate(t.ctx, t.resultSchema, buf)
if t.Error != nil {
return
}
}
type globalTaskService struct {
sync.RWMutex
name string
config gofig.Config
tasks map[int]*task
resultSchemaValidationEnabled bool
}
// Init initializes the service.
func (s *globalTaskService) Init(ctx types.Context, config gofig.Config) error {
s.tasks = map[int]*task{}
s.config = config
s.resultSchemaValidationEnabled = config.GetBool(
types.ConfigSchemaResponseValidationEnabled)
ctx.WithField("enabled", s.resultSchemaValidationEnabled).Debug(
"configured result schema validation")
return nil
}
func (s *globalTaskService) Name() string {
return s.name
}
// Tasks returns a channel on which all tasks are received.
func (s *globalTaskService) Tasks() <-chan *types.Task {
tasks := []*types.Task{}
s.RLock()
for _, v := range s.tasks {
tasks = append(tasks, &v.Task)
}
s.RUnlock()
c := make(chan *types.Task)
go func() {
for _, t := range tasks {
c <- t
}
close(c)
}()
return c
}
// TaskTrack creates a new, trackable task.
func (s *globalTaskService) TaskTrack(ctx types.Context) *types.Task {
return &s.taskTrack(ctx).Task
}
func (s *globalTaskService) taskTrack(ctx types.Context) *task {
now := time.Now().Unix()
s.RLock()
taskID := len(s.tasks)
s.RUnlock()
t := &task{
Task: types.Task{
ID: taskID,
QueueTime: now,
},
resultSchemaValidationEnabled: s.resultSchemaValidationEnabled,
ctx: ctx.WithValue(context.TaskKey, fmt.Sprintf("%d", taskID)),
}
s.Lock()
s.tasks[taskID] = t
s.Unlock()
return t
}
// TaskExecute enqueues a task for execution.
func (s *globalTaskService) TaskEnqueue(
ctx types.Context,
run types.TaskRunFunc,
schema []byte) *types.Task {
t := newGenericTask(ctx, run, schema)
go func() { execTask(t) }()
return &t.Task
}
// TaskInspect returns the task with the specified ID.
func (s *globalTaskService) TaskInspect(taskID int) *types.Task {
s.RLock()
defer s.RUnlock()
if t, ok := s.tasks[taskID]; ok {
return &t.Task
}
return nil
}
// TaskWait blocks until the specified task is completed.
func (s *globalTaskService) TaskWait(taskID int) {
<-s.TaskWaitC(taskID)
}
// TaskWait returns a channel that is closed only when the specified task is
// completed.
func (s *globalTaskService) TaskWaitC(taskID int) <-chan int {
c := make(chan int)
go func() {
defer close(c)
s.RLock()
t, ok := s.tasks[taskID]
s.RUnlock()
if !ok {
return
}
// remove the task from the queue after a configured about of time
defer s.taskRemoveAfter(t)
// signal that the task is complete
<-t.done
}()
return c
}
// taskRemoveAfter tells the task service to remove the task after the duration
// specified by `libstorage.server.tasks.logTimeout`.
func (s *globalTaskService) taskRemoveAfter(t *task) {
go func() {
logTimeoutDur, err := time.ParseDuration(
s.config.GetString(types.ConfigServerTasksLogTimeout))
if err != nil {
logTimeoutDur = time.Duration(time.Second * 60)
}
// wait to remove the task
time.Sleep(logTimeoutDur)
// sync access to the task map for querying its size before and after
// executing the delete operation on it
s.Lock()
defer s.Unlock()
t.ctx.WithFields(log.Fields{
"removedAfter": logTimeoutDur,
"tasksLen": len(s.tasks),
}).Debug("removing task")
// delete the task
delete(s.tasks, t.ID)
t.ctx.WithField("tasksLen", len(s.tasks)).Debug("removed task")
}()
}
// TaskWaitAll blocks until all the specified task are complete.
func (s *globalTaskService) TaskWaitAll(taskIDs ...int) {
<-s.TaskWaitAllC(taskIDs...)
}
// TaskWaitAllC returns a channel that is closed only when all the specified
// tasks are completed.
func (s *globalTaskService) TaskWaitAllC(taskIDs ...int) <-chan int {
c := make(chan int)
go func() {
defer close(c)
wg := &sync.WaitGroup{}
for _, tid := range taskIDs {
wg.Add(1)
go func(tid int) {
s.TaskWait(tid)
wg.Done()
}(tid)
}
wg.Wait()
}()
return c
}