/
events.go
134 lines (111 loc) · 2.39 KB
/
events.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
package session
import (
"fmt"
"os"
"sort"
"sync"
"time"
"github.com/bettercap/bettercap/core"
)
type Event struct {
Tag string `json:"tag"`
Time time.Time `json:"time"`
Data interface{} `json:"data"`
}
type LogMessage struct {
Level int
Message string
}
func NewEvent(tag string, data interface{}) Event {
return Event{
Tag: tag,
Time: time.Now(),
Data: data,
}
}
func (e Event) Label() string {
log := e.Data.(LogMessage)
label := core.LogLabels[log.Level]
color := core.LogColors[log.Level]
return color + label + core.RESET
}
type EventPool struct {
sync.Mutex
debug bool
silent bool
events []Event
listeners []chan Event
}
func NewEventPool(debug bool, silent bool) *EventPool {
return &EventPool{
debug: debug,
silent: silent,
events: make([]Event, 0),
listeners: make([]chan Event, 0),
}
}
func (p *EventPool) Listen() <-chan Event {
p.Lock()
defer p.Unlock()
l := make(chan Event)
p.listeners = append(p.listeners, l)
return l
}
func (p *EventPool) SetSilent(s bool) {
p.Lock()
defer p.Unlock()
p.silent = s
}
func (p *EventPool) SetDebug(d bool) {
p.Lock()
defer p.Unlock()
p.debug = d
}
func (p *EventPool) Add(tag string, data interface{}) {
p.Lock()
defer p.Unlock()
e := NewEvent(tag, data)
p.events = append([]Event{e}, p.events...)
// broadcast the event to every listener
for _, l := range p.listeners {
select {
case l <- e:
// NOTE: Without this 'default', errors in sending the event
// to the listener would not empty the channel, therefore
// all operations would be stuck at some point (after the first
// event if not buffered or after the first N events if buffered)
//
// See https://github.com/bettercap/bettercap/issues/198
default:
}
}
}
func (p *EventPool) Log(level int, format string, args ...interface{}) {
if level == core.DEBUG && p.debug == false {
return
} else if level < core.ERROR && p.silent == true {
return
}
message := fmt.Sprintf(format, args...)
p.Add("sys.log", LogMessage{
level,
message,
})
if level == core.FATAL {
fmt.Fprintf(os.Stderr, "%s\n", message)
os.Exit(1)
}
}
func (p *EventPool) Clear() {
p.Lock()
defer p.Unlock()
p.events = make([]Event, 0)
}
func (p *EventPool) Sorted() []Event {
p.Lock()
defer p.Unlock()
sort.Slice(p.events, func(i, j int) bool {
return p.events[i].Time.Before(p.events[j].Time)
})
return p.events
}