chore: Fix linter findings for Windows (part3) (#13143)

This commit is contained in:
Paweł Żak 2023-05-04 18:14:36 +02:00 committed by GitHub
parent 8396f1a00d
commit 7919405cfd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 638 additions and 846 deletions

View File

@ -36,38 +36,21 @@ import (
"syscall"
)
type SYSTEMTIME struct {
wYear uint16
wMonth uint16
wDayOfWeek uint16
wDay uint16
wHour uint16
wMinute uint16
wSecond uint16
wMilliseconds uint16
}
type FILETIME struct {
type fileTime struct {
dwLowDateTime uint32
dwHighDateTime uint32
}
var (
// Library
libkrnDll *syscall.DLL
libKernelDll *syscall.DLL
// Functions
krn_FileTimeToSystemTime *syscall.Proc
krn_FileTimeToLocalFileTime *syscall.Proc
krn_LocalFileTimeToFileTime *syscall.Proc
krn_WideCharToMultiByte *syscall.Proc
kernelLocalFileTimeToFileTime *syscall.Proc
)
func init() {
libkrnDll = syscall.MustLoadDLL("Kernel32.dll")
libKernelDll = syscall.MustLoadDLL("Kernel32.dll")
krn_FileTimeToSystemTime = libkrnDll.MustFindProc("FileTimeToSystemTime")
krn_FileTimeToLocalFileTime = libkrnDll.MustFindProc("FileTimeToLocalFileTime")
krn_LocalFileTimeToFileTime = libkrnDll.MustFindProc("LocalFileTimeToFileTime")
krn_WideCharToMultiByte = libkrnDll.MustFindProc("WideCharToMultiByte")
kernelLocalFileTimeToFileTime = libKernelDll.MustFindProc("LocalFileTimeToFileTime")
}

View File

@ -44,10 +44,10 @@ import (
// Error codes
const (
ERROR_SUCCESS = 0
ERROR_FAILURE = 1
ERROR_INVALID_FUNCTION = 1
EPOCH_DIFFERENCE_MICROS int64 = 11644473600000000
ErrorSuccess = 0
ErrorFailure = 1
ErrorInvalidFunction = 1
EpochDifferenceMicros int64 = 11644473600000000
)
type (
@ -57,249 +57,249 @@ type (
// PDH error codes, which can be returned by all Pdh* functions. Taken from mingw-w64 pdhmsg.h
const (
PDH_CSTATUS_VALID_DATA = 0x00000000 // The returned data is valid.
PDH_CSTATUS_NEW_DATA = 0x00000001 // The return data value is valid and different from the last sample.
PDH_CSTATUS_NO_MACHINE = 0x800007D0 // Unable to connect to the specified computer, or the computer is offline.
PDH_CSTATUS_NO_INSTANCE = 0x800007D1
PDH_MORE_DATA = 0x800007D2 // The PdhGetFormattedCounterArray* function can return this if there's 'more data to be displayed'.
PDH_CSTATUS_ITEM_NOT_VALIDATED = 0x800007D3
PDH_RETRY = 0x800007D4
PDH_NO_DATA = 0x800007D5 // The query does not currently contain any counters (for example, limited access)
PDH_CALC_NEGATIVE_DENOMINATOR = 0x800007D6
PDH_CALC_NEGATIVE_TIMEBASE = 0x800007D7
PDH_CALC_NEGATIVE_VALUE = 0x800007D8
PDH_DIALOG_CANCELLED = 0x800007D9
PDH_END_OF_LOG_FILE = 0x800007DA
PDH_ASYNC_QUERY_TIMEOUT = 0x800007DB
PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE = 0x800007DC
PDH_CSTATUS_NO_OBJECT = 0xC0000BB8
PDH_CSTATUS_NO_COUNTER = 0xC0000BB9 // The specified counter could not be found.
PDH_CSTATUS_INVALID_DATA = 0xC0000BBA // The counter was successfully found, but the data returned is not valid.
PDH_MEMORY_ALLOCATION_FAILURE = 0xC0000BBB
PDH_INVALID_HANDLE = 0xC0000BBC
PDH_INVALID_ARGUMENT = 0xC0000BBD // Required argument is missing or incorrect.
PDH_FUNCTION_NOT_FOUND = 0xC0000BBE
PDH_CSTATUS_NO_COUNTERNAME = 0xC0000BBF
PDH_CSTATUS_BAD_COUNTERNAME = 0xC0000BC0 // Unable to parse the counter path. Check the format and syntax of the specified path.
PDH_INVALID_BUFFER = 0xC0000BC1
PDH_INSUFFICIENT_BUFFER = 0xC0000BC2
PDH_CANNOT_CONNECT_MACHINE = 0xC0000BC3
PDH_INVALID_PATH = 0xC0000BC4
PDH_INVALID_INSTANCE = 0xC0000BC5
PDH_INVALID_DATA = 0xC0000BC6 // specified counter does not contain valid data or a successful status code.
PDH_NO_DIALOG_DATA = 0xC0000BC7
PDH_CANNOT_READ_NAME_STRINGS = 0xC0000BC8
PDH_LOG_FILE_CREATE_ERROR = 0xC0000BC9
PDH_LOG_FILE_OPEN_ERROR = 0xC0000BCA
PDH_LOG_TYPE_NOT_FOUND = 0xC0000BCB
PDH_NO_MORE_DATA = 0xC0000BCC
PDH_ENTRY_NOT_IN_LOG_FILE = 0xC0000BCD
PDH_DATA_SOURCE_IS_LOG_FILE = 0xC0000BCE
PDH_DATA_SOURCE_IS_REAL_TIME = 0xC0000BCF
PDH_UNABLE_READ_LOG_HEADER = 0xC0000BD0
PDH_FILE_NOT_FOUND = 0xC0000BD1
PDH_FILE_ALREADY_EXISTS = 0xC0000BD2
PDH_NOT_IMPLEMENTED = 0xC0000BD3
PDH_STRING_NOT_FOUND = 0xC0000BD4
PDH_UNABLE_MAP_NAME_FILES = 0x80000BD5
PDH_UNKNOWN_LOG_FORMAT = 0xC0000BD6
PDH_UNKNOWN_LOGSVC_COMMAND = 0xC0000BD7
PDH_LOGSVC_QUERY_NOT_FOUND = 0xC0000BD8
PDH_LOGSVC_NOT_OPENED = 0xC0000BD9
PDH_WBEM_ERROR = 0xC0000BDA
PDH_ACCESS_DENIED = 0xC0000BDB
PDH_LOG_FILE_TOO_SMALL = 0xC0000BDC
PDH_INVALID_DATASOURCE = 0xC0000BDD
PDH_INVALID_SQLDB = 0xC0000BDE
PDH_NO_COUNTERS = 0xC0000BDF
PDH_SQL_ALLOC_FAILED = 0xC0000BE0
PDH_SQL_ALLOCCON_FAILED = 0xC0000BE1
PDH_SQL_EXEC_DIRECT_FAILED = 0xC0000BE2
PDH_SQL_FETCH_FAILED = 0xC0000BE3
PDH_SQL_ROWCOUNT_FAILED = 0xC0000BE4
PDH_SQL_MORE_RESULTS_FAILED = 0xC0000BE5
PDH_SQL_CONNECT_FAILED = 0xC0000BE6
PDH_SQL_BIND_FAILED = 0xC0000BE7
PDH_CANNOT_CONNECT_WMI_SERVER = 0xC0000BE8
PDH_PLA_COLLECTION_ALREADY_RUNNING = 0xC0000BE9
PDH_PLA_ERROR_SCHEDULE_OVERLAP = 0xC0000BEA
PDH_PLA_COLLECTION_NOT_FOUND = 0xC0000BEB
PDH_PLA_ERROR_SCHEDULE_ELAPSED = 0xC0000BEC
PDH_PLA_ERROR_NOSTART = 0xC0000BED
PDH_PLA_ERROR_ALREADY_EXISTS = 0xC0000BEE
PDH_PLA_ERROR_TYPE_MISMATCH = 0xC0000BEF
PDH_PLA_ERROR_FILEPATH = 0xC0000BF0
PDH_PLA_SERVICE_ERROR = 0xC0000BF1
PDH_PLA_VALIDATION_ERROR = 0xC0000BF2
PDH_PLA_VALIDATION_WARNING = 0x80000BF3
PDH_PLA_ERROR_NAME_TOO_LONG = 0xC0000BF4
PDH_INVALID_SQL_LOG_FORMAT = 0xC0000BF5
PDH_COUNTER_ALREADY_IN_QUERY = 0xC0000BF6
PDH_BINARY_LOG_CORRUPT = 0xC0000BF7
PDH_LOG_SAMPLE_TOO_SMALL = 0xC0000BF8
PDH_OS_LATER_VERSION = 0xC0000BF9
PDH_OS_EARLIER_VERSION = 0xC0000BFA
PDH_INCORRECT_APPEND_TIME = 0xC0000BFB
PDH_UNMATCHED_APPEND_COUNTER = 0xC0000BFC
PDH_SQL_ALTER_DETAIL_FAILED = 0xC0000BFD
PDH_QUERY_PERF_DATA_TIMEOUT = 0xC0000BFE
PdhCstatusValidData = 0x00000000 // The returned data is valid.
PdhCstatusNewData = 0x00000001 // The return data value is valid and different from the last sample.
PdhCstatusNoMachine = 0x800007D0 // Unable to connect to the specified computer, or the computer is offline.
PdhCstatusNoInstance = 0x800007D1
PdhMoreData = 0x800007D2 // The PdhGetFormattedCounterArray* function can return this if there's 'more data to be displayed'.
PdhCstatusItemNotValidated = 0x800007D3
PdhRetry = 0x800007D4
PdhNoData = 0x800007D5 // The query does not currently contain any counters (for example, limited access)
PdhCalcNegativeDenominator = 0x800007D6
PdhCalcNegativeTimebase = 0x800007D7
PdhCalcNegativeValue = 0x800007D8
PdhDialogCancelled = 0x800007D9
PdhEndOfLogFile = 0x800007DA
PdhAsyncQueryTimeout = 0x800007DB
PdhCannotSetDefaultRealtimeDatasource = 0x800007DC
PdhCstatusNoObject = 0xC0000BB8
PdhCstatusNoCounter = 0xC0000BB9 // The specified counter could not be found.
PdhCstatusInvalidData = 0xC0000BBA // The counter was successfully found, but the data returned is not valid.
PdhMemoryAllocationFailure = 0xC0000BBB
PdhInvalidHandle = 0xC0000BBC
PdhInvalidArgument = 0xC0000BBD // Required argument is missing or incorrect.
PdhFunctionNotFound = 0xC0000BBE
PdhCstatusNoCountername = 0xC0000BBF
PdhCstatusBadCountername = 0xC0000BC0 // Unable to parse the counter path. Check the format and syntax of the specified path.
PdhInvalidBuffer = 0xC0000BC1
PdhInsufficientBuffer = 0xC0000BC2
PdhCannotConnectMachine = 0xC0000BC3
PdhInvalidPath = 0xC0000BC4
PdhInvalidInstance = 0xC0000BC5
PdhInvalidData = 0xC0000BC6 // specified counter does not contain valid data or a successful status code.
PdhNoDialogData = 0xC0000BC7
PdhCannotReadNameStrings = 0xC0000BC8
PdhLogFileCreateError = 0xC0000BC9
PdhLogFileOpenError = 0xC0000BCA
PdhLogTypeNotFound = 0xC0000BCB
PdhNoMoreData = 0xC0000BCC
PdhEntryNotInLogFile = 0xC0000BCD
PdhDataSourceIsLogFile = 0xC0000BCE
PdhDataSourceIsRealTime = 0xC0000BCF
PdhUnableReadLogHeader = 0xC0000BD0
PdhFileNotFound = 0xC0000BD1
PdhFileAlreadyExists = 0xC0000BD2
PdhNotImplemented = 0xC0000BD3
PdhStringNotFound = 0xC0000BD4
PdhUnableMapNameFiles = 0x80000BD5
PdhUnknownLogFormat = 0xC0000BD6
PdhUnknownLogsvcCommand = 0xC0000BD7
PdhLogsvcQueryNotFound = 0xC0000BD8
PdhLogsvcNotOpened = 0xC0000BD9
PdhWbemError = 0xC0000BDA
PdhAccessDenied = 0xC0000BDB
PdhLogFileTooSmall = 0xC0000BDC
PdhInvalidDatasource = 0xC0000BDD
PdhInvalidSqldb = 0xC0000BDE
PdhNoCounters = 0xC0000BDF
PdhSQLAllocFailed = 0xC0000BE0
PdhSQLAllocconFailed = 0xC0000BE1
PdhSQLExecDirectFailed = 0xC0000BE2
PdhSQLFetchFailed = 0xC0000BE3
PdhSQLRowcountFailed = 0xC0000BE4
PdhSQLMoreResultsFailed = 0xC0000BE5
PdhSQLConnectFailed = 0xC0000BE6
PdhSQLBindFailed = 0xC0000BE7
PdhCannotConnectWmiServer = 0xC0000BE8
PdhPlaCollectionAlreadyRunning = 0xC0000BE9
PdhPlaErrorScheduleOverlap = 0xC0000BEA
PdhPlaCollectionNotFound = 0xC0000BEB
PdhPlaErrorScheduleElapsed = 0xC0000BEC
PdhPlaErrorNostart = 0xC0000BED
PdhPlaErrorAlreadyExists = 0xC0000BEE
PdhPlaErrorTypeMismatch = 0xC0000BEF
PdhPlaErrorFilepath = 0xC0000BF0
PdhPlaServiceError = 0xC0000BF1
PdhPlaValidationError = 0xC0000BF2
PdhPlaValidationWarning = 0x80000BF3
PdhPlaErrorNameTooLong = 0xC0000BF4
PdhInvalidSQLLogFormat = 0xC0000BF5
PdhCounterAlreadyInQuery = 0xC0000BF6
PdhBinaryLogCorrupt = 0xC0000BF7
PdhLogSampleTooSmall = 0xC0000BF8
PdhOsLaterVersion = 0xC0000BF9
PdhOsEarlierVersion = 0xC0000BFA
PdhIncorrectAppendTime = 0xC0000BFB
PdhUnmatchedAppendCounter = 0xC0000BFC
PdhSQLAlterDetailFailed = 0xC0000BFD
PdhQueryPerfDataTimeout = 0xC0000BFE
)
var PDHErrors = map[uint32]string{
PDH_CSTATUS_VALID_DATA: "PDH_CSTATUS_VALID_DATA",
PDH_CSTATUS_NEW_DATA: "PDH_CSTATUS_NEW_DATA",
PDH_CSTATUS_NO_MACHINE: "PDH_CSTATUS_NO_MACHINE",
PDH_CSTATUS_NO_INSTANCE: "PDH_CSTATUS_NO_INSTANCE",
PDH_MORE_DATA: "PDH_MORE_DATA",
PDH_CSTATUS_ITEM_NOT_VALIDATED: "PDH_CSTATUS_ITEM_NOT_VALIDATED",
PDH_RETRY: "PDH_RETRY",
PDH_NO_DATA: "PDH_NO_DATA",
PDH_CALC_NEGATIVE_DENOMINATOR: "PDH_CALC_NEGATIVE_DENOMINATOR",
PDH_CALC_NEGATIVE_TIMEBASE: "PDH_CALC_NEGATIVE_TIMEBASE",
PDH_CALC_NEGATIVE_VALUE: "PDH_CALC_NEGATIVE_VALUE",
PDH_DIALOG_CANCELLED: "PDH_DIALOG_CANCELLED",
PDH_END_OF_LOG_FILE: "PDH_END_OF_LOG_FILE",
PDH_ASYNC_QUERY_TIMEOUT: "PDH_ASYNC_QUERY_TIMEOUT",
PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE: "PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE",
PDH_CSTATUS_NO_OBJECT: "PDH_CSTATUS_NO_OBJECT",
PDH_CSTATUS_NO_COUNTER: "PDH_CSTATUS_NO_COUNTER",
PDH_CSTATUS_INVALID_DATA: "PDH_CSTATUS_INVALID_DATA",
PDH_MEMORY_ALLOCATION_FAILURE: "PDH_MEMORY_ALLOCATION_FAILURE",
PDH_INVALID_HANDLE: "PDH_INVALID_HANDLE",
PDH_INVALID_ARGUMENT: "PDH_INVALID_ARGUMENT",
PDH_FUNCTION_NOT_FOUND: "PDH_FUNCTION_NOT_FOUND",
PDH_CSTATUS_NO_COUNTERNAME: "PDH_CSTATUS_NO_COUNTERNAME",
PDH_CSTATUS_BAD_COUNTERNAME: "PDH_CSTATUS_BAD_COUNTERNAME",
PDH_INVALID_BUFFER: "PDH_INVALID_BUFFER",
PDH_INSUFFICIENT_BUFFER: "PDH_INSUFFICIENT_BUFFER",
PDH_CANNOT_CONNECT_MACHINE: "PDH_CANNOT_CONNECT_MACHINE",
PDH_INVALID_PATH: "PDH_INVALID_PATH",
PDH_INVALID_INSTANCE: "PDH_INVALID_INSTANCE",
PDH_INVALID_DATA: "PDH_INVALID_DATA",
PDH_NO_DIALOG_DATA: "PDH_NO_DIALOG_DATA",
PDH_CANNOT_READ_NAME_STRINGS: "PDH_CANNOT_READ_NAME_STRINGS",
PDH_LOG_FILE_CREATE_ERROR: "PDH_LOG_FILE_CREATE_ERROR",
PDH_LOG_FILE_OPEN_ERROR: "PDH_LOG_FILE_OPEN_ERROR",
PDH_LOG_TYPE_NOT_FOUND: "PDH_LOG_TYPE_NOT_FOUND",
PDH_NO_MORE_DATA: "PDH_NO_MORE_DATA",
PDH_ENTRY_NOT_IN_LOG_FILE: "PDH_ENTRY_NOT_IN_LOG_FILE",
PDH_DATA_SOURCE_IS_LOG_FILE: "PDH_DATA_SOURCE_IS_LOG_FILE",
PDH_DATA_SOURCE_IS_REAL_TIME: "PDH_DATA_SOURCE_IS_REAL_TIME",
PDH_UNABLE_READ_LOG_HEADER: "PDH_UNABLE_READ_LOG_HEADER",
PDH_FILE_NOT_FOUND: "PDH_FILE_NOT_FOUND",
PDH_FILE_ALREADY_EXISTS: "PDH_FILE_ALREADY_EXISTS",
PDH_NOT_IMPLEMENTED: "PDH_NOT_IMPLEMENTED",
PDH_STRING_NOT_FOUND: "PDH_STRING_NOT_FOUND",
PDH_UNABLE_MAP_NAME_FILES: "PDH_UNABLE_MAP_NAME_FILES",
PDH_UNKNOWN_LOG_FORMAT: "PDH_UNKNOWN_LOG_FORMAT",
PDH_UNKNOWN_LOGSVC_COMMAND: "PDH_UNKNOWN_LOGSVC_COMMAND",
PDH_LOGSVC_QUERY_NOT_FOUND: "PDH_LOGSVC_QUERY_NOT_FOUND",
PDH_LOGSVC_NOT_OPENED: "PDH_LOGSVC_NOT_OPENED",
PDH_WBEM_ERROR: "PDH_WBEM_ERROR",
PDH_ACCESS_DENIED: "PDH_ACCESS_DENIED",
PDH_LOG_FILE_TOO_SMALL: "PDH_LOG_FILE_TOO_SMALL",
PDH_INVALID_DATASOURCE: "PDH_INVALID_DATASOURCE",
PDH_INVALID_SQLDB: "PDH_INVALID_SQLDB",
PDH_NO_COUNTERS: "PDH_NO_COUNTERS",
PDH_SQL_ALLOC_FAILED: "PDH_SQL_ALLOC_FAILED",
PDH_SQL_ALLOCCON_FAILED: "PDH_SQL_ALLOCCON_FAILED",
PDH_SQL_EXEC_DIRECT_FAILED: "PDH_SQL_EXEC_DIRECT_FAILED",
PDH_SQL_FETCH_FAILED: "PDH_SQL_FETCH_FAILED",
PDH_SQL_ROWCOUNT_FAILED: "PDH_SQL_ROWCOUNT_FAILED",
PDH_SQL_MORE_RESULTS_FAILED: "PDH_SQL_MORE_RESULTS_FAILED",
PDH_SQL_CONNECT_FAILED: "PDH_SQL_CONNECT_FAILED",
PDH_SQL_BIND_FAILED: "PDH_SQL_BIND_FAILED",
PDH_CANNOT_CONNECT_WMI_SERVER: "PDH_CANNOT_CONNECT_WMI_SERVER",
PDH_PLA_COLLECTION_ALREADY_RUNNING: "PDH_PLA_COLLECTION_ALREADY_RUNNING",
PDH_PLA_ERROR_SCHEDULE_OVERLAP: "PDH_PLA_ERROR_SCHEDULE_OVERLAP",
PDH_PLA_COLLECTION_NOT_FOUND: "PDH_PLA_COLLECTION_NOT_FOUND",
PDH_PLA_ERROR_SCHEDULE_ELAPSED: "PDH_PLA_ERROR_SCHEDULE_ELAPSED",
PDH_PLA_ERROR_NOSTART: "PDH_PLA_ERROR_NOSTART",
PDH_PLA_ERROR_ALREADY_EXISTS: "PDH_PLA_ERROR_ALREADY_EXISTS",
PDH_PLA_ERROR_TYPE_MISMATCH: "PDH_PLA_ERROR_TYPE_MISMATCH",
PDH_PLA_ERROR_FILEPATH: "PDH_PLA_ERROR_FILEPATH",
PDH_PLA_SERVICE_ERROR: "PDH_PLA_SERVICE_ERROR",
PDH_PLA_VALIDATION_ERROR: "PDH_PLA_VALIDATION_ERROR",
PDH_PLA_VALIDATION_WARNING: "PDH_PLA_VALIDATION_WARNING",
PDH_PLA_ERROR_NAME_TOO_LONG: "PDH_PLA_ERROR_NAME_TOO_LONG",
PDH_INVALID_SQL_LOG_FORMAT: "PDH_INVALID_SQL_LOG_FORMAT",
PDH_COUNTER_ALREADY_IN_QUERY: "PDH_COUNTER_ALREADY_IN_QUERY",
PDH_BINARY_LOG_CORRUPT: "PDH_BINARY_LOG_CORRUPT",
PDH_LOG_SAMPLE_TOO_SMALL: "PDH_LOG_SAMPLE_TOO_SMALL",
PDH_OS_LATER_VERSION: "PDH_OS_LATER_VERSION",
PDH_OS_EARLIER_VERSION: "PDH_OS_EARLIER_VERSION",
PDH_INCORRECT_APPEND_TIME: "PDH_INCORRECT_APPEND_TIME",
PDH_UNMATCHED_APPEND_COUNTER: "PDH_UNMATCHED_APPEND_COUNTER",
PDH_SQL_ALTER_DETAIL_FAILED: "PDH_SQL_ALTER_DETAIL_FAILED",
PDH_QUERY_PERF_DATA_TIMEOUT: "PDH_QUERY_PERF_DATA_TIMEOUT",
PdhCstatusValidData: "PDH_CSTATUS_VALID_DATA",
PdhCstatusNewData: "PDH_CSTATUS_NEW_DATA",
PdhCstatusNoMachine: "PDH_CSTATUS_NO_MACHINE",
PdhCstatusNoInstance: "PDH_CSTATUS_NO_INSTANCE",
PdhMoreData: "PDH_MORE_DATA",
PdhCstatusItemNotValidated: "PDH_CSTATUS_ITEM_NOT_VALIDATED",
PdhRetry: "PDH_RETRY",
PdhNoData: "PDH_NO_DATA",
PdhCalcNegativeDenominator: "PDH_CALC_NEGATIVE_DENOMINATOR",
PdhCalcNegativeTimebase: "PDH_CALC_NEGATIVE_TIMEBASE",
PdhCalcNegativeValue: "PDH_CALC_NEGATIVE_VALUE",
PdhDialogCancelled: "PDH_DIALOG_CANCELLED",
PdhEndOfLogFile: "PDH_END_OF_LOG_FILE",
PdhAsyncQueryTimeout: "PDH_ASYNC_QUERY_TIMEOUT",
PdhCannotSetDefaultRealtimeDatasource: "PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE",
PdhCstatusNoObject: "PDH_CSTATUS_NO_OBJECT",
PdhCstatusNoCounter: "PDH_CSTATUS_NO_COUNTER",
PdhCstatusInvalidData: "PDH_CSTATUS_INVALID_DATA",
PdhMemoryAllocationFailure: "PDH_MEMORY_ALLOCATION_FAILURE",
PdhInvalidHandle: "PDH_INVALID_HANDLE",
PdhInvalidArgument: "PDH_INVALID_ARGUMENT",
PdhFunctionNotFound: "PDH_FUNCTION_NOT_FOUND",
PdhCstatusNoCountername: "PDH_CSTATUS_NO_COUNTERNAME",
PdhCstatusBadCountername: "PDH_CSTATUS_BAD_COUNTERNAME",
PdhInvalidBuffer: "PDH_INVALID_BUFFER",
PdhInsufficientBuffer: "PDH_INSUFFICIENT_BUFFER",
PdhCannotConnectMachine: "PDH_CANNOT_CONNECT_MACHINE",
PdhInvalidPath: "PDH_INVALID_PATH",
PdhInvalidInstance: "PDH_INVALID_INSTANCE",
PdhInvalidData: "PDH_INVALID_DATA",
PdhNoDialogData: "PDH_NO_DIALOG_DATA",
PdhCannotReadNameStrings: "PDH_CANNOT_READ_NAME_STRINGS",
PdhLogFileCreateError: "PDH_LOG_FILE_CREATE_ERROR",
PdhLogFileOpenError: "PDH_LOG_FILE_OPEN_ERROR",
PdhLogTypeNotFound: "PDH_LOG_TYPE_NOT_FOUND",
PdhNoMoreData: "PDH_NO_MORE_DATA",
PdhEntryNotInLogFile: "PDH_ENTRY_NOT_IN_LOG_FILE",
PdhDataSourceIsLogFile: "PDH_DATA_SOURCE_IS_LOG_FILE",
PdhDataSourceIsRealTime: "PDH_DATA_SOURCE_IS_REAL_TIME",
PdhUnableReadLogHeader: "PDH_UNABLE_READ_LOG_HEADER",
PdhFileNotFound: "PDH_FILE_NOT_FOUND",
PdhFileAlreadyExists: "PDH_FILE_ALREADY_EXISTS",
PdhNotImplemented: "PDH_NOT_IMPLEMENTED",
PdhStringNotFound: "PDH_STRING_NOT_FOUND",
PdhUnableMapNameFiles: "PDH_UNABLE_MAP_NAME_FILES",
PdhUnknownLogFormat: "PDH_UNKNOWN_LOG_FORMAT",
PdhUnknownLogsvcCommand: "PDH_UNKNOWN_LOGSVC_COMMAND",
PdhLogsvcQueryNotFound: "PDH_LOGSVC_QUERY_NOT_FOUND",
PdhLogsvcNotOpened: "PDH_LOGSVC_NOT_OPENED",
PdhWbemError: "PDH_WBEM_ERROR",
PdhAccessDenied: "PDH_ACCESS_DENIED",
PdhLogFileTooSmall: "PDH_LOG_FILE_TOO_SMALL",
PdhInvalidDatasource: "PDH_INVALID_DATASOURCE",
PdhInvalidSqldb: "PDH_INVALID_SQLDB",
PdhNoCounters: "PDH_NO_COUNTERS",
PdhSQLAllocFailed: "PDH_SQL_ALLOC_FAILED",
PdhSQLAllocconFailed: "PDH_SQL_ALLOCCON_FAILED",
PdhSQLExecDirectFailed: "PDH_SQL_EXEC_DIRECT_FAILED",
PdhSQLFetchFailed: "PDH_SQL_FETCH_FAILED",
PdhSQLRowcountFailed: "PDH_SQL_ROWCOUNT_FAILED",
PdhSQLMoreResultsFailed: "PDH_SQL_MORE_RESULTS_FAILED",
PdhSQLConnectFailed: "PDH_SQL_CONNECT_FAILED",
PdhSQLBindFailed: "PDH_SQL_BIND_FAILED",
PdhCannotConnectWmiServer: "PDH_CANNOT_CONNECT_WMI_SERVER",
PdhPlaCollectionAlreadyRunning: "PDH_PLA_COLLECTION_ALREADY_RUNNING",
PdhPlaErrorScheduleOverlap: "PDH_PLA_ERROR_SCHEDULE_OVERLAP",
PdhPlaCollectionNotFound: "PDH_PLA_COLLECTION_NOT_FOUND",
PdhPlaErrorScheduleElapsed: "PDH_PLA_ERROR_SCHEDULE_ELAPSED",
PdhPlaErrorNostart: "PDH_PLA_ERROR_NOSTART",
PdhPlaErrorAlreadyExists: "PDH_PLA_ERROR_ALREADY_EXISTS",
PdhPlaErrorTypeMismatch: "PDH_PLA_ERROR_TYPE_MISMATCH",
PdhPlaErrorFilepath: "PDH_PLA_ERROR_FILEPATH",
PdhPlaServiceError: "PDH_PLA_SERVICE_ERROR",
PdhPlaValidationError: "PDH_PLA_VALIDATION_ERROR",
PdhPlaValidationWarning: "PDH_PLA_VALIDATION_WARNING",
PdhPlaErrorNameTooLong: "PDH_PLA_ERROR_NAME_TOO_LONG",
PdhInvalidSQLLogFormat: "PDH_INVALID_SQL_LOG_FORMAT",
PdhCounterAlreadyInQuery: "PDH_COUNTER_ALREADY_IN_QUERY",
PdhBinaryLogCorrupt: "PDH_BINARY_LOG_CORRUPT",
PdhLogSampleTooSmall: "PDH_LOG_SAMPLE_TOO_SMALL",
PdhOsLaterVersion: "PDH_OS_LATER_VERSION",
PdhOsEarlierVersion: "PDH_OS_EARLIER_VERSION",
PdhIncorrectAppendTime: "PDH_INCORRECT_APPEND_TIME",
PdhUnmatchedAppendCounter: "PDH_UNMATCHED_APPEND_COUNTER",
PdhSQLAlterDetailFailed: "PDH_SQL_ALTER_DETAIL_FAILED",
PdhQueryPerfDataTimeout: "PDH_QUERY_PERF_DATA_TIMEOUT",
}
// Formatting options for GetFormattedCounterValue().
const (
PDH_FMT_RAW = 0x00000010
PDH_FMT_ANSI = 0x00000020
PDH_FMT_UNICODE = 0x00000040
PDH_FMT_LONG = 0x00000100 // Return data as a long int.
PDH_FMT_DOUBLE = 0x00000200 // Return data as a double precision floating point real.
PDH_FMT_LARGE = 0x00000400 // Return data as a 64 bit integer.
PDH_FMT_NOSCALE = 0x00001000 // can be OR-ed: Do not apply the counter's default scaling factor.
PDH_FMT_1000 = 0x00002000 // can be OR-ed: multiply the actual value by 1,000.
PDH_FMT_NODATA = 0x00004000 // can be OR-ed: unknown what this is for, MSDN says nothing.
PDH_FMT_NOCAP100 = 0x00008000 // can be OR-ed: do not cap values > 100.
PERF_DETAIL_COSTLY = 0x00010000
PERF_DETAIL_STANDARD = 0x0000FFFF
PdhFmtRaw = 0x00000010
PdhFmtAnsi = 0x00000020
PdhFmtUnicode = 0x00000040
PdhFmtLong = 0x00000100 // Return data as a long int.
PdhFmtDouble = 0x00000200 // Return data as a double precision floating point real.
PdhFmtLarge = 0x00000400 // Return data as a 64 bit integer.
PdhFmtNoscale = 0x00001000 // can be OR-ed: Do not apply the counter's default scaling factor.
PdhFmt1000 = 0x00002000 // can be OR-ed: multiply the actual value by 1,000.
PdhFmtNodata = 0x00004000 // can be OR-ed: unknown what this is for, MSDN says nothing.
PdhFmtNocap100 = 0x00008000 // can be OR-ed: do not cap values > 100.
PerfDetailCostly = 0x00010000
PerfDetailStandard = 0x0000FFFF
)
type (
PDH_HQUERY HANDLE // query handle
PDH_HCOUNTER HANDLE // counter handle
pdhQueryHandle HANDLE // query handle
pdhCounterHandle HANDLE // counter handle
)
var (
// Library
libpdhDll *syscall.DLL
libPdhDll *syscall.DLL
// Functions
pdh_AddCounterW *syscall.Proc
pdh_AddEnglishCounterW *syscall.Proc
pdh_CloseQuery *syscall.Proc
pdh_CollectQueryData *syscall.Proc
pdh_CollectQueryDataWithTime *syscall.Proc
pdh_GetFormattedCounterValue *syscall.Proc
pdh_GetFormattedCounterArrayW *syscall.Proc
pdh_OpenQuery *syscall.Proc
pdh_ValidatePathW *syscall.Proc
pdh_ExpandWildCardPathW *syscall.Proc
pdh_GetCounterInfoW *syscall.Proc
pdh_GetRawCounterValue *syscall.Proc
pdh_GetRawCounterArrayW *syscall.Proc
pdhAddCounterW *syscall.Proc
pdhAddEnglishCounterW *syscall.Proc
pdhCloseQuery *syscall.Proc
pdhCollectQueryData *syscall.Proc
pdhCollectQueryDataWithTime *syscall.Proc
pdhGetFormattedCounterValue *syscall.Proc
pdhGetFormattedCounterArrayW *syscall.Proc
pdhOpenQuery *syscall.Proc
pdhValidatePathW *syscall.Proc
pdhExpandWildCardPathW *syscall.Proc
pdhGetCounterInfoW *syscall.Proc
pdhGetRawCounterValue *syscall.Proc
pdhGetRawCounterArrayW *syscall.Proc
)
func init() {
// Library
libpdhDll = syscall.MustLoadDLL("pdh.dll")
libPdhDll = syscall.MustLoadDLL("pdh.dll")
// Functions
pdh_AddCounterW = libpdhDll.MustFindProc("PdhAddCounterW")
pdh_AddEnglishCounterW, _ = libpdhDll.FindProc("PdhAddEnglishCounterW") // XXX: only supported on versions > Vista.
pdh_CloseQuery = libpdhDll.MustFindProc("PdhCloseQuery")
pdh_CollectQueryData = libpdhDll.MustFindProc("PdhCollectQueryData")
pdh_CollectQueryDataWithTime, _ = libpdhDll.FindProc("PdhCollectQueryDataWithTime")
pdh_GetFormattedCounterValue = libpdhDll.MustFindProc("PdhGetFormattedCounterValue")
pdh_GetFormattedCounterArrayW = libpdhDll.MustFindProc("PdhGetFormattedCounterArrayW")
pdh_OpenQuery = libpdhDll.MustFindProc("PdhOpenQuery")
pdh_ValidatePathW = libpdhDll.MustFindProc("PdhValidatePathW")
pdh_ExpandWildCardPathW = libpdhDll.MustFindProc("PdhExpandWildCardPathW")
pdh_GetCounterInfoW = libpdhDll.MustFindProc("PdhGetCounterInfoW")
pdh_GetRawCounterValue = libpdhDll.MustFindProc("PdhGetRawCounterValue")
pdh_GetRawCounterArrayW = libpdhDll.MustFindProc("PdhGetRawCounterArrayW")
pdhAddCounterW = libPdhDll.MustFindProc("PdhAddCounterW")
pdhAddEnglishCounterW, _ = libPdhDll.FindProc("PdhAddEnglishCounterW") // XXX: only supported on versions > Vista.
pdhCloseQuery = libPdhDll.MustFindProc("PdhCloseQuery")
pdhCollectQueryData = libPdhDll.MustFindProc("PdhCollectQueryData")
pdhCollectQueryDataWithTime, _ = libPdhDll.FindProc("PdhCollectQueryDataWithTime")
pdhGetFormattedCounterValue = libPdhDll.MustFindProc("PdhGetFormattedCounterValue")
pdhGetFormattedCounterArrayW = libPdhDll.MustFindProc("PdhGetFormattedCounterArrayW")
pdhOpenQuery = libPdhDll.MustFindProc("PdhOpenQuery")
pdhValidatePathW = libPdhDll.MustFindProc("PdhValidatePathW")
pdhExpandWildCardPathW = libPdhDll.MustFindProc("PdhExpandWildCardPathW")
pdhGetCounterInfoW = libPdhDll.MustFindProc("PdhGetCounterInfoW")
pdhGetRawCounterValue = libPdhDll.MustFindProc("PdhGetRawCounterValue")
pdhGetRawCounterArrayW = libPdhDll.MustFindProc("PdhGetRawCounterArrayW")
}
// PdhAddCounter adds the specified counter to the query. This is the internationalized version. Preferably, use the
// function PdhAddEnglishCounter instead. hQuery is the query handle, which has been fetched by PdhOpenQuery.
// szFullCounterPath is a full, internationalized counter path (this will differ per Windows language version).
// dwUserData is a 'user-defined value', which becomes part of the counter information. To retrieve this value
// later, call PdhGetCounterInfo() and access dwQueryUserData of the PDH_COUNTER_INFO structure.
// later, call PdhGetCounterInfo() and access dwQueryUserData of the PdhCounterInfo structure.
//
// Examples of szFullCounterPath (in an English version of Windows):
//
@ -333,9 +333,9 @@ func init() {
// The typeperf command may also be pretty easy. To find all performance counters, simply execute:
//
// typeperf -qx
func PdhAddCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintptr, phCounter *PDH_HCOUNTER) uint32 {
func PdhAddCounter(hQuery pdhQueryHandle, szFullCounterPath string, dwUserData uintptr, phCounter *pdhCounterHandle) uint32 {
ptxt, _ := syscall.UTF16PtrFromString(szFullCounterPath)
ret, _, _ := pdh_AddCounterW.Call(
ret, _, _ := pdhAddCounterW.Call(
uintptr(hQuery),
uintptr(unsafe.Pointer(ptxt)), //nolint:gosec // G103: Valid use of unsafe call to pass ptxt
dwUserData,
@ -346,20 +346,19 @@ func PdhAddCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintp
// PdhAddEnglishCounterSupported returns true if PdhAddEnglishCounterW Win API function was found in pdh.dll.
// PdhAddEnglishCounterW function is not supported on pre-Windows Vista systems
func PdhAddEnglishCounterSupported() bool {
return pdh_AddEnglishCounterW != nil
return pdhAddEnglishCounterW != nil
}
// PdhAddEnglishCounter adds the specified language-neutral counter to the query. See the PdhAddCounter function. This function only exists on
// Windows versions higher than Vista.
func PdhAddEnglishCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintptr, phCounter *PDH_HCOUNTER) uint32 {
if pdh_AddEnglishCounterW == nil {
return ERROR_INVALID_FUNCTION
func PdhAddEnglishCounter(hQuery pdhQueryHandle, szFullCounterPath string, dwUserData uintptr, phCounter *pdhCounterHandle) uint32 {
if pdhAddEnglishCounterW == nil {
return ErrorInvalidFunction
}
ptxt, _ := syscall.UTF16PtrFromString(szFullCounterPath)
ret, _, _ := pdh_AddEnglishCounterW.Call(
ret, _, _ := pdhAddEnglishCounterW.Call(
uintptr(hQuery),
uintptr(unsafe.Pointer(ptxt)), //nolint:gosec // G103: Valid use of unsafe call to pass ptxt
dwUserData,
@ -370,8 +369,8 @@ func PdhAddEnglishCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserDat
// PdhCloseQuery closes all counters contained in the specified query, closes all handles related to the query,
// and frees all memory associated with the query.
func PdhCloseQuery(hQuery PDH_HQUERY) uint32 {
ret, _, _ := pdh_CloseQuery.Call(uintptr(hQuery))
func PdhCloseQuery(hQuery pdhQueryHandle) uint32 {
ret, _, _ := pdhCloseQuery.Call(uintptr(hQuery))
return uint32(ret)
}
@ -397,38 +396,38 @@ func PdhCloseQuery(hQuery PDH_HQUERY) uint32 {
//
// The PdhCollectQueryData will return an error in the first call because it needs two values for
// displaying the correct data for the processor idle time. The second call will have a 0 return code.
func PdhCollectQueryData(hQuery PDH_HQUERY) uint32 {
ret, _, _ := pdh_CollectQueryData.Call(uintptr(hQuery))
func PdhCollectQueryData(hQuery pdhQueryHandle) uint32 {
ret, _, _ := pdhCollectQueryData.Call(uintptr(hQuery))
return uint32(ret)
}
// PdhCollectQueryDataWithTime queries data from perfmon, retrieving the device/windows timestamp from the node it was collected on.
// Converts the filetime structure to a GO time class and returns the native time.
func PdhCollectQueryDataWithTime(hQuery PDH_HQUERY) (uint32, time.Time) {
var localFileTime FILETIME
func PdhCollectQueryDataWithTime(hQuery pdhQueryHandle) (uint32, time.Time) {
var localFileTime fileTime
//nolint:gosec // G103: Valid use of unsafe call to pass localFileTime
ret, _, _ := pdh_CollectQueryDataWithTime.Call(uintptr(hQuery), uintptr(unsafe.Pointer(&localFileTime)))
ret, _, _ := pdhCollectQueryDataWithTime.Call(uintptr(hQuery), uintptr(unsafe.Pointer(&localFileTime)))
if ret == ERROR_SUCCESS {
var utcFileTime FILETIME
ret, _, _ := krn_LocalFileTimeToFileTime.Call(
if ret == ErrorSuccess {
var utcFileTime fileTime
ret, _, _ := kernelLocalFileTimeToFileTime.Call(
uintptr(unsafe.Pointer(&localFileTime)), //nolint:gosec // G103: Valid use of unsafe call to pass localFileTime
uintptr(unsafe.Pointer(&utcFileTime))) //nolint:gosec // G103: Valid use of unsafe call to pass utcFileTime
if ret == 0 {
return uint32(ERROR_FAILURE), time.Now()
return uint32(ErrorFailure), time.Now()
}
// First convert 100-ns intervals to microseconds, then adjust for the
// epoch difference
var totalMicroSeconds int64
totalMicroSeconds = ((int64(utcFileTime.dwHighDateTime) << 32) | int64(utcFileTime.dwLowDateTime)) / 10
totalMicroSeconds -= EPOCH_DIFFERENCE_MICROS
totalMicroSeconds -= EpochDifferenceMicros
retTime := time.Unix(0, totalMicroSeconds*1000)
return uint32(ERROR_SUCCESS), retTime
return uint32(ErrorSuccess), retTime
}
return uint32(ret), time.Now()
@ -436,10 +435,10 @@ func PdhCollectQueryDataWithTime(hQuery PDH_HQUERY) (uint32, time.Time) {
// PdhGetFormattedCounterValueDouble formats the given hCounter using a 'double'. The result is set into the specialized union struct pValue.
// This function does not directly translate to a Windows counterpart due to union specialization tricks.
func PdhGetFormattedCounterValueDouble(hCounter PDH_HCOUNTER, lpdwType *uint32, pValue *PDH_FMT_COUNTERVALUE_DOUBLE) uint32 {
ret, _, _ := pdh_GetFormattedCounterValue.Call(
func PdhGetFormattedCounterValueDouble(hCounter pdhCounterHandle, lpdwType *uint32, pValue *PdhFmtCountervalueDouble) uint32 {
ret, _, _ := pdhGetFormattedCounterValue.Call(
uintptr(hCounter),
uintptr(PDH_FMT_DOUBLE|PDH_FMT_NOCAP100),
uintptr(PdhFmtDouble|PdhFmtNocap100),
uintptr(unsafe.Pointer(lpdwType)), //nolint:gosec // G103: Valid use of unsafe call to pass lpdwType
uintptr(unsafe.Pointer(pValue))) //nolint:gosec // G103: Valid use of unsafe call to pass pValue
@ -447,7 +446,7 @@ func PdhGetFormattedCounterValueDouble(hCounter PDH_HCOUNTER, lpdwType *uint32,
}
// PdhGetFormattedCounterArrayDouble returns an array of formatted counter values. Use this function when you want to format the counter values of a
// counter that contains a wildcard character for the instance name. The itemBuffer must a slice of type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE.
// counter that contains a wildcard character for the instance name. The itemBuffer must a slice of type PdhFmtCountervalueItemDouble.
// An example of how this function can be used:
//
// okPath := "\\Process(*)\\% Processor Time" // notice the wildcard * character
@ -483,10 +482,10 @@ func PdhGetFormattedCounterValueDouble(hCounter PDH_HCOUNTER, lpdwType *uint32,
// time.Sleep(2000 * time.Millisecond)
// }
// }
func PdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *byte) uint32 {
ret, _, _ := pdh_GetFormattedCounterArrayW.Call(
func PdhGetFormattedCounterArrayDouble(hCounter pdhCounterHandle, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *byte) uint32 {
ret, _, _ := pdhGetFormattedCounterArrayW.Call(
uintptr(hCounter),
uintptr(PDH_FMT_DOUBLE|PDH_FMT_NOCAP100),
uintptr(PdhFmtDouble|PdhFmtNocap100),
uintptr(unsafe.Pointer(lpdwBufferSize)), //nolint:gosec // G103: Valid use of unsafe call to pass lpdwBufferSize
uintptr(unsafe.Pointer(lpdwBufferCount)), //nolint:gosec // G103: Valid use of unsafe call to pass lpdwBufferCount
uintptr(unsafe.Pointer(itemBuffer))) //nolint:gosec // G103: Valid use of unsafe call to pass itemBuffer
@ -498,11 +497,11 @@ func PdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *ui
// szDataSource is a null terminated string that specifies the name of the log file from which to
// retrieve the performance data. If 0, performance data is collected from a real-time data source.
// dwUserData is a user-defined value to associate with this query. To retrieve the user data later,
// call PdhGetCounterInfo and access dwQueryUserData of the PDH_COUNTER_INFO structure. phQuery is
// call PdhGetCounterInfo and access dwQueryUserData of the PdhCounterInfo structure. phQuery is
// the handle to the query, and must be used in subsequent calls. This function returns a PDH_
// constant error code, or ERROR_SUCCESS if the call succeeded.
func PdhOpenQuery(szDataSource uintptr, dwUserData uintptr, phQuery *PDH_HQUERY) uint32 {
ret, _, _ := pdh_OpenQuery.Call(
// constant error code, or ErrorSuccess if the call succeeded.
func PdhOpenQuery(szDataSource uintptr, dwUserData uintptr, phQuery *pdhQueryHandle) uint32 {
ret, _, _ := pdhOpenQuery.Call(
szDataSource,
dwUserData,
uintptr(unsafe.Pointer(phQuery))) //nolint:gosec // G103: Valid use of unsafe call to pass phQuery
@ -546,7 +545,7 @@ func PdhOpenQuery(szDataSource uintptr, dwUserData uintptr, phQuery *PDH_HQUERY)
func PdhExpandWildCardPath(szWildCardPath string, mszExpandedPathList *uint16, pcchPathListLength *uint32) uint32 {
ptxt, _ := syscall.UTF16PtrFromString(szWildCardPath)
flags := uint32(0) // expand instances and counters
ret, _, _ := pdh_ExpandWildCardPathW.Call(
ret, _, _ := pdhExpandWildCardPathW.Call(
0, // search counters on local computer
uintptr(unsafe.Pointer(ptxt)), //nolint:gosec // G103: Valid use of unsafe call to pass ptxt
uintptr(unsafe.Pointer(mszExpandedPathList)), //nolint:gosec // G103: Valid use of unsafe call to pass mszExpandedPathList
@ -556,22 +555,22 @@ func PdhExpandWildCardPath(szWildCardPath string, mszExpandedPathList *uint16, p
return uint32(ret)
}
// PdhValidatePath validates a path. Will return ERROR_SUCCESS when ok, or PDH_CSTATUS_BAD_COUNTERNAME when the path is erroneous.
// PdhValidatePath validates a path. Will return ErrorSuccess when ok, or PdhCstatusBadCountername when the path is erroneous.
func PdhValidatePath(path string) uint32 {
ptxt, _ := syscall.UTF16PtrFromString(path)
ret, _, _ := pdh_ValidatePathW.Call(uintptr(unsafe.Pointer(ptxt))) //nolint:gosec // G103: Valid use of unsafe call to pass ptxt
ret, _, _ := pdhValidatePathW.Call(uintptr(unsafe.Pointer(ptxt))) //nolint:gosec // G103: Valid use of unsafe call to pass ptxt
return uint32(ret)
}
func PdhFormatError(msgId uint32) string {
func PdhFormatError(msgID uint32) string {
var flags uint32 = windows.FORMAT_MESSAGE_FROM_HMODULE | windows.FORMAT_MESSAGE_ARGUMENT_ARRAY | windows.FORMAT_MESSAGE_IGNORE_INSERTS
buf := make([]uint16, 300)
_, err := windows.FormatMessage(flags, uintptr(libpdhDll.Handle), msgId, 0, buf, nil)
_, err := windows.FormatMessage(flags, uintptr(libPdhDll.Handle), msgID, 0, buf, nil)
if err == nil {
return UTF16PtrToString(&buf[0])
}
return fmt.Sprintf("(pdhErr=%d) %s", msgId, err.Error())
return fmt.Sprintf("(pdhErr=%d) %s", msgID, err.Error())
}
// PdhGetCounterInfo retrieves information about a counter, such as data size, counter type, path, and user-supplied data values
@ -583,16 +582,16 @@ func PdhFormatError(msgId uint32) string {
// If you set this parameter to FALSE, the field in the returned buffer is NULL.
//
// pdwBufferSize [in, out]
// Size of the lpBuffer buffer, in bytes. If zero on input, the function returns PDH_MORE_DATA and sets this parameter to the required buffer size.
// Size of the lpBuffer buffer, in bytes. If zero on input, the function returns PdhMoreData and sets this parameter to the required buffer size.
// If the buffer is larger than the required size, the function sets this parameter to the actual size of the buffer that was used.
// If the specified size on input is greater than zero but less than the required size, you should not rely on the returned size to reallocate the buffer.
//
// lpBuffer [out]
// Caller-allocated buffer that receives a PDH_COUNTER_INFO structure.
// Caller-allocated buffer that receives a PdhCounterInfo structure.
// The structure is variable-length, because the string data is appended to the end of the fixed-format portion of the structure.
// This is done so that all data is returned in a single buffer allocated by the caller. Set to NULL if pdwBufferSize is zero.
func PdhGetCounterInfo(hCounter PDH_HCOUNTER, bRetrieveExplainText int, pdwBufferSize *uint32, lpBuffer *byte) uint32 {
ret, _, _ := pdh_GetCounterInfoW.Call(
func PdhGetCounterInfo(hCounter pdhCounterHandle, bRetrieveExplainText int, pdwBufferSize *uint32, lpBuffer *byte) uint32 {
ret, _, _ := pdhGetCounterInfoW.Call(
uintptr(hCounter),
uintptr(bRetrieveExplainText),
uintptr(unsafe.Pointer(pdwBufferSize)), //nolint:gosec // G103: Valid use of unsafe call to pass pdwBufferSize
@ -602,8 +601,8 @@ func PdhGetCounterInfo(hCounter PDH_HCOUNTER, bRetrieveExplainText int, pdwBuffe
}
// PdhGetRawCounterValue returns the current raw value of the counter.
// If the specified counter instance does not exist, this function will return ERROR_SUCCESS
// and the CStatus member of the PDH_RAW_COUNTER structure will contain PDH_CSTATUS_NO_INSTANCE.
// If the specified counter instance does not exist, this function will return ErrorSuccess
// and the CStatus member of the PdhRawCounter structure will contain PdhCstatusNoInstance.
//
// hCounter [in]
// Handle of the counter from which to retrieve the current raw value. The PdhAddCounter function returns this handle.
@ -613,9 +612,9 @@ func PdhGetCounterInfo(hCounter PDH_HCOUNTER, bRetrieveExplainText int, pdwBuffe
// This parameter is optional.
//
// pValue [out]
// A PDH_RAW_COUNTER structure that receives the counter value.
func PdhGetRawCounterValue(hCounter PDH_HCOUNTER, lpdwType *uint32, pValue *PDH_RAW_COUNTER) uint32 {
ret, _, _ := pdh_GetRawCounterValue.Call(
// A PdhRawCounter structure that receives the counter value.
func PdhGetRawCounterValue(hCounter pdhCounterHandle, lpdwType *uint32, pValue *PdhRawCounter) uint32 {
ret, _, _ := pdhGetRawCounterValue.Call(
uintptr(hCounter),
uintptr(unsafe.Pointer(lpdwType)), //nolint:gosec // G103: Valid use of unsafe call to pass lpdwType
uintptr(unsafe.Pointer(pValue))) //nolint:gosec // G103: Valid use of unsafe call to pass pValue
@ -629,7 +628,7 @@ func PdhGetRawCounterValue(hCounter PDH_HCOUNTER, lpdwType *uint32, pValue *PDH_
// Handle of the counter for whose current raw instance values you want to retrieve. The PdhAddCounter function returns this handle.
//
// lpdwBufferSize
// Size of the ItemBuffer buffer, in bytes. If zero on input, the function returns PDH_MORE_DATA and sets this parameter to the required buffer size.
// Size of the ItemBuffer buffer, in bytes. If zero on input, the function returns PdhMoreData and sets this parameter to the required buffer size.
// If the buffer is larger than the required size, the function sets this parameter to the actual size of the buffer that was used.
// If the specified size on input is greater than zero but less than the required size, you should not rely on the returned size to reallocate the buffer.
//
@ -637,10 +636,10 @@ func PdhGetRawCounterValue(hCounter PDH_HCOUNTER, lpdwType *uint32, pValue *PDH_
// Number of raw counter values in the ItemBuffer buffer.
//
// ItemBuffer
// Caller-allocated buffer that receives the array of PDH_RAW_COUNTER_ITEM structures; the structures contain the raw instance counter values.
// Caller-allocated buffer that receives the array of PdhRawCounterItem structures; the structures contain the raw instance counter values.
// Set to NULL if lpdwBufferSize is zero.
func PdhGetRawCounterArray(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *byte) uint32 {
ret, _, _ := pdh_GetRawCounterArrayW.Call(
func PdhGetRawCounterArray(hCounter pdhCounterHandle, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *byte) uint32 {
ret, _, _ := pdhGetRawCounterArrayW.Call(
uintptr(hCounter),
uintptr(unsafe.Pointer(lpdwBufferSize)), //nolint:gosec // G103: Valid use of unsafe call to pass lpdwBufferSize
uintptr(unsafe.Pointer(lpdwBufferCount)), //nolint:gosec // G103: Valid use of unsafe call to pass lpdwBufferCount

View File

@ -32,52 +32,53 @@
package win_perf_counters
// Union specialization for double values
type PDH_FMT_COUNTERVALUE_DOUBLE struct {
// PdhFmtCountervalueDouble is a union specialization for double values
type PdhFmtCountervalueDouble struct {
CStatus uint32
padding [4]byte
DoubleValue float64
}
// Union specialization for 64 bit integer values
type PDH_FMT_COUNTERVALUE_LARGE struct {
// PdhFmtCountervalueLarge is a union specialization for 64-bit integer values
type PdhFmtCountervalueLarge struct {
CStatus uint32
padding [4]byte
padding [4]byte //nolint:unused // Memory reservation
LargeValue int64
}
// Union specialization for long values
type PDH_FMT_COUNTERVALUE_LONG struct {
// PdhFmtCountervalueLong is a union specialization for long values
type PdhFmtCountervalueLong struct {
CStatus uint32
LongValue int32
padding [4]byte
padding [4]byte //nolint:unused // Memory reservation
}
type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE struct {
type PdhFmtCountervalueItemDouble struct {
SzName *uint16
padding [4]byte
FmtValue PDH_FMT_COUNTERVALUE_DOUBLE
padding [4]byte //nolint:unused // Memory reservation
FmtValue PdhFmtCountervalueDouble
}
// Union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()
type PDH_FMT_COUNTERVALUE_ITEM_LARGE struct {
// PdhFmtCountervalueItemLarge is a union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()
type PdhFmtCountervalueItemLarge struct {
SzName *uint16 // pointer to a string
padding [4]byte
FmtValue PDH_FMT_COUNTERVALUE_LARGE
padding [4]byte //nolint:unused // Memory reservation
FmtValue PdhFmtCountervalueLarge
}
// Union specialization for long values, used by PdhGetFormattedCounterArrayLong()
type PDH_FMT_COUNTERVALUE_ITEM_LONG struct {
// PdhFmtCountervalueItemLong is a union specialization for long values, used by PdhGetFormattedCounterArrayLong()
type PdhFmtCountervalueItemLong struct {
SzName *uint16 // pointer to a string
padding [4]byte
FmtValue PDH_FMT_COUNTERVALUE_LONG
padding [4]byte //nolint:unused // Memory reservation
FmtValue PdhFmtCountervalueLong
}
// PDH_COUNTER_INFO structure contains information describing the properties of a counter. This information also includes the counter path.
type PDH_COUNTER_INFO struct {
// PdhCounterInfo structure contains information describing the properties of a counter. This information also includes the counter path.
type PdhCounterInfo struct {
//Size of the structure, including the appended strings, in bytes.
DwLength uint32
//Counter type. For a list of counter types, see the Counter Types section of the <a "href=http://go.microsoft.com/fwlink/p/?linkid=84422">Windows Server 2003 Deployment Kit</a>.
//Counter type. For a list of counter types, see the Counter Types section of the
//<a "href=http://go.microsoft.com/fwlink/p/?linkid=84422">Windows Server 2003 Deployment Kit</a>.
//The counter type constants are defined in Winperf.h.
DwType uint32
//Counter version information. Not used.
@ -105,7 +106,8 @@ type PDH_COUNTER_INFO struct {
//Null-terminated string that contains the name of the object instance specified in the counter path. Is NULL, if the path does not specify an instance.
//The string follows this structure in memory.
SzInstanceName *uint16 // pointer to a string
//Null-terminated string that contains the name of the parent instance specified in the counter path. Is NULL, if the path does not specify a parent instance.
//Null-terminated string that contains the name of the parent instance specified in the counter path. Is NULL,
//if the path does not specify a parent instance.
//The string follows this structure in memory.
SzParentInstance *uint16 // pointer to a string
//Instance index specified in the counter path. Is 0, if the path does not specify an instance index.
@ -120,13 +122,14 @@ type PDH_COUNTER_INFO struct {
DataBuffer [1]uint32 // pointer to an extra space
}
// The PDH_RAW_COUNTER structure returns the data as it was collected from the counter provider. No translation, formatting, or other interpretation is performed on the data
type PDH_RAW_COUNTER struct {
// Counter status that indicates if the counter value is valid. Check this member before using the data in a calculation or displaying its value. For a list of possible values,
// see https://docs.microsoft.com/windows/desktop/PerfCtrs/checking-pdh-interface-return-values
// The PdhRawCounter structure returns the data as it was collected from the counter provider. No translation, formatting,
// or other interpretation is performed on the data
type PdhRawCounter struct {
// Counter status that indicates if the counter value is valid. Check this member before using the data in a calculation or displaying its value.
// For a list of possible values, see https://docs.microsoft.com/windows/desktop/PerfCtrs/checking-pdh-interface-return-values
CStatus uint32
// Local time for when the data was collected
TimeStamp FILETIME
TimeStamp fileTime
// First raw counter value.
FirstValue int64
// Second raw counter value. Rate counters require two values in order to compute a displayable value.
@ -136,9 +139,9 @@ type PDH_RAW_COUNTER struct {
MultiCount uint32
}
type PDH_RAW_COUNTER_ITEM struct {
type PdhRawCounterItem struct {
// Pointer to a null-terminated string that specifies the instance name of the counter. The string is appended to the end of this structure.
SzName *uint16
//A PDH_RAW_COUNTER structure that contains the raw counter value of the instance
RawValue PDH_RAW_COUNTER
//A PdhRawCounter structure that contains the raw counter value of the instance
RawValue PdhRawCounter
}

View File

@ -32,45 +32,45 @@
package win_perf_counters
// PDH_FMT_COUNTERVALUE_DOUBLE is an union specialization for double values
type PDH_FMT_COUNTERVALUE_DOUBLE struct {
// PdhFmtCountervalueDouble is a union specialization for double values
type PdhFmtCountervalueDouble struct {
CStatus uint32
DoubleValue float64
}
// PDH_FMT_COUNTERVALUE_LARGE is a union specialization for 64-bit integer values
type PDH_FMT_COUNTERVALUE_LARGE struct {
// PdhFmtCountervalueLarge is a union specialization for 64-bit integer values
type PdhFmtCountervalueLarge struct {
CStatus uint32
LargeValue int64
}
// PDH_FMT_COUNTERVALUE_LONG is a union specialization for long values
type PDH_FMT_COUNTERVALUE_LONG struct {
// PdhFmtCountervalueLong is a union specialization for long values
type PdhFmtCountervalueLong struct {
CStatus uint32
LongValue int32
padding [4]byte
padding [4]byte //nolint:unused // Memory reservation
}
// PDH_FMT_COUNTERVALUE_ITEM_DOUBLE is a union specialization for double values, used by PdhGetFormattedCounterArrayDouble
type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE struct {
// PdhFmtCountervalueItemDouble is a union specialization for double values, used by PdhGetFormattedCounterArrayDouble
type PdhFmtCountervalueItemDouble struct {
SzName *uint16
FmtValue PDH_FMT_COUNTERVALUE_DOUBLE
FmtValue PdhFmtCountervalueDouble
}
// PDH_FMT_COUNTERVALUE_ITEM_LARGE is n union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()
type PDH_FMT_COUNTERVALUE_ITEM_LARGE struct {
// PdhFmtCountervalueItemLarge is a union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()
type PdhFmtCountervalueItemLarge struct {
SzName *uint16 // pointer to a string
FmtValue PDH_FMT_COUNTERVALUE_LARGE
FmtValue PdhFmtCountervalueLarge
}
// PDH_FMT_COUNTERVALUE_ITEM_LONG is n union specialization for long values, used by PdhGetFormattedCounterArrayLong()
type PDH_FMT_COUNTERVALUE_ITEM_LONG struct {
// PdhFmtCountervalueItemLong is a union specialization for long values, used by PdhGetFormattedCounterArrayLong()
type PdhFmtCountervalueItemLong struct {
SzName *uint16 // pointer to a string
FmtValue PDH_FMT_COUNTERVALUE_LONG
FmtValue PdhFmtCountervalueLong
}
// PDH_COUNTER_INFO structure contains information describing the properties of a counter. This information also includes the counter path.
type PDH_COUNTER_INFO struct {
// PdhCounterInfo structure contains information describing the properties of a counter. This information also includes the counter path.
type PdhCounterInfo struct {
//Size of the structure, including the appended strings, in bytes.
DwLength uint32
//Counter type. For a list of counter types,
@ -115,14 +115,14 @@ type PDH_COUNTER_INFO struct {
DataBuffer [1]uint32 // pointer to an extra space
}
// The PDH_RAW_COUNTER structure returns the data as it was collected from the counter provider.
// The PdhRawCounter structure returns the data as it was collected from the counter provider.
// No translation, formatting, or other interpretation is performed on the data
type PDH_RAW_COUNTER struct {
type PdhRawCounter struct {
// Counter status that indicates if the counter value is valid. Check this member before using the data in a calculation or displaying its value.
// For a list of possible values, see https://docs.microsoft.com/windows/desktop/PerfCtrs/checking-pdh-interface-return-values
CStatus uint32
// Local time for when the data was collected
TimeStamp FILETIME
TimeStamp fileTime
// First raw counter value.
FirstValue int64
// Second raw counter value. Rate counters require two values in order to compute a displayable value.
@ -132,9 +132,9 @@ type PDH_RAW_COUNTER struct {
MultiCount uint32
}
type PDH_RAW_COUNTER_ITEM struct {
type PdhRawCounterItem struct {
// Pointer to a null-terminated string that specifies the instance name of the counter. The string is appended to the end of this structure.
SzName *uint16
//A PDH_RAW_COUNTER structure that contains the raw counter value of the instance
RawValue PDH_RAW_COUNTER
//A PdhRawCounter structure that contains the raw counter value of the instance
RawValue PdhRawCounter
}

View File

@ -32,47 +32,48 @@
package win_perf_counters
// Union specialization for double values
type PDH_FMT_COUNTERVALUE_DOUBLE struct {
// PdhFmtCountervalueDouble is a union specialization for double values
type PdhFmtCountervalueDouble struct {
CStatus uint32
DoubleValue float64
}
// Union specialization for 64 bit integer values
type PDH_FMT_COUNTERVALUE_LARGE struct {
// PdhFmtCountervalueLarge is a union specialization for 64-bit integer values
type PdhFmtCountervalueLarge struct {
CStatus uint32
LargeValue int64
}
// Union specialization for long values
type PDH_FMT_COUNTERVALUE_LONG struct {
// PdhFmtCountervalueLong is a union specialization for long values
type PdhFmtCountervalueLong struct {
CStatus uint32
LongValue int32
padding [4]byte
padding [4]byte //nolint:unused // Memory reservation
}
type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE struct {
type PdhFmtCountervalueItemDouble struct {
SzName *uint16
FmtValue PDH_FMT_COUNTERVALUE_DOUBLE
FmtValue PdhFmtCountervalueDouble
}
// Union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()
type PDH_FMT_COUNTERVALUE_ITEM_LARGE struct {
// PdhFmtCountervalueItemLarge is a union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()
type PdhFmtCountervalueItemLarge struct {
SzName *uint16 // pointer to a string
FmtValue PDH_FMT_COUNTERVALUE_LARGE
FmtValue PdhFmtCountervalueLarge
}
// Union specialization for long values, used by PdhGetFormattedCounterArrayLong()
type PDH_FMT_COUNTERVALUE_ITEM_LONG struct {
// PdhFmtCountervalueItemLong is a union specialization for long values, used by PdhGetFormattedCounterArrayLong()
type PdhFmtCountervalueItemLong struct {
SzName *uint16 // pointer to a string
FmtValue PDH_FMT_COUNTERVALUE_LONG
FmtValue PdhFmtCountervalueLong
}
// PDH_COUNTER_INFO structure contains information describing the properties of a counter. This information also includes the counter path.
type PDH_COUNTER_INFO struct {
// PdhCounterInfo structure contains information describing the properties of a counter. This information also includes the counter path.
type PdhCounterInfo struct {
//Size of the structure, including the appended strings, in bytes.
DwLength uint32
//Counter type. For a list of counter types, see the Counter Types section of the <a "href=http://go.microsoft.com/fwlink/p/?linkid=84422">Windows Server 2003 Deployment Kit</a>.
//Counter type. For a list of counter types, see the Counter Types section
//of the Windows Server 2003 Deployment Kit (http://go.microsoft.com/fwlink/p/?linkid=84422).
//The counter type constants are defined in Winperf.h.
DwType uint32
//Counter version information. Not used.
@ -100,7 +101,8 @@ type PDH_COUNTER_INFO struct {
//Null-terminated string that contains the name of the object instance specified in the counter path. Is NULL, if the path does not specify an instance.
//The string follows this structure in memory.
SzInstanceName *uint16 // pointer to a string
//Null-terminated string that contains the name of the parent instance specified in the counter path. Is NULL, if the path does not specify a parent instance.
//Null-terminated string that contains the name of the parent instance specified in the counter path.
//Is NULL, if the path does not specify a parent instance.
//The string follows this structure in memory.
SzParentInstance *uint16 // pointer to a string
//Instance index specified in the counter path. Is 0, if the path does not specify an instance index.
@ -113,13 +115,14 @@ type PDH_COUNTER_INFO struct {
DataBuffer [1]uint32 // pointer to an extra space
}
// The PDH_RAW_COUNTER structure returns the data as it was collected from the counter provider. No translation, formatting, or other interpretation is performed on the data
type PDH_RAW_COUNTER struct {
// Counter status that indicates if the counter value is valid. Check this member before using the data in a calculation or displaying its value. For a list of possible values,
// see https://docs.microsoft.com/windows/desktop/PerfCtrs/checking-pdh-interface-return-values
// The PdhRawCounter structure returns the data as it was collected from the counter provider.
// No translation, formatting, or other interpretation is performed on the data.
type PdhRawCounter struct {
// Counter status that indicates if the counter value is valid. Check this member before using the data in a calculation or displaying its value.
// For a list of possible values, see https://docs.microsoft.com/windows/desktop/PerfCtrs/checking-pdh-interface-return-values
CStatus uint32
// Local time for when the data was collected
TimeStamp FILETIME
TimeStamp fileTime
// First raw counter value.
FirstValue int64
// Second raw counter value. Rate counters require two values in order to compute a displayable value.
@ -129,9 +132,9 @@ type PDH_RAW_COUNTER struct {
MultiCount uint32
}
type PDH_RAW_COUNTER_ITEM struct {
type PdhRawCounterItem struct {
// Pointer to a null-terminated string that specifies the instance name of the counter. The string is appended to the end of this structure.
SzName *uint16
//A PDH_RAW_COUNTER structure that contains the raw counter value of the instance
RawValue PDH_RAW_COUNTER
//A PdhRawCounter structure that contains the raw counter value of the instance
RawValue PdhRawCounter
}

View File

@ -10,7 +10,7 @@ import (
"unsafe"
)
// CounterValue is abstraction for PDH_FMT_COUNTERVALUE_ITEM_DOUBLE
// CounterValue is abstraction for PdhFmtCountervalueItemDouble
type CounterValue struct {
InstanceName string
Value interface{}
@ -22,14 +22,14 @@ type CounterValue struct {
type PerformanceQuery interface {
Open() error
Close() error
AddCounterToQuery(counterPath string) (PDH_HCOUNTER, error)
AddEnglishCounterToQuery(counterPath string) (PDH_HCOUNTER, error)
GetCounterPath(counterHandle PDH_HCOUNTER) (string, error)
AddCounterToQuery(counterPath string) (pdhCounterHandle, error)
AddEnglishCounterToQuery(counterPath string) (pdhCounterHandle, error)
GetCounterPath(counterHandle pdhCounterHandle) (string, error)
ExpandWildCardPath(counterPath string) ([]string, error)
GetFormattedCounterValueDouble(hCounter PDH_HCOUNTER) (float64, error)
GetRawCounterValue(hCounter PDH_HCOUNTER) (int64, error)
GetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER) ([]CounterValue, error)
GetRawCounterArray(hCounter PDH_HCOUNTER) ([]CounterValue, error)
GetFormattedCounterValueDouble(hCounter pdhCounterHandle) (float64, error)
GetRawCounterValue(hCounter pdhCounterHandle) (int64, error)
GetFormattedCounterArrayDouble(hCounter pdhCounterHandle) ([]CounterValue, error)
GetRawCounterArray(hCounter pdhCounterHandle) ([]CounterValue, error)
CollectData() error
CollectDataWithTime() (time.Time, error)
IsVistaOrNewer() bool
@ -58,7 +58,7 @@ func NewPdhError(code uint32) error {
// PerformanceQueryImpl is implementation of PerformanceQuery interface, which calls phd.dll functions
type PerformanceQueryImpl struct {
query PDH_HQUERY
query pdhQueryHandle
}
type PerformanceQueryCreatorImpl struct {
@ -77,9 +77,9 @@ func (m *PerformanceQueryImpl) Open() error {
return err
}
}
var handle PDH_HQUERY
var handle pdhQueryHandle
if ret := PdhOpenQuery(0, 0, &handle); ret != ERROR_SUCCESS {
if ret := PdhOpenQuery(0, 0, &handle); ret != ErrorSuccess {
return NewPdhError(ret)
}
m.query = handle
@ -92,46 +92,46 @@ func (m *PerformanceQueryImpl) Close() error {
return errors.New("uninitialized query")
}
if ret := PdhCloseQuery(m.query); ret != ERROR_SUCCESS {
if ret := PdhCloseQuery(m.query); ret != ErrorSuccess {
return NewPdhError(ret)
}
m.query = 0
return nil
}
func (m *PerformanceQueryImpl) AddCounterToQuery(counterPath string) (PDH_HCOUNTER, error) {
var counterHandle PDH_HCOUNTER
func (m *PerformanceQueryImpl) AddCounterToQuery(counterPath string) (pdhCounterHandle, error) {
var counterHandle pdhCounterHandle
if m.query == 0 {
return 0, errors.New("uninitialized query")
}
if ret := PdhAddCounter(m.query, counterPath, 0, &counterHandle); ret != ERROR_SUCCESS {
if ret := PdhAddCounter(m.query, counterPath, 0, &counterHandle); ret != ErrorSuccess {
return 0, NewPdhError(ret)
}
return counterHandle, nil
}
func (m *PerformanceQueryImpl) AddEnglishCounterToQuery(counterPath string) (PDH_HCOUNTER, error) {
var counterHandle PDH_HCOUNTER
func (m *PerformanceQueryImpl) AddEnglishCounterToQuery(counterPath string) (pdhCounterHandle, error) {
var counterHandle pdhCounterHandle
if m.query == 0 {
return 0, errors.New("uninitialized query")
}
if ret := PdhAddEnglishCounter(m.query, counterPath, 0, &counterHandle); ret != ERROR_SUCCESS {
if ret := PdhAddEnglishCounter(m.query, counterPath, 0, &counterHandle); ret != ErrorSuccess {
return 0, NewPdhError(ret)
}
return counterHandle, nil
}
// GetCounterPath return counter information for given handle
func (m *PerformanceQueryImpl) GetCounterPath(counterHandle PDH_HCOUNTER) (string, error) {
func (m *PerformanceQueryImpl) GetCounterPath(counterHandle pdhCounterHandle) (string, error) {
var bufSize uint32
var buff []byte
var ret uint32
if ret = PdhGetCounterInfo(counterHandle, 0, &bufSize, nil); ret == PDH_MORE_DATA {
if ret = PdhGetCounterInfo(counterHandle, 0, &bufSize, nil); ret == PdhMoreData {
buff = make([]byte, bufSize)
bufSize = uint32(len(buff))
if ret = PdhGetCounterInfo(counterHandle, 0, &bufSize, &buff[0]); ret == ERROR_SUCCESS {
ci := (*PDH_COUNTER_INFO)(unsafe.Pointer(&buff[0])) //nolint:gosec // G103: Valid use of unsafe call to create PDH_COUNTER_INFO
if ret = PdhGetCounterInfo(counterHandle, 0, &bufSize, &buff[0]); ret == ErrorSuccess {
ci := (*PdhCounterInfo)(unsafe.Pointer(&buff[0])) //nolint:gosec // G103: Valid use of unsafe call to create PDH_COUNTER_INFO
return UTF16PtrToString(ci.SzFullPath), nil
}
}
@ -144,11 +144,11 @@ func (m *PerformanceQueryImpl) ExpandWildCardPath(counterPath string) ([]string,
var buff []uint16
var ret uint32
if ret = PdhExpandWildCardPath(counterPath, nil, &bufSize); ret == PDH_MORE_DATA {
if ret = PdhExpandWildCardPath(counterPath, nil, &bufSize); ret == PdhMoreData {
buff = make([]uint16, bufSize)
bufSize = uint32(len(buff))
ret = PdhExpandWildCardPath(counterPath, &buff[0], &bufSize)
if ret == ERROR_SUCCESS {
if ret == ErrorSuccess {
list := UTF16ToStringArray(buff)
return list, nil
}
@ -157,36 +157,34 @@ func (m *PerformanceQueryImpl) ExpandWildCardPath(counterPath string) ([]string,
}
// GetFormattedCounterValueDouble computes a displayable value for the specified counter
func (m *PerformanceQueryImpl) GetFormattedCounterValueDouble(hCounter PDH_HCOUNTER) (float64, error) {
func (m *PerformanceQueryImpl) GetFormattedCounterValueDouble(hCounter pdhCounterHandle) (float64, error) {
var counterType uint32
var value PDH_FMT_COUNTERVALUE_DOUBLE
var value PdhFmtCountervalueDouble
var ret uint32
if ret = PdhGetFormattedCounterValueDouble(hCounter, &counterType, &value); ret == ERROR_SUCCESS {
if value.CStatus == PDH_CSTATUS_VALID_DATA || value.CStatus == PDH_CSTATUS_NEW_DATA {
if ret = PdhGetFormattedCounterValueDouble(hCounter, &counterType, &value); ret == ErrorSuccess {
if value.CStatus == PdhCstatusValidData || value.CStatus == PdhCstatusNewData {
return value.DoubleValue, nil
} else {
return 0, NewPdhError(value.CStatus)
}
} else {
return 0, NewPdhError(ret)
return 0, NewPdhError(value.CStatus)
}
return 0, NewPdhError(ret)
}
func (m *PerformanceQueryImpl) GetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER) ([]CounterValue, error) {
func (m *PerformanceQueryImpl) GetFormattedCounterArrayDouble(hCounter pdhCounterHandle) ([]CounterValue, error) {
var buffSize uint32
var itemCount uint32
var ret uint32
if ret = PdhGetFormattedCounterArrayDouble(hCounter, &buffSize, &itemCount, nil); ret == PDH_MORE_DATA {
if ret = PdhGetFormattedCounterArrayDouble(hCounter, &buffSize, &itemCount, nil); ret == PdhMoreData {
buff := make([]byte, buffSize)
if ret = PdhGetFormattedCounterArrayDouble(hCounter, &buffSize, &itemCount, &buff[0]); ret == ERROR_SUCCESS {
if ret = PdhGetFormattedCounterArrayDouble(hCounter, &buffSize, &itemCount, &buff[0]); ret == ErrorSuccess {
//nolint:gosec // G103: Valid use of unsafe call to create PDH_FMT_COUNTERVALUE_ITEM_DOUBLE
items := (*[1 << 20]PDH_FMT_COUNTERVALUE_ITEM_DOUBLE)(unsafe.Pointer(&buff[0]))[:itemCount]
items := (*[1 << 20]PdhFmtCountervalueItemDouble)(unsafe.Pointer(&buff[0]))[:itemCount]
values := make([]CounterValue, 0, itemCount)
for _, item := range items {
if item.FmtValue.CStatus == PDH_CSTATUS_VALID_DATA || item.FmtValue.CStatus == PDH_CSTATUS_NEW_DATA {
if item.FmtValue.CStatus == PdhCstatusValidData || item.FmtValue.CStatus == PdhCstatusNewData {
val := CounterValue{UTF16PtrToString(item.SzName), item.FmtValue.DoubleValue}
values = append(values, val)
}
@ -197,20 +195,20 @@ func (m *PerformanceQueryImpl) GetFormattedCounterArrayDouble(hCounter PDH_HCOUN
return nil, NewPdhError(ret)
}
func (m *PerformanceQueryImpl) GetRawCounterArray(hCounter PDH_HCOUNTER) ([]CounterValue, error) {
func (m *PerformanceQueryImpl) GetRawCounterArray(hCounter pdhCounterHandle) ([]CounterValue, error) {
var buffSize uint32
var itemCount uint32
var ret uint32
if ret = PdhGetRawCounterArray(hCounter, &buffSize, &itemCount, nil); ret == PDH_MORE_DATA {
if ret = PdhGetRawCounterArray(hCounter, &buffSize, &itemCount, nil); ret == PdhMoreData {
buff := make([]byte, buffSize)
if ret = PdhGetRawCounterArray(hCounter, &buffSize, &itemCount, &buff[0]); ret == ERROR_SUCCESS {
if ret = PdhGetRawCounterArray(hCounter, &buffSize, &itemCount, &buff[0]); ret == ErrorSuccess {
//nolint:gosec // G103: Valid use of unsafe call to create PDH_RAW_COUNTER_ITEM
items := (*[1 << 20]PDH_RAW_COUNTER_ITEM)(unsafe.Pointer(&buff[0]))[:itemCount]
items := (*[1 << 20]PdhRawCounterItem)(unsafe.Pointer(&buff[0]))[:itemCount]
values := make([]CounterValue, 0, itemCount)
for _, item := range items {
if item.RawValue.CStatus == PDH_CSTATUS_VALID_DATA || item.RawValue.CStatus == PDH_CSTATUS_NEW_DATA {
if item.RawValue.CStatus == PdhCstatusValidData || item.RawValue.CStatus == PdhCstatusNewData {
val := CounterValue{UTF16PtrToString(item.SzName), item.RawValue.FirstValue}
values = append(values, val)
}
@ -227,7 +225,7 @@ func (m *PerformanceQueryImpl) CollectData() error {
return errors.New("uninitialized query")
}
if ret = PdhCollectQueryData(m.query); ret != ERROR_SUCCESS {
if ret = PdhCollectQueryData(m.query); ret != ErrorSuccess {
return NewPdhError(ret)
}
return nil
@ -238,7 +236,7 @@ func (m *PerformanceQueryImpl) CollectDataWithTime() (time.Time, error) {
return time.Now(), errors.New("uninitialized query")
}
ret, mtime := PdhCollectQueryDataWithTime(m.query)
if ret != ERROR_SUCCESS {
if ret != ErrorSuccess {
return time.Now(), NewPdhError(ret)
}
return mtime, nil
@ -248,25 +246,22 @@ func (m *PerformanceQueryImpl) IsVistaOrNewer() bool {
return PdhAddEnglishCounterSupported()
}
func (m *PerformanceQueryImpl) GetRawCounterValue(hCounter PDH_HCOUNTER) (int64, error) {
func (m *PerformanceQueryImpl) GetRawCounterValue(hCounter pdhCounterHandle) (int64, error) {
if m.query == 0 {
return 0, errors.New("uninitialised query")
}
var counterType uint32
var value PDH_RAW_COUNTER
var value PdhRawCounter
var ret uint32
if ret = PdhGetRawCounterValue(hCounter, &counterType, &value); ret == ERROR_SUCCESS {
if value.CStatus == PDH_CSTATUS_VALID_DATA || value.CStatus == PDH_CSTATUS_NEW_DATA {
if ret = PdhGetRawCounterValue(hCounter, &counterType, &value); ret == ErrorSuccess {
if value.CStatus == PdhCstatusValidData || value.CStatus == PdhCstatusNewData {
return value.FirstValue, nil
} else {
return 0, NewPdhError(value.CStatus)
}
} else {
return 0, NewPdhError(ret)
return 0, NewPdhError(value.CStatus)
}
return 0, NewPdhError(ret)
}
// UTF16PtrToString converts Windows API LPTSTR (pointer to string) to go string

View File

@ -24,7 +24,7 @@ type WinPerfCounters struct {
PrintValid bool `toml:"PrintValid"`
PreVistaSupport bool `toml:"PreVistaSupport" deprecated:"1.7.0;determined dynamically"`
UsePerfCounterTime bool
Object []perfobject
Object []perfObject
CountersRefreshInterval config.Duration
UseWildcardsExpansion bool
LocalizeWildcardsExpansion bool
@ -50,7 +50,7 @@ type hostCountersInfo struct {
timestamp time.Time
}
type perfobject struct {
type perfObject struct {
Sources []string
ObjectName string
Counters []string
@ -71,13 +71,13 @@ type counter struct {
measurement string
includeTotal bool
useRawValue bool
counterHandle PDH_HCOUNTER
counterHandle pdhCounterHandle
}
type instanceGrouping struct {
name string
instance string
objectname string
objectName string
}
type fieldGrouping map[instanceGrouping]map[string]interface{}
@ -88,7 +88,9 @@ var sanitizedChars = strings.NewReplacer("/sec", "_persec", "/Sec", "_persec",
// extractCounterInfoFromCounterPath gets object name, instance name (if available) and counter name from counter path
// General Counter path pattern is: \\computer\object(parent/instance#index)\counter
// parent/instance#index part is skipped in single instance objects (e.g. Memory): \\computer\object\counter
func extractCounterInfoFromCounterPath(counterPath string) (string, string, string, string, error) {
//
//nolint:revive //function-result-limit conditionally 5 return results allowed
func extractCounterInfoFromCounterPath(counterPath string) (computer string, object string, instance string, counter string, err error) {
leftComputerBorderIndex := -1
rightObjectBorderIndex := -1
leftObjectBorderIndex := -1
@ -129,7 +131,6 @@ func extractCounterInfoFromCounterPath(counterPath string) (string, string, stri
return "", "", "", "", errors.New("cannot parse object from: " + counterPath)
}
var computer, object, instance, counter string
if leftComputerBorderIndex > -1 {
// validate there is leading \\ and not empty computer (\\\O)
if leftComputerBorderIndex != 1 || leftComputerBorderIndex == leftObjectBorderIndex-1 {
@ -165,8 +166,9 @@ func (m *WinPerfCounters) hostname() string {
return m.cachedHostname
}
//nolint:revive //argument-limit conditionally more arguments allowed for helper function
func newCounter(
counterHandle PDH_HCOUNTER,
counterHandle pdhCounterHandle,
counterPath string,
computer string,
objectName string,
@ -188,10 +190,11 @@ func newCounter(
includeTotal, useRawValue, counterHandle}
}
//nolint:revive //argument-limit conditionally more arguments allowed
func (m *WinPerfCounters) AddItem(counterPath, computer, objectName, instance, counterName, measurement string, includeTotal bool, useRawValue bool) error {
origCounterPath := counterPath
var err error
var counterHandle PDH_HCOUNTER
var counterHandle pdhCounterHandle
sourceTag := computer
if computer == "localhost" {
@ -330,12 +333,12 @@ func (m *WinPerfCounters) AddItem(counterPath, computer, objectName, instance, c
const emptyInstance = "------"
func formatPath(computer, objectname, instance, counter string) string {
func formatPath(computer, objectName, instance, counter string) string {
path := ""
if instance == emptyInstance {
path = fmt.Sprintf(`\%s\%s`, objectname, counter)
path = fmt.Sprintf(`\%s\%s`, objectName, counter)
} else {
path = fmt.Sprintf(`\%s(%s)\%s`, objectname, instance, counter)
path = fmt.Sprintf(`\%s(%s)\%s`, objectName, instance, counter)
}
if computer != "" && computer != "localhost" {
path = fmt.Sprintf(`\\%s%s`, computer, path)
@ -370,11 +373,10 @@ func (m *WinPerfCounters) ParseConfig() error {
m.Log.Warnf("Missing 'Instances' param for object %q", PerfObject.ObjectName)
}
for _, instance := range PerfObject.Instances {
objectname := PerfObject.ObjectName
objectName := PerfObject.ObjectName
counterPath = formatPath(computer, objectName, instance, counter)
counterPath = formatPath(computer, objectname, instance, counter)
err := m.AddItem(counterPath, computer, objectname, instance, counter,
err := m.AddItem(counterPath, computer, objectName, instance, counter,
PerfObject.Measurement, PerfObject.IncludeTotal, PerfObject.UseRawValues)
if err != nil {
if PerfObject.FailOnMissing || PerfObject.WarnOnMissing {
@ -500,7 +502,6 @@ func (m *WinPerfCounters) gatherComputerCounters(hostCounterInfo *hostCountersIn
continue
}
for _, cValue := range counterValues {
if strings.Contains(metric.instance, "#") && strings.HasPrefix(metric.instance, cValue.InstanceName) {
// If you are using a multiple instance identifier such as "w3wp#1"
// phd.dll returns only the first 2 characters of the identifier.
@ -515,7 +516,7 @@ func (m *WinPerfCounters) gatherComputerCounters(hostCounterInfo *hostCountersIn
}
for instance, fields := range collectedFields {
var tags = map[string]string{
"objectname": instance.objectname,
"objectname": instance.objectName,
}
if len(instance.instance) > 0 {
tags["instance"] = instance.instance
@ -526,7 +527,6 @@ func (m *WinPerfCounters) gatherComputerCounters(hostCounterInfo *hostCountersIn
acc.AddFields(instance.name, fields, tags, hostCounterInfo.timestamp)
}
return nil
}
func (m *WinPerfCounters) cleanQueries() error {
@ -568,11 +568,11 @@ func addCounterMeasurement(metric *counter, instanceName string, value interface
func isKnownCounterDataError(err error) bool {
var pdhErr *PdhError
if errors.As(err, &pdhErr) && (pdhErr.ErrorCode == PDH_INVALID_DATA ||
pdhErr.ErrorCode == PDH_CALC_NEGATIVE_DENOMINATOR ||
pdhErr.ErrorCode == PDH_CALC_NEGATIVE_VALUE ||
pdhErr.ErrorCode == PDH_CSTATUS_INVALID_DATA ||
pdhErr.ErrorCode == PDH_NO_DATA) {
if errors.As(err, &pdhErr) && (pdhErr.ErrorCode == PdhInvalidData ||
pdhErr.ErrorCode == PdhCalcNegativeDenominator ||
pdhErr.ErrorCode == PdhCalcNegativeValue ||
pdhErr.ErrorCode == PdhCstatusInvalidData ||
pdhErr.ErrorCode == PdhNoData) {
return true
}
return false

View File

@ -18,40 +18,34 @@ func TestWinPerformanceQueryImplIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var query PerformanceQuery
var hCounter PDH_HCOUNTER
var err error
query = &PerformanceQueryImpl{}
query := &PerformanceQueryImpl{}
err = query.Close()
err := query.Close()
require.Error(t, err, "uninitialized query must return errors")
_, err = query.AddCounterToQuery("")
require.Error(t, err, "uninitialized query must return errors")
require.True(t, strings.Contains(err.Error(), "uninitialized"))
require.ErrorContains(t, err, "uninitialized")
_, err = query.AddEnglishCounterToQuery("")
require.Error(t, err, "uninitialized query must return errors")
require.True(t, strings.Contains(err.Error(), "uninitialized"))
require.ErrorContains(t, err, "uninitialized")
err = query.CollectData()
require.Error(t, err, "uninitialized query must return errors")
require.True(t, strings.Contains(err.Error(), "uninitialized"))
require.ErrorContains(t, err, "uninitialized")
err = query.Open()
require.NoError(t, err)
require.NoError(t, query.Open())
counterPath := "\\Processor Information(_Total)\\% Processor Time"
hCounter, err = query.AddCounterToQuery(counterPath)
hCounter, err := query.AddCounterToQuery(counterPath)
require.NoError(t, err)
require.NotEqual(t, 0, hCounter)
err = query.Close()
require.NoError(t, err)
require.NoError(t, query.Close())
err = query.Open()
require.NoError(t, err)
require.NoError(t, query.Open())
hCounter, err = query.AddEnglishCounterToQuery(counterPath)
require.NoError(t, err)
@ -61,12 +55,10 @@ func TestWinPerformanceQueryImplIntegration(t *testing.T) {
require.NoError(t, err)
require.True(t, strings.HasSuffix(cp, counterPath))
err = query.CollectData()
require.NoError(t, err)
require.NoError(t, query.CollectData())
time.Sleep(time.Second)
err = query.CollectData()
require.NoError(t, err)
require.NoError(t, query.CollectData())
fcounter, err := query.GetFormattedCounterValueDouble(hCounter)
require.NoError(t, err)
@ -93,24 +85,21 @@ func TestWinPerformanceQueryImplIntegration(t *testing.T) {
require.NotNil(t, paths)
require.True(t, len(paths) > 1)
err = query.Open()
require.NoError(t, err)
require.NoError(t, query.Open())
counterPath = "\\Process(*)\\% Processor Time"
hCounter, err = query.AddEnglishCounterToQuery(counterPath)
require.NoError(t, err)
require.NotEqual(t, 0, hCounter)
err = query.CollectData()
require.NoError(t, err)
require.NoError(t, query.CollectData())
time.Sleep(time.Second)
err = query.CollectData()
require.NoError(t, err)
require.NoError(t, query.CollectData())
farr, err := query.GetFormattedCounterArrayDouble(hCounter)
var phdErr *PdhError
if errors.As(err, &phdErr) && phdErr.ErrorCode != PDH_INVALID_DATA && phdErr.ErrorCode != PDH_CALC_NEGATIVE_VALUE {
if errors.As(err, &phdErr) && phdErr.ErrorCode != PdhInvalidData && phdErr.ErrorCode != PdhCalcNegativeValue {
time.Sleep(time.Second)
farr, err = query.GetFormattedCounterArrayDouble(hCounter)
}
@ -121,85 +110,61 @@ func TestWinPerformanceQueryImplIntegration(t *testing.T) {
require.NoError(t, err)
require.True(t, len(rarr) > 0, "Too")
err = query.Close()
require.NoError(t, err)
require.NoError(t, query.Close())
}
func TestWinPerfcountersConfigGet1Integration(t *testing.T) {
func TestWinPerfCountersConfigGet1Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
counters[0] = "% Processor Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total"}
counters := []string{"% Processor Time"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
}
func TestWinPerfcountersConfigGet2Integration(t *testing.T) {
func TestWinPerfCountersConfigGet2Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
counters[0] = "% Processor Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total"}
counters := []string{"% Processor Time"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok)
@ -215,46 +180,33 @@ func TestWinPerfcountersConfigGet2Integration(t *testing.T) {
}
}
func TestWinPerfcountersConfigGet3Integration(t *testing.T) {
func TestWinPerfCountersConfigGet3Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var sources = make([]string, 1)
var instances = make([]string, 1)
var counters = make([]string, 2)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
counters[0] = "% Processor Time"
counters[1] = "% Idle Time"
sources[0] = "localhost"
var measurement = "test"
PerfObject := perfobject{
sources := []string{"localhost"}
instances := []string{"_Total"}
counters := []string{"% Processor Time", "% Idle Time"}
perfObjects := []perfObject{{
Sources: sources,
ObjectName: objectname,
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok)
@ -270,43 +222,31 @@ func TestWinPerfcountersConfigGet3Integration(t *testing.T) {
}
}
func TestWinPerfcountersConfigGet4Integration(t *testing.T) {
func TestWinPerfCountersConfigGet4Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 2)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
instances[1] = "0,1"
counters[0] = "% Processor Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total", "0,1"}
counters := []string{"% Processor Time"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok)
@ -322,44 +262,31 @@ func TestWinPerfcountersConfigGet4Integration(t *testing.T) {
}
}
func TestWinPerfcountersConfigGet5Integration(t *testing.T) {
func TestWinPerfCountersConfigGet5Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 2)
var counters = make([]string, 2)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
instances[1] = "0,1"
counters[0] = "% Processor Time"
counters[1] = "% Idle Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total", "0,1"}
counters := []string{"% Processor Time", "% Idle Time"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok)
@ -375,82 +302,58 @@ func TestWinPerfcountersConfigGet5Integration(t *testing.T) {
}
}
func TestWinPerfcountersConfigGet6Integration(t *testing.T) {
func TestWinPerfCountersConfigGet6Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "System"
instances[0] = "------"
counters[0] = "Context Switches/sec"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"------"}
counters := []string{"Context Switches/sec"}
perfObjects := []perfObject{{
ObjectName: "System",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
_, ok := m.hostCounters["localhost"]
require.True(t, ok)
}
func TestWinPerfcountersConfigGet7Integration(t *testing.T) {
func TestWinPerfCountersConfigGet7Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 3)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
counters[0] = "% Processor Time"
counters[1] = "% Processor TimeERROR"
counters[2] = "% Idle Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total"}
counters := []string{"% Processor Time", "% Processor TimeERROR", "% Idle Time"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Counters: counters,
Instances: instances,
Measurement: measurement,
}
perfobjects[0] = PerfObject
Measurement: "test",
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.NoError(t, err)
require.NoError(t, m.ParseConfig())
hostCounters, ok := m.hostCounters["localhost"]
require.True(t, ok)
@ -466,271 +369,199 @@ func TestWinPerfcountersConfigGet7Integration(t *testing.T) {
}
}
func TestWinPerfcountersConfigError1Integration(t *testing.T) {
func TestWinPerfCountersConfigError1Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor InformationERROR"
instances[0] = "_Total"
counters[0] = "% Processor Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total"}
counters := []string{"% Processor Time"}
perfObjects := []perfObject{{
ObjectName: "Processor InformationERROR",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.Error(t, err)
}
func TestWinPerfcountersConfigError2Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor"
instances[0] = "SuperERROR"
counters[0] = "% C1 Time"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
Instances: instances,
Counters: counters,
Measurement: measurement,
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
require.Error(t, m.ParseConfig())
}
func TestWinPerfCountersConfigError2Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
instances := []string{"SuperERROR"}
counters := []string{"% C1 Time"}
perfObjects := []perfObject{{
ObjectName: "Processor",
Instances: instances,
Counters: counters,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
require.NoError(t, m.ParseConfig())
var acc testutil.Accumulator
require.Error(t, m.Gather(&acc))
}
func TestWinPerfcountersConfigError3Integration(t *testing.T) {
func TestWinPerfCountersConfigError3Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
counters[0] = "% Processor TimeERROR"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total"}
counters := []string{"% Processor TimeERROR"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
err := m.ParseConfig()
require.Error(t, err)
require.Error(t, m.ParseConfig())
}
func TestWinPerfcountersCollect1Integration(t *testing.T) {
func TestWinPerfCountersCollect1Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
counters[0] = "Parking Status"
var expectedCounter = "Parking_Status"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total"}
counters := []string{"Parking Status"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
Log: testutil.Logger{},
}
var acc testutil.Accumulator
err := m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
time.Sleep(2000 * time.Millisecond)
err = m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
require.Len(t, acc.Metrics, 2)
for _, metric := range acc.Metrics {
_, ok := metric.Fields[expectedCounter]
_, ok := metric.Fields["Parking_Status"]
require.True(t, ok)
}
}
func TestWinPerfcountersCollect2Integration(t *testing.T) {
func TestWinPerfCountersCollect2Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 2)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor Information"
instances[0] = "_Total"
instances[1] = "0,0"
counters[0] = "Performance Limit Flags"
var expectedCounter = "Performance_Limit_Flags"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"_Total", "0,0"}
counters := []string{"Performance Limit Flags"}
perfObjects := []perfObject{{
ObjectName: "Processor Information",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
UsePerfCounterTime: true,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
UseWildcardsExpansion: true,
Log: testutil.Logger{},
}
var acc testutil.Accumulator
err := m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
time.Sleep(2000 * time.Millisecond)
err = m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
require.Len(t, acc.Metrics, 4)
for _, metric := range acc.Metrics {
_, ok := metric.Fields[expectedCounter]
_, ok := metric.Fields["Performance_Limit_Flags"]
require.True(t, ok)
}
}
func TestWinPerfcountersCollectRawIntegration(t *testing.T) {
func TestWinPerfCountersCollectRawIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
var instances = make([]string, 1)
var counters = make([]string, 1)
var perfobjects = make([]perfobject, 1)
objectname := "Processor"
instances[0] = "*"
counters[0] = "% Idle Time"
var expectedCounter = "Percent_Idle_Time_Raw"
var measurement = "test"
PerfObject := perfobject{
ObjectName: objectname,
instances := []string{"*"}
counters := []string{"% Idle Time"}
perfObjects := []perfObject{{
ObjectName: "Processor",
Instances: instances,
Counters: counters,
Measurement: measurement,
Measurement: "test",
WarnOnMissing: false,
FailOnMissing: true,
IncludeTotal: false,
UseRawValues: true,
}
perfobjects[0] = PerfObject
}}
m := WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
UseWildcardsExpansion: true,
Log: testutil.Logger{},
}
var acc testutil.Accumulator
err := m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
time.Sleep(2000 * time.Millisecond)
err = m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
require.True(t, len(acc.Metrics) > 1)
expectedCounter := "Percent_Idle_Time_Raw"
for _, metric := range acc.Metrics {
val, ok := metric.Fields[expectedCounter]
require.True(t, ok, "Expected presence of %s field", expectedCounter)
@ -742,18 +573,16 @@ func TestWinPerfcountersCollectRawIntegration(t *testing.T) {
// Test *Array way
m = WinPerfCounters{
PrintValid: false,
Object: perfobjects,
Object: perfObjects,
queryCreator: &PerformanceQueryCreatorImpl{},
UseWildcardsExpansion: false,
Log: testutil.Logger{},
}
var acc2 testutil.Accumulator
err = m.Gather(&acc)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc))
time.Sleep(2000 * time.Millisecond)
err = m.Gather(&acc2)
require.NoError(t, err)
require.NoError(t, m.Gather(&acc2))
require.True(t, len(acc2.Metrics) > 1)
for _, metric := range acc2.Metrics {
@ -763,5 +592,4 @@ func TestWinPerfcountersCollectRawIntegration(t *testing.T) {
require.True(t, ok, fmt.Sprintf("Expected int64, got %T", val))
require.True(t, valInt64 > 0, fmt.Sprintf("Expected > 0, got %d, for %#v", valInt64, metric))
}
}

View File

@ -16,11 +16,12 @@ import (
)
type testCounter struct {
handle PDH_HCOUNTER
handle pdhCounterHandle
path string
value float64
status uint32 // allows for tests against specific pdh_error codes, rather than assuming all cases of "value == 0" to indicate error conditions
}
type FakePerformanceQuery struct {
counters map[string]testCounter
vistaAndNewer bool
@ -64,29 +65,27 @@ func (m *FakePerformanceQuery) Close() error {
return nil
}
func (m *FakePerformanceQuery) AddCounterToQuery(counterPath string) (PDH_HCOUNTER, error) {
func (m *FakePerformanceQuery) AddCounterToQuery(counterPath string) (pdhCounterHandle, error) {
if !m.openCalled {
return 0, errors.New("in AddCounterToQuery: uninitialized query")
}
if c, ok := m.counters[counterPath]; ok {
return c.handle, nil
} else {
return 0, fmt.Errorf("in AddCounterToQuery: invalid counter path: %q", counterPath)
}
return 0, fmt.Errorf("in AddCounterToQuery: invalid counter path: %q", counterPath)
}
func (m *FakePerformanceQuery) AddEnglishCounterToQuery(counterPath string) (PDH_HCOUNTER, error) {
func (m *FakePerformanceQuery) AddEnglishCounterToQuery(counterPath string) (pdhCounterHandle, error) {
if !m.openCalled {
return 0, errors.New("in AddEnglishCounterToQuery: uninitialized query")
}
if c, ok := m.counters[counterPath]; ok {
return c.handle, nil
} else {
return 0, fmt.Errorf("in AddEnglishCounterToQuery: invalid counter path: %q", counterPath)
}
return 0, fmt.Errorf("in AddEnglishCounterToQuery: invalid counter path: %q", counterPath)
}
func (m *FakePerformanceQuery) GetCounterPath(counterHandle PDH_HCOUNTER) (string, error) {
func (m *FakePerformanceQuery) GetCounterPath(counterHandle pdhCounterHandle) (string, error) {
for _, counter := range m.counters {
if counter.handle == counterHandle {
return counter.path, nil
@ -98,12 +97,11 @@ func (m *FakePerformanceQuery) GetCounterPath(counterHandle PDH_HCOUNTER) (strin
func (m *FakePerformanceQuery) ExpandWildCardPath(counterPath string) ([]string, error) {
if e, ok := m.expandPaths[counterPath]; ok {
return e, nil
} else {
return []string{}, fmt.Errorf("in ExpandWildCardPath: invalid counter path: %q", counterPath)
}
return []string{}, fmt.Errorf("in ExpandWildCardPath: invalid counter path: %q", counterPath)
}
func (m *FakePerformanceQuery) GetFormattedCounterValueDouble(counterHandle PDH_HCOUNTER) (float64, error) {
func (m *FakePerformanceQuery) GetFormattedCounterValueDouble(counterHandle pdhCounterHandle) (float64, error) {
if !m.openCalled {
return 0, errors.New("in GetFormattedCounterValueDouble: uninitialized query")
}
@ -118,7 +116,7 @@ func (m *FakePerformanceQuery) GetFormattedCounterValueDouble(counterHandle PDH_
return 0, fmt.Errorf("in GetFormattedCounterValueDouble: invalid handle: %q", counterHandle)
}
func (m *FakePerformanceQuery) GetRawCounterValue(counterHandle PDH_HCOUNTER) (int64, error) {
func (m *FakePerformanceQuery) GetRawCounterValue(counterHandle pdhCounterHandle) (int64, error) {
if !m.openCalled {
return 0, errors.New("in GetRawCounterValue: uninitialised query")
}
@ -142,16 +140,7 @@ func (m *FakePerformanceQuery) findCounterByPath(counterPath string) *testCounte
return nil
}
func (m *FakePerformanceQuery) findCounterByHandle(counterHandle PDH_HCOUNTER) *testCounter {
for _, c := range m.counters {
if c.handle == counterHandle {
return &c
}
}
return nil
}
func (m *FakePerformanceQuery) GetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER) ([]CounterValue, error) {
func (m *FakePerformanceQuery) GetFormattedCounterArrayDouble(hCounter pdhCounterHandle) ([]CounterValue, error) {
if !m.openCalled {
return nil, errors.New("in GetFormattedCounterArrayDouble: uninitialized query")
}
@ -161,25 +150,23 @@ func (m *FakePerformanceQuery) GetFormattedCounterArrayDouble(hCounter PDH_HCOUN
counters := make([]CounterValue, 0, len(e))
for _, p := range e {
counter := m.findCounterByPath(p)
if counter != nil {
if counter.status > 0 {
return nil, NewPdhError(counter.status)
}
counters = append(counters, *counter.ToCounterValue(false))
} else {
if counter == nil {
return nil, fmt.Errorf("in GetFormattedCounterArrayDouble: invalid counter: %q", p)
}
if counter.status > 0 {
return nil, NewPdhError(counter.status)
}
counters = append(counters, *counter.ToCounterValue(false))
}
return counters, nil
} else {
return nil, fmt.Errorf("in GetFormattedCounterArrayDouble: invalid counter: %q", hCounter)
}
return nil, fmt.Errorf("in GetFormattedCounterArrayDouble: invalid counter: %q", hCounter)
}
}
return nil, fmt.Errorf("in GetFormattedCounterArrayDouble: invalid counter: %q, no paths found", hCounter)
}
func (m *FakePerformanceQuery) GetRawCounterArray(hCounter PDH_HCOUNTER) ([]CounterValue, error) {
func (m *FakePerformanceQuery) GetRawCounterArray(hCounter pdhCounterHandle) ([]CounterValue, error) {
if !m.openCalled {
return nil, errors.New("in GetRawCounterArray: uninitialised query")
}
@ -189,19 +176,17 @@ func (m *FakePerformanceQuery) GetRawCounterArray(hCounter PDH_HCOUNTER) ([]Coun
counters := make([]CounterValue, 0, len(e))
for _, p := range e {
counter := m.findCounterByPath(p)
if counter != nil {
if counter.status > 0 {
return nil, NewPdhError(counter.status)
}
counters = append(counters, *counter.ToCounterValue(true))
} else {
if counter == nil {
return nil, fmt.Errorf("in GetRawCounterArray: invalid counter: %q", p)
}
if counter.status > 0 {
return nil, NewPdhError(counter.status)
}
counters = append(counters, *counter.ToCounterValue(true))
}
return counters, nil
} else {
return nil, fmt.Errorf("in GetRawCounterArray: invalid counter: %q", hCounter)
}
return nil, fmt.Errorf("in GetRawCounterArray: invalid counter: %q", hCounter)
}
}
return nil, fmt.Errorf("in GetRawCounterArray: invalid counter: %q, no paths found", hCounter)
@ -238,6 +223,7 @@ func (m FakePerformanceQueryCreator) NewPerformanceQuery(computer string) Perfor
return ret
}
//nolint:revive //argument-limit allowed for helper function
func createPerfObject(
computer string,
measurement string,
@ -247,8 +233,8 @@ func createPerfObject(
failOnMissing bool,
includeTotal bool,
useRawValues bool,
) []perfobject {
PerfObject := perfobject{
) []perfObject {
perfObj := perfObject{
ObjectName: object,
Instances: instances,
Counters: counters,
@ -260,16 +246,16 @@ func createPerfObject(
}
if computer != "" {
PerfObject.Sources = []string{computer}
perfObj.Sources = []string{computer}
}
return []perfobject{PerfObject}
return []perfObject{perfObj}
}
func createCounterMap(counterPaths []string, values []float64, status []uint32) map[string]testCounter {
counters := make(map[string]testCounter)
for i, cp := range counterPaths {
counters[cp] = testCounter{
PDH_HCOUNTER(i),
pdhCounterHandle(i),
cp,
values[i],
status[i],
@ -435,7 +421,7 @@ func TestParseConfigBasic(t *testing.T) {
func TestParseConfigMultiComps(t *testing.T) {
var err error
perfObjects := []perfobject{
perfObjects := []perfObject{
createPerfObject("", "m", "O", []string{"I"}, []string{"C"}, false, false, false)[0],
createPerfObject("", "m", "O1", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
createPerfObject("", "m", "O2", []string{"I"}, []string{"C1", "C2", "C3"}, false, false, false)[0],
@ -670,12 +656,11 @@ func TestParseConfigMultiComps(t *testing.T) {
require.True(t, counters.counters[7].counter == "C3")
require.True(t, counters.counters[7].measurement == "m")
require.True(t, !counters.counters[7].includeTotal)
}
func TestParseConfigMultiCompsOverrideMultiplePerfObjects(t *testing.T) {
var err error
perfObjects := []perfobject{
perfObjects := []perfObject{
createPerfObject("localhost", "m", "O", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
createPerfObject("cmp1", "m", "O1", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
createPerfObject("cmp2", "m", "O2", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
@ -815,13 +800,12 @@ func TestParseConfigMultiCompsOverrideMultiplePerfObjects(t *testing.T) {
require.True(t, counters.counters[3].counter == "C2")
require.True(t, counters.counters[3].measurement == "m")
require.True(t, !counters.counters[3].includeTotal)
}
func TestParseConfigMultiCompsOverrideOnePerfObject(t *testing.T) {
var err error
PerfObject := perfobject{
perfObj := perfObject{
Sources: []string{"cmp1", "cmp2"},
ObjectName: "O",
Instances: []string{"I1", "I2"},
@ -839,7 +823,7 @@ func TestParseConfigMultiCompsOverrideOnePerfObject(t *testing.T) {
Sources: []string{"localhost", "cmp1"},
Log: testutil.Logger{},
PrintValid: false,
Object: []perfobject{PerfObject, createPerfObject("", "m", "O1", []string{"I"}, []string{"C"}, false, false, false)[0]},
Object: []perfObject{perfObj, createPerfObject("", "m", "O1", []string{"I"}, []string{"C"}, false, false, false)[0]},
queryCreator: &FakePerformanceQueryCreator{
fakeQueries: map[string]*FakePerformanceQuery{
"localhost": {
@ -958,11 +942,9 @@ func TestParseConfigMultiCompsOverrideOnePerfObject(t *testing.T) {
require.True(t, counters.counters[3].counter == "C2")
require.True(t, counters.counters[3].measurement == "m")
require.True(t, !counters.counters[3].includeTotal)
}
func TestParseConfigLocalhost(t *testing.T) {
var err error
perfObjects := createPerfObject("localhost", "m", "O", []string{"------"}, []string{"C"}, false, false, false)
cps1 := []string{"\\O\\C"}
@ -1270,7 +1252,7 @@ func TestSimpleGatherNoData(t *testing.T) {
Object: perfObjects,
queryCreator: &FakePerformanceQueryCreator{
fakeQueries: map[string]*FakePerformanceQuery{"localhost": {
counters: createCounterMap([]string{cp1}, []float64{1.2}, []uint32{PDH_NO_DATA}),
counters: createCounterMap([]string{cp1}, []float64{1.2}, []uint32{PdhNoData}),
expandPaths: map[string][]string{
cp1: {cp1},
},
@ -1366,7 +1348,7 @@ func TestGatherError(t *testing.T) {
Object: perfObjects,
queryCreator: &FakePerformanceQueryCreator{
fakeQueries: map[string]*FakePerformanceQuery{"localhost": {
counters: createCounterMap([]string{cp1}, []float64{-2}, []uint32{PDH_PLA_VALIDATION_WARNING}),
counters: createCounterMap([]string{cp1}, []float64{-2}, []uint32{PdhPlaValidationWarning}),
expandPaths: map[string][]string{
cp1: {cp1},
},
@ -1376,8 +1358,8 @@ func TestGatherError(t *testing.T) {
},
}
expectedError := "error during collecting data on host 'localhost': error while getting value for counter \\O(I)\\C: " +
"The information passed is not valid.\r\n"
expectedError := fmt.Sprintf("error during collecting data on host %q: error while getting value for counter %q: "+
"The information passed is not valid.\r\n", "localhost", "\\O(I)\\C")
var acc1 testutil.Accumulator
require.NoError(t, m.Gather(&acc1))
require.Len(t, acc1.Errors, 1)
@ -1409,7 +1391,7 @@ func TestGatherInvalidDataIgnore(t *testing.T) {
Object: perfObjects,
queryCreator: &FakePerformanceQueryCreator{
fakeQueries: map[string]*FakePerformanceQuery{"localhost": {
counters: createCounterMap(cps1, []float64{1.2, 1, 0}, []uint32{0, PDH_INVALID_DATA, 0}),
counters: createCounterMap(cps1, []float64{1.2, 1, 0}, []uint32{0, PdhInvalidData, 0}),
expandPaths: map[string][]string{
cps1[0]: {cps1[0]},
cps1[1]: {cps1[1]},
@ -1555,7 +1537,6 @@ func TestGatherRefreshingWithExpansion(t *testing.T) {
acc3.AssertContainsTaggedFields(t, measurement, fields3, tags3)
err = m.cleanQueries()
require.NoError(t, err)
}
func TestGatherRefreshingWithoutExpansion(t *testing.T) {
@ -1795,7 +1776,7 @@ func TestGatherTotalNoExpansion(t *testing.T) {
func TestGatherMultiComps(t *testing.T) {
var err error
perfObjects := []perfobject{
perfObjects := []perfObject{
createPerfObject("", "m", "O", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
createPerfObject("cmp1", "m1", "O", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
createPerfObject("cmp2", "m2", "O", []string{"I1", "I2"}, []string{"C1", "C2"}, false, false, false)[0],
@ -2086,7 +2067,7 @@ func TestCheckError(t *testing.T) {
{
Name: "Ignore PDH_NO_DATA",
Err: &PdhError{
ErrorCode: uint32(PDH_NO_DATA),
ErrorCode: uint32(PdhNoData),
},
IgnoredErrors: []string{
"PDH_NO_DATA",
@ -2096,10 +2077,10 @@ func TestCheckError(t *testing.T) {
{
Name: "Don't ignore PDH_NO_DATA",
Err: &PdhError{
ErrorCode: uint32(PDH_NO_DATA),
ErrorCode: uint32(PdhNoData),
},
ExpectedErr: &PdhError{
ErrorCode: uint32(PDH_NO_DATA),
ErrorCode: uint32(PdhNoData),
},
},
}