-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
105 lines (94 loc) · 2.13 KB
/
monitor.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
package iote
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"time"
)
const persistDir = "log"
type Worker func(context.Context, int, chan<- error)
type EventMonitor struct {
Name string
Entity EventEntity
entityChan chan EventEntity
Inspectors []EventInspector
WorkerCreate chan int
}
func (em *EventMonitor) CreateChan(size int) {
em.entityChan = make(chan EventEntity, size)
em.WorkerCreate = make(chan int, 1)
}
func (em *EventMonitor) GetHandler() http.HandlerFunc {
etp := reflect.TypeOf(em.Entity)
if etp.Kind() == reflect.Ptr {
etp = etp.Elem()
}
return func(w http.ResponseWriter, req *http.Request) {
b, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, err.Error())
return
}
e := reflect.New(etp).Interface().(EventEntity)
err = e.ParseBinary(b)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, err.Error())
return
}
em.entityChan <- e
fmt.Fprintf(w, em.Name+" ok")
}
}
func (em *EventMonitor) GetWorker(prefix string) Worker {
etp := reflect.TypeOf(em.Entity)
if etp.Kind() == reflect.Ptr {
etp = etp.Elem()
}
if _, err := os.Stat(persistDir); os.IsNotExist(err) {
os.Mkdir(persistDir, os.ModeDir)
}
return func(ctx context.Context, index int, errChan chan<- error) {
pattern := fmt.Sprintf("%s_%d_%s", prefix, index, etp.Name())
f, err := ioutil.TempFile(persistDir, pattern)
if err != nil {
errChan <- err
return
}
timer := time.NewTimer(5*time.Hour + time.Duration(index)*time.Minute)
defer f.Sync()
defer f.Close()
defer timer.Stop()
for e := range em.entityChan {
select {
case <-ctx.Done():
em.entityChan <- e
return
case <-timer.C:
em.WorkerCreate <- index
em.entityChan <- e
return
default:
go func(entity EventEntity) {
for _, i := range em.Inspectors {
i.Inspect(entity, errChan)
}
}(e)
b, err := json.Marshal(e)
if err != nil {
errChan <- err
}
b = append(b, []byte("\n")...)
_, err = f.Write(b)
if err != nil {
errChan <- err
}
}
}
}
}