wavefront

package module
v2.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2023 License: Apache-2.0 Imports: 15 Imported by: 1

README

Golang Wavefront Client

Golang SDK for interacting with the Wavefront v2 REST API, and sending metrics through a Wavefront proxy.

Usage

API Client

Supports most public API paths. Refer to the documentation for further information.

package main

import (
    "fmt"
    "log"
    "os"

    wavefront "github.com/WavefrontHQ/go-wavefront-management-api/v2"
)

func main() {
    client, err := wavefront.NewClient(
        &wavefront.Config{
            Address: os.Getenv("WAVEFRONT_ADDRESS"),
            Token:     os.Getenv("WAVEFRONT_TOKEN"),
        },
    )

    query := client.NewQuery(
        wavefront.NewQueryParams(`ts("cpu.load.1m.avg", dc=dc1)`),
    )

    result, err := query.Execute()

    if err != nil {
        log.Fatal(err)
    }

    if len(result.TimeSeries) > 0 {
        fmt.Println(result.TimeSeries[0].Label)
        fmt.Println(result.TimeSeries[0].DataPoints[0])
    } else {
        fmt.Println("No matching data.")
    }
}
Writer

Writer has full support for metric tagging etc.

Again, see examples for a more detailed explanation.

package main

import (
    "log"
    "os"

    wavefront "github.com/WavefrontHQ/go-wavefront-management-api/v2/writer"
)

func main() {
    source, _ := os.Hostname()

    wf, err := wavefront.NewWriter("wavefront-proxy.example.com", 2878, source, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer wf.Close()

    wf.Write(wavefront.NewMetric("something.very.good.count", 33))
}

Contributing

Pull requests are welcomed.

If you'd like to contribute to this project, please raise an issue and indicate that you'd like to take on the work prior to submitting a pull request.

Documentation

Overview

Package wavefront provides a library for interacting with the Wavefront API, along with a writer for sending metrics to a Wavefront proxy.

Index

Examples

Constants

View Source
const (
	AlertTypeThreshold = "THRESHOLD"
	AlertTypeClassic   = "CLASSIC"
)
View Source
const (

	// some constants provided for time convenience
	LastHour    = 60 * 60
	Last3Hours  = LastHour * 3
	Last6Hours  = LastHour * 6
	Last24Hours = LastHour * 24
	LastDay     = Last24Hours
	LastWeek    = LastDay * 7
)
View Source
const (
	AGENT_MANAGEMENT           = "agent_management"
	ALERTS_MANAGEMENT          = "alerts_management"
	DASHBOARD_MANAGEMENT       = "dashboard_management"
	EMBEDDED_CHARTS_MANAGEMENT = "embedded_charts"
	EVENTS_MANAGEMENT          = "events_management"
	EXTERNAL_LINKS_MANAGEMENT  = "external_links_management"
	HOST_TAG_MANAGEMENT        = "host_tag_management"
	METRICS_MANAGEMENT         = "metrics_management"
	USER_MANAGEMENT            = "user_management"
	INTEGRATIONS_MANAGEMENT    = "application_management"
	DIRECT_INGESTION           = "ingestion"
	BATCH_QUERY_PRIORITY       = "batch_query_priority"
	DERIVED_METRICS_MANAGEMENT = "derived_metrics_management"
)

Variables

This section is empty.

Functions

func NotFound

func NotFound(err error) bool

NotFound returns true if err is because the resource doesn't exist.

Types

type AWSBaseCredentials

type AWSBaseCredentials struct {
	// The Role ARN that the customer has created in AWS IAM to allow access to Wavefront
	RoleARN string `json:"roleArn"`

	// The external id corresponding to the Role ARN
	ExternalID string `json:"externalId"`
}

type AccessControlList

type AccessControlList struct {
	CanView   []string `json:"canView,omitempty"`
	CanModify []string `json:"canModify,omitempty"`
}

type Alert

type Alert struct {
	// Name is the name given to an Alert
	Name string `json:"name"`

	// ID is the Wavefront-assigned ID of an existing Alert
	ID *string `json:"id,omitempty"`

	// AlertType should be either CLASSIC or THRESHOLD
	AlertType string `json:"alertType,omitempty"`

	// AdditionalInfo is any extra information about the Alert
	AdditionalInfo string `json:"additionalInformation"`

	// Target is a comma-separated list of targets for the Alert
	Target string `json:"target,omitempty"`

	// For THRESHOLD alerts. Targets is a map[string]string. This maps severity to lists of targets.
	// Valid keys are: severe, smoke, warn or info
	Targets map[string]string `json:"targets"`

	// Condition is the condition under which the Alert will fire
	Condition string `json:"condition"`

	// For THRESHOLD alerts. Conditions is a map[string]string. This maps severity to respective conditions.
	// Valid keys are: severe, smoke, warn or info
	Conditions map[string]string `json:"conditions"`

	// DisplayExpression is the ts query to generate a graph of this Alert, in the UI
	DisplayExpression string `json:"displayExpression,omitempty"`

	// Minutes is the number of minutes the Condition must be met, before the
	// Alert will fire
	Minutes int `json:"minutes"`

	// ResolveAfterMinutes is the number of minutes the Condition must be un-met
	// before the Alert is considered resolved
	ResolveAfterMinutes int `json:"resolveAfterMinutes,omitempty"`

	// Minutes to wait before re-sending notification of firing alert.
	NotificationResendFrequencyMinutes int `json:"notificationResendFrequencyMinutes"`

	// Severity is the severity of the Alert, and can be one of SEVERE,
	// SMOKE, WARN or INFO
	Severity string `json:"severity,omitempty"`

	// For THRESHOLD alerts. SeverityList is a list of strings. Different severities applicable to this alert.
	// Valid elements are: SEVERE, SMOKE, WARN or INFO
	SeverityList []string `json:"severityList"`

	// Status is the current status of the Alert
	Status []string `json:"status"`

	// Tags are the tags applied to the Alert
	Tags []string

	// Access Control Lists for who can view or modify (user or group IDs)// ACL to apply to the alert
	ACL AccessControlList `json:"acl"`

	FailingHostLabelPairs       []SourceLabelPair `json:"failingHostLabelPairs,omitempty"`
	InMaintenanceHostLabelPairs []SourceLabelPair `json:"inMaintenanceHostLabelPairs,omitempty"`

	// The interval between checks for this alert, in minutes
	CheckingFrequencyInMinutes int `json:"processRateMinutes,omitempty"`

	// Real-Time Alerting, evaluate the alert strictly on ingested data without accounting for delays
	EvaluateRealtimeData bool `json:"evaluateRealtimeData,omitempty"`

	// Include obsolete metrics in alert query
	IncludeObsoleteMetrics bool `json:"includeObsoleteMetrics,omitempty"`

	// User-supplied runbook links for this alert
	RunbookLinks []string `json:"runbookLinks"`

	// User-supplied dashboard and parameters to create dashboard links
	AlertTriageDashboards []AlertTriageDashboard `json:"alertTriageDashboards"`
}

Alert represents a single Wavefront Alert

func (*Alert) MarshalJSON

func (a *Alert) MarshalJSON() ([]byte, error)

func (*Alert) UnmarshalJSON

func (a *Alert) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom JSON unmarshaller for an Alert, used in order to populate the Tags field in a more intuitive fashion

type AlertRoute

type AlertRoute struct {
	// The notification target method, supports values in EMAIL, PAGERDUTY, WEBHOOK
	Method string `json:"method,omitempty"`

	// The endpoint for the notification target
	Target string `json:"target,omitempty"`

	// A space delimited string to filter on tagk=value e.g. env prod
	Filter string `json:"filter,omitempty"`
}

type AlertTriageDashboard added in v2.2.0

type AlertTriageDashboard struct {
	DashboardId string                       `json:"dashboardId"`
	Parameters  map[string]map[string]string `json:"parameters"`
	Description string                       `json:"description"`
}

type Alerts

type Alerts struct {
	// contains filtered or unexported fields
}

Alerts is used to perform alert-related operations against the Wavefront API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

alerts := client.Alerts()
targets := client.Targets()

// ######################
// EXAMPLE: Classic Alert
// ######################

a := &wavefront.Alert{
	Name:                "My First Alert",
	Target:              "test@example.com",
	Condition:           "ts(servers.cpu.usage, dc=dc2) > 10 * 10",
	DisplayExpression:   "ts(servers.cpu.usage, dc=dc2)",
	Minutes:             2,
	ResolveAfterMinutes: 2,
	Severity:            "WARN",
	Tags:                []string{"dc1", "synergy"},
}

// Create the alert on Wavefront
err = alerts.Create(a)
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete the Alert
fmt.Println("alert ID is", *a.ID)

// Alternatively we could search for the Alert
err = alerts.Get(&wavefront.Alert{
	ID: a.ID,
})

if err != nil {
	log.Fatal(err)
}

// Update the Alert
a.Target = "test@example.com,bob@example.com"
err = alerts.Update(a)
if err != nil {
	log.Fatal(err)
}

// Delete the Alert
err = alerts.Delete(a, true)
if err != nil {
	log.Fatal(err)
}

fmt.Println("alert deleted")

// ########################
// EXAMPLE: Threshold Alert
// ########################

// Threshold Alerts only accept custom alert targets
// Create Alert Targets that can be used for the example

tmpl, _ := os.ReadFile("./target-template.tmpl")
targetA := wavefront.Target{
	Title:       "test target",
	Description: "testing something A",
	Method:      "WEBHOOK",
	Recipient:   "https://hooks.slack.com/services/test/me",
	ContentType: "application/json",
	CustomHeaders: map[string]string{
		"Testing": "true",
	},
	Triggers: []string{"ALERT_OPENED", "ALERT_RESOLVED"},
	Template: string(tmpl),
}

targetB := wavefront.Target{
	Title:       "test target",
	Description: "testing something B",
	Method:      "WEBHOOK",
	Recipient:   "https://hooks.slack.com/services/test/me",
	ContentType: "application/json",
	CustomHeaders: map[string]string{
		"Testing": "true",
	},
	Triggers: []string{"ALERT_OPENED", "ALERT_RESOLVED"},
	Template: string(tmpl),
}

targetC := wavefront.Target{
	Title:       "test target",
	Description: "testing something C",
	Method:      "WEBHOOK",
	Recipient:   "https://hooks.slack.com/services/test/me",
	ContentType: "application/json",
	CustomHeaders: map[string]string{
		"Testing": "true",
	},
	Triggers: []string{"ALERT_OPENED", "ALERT_RESOLVED"},
	Template: string(tmpl),
}

// Create the targets on Wavefront
err = targets.Create(&targetA)
if err != nil {
	log.Fatal(err)
}
err = targets.Create(&targetB)
if err != nil {
	log.Fatal(err)
}
err = targets.Create(&targetC)
if err != nil {
	log.Fatal(err)
}

fmt.Println("alert targets created")

strA := fmt.Sprintf("target:%s", *targetA.ID)
strB := fmt.Sprintf("target:%s", *targetB.ID)
strC := fmt.Sprintf("target:%s", *targetC.ID)

mta := &wavefront.Alert{
	Name:      "My First Threshold Alert",
	AlertType: "THRESHOLD",
	Targets: map[string]string{
		"smoke": strA,
		"warn":  strB,
	},
	Conditions: map[string]string{
		"smoke": "ts(servers.cpu.usage) > 70",
		"warn":  "ts(servers.cpu.usage) > 100",
	},
	DisplayExpression:   "ts(servers.cpu.usage)",
	Minutes:             2,
	ResolveAfterMinutes: 2,
	SeverityList:        []string{"SMOKE", "WARN"},
	Tags:                []string{"dc1", "synergy"},
}

// Create the thresold alert on Wavefront
err = alerts.Create(mta)
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete the Threshold Alert
fmt.Println("threshold alert ID is", *mta.ID)

// Alternatively we could search for the Threshold Alert
err = alerts.Get(&wavefront.Alert{
	ID: mta.ID,
})

if err != nil {
	log.Fatal(err)
}

// Update the Threshold Alert
mta.Targets["smoke"] = strC
err = alerts.Update(mta)
if err != nil {
	log.Fatal(err)
}

// Delete the Threshold Alert
err = alerts.Delete(mta, true)
if err != nil {
	log.Fatal(err)
}

fmt.Println("threshold alert deleted")

err = targets.Delete(&targetA)
if err != nil {
	log.Fatal(err)
}
err = targets.Delete(&targetB)
if err != nil {
	log.Fatal(err)
}
err = targets.Delete(&targetC)
if err != nil {
	log.Fatal(err)
}

fmt.Println("alert targets deleted")
Output:

func (Alerts) Create

func (a Alerts) Create(alert *Alert) error

Create is used to create an Alert in Wavefront. If successful, the ID field of the alert will be populated.

func (Alerts) Delete

func (a Alerts) Delete(alert *Alert, skipTrash bool) error

Delete is used to delete an existing Alert. The ID field of the alert must be populated

func (Alerts) Find

func (a Alerts) Find(filter []*SearchCondition) (alerts []*Alert, err error)

Find returns all alerts filtered by the given search conditions. If filter is nil, all alerts are returned.

func (Alerts) Get

func (a Alerts) Get(alert *Alert) error

Get is used to retrieve an existing Alert by ID. The ID field must be provided

func (Alerts) SetACL

func (a Alerts) SetACL(id string, canView, canModify []string) error

Sets the ACL on the alert with the supplied list of IDs for canView and canModify an empty []string on canView will remove all values set an empty []string on canModify will set the value to the owner of the token issuing the API call

func (Alerts) Update

func (a Alerts) Update(alert *Alert) error

Update is used to update an existing Alert. The ID field of the alert must be populated

type AppDynamicsConfiguration

type AppDynamicsConfiguration struct {
	// Username is a combination of username and the account name
	UserName string `json:"userName"`

	// Name of the SaaS controller
	ControllerName string `json:"controllerName"`

	// Password for the AppDynamics user
	EncryptedPassword string `json:"encryptedPassword"`

	// Set this to 'false' to get separate results for all values with in the time range, by default it is true
	EnableRollup bool `json:"enableRollup,omitempty"`

	// Flag to control Error metric injections
	EnableErrorMetrics bool `json:"enableErrorMetrics,omitempty"`

	// Flag to control Business Transaction Metric injection
	EnableBusinessTrxMetrics bool `json:"enableBusinessTrxMetrics,omitempty"`

	// flag to control Backend metric injection
	EnableBackendMetrics bool `json:"enableBackendMetrics,omitempty"`

	// Flag to control Overall Performance metric injection
	EnableOverallPerfMetrics bool `json:"enableOverallPerfMetrics,omitempty"`

	// Flag to control individual Node metric injection
	EnableIndividualNodeMetrics bool `json:"enableIndividualNodeMetrics,omitempty"`

	// Flag to control Application Infrastructure metric injection
	EnableAppInfraMetrics bool `json:"enableAppInfraMetrics,omitempty"`

	// Flag to control Service End point metric injection
	EnableServiceEndpointMetrics bool `json:"enableServiceEndpointMetrics,omitempty"`

	// List of regular expressions that a application name must match (case-insensitively) in order to be ingested
	AppFilterRegex []string `json:"appFilterRegex"`
}

type AzureActivityLogConfiguration

type AzureActivityLogConfiguration struct {
	BaseCredentials *AzureBaseCredentials `json:"baseCredentials,omitempty"`

	// A list of Azure ActivityLog categories to pull events for
	CategoryFilter []string `json:"categoryFilter,omitempty"`
}

type AzureBaseCredentials

type AzureBaseCredentials struct {
	// Client Id for an Azure service account within your project
	ClientID string `json:"clientId"`

	// Client Secret for an Azure service account within your project.  use `saved_secret` to retain the client secret
	// when updating
	ClientSecret string `json:"clientSecret"`

	// Tenant Id for an Azure service account within your project
	Tenant string `json:"tenant"`
}

type AzureConfiguration

type AzureConfiguration struct {
	// A regular expression that a CloudWatch metric name must match (case-insensitively) in order to be ingested
	MetricFilterRegex string `json:"metricFilterRegex,omitempty"`

	BaseCredentials *AzureBaseCredentials `json:"baseCredentials,omitempty"`

	// A list of Azure services (such as Microsoft.Compute/virtualMachines,Microsoft.Cache/redis etc) from which to pull
	// metrics
	CategoryFilter []string `json:"categoryFilter,omitempty"`

	// A list of Azure resource groups from which to pull metrics
	ResourceGroupFilter []string `json:"resourceGroupFilter,omitempty"`
}

type Chart

type Chart struct {
	// Name is the name of a chart
	Name string `json:"name"`

	// Description is the description of the chart
	Description string `json:"description"`

	// Base (unknown usage, defaults to 1)
	Base int `json:"base"`

	// Include obsolete metrics older than 4 weeks ago into the current time window
	IncludeObsoleteMetrics bool `json:"includeObsoleteMetrics"`

	// Interpolate points that existed in the past /future into the current time window
	InterpolatePoints bool `json:"interpolatePoints"`

	// Don't include default events on the chart
	NoDefaultEvents bool `json:"noDefaultEvents"`

	// Strategy to use when aggregating metric points (LAST, AVERAGE, COUNT, etc)
	Summarization string `json:"summarization,omitempty"`

	// Sources is an Array of Source
	Sources []Source `json:"sources"`

	// Units are the units to use for the y-axis
	Units string `json:"units,omitempty"`

	// ChartSettings are custom settings for the chart
	ChartSettings ChartSetting `json:"chartSettings"`

	// ChartAttributes is arbitrary JSON used to configure a chart's attributes
	ChartAttributes json.RawMessage `json:"chartAttributes,omitempty"`
}

Chart represents a single Chart, on a single Row with in Section of a Wavefront Dashboard

type ChartSetting

type ChartSetting struct {
	AutoColumnTags                     bool      `json:"autoColumnTags,omitempty"`
	ColumnTags                         string    `json:"columnTags,omitempty"`
	CustomTags                         []string  `json:"customTags,omitempty"`
	ExpectedDataSpacing                int       `json:"expectedDataSpacing,omitempty"`
	FixedLegendDisplayStats            []string  `json:"fixedLegendDisplayStats,omitempty"`
	FixedLegendEnabled                 bool      `json:"fixedLegendEnabled,omitempty"`
	FixedLegendFilterField             string    `json:"fixedLegendFilterField,omitempty"`
	FixedLegendFilterLimit             int       `json:"fixedLegendFilterLimit,omitempty"`
	FixedLegendFilterSort              string    `json:"fixedLegendFilterSort,omitempty"`
	FixedLegendHideLabel               bool      `json:"fixedLegendHideLabel,omitempty"`
	FixedLegendPosition                string    `json:"fixedLegendPosition,omitempty"`
	FixedLegendUseRawStats             bool      `json:"fixedLegendUseRawStats,omitempty"`
	GroupBySource                      bool      `json:"groupBySource,omitempty"`
	InvertDynamicLegendHoverControl    bool      `json:"invertDynamicLegendHoverControl,omitempty"`
	LineType                           string    `json:"lineType,omitempty"`
	Max                                float32   `json:"max,omitempty"`
	Min                                float32   `json:"min,omitempty"`
	NumTags                            int       `json:"numTags,omitempty"`
	PlainMarkdownContent               string    `json:"plainMarkdownContent,omitempty"`
	ShowHosts                          bool      `json:"showHosts,omitempty"`
	ShowLabels                         bool      `json:"showLabels,omitempty"`
	ShowRawValues                      bool      `json:"showRawValues,omitempty"`
	SortValuesDescending               bool      `json:"sortValuesDescending,omitempty"`
	SparklineDecimalPrecision          int       `json:"sparklineDecimalPrecision"`
	SparklineDisplayColor              string    `json:"sparklineDisplayColor,omitempty"`
	SparklineDisplayFontSize           string    `json:"sparklineDisplayFontSize,omitempty"`
	SparklineDisplayHorizontalPosition string    `json:"sparklineDisplayHorizontalPosition,omitempty"`
	SparklineDisplayPostfix            string    `json:"sparklineDisplayPostfix,omitempty"`
	SparklineDisplayPrefix             string    `json:"sparklineDisplayPrefix,omitempty"`
	SparklineDisplayValueType          string    `json:"sparklineDisplayValueType,omitempty"`
	SparklineDisplayVerticalPosition   string    `json:"sparklineDisplayVerticalPosition,omitempty"`
	SparklineFillColor                 string    `json:"sparklineFillColor,omitempty"`
	SparklineLineColor                 string    `json:"sparklineLineColor,omitempty"`
	SparklineSize                      string    `json:"sparklineSize,omitempty"`
	SparklineValueColorMapApplyTo      string    `json:"sparklineValueColorMapApplyTo,omitempty"`
	SparklineValueColorMapColors       []string  `json:"sparklineValueColorMapColors,omitempty"`
	SparklineValueColorMapValues       []int     `json:"sparklineValueColorMapValues,omitempty"`
	SparklineValueColorMapValuesV2     []float32 `json:"sparklineValueColorMapValuesV2,omitempty"`
	SparklineValueTextMapText          []string  `json:"sparklineValueTextMapText,omitempty"`
	SparklineValueTextMapThresholds    []float32 `json:"sparklineValueTextMapThresholds,omitempty"`
	StackType                          string    `json:"stackType,omitempty"`
	TagMode                            string    `json:"tagMode,omitempty"`
	TimeBasedColoring                  bool      `json:"timeBasedColoring,omitempty"`
	Type                               string    `json:"type,omitempty"`
	Windowing                          string    `json:"windowing,omitempty"`
	WindowSize                         int       `json:"windowSize,omitempty"`
	Xmax                               float32   `json:"xmax,omitempty"`
	Xmin                               float32   `json:"xmin,omitempty"`
	Y0ScaleSIBy1024                    bool      `json:"y0ScaleSIBy1024,omitempty"`
	Y0UnitAutoscaling                  bool      `json:"y0UnitAutoscaling,omitempty"`
	Y1Max                              float32   `json:"y1Max,omitempty"`
	Y1Min                              float32   `json:"y1Min,omitempty"`
	Y1ScaleSIBy1024                    bool      `json:"y1ScaleSIBy1024,omitempty"`
	Y1UnitAutoscaling                  bool      `json:"y1UnitAutoscaling,omitempty"`
	Y1Units                            string    `json:"y1Units,omitempty"`
	Ymax                               float32   `json:"ymax,omitempty"`
	Ymin                               float32   `json:"ymin,omitempty"`
}

ChartSetting represents various custom settings for a Chart

type Client

type Client struct {
	// Config is a Config object that will be used to construct requests
	Config *Config

	// BaseURL is the full URL of the Wavefront API, of the form
	// https://example.wavefront.com/api/v2
	BaseURL *url.URL

	// The maximum amount of time we will wait
	MaxRetryDurationInMS int
	// contains filtered or unexported fields
}

Client is used to generate API requests against the Wavefront API.

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient returns a new Wavefront client according to the given Config

func (*Client) Alerts

func (c *Client) Alerts() *Alerts

Alerts is used to return a client for alert-related operations

func (*Client) CloudIntegrations

func (c *Client) CloudIntegrations() *CloudIntegrations

func (*Client) Dashboards

func (c *Client) Dashboards() *Dashboards

Dashboards is used to return a client for Dashboard-related operations

func (*Client) Debug

func (c *Client) Debug(enable bool)

Debug enables dumping http request objects to stdout

func (*Client) DerivedMetrics

func (c *Client) DerivedMetrics() *DerivedMetrics

func (Client) Do

func (c Client) Do(req *http.Request) (io.ReadCloser, error)

Do executes a request against the Wavefront API. The response body is returned if the request is successful, and should be closed by the requester.

func (*Client) Events

func (c *Client) Events() *Events

Events is used to return a client for event-related operations

func (c *Client) ExternalLinks() *ExternalLinks

func (*Client) IngestionPolicies

func (c *Client) IngestionPolicies() *IngestionPolicies

func (*Client) MaintenanceWindows

func (c *Client) MaintenanceWindows() *MaintenanceWindows

MaintenanceWindows is used to return a client for maintenance window related operations

func (*Client) MetricsPolicyAPI

func (c *Client) MetricsPolicyAPI() *MetricsPolicyAPI

MetricsPolicyAPI is used to return a client for MetricsPolicy-related operations

func (*Client) NewQuery

func (c *Client) NewQuery(params *QueryParams) *Query

NewQuery returns a Query based on QueryParams

func (Client) NewRequest

func (c Client) NewRequest(method, path string, params *map[string]string, body []byte) (*http.Request, error)

NewRequest creates a request object to query the Wavefront API. Path is a relative URI that should be specified with no trailing slash, it will be resolved against the BaseURL of the client. Params should be passed as a map[string]string, these will be converted to query parameters.

func (*Client) NewSearch

func (c *Client) NewSearch(searchType string, params *SearchParams) *Search

NewSearch returns a Search based on SearchParams. searchType is the type of entity to be searched for (i.e. alert, event, dashboard, extlink, cloudintegration etc.)

func (*Client) Roles

func (c *Client) Roles() *Roles

func (*Client) ServiceAccounts

func (c *Client) ServiceAccounts() *ServiceAccounts

ServiceAccounts is used to return a client for service account related operations

func (*Client) Targets

func (c *Client) Targets() *Targets

Targets is used to return a client for target-related operations

func (*Client) Tokens

func (c *Client) Tokens() *Tokens

Tokens is used to return a client for service account token related operations

func (*Client) UserGroups

func (c *Client) UserGroups() *UserGroups

UserGroups is used to return a client for user-group related operations

func (*Client) Users

func (c *Client) Users() *Users

Users is used to return a client for user-related operations

type CloudIntegration

type CloudIntegration struct {
	ForceSave bool   `json:"forceSave,omitempty"`
	Id        string `json:"id,omitempty"`

	// The human-readable name of this integration
	Name string `json:"name"`

	// A value denoting which cloud service this integration integrates with
	Service string `json:"service"`

	// A value denoting whether or not this cloud integration is in the trashcan
	InTrash bool `json:"inTrash,omitempty"`

	// The creator of the cloud integration
	CreatorId string `json:"creatorId,omitempty"`

	// The user of the last person to update this integration
	UpdaterId string `json:"updaterId,omitempty"`

	// Event of the last error encountered by Wavefront servers when fetching data using this integration
	LastErrorEvent *Event `json:"lastErrorEvent,omitempty"`

	// A list of point tag key-values to add to every point ingested using this integration
	AdditionalTags map[string]string `json:"additionalTags,omitempty"`

	// Time that this integration last received a data point, in epoch millis
	LastReceivedDataPointMs int `json:"lastReceivedDataPointMs,omitempty"`

	// Number of metrics / events ingested by this integration the last time it ran
	LastMetricCount int `json:"lastMetricCount,omitempty"`

	CloudWatch       *CloudWatchConfiguration       `json:"cloudWatch,omitempty"`
	CloudTrail       *CloudTrailConfiguration       `json:"cloudTrail,omitempty"`
	EC2              *EC2Configuration              `json:"ec2,omitempty"`
	GCP              *GCPConfiguration              `json:"gcp,omitempty"`
	GCPBilling       *GCPBillingConfiguration       `json:"gcpBilling,omitempty"`
	NewRelic         *NewRelicConfiguration         `json:"newRelic,omitempty"`
	AppDynamics      *AppDynamicsConfiguration      `json:"appDynamics,omitempty"`
	Tesla            *TeslaConfiguration            `json:"tesla,omitempty"`
	Azure            *AzureConfiguration            `json:"azure,omitempty"`
	AzureActivityLog *AzureActivityLogConfiguration `json:"azureActivityLog,omitempty"`

	// Time, in epoch millis, of the last error encountered by Wavefront servers when fetching data using this integration.
	LastErrorMs int `json:"lastErrorMs,omitempty"`

	// True when an aws credential failed to authenticate
	Disabled bool `json:"disabled,omitempty"`

	// Opaque Id of the last Wavefront Integrations service to act on this integration
	LastProcessorId string `json:"lastProcessorId,omitempty"`

	// Time, in epoch millis, that this integration was last processed
	LastProcessingTimestamp int `json:"lastProcessingTimestamp,omitempty"`

	CreatedEpochMillis int `json:"createdEpochMillis,omitempty"`
	UpdatedEpochMillis int `json:"updatedEpochMillis,omitempty"`

	// Service refresh rate in minutes
	ServiceRefreshRateInMins int `json:"serviceRefreshRateInMins,omitempty"`

	Deleted bool `json:"deleted,omitempty"`
}

type CloudIntegrations

type CloudIntegrations struct {
	// contains filtered or unexported fields
}
Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

cloudIntegrations := client.CloudIntegrations()

// Create a new AWS CloudWatch Integration
externalId, err := cloudIntegrations.CreateAwsExternalID()
if err != nil {
	log.Fatal(err)
}

cloudWatchIntegration := wavefront.CloudIntegration{
	Name:    "example-cloud-watch-integration",
	Service: "CLOUDWATCH",
	CloudWatch: &wavefront.CloudWatchConfiguration{
		MetricFilterRegex: "^(ec2|elb).*$",
		BaseCredentials: &wavefront.AWSBaseCredentials{
			RoleARN:    "arn:aws:iam:1234567890:role/example-cloud-watch-integration",
			ExternalID: externalId,
		},
	},
}

err = cloudIntegrations.Create(&cloudWatchIntegration)
if err != nil {
	log.Fatal(err)
}

// Get an integration by id
err = cloudIntegrations.Get(&cloudWatchIntegration)
if err != nil {
	log.Fatal(err)
}

// Update an existing integration
cloudWatchIntegration.CloudWatch.InstanceSelectionTags = map[string]string{
	"env":  "prod",
	"role": "app",
}

err = cloudIntegrations.Update(&cloudWatchIntegration)

if err != nil {
	log.Fatal(err)
}

// Delete an existing integration and bypass the trashcan
err = cloudIntegrations.Delete(&cloudWatchIntegration, true)

if err != nil {
	log.Fatal(err)
}
Output:

func (CloudIntegrations) Create

func (ci CloudIntegrations) Create(cloudIntegration *CloudIntegration) error

Creates a CloudIntegration in Wavefront If successful, the ID field will be populated

func (CloudIntegrations) CreateAwsExternalID

func (ci CloudIntegrations) CreateAwsExternalID() (string, error)

Creates an AWS ExternalID for use in AWS IAM Roles

func (CloudIntegrations) Delete

func (ci CloudIntegrations) Delete(cloudIntegration *CloudIntegration, skipTrash bool) error

Deletes a given CloudIntegration and sets the ID of the object to "" ID must be specified

func (CloudIntegrations) DeleteAwsExternalID

func (ci CloudIntegrations) DeleteAwsExternalID(externalId *string) error

Deletes an AWS ExternalID

func (CloudIntegrations) Find

func (ci CloudIntegrations) Find(filter []*SearchCondition) (
	results []*CloudIntegration, err error)

func (CloudIntegrations) Get

func (ci CloudIntegrations) Get(cloudIntegration *CloudIntegration) error

Get a CloudIntegration for a given ID ID must be specified

func (CloudIntegrations) Update

func (ci CloudIntegrations) Update(cloudIntegration *CloudIntegration) error

Updates a given CloudIntegration in Wavefront

func (CloudIntegrations) VerifyAwsExternalID

func (ci CloudIntegrations) VerifyAwsExternalID(externalId string) error

Verifies an AWS ExternalID exists

type CloudTrailConfiguration

type CloudTrailConfiguration struct {
	// The AWS Region of the S3 bucket where CloudTrail logs are stored
	Region string `json:"region"`

	// The common prefix, if any, appended to all CloudTrail log files
	Prefix string `json:"prefix,omitempty"`

	BaseCredentials *AWSBaseCredentials `json:"baseCredentials,omitempty"`

	// Name of the S3 bucket where CloudTrail logs are stored
	BucketName string `json:"bucketName"`

	// Rule to filter cloud trail log event
	FilterRule string `json:"filterRule,omitempty"`
}

type CloudWatchConfiguration

type CloudWatchConfiguration struct {
	// A regular expression that a CloudWatch metric name must match (case-insensitively) in order to be ingested
	MetricFilterRegex string `json:"metricFilterRegex,omitempty"`

	// A list of namespace that limit what we query from cloudwatch
	Namespaces []string `json:"namespaces,omitempty"`

	BaseCredentials *AWSBaseCredentials `json:"baseCredentials,omitempty"`

	// A string->string map of white list of AWS instance tag-value pairs (in AWS).
	// If the instance's AWS tags match this whitelist, CloudWatch data about this instance is ingested.
	// Multiple entries are OR'ed
	InstanceSelectionTags map[string]string `json:"instanceSelectionTags,omitempty"`

	// A string->string map of white list of AWS volume tag-value pairs (in AWS).
	// If the volume's AWS tags match this whitelist, CloudWatch data about this volume is ingested.
	// Multiple entries are OR'ed
	VolumeSelectionTags map[string]string `json:"volumeSelectionTags,omitempty"`

	// A regular expression that AWS tag key name must match (case-insensitively) in order to be ingested
	PointTagFilterRegex string `json:"pointTagFilterRegex,omitempty"`
}

type Config

type Config struct {
	// Address is the address of the Wavefront API, of the form
	// example.wavefront.com or http://localhost:8080.
	Address string

	// Token is an authentication token that will be passed with all requests
	Token string

	// SET HTTP Proxy configuration
	HttpProxy string

	// SkipTLSVerify disables SSL certificate checking and should be used for
	// testing only
	SkipTLSVerify bool
}

Config is used to hold configuration, used when constructing a Client

type Dashboard

type Dashboard struct {
	// Name is the name given to an Dashboard
	Name string `json:"name"`

	// ID is the Wavefront-assigned ID of an existing Dashboard
	ID string `json:"id"`

	// Tags are the tags applied to the Dashboard
	Tags []string `json:"-"`

	// Description is a description given to the Dashboard
	Description string `json:"description"`

	// Url is the relative url to access the dashboard by on a cluster
	Url string `json:"url"`

	// Sections is an array of Section that split up the dashboard
	Sections []Section `json:"sections"`

	// Access Control Lists for who can view or modify (user or group IDs)
	ACL AccessControlList `json:"acl"`

	// Additional dashboard settings
	ChartTitleBgColor             string `json:"chartTitleBgColor,omitempty"`
	ChartTitleColor               string `json:"chartTitleColor,omitempty"`
	ChartTitleScalar              int    `json:"chartTitleScalar,omitempty"`
	DefaultEndTime                int    `json:"defaultEndTime,omitempty"`
	DefaultStartTime              int    `json:"defaultStartTime,omitempty"`
	DefaultTimeWindow             string `json:"defaultTimeWindow"`
	DisplayDescription            bool   `json:"displayDescription"`
	DisplayQueryParameters        bool   `json:"displayQueryParameters"`
	DisplaySectionTableOfContents bool   `json:"displaySectionTableOfContents"`
	EventFilterType               string `json:"eventFilterType"`
	EventQuery                    string `json:"eventQuery"`
	Favorite                      bool   `json:"favorite"`

	// Additional dashboard information
	Customer           string `json:"customer,omitempty"`
	Deleted            bool   `json:"deleted,omitempty"`
	Hidden             bool   `json:"hidden,omitempty"`
	NumCharts          int    `json:"numCharts,omitempty"`
	NumFavorites       int    `json:"numFavorites,omitempty"`
	CreatorId          string `json:"creatorId,omitempty"`
	UpdaterId          string `json:"updaterId,omitempty"`
	SystemOwned        bool   `json:"systemOwned,omitempty"`
	ViewsLastDay       int    `json:"viewsLastDay,omitempty"`
	ViewsLastMonth     int    `json:"viewsLastMonth,omitempty"`
	ViewsLastWeek      int    `json:"viewsLastWeek,omitempty"`
	CreatedEpochMillis int64  `json:"createdEpochMillis,omitempty"`
	UpdatedEpochMillis int64  `json:"updatedEpochMillis,omitempty"`

	// Parameters (reserved - usage unknown at this time)
	Parameters struct{} `json:"parameters"`

	// ParameterDetails sets variables that can be used within queries
	ParameterDetails map[string]ParameterDetail `json:"parameterDetails"`
}

Dashboard represents a single Wavefront Dashboard

func (*Dashboard) MarshalJSON

func (d *Dashboard) MarshalJSON() ([]byte, error)

func (*Dashboard) UnmarshalJSON

func (d *Dashboard) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom JSON unmarshaller for a Dashboard, used to populate the Tags field in a more intuitive fashion

type Dashboards

type Dashboards struct {
	// contains filtered or unexported fields
}

Dashboards is used to perform Dashboard-related operations against the Wavefront API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

dashboards := client.Dashboards()

// Create the components of the Dashboard (Sections, Rows, Charts and Sources).

sources := []wavefront.Source{
	{
		Name:  "Source 1",
		Query: "ts()",
	},
}

charts := []wavefront.Chart{
	{
		Name:        "Chart 1",
		Description: "Chart 1 shows ...",
		Sources:     sources,
		Units:       "units per time",
	},
}

rows := []wavefront.Row{
	{
		Name:   "Row 1",
		Charts: charts,
	},
}

sections := []wavefront.Section{
	{
		Name: "Section 1",
		Rows: rows,
	},
}

params := map[string]wavefront.ParameterDetail{
	"param": {
		Label:                   "test",
		DefaultValue:            "Label",
		HideFromView:            false,
		ParameterType:           "SIMPLE",
		ValuesToReadableStrings: map[string]string{"Label": "test"},
	},
}

d := &wavefront.Dashboard{
	Name:             "My First Dashboard",
	ID:               "dashboard1",
	Description:      "A Dashboard to show things",
	Url:              "dashboard1",
	Sections:         sections,
	Tags:             []string{"dc1", "synergy"},
	ParameterDetails: params,
}

// Create the dashboard on Wavefront
err = dashboards.Create(d)
if err != nil {
	log.Fatal(err)
}

// We can update/delete the Dashboard
fmt.Println("dashboard ID is", d.ID)

// Alternatively we could search for the Dashboard
results, err := dashboards.Find(
	[]*wavefront.SearchCondition{
		{
			Key:            "name",
			Value:          "My First Dashboard",
			MatchingMethod: "EXACT",
		},
	})

if err != nil {
	log.Fatal(err)
}

fmt.Println("found dashboard with ID", results[0].ID)

// Update the Dashboard
d.Sections[0].Rows[0].Name = "Updated Chart Name"
err = dashboards.Update(d)
if err != nil {
	log.Fatal(err)
}

// Delete the Dashboard
err = dashboards.Delete(d, true)
if err != nil {
	log.Fatal(err)
}

fmt.Println("dashboard deleted")
Output:

func (Dashboards) Create

func (d Dashboards) Create(dashboard *Dashboard) error

Create is used to create an Dashboard in Wavefront. If successful, the ID field of the Dashboard will be populated.

func (Dashboards) Delete

func (d Dashboards) Delete(dashboard *Dashboard, skipTrash bool) error

Delete is used to delete an existing Dashboard. The ID field of the Dashboard must be populated

func (Dashboards) Find

func (d Dashboards) Find(filter []*SearchCondition) (
	results []*Dashboard, err error)

Find returns all Dashboards filtered by the given search conditions. If filter is nil, all Dashboards are returned.

func (Dashboards) Get

func (d Dashboards) Get(dashboard *Dashboard) error

Get is used to retrieve an existing Dashboard by ID. The ID field must be provided

func (Dashboards) SetACL

func (d Dashboards) SetACL(id string, canView, canModify []string) error

SetACL Sets the ACL on the dashboard with the supplied list of IDs for canView and canModify an empty []string on canView will remove all values set an empty []string on canModify will set the value to the owner of the token issuing the API call

func (Dashboards) SetTags

func (d Dashboards) SetTags(id string, tags []string) error

SetTags Set Tags is used to set the tags on an existing dashboard

func (Dashboards) Update

func (d Dashboards) Update(dashboard *Dashboard) error

Update is used to update an existing Dashboard. The ID field of the Dashboard must be populated

type DataPoint

type DataPoint []float64

DataPoint represents a single timestamp/value data point as returned by Wavefront

type DerivedMetric

type DerivedMetric struct {
	ID                       *string  `json:"id,omitempty"`
	Name                     string   `json:"name,omitempty"`
	Query                    string   `json:"query,omitempty"`
	Minutes                  int      `json:"minutes,omitempty"`
	Tags                     WFTags   `json:"tags,omitempty"`
	Status                   []string `json:"status,omitempty"`
	InTrash                  bool     `json:"inTrash,omitempty"`
	QueryFailing             bool     `json:"queryFailing,omitempty"`
	LastFailedTime           int      `json:"lastFailedTime,omitempty"`
	LastErrorMessage         string   `json:"lastErrorMessage,omitempty"`
	AdditionalInformation    string   `json:"additionalInformation,omitempty"`
	HostsUsed                []string `json:"hostsUsed,omitempty"`
	UpdateUserId             string   `json:"updateUserId,omitempty"`
	CreateUserId             string   `json:"createUserId,omitempty"`
	LastProcessedMillis      int      `json:"lastProcessedMillis,omitempty"`
	ProcessRateMinutes       int      `json:"processRateMinutes,omitempty"`
	PointsScannedAtLastQuery int      `json:"pointsScannedAtLastQuery,omitempty"`
	IncludeObsoleteMetrics   bool     `json:"includeObsoleteMetrics,omitempty"`
	LastQueryTime            int      `json:"lastQueryTime,omitempty"`
	MetricsUsed              []string `json:"metricsUsed,omitempty"`
	QueryQBEnabled           bool     `json:"queryQBEnabled,omitempty"`
	UpdatedEpochMillis       int      `json:"updatedEpochMillis,omitempty"`
	CreatedEpochMillis       int      `json:"createdEpochMillis,omitempty"`
	Deleted                  bool     `json:"deleted,omitempty"`
}

type DerivedMetrics

type DerivedMetrics struct {
	// contains filtered or unexported fields
}
Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

derivedMetrics := client.DerivedMetrics()

dm := &wavefront.DerivedMetric{
	Name:    "Some Derived Metric",
	Query:   "ts(someQuery)",
	Minutes: 5,
	Tags: wavefront.WFTags{
		CustomerTags: []string{"prod"},
	},
}

// Create the DerivedMetric on Wavefront
err = derivedMetrics.Create(dm)
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete the DerivedMetric
fmt.Println("derived metric ID is", *dm.ID)

// Change to 10 minutes
dm.Minutes = 10

// Update the DerivedMetric
err = derivedMetrics.Update(dm)
if err != nil {
	log.Fatal(err)
}

time.Sleep(time.Second * 60)

// Delete the DerivedMetric
err = derivedMetrics.Delete(dm, true)
if err != nil {
	log.Fatal(err)
}

fmt.Println("derived metric deleted")
Output:

func (DerivedMetrics) Create

func (dm DerivedMetrics) Create(metric *DerivedMetric) error

Create a DerivedMetric, name, query, and minutes are required

func (DerivedMetrics) Delete

func (dm DerivedMetrics) Delete(metric *DerivedMetric, skipTrash bool) error

Delete a DerivedMetric all fields are optional except for ID

func (DerivedMetrics) Find

func (dm DerivedMetrics) Find(filter []*SearchCondition) (
	results []*DerivedMetric, err error)

Find returns all DerivedMetrics filtered by the given search conditions. If filter is nil, all DerivedMetrics are returned.

func (DerivedMetrics) Get

func (dm DerivedMetrics) Get(metric *DerivedMetric) error

Get is used to retrieve an existing DerivedMetric by ID. The ID field must be specified

func (DerivedMetrics) Update

func (dm DerivedMetrics) Update(metric *DerivedMetric) error

Update a DerivedMetric all fields are optional except for ID

type EC2Configuration

type EC2Configuration struct {
	BaseCredentials *AWSBaseCredentials `json:"baseCredentials,omitempty"`

	// A list of AWS instance tags that, when found, will be used as the "source" name in a series.
	// Default: hostname, host, name
	// If no tag in this list is found, the series source is set to the instance id.
	HostNameTags []string `json:"hostNameTags"`
}

type Event

type Event struct {
	// Name is the name given to the Event
	Name string `json:"name"`

	// ID is the Wavefront-assigned ID of an existing Event
	ID *string `json:"id,omitempty"`

	// StartTime is the start time, in epoch milliseconds, of the Event.
	// If zero, it will be set to current time
	StartTime int64 `json:"startTime"`

	// EndTime is the end time, in epoch milliseconds, of the Event
	EndTime int64 `json:"endTime,omitempty"`

	// Tags are the tags associated with the Event
	Tags []string `json:"tags"`

	// Severity is the severity category of the Event, can be INFO, WARN,
	// SEVERE or UNCLASSIFIED
	Severity string

	// Type is the type of the Event, e.g. "Alert", "Deploy" etc.
	Type string

	// Details is a description of the Event
	Details string

	// Instantaneous, if true, creates a point-in-time Event (i.e. with no duration)
	Instantaneous bool `json:"isEphemeral"`

	// Annotations on the event
	Annotations map[string]string `json:"annotations"`
}

Event represents a single Wavefront Event

func (*Event) MarshalJSON

func (e *Event) MarshalJSON() ([]byte, error)

func (*Event) UnmarshalJSON

func (e *Event) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom JSON unmarshaller for an Event, used to explode the annotations.

type Events

type Events struct {
	// contains filtered or unexported fields
}

Events is used to perform event-related operations against the Wavefront API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

events := client.Events()

e := &wavefront.Event{
	Name:    "Deploying Stuff",
	Type:    "deployment",
	Details: "Stuff being deployed.",
	Tags:    []string{"prod"},
}

// Create the event on Wavefront
err = events.Create(e)
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete/close the Event
fmt.Println("event ID is", *e.ID)

// Close the Event
err = events.Close(e)
if err != nil {
	log.Fatal(err)
}

time.Sleep(time.Second * 60)

// Delete the Event
err = events.Delete(e)
if err != nil {
	log.Fatal(err)
}

fmt.Println("event deleted")
Output:

func (Events) Close

func (e Events) Close(event *Event) error

Close is used to close an existing Event

func (Events) Create

func (e Events) Create(event *Event) error

Create is used to create an Event in Wavefront. If successful, the ID field of the event will be populated.

func (Events) Delete

func (e Events) Delete(event *Event) error

Delete is used to delete an existing Event. The ID field of the Event must be populated

func (Events) Find

func (e Events) Find(filter []*SearchCondition, timeRange *TimeRange) ([]*Event, error)

Find returns all events filtered by the given search conditions. If filter is nil then all Events are returned. The result set is limited to the first 100 entries. If more results are required the Search type can be used directly.

func (Events) FindByID

func (e Events) FindByID(id string) (*Event, error)

FindByID returns the Event with the Wavefront-assigned ID. If not found an error is returned

func (Events) Update

func (e Events) Update(event *Event) error

Update is used to update an existing Event. The ID field of the Event must be populated

type ExternalLink struct {
	ID                    *string           `json:"id,omitempty"`
	Name                  string            `json:"name"`
	Description           string            `json:"description"`
	CreatorId             string            `json:"creatorId,omitempty"`
	UpdaterId             string            `json:"updaterId,omitempty"`
	UpdatedEpochMillis    int               `json:"updatedEpochMillis,omitempty"`
	CreatedEpochMillis    int               `json:"createdEpochMillis,omitempty"`
	Template              string            `json:"template"`
	MetricFilterRegex     string            `json:"metricFilterRegex,omitempty"`
	SourceFilterRegex     string            `json:"sourceFilterRegex,omitempty"`
	PointTagFilterRegexes map[string]string `json:"pointTagFilterRegexes,omitempty"`
	IsLogIntegration      bool              `json:"isLogIntegration,omitempty"`
}
type ExternalLinks struct {
	// contains filtered or unexported fields
}

func (ExternalLinks) Create

func (e ExternalLinks) Create(link *ExternalLink) error

func (ExternalLinks) Delete

func (e ExternalLinks) Delete(link *ExternalLink) error

func (ExternalLinks) Find

func (e ExternalLinks) Find(conditions []*SearchCondition) (
	results []*ExternalLink, err error)

func (ExternalLinks) Get

func (e ExternalLinks) Get(link *ExternalLink) error

func (ExternalLinks) Update

func (e ExternalLinks) Update(link *ExternalLink) error

type GCPBillingConfiguration

type GCPBillingConfiguration struct {
	// The Google Cloud Platform (GCP) project id.
	ProjectId string `json:"projectId"`

	// API key for Google Cloud Platform (GCP). Use 'saved_api_key' to retain existing API key when updating
	GcpApiKey string `json:"gcpApiKey"`

	// Private key for a Google Cloud Platform (GCP) service account within your project. The account must at least be
	// granted Monitoring Viewer permissions.  This key must be in the JSON format generated by GCP.
	// Use `{"project_id":"%s"}' to retain the existing key when updating
	GcpJSONKey string `json:"gcpJsonKey"`
}

type GCPConfiguration

type GCPConfiguration struct {
	// A regular expression that a CloudWatch metric name must match (case-insensitively) in order to be ingested
	MetricFilterRegex string `json:"metricFilterRegex,omitempty"`

	// The Google Cloud Platform (GCP) project id.
	ProjectId string `json:"projectId"`

	// Private key for a Google Cloud Platform (GCP) service account within your project. The account must at least be
	// granted Monitoring Viewer permissions.  This key must be in the JSON format generated by GCP.
	// Use `{"project_id":"%s"}' to retain the existing key when updating
	GcpJSONKey string `json:"gcpJsonKey"`

	// A list of Google Cloud Platform (GCP) services (Such as ComputeEngine, PUbSub...etc) from which to pull metrics.
	CategoriesToFetch []string `json:"categoriesToFetch,omitempty"`
}

type IngestionPolicies

type IngestionPolicies struct {
	// contains filtered or unexported fields
}
Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}

client, err := wavefront.NewClient(config)

if err != nil {
	log.Fatal(err)
}

ingestionPolicies := client.IngestionPolicies()

policyRequest := &wavefront.IngestionPolicyRequest{
	Name:        "test ingestion policy",
	Description: "an ingestion policy created by the Go SDK test suite",
	Scope:       "ACCOUNT",
	Accounts:    []string{"user@example.com"},
}

ingestionPolicy, err := ingestionPolicies.Create(policyRequest)

if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete the policy
fmt.Println("policy ID is", ingestionPolicy.ID)

ingestionPolicy, err = ingestionPolicies.GetByID(ingestionPolicy.ID)

if err != nil {
	log.Fatal(err)
}

// Change the description
ingestionPolicy.Description = "an ingestion policy updated by the Go SDK test suite"

err = ingestionPolicies.Update(ingestionPolicy)

if err != nil {
	log.Fatal(err)
}

time.Sleep(time.Second * 60)

err = ingestionPolicies.DeleteByID(ingestionPolicy.ID)

if err != nil {
	log.Fatal(err)
}

fmt.Println("policy deleted")
Output:

func (*IngestionPolicies) Create

func (*IngestionPolicies) DeleteByID

func (p *IngestionPolicies) DeleteByID(policyID string) error

func (*IngestionPolicies) Find

func (p *IngestionPolicies) Find(conditions []*SearchCondition) (results []*IngestionPolicyResponse, err error)

func (*IngestionPolicies) GetByID

func (p *IngestionPolicies) GetByID(policyID string) (*IngestionPolicyResponse, error)

func (*IngestionPolicies) Update

func (p *IngestionPolicies) Update(policy *IngestionPolicyResponse) error

type IngestionPolicyAccount

type IngestionPolicyAccount struct {
	Name string `json:"name,omitempty"`
	ID   string `json:"id,omitempty"`
}

type IngestionPolicyGroup

type IngestionPolicyGroup struct {
	Name        string `json:"name,omitempty"`
	ID          string `json:"id,omitempty"`
	Description string `json:"description,omitempty"`
}

type IngestionPolicyRequest

type IngestionPolicyRequest struct {
	ID          string   `json:"id,omitempty"`
	Name        string   `json:"name,omitempty"`
	Description string   `json:"description,omitempty"`
	Scope       string   `json:"scope,omitempty"`
	Accounts    []string `json:"accounts,omitempty"`
	Groups      []string `json:"groups,omitempty"`
	Sources     []string `json:"sources,omitempty"`
	Namespaces  []string `json:"namespaces,omitempty"`
	// This is a slice of maps because you may have different values with the same key
	// and also there is potentially an AND or OR operation assigned to them.
	Tags []map[string]string `json:"pointTags,omitempty"`
}

type IngestionPolicyResponse

type IngestionPolicyResponse struct {
	ID          string                   `json:"id,omitempty"`
	Name        string                   `json:"name,omitempty"`
	Description string                   `json:"description,omitempty"`
	Scope       string                   `json:"scope,omitempty"`
	Accounts    []IngestionPolicyAccount `json:"accounts,omitempty"`
	Groups      []IngestionPolicyGroup   `json:"groups,omitempty"`
	Sources     []string                 `json:"sources,omitempty"`
	Namespaces  []string                 `json:"namespaces,omitempty"`
	Tags        []IngestionPolicyTag     `json:"pointTags,omitempty"`
}

type IngestionPolicyTag

type IngestionPolicyTag struct {
	Key   string `json:"key,omitempty"`
	Value string `json:"value,omitempty"`
}

type MaintenanceWindow

type MaintenanceWindow struct {
	ID                              string   `json:"id"`
	RunningState                    string   `json:"runningState"`
	SortAttr                        int      `json:"sortAttr"`
	Reason                          string   `json:"reason"`
	CustomerId                      string   `json:"customerId"`
	RelevantCustomerTags            []string `json:"relevantCustomerTags"`
	Title                           string   `json:"title"`
	StartTimeInSeconds              int64    `json:"startTimeInSeconds"`
	EndTimeInSeconds                int64    `json:"endTimeInSeconds"`
	RelevantHostTags                []string `json:"relevantHostTags"`
	RelevantHostNames               []string `json:"relevantHostNames"`
	CreatorId                       string   `json:"creatorId"`
	UpdaterId                       string   `json:"updaterId"`
	CreatedEpochMillis              int64    `json:"createdEpochMillis"`
	UpdatedEpochMillis              int64    `json:"updatedEpochMillis"`
	RelevantHostTagsAnded           bool     `json:"relevantHostTagsAnded"`
	HostTagGroupHostNamesGroupAnded bool     `json:"hostTagGroupHostNamesGroupAnded"`
	EventName                       string   `json:"eventName"`
}

MaintenanceWindow represents a maintenance window in Wavefront

func (*MaintenanceWindow) Options

Options returns the current options for this maintenance window

type MaintenanceWindowOptions

type MaintenanceWindowOptions struct {
	// Required. The reason for the maintenance window.
	Reason string `json:"reason,omitempty"`

	// Required. The title of the maintenance window.
	Title string `json:"title,omitempty"`

	// Required. The start time of the maintenance window in seconds since 1 Jan 1970
	StartTimeInSeconds int64 `json:"startTimeInSeconds,omitempty"`

	// Required. The end time of the maintenance window in seconds since 1 Jan 1970
	EndTimeInSeconds int64 `json:"endTimeInSeconds,omitempty"`

	RelevantCustomerTags []string `json:"relevantCustomerTags"`
	RelevantHostTags     []string `json:"relevantHostTags,omitempty"`
	RelevantHostNames    []string `json:"relevantHostNames,omitempty"`

	RelevantHostTagsAnded           bool `json:"relevantHostTagsAnded,omitempty"`
	HostTagGroupHostNamesGroupAnded bool `json:"hostTagGroupHostNamesGroupAnded,omitempty"`
}

MaintenanceWindowOptions represents the configurable options for a maintenance window.

type MaintenanceWindows

type MaintenanceWindows struct {
	// contains filtered or unexported fields
}

MaintenanceWindows is used to perform maintenance window related operations against the Wavefront API

func (*MaintenanceWindows) Create

func (m *MaintenanceWindows) Create(options *MaintenanceWindowOptions) (
	maintenanceWindow *MaintenanceWindow, err error)

Create creates a MaintenanceWindow according to options and returns the newly created MaintenanceWindow.

func (*MaintenanceWindows) DeleteByID

func (m *MaintenanceWindows) DeleteByID(id string) error

DeleteByID deletes the MaintenanceWindow with given id.

func (*MaintenanceWindows) Find

func (m *MaintenanceWindows) Find(filter []*SearchCondition) (
	results []*MaintenanceWindow, err error)

Find returns all maintenance windows filtered by the given search conditions. If filter is nil, all maintenance windows are returned.

func (*MaintenanceWindows) GetByID

func (m *MaintenanceWindows) GetByID(id string) (
	maintenanceWindow *MaintenanceWindow, err error)

GetByID returns the MaintenanceWindow with given ID. If no such MaintenanceWindow exists, GetByID returns an error. The caller can call NotFound on err to determine whether the error is because the MaintenanceWindow doesn't exist.

func (*MaintenanceWindows) Update

func (m *MaintenanceWindows) Update(
	id string, options *MaintenanceWindowOptions) (
	maintenanceWindow *MaintenanceWindow, err error)

Update updates a MaintenanceWindow according to options and returns the updated MaintenanceWindow.

type MetricsPolicy

type MetricsPolicy struct {
	PolicyRules        []PolicyRule `json:"policyRules,omitempty"`
	Customer           string       `json:"customer,omitempty"`
	UpdaterId          string       `json:"updaterId,omitempty"`
	UpdatedEpochMillis int          `json:"updatedEpochMillis,omitempty"`
}

MetricsPolicy represents the global metrics policy for a given Wavefront domain

type MetricsPolicyAPI

type MetricsPolicyAPI struct {
	// contains filtered or unexported fields
}

MetricsPolicyAPI is used to perform MetricsPolicy-related operations against the Wavefront API

func (*MetricsPolicyAPI) Get

func (m *MetricsPolicyAPI) Get() (*MetricsPolicy, error)

func (*MetricsPolicyAPI) Update

func (m *MetricsPolicyAPI) Update(policyRules *UpdateMetricsPolicyRequest) (*MetricsPolicy, error)

type NewRelicConfiguration

type NewRelicConfiguration struct {
	// New Relic REST API Key
	ApiKey string `json:"apiKey"`

	// A regular expression that a application name must match (case-insensitively) in order to collect metrics
	AppFilterRegex string `json:"appFilterRegex,omitempty"`

	// A regular expression that a host name must match (case-insensitively) in order to collect metrics
	HostFilterRegex string `json:"hostFilterRegex,omitempty"`

	NewRelicMetricFilters []*NewRelicMetricFilters `json:"newRelicMetricFilters,omitempty"`
}

type NewRelicMetricFilters

type NewRelicMetricFilters struct {
	AppName           string `json:"appName"`
	MetricFilterRegex string `json:"metricFilterRegex"`
}

type NewUserRequest

type NewUserRequest struct {
	// The only time it is referred to as emailAddress is when it's a new user
	EmailAddress string `json:"emailAddress"`

	// The permissions granted to this user
	Permissions []string `json:"groups,omitempty"`

	// Groups this user belongs to
	// This is wrapped with a Wrapper to manage the serialization between what we send to the API
	// And what the API sends back (which is to say, we send just IDs but we always receive a complete object)
	Groups UserGroupsWrapper `json:"userGroups,omitempty"`
}

type ParameterDetail

type ParameterDetail struct {
	// Label represents the name of the variable
	Label string `json:"label"`

	// DefaultValue maps to keys in the map ValuesToReadableStrings
	DefaultValue string `json:"defaultValue"`

	// HideFromView Whether to hide from the view of the user viewing the Dashboard
	HideFromView bool `json:"hideFromView"`

	// ParameterType (SIMPLE, LIST, DYNAMIC)
	ParameterType string `json:"parameterType"`

	// ValuesToReadableStrings
	ValuesToReadableStrings map[string]string `json:"valuesToReadableStrings"`

	// QueryValue
	QueryValue string `json:"queryValue,omitempty"`

	// TagKey Only required for a DynamicFieldType of TAG_KEY
	TagKey string `json:"tagKey,omitempty"`

	// DynamicFieldType (TAG_KEY, MATCHING_SOURCE_TAG, SOURCE_TAG, SOURCE, METRIC_NAME)
	// Only required for a Parameter type of Dynamic.
	DynamicFieldType string `json:"dynamicFieldType,omitempty"`
}

ParameterDetail represents a parameter to dashboard that can be consumed in queries

type PolicyRule

type PolicyRule struct {
	Accounts    []PolicyUser      `json:"accounts,omitempty"`
	UserGroups  []PolicyUserGroup `json:"userGroups,omitempty"`
	Roles       []Role            `json:"roles,omitempty"`
	Name        string            `json:"name,omitempty"`
	Tags        []PolicyTag       `json:"tags,omitempty"`
	Description string            `json:"description,omitempty"`
	Prefixes    []string          `json:"prefixes,omitempty"`
	TagsAnded   bool              `json:"tagsAnded,omitempty"`
	AccessType  string            `json:"accessType,omitempty"`
}

type PolicyRuleRequest

type PolicyRuleRequest struct {
	AccountIds   []string    `json:"accounts,omitempty"`
	UserGroupIds []string    `json:"userGroups,omitempty"`
	RoleIds      []string    `json:"roles,omitempty"`
	Name         string      `json:"name,omitempty"`
	Tags         []PolicyTag `json:"tags,omitempty"`
	Description  string      `json:"description,omitempty"`
	Prefixes     []string    `json:"prefixes,omitempty"`
	TagsAnded    bool        `json:"tagsAnded,omitempty"`
	AccessType   string      `json:"accessType,omitempty"`
}

type PolicyTag

type PolicyTag struct {
	Key   string `json:"key,omitempty"`
	Value string `json:"value,omitempty"`
}

type PolicyUser

type PolicyUser struct {
	// Unique ID for the user
	ID string `json:"id,omitempty"`
	// Name of the user
	Name string `json:"name,omitempty"`
}

type PolicyUserGroup

type PolicyUserGroup struct {
	// Unique ID for the user group
	ID string `json:"id,omitempty"`
	// Name of the user group
	Name string `json:"name,omitempty"`
	// Description of the Group purpose
	Description string `json:"description,omitempty"`
}

type Query

type Query struct {

	// Params is the set of parameters that will be used when executing the Query
	Params *QueryParams

	// Response will be the response of the last executed Query
	Response *QueryResponse
	// contains filtered or unexported fields
}

Query represents a query to be made against the Charts API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

// enable debug - all requests get dumped to stdout before being executed
client.Debug(true)

// NewQueryParams generates a query using the given ts expression.
// By default the query period will be one hour since the current time.
query := client.NewQuery(wavefront.NewQueryParams(
	`ts("cpu.load.1m.avg", dc=dc1)`,
))

// Set the query period to be one day instead of one hour
err = query.SetStartTime(24 * 60 * 60)
if err != nil {
	log.Fatal(err)
}

// Execute carries out the query
result, err := query.Execute()
if err != nil {
	log.Fatal(err)
}

// The raw JSON response is available as RawResponse.
// This can be useful for debugging
b, _ := io.ReadAll(result.RawResponse)
fmt.Println(string(b))

// The timeseries response can now be used to explore the results
fmt.Println(result.TimeSeries[0].Label)
fmt.Println(result.TimeSeries[0].DataPoints[0])
Output:

func (*Query) Execute

func (q *Query) Execute() (*QueryResponse, error)

Execute is used to execute a query against the Wavefront Chart API

func (*Query) SetEndTime

func (q *Query) SetEndTime(endTime time.Time)

SetEndTime sets the time at which the query should end

func (*Query) SetStartTime

func (q *Query) SetStartTime(seconds int64) error

SetStartTime sets the time from which to query for points. 'seconds' is the number of seconds before the end-time that the query will be inclusive of. EndTime must be set before calling this function. Some constants are provided for convenience: LastHour, Last3Hours, LastDay etc.

type QueryParams

type QueryParams struct {
	// Name is an optional name to identify the query
	Name string `query:"n"`

	// QueryString is the actual timeseries query to be executed
	QueryString string `query:"q"`

	// StartTime is the start time for the query in epoch milliseconds
	StartTime string `query:"s"`

	// EndTime is the end time for the query in epoch milliseconds
	EndTime string `query:"e"`

	// Granularity is the granularity of the points returned, and can be one of
	// d,h,m or s
	Granularity string `query:"g"`

	// MaxPoints is the maximum number of points to return
	MaxPoints string `query:"p"`

	// SeriesOutsideTimeWindow is a boolean to indicate whether series with only
	// points that are outside  of the query window will be returned
	SeriesOutsideTimeWindow bool `query:"i"`

	// AutoEvents is a boolean to indicate whether to return Events for sources
	// included in the query
	AutoEvents bool `query:"autoEvents"`

	// SummarizationStrategy is the strategy to be used when grouping points together.
	// Valid values are MEAN, MEDIAN, MIN, MAX, SUN, COUNT, LAST, FIRST
	SummarizationStrategy string `query:"summarization"`

	// ListMode is a boolean to indicate whether to retrieve events more optimally
	// displayed for a list.
	ListMode bool `query:"listmode"`

	// StrictMode is a boolean which, if true, will not return points outside of the
	// query window. Defaults to false if ommitted.
	StrictMode bool `query:"strict"`

	// IncludeObsoleteMetrics is a boolean to indicate whether to return points from
	// sources which have stopped reporting. Defaults to false if ommitted.
	IncludeObsoleteMetrics bool `query:"includeObsoleteMetrics"`
}

QueryParams represents parameters that will be passed when making a Query

func NewQueryParams

func NewQueryParams(query string) *QueryParams

NewQueryParams takes a query string and returns a set of QueryParams with a query window of one hour since now and a set of sensible default values

func NewQueryParamsNoStrict

func NewQueryParamsNoStrict(query string) *QueryParams

type QueryResponse

type QueryResponse struct {
	RawResponse *bytes.Reader
	TimeSeries  []TimeSeries   `json:"timeseries"`
	Query       string         `json:"query"`
	Stats       map[string]int `json:"stats"`
	Name        string         `json:"name"`
	Granularity int            `json:"granularity"`
	Hosts       []string       `json:"hostsUsed"`
	Warnings    string         `json:"warnings"`

	// ErrType : ref https://code.vmware.com/apis/714/wavefront-rest#/Query/queryApi
	ErrType string `json:"errorType"`

	// ErrMessage : ref https://code.vmware.com/apis/714/wavefront-rest#/Query/queryApi
	ErrMessage string `json:"errorMessage"`
}

QueryResponse is used to represent a Wavefront query response

func (QueryResponse) String

func (qr QueryResponse) String() string

String outputs the time-series of a QueryResponse object in a human-readable format

func (*QueryResponse) UnmarshalJSON

func (qr *QueryResponse) UnmarshalJSON(data []byte) error

type Role

type Role struct {
	ID                   string       `json:"id"`
	CreatedEpochMillis   int          `json:"createdEpochMillis,omitempty"`
	LastUpdatedMs        int          `json:"lastUpdatedMs,omitempty"`
	SampleLinkedGroups   *[]UserGroup `json:"sampleLinkedGroups,omitempty"`
	SampleLinkedAccounts *[]string    `json:"sampleLinkedAccounts,omitempty"`
	LinkedGroupsCount    int          `json:"linkedGroupsCount,omitempty"`
	LinkedAccountsCount  int          `json:"linkedAccountsCount,omitempty"`
	Customer             string       `json:"customer,omitempty"`
	LastUpdatedAccountId string       `json:"lastUpdatedAccountId,omitempty"`
	Name                 string       `json:"name"`
	Permissions          []string     `json:"permissions,omitempty"`
	Description          string       `json:"description,omitempty"`
}

type Roles

type Roles struct {
	// contains filtered or unexported fields
}
Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)

if err != nil {
	log.Fatal(err)
}

client.Debug(true)

roles := client.Roles()

role := wavefront.Role{
	Name: "test role",
	Permissions: []string{
		wavefront.AGENT_MANAGEMENT,
		wavefront.ALERTS_MANAGEMENT,
		wavefront.DASHBOARD_MANAGEMENT,
	},
	Description: "testing something",
}

// Create the role on Wavefront
err = roles.Create(&role)
if err != nil {
	log.Fatal(err)
}

/**
The following Add/Remove Assignees will return an error if the assignee does not exist in wavefront
An assignee is either a UserGroup or User
*/
// Add an assignee
err = roles.AddAssignees([]string{"user@example.com"}, &role)
if err != nil {
	log.Fatal(err)
}
// Remove an assignee
err = roles.RemoveAssignees([]string{"user@example.com"}, &role)
if err != nil {
	log.Fatal(err)
}
// Revoke a permission
err = roles.RevokePermission(wavefront.ALERTS_MANAGEMENT, []*wavefront.Role{&role})
if err != nil {
	log.Fatal(err)
}
// Grant a permission
err = roles.GrantPermission(wavefront.EVENTS_MANAGEMENT, []*wavefront.Role{&role})
if err != nil {
	log.Fatal(err)
}
// Get an target by ID
err = roles.Get(&wavefront.Role{ID: role.ID})
if err != nil {
	log.Fatal(err)
}
// The ID field is now set, so we can update or delete the Target
role.Description = "new description"
err = roles.Update(&role)
if err != nil {
	log.Fatal(err)
}
err = roles.Delete(&role)
if err != nil {
	log.Fatal(err)
}
Output:

func (Roles) AddAssignees

func (r Roles) AddAssignees(assignees []string, role *Role) error

func (Roles) Create

func (r Roles) Create(role *Role) error

func (Roles) Delete

func (r Roles) Delete(role *Role) error

func (Roles) Find

func (r Roles) Find(filter []*SearchCondition) (roles []*Role, err error)

func (Roles) Get

func (r Roles) Get(role *Role) error

Get a specific Role for the given ID ID field must be specified

func (Roles) GrantPermission

func (r Roles) GrantPermission(permission string, roles []*Role) error

func (Roles) RemoveAssignees

func (r Roles) RemoveAssignees(assignees []string, role *Role) error

func (Roles) RevokePermission

func (r Roles) RevokePermission(permission string, roles []*Role) error

func (Roles) Update

func (r Roles) Update(role *Role) error

Update a specific Role for the given ID ID field must be specified

type Row

type Row struct {
	// Name represents the display name of the Row
	Name string `json:"name"`

	// HeightFactor sets the height of the Row
	HeightFactor int `json:"heightFactor"`

	// Charts is an array of Chart that this row contains
	Charts []Chart `json:"charts"`
}

Row represents a single Row withing a Section of a Wavefront Dashboard

type Search struct {

	// Type is the type of entity to be searched for (i.e. alert, event, dashboard,
	// extlink, cloudintegration etc.)
	Type string

	// Params are the Search parameters to be applied
	Params *SearchParams

	// Deleted is whether to search against the /{entity}/deleted endpoint (for
	// deleted items) instead of the normal one. Defaults to false.
	Deleted bool
	// contains filtered or unexported fields
}

Search represents a search to be made against the Search API

func (*Search) Execute

func (s *Search) Execute() (*SearchResponse, error)

Execute is used to carry out a search

type SearchCondition

type SearchCondition struct {
	// Key is the type of parameter to be matched (e.g. tags, status, id)
	Key string `json:"key"`

	// Value is the value of Key to be searched for (e.g. the tag name, or snoozed)
	Value string `json:"value"`

	// MatchingMethod must be one of CONTAINS, STARTSWITH, EXACT, TAGPATH
	MatchingMethod string `json:"matchingMethod"`
}

SearchCondition represents a single search condition. Multiple conditions can be applied to one search, they will act as a logical AND.

type SearchParams

type SearchParams struct {
	// Conditions are the search conditions to be matched.
	// If multiple are given they will act like a logical AND
	Conditions []*SearchCondition `json:"query"`

	// Limit is the max number of results to be returned. Defaults to 100.
	Limit int `json:"limit"`

	// Offset is the offset from the first result to be returned.
	// For instance, an Offset of 100 will yield results 101 - 200
	// (assuming a Limit of 100). Defaults to 0.
	Offset int `json:"offset"`

	// TimeRange is the range between which results will be searched.
	// This is only valid for certain search types (e.g. Events)
	TimeRange *TimeRange `json:"timeRange,omitempty"`
}

SearchParams represents paramaters used to effect a Search. If multiple search terms are given they will act like a logical AND. If Conditions is nil, all items of the given Type will be returned

type SearchResponse

type SearchResponse struct {
	// RawResponse is the raw JSON response returned by Wavefront from a Search
	// operation
	RawResponse *bytes.Reader

	// Response is the response body of a Search operation
	Response struct {
		// Items will be the Wavefront entities returned by a successful search
		// operation (i.e. the Alerts, or Dashboards etc.)
		Items json.RawMessage

		// MoreResults indicates whether there are further items to be returned in a
		// paginated response.
		MoreItems bool `json:"moreItems"`
	} `json:"response"`

	// NextOffset is the offset that should be used to retrieve the next page of
	// results in a paginated response. If there are no more results, it will be zero.
	NextOffset int
}

SearchResponse represents the result of a successful search operation

type Section

type Section struct {
	// Name is the name given to this section
	Name string `json:"name"`

	// Rows is an array of Rows in this section
	Rows []Row `json:"rows"`
}

Section Represents a Single section within a Dashboard

type ServiceAccount

type ServiceAccount struct {
	ID              string                  `json:"identifier"`
	Description     string                  `json:"description"`
	Permissions     []string                `json:"groups"`
	Active          bool                    `json:"active"`
	Roles           []Role                  `json:"roles"`
	UserGroups      []UserGroup             `json:"userGroups"`
	Tokens          []Token                 `json:"tokens"`
	IngestionPolicy IngestionPolicyResponse `json:"ingestionPolicy"`
}

ServiceAccount represents a ServiceAccount which exists in Wavefront. Note that here, roles, groups, tokens and the ingestion policy are embedded structs.

func (*ServiceAccount) IngestionPolicyId

func (s *ServiceAccount) IngestionPolicyId() string

IngestionPolicyId returns the Id of the ingestion policy in this instance

func (*ServiceAccount) Options

func (s *ServiceAccount) Options() *ServiceAccountOptions

Options returns a ServiceAccountOptions prepopulated with the settings from this instance. Use this to update a ServiceAccount.

func (*ServiceAccount) RoleIds

func (s *ServiceAccount) RoleIds() []string

RoleIds returns the Ids of the Roles in this instance

func (*ServiceAccount) TokenIds

func (s *ServiceAccount) TokenIds() []string

TokenIds returns the Ids of the tokens in this instance.

func (*ServiceAccount) UserGroupIds

func (s *ServiceAccount) UserGroupIds() []string

UserGroupIds returns the Ids of the UserGroups in this instance

type ServiceAccountOptions

type ServiceAccountOptions struct {

	// Required
	ID string `json:"identifier"`

	// Required
	Active bool `json:"active"`

	// Always leave empty for now.
	Tokens []string `json:"tokens"`

	Description       string   `json:"description,omitempty"`
	Permissions       []string `json:"groups,omitempty"`
	Roles             []string `json:"roles,omitempty"`
	UserGroups        []string `json:"userGroups,omitempty"`
	IngestionPolicyID string   `json:"ingestionPolicyId,omitempty"`
}

ServiceAccountOptions represents the options for creating or updating a ServiceAccount in Wavefront. Note that here, Roles, UserGroups and the ingestion policy are the IDs of existing objects.

type ServiceAccounts

type ServiceAccounts struct {
	// contains filtered or unexported fields
}

ServiceAccounts is used to perform service account related operations against the Wavefront API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}

wfClient, err := wavefront.NewClient(config)

if err != nil {
	log.Fatal(err)
}

client := wfClient.ServiceAccounts()

opts := &wavefront.ServiceAccountOptions{
	ID:                "sa::example",
	Description:       "an example service account",
	IngestionPolicyID: "example-policy-1579802191862",
}

obj, err := client.Create(opts)

if err != nil {
	log.Fatal(err)
}

fmt.Printf("ID is '%s' and description is '%s'.\n", obj.ID, obj.Description)
time.Sleep(time.Second * 10)

opts.Description = "a brand new description"
obj, err = client.Update(opts)

if err != nil {
	log.Fatal(err)
}

fmt.Printf("ID is '%s' and description is now '%s'.\n", obj.ID, obj.Description)
time.Sleep(time.Second * 10)

err = client.DeleteByID(obj.ID)

if err != nil {
	log.Fatal(err)
}

fmt.Println("Object deleted.")
Output:

func (*ServiceAccounts) Create

func (s *ServiceAccounts) Create(options *ServiceAccountOptions) (
	serviceAccount *ServiceAccount, err error)

Create creates a ServiceAccount according to options and returns the newly created ServiceAccount.

func (*ServiceAccounts) DeleteByID

func (s *ServiceAccounts) DeleteByID(id string) error

DeleteById deletes the ServiceAccount with given id.

func (*ServiceAccounts) Find

func (s *ServiceAccounts) Find(filter []*SearchCondition) (
	results []*ServiceAccount, err error)

Find returns all service accounts filtered by the given search conditions. If filter is nil, all service accounts are returned.

func (*ServiceAccounts) GetByID

func (s *ServiceAccounts) GetByID(id string) (
	serviceAccount *ServiceAccount, err error)

GetByID returns the ServiceAccount with given ID. If no such ServiceAccount exists, GetByID returns an error. The caller can call NotFound on err to determine whether or not the error is because the ServiceAccount doesn't exist.

func (*ServiceAccounts) Update

func (s *ServiceAccounts) Update(options *ServiceAccountOptions) (
	serviceAccount *ServiceAccount, err error)

Update updates a ServiceAccount according to options and returns the updated ServiceAccount.

type Source

type Source struct {
	// Name is the name given to the source
	Name string `json:"name"`

	// Query is a wavefront Query
	Query string `json:"query"`

	// Disabled indicated whether the source is disabled from being rendered on the chart
	Disabled bool `json:"disabled,omitempty"`

	// ScatterPlotSource
	ScatterPlotSource string `json:"scatterPlotSource,omitempty"`

	// QuerybuilderEnabled
	QuerybuilderEnabled bool `json:"querybuilderEnabled"`

	// SourceDescription
	SourceDescription string `json:"sourceDescription"`

	// SourceColor
	SourceColor string `json:"sourceColor,omitempty"`

	// SecondaryAxis
	SecondaryAxis bool `json:"secondaryAxis,omitempty"`
}

Source represents a single Source for a Chart

type SourceLabelPair

type SourceLabelPair struct {
	Host   string `json:"host"`
	Firing int    `json:"firing"`
}

type Target

type Target struct {
	// Description is a description of the target Target
	Description string `json:"description"`

	// ID is the Wavefront-assigned ID of an existing Target
	ID *string `json:"id"`

	// Template is the Mustache template for the notification body
	Template string `json:"template"`

	// Title is the title(name) of the Target
	Title string `json:"title"`

	// Method must be EMAIL, WEBHOOK or PAGERDUTY
	Method string `json:"method"`

	// List of routing targets that this notificant will notify
	Routes []AlertRoute `json:"routes"`

	// Recipient is a comma-separated list of email addresses, webhook URL,
	// or 32-digit PagerDuty key  to which notifications will be sent for this Target
	Recipient string `json:"recipient"`

	// EmailSubject is the subject of the email which will be sent for this Target
	// (EMAIL targets only)
	EmailSubject string `json:"emailSubject"`

	// IsHTMLContent is a boolean value for wavefront to add HTML Boilerplate
	// while using HTML Templates as email.
	// (EMAIL targets only)
	IsHtmlContent bool `json:"isHtmlContent"`

	// ContentType is the content type for webhook posts (e.g. application/json)
	// (WEBHOOK targets only)
	ContentType string `json:"contentType"`

	// CustomHeaders are any custom HTTP headers that should be sent with webhook,
	// in key:value syntax (WEBHOOK targets only)
	CustomHeaders map[string]string `json:"customHttpHeaders"`

	// Triggers is a list of Alert states that will trigger this notification
	// and can include ALERT_OPENED, ALERT_RESOLVED, ALERT_STATUS_RESOLVED,
	// ALERT_AFFECTED_BY_MAINTENANCE_WINDOW, ALERT_SNOOZED, ALERT_NO_DATA,
	// ALERT_NO_DATA_RESOLVED
	Triggers []string `json:"triggers"`
}

Target represents a Wavefront Alert Target, for routing notifications associated with Alerts. Targets can be either email or webhook targets, and the Method must be set appropriately.

type Targets

type Targets struct {
	// contains filtered or unexported fields
}

Targets is used to perform target-related operations against the Wavefront API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)

if err != nil {
	log.Fatal(err)
}

client.Debug(true)

targets := client.Targets()

tmpl, _ := os.ReadFile("./target-template.tmpl")

target := wavefront.Target{
	Title:       "test target",
	Description: "testing something",
	Method:      "WEBHOOK",
	Recipient:   "https://hooks.slack.com/services/test/me",
	ContentType: "application/json",
	CustomHeaders: map[string]string{
		"Testing": "true",
	},
	Triggers: []string{"ALERT_OPENED", "ALERT_RESOLVED"},
	Template: string(tmpl),
}

// Create the target on Wavefront
err = targets.Create(&target)
if err != nil {
	log.Fatal(err)
}

// Get an target by ID
err = targets.Get(&wavefront.Target{ID: target.ID})
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update or delete the Target
target.Description = "new description"
err = targets.Update(&target)
if err != nil {
	log.Fatal(err)
}

err = targets.Delete(&target)
if err != nil {
	log.Fatal(err)
}
Output:

func (Targets) Create

func (t Targets) Create(target *Target) error

Create is used to create a Target in Wavefront. If successful, the ID field of the target will be populated.

func (Targets) Delete

func (t Targets) Delete(target *Target) error

Delete is used to delete an existing Target. The ID field of the target must be populated

func (Targets) Find

func (t Targets) Find(filter []*SearchCondition) (
	results []*Target, err error)

Find returns all targets filtered by the given search conditions. If filter is nil, all targets are returned.

func (Targets) Get

func (t Targets) Get(target *Target) error

Get is used to retrieve an existing Target by ID. The ID field must be provided

func (Targets) Update

func (t Targets) Update(target *Target) error

Update is used to update an existing Target. The ID field of the target must be populated

type TeslaConfiguration

type TeslaConfiguration struct {
	// Email address for the Tesla account login
	Email    string `json:"email"`
	Password string `json:"password"`
}

type TimeRange

type TimeRange struct {
	// StartTime is the time, in epoch milliseconds from which search results
	// will be returned.
	StartTime int64 `json:"earliestStartTimeEpochMillis"`

	// EndTime is the time, in epoch milliseconds up to which search results
	// will be returned.
	EndTime int64 `json:"latestStartTimeEpochMillis"`
}

TimeRange represents a range of times to search between. It is only valid for certain search types (e.g. Events)

func NewTimeRange

func NewTimeRange(endTime, period int64) (*TimeRange, error)

NewTimeRange returns a *TimeRange encompassing the period seconds before the given endTime. If endTime is 0, the current time will be used.

type TimeSeries

type TimeSeries struct {
	DataPoints []DataPoint       `json:"data"`
	Label      string            `json:"label"`
	Host       string            `json:"host"`
	Tags       map[string]string `json:"tags"`
}

TimeSeries represents a single TimeSeries as returned by Wavefront

type Token

type Token struct {
	ID   string `json:"tokenID"`
	Name string `json:"tokenName"`
}

Token represents an API token in Wavefront

func (*Token) Options

func (s *Token) Options() *TokenOptions

Options returns the options for this token.

type TokenOptions

type TokenOptions struct {

	// ID must be blank when creating a token.
	ID string `json:"tokenID,omitempty"`

	Name string `json:"tokenName,omitempty"`
}

TokenOptions represents the options for creating or modifying tokens

type Tokens

type Tokens struct {
	// contains filtered or unexported fields
}

Tokens is used to perform service account token related operations against the Wavefront API

func (*Tokens) Create

func (s *Tokens) Create(
	serviceAccountID string, options *TokenOptions) (
	tokens []Token, err error)

Create creates a Token according to options and returns all the tokens including the newly created one for the given serviceAccountID.

func (*Tokens) Delete

func (s *Tokens) Delete(serviceAccountID, tokenID string) error

Delete deletes a token

func (*Tokens) Update

func (s *Tokens) Update(
	serviceAccountID string, options *TokenOptions) (
	token *Token, err error)

Update updates a token and returns the updated token.

type UpdateMetricsPolicyRequest

type UpdateMetricsPolicyRequest struct {
	PolicyRules []PolicyRuleRequest `json:"policyRules,omitempty"`
}

type User

type User struct {
	// The email identifier for a user
	ID *string `json:"identifier"`

	// The customer the user is a member of
	Customer string `json:"customer,omitempty"`

	// Last successful login in epoch millis
	LastSuccessfulLogin uint `json:"lastSuccessfulLogin,omitempty"`

	// The permissions granted to this user
	Permissions []string `json:"groups,omitempty"`

	// Groups this user belongs to
	// This is wrapped with a Wrapper to manage the serialization between what we send to the API
	// And what the API sends back (which is to say, we send just IDs but we always receive a complete object)
	Groups UserGroupsWrapper `json:"userGroups,omitempty"`

	// Used during an PUT call to modify a users password
	Credential string `json:"credential,omitempty"`
}

User represents a Wavefront User

type UserGroup

type UserGroup struct {
	// Unique ID for the user group
	ID *string `json:"id,omitempty"`

	// Name of the user group
	Name string `json:"name,omitempty"`

	// Customer
	Customer string `json:"customer,omitempty"`

	// Roles assigned to the group
	Roles []Role

	// Users that are members of the group
	Users []string `json:"users,omitempty"`

	// Total number of users that are members of the user group
	UserCount int `json:"userCount,omitempty"`

	// Which properties of the user group are editable
	Properties UserGroupPropertiesDTO `json:"properties,omitempty"`

	// Description of the Group purpose
	Description string `json:"description,omitempty"`

	// When the group was created
	CreatedEpochMillis int `json:"createdEpochMillis,omitempty"`
}

type UserGroupPropertiesDTO

type UserGroupPropertiesDTO struct {
	NameEditable bool `json:"nameEditable"`

	PermissionsEditable bool `json:"permissionsEditable"`

	UsersEditable bool `json:"usersEditable"`

	RolesEditable bool `json:"rolesEditable"`
}

type UserGroups

type UserGroups struct {
	// contains filtered or unexported fields
}
Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

userGroups := client.UserGroups()
// Which populates a User object upon success
ug := &wavefront.UserGroup{
	Name: "Alert Users",
	Users: []string{
		"someone@example.com",
	},
	Description: "Users can access & edit Wavefront Alerts",
}

// Create the UserGroup on Wavefront
err = userGroups.Create(ug)
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete the UserGroup
fmt.Println("user group ID is", *ug.ID)

ug.Name = "Alert Users Rename"

// Update the User
err = userGroups.Update(ug)
if err != nil {
	log.Fatal(err)
}

time.Sleep(time.Second * 60)

// Delete the User
err = userGroups.Delete(ug)
if err != nil {
	log.Fatal(err)
}

fmt.Println("user group deleted")
Output:

func (UserGroups) AddUsers

func (g UserGroups) AddUsers(id *string, users *[]string) error

Adds the specified users to the group

func (UserGroups) Create

func (g UserGroups) Create(userGroup *UserGroup) error

func (UserGroups) Delete

func (g UserGroups) Delete(userGroup *UserGroup) error

func (UserGroups) Find

func (g UserGroups) Find(filter []*SearchCondition) (
	results []*UserGroup, err error)

Find returns all UsersGroups filtered by the given search conditions. If filter is nil, all UserGroups are returned.

func (UserGroups) Get

func (g UserGroups) Get(userGroup *UserGroup) error

Gets a specific UserGroup by ID The ID field must be specified

func (UserGroups) RemoveUsers

func (g UserGroups) RemoveUsers(id *string, users *[]string) error

Removes the specified users from the group

func (UserGroups) Update

func (g UserGroups) Update(userGroup *UserGroup) error

Update does not support updating the users on the group To update the users in a group use AddUsers and RemoveUsers The ID field must be specified

type UserGroupsWrapper

type UserGroupsWrapper struct {
	UserGroups []UserGroup
}

func (*UserGroupsWrapper) MarshalJSON

func (w *UserGroupsWrapper) MarshalJSON() ([]byte, error)

During a POST/PUT/DELETE on a User only the UserGroup.ID is transmitted

func (*UserGroupsWrapper) UnmarshalJSON

func (w *UserGroupsWrapper) UnmarshalJSON(data []byte) error

During a GET operation or returned AFTER a POST/PUT/DELETE we receive a complete UserGroup struct

type Users

type Users struct {
	// contains filtered or unexported fields
}

Users is used to perform user-related operations against the Wavefront API

Example
config := &wavefront.Config{
	Address: "test.wavefront.com",
	Token:   "xxxx-xxxx-xxxx-xxxx-xxxx",
}
client, err := wavefront.NewClient(config)
if err != nil {
	log.Fatal(err)
}

users := client.Users()

// Users are created with a NewUserRequest
newUserRequest := &wavefront.NewUserRequest{
	EmailAddress: "someone@example.com",
	Permissions: []string{
		wavefront.ALERTS_MANAGEMENT,
	},
	Groups: wavefront.UserGroupsWrapper{},
}

// Which populates a User object upon success
u := &wavefront.User{}

// Create the User on Wavefront and don't send an email
err = users.Create(newUserRequest, u, false)
if err != nil {
	log.Fatal(err)
}

// The ID field is now set, so we can update/delete the User
fmt.Println("user ID is", *u.ID)

// Change to 10 minutes
u.Permissions = append(u.Permissions, wavefront.DERIVED_METRICS_MANAGEMENT)

// Update the User
err = users.Update(u)
if err != nil {
	log.Fatal(err)
}

time.Sleep(time.Second * 60)

// Delete the User
err = users.Delete(u)
if err != nil {
	log.Fatal(err)
}

fmt.Println("user deleted")
Output:

func (Users) Create

func (u Users) Create(newUser *NewUserRequest, user *User, sendEmail bool) error

Does not support specifying a credential The EmailAddress field must be specified

func (Users) Delete

func (u Users) Delete(user *User) error

Deletes the specified user The ID field must be specified

func (Users) Find

func (u Users) Find(filter []*SearchCondition) (users []*User, err error)

Find returns all Users filtered by the given search conditions. If filter is nil, all Users are returned. UserGroups returned on the User from this call will be ID only

func (Users) Get

func (u Users) Get(user *User) error

Get is used to retrieve an existing User by ID. The identifier field must be specified

func (Users) Update

func (u Users) Update(user *User) error

Supports specifying the credential The identifier field must be specified

type WFTags

type WFTags struct {
	CustomerTags []string `json:"customerTags"`
}

type Wavefronter

type Wavefronter interface {
	NewRequest(method, path string, params *map[string]string, body []byte) (*http.Request, error)
	Do(req *http.Request) (io.ReadCloser, error)
}

Wavefronter is an interface that a Wavefront client must satisfy (generally this is abstracted for easier testing)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL