Created
November 26, 2014 17:39
-
-
Save abombss/721d9c2b2c14b22a1d8a to your computer and use it in GitHub Desktop.
SumoLogic Powershell API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
The MIT License (MIT) | |
Copyright (c) 2014 Adam Tybor | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
#> | |
$script:SumoApiUri = "https://api.sumologic.com/api" | |
$script:SumoObjectTypes = @{ | |
'PoshSumo.Entity.Collector' = @{ | |
ImmutableFields = @('id','collectorType','collectorVersion') | |
MutableFields = @('name', 'description', 'category', 'hostName', 'timeZone', 'ephemeral') | |
TransientFields = @('alive', 'status') | |
MetadataFields = @('links') | |
Name='collector' | |
Listing='collectors' | |
VerboseId='CollectorId' | |
SubTypes = @('PoshSumo.Entity.Collector.Installable', 'PoshSumo.Entity.Collector.Hosted') | |
SubTypeDescriminator = { | |
param($entity) | |
switch ($entity.collectorType) { | |
'Installable' { | |
'PoshSumo.Entity.Collector.Installable'; | |
break; | |
} 'Hosted' { | |
'PoshSumo.Entity.Collector.Hosted'; | |
break; | |
} | |
} | |
} | |
} | |
'PoshSumo.Entity.Collector.Installable' = @{ | |
ImmutableFields = @('osName', 'osVersion', 'osArch') | |
MutableFields = @() | |
TransientFields = @('uptime') | |
} | |
'PoshSumo.Entity.Collector.Hosted' = @{ | |
} | |
'PoshSumo.Entity.Source.Filter' = @{ | |
EntityType='ValueObject' | |
MutableFields = @('name','filterType', 'regexp', 'mask') | |
} | |
'PoshSumo.Entity.Source'= @{ | |
Fields = @{ | |
id = @{ Type=[long];Required=$true;Default='';Description="ID";Access='immutable' } | |
name = @{ Type=[string];Required=$true;Default='';Description="Name";Access='modifiable' } | |
description = @{ Type=[string];Required=$false;Default=$null;Description="Description";Access='modifiable' } | |
category = @{ Type=[string];Required=$false;Default=$null;Description="Category";Access='modifiable' } | |
hostName = @{ Type=[string];Required=$false;Default=$null;Description="Host name";Access='modifiable' } | |
timeZone = @{ Type=[string];Required=$false;Default=$null;Description="Time zone";Access='modifiable' } | |
} | |
} | |
} | |
$script:CommonParameters = @( | |
'Verbose' | |
'Debug' | |
'WarningAction' | |
'WarningVariable' | |
'ErrorAction' | |
'ErrorVariable' | |
'OutVariable' | |
'OutBuffer' | |
'WhatIf' | |
) | |
function Set-SumoSession { | |
[CmdletBinding(DefaultParameterSetName="Set")] | |
param( | |
[Parameter(Mandatory, ParameterSetName="Set")] | |
[PsCredential]$Credential, | |
[Parameter(ParameterSetName="Clear")] | |
[switch]$Clear | |
) | |
if ($Clear) { | |
$script:CurrentSumoCredential=$null | |
} else { | |
$script:CurrentSumoCredential=$Credential | |
} | |
} | |
function Test-SumoObject | |
{ | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory, ValueFromPipeline, Position=0)] | |
[object]$InputObject, | |
[Parameter(Position=1)] | |
[string]$TypeName | |
) | |
process | |
{ | |
if (!$InputObject) | |
{ | |
Write-Output $false | |
} | |
else | |
{ | |
foreach($obj in $InputObject) | |
{ | |
$found = $false | |
if ($TypeName) | |
{ | |
$found = $obj.PSObject.TypeNames -contains $TypeName | |
} | |
else | |
{ | |
foreach($name in $obj.PSObject.TypeNames) | |
{ | |
if ($name -match '^PoshSumo') | |
{ | |
$found = $true | |
break; | |
} | |
} | |
} | |
Write-Output $found | |
} | |
} | |
} | |
} | |
function ConvertTo-SumoObject | |
{ | |
param( | |
[Parameter(Mandatory, ValueFromPipeline)] | |
[object[]]$InputObject, | |
[string]$WrapperProperty, | |
[string]$Type, | |
[hashtable]$Properties, | |
[hashtable]$ScriptProperties, | |
[hashtable]$ScriptMethods | |
) | |
process | |
{ | |
foreach($obj in $InputObject) | |
{ | |
if ( (Test-SumoObject -InputObject $obj -TypeName PoshSumo.WebResponse) ) | |
{ | |
$objContainer = ConvertFrom-Json -InputObject $obj.Content | Select-Object -ExpandProperty $WrapperProperty | |
if ($obj.Headers.ContainsKey('ETag')) | |
{ | |
Add-Member -InputObject $objContainer -NotePropertyName ETag -NotePropertyValue $obj.Headers.ETag.Trim('"') | |
} | |
} | |
elseif ($obj -is [string]) | |
{ | |
$objContainer = ConvertFrom-Json -InputObject $obj | Select-Object -ExpandProperty $WrapperProperty | |
} | |
else | |
{ | |
$objContainer = $obj | |
} | |
foreach($psObj in $objContainer) | |
{ | |
if ($Properties) | |
{ | |
foreach ($prop in $Properties.GetEnumerator()) | |
{ | |
Add-Member -InputObject $psObj -NotePropertyName $prop.Key -NotePropertyValue $prop.Value | |
} | |
} | |
if ($ScriptProperties) | |
{ | |
foreach ($prop in $ScriptProperties.GetEnumerator()) | |
{ | |
Add-Member -InputObject $psObj -MemberType ScriptProperty -Name $prop.Key -Value ([scriptblock] $prop.Value) | |
} | |
} | |
if ($ScriptMethods) | |
{ | |
foreach ($prop in $ScriptMethods.GetEnumerator()) | |
{ | |
Add-Member -InputObject $psObj -MemberType ScriptMethod -Name $prop.Key -Value ([scriptblock] $prop.Value) | |
} | |
} | |
[void] $psObj.PSObject.TypeNames.Insert(0,$Type) | |
Write-Output -InputObject $psObj | |
} | |
} | |
} | |
} | |
function Get-SumoCollector { | |
[CmdletBinding(DefaultParameterSetName="List")] | |
param( | |
[Alias("Id")] | |
[Parameter(Mandatory, ParameterSetName="Entity", ValueFromPipeline, ValueFromPipelineByPropertyName)] | |
[long[]]$CollectorId, | |
[Parameter(ParameterSetName="List")] | |
[long]$Limit=-1, | |
[Parameter(ParameterSetName="List")] | |
[long]$Offset=0, | |
[long]$TimeoutSec=0, | |
[PsCredential]$Credential = $CurrentSumoCredential, | |
[string]$ApiVersion='v1' | |
) | |
begin { | |
$webArgs = @{ | |
Credential = $Credential | |
TimeoutSec = $TimeoutSec | |
ReturnHeaders = $true | |
} | |
$sumoObjArgs = @{ | |
Type = 'PoshSumo.Entity.collector' | |
WrapperProperty = 'collector' | |
ScriptProperties = @{ CollectorId = { $this.id } } | |
ScriptMethods = @{ GetSources = { Get-SumoCollectorSource -CollectorId $this.id } } | |
} | |
if ($PSCmdlet.ParameterSetName -eq "List") | |
{ | |
$sumoObjArgs.WrapperProperty = 'collectors' | |
} | |
} | |
process | |
{ | |
if ($PSCmdlet.ParameterSetName -eq "List") | |
{ | |
$uri = "$SumoApiUri/$ApiVersion/collectors" | |
if ($Limit -gt 0) { $uri = "$($uri)?limit=$Limit" } | |
if ($Offset -gt 0) { if ($uri.Contains("?")) { $uri = "$uri&offset=$Offset" } else { $uri = "$($uri)?offset=$Offset" } } | |
Invoke-WebRequestWithRetries -Uri $uri @webArgs | ConvertTo-SumoObject @sumoObjArgs | |
} | |
else | |
{ | |
foreach($id in $CollectorId) | |
{ | |
Invoke-WebRequestWithRetries -Uri "$SumoApiUri/$ApiVersion/collectors/$id" @webArgs | ConvertTo-SumoObject @sumoObjArgs | |
} | |
} | |
} | |
end { } | |
} | |
function Get-SumoCollectorSource { | |
[CmdletBinding(DefaultParameterSetName="List")] | |
param( | |
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] | |
[long]$CollectorId, | |
[Parameter(Mandatory, ParameterSetName="Entity", ValueFromPipelineByPropertyName)] | |
[long[]]$SourceId, | |
[Parameter(ParameterSetName="List")] | |
[long]$Limit=-1, | |
[Parameter(ParameterSetName="List")] | |
[long]$Offset=0, | |
[long]$TimeoutSec=0, | |
[PsCredential]$Credential = $CurrentSumoCredential, | |
[string]$ApiVersion='v1' | |
) | |
begin | |
{ | |
$webReqArgs = @{ | |
Credential = $Credential | |
TimeoutSec = $TimeoutSec | |
ReturnHeaders = $true | |
} | |
$sumoObjArgs = @{ | |
WrapperProperty = 'source' | |
Type = 'PoshSumo.Entity.collector.source' | |
ScriptProperties = @{ SourceId = { $this.id } } | |
Properties = @{ } | |
} | |
if ($PSCmdlet.ParameterSetName -eq 'List') | |
{ | |
$sumoObjArgs.WrapperProperty = 'sources' | |
} | |
} | |
process { | |
$sumoObjArgs.Properties['CollectorId'] = $CollectorId | |
$uri = "$SumoApiUri/$ApiVersion/collectors/$CollectorId/sources/" | |
if ($SourceId -and $SourceId.Count -gt 0) | |
{ | |
$sumoObjArgs.WrapperProperty = 'source' | |
foreach($id in $SourceId) | |
{ | |
Invoke-WebRequestWithRetries @webReqArgs -Uri "$($uri)$id" | ConvertTo-SumoObject @sumoObjArgs | |
} | |
} | |
else | |
{ | |
$sumoObjArgs.WrapperProperty = 'sources' | |
Invoke-WebRequestWithRetries @webReqArgs -Uri $uri | ConvertTo-SumoObject @sumoObjArgs | |
} | |
} | |
} | |
function Set-SumoCollector | |
{ | |
[CmdletBinding(SupportsShouldProcess)] | |
param( | |
[Parameter(Mandatory, ParameterSetName="Id")] | |
[long]$CollectorId, | |
[Alias("Collector")] | |
[ValidateNotNull()] | |
[ValidateScript({(Test-SumoObject $_) -and ($_.PSObject.Properties.Match('ETag'))})] | |
[Parameter(Mandatory, ParameterSetName="Entity", ValueFromPipeline)] | |
[object]$InputObject, | |
[string]$name, | |
[string]$description, | |
[string]$category, | |
[string]$hostName, | |
[string]$timeZone, | |
[switch]$ephemeral, | |
[pscredential] $Credential = $CurrentSumoCredential, | |
[string] $ApiVersion = "v1" | |
) | |
process | |
{ | |
if (!$InputObject) | |
{ | |
$InputObject = Get-SumoCollector -CollectorId $CollectorId | |
} | |
$payload = Clone-ObjectForWrite $InputObject $PSBoundParameters | ConvertTo-Json | |
$webReqArgs = @{ | |
ContentType = 'application/json' | |
Method = 'Put' | |
UserAgent = 'PoshSumo v1.0' | |
Credential = $Credential | |
Body = $payload | |
Uri = "$SumoApiUri/$ApiVersion/collectors/$($InputObject.CollectorId)" | |
Headers = @{ | |
'If-Match' = if(!$InputObject.ETag.StartsWith('"')) { "`"$($InputObject.ETag)`"" } else { $InputObject.ETag } | |
} | |
} | |
if ($PSCmdlet.ShouldProcess($webReqArgs.Uri)) | |
{ | |
Write-Verbose $payload | |
Invoke-WebRequest @webReqArgs | |
} | |
else | |
{ | |
Write-Host "Invoking [$($webReqArgs.Method)] [$($webReqArgs.Uri)]" | |
foreach($header in $webReqArgs.Headers.GetEnumerator()) | |
{ | |
Write-Host "$($header.Key):$($header.Value)" | |
} | |
Write-Host "$payload" | |
} | |
} | |
} | |
function Remove-SumoCollector { | |
[CmdletBinding(SupportsShouldProcess)] | |
param( | |
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName,ParameterSetName='Id')] | |
[Alias('CollectorId')] | |
[long[]]$Id, | |
[Parameter(Mandatory,ValueFromPipeline,ParameterSetName='Object')] | |
[object]$InputObject, | |
[pscredential] $Credential = $CurrentSumoCredential, | |
[string] $ApiVersion = "v1" | |
) | |
process { | |
[long[]]$collectorIds = @() | |
switch ($PSCmdlet.ParameterSetName) { | |
Id { | |
$collectorIds += @($Id) | |
} | |
Object { | |
foreach($obj in $InputObject) { | |
if ($obj -is [int] -or $obj -is [long]) { | |
$collectorIds += @($obj) | |
} elseif ($obj -is [hashtable]) { | |
if ($obj.ContainsKey('Id')) { | |
$collectorIds += @( [Convert]::ToInt64( $obj['Id'] ) ) | |
} elseif ($obj.ContainsKey('CollectorId')) { | |
$collectorIds += @( [Convert]::ToInt64( $obj['CollectorId'] ) ) | |
} | |
} else { | |
$propertyName = $obj | Get-Member -Name Id,CollectorId | select -ExpandProperty Name -First 1 | |
$collectorIds += @( [Convert]::ToInt64( $obj.$propertyName ) ) | |
} | |
} | |
} | |
} | |
foreach($collectorId in $collectorIds) { | |
$webReqArgs = @{ | |
Method = 'Delete' | |
UserAgent = 'PoshSumo v1.0' | |
Credential = $Credential | |
Uri = "$SumoApiUri/$ApiVersion/collectors/$collectorId" | |
} | |
if ($PSCmdlet.ShouldProcess($webReqArgs.Uri)) { | |
Invoke-WebRequest @webReqArgs | |
} else { | |
Write-Host "Invoking [$($webReqArgs.Method)] [$($webReqArgs.Uri)]" | |
} | |
} | |
} | |
} | |
function Test-Stack { param($name) Get-Stack } | |
function Get-Stack { Get-PSCallStack } | |
function Clone-ObjectForWrite { | |
param($instance, $newValues); | |
if (!(Test-SumoObject $instance)) | |
{ | |
throw (new-object System.ArgumentException("instance does not appear to be a Sumo object, cannot clone and update it")) | |
} | |
$sumoType = $script:SumoObjectTypes[$instance.PSObject.TypeNames[0]] | |
if (!$sumoType) | |
{ | |
throw (new-object System.InvalidOperationException("'$($instance.PSObject.TypeNames[0])' is an unknown Sumo Type")) | |
} | |
$newObj = @{} | |
foreach($field in $sumoType.ImmutableFields) | |
{ | |
if ($instance.PSObject.Properties.Match($field)) | |
{ | |
$newObj[$field] = $instance.PSObject.Properties[$field].Value | |
} | |
} | |
foreach($field in $sumoType.MutableFields) | |
{ | |
if ($newValues.ContainsKey($field)) | |
{ | |
$newObj[$field] = $newValues[$field] | |
} | |
else | |
{ | |
if ($instance.PSObject.Properties.Match($field)) | |
{ | |
$newObj[$field] = $instance.PSObject.Properties[$field].Value | |
} | |
} | |
} | |
@{ $sumoType.Name = $newObj } | |
} | |
function Invoke-WebRequestWithRetries { | |
param( | |
[Parameter(Mandatory)] | |
[string]$Uri, | |
[PsCredential]$Credential, | |
[long]$TimeoutSec=3, | |
[long]$RetryLimit=3, | |
[long[]]$RetryStatusCodes=@(503), | |
[long[]]$IgnoreStatusCodes, | |
[long[]]$RetryBackOff=@(100, 100, 1000), | |
[switch]$ReturnHeaders | |
) | |
$stopLoop = $false | |
$retryCount = 0 | |
do { | |
try | |
{ | |
$requestArgs = @{ | |
UserAgent="PoshSumo v1.0" | |
TimeoutSec=$TimeoutSec | |
Uri=$Uri | |
} | |
if ($Credential) { $requestArgs['Credential'] = $Credential } | |
$resp = Invoke-WebRequest @requestArgs | |
$stopLoop = $true | |
} | |
catch [System.Net.WebException] | |
{ | |
$stopLoop = $true | |
[System.Net.WebException]$ex = $Error[0].Exception | |
$resp = $ex.Response | |
if ($resp) | |
{ | |
if ($RetryStatusCodes -contains $resp.StatusCode) | |
{ | |
if ($retryCount -lt $RetryLimit) | |
{ | |
$stopLoop = $false | |
if ($retryCount -ge $RetryBackOff.Count) | |
{ | |
$backOffIndex = 0; | |
} | |
else | |
{ | |
$backOffIndex = $retryCount | |
} | |
Write-Warning "Retrying failed request [$([long]$resp.StatusCode)][$Uri], backing off for $($RetryBackOff[$retryCount]) milliseconds before trying again" | |
Start-Sleep -Milliseconds $RetryBackOff[$retryCount] | |
$retryCount++ | |
} | |
else | |
{ | |
throw | |
} | |
} | |
else | |
{ | |
throw | |
} | |
} | |
else | |
{ | |
throw | |
} | |
} catch [System.Exception] { | |
$stopLoop = $true | |
throw | |
} | |
} while (!$stopLoop) | |
if ($ReturnHeaders) | |
{ | |
$obj = new-object psobject -Property @{Content=$resp.Content;Headers=$resp.Headers} | |
[void]$obj.PsObject.TypeNames.Insert(0, 'PoshSumo.WebResponse') | |
Write-Output $obj | |
} | |
else | |
{ | |
Write-Output $resp.Content | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Setup a session, will prompt for creds | |
Set-SumoSession | |
# Get all the collectors | |
$collectors = Get-SumoCollector | |
$c = $collectors | select -first 1 | |
# Get the sources for a collector | |
$c.GetSources() | |
# or | |
$c | Get-SumoCollectorSource | |
# update a collector | |
$c.Description = "Changing Description" | |
$c | Set-SumoCollector | |
# remove collector | |
$c | Remove-SumoCollector |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment