-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathinput.go
347 lines (295 loc) · 9.55 KB
/
input.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
//go:build windows
package windows // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/input/windows"
import (
"context"
"errors"
"fmt"
"sync"
"time"
"go.opentelemetry.io/collector/component"
"go.uber.org/zap"
"golang.org/x/sys/windows"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper"
)
// Input is an operator that creates entries using the windows event log api.
type Input struct {
helper.InputOperator
bookmark Bookmark
buffer Buffer
channel string
maxReads int
startAt string
raw bool
excludeProviders []string
pollInterval time.Duration
persister operator.Persister
publisherCache publisherCache
cancel context.CancelFunc
wg sync.WaitGroup
subscription Subscription
remote RemoteConfig
remoteSessionHandle windows.Handle
startRemoteSession func() error
}
// newInput creates a new Input operator.
func newInput(settings component.TelemetrySettings) *Input {
basicConfig := helper.NewBasicConfig("windowseventlog", "input")
basicOperator, _ := basicConfig.Build(settings)
input := &Input{
InputOperator: helper.InputOperator{
WriterOperator: helper.WriterOperator{
BasicOperator: basicOperator,
},
},
}
input.startRemoteSession = input.defaultStartRemoteSession
return input
}
// defaultStartRemoteSession starts a remote session for reading event logs from a remote server.
func (i *Input) defaultStartRemoteSession() error {
if i.remote.Server == "" {
return nil
}
login := EvtRpcLogin{
Server: windows.StringToUTF16Ptr(i.remote.Server),
User: windows.StringToUTF16Ptr(i.remote.Username),
Password: windows.StringToUTF16Ptr(i.remote.Password),
}
sessionHandle, err := evtOpenSession(EvtRpcLoginClass, &login, 0, 0)
if err != nil {
return fmt.Errorf("failed to open session for server %s: %w", i.remote.Server, err)
}
i.remoteSessionHandle = sessionHandle
return nil
}
// stopRemoteSession stops the remote session if it is active.
func (i *Input) stopRemoteSession() error {
if i.remoteSessionHandle != 0 {
if err := evtClose(uintptr(i.remoteSessionHandle)); err != nil {
return fmt.Errorf("failed to close remote session handle for server %s: %w", i.remote.Server, err)
}
i.remoteSessionHandle = 0
}
return nil
}
// isRemote checks if the input is configured for remote access.
func (i *Input) isRemote() bool {
return i.remote.Server != ""
}
// isNonTransientError checks if the error is likely non-transient.
func isNonTransientError(err error) bool {
return errors.Is(err, windows.ERROR_EVT_CHANNEL_NOT_FOUND) || errors.Is(err, windows.ERROR_ACCESS_DENIED)
}
// Start will start reading events from a subscription.
func (i *Input) Start(persister operator.Persister) error {
ctx, cancel := context.WithCancel(context.Background())
i.cancel = cancel
i.persister = persister
if i.isRemote() {
if err := i.startRemoteSession(); err != nil {
return fmt.Errorf("failed to start remote session for server %s: %w", i.remote.Server, err)
}
}
i.bookmark = NewBookmark()
offsetXML, err := i.getBookmarkOffset(ctx)
if err != nil {
_ = i.persister.Delete(ctx, i.channel)
}
if offsetXML != "" {
if err := i.bookmark.Open(offsetXML); err != nil {
return fmt.Errorf("failed to open bookmark: %w", err)
}
}
i.publisherCache = newPublisherCache()
subscription := NewLocalSubscription()
if i.isRemote() {
subscription = NewRemoteSubscription(i.remote.Server)
}
if err := subscription.Open(i.startAt, uintptr(i.remoteSessionHandle), i.channel, i.bookmark); err != nil {
if isNonTransientError(err) {
if i.isRemote() {
return fmt.Errorf("failed to open subscription for remote server %s: %w", i.remote.Server, err)
}
return fmt.Errorf("failed to open local subscription: %w", err)
}
if i.isRemote() {
i.Logger().Warn("Transient error opening subscription for remote server, continuing", zap.String("server", i.remote.Server), zap.Error(err))
} else {
i.Logger().Warn("Transient error opening local subscription, continuing", zap.Error(err))
}
}
i.subscription = subscription
i.wg.Add(1)
go i.readOnInterval(ctx)
return nil
}
// Stop will stop reading events from a subscription.
func (i *Input) Stop() error {
i.cancel()
i.wg.Wait()
if err := i.subscription.Close(); err != nil {
return fmt.Errorf("failed to close subscription: %w", err)
}
if err := i.bookmark.Close(); err != nil {
return fmt.Errorf("failed to close bookmark: %w", err)
}
if err := i.publisherCache.evictAll(); err != nil {
return fmt.Errorf("failed to close publishers: %w", err)
}
return i.stopRemoteSession()
}
// readOnInterval will read events with respect to the polling interval.
func (i *Input) readOnInterval(ctx context.Context) {
defer i.wg.Done()
ticker := time.NewTicker(i.pollInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
i.readToEnd(ctx)
}
}
}
// readToEnd will read events from the subscription until it reaches the end of the channel.
func (i *Input) readToEnd(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
if count := i.read(ctx); count == 0 {
if i.isRemote() {
if err := i.startRemoteSession(); err != nil {
i.Logger().Error("Failed to re-establish remote session", zap.String("server", i.remote.Server), zap.Error(err))
return
}
if err := i.subscription.Open(i.startAt, uintptr(i.remoteSessionHandle), i.channel, i.bookmark); err != nil {
i.Logger().Error("Failed to re-open subscription for remote server", zap.String("server", i.remote.Server), zap.Error(err))
}
}
return
}
}
}
}
// read will read events from the subscription.
func (i *Input) read(ctx context.Context) int {
events, err := i.subscription.Read(i.maxReads)
if err != nil {
i.Logger().Error("Failed to read events from subscription", zap.Error(err))
return 0
}
for n, event := range events {
i.processEvent(ctx, event)
if len(events) == n+1 {
i.updateBookmarkOffset(ctx, event)
}
event.Close()
}
return len(events)
}
// processEvent will process and send an event retrieved from windows event log.
func (i *Input) processEvent(ctx context.Context, event Event) {
remoteServer := i.remote.Server
if i.raw {
if len(i.excludeProviders) > 0 {
simpleEvent, err := event.RenderSimple(i.buffer)
if err != nil {
i.Logger().Error("Failed to render simple event", zap.Error(err))
return
}
for _, excludeProvider := range i.excludeProviders {
if simpleEvent.Provider.Name == excludeProvider {
return
}
}
}
rawEvent, err := event.RenderRaw(i.buffer)
if err != nil {
i.Logger().Error("Failed to render raw event", zap.Error(err))
return
}
rawEvent.RemoteServer = remoteServer
i.sendEventRaw(ctx, rawEvent)
return
}
simpleEvent, err := event.RenderSimple(i.buffer)
if err != nil {
i.Logger().Error("Failed to render simple event", zap.Error(err))
return
}
simpleEvent.RemoteServer = remoteServer
for _, excludeProvider := range i.excludeProviders {
if simpleEvent.Provider.Name == excludeProvider {
return
}
}
publisher, openPublisherErr := i.publisherCache.get(simpleEvent.Provider.Name)
if openPublisherErr != nil {
i.Logger().Warn(
"Failed to open event source, respective log entries cannot be formatted",
zap.String("provider", simpleEvent.Provider.Name), zap.Error(openPublisherErr))
}
if !publisher.Valid() {
i.sendEvent(ctx, simpleEvent)
return
}
formattedEvent, err := event.RenderFormatted(i.buffer, publisher)
if err != nil {
i.Logger().Error("Failed to render formatted event", zap.Error(err))
i.sendEvent(ctx, simpleEvent)
return
}
formattedEvent.RemoteServer = remoteServer
i.sendEvent(ctx, formattedEvent)
}
// sendEvent will send EventXML as an entry to the operator's output.
func (i *Input) sendEvent(ctx context.Context, eventXML EventXML) {
body := eventXML.parseBody()
entry, err := i.NewEntry(body)
if err != nil {
i.Logger().Error("Failed to create entry", zap.Error(err))
return
}
entry.Timestamp = eventXML.parseTimestamp()
entry.Severity = eventXML.parseRenderedSeverity()
i.Write(ctx, entry)
}
// sendEventRaw will send EventRaw as an entry to the operator's output.
func (i *Input) sendEventRaw(ctx context.Context, eventRaw EventRaw) {
body := eventRaw.parseBody()
entry, err := i.NewEntry(body)
if err != nil {
i.Logger().Error("Failed to create entry", zap.Error(err))
return
}
entry.Timestamp = eventRaw.parseTimestamp()
entry.Severity = eventRaw.parseRenderedSeverity()
i.Write(ctx, entry)
}
// getBookmarkXML will get the bookmark xml from the offsets database.
func (i *Input) getBookmarkOffset(ctx context.Context) (string, error) {
bytes, err := i.persister.Get(ctx, i.channel)
return string(bytes), err
}
// updateBookmark will update the bookmark xml and save it in the offsets database.
func (i *Input) updateBookmarkOffset(ctx context.Context, event Event) {
if err := i.bookmark.Update(event); err != nil {
i.Logger().Error("Failed to update bookmark from event", zap.Error(err))
return
}
bookmarkXML, err := i.bookmark.Render(i.buffer)
if err != nil {
i.Logger().Error("Failed to render bookmark xml", zap.Error(err))
return
}
if err := i.persister.Set(ctx, i.channel, []byte(bookmarkXML)); err != nil {
i.Logger().Error("failed to set offsets", zap.Error(err))
return
}
}