forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
winlogbeat.go
263 lines (226 loc) · 6.87 KB
/
winlogbeat.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package beater
import (
"expvar"
"fmt"
"net"
"net/http"
"path/filepath"
"sync"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/publisher"
"github.com/elastic/beats/winlogbeat/checkpoint"
"github.com/elastic/beats/winlogbeat/config"
"github.com/elastic/beats/winlogbeat/eventlog"
)
// Metrics that can retrieved through the expvar web interface. Metrics must be
// enable through configuration in order for the web service to be started.
var (
publishedEvents = expvar.NewMap("publishedEvents")
ignoredEvents = expvar.NewMap("ignoredEvents")
)
func init() {
expvar.Publish("uptime", expvar.Func(uptime))
}
// Debug logging functions for this package.
var (
debugf = logp.MakeDebug("winlogbeat")
memstatsf = logp.MakeDebug("memstats")
)
// Time the application was started.
var startTime = time.Now().UTC()
// Winlogbeat is used to conform to the beat interface
type Winlogbeat struct {
beat *beat.Beat // Common beat information.
config *config.Settings // Configuration settings.
eventLogs []eventlog.EventLog // List of all event logs being monitored.
done chan struct{} // Channel to initiate shutdown of main event loop.
client publisher.Client // Interface to publish event.
checkpoint *checkpoint.Checkpoint // Persists event log state to disk.
}
// New returns a new Winlogbeat.
func New() *Winlogbeat {
return &Winlogbeat{}
}
// Config sets up the necessary configuration to use the winlogbeat
func (eb *Winlogbeat) Config(b *beat.Beat) error {
// Read configuration.
err := b.RawConfig.Unpack(&eb.config)
if err != nil {
return fmt.Errorf("Error reading configuration file. %v", err)
}
// Validate configuration.
err = eb.config.Validate()
if err != nil {
return fmt.Errorf("Error validating configuration file. %v", err)
}
debugf("Configuration validated. config=%v", eb.config)
// Registry file grooming.
if eb.config.Winlogbeat.RegistryFile == "" {
eb.config.Winlogbeat.RegistryFile = config.DefaultRegistryFile
}
eb.config.Winlogbeat.RegistryFile, err = filepath.Abs(
eb.config.Winlogbeat.RegistryFile)
if err != nil {
return fmt.Errorf("Error getting absolute path of registry file %s. %v",
eb.config.Winlogbeat.RegistryFile, err)
}
logp.Info("State will be read from and persisted to %s",
eb.config.Winlogbeat.RegistryFile)
return nil
}
// Setup uses the loaded config and creates necessary markers and environment
// settings to allow the beat to be used.
func (eb *Winlogbeat) Setup(b *beat.Beat) error {
eb.beat = b
eb.client = b.Events
eb.done = make(chan struct{})
var err error
eb.checkpoint, err = checkpoint.NewCheckpoint(
eb.config.Winlogbeat.RegistryFile, 10, 5*time.Second)
if err != nil {
return err
}
if eb.config.Winlogbeat.Metrics.BindAddress != "" {
bindAddress := eb.config.Winlogbeat.Metrics.BindAddress
sock, err := net.Listen("tcp", bindAddress)
if err != nil {
return err
}
go func() {
logp.Info("Metrics hosted at http://%s/debug/vars", bindAddress)
err := http.Serve(sock, nil)
if err != nil {
logp.Warn("Unable to launch HTTP service for metrics. %v", err)
}
}()
}
// Create the event logs. This will validate the event log specific
// configuration.
eb.eventLogs = make([]eventlog.EventLog, 0, len(eb.config.Winlogbeat.EventLogs))
for _, config := range eb.config.Winlogbeat.EventLogs {
eventLog, err := eventlog.New(config)
if err != nil {
return fmt.Errorf("Failed to create new event log. %v", err)
}
debugf("Initialized EventLog[%s]", eventLog.Name())
eb.eventLogs = append(eb.eventLogs, eventLog)
}
return nil
}
// Run is used within the beats interface to execute the Winlogbeat workers.
func (eb *Winlogbeat) Run(b *beat.Beat) error {
persistedState := eb.checkpoint.States()
// Initialize metrics.
publishedEvents.Add("total", 0)
publishedEvents.Add("failures", 0)
ignoredEvents.Add("total", 0)
var wg sync.WaitGroup
for _, log := range eb.eventLogs {
state, _ := persistedState[log.Name()]
// Initialize per event log metrics.
publishedEvents.Add(log.Name(), 0)
ignoredEvents.Add(log.Name(), 0)
// Start a goroutine for each event log.
wg.Add(1)
go eb.processEventLog(&wg, log, state)
}
wg.Wait()
eb.checkpoint.Shutdown()
return nil
}
// Cleanup attempts to remove any files or data it may have created which should
// not be persisted.
func (eb *Winlogbeat) Cleanup(b *beat.Beat) error {
logp.Info("Dumping runtime metrics...")
expvar.Do(func(kv expvar.KeyValue) {
logf := logp.Info
if kv.Key == "memstats" {
logf = memstatsf
}
logf("%s=%s", kv.Key, kv.Value.String())
})
return nil
}
// Stop is used to tell the winlogbeat that it should cease executing.
func (eb *Winlogbeat) Stop() {
logp.Info("Stopping Winlogbeat")
if eb.done != nil {
close(eb.done)
}
}
func (eb *Winlogbeat) processEventLog(
wg *sync.WaitGroup,
api eventlog.EventLog,
state checkpoint.EventLogState,
) {
defer wg.Done()
err := api.Open(state.RecordNumber)
if err != nil {
logp.Warn("EventLog[%s] Open() error. No events will be read from "+
"this source. %v", api.Name(), err)
return
}
defer func() {
err := api.Close()
if err != nil {
logp.Warn("EventLog[%s] Close() error. %v", api.Name(), err)
return
}
}()
debugf("EventLog[%s] opened successfully", api.Name())
loop:
for {
select {
case <-eb.done:
break loop
default:
}
// Read from the event.
records, err := api.Read()
if err != nil {
logp.Warn("EventLog[%s] Read() error: %v", api.Name(), err)
break
}
debugf("EventLog[%s] Read() returned %d records", api.Name(), len(records))
if len(records) == 0 {
// TODO: Consider implementing notifications using
// NotifyChangeEventLog instead of polling.
time.Sleep(time.Second)
continue
}
events := make([]common.MapStr, 0, len(records))
for _, lr := range records {
events = append(events, lr.ToMapStr())
}
// Publish events.
numEvents := int64(len(events))
ok := eb.client.PublishEvents(events, publisher.Sync, publisher.Guaranteed)
if ok {
publishedEvents.Add("total", numEvents)
publishedEvents.Add(api.Name(), numEvents)
logp.Info("EventLog[%s] Successfully published %d events",
api.Name(), numEvents)
} else {
logp.Warn("EventLog[%s] Failed to publish %d events",
api.Name(), numEvents)
publishedEvents.Add("failures", 1)
}
eb.checkpoint.Persist(api.Name(),
records[len(records)-1].RecordID,
records[len(records)-1].TimeCreated.SystemTime.UTC())
}
}
// uptime returns a map of uptime related metrics.
func uptime() interface{} {
now := time.Now().UTC()
uptimeDur := now.Sub(startTime)
return map[string]interface{}{
"start_time": startTime,
"uptime": uptimeDur.String(),
"uptime_ms": fmt.Sprintf("%d", uptimeDur.Nanoseconds()/int64(time.Microsecond)),
"server_time": now,
}
}