-
Notifications
You must be signed in to change notification settings - Fork 12
/
util.go
100 lines (82 loc) · 1.61 KB
/
util.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
package swim
import (
"context"
"errors"
"net"
"strconv"
"sync/atomic"
"github.com/DE-labtory/iLogger"
)
type status = int32
const (
AVAILABLE status = iota
DIE
)
type Task func() (interface{}, error)
type TaskResponse struct {
payload interface{}
err error
}
type TaskRunner struct {
task Task
ctx context.Context
stopFlag int32
}
func NewTaskRunner(task Task, ctx context.Context) *TaskRunner {
return &TaskRunner{
task: task,
ctx: ctx,
}
}
func (t *TaskRunner) stop() {
atomic.CompareAndSwapInt32(&t.stopFlag, AVAILABLE, DIE)
}
func (t *TaskRunner) toDie() bool {
return atomic.LoadInt32(&(t.stopFlag)) == DIE
}
func (t *TaskRunner) Start() TaskResponse {
done := make(chan TaskResponse)
defer func() {
t.stop()
}()
go func() {
result, err := t.task()
if t.toDie() {
return
}
if err != nil {
iLogger.Errorf(nil, "[TaskRunner] error occured: [%s]", err.Error())
done <- TaskResponse{
payload: nil,
err: err,
}
return
}
done <- TaskResponse{
payload: result,
err: nil,
}
}()
select {
case resp := <-done:
return resp
case <-t.ctx.Done():
iLogger.Infof(nil, "[TaskRunner] receive cancel signal, quit")
return TaskResponse{}
}
}
func ParseHostPort(address string) (net.IP, uint16, error) {
shost, sport, err := net.SplitHostPort(address)
if err != nil {
return net.IP{}, 0, err
}
host := net.ParseIP(shost)
if net.IP(nil).Equal(host) {
return net.IP{}, 0, errors.New("invalid ip format")
}
port, err := strconv.ParseUint(sport, 10, 16)
if err != nil {
return net.IP{}, 0, err
}
return host, uint16(port), nil
}