Categorygithub.com/PagerDuty/go-pagerduty
modulepackage
1.8.0
Repository: https://github.com/pagerduty/go-pagerduty.git
Documentation: pkg.go.dev

# README

GoDoc Go Report Card License

go-pagerduty

go-pagerduty is a CLI and go client library for the PagerDuty API.

Installation

To add the latest stable version to your project:

go get github.com/PagerDuty/[email protected]

If you instead wish to work with the latest code from main:

go get github.com/PagerDuty/go-pagerduty@latest

Usage

CLI

The CLI requires an authentication token, which can be specified in .pd.yml file in the home directory of the user, or passed as a command-line argument. Example of config file:

---
authtoken: fooBar

Commands

pd command provides a single entrypoint for all the API endpoints, with individual API represented by their own sub commands. For an exhaustive list of sub-commands, try:

pd --help

An example of the service sub-command

pd service list

Client Library

NOTICE: Breaking API Changes in v1.5.0

As part of the v1.5.0 release, we have fixed features that have never worked correctly and require a breaking API change to fix. One example is the issue reported in #232, as well as a handful of other examples within the v1.5.0 milestone.

If you are impacted by a breaking change in this release, you should audit the functionality you depended on as it may not have been working. If you cannot upgrade for some reason, the v1.4.x line of releases should still work. At the time of writing v1.4.3 was the latest, and we intend to backport any critical fixes for the time being.

Example Usage

package main

import (
	"fmt"
	"github.com/PagerDuty/go-pagerduty"
)

var	authtoken = "" // Set your auth token here

func main() {
	ctx := context.Background()
	client := pagerduty.NewClient(authtoken)

	var opts pagerduty.ListEscalationPoliciesOptions
	eps, err := client.ListEscalationPoliciesWithContext(ctx, opts)
	if err != nil {
		panic(err)
	}
	for _, p := range eps.EscalationPolicies {
		fmt.Println(p.Name)
	}
}

The PagerDuty API client also exposes its HTTP client as the HTTPClient field. If you need to use your own HTTP client, for doing things like defining your own transport settings, you can replace the default HTTP client with your own by simply by setting a new value in the HTTPClient field.

API Error Responses

For cases where your request results in an error from the API, you can use the errors.As() function from the standard library to extract the pagerduty.APIError error value and inspect more details about the error, including the HTTP response code and PagerDuty API Error Code.

package main

import (
	"fmt"
	"github.com/PagerDuty/go-pagerduty"
)

var	authtoken = "" // Set your auth token here

func main() {
	ctx := context.Background()
	client := pagerduty.NewClient(authtoken)
	user, err := client.GetUserWithContext(ctx, "NOTREAL", pagerduty.GetUserOptions{})
	if err != nil {
		var aerr pagerduty.APIError

		if errors.As(err, &aerr) {
			if aerr.RateLimited() {
				fmt.Println("rate limited")
				return
			}

			fmt.Println("unknown status code:", aerr.StatusCode)

			return
		}

		panic(err)
	}
	fmt.Println(user)
}

Extending and Debugging Client

Extending The Client

The *pagerduty.Client has a Do method which allows consumers to wrap the client, and make their own requests to the PagerDuty API. The method signature is similar to that of the http.Client.Do method, except it also includes a bool to incidate whether the API endpoint is authenticated (i.e., the REST API). When the API is authenticated, the client will annotate the request with the appropriate headers to be authenticated by the API.

If the PagerDuty client doesn't natively expose functionality that you wish to use, such as undocumented JSON fields, you can use the Do() method to issue your own request that you can parse the response of.

Likewise, you can use it to issue requests to the API for the purposes of debugging. However, that's not the only mechanism for debugging.

Debugging the Client

The *pagerduty.Client has a method that allows consumers to enable debug functionality, including interception of PagerDuty API responses. This is done by using the SetDebugFlag() method using the pagerduty.DebugFlag unsigned integer type. There are also exported constants to help consumers enable specific debug behaviors.

Capturing Last PagerDuty Response

If you're not getting the response you expect from the PagerDuty Go client, you can enable the DebugCaptureLastResponse debug flag to capture the HTTP responses. You can then use one of the methods to make an API call, and then inspect the API response received. For example:

client := pagerduty.NewClient("example")

client.SetDebugFlag(pagerduty.DebugCaptureLastResponse)

oncalls, err := client.ListOnCallsWithContext(ctx, pagerduty.ListOnCallOptions{})

resp, ok := client.LastAPIResponse()
if ok { // resp is an *http.Response we can inspect
	body, err := httputil.DumpResponse(resp, true)
    // ...
}

Included Packages

webhookv3

Support for V3 of PagerDuty Webhooks is provided via the webhookv3 package. The intent is for this package to provide signature verification and decoding helpers.

Contributing

  1. Fork it ( https://github.com/PagerDuty/go-pagerduty/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

License

Apache 2

# Packages

No description provided by the author
No description provided by the author
Package webhookv3 provides functionality for working with V3 PagerDuty Webhooks, including signature verification and decoding.

# Functions

CreateEvent sends PagerDuty an event to trigger, acknowledge, or resolve a problem.
CreateEventWithHTTPClient sends PagerDuty an event to trigger, acknowledge, or resolve a problem.
DecodeWebhook decodes a webhook from a response object.
ManageEvent handles the trigger, acknowledge, and resolve methods for an event.
ManageEventWithContext handles the trigger, acknowledge, and resolve methods for an event.
NewClient creates an API client using an account/user API token.
NewOAuthClient creates an API client using an OAuth token.
WithAPIEndpoint allows for a custom API endpoint to be passed into the the client.
WithOAuth allows for an OAuth token to be passed into the the client.
WithTerraformProvider configures the client to be used as the PagerDuty Terraform provider.
WithV2EventsAPIEndpoint allows for a custom V2 Events API endpoint to be passed into the client.

# Constants

DebugCaptureLastRequest captures the last HTTP request made to the API (if there was one) and makes it available via the LastAPIRequest() method.
DebugCaptureLastResponse captures the last HTTP response from the API (if there was one) and makes it available via the LastAPIResponse() method.
DebugDisabled disables all debug behaviors.
EmailFilterModeAll means that all incoming email will be be accepted, and no email rules will be considered.
EmailFilterModeAnd instructs the email filtering system to accept the email only if all of the rules match the message.
EmailFilterModeInvalid only exists to make it harder to use values of this type incorrectly.
EmailFilterModeOr instructs the email filtering system to accept the email if one or more rules match the message.
EmailFilterRuleModeAlways means that the specific value can be anything.
EmailFilterRuleModeInvalid only exists to make it harder to use values of this type incorrectly.
EmailFilterRuleModeMatch means that the associated regular expression must match the associated value.
EmailFilterRuleModeNoMatch means that the associated regular expression must NOT match the associated value.
TeamUserRoleManager is the manager team role, and they are given the same permissions as the responder plus the ability to edit and delete the different resources owned by the team.
TeamUserRoleObserver is the obesrver team role, which generally provides read-only access.
TeamUserRoleResponder is the responder team role, and they are given the same permissions as the observer plus the ability to respond to incidents, trigger incidents, and manage overrides.
Version is current version of this client.

# Structs

Acknowledgement is the data structure of an acknowledgement of an incident.
ActiveBetween represents an active_between object for setting a timeline for rules.
AddIncidentNotificationSubscribersResponse is the response structure when calling the AddNotificationSubscribers API endpoint.
Addon is a third-party add-on to PagerDuty's UI.
AddUserToTeamOptions is an option struct for the AddUserToTeamWithContext method.
AlertCounts is the data structure holding a summary of the number of alerts by status of an incident.
AlertGroupingParameters defines how alerts on the service will be automatically grouped into incidents.
AlertGroupParamsConfig is the config object on alert_grouping_parameters.
AnalyticsData represents the structure of the analytics we have available.
AnalyticsFilter represents the set of filters as part of the request to PagerDuty when requesting analytics.
AnalyticsRequest represents the request to be sent to PagerDuty when you want aggregated analytics.
AnalyticsResponse represents the response from the PagerDuty API.
APIDetails are the fields required to represent a details non-hydrated object.
APIError represents the error response received when an API call fails.
APIErrorObject represents the object returned by the API when an error occurs.
APIListObject are the fields used to control pagination when listing objects.
APIObject represents generic api json response that is shared by most domain objects (like escalation).
APIReference are the fields required to reference another API object.
Assignee is an individual assigned to an incident.
Assignment is the data structure for an assignment of an incident.
AuditRecord is a audit trail record that matches the query criteria.
No description provided by the author
AutoPauseNotificationsParameters defines how alerts on the service will be automatically paused.
BusinessService represents a business service.
BusinessServicePayload represents payload with a business service object.
BusinessServiceTeam represents a team object in a business service.
ChangeEvent represents a ChangeEvent's request parameters https://developer.pagerduty.com/docs/events-api-v2/send-change-events/#parameters.
ChangeEventLink represents a single link in a ChangeEvent https://developer.pagerduty.com/docs/events-api-v2/send-change-events/#the-links-property.
ChangeEventPayload ChangeEvent ChangeEventPayload https://developer.pagerduty.com/docs/events-api-v2/send-change-events/#example-request-payload.
ChangeEventResponse is the json response body for an event.
Channel is the means by which the action was carried out.
Client wraps http client.
CommonLogEntryField is the list of shared log entry between Incident and LogEntry.
ConditionParameter represents parameters in a rule condition.
ConferenceBridge is a struct for the conference_bridge object on an incident.
ContactMethod is a way of contacting the user.
Context are to be included with the trigger such as links to graphs or images.
CreateIncidentNoteResponse is returned from the API as a response to creating an incident note.
CreateIncidentOptions is the structure used when POSTing to the CreateIncident API endpoint.
Details contain additional information about the action or the resource that has been audited.
EscalationPolicy is a collection of escalation rules.
EscalationRule is a rule for an escalation policy to trigger.
Event stores data for problem reporting, acknowledgement, and resolution.
EventResponse is the data returned from the CreateEvent API endpoint.
EventsAPIV2Error represents the error response received when an Events API V2 call fails.
EventsAPIV2ErrorObject represents the object returned by the Events V2 API when an error occurs.
ExecutionContext contains information about the action execution context.
Extension represents a single PagerDuty extension.
ExtensionSchema represnts the object presented by the API for each extension schema.
Field contains information about the resource field that have been affected.
FirstTriggerLogEntry is the first LogEntry.
GetCurrentUserOptions is the data structure used when calling the GetCurrentUser API endpoint.
GetEscalationPolicyOptions is the data structure used when calling the GetEscalationPolicy API endpoint.
GetEscalationRuleOptions is the data structure used when calling the GetEscalationRule API endpoint.
GetIntegrationOptions is the data structure used when calling the GetIntegration API endpoint.
GetLogEntryOptions is the data structure used when calling the GetLogEntry API endpoint.
GetMaintenanceWindowOptions is the data structure used when calling the GetMaintenanceWindow API endpoint.
GetOrchestrationOptions is the data structure used when calling the GetOrchestration API endpoint.
GetOrchestrationRouterOptions is the data structure used when calling the GetOrchestrationRouter API endpoint.
GetOrchestrationUnroutedOptions is the data structure used when calling the GetOrchestrationUnrouted API endpoint.
GetScheduleOptions is the data structure used when calling the GetSchedule API endpoint.
GetServiceOptions is the data structure used when calling the GetService API endpoint.
GetServiceOrchestrationOptions is the data structure used when calling the GetServiceOrchestration API endpoint.
GetUserOptions is the data structure used when calling the GetUser API endpoint.
Incident is a normalized, de-duplicated event generated by a PagerDuty integration.
IncidentAlert is a alert for the specified incident.
IncidentAlertList is the generic structure of a list of alerts.
IncidentAlertResponse is the response of a sincle incident alert.
IncidentBody is the datastructure containing data describing the incident.
IncidentDetails contains a representation of the incident associated with the action that caused this webhook message.
IncidentNote is a note for the specified incident.
IncidentNotificationSubscriber is a Notification Subscriber on a Incident.
No description provided by the author
IncidentNotificationSubscriptionWithContext contains extra context returned from the API.
IncidentResponders contains details about responders to an incident.
IncidentStatusUpdate is a status update for the specified incident.
IncidentUrgencyRule is the default urgency for new incidents.
IncidentUrgencyType are the incidents urgency during or outside support hours.
InlineModel represents when a scheduled action will occur.
Integration is an endpoint (like Nagios, email, or an API call) that generates events, which are normalized and de-duplicated by PagerDuty to create incidents.
IntegrationEmailFilterRule represents a single email filter rule for an integration of type generic_email_inbound_integration.
No description provided by the author
No description provided by the author
No description provided by the author
ListAbilityResponse is the response when calling the ListAbility API endpoint.
ListAddonOptions are the options available when calling the ListAddons API endpoint.
ListAddonResponse is the response when calling the ListAddons API endpoint.
ListAlertsResponse is the response structure when calling the ListAlert API endpoint.
ListAuditRecordsOptions is the data structure used when calling the ListAuditRecords API endpoint.
ListAuditRecordsResponse is the response data received when calling the ListAuditRecords API endpoint.
ListBusinessServiceOptions is the data structure used when calling the ListBusinessServices API endpoint.
ListBusinessServicesResponse represents a list response of business services.
ListContactMethodsResponse is the data structure returned from calling the GetUserContactMethod API endpoint.
ListEPResponse is the structure used to list escalation policies assigned a given tag.
ListEscalationPoliciesOptions is the data structure used when calling the ListEscalationPolicies API endpoint.
ListEscalationPoliciesResponse is the data structure returned from calling the ListEscalationPolicies API endpoint.
ListEscalationRulesResponse represents the data structure returned when calling the ListEscalationRules API endpoint.
ListExtensionOptions are the options to use when listing extensions.
ListExtensionResponse represents the single response from the PagerDuty API when listing extensions.
ListExtensionSchemaOptions are the options to send with the ListExtensionSchema reques(s).
ListExtensionSchemaResponse is the object presented in response to the request to list all extension schemas.
ListIncidentAlertsOptions is the structure used when passing parameters to the ListIncidentAlerts API endpoint.
ListIncidentLogEntriesOptions is the structure used when passing parameters to the ListIncidentLogEntries API endpoint.
ListIncidentLogEntriesResponse is the response structure when calling the ListIncidentLogEntries API endpoint.
ListIncidentNotificationSubscribersResponse is the response structure when calling the ListNotificationSubscribers API endpoint.
ListIncidentsOptions is the structure used when passing parameters to the ListIncident API endpoint.
ListIncidentsResponse is the response structure when calling the ListIncident API endpoint.
No description provided by the author
No description provided by the author
No description provided by the author
ListLogEntriesOptions is the data structure used when calling the ListLogEntry API endpoint.
ListLogEntryResponse is the response data when calling the ListLogEntry API endpoint.
ListMaintenanceWindowsOptions is the data structure used when calling the ListMaintenanceWindows API endpoint.
ListMaintenanceWindowsResponse is the data structur returned from calling the ListMaintenanceWindows API endpoint.
No description provided by the author
No description provided by the author
ListNotificationOptions is the data structure used when calling the ListNotifications API endpoint.
ListNotificationsResponse is the data structure returned from the ListNotifications API endpoint.
ListOnCallOptions is the data structure used when calling the ListOnCalls API endpoint.
ListOnCallsResponse is the data structure returned from calling the ListOnCalls API endpoint.
ListOnCallUsersOptions is the data structure used when calling the ListOnCallUsers API endpoint.
ListOrchestrationsOptions is the data structure used when calling the ListOrchestrations API endpoint.
ListOrchestrationsResponse is the data structure returned from calling the ListOrchestrations API endpoint.
ListOverridesOptions is the data structure used when calling the ListOverrides API endpoint.
ListOverridesResponse is the data structure returned from calling the ListOverrides API endpoint.
ListPrioritiesOptions is the data structure used when calling the ListPriorities API endpoint.
ListPrioritiesResponse repreents the API response from PagerDuty when listing the configured priorities.
ListResponsePlaysOptions are the options for listing response plays.
ListResponsePlaysResponse represents the list of response plays.
ListRulesetRulesResponse represents a list of rules in a ruleset.
ListRulesetsResponse represents a list response of rulesets.
ListSchedulesOptions is the data structure used when calling the ListSchedules API endpoint.
ListSchedulesResponse is the data structure returned from calling the ListSchedules API endpoint.
ListServiceDependencies represents a list of dependencies for a service.
ListServiceOptions is the data structure used when calling the ListServices API endpoint.
ListServiceResponse is the data structure returned from calling the ListServices API endpoint.
ListServiceRulesResponse represents a list of rules in a service.
ListStandardsOptions is the data structure used when calling the ListStandards API endpoint.
ListStandardsResponse is the data structure returned from calling the ListStandards API endpoint.
ListTagOptions are the input parameters used when calling the ListTags API endpoint.
ListTagResponse is the structure used when calling the ListTags API endpoint.
ListTeamMembersOptions are the optional parameters for a members request.
ListTeamMembersResponse is the response from the members endpoint.
ListTeamOptions are the input parameters used when calling the ListTeams API endpoint.
ListTeamResponse is the structure used when calling the ListTeams API endpoint.
ListTeamsForTagResponse is the structure used to list teams assigned a given tag.
ListUserNotificationRulesResponse the data structure returned from calling the ListNotificationRules API endpoint.
ListUserResponse is the structure used to list users assigned a given tag.
ListUsersOptions is the data structure used when calling the ListUsers API endpoint.
ListUsersResponse is the data structure returned from calling the ListUsers API endpoint.
ListVendorOptions is the data structure used when calling the ListVendors API endpoint.
ListVendorResponse is the data structure returned from calling the ListVendors API endpoint.
LogEntry is a list of all of the events that happened to an incident.
MaintenanceWindow is used to temporarily disable one or more services for a set period of time.
ManageIncidentsOptions is the structure used when PUTing updates to incidents to the ManageIncidents func.
Member is a team member.
MergeIncidentsOptions is the structure used when merging incidents with MergeIncidents func.
Method contains information on the method used to perform the action.
Notification is a message containing the details of the incident.
NotificationRule is a rule for notifying the user.
NullAPIErrorObject is a wrapper around the APIErrorObject type.
NullEventsAPIV2ErrorObject is a wrapper around the EventsAPIV2ErrorObject type.
Occurrence is the data around whether this is a reocurring issue.
OnCall represents a contiguous unit of time for which a user will be on call for a given escalation policy and escalation rule.
Orchestration defines a global orchestration to route events the same source to different services.
OrchestrationExtraction defines a value extraction in an orchestration rule.
No description provided by the author
OrchestrationIntegration is a route into an orchestration.
No description provided by the author
No description provided by the author
OrchestrationRouter is an event router.
OrchestrationRouterActions are the actions that will be taken to change the resulting alert and incident.
OrchestrationRouterCatchAllRule routes an event when none of the rules match an event.
No description provided by the author
No description provided by the author
No description provided by the author
OrchestrationUnrouted defines sets of rules to be applied to unrouted events.
No description provided by the author
No description provided by the author
OrchestrationUnroutedRuleActions are the actions that will be taken to change the resulting alert and incident.
No description provided by the author
No description provided by the author
OrchestrationVariable defines a variable in an orchestration rule.
Override are any schedule layers from the override layer.
No description provided by the author
PendingAction is the data structure for any pending actions on an incident.
PreviewScheduleOptions is the data structure used when calling the PreviewSchedule API endpoint.
Priority is the data structure describing the priority of an incident.
Reference contains information about the reference that have been affected.
RemoveIncidentNotificationSubscribersResponse is the response structure when calling the RemoveNotificationSubscriber API endpoint.
RenderedScheduleEntry represents the computed set of schedule layer entries that put users on call for a schedule, and cannot be modified directly.
ResolveReason is the data structure describing the reason an incident was resolved.
No description provided by the author
No description provided by the author
No description provided by the author
ResponderRequest contains the API structure for an incident responder request.
ResponderRequestOptions defines the input options for the Create Responder function.
ResponderRequestResponse is the response from the API when requesting someone respond to an incident.
ResponderRequestTarget specifies an individual target for the responder request.
ResponderRequestTargetWrapper is a wrapper for a ResponderRequestTarget.
ResponseMetadata contains information about the response.
ResponsePlay represents the API object for a response object: https://developer.pagerduty.com/api-reference/b3A6Mjc0ODE2Ng-create-a-response-play.
Restriction limits on-call responsibility for a layer to certain times of the day or week.
RuleActionExtraction represents a rule extraction action object.
RuleActionParameter represents a generic parameter object on a rule action.
RuleActions represents a rule action.
RuleActionSuppress represents a rule suppress action object.
RuleActionSuspend represents a rule suspend action object.
RuleConditions represents the conditions field for a Ruleset.
Ruleset represents a ruleset.
RulesetObject represents a generic object that is common within a ruleset object.
RulesetPayload represents payload with a ruleset object.
RulesetRule represents a Ruleset rule.
RulesetRulePayload represents a payload for ruleset rules.
RuleSubcondition represents a subcondition of a ruleset condition.
RuleTimeFrame represents a time_frame object on the rule object.
Schedule determines the time periods that users are on call.
ScheduledAction contains scheduled actions for the service.
ScheduledWeekly represents a time_frame object for scheduling rules weekly.
ScheduleLayer is an entry that puts users on call for a schedule.
Service represents something you monitor (like a web service, email service, or database service).
ServiceDependency represents a relationship between a business and technical service.
ServiceObj represents a service object in service relationship.
ServiceOrchestration defines sets of rules belonging to a service.
No description provided by the author
No description provided by the author
No description provided by the author
ServiceOrchestrationRuleActions are the actions that will be taken to change the resulting alert and incident.
No description provided by the author
No description provided by the author
ServiceRule represents a Service rule.
ServiceRuleActions represents a rule action.
Standard defines a PagerDuty resource standard.
No description provided by the author
SupportHours are the support hours for the service.
Tag is a way to label user, team and escalation policies in PagerDuty.
TagAssignment is the structure for assigning tags to an entity.
TagAssignments can be applied teams, users and escalation policies.
Team is a collection of users and escalation policies that represent a group of people within an organization.
UpdateScheduleOptions is the data structure used when calling the UpdateSchedule API endpoint.
User is a member of a PagerDuty account that has the ability to interact with incidents and other data on the account.
UserReference is a reference to an authorized PagerDuty user.
V2Event includes the incident/alert details.
V2EventResponse is the json response body for an event.
V2Payload represents the individual event details for an event.
Vendor represents a specific type of integration.
WebhookPayload represents the V2 webhook payload.
WebhookPayloadMessages is the wrapper around the Webhook payloads.

# Interfaces

HTTPClient is an interface which declares the functionality we need from an HTTP client.

# Type aliases

Agent is the actor who carried out the action.
ClientOptions allows for options to be passed into the Client for customization.
DebugFlag represents a set of debug bit flags that can be bitwise-ORed together to configure the different behaviors.
IntegrationEmailFilterMode is a type to respresent the different filter modes for a Generic Email Integration.
IntegrationEmailFilterRuleMode is a type to represent the different matching modes of Generic Email Integration Filer Rules without consumers of this package needing to be intimately familiar with the specifics of the REST API.
ListMembersOptions is the original type name and is retained as an alias for API compatibility.
ListMembersResponse is the original type name and is retained as an alias for API compatibility.
Priorities is the original type name and is retained as an alias for API compatibility.
PriorityProperty is the original type name and is retained as an alias for API compatibility.
TeamUserRole is a named type to represent the different Team Roles supported by PagerDuty when adding a user to a team.