読者です 読者をやめる 読者になる 読者になる

PowerShellでgmetricを送るには

※ CentOS6/gmond-3.7.1で動作確認済み($ nc localhost 8649 で値が表示されるところまで)

(参考サイト)
https://github.com/ganglia/ganglia_contrib/blob/master/gmetric-python/gmetric.py
http://stackoverflow.com/questions/12148666/send-and-receive-data-via-udp-in-powershell

# Define port and target IP address 
[int] $Port = 8649 
$IP = "192.168.122.101" 
$hostname="null" # not used by gmond


#############

function get_string_header($str) {
 $a=$str.length
 if ($a -lt 255) {
  return [char]0+[char]0+[char]0+[char]$a
 }
 else {
  return [char]0+[char]0+[char]$a
 }
}

function get_padded_string($str) {
 $len=$str.length
 $a=$len % 4
 $tmp=$str
 
 for ($i=0; $i -lt $a; ++$i){
  $tmp+=[char]0
 }
 return $tmp
}


function packer_pack($str) {
 $tmp=get_string_header $str
 $tmp+=get_padded_string $str
 return $tmp
}



function get_padded_int($int) {
 if ($int -lt 255) {
  return [char]0+[char]0+[char]0+[char]$int
 }
 else {
  return [char]0+[char]0+[char]$int
 }

}



function gmetric_buffer($name, $val, $type) {


#
# Meta Packet
#

 $meta=""

 $meta+=get_padded_int 0x80
 $meta+=packer_pack $hostname
 $meta+=packer_pack $name

 $meta += get_padded_int 0 # slope: zero
 $meta+=[char]0
 $meta+=[char]0

 $meta += packer_pack $type
 $meta+=[char]0
 $meta+=[char]0
 $meta += packer_pack $name

 $meta+=[char]0 # units ""
 $meta+=[char]0

 $meta += get_padded_int 0 # slope: zero
 $meta += get_padded_int 58 #
 $meta += get_padded_int 60 # tmax uint
 $meta += get_padded_int 60 # dmax uint
 $meta += get_padded_int 0 # group: not in any group


#
# Data Packet
#
 $data=""
 $data+=get_padded_int 0x85

 $data += packer_pack $hostname
 $data += packer_pack $name

 $data+=get_padded_int 0
 $data+=[char]0
 $data+=[char]0
 $data += packer_pack "%s"
 $data += packer_pack $val

 return ($meta, $data)
}




#
# Main
#

if ($args.length -ne 3) {
 echo "gmetric.ps1 name val type"
 return 0
}

$name=$args[0]
$val=$args[1]
$type=$args[2]


$Address = [system.net.IPAddress]::Parse($IP) 

# Create IP Endpoint 
$End = New-Object System.Net.IPEndPoint $address, $port 

# Create Socket 
$Saddrf   = [System.Net.Sockets.AddressFamily]::InterNetwork 
$Stype    = [System.Net.Sockets.SocketType]::Dgram 
$Ptype    = [System.Net.Sockets.ProtocolType]::UDP 
$Sock     = New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype 
$Sock.TTL = 26 

# Connect to socket 
$sock.Connect($end) 

# Create encoded buffer 
$Enc     = [System.Text.Encoding]::getencoding("iso-8859-1")
($meta, $data)=gmetric_buffer $name "$val" $type

$Buffer  = $Enc.GetBytes($meta) 
$Sent   = $Sock.Send($Buffer) 

$Buffer  = $Enc.GetBytes($data) 
$Sent   = $Sock.Send($Buffer)