Skip to content

Commit

Permalink
chore: Fix linter findings for Windows (part2) (#13096)
Browse files Browse the repository at this point in the history
Co-authored-by: pzak <pzak>
(cherry picked from commit 4d4bed4)
  • Loading branch information
zak-pawel authored and powersj committed May 22, 2023
1 parent a03ea24 commit 54eda9b
Show file tree
Hide file tree
Showing 12 changed files with 158 additions and 121 deletions.
8 changes: 5 additions & 3 deletions logger/event_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ type eventLogger struct {
logger *eventlog.Log
}

func (t *eventLogger) Write(b []byte) (n int, err error) {
func (t *eventLogger) Write(b []byte) (int, error) {
var err error

loc := prefixRegex.FindIndex(b)
n = len(b)
n := len(b)
if loc == nil {
err = t.logger.Info(1, string(b))
} else if n > 2 { //skip empty log messages
Expand All @@ -39,7 +41,7 @@ func (t *eventLogger) Write(b []byte) (n int, err error) {
}
}

return
return n, err
}

type eventLoggerCreator struct {
Expand Down
8 changes: 7 additions & 1 deletion logger/event_logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package logger
import (
"bytes"
"encoding/xml"
"fmt"
"log"
"os/exec"
"testing"
Expand All @@ -30,7 +31,12 @@ type Event struct {
func getEventLog(t *testing.T, since time.Time) []Event {
timeStr := since.UTC().Format(time.RFC3339)
timeStr = timeStr[:19]
cmd := exec.Command("wevtutil", "qe", "Application", "/rd:true", "/q:Event[System[TimeCreated[@SystemTime >= '"+timeStr+"'] and Provider[@Name='telegraf']]]")
args := []string{
"qe",
"Application",
"/rd:true",
fmt.Sprintf("/q:Event[System[TimeCreated[@SystemTime >= %q] and Provider[@Name='telegraf']]]", timeStr)}
cmd := exec.Command("wevtutil", args...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
Expand Down
8 changes: 4 additions & 4 deletions plugins/inputs/win_eventlog/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func DecodeUTF16(b []byte) ([]byte, error) {
// GetFromSnapProcess finds information about process by the given pid
// Returns process parent pid, threads info handle and process name
func GetFromSnapProcess(pid uint32) (uint32, uint32, string, error) {
snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, uint32(pid))
snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, pid)
if err != nil {
return 0, 0, "", err
}
Expand All @@ -56,9 +56,9 @@ func GetFromSnapProcess(pid uint32) (uint32, uint32, string, error) {
return 0, 0, "", err
}
for {
if pe32.ProcessID == uint32(pid) {
if pe32.ProcessID == pid {
szexe := windows.UTF16ToString(pe32.ExeFile[:])
return uint32(pe32.ParentProcessID), uint32(pe32.Threads), szexe, nil
return pe32.ParentProcessID, pe32.Threads, szexe, nil
}
if err = windows.Process32Next(snap, &pe32); err != nil {
break
Expand Down Expand Up @@ -139,7 +139,7 @@ func walkXML(nodes []xmlnode, parents []string, separator string, f func(xmlnode
// by adding _<num> if there are several of them
func UniqueFieldNames(fields []EventField, fieldsUsage map[string]int, separator string) []EventField {
var fieldsCounter = map[string]int{}
var fieldsUnique []EventField
fieldsUnique := make([]EventField, 0, len(fields))
for _, field := range fields {
fieldName := field.Name
if fieldsUsage[field.Name] > 1 {
Expand Down
12 changes: 6 additions & 6 deletions plugins/inputs/win_eventlog/win_eventlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,13 @@ func (w *WinEventLog) Gather(acc telegraf.Accumulator) error {
return err
}

for _, event := range events {
for i := range events {
// Prepare fields names usage counter
var fieldsUsage = map[string]int{}

tags := map[string]string{}
fields := map[string]interface{}{}
event := events[i]
evt := reflect.ValueOf(&event).Elem()
timeStamp := time.Now()
// Walk through all fields of Event struct to process System tags or fields
Expand Down Expand Up @@ -403,17 +404,16 @@ func (w *WinEventLog) renderEvent(eventHandle EvtHandle) (Event, error) {
return event, err
}

err = xml.Unmarshal([]byte(eventXML), &event)
err = xml.Unmarshal(eventXML, &event)
if err != nil {
// We can return event without most text values,
// that way we will not loose information
//nolint:nilerr // We can return event without most text values, that way we will not lose information
// This can happen when processing Forwarded Events
return event, nil
}

// Do resolve local messages the usual way, while using built-in information for events forwarded by WEC.
// This is a safety measure as the underlying Windows-internal EvtFormatMessage might segfault in cases
// where the publisher (i.e. the remote machine which forwared the event) is unavailable e.g. due to
// where the publisher (i.e. the remote machine which forwarded the event) is unavailable e.g. due to
// a reboot. See https://github.com/influxdata/telegraf/issues/12328 for the full story.
if event.RenderingInfo == nil {
return w.renderLocalMessage(event, eventHandle)
Expand All @@ -426,7 +426,7 @@ func (w *WinEventLog) renderEvent(eventHandle EvtHandle) (Event, error) {
func (w *WinEventLog) renderLocalMessage(event Event, eventHandle EvtHandle) (Event, error) {
publisherHandle, err := openPublisherMetadata(0, event.Source.Name, w.Locale)
if err != nil {
return event, nil
return event, nil //nolint:nilerr // We can return event without most values
}
defer _EvtClose(publisherHandle)

Expand Down
87 changes: 43 additions & 44 deletions plugins/inputs/win_eventlog/zsyscall_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,18 @@ type EvtFormatMessageFlag uint32
// EVT_FORMAT_MESSAGE_FLAGS enumeration
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa385525(v=vs.85).aspx
const (
//revive:disable:var-naming
// Format the event's message string.
// EvtFormatMessageEvent - Format the event's message string.
EvtFormatMessageEvent EvtFormatMessageFlag = iota + 1
// Format the message string of the level specified in the event.
// EvtFormatMessageLevel - Format the message string of the level specified in the event.
EvtFormatMessageLevel
// Format the message string of the task specified in the event.
// EvtFormatMessageTask - Format the message string of the task specified in the event.
EvtFormatMessageTask
// Format the message string of the task specified in the event.
// EvtFormatMessageOpcode - Format the message string of the task specified in the event.
EvtFormatMessageOpcode
// Format the message string of the keywords specified in the event. If the
// event specifies multiple keywords, the formatted string is a list of
// null-terminated strings. Increment through the strings until your pointer
// points past the end of the used buffer.
// EvtFormatMessageKeyword - Format the message string of the keywords specified in the event. If the
// event specifies multiple keywords, the formatted string is a list of null-terminated strings.
// Increment through the strings until your pointer points past the end of the used buffer.
EvtFormatMessageKeyword
//revive:enable:var-naming
)

// errnoErr returns common boxed Errno values, to prevent
Expand Down Expand Up @@ -88,29 +85,29 @@ func _EvtSubscribe(
context uintptr,
callback syscall.Handle,
flags EvtSubscribeFlag,
) (handle EvtHandle, err error) {
r0, _, e1 := syscall.Syscall9(
) (EvtHandle, error) {
r0, _, e1 := syscall.SyscallN(
procEvtSubscribe.Addr(),
8,
uintptr(session),
uintptr(signalEvent),
signalEvent,
uintptr(unsafe.Pointer(channelPath)), //nolint:gosec // G103: Valid use of unsafe call to pass channelPath
uintptr(unsafe.Pointer(query)), //nolint:gosec // G103: Valid use of unsafe call to pass query
uintptr(bookmark),
uintptr(context),
context,
uintptr(callback),
uintptr(flags),
0,
)
handle = EvtHandle(r0)

var err error
handle := EvtHandle(r0)
if handle == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
return handle, err
}

func _EvtRender(
Expand All @@ -121,61 +118,62 @@ func _EvtRender(
buffer *byte,
bufferUsed *uint32,
propertyCount *uint32,
) (err error) {
r1, _, e1 := syscall.Syscall9(
) error {
r1, _, e1 := syscall.SyscallN(
procEvtRender.Addr(),
7,
uintptr(context),
uintptr(fragment),
uintptr(flags),
uintptr(bufferSize),
uintptr(unsafe.Pointer(buffer)), //nolint:gosec // G103: Valid use of unsafe call to pass buffer
uintptr(unsafe.Pointer(bufferUsed)), //nolint:gosec // G103: Valid use of unsafe call to pass bufferUsed
uintptr(unsafe.Pointer(propertyCount)), //nolint:gosec // G103: Valid use of unsafe call to pass propertyCount
0,
0,
)

var err error
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
return err
}

func _EvtClose(object EvtHandle) (err error) {
r1, _, e1 := syscall.Syscall(procEvtClose.Addr(), 1, uintptr(object), 0, 0)
func _EvtClose(object EvtHandle) error {
r1, _, e1 := syscall.SyscallN(procEvtClose.Addr(), uintptr(object))
var err error
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
return err
}

func _EvtNext(resultSet EvtHandle, eventArraySize uint32, eventArray *EvtHandle, timeout uint32, flags uint32, numReturned *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(
func _EvtNext(resultSet EvtHandle, eventArraySize uint32, eventArray *EvtHandle, timeout uint32, flags uint32, numReturned *uint32) error {
r1, _, e1 := syscall.SyscallN(
procEvtNext.Addr(),
6,
uintptr(resultSet),
uintptr(eventArraySize),
uintptr(unsafe.Pointer(eventArray)), //nolint:gosec // G103: Valid use of unsafe call to pass eventArray
uintptr(timeout),
uintptr(flags),
uintptr(unsafe.Pointer(numReturned)), //nolint:gosec // G103: Valid use of unsafe call to pass numReturned
)

var err error
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
return err
}

func _EvtFormatMessage(
Expand All @@ -188,55 +186,56 @@ func _EvtFormatMessage(
bufferSize uint32,
buffer *byte,
bufferUsed *uint32,
) (err error) {
r1, _, e1 := syscall.Syscall9(
) error {
r1, _, e1 := syscall.SyscallN(
procEvtFormatMessage.Addr(),
9,
uintptr(publisherMetadata),
uintptr(event),
uintptr(messageID),
uintptr(valueCount),
uintptr(values),
values,
uintptr(flags),
uintptr(bufferSize),
uintptr(unsafe.Pointer(buffer)), //nolint:gosec // G103: Valid use of unsafe call to pass buffer
uintptr(unsafe.Pointer(bufferUsed)), //nolint:gosec // G103: Valid use of unsafe call to pass bufferUsed
)

var err error
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
return err
}

func _EvtOpenPublisherMetadata(session EvtHandle, publisherIdentity *uint16, logFilePath *uint16, locale uint32, flags uint32) (handle EvtHandle, err error) {
r0, _, e1 := syscall.Syscall6(
func _EvtOpenPublisherMetadata(session EvtHandle, publisherIdentity *uint16, logFilePath *uint16, locale uint32, flags uint32) (EvtHandle, error) {
r0, _, e1 := syscall.SyscallN(
procEvtOpenPublisherMetadata.Addr(),
5,
uintptr(session),
uintptr(unsafe.Pointer(publisherIdentity)), //nolint:gosec // G103: Valid use of unsafe call to pass publisherIdentity
uintptr(unsafe.Pointer(logFilePath)), //nolint:gosec // G103: Valid use of unsafe call to pass logFilePath
uintptr(locale),
uintptr(flags),
0,
)
handle = EvtHandle(r0)

var err error
handle := EvtHandle(r0)
if handle == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
return handle, err
}

func _EvtCreateBookmark(bookmarkXML *uint16) (EvtHandle, error) {
//nolint:gosec // G103: Valid use of unsafe call to pass bookmarkXML
r0, _, e1 := syscall.Syscall(procEvtCreateBookmark.Addr(), 1, uintptr(unsafe.Pointer(bookmarkXML)), 0, 0)
r0, _, e1 := syscall.SyscallN(procEvtCreateBookmark.Addr(), uintptr(unsafe.Pointer(bookmarkXML)))
handle := EvtHandle(r0)
if handle != 0 {
return handle, nil
Expand All @@ -248,7 +247,7 @@ func _EvtCreateBookmark(bookmarkXML *uint16) (EvtHandle, error) {
}

func _EvtUpdateBookmark(bookmark, event EvtHandle) error {
r0, _, e1 := syscall.Syscall(procEvtUpdateBookmark.Addr(), 2, uintptr(bookmark), uintptr(event), 0)
r0, _, e1 := syscall.SyscallN(procEvtUpdateBookmark.Addr(), uintptr(bookmark), uintptr(event))
if r0 != 0 {
return nil
}
Expand Down
Loading

0 comments on commit 54eda9b

Please sign in to comment.