-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathtask.go
More file actions
86 lines (72 loc) · 1.78 KB
/
Copy pathtask.go
File metadata and controls
86 lines (72 loc) · 1.78 KB
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
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package build
import (
"sync"
"errors"
"fmt"
"github.com/dreamans/syncd/util/command"
)
type buildTask struct {
builds map[int]*Build
mu sync.Mutex
}
type CallbackFn func(int, string, *Result, []*command.TaskResult)
var task = &buildTask{
builds: make(map[int]*Build),
}
func NewTask(id int, build *Build, fn CallbackFn) error {
if exists := task.exists(id); exists {
return fmt.Errorf("build task [id: %d] have exists", id)
}
task.append(id, build)
go func() {
build.Run()
task.remove(id)
if fn != nil {
fn(id, build.PackRealFile(), build.Result(), build.Output())
}
}()
return nil
}
func StopTask(id int) {
task.stop(id)
}
func StatusTask(id int) (*Result, []*command.TaskResult, error) {
build, exists := task.get(id)
if !exists {
return nil, nil, fmt.Errorf("build task [id: %d] not exists", id)
}
return build.Result(), build.Output(), nil
}
func (t *buildTask) exists(id int) bool {
t.mu.Lock()
defer t.mu.Unlock()
_, exists := t.builds[id]
return exists
}
func (t *buildTask) append(id int, build *Build) {
t.mu.Lock()
defer t.mu.Unlock()
t.builds[id] = build
}
func (t *buildTask) remove(id int) {
t.mu.Lock()
defer t.mu.Unlock()
delete(t.builds, id)
}
func (t *buildTask) get(id int) (*Build, bool) {
t.mu.Lock()
defer t.mu.Unlock()
build, exists := t.builds[id]
return build, exists
}
func (t *buildTask) stop(id int) {
t.mu.Lock()
defer t.mu.Unlock()
build, exists := t.builds[id]
if exists {
build.Terminate()
}
}