win_perf_counters

package
v1.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2023 License: MIT Imports: 3 Imported by: 17

README

Windows Performance Counters Input Plugin

This document presents the input plugin to read Performance Counters on Windows operating systems.

The configuration is parsed and then tested for validity, such as whether the Object, Instance and Counter exist on Telegraf startup.

Counter paths are refreshed periodically, see the CountersRefreshInterval configuration parameter for more info.

In case of query for all instances ["*"], the plugin does not return the instance _Total by default. See IncludeTotal for more info.

Basics

The examples contained in this file have been found on the internet as counters used when performance monitoring Active Directory and IIS in particular. There are a lot of other good objects to monitor, if you know what to look for. This file is likely to be updated in the future with more examples for useful configurations for separate scenarios.

For more information on concepts and terminology including object, counter, and instance names, see the help in the Windows Performance Monitor app.

Schema

Measurement name is specified per performance object or win_perf_counters by default.

Tags:

  • source - computer name, as specified in the Sources parameter. Name localhost is translated into the host name
  • objectname - normalized name of the performance object
  • instance - instance name, if performance object supports multiple instances, otherwise omitted

Fields are counters of the performance object. The field name is normalized counter name.

Plugin wide

Plugin wide entries are underneath [[inputs.win_perf_counters]].

PrintValid

Bool, if set to true will print out all matching performance objects.

Example: PrintValid=true

UseWildcardsExpansion

If UseWildcardsExpansion is true, wildcards can be used in the instance name and the counter name. Instance indexes will also be returned in the instance name.

Partial wildcards (e.g. chrome*) are supported only in the instance name on Windows Vista and newer.

If disabled, wildcards (not partial) in instance names can still be used, but instance indexes will not be returned in the instance names.

Example: UseWildcardsExpansion=true

LocalizeWildcardsExpansion

LocalizeWildcardsExpansion selects whether object and counter names are localized when UseWildcardsExpansion is true and Telegraf is running on a localized installation of Windows.

When LocalizeWildcardsExpansion is true, Telegraf produces metrics with localized tags and fields even when object and counter names are in English.

When LocalizeWildcardsExpansion is false, Telegraf expects object and counter names to be in English and produces metrics with English tags and fields.

When LocalizeWildcardsExpansion is false, wildcards can only be used in instances. Object and counter names must not have wildcards.

Example: LocalizeWildcardsExpansion=true

CountersRefreshInterval

Configured counters are matched against available counters at the interval specified by the CountersRefreshInterval parameter. The default value is 1m (1 minute).

If wildcards are used in instance or counter names, they are expanded at this point, if the UseWildcardsExpansion param is set to true.

Setting the CountersRefreshInterval too low (order of seconds) can cause Telegraf to create a high CPU load.

Set it to 0s to disable periodic refreshing.

Example: CountersRefreshInterval=1m

PreVistaSupport

(Deprecated in 1.7; Necessary features on Windows Vista and newer are checked dynamically)

Bool, if set to true, the plugin will use the localized PerfCounter interface that has been present since before Vista for backwards compatibility.

It is recommended NOT to use this on OSes starting with Vista and newer because it requires more configuration to use this than the newer interface present since Vista.

Example for Windows Server 2003, this would be set to true: PreVistaSupport=true

UsePerfCounterTime

Bool, if set to true will request a timestamp along with the PerfCounter data. If se to false, current time will be used.

Supported on Windows Vista/Windows Server 2008 and newer Example: UsePerfCounterTime=true

IgnoredErrors

IgnoredErrors accepts a list of PDH error codes which are defined in pdh.go, if this error is encountered it will be ignored. For example, you can provide "PDH_NO_DATA" to ignore performance counters with no instances, but by default no errors are ignored. You can find the list of possible errors here: PDH errors.

Example: IgnoredErrors=["PDH_NO_DATA"]

Sources

(Optional)

Host names or ip addresses of computers to gather all performance counters from. The user running Telegraf must be authenticated to the remote computer(s). E.g. via Windows sharing net use \\SQL-SERVER-01. Use either localhost ("localhost") or real local computer name to gather counters also from localhost among other computers. Skip, if gather only from localhost.

If a performance counter is present only on specific hosts set Sources param on the specific counter level configuration to override global (plugin wide) sources.

Example: Sources = ["localhost", "SQL-SERVER-01", "SQL-SERVER-02", "SQL-SERVER-03"]

Default: Sources = ["localhost"]

Object

See Entry below.

Entry

A new configuration entry consists of the TOML header starting with, [[inputs.win_perf_counters.object]]. This must follow before other plugin configurations, beneath the main win_perf_counters entry, [[inputs.win_perf_counters]].

Following this are 3 required key/value pairs and three optional parameters and their usage.

ObjectName

(Required)

ObjectName is the Object to query for, like Processor, DirectoryServices, LogicalDisk or similar.

Example: ObjectName = "LogicalDisk"

Instances

(Required)

The instances key (this is an array) declares the instances of a counter you would like returned, it can be one or more values.

Example: Instances = ["C:","D:","E:"]

This will return only for the instances C:, D: and E: where relevant. To get all instances of a Counter, use ["*"] only. By default any results containing _Total are stripped, unless this is specified as the wanted instance. Alternatively see the option IncludeTotal below.

It is also possible to set partial wildcards, eg. ["chrome*"], if the UseWildcardsExpansion param is set to true

Some Objects do not have instances to select from at all. Here only one option is valid if you want data back, and that is to specify Instances = ["------"].

Counters

(Required)

The Counters key (this is an array) declares the counters of the ObjectName you would like returned, it can also be one or more values.

Example: Counters = ["% Idle Time", "% Disk Read Time", "% Disk Write Time"]

This must be specified for every counter you want the results of, or use ["*"] for all the counters of the object, if the UseWildcardsExpansion param is set to true.

Sources (Object)

(Optional)

Overrides the Sources global parameter for current performance object. See Sources description for more details.

Measurement

(Optional)

This key is optional. If it is not set it will be win_perf_counters. In InfluxDB this is the key underneath which the returned data is stored. So for ordering your data in a good manner, this is a good key to set with a value when you want your IIS and Disk results stored separately from Processor results.

Example: Measurement = "win_disk"

UseRawValues

(Optional)

This key is optional. It is a simple bool. If set to true, counter values will be provided in the raw, integer, form. This is in contrast with the default behavior, where values are returned in a formatted, displayable, form as seen in the Windows Performance Monitor.

A field representing raw counter value has the _Raw suffix. Raw values should be further used in a calculation, e.g. 100-(non_negative_derivative("Percent_Processor_Time_Raw",1s)/100000 Note: Time based counters (i.e. % Processor Time) are reported in hundredths of nanoseconds. This key is optional. It is a simple bool. If set to true, counter values will be provided in the raw, integer, form. This is in contrast with the default behavior, where values are returned in a formatted, displayable, form as seen in the Windows Performance Monitor. A field representing raw counter value has the _Raw suffix. Raw values should be further used in a calculation, e.g. 100-(non_negative_derivative("Percent_Processor_Time_Raw",1s)/100000 Note: Time based counters (i.e. % Processor Time) are reported in hundredths of nanoseconds.

Example: UseRawValues = true

IncludeTotal

(Optional)

This key is optional. It is a simple bool. If it is not set to true or included it is treated as false. This key only has effect if the Instances key is set to ["*"] and you would also like all instances containing _Total to be returned, like _Total, 0,_Total and so on where applicable (Processor Information is one example).

WarnOnMissing

(Optional)

This key is optional. It is a simple bool. If it is not set to true or included it is treated as false. This only has effect on the first execution of the plugin. It will print out any ObjectName/Instance/Counter combinations asked for that do not match. Useful when debugging new configurations.

FailOnMissing

(Internal)

This key should not be used. It is for testing purposes only. It is a simple bool. If it is not set to true or included this is treated as false. If this is set to true, the plugin will abort and end prematurely if any of the combinations of ObjectName/Instances/Counters are invalid.

Global configuration options

In addition to the plugin-specific configuration settings, plugins support additional global and plugin configuration settings. These settings are used to modify metrics, tags, and field or create aliases and configure ordering, etc. See the CONFIGURATION.md for more details.

Configuration

# # Input plugin to counterPath Performance Counters on Windows operating systems
# # This plugin ONLY supports Windows
# [[inputs.win_perf_counters]]
#   ## By default this plugin returns basic CPU and Disk statistics.
#   ## See the README file for more examples.
#   ## Uncomment examples below or write your own as you see fit. If the system
#   ## being polled for data does not have the Object at startup of the Telegraf
#   ## agent, it will not be gathered.
#   ## Settings:
#   # PrintValid = false # Print All matching performance counters
#   # Whether request a timestamp along with the PerfCounter data or just use current time
#   # UsePerfCounterTime=true
#   # If UseWildcardsExpansion params is set to true, wildcards (partial wildcards in instance names and wildcards in counters names) in configured counter paths will be expanded
#   # and in case of localized Windows, counter paths will be also localized. It also returns instance indexes in instance names.
#   # If false, wildcards (not partial) in instance names will still be expanded, but instance indexes will not be returned in instance names.
#   #UseWildcardsExpansion = false
#   # When running on a localized version of Windows and with UseWildcardsExpansion = true, Windows will
#   # localize object and counter names. When LocalizeWildcardsExpansion = false, use the names in object.Counters instead
#   # of the localized names. Only Instances can have wildcards in this case. ObjectName and Counters must not have wildcards when this
#   # setting is false.
#   #LocalizeWildcardsExpansion = true
#   # Period after which counters will be reread from configuration and wildcards in counter paths expanded
#   CountersRefreshInterval="1m"
#   ## Accepts a list of PDH error codes which are defined in pdh.go, if this error is encountered it will be ignored
#   ## For example, you can provide "PDH_NO_DATA" to ignore performance counters with no instances
#   ## By default no errors are ignored
#   ## You can find the list here: https://github.com/influxdata/telegraf/blob/master/plugins/inputs/win_perf_counters/pdh.go
#   ## e.g.: IgnoredErrors = ["PDH_NO_DATA"]
#   # IgnoredErrors = []
#
#   [[inputs.win_perf_counters.object]]
#     # Processor usage, alternative to native, reports on a per core.
#     ObjectName = "Processor"
#     Instances = ["*"]
#     Counters = [
#       "% Idle Time",
#       "% Interrupt Time",
#       "% Privileged Time",
#       "% User Time",
#       "% Processor Time",
#       "% DPC Time",
#     ]
#     Measurement = "win_cpu"
#     # Set to true to include _Total instance when querying for all (*).
#     # IncludeTotal=false
#     # Print out when the performance counter is missing from object, counter or instance.
#     # WarnOnMissing = false
#     # Gather raw values instead of formatted. Raw value is stored in the field name with the "_Raw" suffix, e.g. "Disk_Read_Bytes_sec_Raw".
#     # UseRawValues = true
#
#   [[inputs.win_perf_counters.object]]
#     # Disk times and queues
#     ObjectName = "LogicalDisk"
#     Instances = ["*"]
#     Counters = [
#       "% Idle Time",
#       "% Disk Time",
#       "% Disk Read Time",
#       "% Disk Write Time",
#       "% User Time",
#       "% Free Space",
#       "Current Disk Queue Length",
#       "Free Megabytes",
#     ]
#     Measurement = "win_disk"
#
#   [[inputs.win_perf_counters.object]]
#     ObjectName = "PhysicalDisk"
#     Instances = ["*"]
#     Counters = [
#       "Disk Read Bytes/sec",
#       "Disk Write Bytes/sec",
#       "Current Disk Queue Length",
#       "Disk Reads/sec",
#       "Disk Writes/sec",
#       "% Disk Time",
#       "% Disk Read Time",
#       "% Disk Write Time",
#     ]
#     Measurement = "win_diskio"
#
#   [[inputs.win_perf_counters.object]]
#     ObjectName = "Network Interface"
#     Instances = ["*"]
#     Counters = [
#       "Bytes Received/sec",
#       "Bytes Sent/sec",
#       "Packets Received/sec",
#       "Packets Sent/sec",
#       "Packets Received Discarded",
#       "Packets Outbound Discarded",
#       "Packets Received Errors",
#       "Packets Outbound Errors",
#     ]
#     Measurement = "win_net"
#
#
#   [[inputs.win_perf_counters.object]]
#     ObjectName = "System"
#     Counters = [
#       "Context Switches/sec",
#       "System Calls/sec",
#       "Processor Queue Length",
#       "System Up Time",
#     ]
#     Instances = ["------"]
#     Measurement = "win_system"
#
#   [[inputs.win_perf_counters.object]]
#     # Example counterPath where the Instance portion must be removed to get data back,
#     # such as from the Memory object.
#     ObjectName = "Memory"
#     Counters = [
#       "Available Bytes",
#       "Cache Faults/sec",
#       "Demand Zero Faults/sec",
#       "Page Faults/sec",
#       "Pages/sec",
#       "Transition Faults/sec",
#       "Pool Nonpaged Bytes",
#       "Pool Paged Bytes",
#       "Standby Cache Reserve Bytes",
#       "Standby Cache Normal Priority Bytes",
#       "Standby Cache Core Bytes",
#     ]
#     Instances = ["------"] # Use 6 x - to remove the Instance bit from the counterPath.
#     Measurement = "win_mem"
#
#   [[inputs.win_perf_counters.object]]
#     # Example query where the Instance portion must be removed to get data back,
#     # such as from the Paging File object.
#     ObjectName = "Paging File"
#     Counters = [
#       "% Usage",
#     ]
#     Instances = ["_Total"]
#     Measurement = "win_swap"
Generic Queries
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    # Processor usage, alternative to native, reports on a per core.
    ObjectName = "Processor"
    Instances = ["*"]
    Counters = ["% Idle Time", "% Interrupt Time", "% Privileged Time", "% User Time", "% Processor Time"]
    Measurement = "win_cpu"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # Disk times and queues
    ObjectName = "LogicalDisk"
    Instances = ["*"]
    Counters = ["% Idle Time", "% Disk Time","% Disk Read Time", "% Disk Write Time", "% User Time", "Current Disk Queue Length"]
    Measurement = "win_disk"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    ObjectName = "System"
    Counters = ["Context Switches/sec","System Calls/sec", "Processor Queue Length"]
    Instances = ["------"]
    Measurement = "win_system"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # Example query where the Instance portion must be removed to get data back, such as from the Memory object.
    ObjectName = "Memory"
    Counters = ["Available Bytes","Cache Faults/sec","Demand Zero Faults/sec","Page Faults/sec","Pages/sec","Transition Faults/sec","Pool Nonpaged Bytes","Pool Paged Bytes"]
    Instances = ["------"] # Use 6 x - to remove the Instance bit from the query.
    Measurement = "win_mem"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # more counters for the Network Interface Object can be found at
    # https://msdn.microsoft.com/en-us/library/ms803962.aspx
    ObjectName = "Network Interface"
    Counters = ["Bytes Received/sec","Bytes Sent/sec","Packets Received/sec","Packets Sent/sec"]
    Instances = ["*"] # Use 6 x - to remove the Instance bit from the query.
    Measurement = "win_net"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
Active Directory Domain Controller
[[inputs.win_perf_counters]]
  [inputs.win_perf_counters.tags]
    monitorgroup = "ActiveDirectory"
  [[inputs.win_perf_counters.object]]
    ObjectName = "DirectoryServices"
    Instances = ["*"]
    Counters = ["Base Searches/sec","Database adds/sec","Database deletes/sec","Database modifys/sec","Database recycles/sec","LDAP Client Sessions","LDAP Searches/sec","LDAP Writes/sec"]
    Measurement = "win_ad" # Set an alternative measurement to win_perf_counters if wanted.
    #Instances = [""] # Gathers all instances by default, specify to only gather these
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    ObjectName = "Security System-Wide Statistics"
    Instances = ["*"]
    Counters = ["NTLM Authentications","Kerberos Authentications","Digest Authentications"]
    Measurement = "win_ad"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    ObjectName = "Database"
    Instances = ["*"]
    Counters = ["Database Cache % Hit","Database Cache Page Fault Stalls/sec","Database Cache Page Faults/sec","Database Cache Size"]
    Measurement = "win_db"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
DFS Namespace + Domain Controllers
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    # AD, DFS N, Useful if the server hosts a DFS Namespace or is a Domain Controller
    ObjectName = "DFS Namespace Service Referrals"
    Instances = ["*"]
    Counters = ["Requests Processed","Requests Failed","Avg. Response Time"]
    Measurement = "win_dfsn"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
    #WarnOnMissing = false # Print out when the performance counter is missing, either of object, counter or instance.
DFS Replication + Domain Controllers
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    # AD, DFS R, Useful if the server hosts a DFS Replication folder or is a Domain Controller
    ObjectName = "DFS Replication Service Volumes"
    Instances = ["*"]
    Counters = ["Data Lookups","Database Commits"]
    Measurement = "win_dfsr"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
    #WarnOnMissing = false # Print out when the performance counter is missing, either of object, counter or instance.
DNS Server + Domain Controllers
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    ObjectName = "DNS"
    Counters = ["Dynamic Update Received","Dynamic Update Rejected","Recursive Queries","Recursive Queries Failure","Secure Update Failure","Secure Update Received","TCP Query Received","TCP Response Sent","UDP Query Received","UDP Response Sent","Total Query Received","Total Response Sent"]
    Instances = ["------"]
    Measurement = "win_dns"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
IIS / ASP.NET
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    # HTTP Service request queues in the Kernel before being handed over to User Mode.
    ObjectName = "HTTP Service Request Queues"
    Instances = ["*"]
    Counters = ["CurrentQueueSize","RejectedRequests"]
    Measurement = "win_http_queues"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # IIS, ASP.NET Applications
    ObjectName = "ASP.NET Applications"
    Counters = ["Cache Total Entries","Cache Total Hit Ratio","Cache Total Turnover Rate","Output Cache Entries","Output Cache Hits","Output Cache Hit Ratio","Output Cache Turnover Rate","Compilations Total","Errors Total/Sec","Pipeline Instance Count","Requests Executing","Requests in Application Queue","Requests/Sec"]
    Instances = ["*"]
    Measurement = "win_aspnet_app"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # IIS, ASP.NET
    ObjectName = "ASP.NET"
    Counters = ["Application Restarts","Request Wait Time","Requests Current","Requests Queued","Requests Rejected"]
    Instances = ["*"]
    Measurement = "win_aspnet"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # IIS, Web Service
    ObjectName = "Web Service"
    Counters = ["Get Requests/sec","Post Requests/sec","Connection Attempts/sec","Current Connections","ISAPI Extension Requests/sec"]
    Instances = ["*"]
    Measurement = "win_websvc"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # Web Service Cache / IIS
    ObjectName = "Web Service Cache"
    Counters = ["URI Cache Hits %","Kernel: URI Cache Hits %","File Cache Hits %"]
    Instances = ["*"]
    Measurement = "win_websvc_cache"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
Process
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    # Process metrics, in this case for IIS only
    ObjectName = "Process"
    Counters = ["% Processor Time","Handle Count","Private Bytes","Thread Count","Virtual Bytes","Working Set"]
    Instances = ["w3wp"]
    Measurement = "win_proc"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).
.NET Monitoring
[[inputs.win_perf_counters]]
  [[inputs.win_perf_counters.object]]
    # .NET CLR Exceptions, in this case for IIS only
    ObjectName = ".NET CLR Exceptions"
    Counters = ["# of Exceps Thrown / sec"]
    Instances = ["w3wp"]
    Measurement = "win_dotnet_exceptions"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # .NET CLR Jit, in this case for IIS only
    ObjectName = ".NET CLR Jit"
    Counters = ["% Time in Jit","IL Bytes Jitted / sec"]
    Instances = ["w3wp"]
    Measurement = "win_dotnet_jit"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # .NET CLR Loading, in this case for IIS only
    ObjectName = ".NET CLR Loading"
    Counters = ["% Time Loading"]
    Instances = ["w3wp"]
    Measurement = "win_dotnet_loading"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # .NET CLR LocksAndThreads, in this case for IIS only
    ObjectName = ".NET CLR LocksAndThreads"
    Counters = ["# of current logical Threads","# of current physical Threads","# of current recognized threads","# of total recognized threads","Queue Length / sec","Total # of Contentions","Current Queue Length"]
    Instances = ["w3wp"]
    Measurement = "win_dotnet_locks"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # .NET CLR Memory, in this case for IIS only
    ObjectName = ".NET CLR Memory"
    Counters = ["% Time in GC","# Bytes in all Heaps","# Gen 0 Collections","# Gen 1 Collections","# Gen 2 Collections","# Induced GC","Allocated Bytes/sec","Finalization Survivors","Gen 0 heap size","Gen 1 heap size","Gen 2 heap size","Large Object Heap size","# of Pinned Objects"]
    Instances = ["w3wp"]
    Measurement = "win_dotnet_mem"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

  [[inputs.win_perf_counters.object]]
    # .NET CLR Security, in this case for IIS only
    ObjectName = ".NET CLR Security"
    Counters = ["% Time in RT checks","Stack Walk Depth","Total Runtime Checks"]
    Instances = ["w3wp"]
    Measurement = "win_dotnet_security"
    #IncludeTotal=false #Set to true to include _Total instance when querying for all (*).

Troubleshooting

If you are getting an error about an invalid counter, use the typeperf command to check the counter path on the command line. E.g. typeperf "Process(chrome*)\% Processor Time"

If no metrics are emitted even with the default config, you may need to repair your performance counters.

  1. Launch the Command Prompt as Administrator (right click "Runs As Administrator").
  2. Drop into the C:\WINDOWS\System32 directory by typing C: then cd \Windows\System32
  3. Rebuild your counter values, which may take a few moments so please be patient, by running:
lodctr /r

Metrics

Example Output

Documentation

Index

Constants

View Source
const (
	ERROR_SUCCESS                 = 0
	ERROR_FAILURE                 = 1
	ERROR_INVALID_FUNCTION        = 1
	EPOCH_DIFFERENCE_MICROS int64 = 11644473600000000
)

Error codes

View Source
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
)
View Source
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
)

Formatting options for GetFormattedCounterValue().

Variables

View Source
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",
}

Functions

func NewPdhError

func NewPdhError(code uint32) error

func PdhAddCounter

func PdhAddCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintptr, phCounter *PDH_HCOUNTER) uint32

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.

Examples of szFullCounterPath (in an English version of Windows):

\\Processor(_Total)\\% Idle Time
\\Processor(_Total)\\% Processor Time
\\LogicalDisk(C:)\% Free Space

To view all (internationalized...) counters on a system, there are three non-programmatic ways: perfmon utility, the typeperf command, and the the registry editor. perfmon.exe is perhaps the easiest way, because it's basically a full implementation of the pdh.dll API, except with a GUI and all that. The registry setting also provides an interface to the available counters, and can be found at the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\CurrentLanguage

This registry key contains several values as follows:

1
1847
2
System
4
Memory
6
% Processor Time
... many, many more

Somehow, these numeric values can be used as szFullCounterPath too:

\2\6 will correspond to \\System\% Processor Time

The typeperf command may also be pretty easy. To find all performance counters, simply execute:

typeperf -qx

func PdhAddEnglishCounter

func PdhAddEnglishCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintptr, phCounter *PDH_HCOUNTER) uint32

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 PdhAddEnglishCounterSupported

func PdhAddEnglishCounterSupported() bool

func PdhCloseQuery

func PdhCloseQuery(hQuery PDH_HQUERY) uint32

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 PdhCollectQueryData

func PdhCollectQueryData(hQuery PDH_HQUERY) uint32

Collects the current raw data value for all counters in the specified query and updates the status code of each counter. With some counters, this function needs to be repeatedly called before the value of the counter can be extracted with PdhGetFormattedCounterValue(). For example, the following code requires at least two calls:

var handle win.PDH_HQUERY
var counterHandle win.PDH_HCOUNTER
ret := win.PdhOpenQuery(0, 0, &handle)
ret = win.PdhAddEnglishCounter(handle, "\\Processor(_Total)\\% Idle Time", 0, &counterHandle)
var derp win.PDH_FMT_COUNTERVALUE_DOUBLE

ret = win.PdhCollectQueryData(handle)
fmt.Printf("Collect return code is %x\n", ret) // return code will be PDH_CSTATUS_INVALID_DATA
ret = win.PdhGetFormattedCounterValueDouble(counterHandle, 0, &derp)

ret = win.PdhCollectQueryData(handle)
fmt.Printf("Collect return code is %x\n", ret) // return code will be ERROR_SUCCESS
ret = win.PdhGetFormattedCounterValueDouble(counterHandle, 0, &derp)

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 PdhCollectQueryDataWithTime

func PdhCollectQueryDataWithTime(hQuery PDH_HQUERY) (uint32, time.Time)

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 PdhExpandWildCardPath

func PdhExpandWildCardPath(szWildCardPath string, mszExpandedPathList *uint16, pcchPathListLength *uint32) uint32

PdhExpandWildCardPath examines the specified computer or log file and returns those counter paths that match the given counter path which contains wildcard characters. The general counter path format is as follows:

\\computer\object(parent/instance#index)\counter

The parent, instance, index, and counter components of the counter path may contain either a valid name or a wildcard character. The computer, parent, instance, and index components are not necessary for all counters.

The following is a list of the possible formats:

\\computer\object(parent/instance#index)\counter \\computer\object(parent/instance)\counter \\computer\object(instance#index)\counter \\computer\object(instance)\counter \\computer\object\counter \object(parent/instance#index)\counter \object(parent/instance)\counter \object(instance#index)\counter \object(instance)\counter \object\counter Use an asterisk (*) as the wildcard character, for example, \object(*)\counter.

If a wildcard character is specified in the parent name, all instances of the specified object that match the specified instance and counter fields will be returned. For example, \object(*/instance)\counter.

If a wildcard character is specified in the instance name, all instances of the specified object and parent object will be returned if all instance names corresponding to the specified index match the wildcard character. For example, \object(parent/*)\counter. If the object does not contain an instance, an error occurs.

If a wildcard character is specified in the counter name, all counters of the specified object are returned.

Partial counter path string matches (for example, "pro*") are supported.

func PdhFormatError

func PdhFormatError(msgId uint32) string

func PdhGetCounterInfo

func PdhGetCounterInfo(hCounter PDH_HCOUNTER, bRetrieveExplainText int, pdwBufferSize *uint32, lpBuffer *byte) uint32

Retrieves information about a counter, such as data size, counter type, path, and user-supplied data values hCounter [in] Handle of the counter from which you want to retrieve information. The PdhAddCounter function returns this handle.

bRetrieveExplainText [in] Determines whether explain text is retrieved. If you set this parameter to TRUE, the explain text for the counter is retrieved. 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. 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. 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 PdhGetFormattedCounterArrayDouble

func PdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *byte) 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. An example of how this function can be used:

okPath := "\\Process(*)\\% Processor Time" // notice the wildcard * character

// omitted all necessary stuff ...

var bufSize uint32
var bufCount uint32
var size uint32 = uint32(unsafe.Sizeof(win.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE{}))
var emptyBuf [1]win.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE // need at least 1 addressable null ptr.

for {
	// collect
	ret := win.PdhCollectQueryData(queryHandle)
	if ret == win.ERROR_SUCCESS {
		ret = win.PdhGetFormattedCounterArrayDouble(counterHandle, &bufSize, &bufCount, &emptyBuf[0]) // uses null ptr here according to MSDN.
		if ret == win.PDH_MORE_DATA {
			filledBuf := make([]win.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, bufCount*size)
			ret = win.PdhGetFormattedCounterArrayDouble(counterHandle, &bufSize, &bufCount, &filledBuf[0])
			for i := 0; i < int(bufCount); i++ {
				c := filledBuf[i]
				var s string = win.UTF16PtrToString(c.SzName)
				fmt.Printf("Index %d -> %s, value %v\n", i, s, c.FmtValue.DoubleValue)
			}

			filledBuf = nil
			// Need to at least set bufSize to zero, because if not, the function will not
			// return PDH_MORE_DATA and will not set the bufSize.
			bufCount = 0
			bufSize = 0
		}

		time.Sleep(2000 * time.Millisecond)
	}
}

func PdhGetFormattedCounterValueDouble

func PdhGetFormattedCounterValueDouble(hCounter PDH_HCOUNTER, lpdwType *uint32, pValue *PDH_FMT_COUNTERVALUE_DOUBLE) uint32

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 PdhGetRawCounterArray added in v1.22.0

func PdhGetRawCounterArray(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *byte) uint32

Returns an array of raw values from the specified counter. Use this function when you want to retrieve the raw counter values of a counter that contains a wildcard character for the instance name. hCounter 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. 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.

lpdwItemCount 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. Set to NULL if lpdwBufferSize is zero.

func PdhGetRawCounterValue added in v1.22.0

func PdhGetRawCounterValue(hCounter PDH_HCOUNTER, lpdwType *uint32, pValue *PDH_RAW_COUNTER) uint32

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.

hCounter [in] Handle of the counter from which to retrieve the current raw value. The PdhAddCounter function returns this handle.

lpdwType [out] Receives the counter type. For a list of counter types, see the Counter Types section of the Windows Server 2003 Deployment Kit. This parameter is optional.

pValue [out] A PDH_RAW_COUNTER structure that receives the counter value.

func PdhOpenQuery

func PdhOpenQuery(szDataSource uintptr, dwUserData uintptr, phQuery *PDH_HQUERY) uint32

PdhOpenQuery creates a new query that is used to manage the collection of performance data. 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 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 PdhValidatePath

func PdhValidatePath(path string) uint32

PdhValidatePath validates a path. Will return ERROR_SUCCESS when ok, or PDH_CSTATUS_BAD_COUNTERNAME when the path is erroneous.

func UTF16PtrToString

func UTF16PtrToString(s *uint16) string

UTF16PtrToString converts Windows API LPTSTR (pointer to string) to go string

func UTF16ToStringArray

func UTF16ToStringArray(buf []uint16) []string

UTF16ToStringArray converts list of Windows API NULL terminated strings to go string array

Types

type CounterValue

type CounterValue struct {
	InstanceName string
	Value        interface{}
}

PerformanceQuery is abstraction for PDH_FMT_COUNTERVALUE_ITEM_DOUBLE

type FILETIME

type FILETIME struct {
	// contains filtered or unexported fields
}

type HANDLE

type HANDLE uintptr

type PDH_COUNTER_INFO

type PDH_COUNTER_INFO 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>.
	//The counter type constants are defined in Winperf.h.
	DwType uint32
	//Counter version information. Not used.
	CVersion uint32
	//Counter status that indicates if the counter value is valid. For a list of possible values,
	//see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa371894(v=vs.85).aspx">Checking PDH Interface Return Values</a>.
	CStatus uint32
	//Scale factor to use when computing the displayable value of the counter. The scale factor is a power of ten.
	//The valid range of this parameter is PDH_MIN_SCALE (–7) (the returned value is the actual value times 10–⁷) to
	//PDH_MAX_SCALE (+7) (the returned value is the actual value times 10⁺⁷). A value of zero will set the scale to one, so that the actual value is returned
	LScale int32
	//Default scale factor as suggested by the counter's provider.
	LDefaultScale int32
	//The value passed in the dwUserData parameter when calling PdhAddCounter.
	DwUserData *uint32
	//The value passed in the dwUserData parameter when calling PdhOpenQuery.
	DwQueryUserData *uint32
	//Null-terminated string that specifies the full counter path. The string follows this structure in memory.
	SzFullPath *uint16 // pointer to a string
	//Null-terminated string that contains the name of the computer specified in the counter path. Is NULL, if the path does not specify a computer.
	//The string follows this structure in memory.
	SzMachineName *uint16 // pointer to a string
	//Null-terminated string that contains the name of the performance object specified in the counter path. The string follows this structure in memory.
	SzObjectName *uint16 // pointer to a string
	//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.
	//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.
	DwInstanceIndex uint32 // pointer to a string
	//Null-terminated string that contains the counter name. The string follows this structure in memory.
	SzCounterName *uint16 // pointer to a string
	//Help text that describes the counter. Is NULL if the source is a log file.
	SzExplainText *uint16 // pointer to a string
	//Start of the string data that is appended to the structure.
	DataBuffer [1]uint32 // pointer to an extra space
}

PDH_COUNTER_INFO structure contains information describing the properties of a counter. This information also includes the counter path.

type PDH_FMT_COUNTERVALUE_DOUBLE

type PDH_FMT_COUNTERVALUE_DOUBLE struct {
	CStatus     uint32
	DoubleValue float64
}

Union specialization for double values

type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE

type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE struct {
	SzName   *uint16
	FmtValue PDH_FMT_COUNTERVALUE_DOUBLE
}

type PDH_FMT_COUNTERVALUE_ITEM_LARGE

type PDH_FMT_COUNTERVALUE_ITEM_LARGE struct {
	SzName   *uint16 // pointer to a string
	FmtValue PDH_FMT_COUNTERVALUE_LARGE
}

Union specialization for 'large' values, used by PdhGetFormattedCounterArrayLarge()

type PDH_FMT_COUNTERVALUE_ITEM_LONG

type PDH_FMT_COUNTERVALUE_ITEM_LONG struct {
	SzName   *uint16 // pointer to a string
	FmtValue PDH_FMT_COUNTERVALUE_LONG
}

Union specialization for long values, used by PdhGetFormattedCounterArrayLong()

type PDH_FMT_COUNTERVALUE_LARGE

type PDH_FMT_COUNTERVALUE_LARGE struct {
	CStatus    uint32
	LargeValue int64
}

Union specialization for 64 bit integer values

type PDH_FMT_COUNTERVALUE_LONG

type PDH_FMT_COUNTERVALUE_LONG struct {
	CStatus   uint32
	LongValue int32
	// contains filtered or unexported fields
}

Union specialization for long values

type PDH_HCOUNTER

type PDH_HCOUNTER HANDLE // counter handle

type PDH_HQUERY

type PDH_HQUERY HANDLE // query handle

type PDH_RAW_COUNTER added in v1.22.0

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
	CStatus uint32
	// Local time for when the data was collected
	TimeStamp FILETIME
	// First raw counter value.
	FirstValue int64
	// Second raw counter value. Rate counters require two values in order to compute a displayable value.
	SecondValue int64
	// If the counter type contains the PERF_MULTI_COUNTER flag, this member contains the additional counter data used in the calculation.
	// For example, the PERF_100NSEC_MULTI_TIMER counter type contains the PERF_MULTI_COUNTER flag.
	MultiCount uint32
}

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_ITEM added in v1.22.0

type PDH_RAW_COUNTER_ITEM 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
}

type PdhError

type PdhError struct {
	ErrorCode uint32
	// contains filtered or unexported fields
}

PdhError represents error returned from Performance Counters API

func (*PdhError) Error

func (m *PdhError) Error() string

type PerformanceQuery

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)
	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)
	CollectData() error
	CollectDataWithTime() (time.Time, error)
	IsVistaOrNewer() bool
}

PerformanceQuery provides wrappers around Windows performance counters API for easy usage in GO

type PerformanceQueryCreator added in v1.26.0

type PerformanceQueryCreator interface {
	NewPerformanceQuery(string) PerformanceQuery
}

type PerformanceQueryCreatorImpl added in v1.26.0

type PerformanceQueryCreatorImpl struct {
}

func (PerformanceQueryCreatorImpl) NewPerformanceQuery added in v1.26.0

func (m PerformanceQueryCreatorImpl) NewPerformanceQuery(string) PerformanceQuery

type PerformanceQueryImpl

type PerformanceQueryImpl struct {
	// contains filtered or unexported fields
}

PerformanceQueryImpl is implementation of PerformanceQuery interface, which calls phd.dll functions

func (*PerformanceQueryImpl) AddCounterToQuery

func (m *PerformanceQueryImpl) AddCounterToQuery(counterPath string) (PDH_HCOUNTER, error)

func (*PerformanceQueryImpl) AddEnglishCounterToQuery

func (m *PerformanceQueryImpl) AddEnglishCounterToQuery(counterPath string) (PDH_HCOUNTER, error)

func (*PerformanceQueryImpl) Close

func (m *PerformanceQueryImpl) Close() error

Close closes the counterPath, releases associated counter handles and frees resources

func (*PerformanceQueryImpl) CollectData

func (m *PerformanceQueryImpl) CollectData() error

func (*PerformanceQueryImpl) CollectDataWithTime

func (m *PerformanceQueryImpl) CollectDataWithTime() (time.Time, error)

func (*PerformanceQueryImpl) ExpandWildCardPath

func (m *PerformanceQueryImpl) ExpandWildCardPath(counterPath string) ([]string, error)

ExpandWildCardPath examines local computer and returns those counter paths that match the given counter path which contains wildcard characters.

func (*PerformanceQueryImpl) GetCounterPath

func (m *PerformanceQueryImpl) GetCounterPath(counterHandle PDH_HCOUNTER) (string, error)

GetCounterPath return counter information for given handle

func (*PerformanceQueryImpl) GetFormattedCounterArrayDouble

func (m *PerformanceQueryImpl) GetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER) ([]CounterValue, error)

func (*PerformanceQueryImpl) GetFormattedCounterValueDouble

func (m *PerformanceQueryImpl) GetFormattedCounterValueDouble(hCounter PDH_HCOUNTER) (float64, error)

GetFormattedCounterValueDouble computes a displayable value for the specified counter

func (*PerformanceQueryImpl) GetRawCounterArray added in v1.22.0

func (m *PerformanceQueryImpl) GetRawCounterArray(hCounter PDH_HCOUNTER) ([]CounterValue, error)

func (*PerformanceQueryImpl) GetRawCounterValue added in v1.22.0

func (m *PerformanceQueryImpl) GetRawCounterValue(hCounter PDH_HCOUNTER) (int64, error)

func (*PerformanceQueryImpl) IsVistaOrNewer

func (m *PerformanceQueryImpl) IsVistaOrNewer() bool

func (*PerformanceQueryImpl) Open

func (m *PerformanceQueryImpl) Open() error

Open creates a new counterPath that is used to manage the collection of performance data. It returns counterPath handle used for subsequent calls for adding counters and querying data

type SYSTEMTIME

type SYSTEMTIME struct {
	// contains filtered or unexported fields
}

type WinPerfCounters added in v1.26.0

type WinPerfCounters struct {
	PrintValid                 bool `toml:"PrintValid"`
	PreVistaSupport            bool `toml:"PreVistaSupport" deprecated:"1.7.0;determined dynamically"`
	UsePerfCounterTime         bool
	Object                     []perfobject
	CountersRefreshInterval    config.Duration
	UseWildcardsExpansion      bool
	LocalizeWildcardsExpansion bool
	IgnoredErrors              []string `toml:"IgnoredErrors"`
	Sources                    []string

	Log telegraf.Logger
	// contains filtered or unexported fields
}

func (*WinPerfCounters) AddItem added in v1.26.0

func (m *WinPerfCounters) AddItem(counterPath, computer, objectName, instance, counterName, measurement string, includeTotal bool, useRawValue bool) error

func (*WinPerfCounters) Gather added in v1.26.0

func (m *WinPerfCounters) Gather(acc telegraf.Accumulator) error

func (*WinPerfCounters) Init added in v1.26.0

func (m *WinPerfCounters) Init() error

func (*WinPerfCounters) ParseConfig added in v1.26.0

func (m *WinPerfCounters) ParseConfig() error

func (*WinPerfCounters) SampleConfig added in v1.26.0

func (m *WinPerfCounters) SampleConfig() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL