-
Notifications
You must be signed in to change notification settings - Fork 1
/
watcher.go
145 lines (118 loc) · 2.52 KB
/
watcher.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
package outis
import (
"context"
"fmt"
"os"
"os/signal"
"reflect"
"runtime"
"syscall"
"time"
)
// ID defines the type of identifier
type ID string
// ToString return the identifier as a string
func (id ID) ToString() string {
return string(id)
}
// Watch defines the type of the watcher structure
type Watch struct {
Id ID `json:"id"`
Name string `json:"name"`
RunAt time.Time `json:"run_at"`
outis IOutis
log ILogger
}
// Watcher initializes a new watcher
func Watcher(id, name string, opts ...WatcherOption) *Watch {
watch := &Watch{
Id: ID(id),
Name: name,
log: setupLogger(),
outis: newOutis(),
RunAt: time.Now(),
}
for _, opt := range opts {
opt(watch)
}
return watch
}
// Wait method responsible for keeping routines running
func (watch *Watch) Wait() {
if err := watch.outis.Wait(); err != nil {
watch.log.Errorf("%s", err.Error())
return
}
}
// Wait responsible for keeping routines running
func Wait() {
wait := make(chan os.Signal, 1)
signal.Notify(wait, syscall.SIGINT, syscall.SIGTERM)
for range wait {
return
}
}
// Go create a new routine in the watcher
func (watch *Watch) Go(opts ...Option) {
watch.outis.Go(func() error {
ctx := &Context{
indicator: make([]*indicator, 0),
metadata: make(Metadata),
log: watch.log,
Interval: time.Minute,
RunAt: time.Now(),
Watcher: *watch,
context: context.Background(),
}
for _, opt := range opts {
opt(ctx)
}
if err := ctx.validate(); err != nil {
return err
}
info := runtime.FuncForPC(reflect.ValueOf(ctx.script).Pointer())
file, line := info.FileLine(info.Entry())
ctx.Path = fmt.Sprintf("%s:%v", file, line)
if err := watch.outis.Init(ctx); err != nil {
return err
}
defer func() {
if r := recover(); r != nil {
ctx.log.Panicf(fmt.Sprintf("%v", r))
}
}()
if ctx.notUseLoop {
return ctx.execute()
}
ticker := time.NewTicker(ctx.Interval)
defer ticker.Stop()
for range ticker.C {
if err := ctx.execute(); err != nil {
ctx.log.Errorf(err.Error())
continue
}
}
return nil
})
}
func (ctx *Context) execute() error {
now := time.Now()
ctx.sleep(now)
defer func() {
if r := recover(); r != nil {
ctx.log.Panicf(fmt.Sprintf("%v", r))
}
}()
if err := ctx.Watcher.outis.Before(ctx); err != nil {
return err
}
if err := ctx.script(ctx); err != nil {
return err
}
ctx.latency = time.Since(now)
if err := ctx.Watcher.outis.After(ctx); err != nil {
return err
}
ctx.metrics(&ctx.Watcher, now)
return nil
}