NewRelicPS.Applications.psm1

Using module .\NewRelicPS.NRQLQuery.psm1
Using module .\NewRelicPS.GraphQLQueries.psm1

<#
.Synopsis
  Gets Application details from New Relic
.Description
  Gets Application details from New Relic
.Example
  Get-NRApplication -APIKey 'fake-api-key'
  Returns all the application in New Relic
.Example
  Get-NRApplication -APIKey 'fake-api-key' -ApplicationId '543219870'
  Returns only the application details specific to the provided application id
.Example
  Get-NRApplication -APIKey 'fake-api-key' -ApplicationId ''
  Returns all the application in New Relic when no Application Id is passed.
.Example
  @('543219870','503698546','657896324') | Get-NRApplication -APIKey 'fake-api-key'
  Returns applications in New Relic when multiple Application Id is passed through pipe
.Parameter APIKey
  Can be either the account level REST API key or an admin user's API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys
.Parameter ApplicationId
  Returns a single Application, identified by ID
#>

Function Get-NRApplication {
  [CmdletBinding()]
  param (
    [Parameter (Mandatory = $true)]
    [string] $APIKey,
    [Parameter (ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
    [string] $ApplicationId
  )

  Begin {
    $headers = @{
      'X-Api-Key' = $APIKey
    }
  }
  Process {
    if ($ApplicationId) {
      $url = "https://api.newrelic.com/v2/applications/$ApplicationId.json"
    }
    else {
      $url = "https://api.newrelic.com/v2/applications.json"
    }
    [array] $application = Invoke-RestMethod -uri $url -method 'GET' -ContentType 'application/json' -header $headers -FollowRelLink
    return $application
  }
}

<#
.Synopsis
  Gets host name using the application id in New Relic
.Description
  Gets host name using the application id in New Relic
.Example
  Get-NRHostName -APIKey 'fake-api-key' -AccountId 2789621
  Returns all the host names in New Relic
.Example
  Get-NRHostName -APIKey 'fake-api-key' -ApplicationId '543256987' -AccountId 2789621
  Returns host name for the provided application id
.Example
  Get-NRHostName -APIKey 'fake-api-key' -ApplicationId '' -AccountId 2789621
  Returns all the host names in New Relic when no ApplicationId is provided
.Example
  @('543219870','503698546','657896324') | Get-NRHostName -APIKey 'fake-api-key' -AccountId 123456789
  Returns applications in New Relic when multiple Application Id is passed through pipe
.Parameter APIKey
  Can be either the account level REST API key or an admin user's API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys
.Parameter ApplicationId
  Returns a single host name, identified by ID
.Parameter AccountId
  New Relic account id
#>

Function Get-NRHostName {
  Param (
    [Parameter (ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
    [string] $ApplicationID,
    [Parameter (Mandatory = $true)]
    [string] $APIKey,
    [Parameter (Mandatory = $true)]
    [string] $AccountId
  )
  Process {
    If ($ApplicationID) {
      [string] $Query = "SELECT uniques(hostname) AS host_names FROM SystemSample SINCE 1 hour ago limit max WHERE apmApplicationIds = '|$ApplicationID|' "
    }
    Else {
      [string] $Query = 'SELECT uniques(hostname) AS host_names FROM SystemSample SINCE 1 hour ago limit max'
    }

    $application_hosts = Invoke-NRQLQuery -AccountId $AccountId -Query $Query -APIKey $APIKey
    $applicationHostName = $application_hosts.data.actor.account.nrql.results.host_names

    return $applicationHostName
  }
}

<#
.Synopsis
  Gets a metric normalization rule or list of rules
.Description
  Returns details on all normalization rules in an account or details on a specific normalization rule if an Id is provided.
.Example
  Get-NRNormalizationRule -APIKey 'fake-api-key' -AccountId 1234567 -Id 12345
  Returns details only for rule 12345 in account 1234567
.Example
  Get-NRNormalizationRule -APIKey 'fake-api-key' -AccountId 1234567
  Returns details for all normalization rules in account 1234567
.Parameter AccountId
  New Relic account id.
.Parameter APIKey
  Can be either the account level REST API key or an admin user's API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys
.Parameter Id
  If provided, results will only be returned for the Id supplied.
#>

Function Get-NRNormalizationRule {
  [CMDLetBinding(SupportsShouldProcess = $true)]
  Param (
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $APIKey,
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $AccountId,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $Id
  )
  Begin {
    $url = 'https://api.newrelic.com/graphql'
    $headers = @{
      'Api-Key' = $APIKey
    }
  }
  Process {

    If ($Id) {
      $graphqlQuery = Get-GraphQLQueryGetMetricNormalizationRule -AccountId $AccountId -RuleId $Id
    }
    Else {
      $graphqlQuery = Get-GraphQLQueryGetMetricNormalizationRuleList -AccountId $AccountId
    }
    Write-Verbose "GraphQLQuery: `n$graphqlQuery"
    $body = @{
      query = $graphqlQuery
    } | ConvertTo-Json

    # Call the API and return results
    If ($PSCmdlet.ShouldProcess($Name, 'Create Normalization Rule')) {
      $result = Invoke-RestMethod -Uri $url -headers $headers -body $body -Method 'Post' -ContentType 'application/json'

      If ($result.errors) {
        Write-Error ($result.errors | ConvertTo-Json -Depth 20)
      }

      # Return the correctly filtered data set
      return $result.data.actor.account.metricnormalization.metricnormalizationrules ? $result.data.actor.account.metricnormalization.metricnormalizationrules : $result.data.actor.account.metricnormalization.metricnormalizationrule
    }
  }
}

<#
.Synopsis
  Creates a new metric normalization rule for an application
.Description
  Creates a new metric normalization rule for an application
.Example
  New-NRNormalizationRule -APIKey 'fake-api-key' -AccountId 1234567 -ApplcationId 'ABC123456789' -Action 'Ignore' -Enabled $true -Expression '^Error/.*'
  Creates a normalization rule for application ABC123456789 to ignore all timeslice metrics that match regex pattern ^Error/.*
.Parameter AccountId
  New Relic account id.
.Parameter APIKey
  Can be either the account level REST API key or an admin user's API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys
.Parameter ApplicationId
  The unique ID of the applicatin where the normalization rule will be created
.Parameter Action
  Specifies what to do with matching metrics. Can be one of 'IGNORE', 'DENY_NEW_METRICS', 'REPLACE'.
.Parameter Enabled
  State of the newly created normalization rule
.Parameter Expression
  The regex expression to match metrics against for the rule
.Parameter Notes
  Descriptive notes to add to the normalization rule
.Parameter Order
  Determines the order in which the normalization rule will be evaluated in (defaults to 9000)
.Parameter ReplacementExpression
  Specifies the expression to replace the metric with. Only valid with action type REPLACE.
.Parameter TerminateChain
  Specifies whether to continue evaluating rules if this rule is matching (defaults to true)
#>

Function New-NRNormalizationRule {
  [CMDLetBinding(SupportsShouldProcess = $true)]
  Param (
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $APIKey,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $ApplicationGUID,
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $AccountId,
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [ValidateSet('DENY_NEW_METRICS','IGNORE','REPLACE')]
    [string] $Action,
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $Expression,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [boolean] $Enabled = $true,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $Notes = '',
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $Order=9000,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $ReplacementExpression,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [boolean] $TerminateChain = $true
  )
  Begin {
    $url = 'https://api.newrelic.com/graphql'
    $headers = @{
      'Api-Key' = $APIKey
    }
  }
  Process {

    # Craft the body of the API call
    $Params = @{
      AccountId = $AccountId
      Action = $Action.ToUpper()
      ApplicationGUID = $ApplicationGUID
      Enabled = $Enabled
      Expression = $Expression
      Notes = $Notes
      Order = $Order
      ReplacementExpression = $ReplacementExpression
      TerminateChain = $TerminateChain
    }
    $graphqlQuery = Get-GraphQLQueryCreateNormalizationRule @Params
    Write-Verbose "GraphQLQuery: `n$graphqlQuery"
    $body = @{
      query = $graphqlQuery
    } | ConvertTo-Json

    # Call the API and return results
    If ($PSCmdlet.ShouldProcess($Name, 'Create Normalization Rule')) {
      $result = Invoke-RestMethod -Uri $url -headers $headers -body $body -Method 'Post' -ContentType 'application/json'

      If ($result.errors) {
        Write-Error ($result.errors | ConvertTo-Json -Depth 20)
      }
      return $result.data.metricNormalizationCreateRule.rule.id
    }
  }
}

<#
.Synopsis
  Updates a metric normalization rule for an application
.Description
  Updates a metric normalization rule for an application
.Example
  Update-NRNormalizationRule -APIKey 'fake-api-key' -AccountId 1234567 -Id 12345 -Enabled $true
  Enables rule 12345
.Example
  Update-NRNormalizationRule -APIKey 'fake-api-key' -AccountId 1234567 -Id 12345 -Action 'Ignore'
  Updates rule 12345 to action type of 'Ignore'
.Parameter AccountId
  New Relic account id.
.Parameter APIKey
  Can be either the account level REST API key or an admin user's API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys
.Parameter Action
  Specifies what to do with matching metrics. Can be one of 'IGNORE', 'DENY_NEW_METRICS', 'REPLACE'.
.Parameter Enabled
  Enables or disables the rule
.Parameter Expression
  The regex expression to match metrics against for the rule
.Parameter Notes
  Descriptive notes to add to the normalization rule
.Parameter Order
  Determines the order in which the normalization rule will be evaluated in (defaults to 9000)
.Parameter ReplacementExpression
  Specifies the expression to replace the metric with. Only valid with action type REPLACE.
.Parameter TerminateChain
  Specifies whether to continue evaluating rules if this rule is matching
#>

Function Update-NRNormalizationRule {
  [CMDLetBinding(SupportsShouldProcess = $true)]
  Param (
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $APIKey,
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $AccountId,
    [Parameter (Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [string] $Id,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [ValidateSet('DENY_NEW_METRICS','IGNORE','REPLACE')]
    [string] $Action,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $Expression,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [nullable[boolean]] $Enabled,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $Notes,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $Order,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [string] $ReplacementExpression,
    [Parameter (ValueFromPipelineByPropertyName = $true)]
    [nullable[boolean]] $TerminateChain
  )
  Begin {
    $url = 'https://api.newrelic.com/graphql'
    $headers = @{
      'Api-Key' = $APIKey
    }
  }
  Process {

    # Get existing rule details
    $existingRule = Get-NRNormalizationRule -ApiKey $APIKey -AccountId $AccountId -Id $Id

    # The NerdGraph API uses a PUT-like operation so all possible details must be provided
    $Params = @{
      RuleId = $Id
      AccountId = $AccountId
      Action = $Action ? $Action.ToUpper() : $existingRule.action
      Enabled = $null -ne $Enabled ? $Enabled : $existingRule.enabled
      Expression = $Expression ? "`"$Expression`"" : "`"$($existingRule.matchExpression)`""
      Notes = $Notes ? "`"$Notes`"" : $($existingRule.notes)
      Order = $Order ? $Order : $existingRule.evalOrder
      ReplacementExpression = $ReplacementExpression ? "`"$ReplacementExpression`"" : $($existingRule.replacement)
      TerminateChain = $null -ne $TerminateChain ? $TerminateChain : $existingRule.terminateChain
    }

    $graphqlQuery = Get-GraphQLQueryUpdateNormalizationRule @Params
    Write-Verbose "GraphQLQuery: `n$graphqlQuery"
    $body = @{
      query = $graphqlQuery
    } | ConvertTo-Json

    # Call the API and return results
    If ($PSCmdlet.ShouldProcess($Id, 'Update Normalization Rule')) {
      $result = Invoke-RestMethod -Uri $url -headers $headers -body $body -Method 'Post' -ContentType 'application/json'

      If ($result.errors) {
        Write-Error ($result.errors | ConvertTo-Json -Depth 20)
      }
      return $result.data.metricNormalizationEditRule.rule
    }
  }
}

<#
.Synopsis
  Gets an APM Entity or list of Entities
.Description
  Returns the complete list of entities within an account or can return a single entity
.Example
  Get-APMEntity -APIKey 'fake-api-key' -AccountId 1234567
  Returns the entire list of application Entities in account 1234567
.Example
  Get-APMEntity -APIKey 'fake-api-key' -AccountId 1234567 -Name 'MyApplication'
  Returns the application entity with name 'MyApplication'
.Parameter AccountId
  New Relic account id.
.Parameter APIKey
  Can be either the account level REST API key or an admin user's API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys
.Parameter Name
  If provided only the entity matching the name will be returned
.Parameter Type
  Defaults to APPLICATION. Acceptable values are: APPLICATION, DASHBOARD, HOST, MONITOR, WORKLOAD
#>

Function Get-NRAPMEntity {
  [CMDLetBinding()]
  Param (
    [Parameter (Mandatory = $true)]
    $ApiKey,
    [Parameter (Mandatory = $true)]
    $AccountId,
    $Name= '""',
    [ValidateSet ('APPLICATION','DASHBOARD','HOST','MONITOR','WORKLOAD')]
    $Type = 'APPLICATION'
  )
  Begin {
    $url = 'https://api.newrelic.com/graphql'
    $headers = @{
      'Api-Key' = $APIKey
    }
  }
  Process {
    [array]$applications = @()

    Do {
      # Craft the body of the GraphQL API call
      $Params = @{
        AccountId = $AccountId
        Name = $Name
        Type = $Type.ToUpper()
        NextCursor = $result.data.actor.entitySearch.results.nextCursor
      }
      $graphqlQuery = Get-GraphQLQueryGetAPMApplicationEntityGUID @Params
      Write-Verbose "GraphQLQuery: `n$graphqlQuery"
      $body = @{
        query = $graphqlQuery
      } | ConvertTo-Json

      # Call the API and return results
      $result = Invoke-RestMethod -Uri $url -headers $headers -body $body -Method 'Post' -ContentType 'application/json'

      If ($result.errors) {
        Write-Error ($result.errors | ConvertTo-Json -Depth 20)
      }
      $applications += $result.data.actor.entitysearch.results.entities
    } While ($result.data.actor.entitySearch.results.nextCursor)

    return $applications
  }
}