Skip to content
This repository was archived by the owner on May 30, 2019. It is now read-only.

Commit 9ffcbcb

Browse files
committed
Converted to Module
Fixes #23
1 parent 217fa9c commit 9ffcbcb

10 files changed

+1015
-998
lines changed
+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
Function ConvertTo-GraphiteMetric
2+
{
3+
<#
4+
.Synopsis
5+
Converts Windows PerfMon metrics into a metric name that is suitable for Graphite.
6+
7+
.Description
8+
Converts Windows PerfMon metrics into a metric name that is suitable for a Graphite metric path.
9+
10+
.Parameter MetricToClean
11+
The metric to be cleaned.
12+
13+
.Parameter RemoveUnderscores
14+
Removes Underscores from the metric name
15+
16+
.Parameter NicePhysicalDisks
17+
Makes the physical disk perf counters prettier
18+
19+
.Example
20+
PS> ConvertTo-GraphiteMetric -MetricToClean "\Processor(_Total)\% Processor Time"
21+
.Processor._Total.ProcessorTime
22+
23+
.Example
24+
PS> ConvertTo-GraphiteMetric -MetricToClean "\Processor(_Total)\% Processor Time" -RemoveUnderscores
25+
.Processor.Total.ProcessorTime
26+
27+
.Notes
28+
NAME: ConvertTo-GraphiteMetric
29+
AUTHOR: Matthew Hodgkins
30+
WEBSITE: http://www.hodgkins.net.au
31+
#>
32+
param
33+
(
34+
[CmdletBinding()]
35+
[parameter(Mandatory = $true)]
36+
[string]$MetricToClean,
37+
38+
[parameter(Mandatory = $false)]
39+
[switch]$RemoveUnderscores,
40+
41+
[parameter(Mandatory = $false)]
42+
[switch]$NicePhysicalDisks
43+
)
44+
45+
# Removing Beginning Backslashes"
46+
$cleanNameOfSample = $MetricToClean -replace '^\\\\', ''
47+
48+
# Replacing Backslashes After ServerName With dot"
49+
$cleanNameOfSample = $cleanNameOfSample -replace '\\\\', '.'
50+
51+
# Removing Replacing Colon with Dot"
52+
$cleanNameOfSample = $cleanNameOfSample -replace ':', '.'
53+
54+
# Changing Fwd Slash To Dash"
55+
$cleanNameOfSample = $cleanNameOfSample -replace '\/', '-'
56+
57+
# Changing BackSlash To Dot"
58+
$cleanNameOfSample = $cleanNameOfSample -replace '\\', '.'
59+
60+
# Changing Opening Round Bracket to Dot"
61+
$cleanNameOfSample = $cleanNameOfSample -replace '\(', '.'
62+
63+
# Removing Closing Round Bracket to Dot"
64+
$cleanNameOfSample = $cleanNameOfSample -replace '\)', ''
65+
66+
# Removing Square Bracket"
67+
$cleanNameOfSample = $cleanNameOfSample -replace '\]', ''
68+
69+
# Removing Square Bracket"
70+
$cleanNameOfSample = $cleanNameOfSample -replace '\[', ''
71+
72+
# Removing Percentage Sign"
73+
$cleanNameOfSample = $cleanNameOfSample -replace '\%', ''
74+
75+
# Removing Spaces"
76+
$cleanNameOfSample = $cleanNameOfSample -replace '\s+', ''
77+
78+
# Removing Double Dots"
79+
$cleanNameOfSample = $cleanNameOfSample -replace '\.\.', '.'
80+
81+
if ($RemoveUnderscores)
82+
{
83+
Write-Verbose "Removing Underscores as the switch is enabled"
84+
$cleanNameOfSample = $cleanNameOfSample -replace '_', ''
85+
}
86+
87+
if ($NicePhysicalDisks)
88+
{
89+
Write-Verbose "NicePhyiscalDisks switch is enabled"
90+
91+
# Get Drive Letter
92+
$driveLetter = ([regex]'physicaldisk\.\d([a-zA-Z])').match($cleanNameOfSample).groups[1].value
93+
94+
# Add -drive to the drive letter
95+
$cleanNameOfSample = $cleanNameOfSample -replace 'physicaldisk\.\d([a-zA-Z])', ('physicaldisk.' + $driveLetter + '-drive')
96+
97+
# Get the new cleaned drive letter
98+
$niceDriveLetter = ([regex]'physicaldisk\.(.*)\.avg\.').match($cleanNameOfSample).groups[1].value
99+
100+
# Remvoe the .avg. section
101+
$cleanNameOfSample = $cleanNameOfSample -replace 'physicaldisk\.(.*)\.avg\.', ('physicaldisk.' + $niceDriveLetter + '.')
102+
}
103+
104+
Write-Output $cleanNameOfSample
105+
}

Functions/Internal.ps1

+290
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
function Convert-TimeZone
2+
{
3+
<#
4+
.Synopsis
5+
Coverts from a given time zone to the specified time zone.
6+
7+
.Description
8+
Coverts from a given time zone to the specified time zone.
9+
10+
.Parameter DateTime
11+
A DateTime object will be converted to the new time zone.
12+
13+
.Parameter ToTimeZone
14+
The name of the target time zone you wish to convert to. You can get the names by using the -ListTimeZones parameter.
15+
16+
.Parameter ListTimeZones
17+
Lists all the time zones that can be used.
18+
19+
.Example
20+
Convert-TimeZone -ListTimeZones
21+
22+
Id : Dateline Standard Time
23+
DisplayName : (UTC-12:00) International Date Line West
24+
StandardName : Dateline Standard Time
25+
DaylightName : Dateline Daylight Time
26+
BaseUtcOffset : -12:00:00
27+
SupportsDaylightSavingTime : False
28+
29+
Id : UTC-11
30+
DisplayName : (UTC-11:00) Coordinated Universal Time-11
31+
StandardName : UTC-11
32+
DaylightName : UTC-11
33+
BaseUtcOffset : -11:00:00
34+
SupportsDaylightSavingTime : False
35+
36+
Lists available time zones to convert to.
37+
38+
.Example
39+
Convert-TimeZone -DateTime (Get-Date) -ToTimeZone UTC
40+
41+
Converts current time to UTC time.
42+
43+
.Notes
44+
NAME: Convert-TimeZone
45+
AUTHOR: Matthew Hodgkins
46+
WEBSITE: http://www.hodgkins.net.au
47+
48+
#>
49+
50+
param
51+
(
52+
[CmdletBinding(DefaultParametersetName = 'Convert Time Zone')]
53+
54+
[Parameter(Mandatory = $true,
55+
ParameterSetName = 'Convert Time Zone')]
56+
[ValidateNotNull()]
57+
[ValidateNotNullOrEmpty()]
58+
[datetime]$DateTime,
59+
60+
[Parameter(Mandatory = $true,
61+
ParameterSetName = 'Convert Time Zone')]
62+
[ValidateNotNull()]
63+
[ValidateNotNullOrEmpty()]
64+
[string]$ToTimeZone,
65+
66+
[Parameter(Mandatory = $false,
67+
ParameterSetName = 'List Time Zones')]
68+
[switch]$ListTimeZones
69+
)
70+
71+
# Loading dll for Windows 2003 R2
72+
[void][System.Reflection.Assembly]::LoadWithPartialName('System.Core')
73+
74+
# List TimeZones for the user
75+
if ($ListTimeZones)
76+
{
77+
[System.TimeZoneInfo]::GetSystemTimeZones()
78+
return
79+
}
80+
81+
# Run the Function
82+
else
83+
{
84+
$TimeZoneObject = [System.TimeZoneInfo]::FindSystemTimeZoneById($ToTimeZone)
85+
$TargetZoneTime = [System.TimeZoneInfo]::ConvertTime($DateTime, $TimeZoneObject)
86+
$OutObject = New-Object -TypeName PSObject -Property @{
87+
LocalTime = $DateTime
88+
LocalTimeZone = $(([System.TimeZoneInfo]::LOCAL).id)
89+
TargetTime = $TargetZoneTime
90+
TargetTimeZone = $($TimeZoneObject.id)
91+
}
92+
93+
Write-Output $OutObject
94+
}
95+
}
96+
97+
Function Import-XMLConfig
98+
{
99+
<#
100+
.Synopsis
101+
Loads the XML Config File for Send-StatsToGraphite.
102+
103+
.Description
104+
Loads the XML Config File for Send-StatsToGraphite.
105+
106+
.Parameter ConfigPath
107+
Full path to the configuration XML file.
108+
109+
.Example
110+
Import-XMLConfig -ConfigPath C:\Stats\Send-PowerShellGraphite.ps1
111+
112+
.Notes
113+
NAME: Convert-TimeZone
114+
AUTHOR: Matthew Hodgkins
115+
WEBSITE: http://www.hodgkins.net.au
116+
117+
#>
118+
[CmdletBinding()]
119+
Param
120+
(
121+
# Configuration File Path
122+
[Parameter(Mandatory = $true)]
123+
$ConfigPath
124+
)
125+
126+
[hashtable]$Config = @{ }
127+
128+
# Load Configuration File
129+
$xmlfile = [xml]([System.IO.File]::ReadAllText($configPath))
130+
131+
#Set the Graphite carbon server location and port number
132+
$Config.CarbonServer = $xmlfile.Configuration.Graphite.CarbonServer
133+
$Config.CarbonServerPort = $xmlfile.Configuration.Graphite.CarbonServerPort
134+
135+
#Get Metric Send Interval From Config
136+
[int]$Config.MetricSendIntervalSeconds = $xmlfile.Configuration.Graphite.MetricSendIntervalSeconds
137+
138+
# Get the Timezone Of the Graphite Server
139+
$Config.TimeZoneOfGraphiteServer = $xmlfile.Configuration.Graphite.TimeZoneOfGraphiteServer
140+
141+
# Convert Value in Configuration File to Bool for Sending via UDP
142+
[bool]$Config.SendUsingUDP = [System.Convert]::ToBoolean($xmlfile.Configuration.Graphite.SendUsingUDP)
143+
144+
# Convert Interval into TimeSpan
145+
$Config.MetricTimeSpan = [timespan]::FromSeconds($Config.MetricSendIntervalSeconds)
146+
147+
# What is the metric path
148+
149+
$Config.MetricPath = $xmlfile.Configuration.Graphite.MetricPath
150+
151+
# Convert Value in Configuration File to Bool for showing Verbose Output
152+
[bool]$Config.ShowOutput = [System.Convert]::ToBoolean($xmlfile.Configuration.Logging.VerboseOutput)
153+
154+
# Create the Performance Counters Array
155+
$Config.Counters = @()
156+
157+
# Load each row from the configuration file into the counter array
158+
foreach ($counter in $xmlfile.Configuration.PerformanceCounters.Counter)
159+
{
160+
$Config.Counters += $counter.Name
161+
}
162+
163+
# Load each row from the configuration file into the counter array
164+
foreach ($MetricFilter in $xmlfile.Configuration.Filtering.MetricFilter)
165+
{
166+
$Config.Filters += $MetricFilter.Name + '|'
167+
}
168+
169+
if($Config.Filters.Length -gt 0) {
170+
# Trim trailing and leading white spaces
171+
$Config.Filters = $Config.Filters.Trim()
172+
173+
# Strip the Last Pipe From the filters string so regex can work against the string.
174+
$Config.Filters = $Config.Filters.TrimEnd("|")
175+
}
176+
else
177+
{
178+
$Config.Filters = $null
179+
}
180+
181+
# Below is for SQL Metrics
182+
$Config.MSSQLMetricPath = $xmlfile.Configuration.MSSQLMetics.MetricPath
183+
$Config.MSSQLMetricSendIntervalSeconds = $xmlfile.Configuration.MSSQLMetics.MetricSendIntervalSeconds
184+
$Config.MSSQLMetricTimeSpan = [timespan]::FromSeconds($Config.MSSQLMetricSendIntervalSeconds)
185+
[int]$Config.MSSQLConnectTimeout = $xmlfile.Configuration.MSSQLMetics.SQLConnectionTimeoutSeconds
186+
[int]$Config.MSSQLQueryTimeout = $xmlfile.Configuration.MSSQLMetics.SQLQueryTimeoutSeconds
187+
188+
# Create the Performance Counters Array
189+
$Config.MSSQLServers = @()
190+
191+
foreach ($sqlServer in $xmlfile.Configuration.MSSQLMetics.SQLServers.SQLServer)
192+
{
193+
# Load each SQL Server into an array
194+
$Config.MSSQLServers += [pscustomobject]@{
195+
ServerInstance = $sqlServer.ServerInstance;
196+
Username = $sqlServer.Username;
197+
Password = $sqlServer.Password;
198+
Queries = $sqlServer.Query
199+
}
200+
}
201+
202+
Return $Config
203+
}
204+
205+
# http://support-hq.blogspot.com/2011/07/using-clause-for-powershell.html
206+
function PSUsing
207+
{
208+
param (
209+
[System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
210+
[ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
211+
)
212+
213+
Try
214+
{
215+
&$scriptBlock
216+
}
217+
Finally
218+
{
219+
if ($inputObject -ne $null)
220+
{
221+
if ($inputObject.psbase -eq $null)
222+
{
223+
$inputObject.Dispose()
224+
}
225+
else
226+
{
227+
$inputObject.psbase.Dispose()
228+
}
229+
}
230+
}
231+
}
232+
233+
function SendMetrics
234+
{
235+
param (
236+
[string]$CarbonServer,
237+
[int]$CarbonServerPort,
238+
[string[]]$Metrics,
239+
[switch]$IsUdp = $false,
240+
[switch]$TestMode = $false
241+
)
242+
243+
if (!($TestMode))
244+
{
245+
try
246+
{
247+
if ($isUdp)
248+
{
249+
PSUsing ($udpobject = new-Object system.Net.Sockets.Udpclient($CarbonServer, $CarbonServerPort)) -ScriptBlock {
250+
$enc = new-object system.text.asciiencoding
251+
$Message = "$($metric)`r"
252+
$byte = $enc.GetBytes($Message)
253+
$Sent = $udpobject.Send($byte,$byte.Length)
254+
}
255+
256+
Write-Verbose "Sent via UDP to $($CarbonServer) on port $($CarbonServerPort)."
257+
}
258+
else
259+
{
260+
PSUsing ($socket = New-Object System.Net.Sockets.TCPClient) -ScriptBlock {
261+
$socket.connect($CarbonServer, $CarbonServerPort)
262+
PSUsing ($stream = $socket.GetStream()) {
263+
PSUSing($writer = new-object System.IO.StreamWriter($stream)) {
264+
foreach ($metricString in $Metrics)
265+
{
266+
$writer.WriteLine($metricString)
267+
}
268+
$writer.Flush()
269+
Write-Verbose "Sent via TCP to $($CarbonServer) on port $($CarbonServerPort)."
270+
}
271+
}
272+
}
273+
}
274+
}
275+
catch
276+
{
277+
$exceptionText = GetPrettyProblem $_
278+
Write-Error "Error sending metrics to the Graphite Server. Please check your configuration file. `n$exceptionText"
279+
}
280+
}
281+
}
282+
283+
function GetPrettyProblem {
284+
param (
285+
$Problem
286+
)
287+
288+
$prettyString = (Out-String -InputObject (format-list -inputobject $Problem -Property * -force)).Trim()
289+
return $prettyString
290+
}

0 commit comments

Comments
 (0)