func (m *CirconusMetrics) AddGauge(metric string, val interface{}) {
	m.gm.Lock()
	defer m.gm.Unlock()

	v, ok := m.gauges[metric]
	if !ok {
		m.gauges[metric] = val
		return
	}

	switch val.(type) {
	default:
		// ignore it, unsupported type
	case int:
		m.gauges[metric] = v.(int) + val.(int)
	case int8:
		m.gauges[metric] = v.(int8) + val.(int8)
	case int16:
		m.gauges[metric] = v.(int16) + val.(int16)
	case int32:
		m.gauges[metric] = v.(int32) + val.(int32)
	case int64:
		m.gauges[metric] = v.(int64) + val.(int64)
	case uint:
		m.gauges[metric] = v.(uint) + val.(uint)
	case uint8:
		m.gauges[metric] = v.(uint8) + val.(uint8)
	case uint16:
		m.gauges[metric] = v.(uint16) + val.(uint16)
	case uint32:
		m.gauges[metric] = v.(uint32) + val.(uint32)
	case uint64:
		m.gauges[metric] = v.(uint64) + val.(uint64)
	case float32:
		m.gauges[metric] = v.(float32) + val.(float32)
	case float64:
		m.gauges[metric] = v.(float64) + val.(float64)
	}
}

func
(
m
*
CirconusMetrics
)
AddGauge
(
metric
string
,
val
interface
{
}
)
{
m
.
gm
.
Lock
(
)
defer
m
.
gm
.
Unlock
(
)
v
,
ok
:=
m
.
gauges
[
metric
]
if
!
ok
{
m
.
gauges
[
metric
]
=
val
return
}
switch
val
.
(
type
)
{
default
:
// ignore it, unsupported type
case
int
:
m
.
gauges
[
metric
]
=
v
.
(
int
)
+
val
.
(
int
)
case
int8
:
m
.
gauges
[
metric
]
=
v
.
(
int8
)
+
val
.
(
int8
)
case
int16
:
m
.
gauges
[
metric
]
=
v
.
(
int16
)
+
val
.
(
int16
)
case
int32
:
m
.
gauges
[
metric
]
=
v
.
(
int32
)
+
val
.
(
int32
)
case
int64
:
m
.
gauges
[
metric
]
=
v
.
(
int64
)
+
val
.
(
int64
)
case
uint
:
m
.
gauges
[
metric
]
=
v
.
(
uint
)
+
val
.
(
uint
)
case
uint8
:
m
.
gauges
[
metric
]
=
v
.
(
uint8
)
+
val
.
(
uint8
)
case
uint16
:
m
.
gauges
[
metric
]
=
v
.
(
uint16
)
+
val
.
(
uint16
)
case
uint32
:
m
.
gauges
[
metric
]
=
v
.
(
uint32
)
+
val
.
(
uint32
)
case
uint64
:
m
.
gauges
[
metric
]
=
v
.
(
uint64
)
+
val
.
(
uint64
)
case
float32
:
m
.
gauges
[
metric
]
=
v
.
(
float32
)
+
val
.
(
float32
)
case
float64
:
m
.
gauges
[
metric
]
=
v
.
(
float64
)
+
val
.
(
float64
)
}
}

// AddGauge adds value to existing gauge


func (m *CirconusMetrics) RemoveGauge(metric string) {
	m.gm.Lock()
	defer m.gm.Unlock()
	delete(m.gauges, metric)
}

func ( m * CirconusMetrics ) RemoveGauge ( metric string ) { m . gm . Lock ( ) defer m . gm . Unlock ( ) delete ( m . gauges , metric ) }


func (m *CirconusMetrics) RemoveGaugeFunc(metric string) {
	m.gfm.Lock()
	defer m.gfm.Unlock()
	delete(m.gaugeFuncs, metric)
}

func ( m * CirconusMetrics ) RemoveGaugeFunc ( metric string ) { m . gfm . Lock ( ) defer m . gfm . Unlock ( ) delete ( m . gaugeFuncs , metric ) }

// RemoveGaugeFunc removes a gauge function


func (m *CirconusMetrics) getGaugeType(v interface{}) string {
	mt := "n"
	switch v.(type) {
	case int:
		mt = "i"
	case int8:
		mt = "i"
	case int16:
		mt = "i"
	case int32:
		mt = "i"
	case uint:
		mt = "I"
	case uint8:
		mt = "I"
	case uint16:
		mt = "I"
	case uint32:
		mt = "I"
	case int64:
		mt = "l"
	case uint64:
		mt = "L"
	}

	return mt
}

func ( m * CirconusMetrics ) getGaugeType ( v interface { } ) string { mt := " " switch v . ( type ) { case int : mt = " " case int8 : mt = " " case int16 : mt = " " case int32 : mt = " " case uint : mt = " " case uint8 : mt = " " case uint16 : mt = " " case uint32 : mt = " " case int64 : mt = " " case uint64 : mt = " " } return mt }

// getGaugeType returns accurate resmon type for underlying type of gauge value


func (a *API) FetchCheckBundleMetrics(cid CIDType) (*CheckBundleMetrics, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid check bundle metrics CID [none]")
	}

	metricsCID := string(*cid)

	matched, err := regexp.MatchString(config.CheckBundleMetricsCIDRegex, metricsCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid check bundle metrics CID [%s]", metricsCID)
	}

	result, err := a.Get(metricsCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch check bundle metrics, received JSON: %s", string(result))
	}

	metrics := &CheckBundleMetrics{}
	if err := json.Unmarshal(result, metrics); err != nil {
		return nil, err
	}

	return metrics, nil
}

func ( a * API ) FetchCheckBundleMetrics ( cid CIDType ) ( * CheckBundleMetrics , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } metricsCID := string ( * cid ) matched , err := regexp . MatchString ( config . CheckBundleMetricsCIDRegex , metricsCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , metricsCID ) } result , err := a . Get ( metricsCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } metrics := & CheckBundleMetrics { } if err := json . Unmarshal ( result , metrics ) ; err != nil { return nil , err } return metrics , nil }

// FetchCheckBundleMetrics retrieves metrics for the check bundle with passed cid.

FetchCheckBundleMetrics retrieves metrics for the check bundle with passed cid .


func (a *API) UpdateCheckBundleMetrics(cfg *CheckBundleMetrics) (*CheckBundleMetrics, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid check bundle metrics config [nil]")
	}

	metricsCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.CheckBundleMetricsCIDRegex, metricsCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid check bundle metrics CID [%s]", metricsCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update check bundle metrics, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(metricsCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	metrics := &CheckBundleMetrics{}
	if err := json.Unmarshal(result, metrics); err != nil {
		return nil, err
	}

	return metrics, nil
}

func ( a * API ) UpdateCheckBundleMetrics ( cfg * CheckBundleMetrics ) ( * CheckBundleMetrics , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } metricsCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . CheckBundleMetricsCIDRegex , metricsCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , metricsCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( metricsCID , jsonCfg ) if err != nil { return nil , err } metrics := & CheckBundleMetrics { } if err := json . Unmarshal ( result , metrics ) ; err != nil { return nil , err } return metrics , nil }

// UpdateCheckBundleMetrics updates passed metrics.

UpdateCheckBundleMetrics updates passed metrics .


func (cm *CheckManager) getBroker() (*api.Broker, error) {
	if cm.brokerID != 0 {
		cid := fmt.Sprintf("/broker/%d", cm.brokerID)
		broker, err := cm.apih.FetchBroker(api.CIDType(&cid))
		if err != nil {
			return nil, err
		}
		if !cm.isValidBroker(broker) {
			return nil, fmt.Errorf(
				"[ERROR] designated broker %d [%s] is invalid (not active, does not support required check type, or connectivity issue)",
				cm.brokerID,
				broker.Name)
		}
		return broker, nil
	}
	broker, err := cm.selectBroker()
	if err != nil {
		return nil, fmt.Errorf("[ERROR] Unable to fetch suitable broker %s", err)
	}
	return broker, nil
}

func ( cm * CheckManager ) getBroker ( ) ( * api . Broker , error ) { if cm . brokerID != 0 { cid := fmt . Sprintf ( " " , cm . brokerID ) broker , err := cm . apih . FetchBroker ( api . CIDType ( & cid ) ) if err != nil { return nil , err } if ! cm . isValidBroker ( broker ) { return nil , fmt . Errorf ( " " , cm . brokerID , broker . Name ) } return broker , nil } broker , err := cm . selectBroker ( ) if err != nil { return nil , fmt . Errorf ( " " , err ) } return broker , nil }

// Get Broker to use when creating a check


func (cm *CheckManager) getBrokerCN(broker *api.Broker, submissionURL api.URLType) (string, error) {
	u, err := url.Parse(string(submissionURL))
	if err != nil {
		return "", err
	}

	hostParts := strings.Split(u.Host, ":")
	host := hostParts[0]

	if net.ParseIP(host) == nil { // it's a non-ip string
		return u.Host, nil
	}

	cn := ""

	for _, detail := range broker.Details {
		if *detail.IP == host {
			cn = detail.CN
			break
		}
	}

	if cn == "" {
		return "", fmt.Errorf("[ERROR] Unable to match URL host (%s) to Broker", u.Host)
	}

	return cn, nil

}

func
(
cm
*
CheckManager
)
getBrokerCN
(
broker
*
api
.
Broker
,
submissionURL
api
.
URLType
)
(
string
,
error
)
{
u
,
err
:=
url
.
Parse
(
string
(
submissionURL
)
)
if
err
!=
{
return
"
"
,
err
}
hostParts
:=
strings
.
Split
(
u
.
Host
,
"
"
)
host
:=
hostParts
[
0
]
if
net
.
ParseIP
(
host
)
==
{
// it's a non-ip string
return
u
.
Host
,
}
cn
:=
"
"
for
_
,
detail
:=
range
broker
.
Details
{
if
*
detail
.
IP
==
host
{
cn
=
detail
.
CN
break
}
}
if
cn
==
"
"
{
return
"
"
,
fmt
.
Errorf
(
"
"
,
u
.
Host
)
}
return
cn
,
}

// Get CN of Broker associated with submission_url to satisfy no IP SANS in certs


func (cm *CheckManager) selectBroker() (*api.Broker, error) {
	var brokerList *[]api.Broker
	var err error
	enterpriseType := "enterprise"

	if len(cm.brokerSelectTag) > 0 {
		filter := api.SearchFilterType{
			"f__tags_has": cm.brokerSelectTag,
		}
		brokerList, err = cm.apih.SearchBrokers(nil, &filter)
		if err != nil {
			return nil, err
		}
	} else {
		brokerList, err = cm.apih.FetchBrokers()
		if err != nil {
			return nil, err
		}
	}

	if len(*brokerList) == 0 {
		return nil, fmt.Errorf("zero brokers found")
	}

	validBrokers := make(map[string]api.Broker)
	haveEnterprise := false

	for _, broker := range *brokerList {
		broker := broker
		if cm.isValidBroker(&broker) {
			validBrokers[broker.CID] = broker
			if broker.Type == enterpriseType {
				haveEnterprise = true
			}
		}
	}

	if haveEnterprise { // eliminate non-enterprise brokers from valid brokers
		for k, v := range validBrokers {
			if v.Type != enterpriseType {
				delete(validBrokers, k)
			}
		}
	}

	if len(validBrokers) == 0 {
		return nil, fmt.Errorf("found %d broker(s), zero are valid", len(*brokerList))
	}

	validBrokerKeys := reflect.ValueOf(validBrokers).MapKeys()
	selectedBroker := validBrokers[validBrokerKeys[rand.Intn(len(validBrokerKeys))].String()]

	if cm.Debug {
		cm.Log.Printf("[DEBUG] Selected broker '%s'\n", selectedBroker.Name)
	}

	return &selectedBroker, nil

}

// Select a broker for use when creating a check, if a specific broker
// was not specified.

Select a broker for use when creating a check if a specific broker was not specified .


func (cm *CheckManager) brokerSupportsCheckType(checkType CheckTypeType, details *api.BrokerDetail) bool {

	baseType := string(checkType)

	for _, module := range details.Modules {
		if module == baseType {
			return true
		}
	}

	if idx := strings.Index(baseType, ":"); idx > 0 {
		baseType = baseType[0:idx]
	}

	for _, module := range details.Modules {
		if module == baseType {
			return true
		}
	}

	return false

}

func ( cm * CheckManager ) brokerSupportsCheckType ( checkType CheckTypeType , details * api . BrokerDetail ) bool { baseType := string ( checkType ) for _ , module := range details . Modules { if module == baseType { return true } } if idx := strings . Index ( baseType , " " ) ; idx > 0 { baseType = baseType [ 0 : idx ] } for _ , module := range details . Modules { if module == baseType { return true } } return false }

// Verify broker supports the check type to be used


func (a *API) FetchMetricCluster(cid CIDType, extras string) (*MetricCluster, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid metric cluster CID [none]")
	}

	clusterCID := string(*cid)

	matched, err := regexp.MatchString(config.MetricClusterCIDRegex, clusterCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid metric cluster CID [%s]", clusterCID)
	}

	reqURL := url.URL{
		Path: clusterCID,
	}

	extra := ""
	switch extras {
	case "metrics":
		extra = "_matching_metrics"
	case "uuids":
		extra = "_matching_uuid_metrics"
	}

	if extra != "" {
		q := url.Values{}
		q.Set("extra", extra)
		reqURL.RawQuery = q.Encode()
	}

	result, err := a.Get(reqURL.String())
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch metric cluster, received JSON: %s", string(result))
	}

	cluster := &MetricCluster{}
	if err := json.Unmarshal(result, cluster); err != nil {
		return nil, err
	}

	return cluster, nil
}

func ( a * API ) FetchMetricCluster ( cid CIDType , extras string ) ( * MetricCluster , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } clusterCID := string ( * cid ) matched , err := regexp . MatchString ( config . MetricClusterCIDRegex , clusterCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , clusterCID ) } reqURL := url . URL { Path : clusterCID , } extra := " " switch extras { case " " : extra = " " case " " : extra = " " } if extra != " " { q := url . Values { } q . Set ( " " , extra ) reqURL . RawQuery = q . Encode ( ) } result , err := a . Get ( reqURL . String ( ) ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } cluster := & MetricCluster { } if err := json . Unmarshal ( result , cluster ) ; err != nil { return nil , err } return cluster , nil }

// FetchMetricCluster retrieves metric cluster with passed cid.

FetchMetricCluster retrieves metric cluster with passed cid .


func (a *API) FetchMetricClusters(extras string) (*[]MetricCluster, error) {
	reqURL := url.URL{
		Path: config.MetricClusterPrefix,
	}

	extra := ""
	switch extras {
	case "metrics":
		extra = "_matching_metrics"
	case "uuids":
		extra = "_matching_uuid_metrics"
	}

	if extra != "" {
		q := url.Values{}
		q.Set("extra", extra)
		reqURL.RawQuery = q.Encode()
	}

	result, err := a.Get(reqURL.String())
	if err != nil {
		return nil, err
	}

	var clusters []MetricCluster
	if err := json.Unmarshal(result, &clusters); err != nil {
		return nil, err
	}

	return &clusters, nil
}

func ( a * API ) FetchMetricClusters ( extras string ) ( * [ ] MetricCluster , error ) { reqURL := url . URL { Path : config . MetricClusterPrefix , } extra := " " switch extras { case " " : extra = " " case " " : extra = " " } if extra != " " { q := url . Values { } q . Set ( " " , extra ) reqURL . RawQuery = q . Encode ( ) } result , err := a . Get ( reqURL . String ( ) ) if err != nil { return nil , err } var clusters [ ] MetricCluster if err := json . Unmarshal ( result , & clusters ) ; err != nil { return nil , err } return & clusters , nil }

// FetchMetricClusters retrieves all metric clusters available to API Token.

FetchMetricClusters retrieves all metric clusters available to API Token .


func (a *API) UpdateMetricCluster(cfg *MetricCluster) (*MetricCluster, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid metric cluster config [nil]")
	}

	clusterCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.MetricClusterCIDRegex, clusterCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid metric cluster CID [%s]", clusterCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update metric cluster, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(clusterCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	cluster := &MetricCluster{}
	if err := json.Unmarshal(result, cluster); err != nil {
		return nil, err
	}

	return cluster, nil
}

func ( a * API ) UpdateMetricCluster ( cfg * MetricCluster ) ( * MetricCluster , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } clusterCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . MetricClusterCIDRegex , clusterCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , clusterCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( clusterCID , jsonCfg ) if err != nil { return nil , err } cluster := & MetricCluster { } if err := json . Unmarshal ( result , cluster ) ; err != nil { return nil , err } return cluster , nil }

// UpdateMetricCluster updates passed metric cluster.

UpdateMetricCluster updates passed metric cluster .


func (a *API) CreateMetricCluster(cfg *MetricCluster) (*MetricCluster, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid metric cluster config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create metric cluster, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.MetricClusterPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	cluster := &MetricCluster{}
	if err := json.Unmarshal(result, cluster); err != nil {
		return nil, err
	}

	return cluster, nil
}

func ( a * API ) CreateMetricCluster ( cfg * MetricCluster ) ( * MetricCluster , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . MetricClusterPrefix , jsonCfg ) if err != nil { return nil , err } cluster := & MetricCluster { } if err := json . Unmarshal ( result , cluster ) ; err != nil { return nil , err } return cluster , nil }

// CreateMetricCluster creates a new metric cluster.

CreateMetricCluster creates a new metric cluster .


func (a *API) DeleteMetricCluster(cfg *MetricCluster) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid metric cluster config [nil]")
	}
	return a.DeleteMetricClusterByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteMetricCluster ( cfg * MetricCluster ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteMetricClusterByCID ( CIDType ( & cfg . CID ) ) }

// DeleteMetricCluster deletes passed metric cluster.

DeleteMetricCluster deletes passed metric cluster .


func (a *API) DeleteMetricClusterByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid metric cluster CID [none]")
	}

	clusterCID := string(*cid)

	matched, err := regexp.MatchString(config.MetricClusterCIDRegex, clusterCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid metric cluster CID [%s]", clusterCID)
	}

	_, err = a.Delete(clusterCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteMetricClusterByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } clusterCID := string ( * cid ) matched , err := regexp . MatchString ( config . MetricClusterCIDRegex , clusterCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , clusterCID ) } _ , err = a . Delete ( clusterCID ) if err != nil { return false , err } return true , nil }

// DeleteMetricClusterByCID deletes metric cluster with passed cid.

DeleteMetricClusterByCID deletes metric cluster with passed cid .


func (cm *CheckManager) loadCACert() error {
	if cm.certPool != nil {
		return nil
	}

	cm.certPool = x509.NewCertPool()

	var cert []byte
	var err error

	if cm.enabled {
		// only attempt to retrieve broker CA cert if
		// the check is being managed.
		cert, err = cm.fetchCert()
		if err != nil {
			return err
		}
	}

	if cert == nil {
		cert = circonusCA
	}

	cm.certPool.AppendCertsFromPEM(cert)

	return nil
}

// loadCACert loads the CA cert for the broker designated by the submission url


func (cm *CheckManager) fetchCert() ([]byte, error) {
	if !cm.enabled {
		return nil, errors.New("check manager is not enabled")
	}

	response, err := cm.apih.Get("/pki/ca.crt")
	if err != nil {
		return nil, err
	}

	cadata := new(CACert)
	if err := json.Unmarshal(response, cadata); err != nil {
		return nil, err
	}

	if cadata.Contents == "" {
		return nil, fmt.Errorf("[ERROR] Unable to find ca cert %+v", cadata)
	}

	return []byte(cadata.Contents), nil
}

func ( cm * CheckManager ) fetchCert ( ) ( [ ] byte , error ) { if ! cm . enabled { return nil , errors . New ( " " ) } response , err := cm . apih . Get ( " " ) if err != nil { return nil , err } cadata := new ( CACert ) if err := json . Unmarshal ( response , cadata ) ; err != nil { return nil , err } if cadata . Contents == " " { return nil , fmt . Errorf ( " " , cadata ) } return [ ] byte ( cadata . Contents ) , nil }

// fetchCert fetches CA certificate using Circonus API


func (a *API) FetchAccounts() (*[]Account, error) {
	result, err := a.Get(config.AccountPrefix)
	if err != nil {
		return nil, err
	}

	var accounts []Account
	if err := json.Unmarshal(result, &accounts); err != nil {
		return nil, err
	}

	return &accounts, nil
}

func ( a * API ) FetchAccounts ( ) ( * [ ] Account , error ) { result , err := a . Get ( config . AccountPrefix ) if err != nil { return nil , err } var accounts [ ] Account if err := json . Unmarshal ( result , & accounts ) ; err != nil { return nil , err } return & accounts , nil }

// FetchAccounts retrieves all accounts available to the API Token.

FetchAccounts retrieves all accounts available to the API Token .


func (a *API) UpdateAccount(cfg *Account) (*Account, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid account config [nil]")
	}

	accountCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.AccountCIDRegex, accountCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid account CID [%s]", accountCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] account update, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(accountCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	account := &Account{}
	if err := json.Unmarshal(result, account); err != nil {
		return nil, err
	}

	return account, nil
}

func ( a * API ) UpdateAccount ( cfg * Account ) ( * Account , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } accountCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . AccountCIDRegex , accountCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , accountCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( accountCID , jsonCfg ) if err != nil { return nil , err } account := & Account { } if err := json . Unmarshal ( result , account ) ; err != nil { return nil , err } return account , nil }

// UpdateAccount updates passed account.


func (a *API) FetchAnnotation(cid CIDType) (*Annotation, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid annotation CID [none]")
	}

	annotationCID := string(*cid)

	matched, err := regexp.MatchString(config.AnnotationCIDRegex, annotationCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid annotation CID [%s]", annotationCID)
	}

	result, err := a.Get(annotationCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch annotation, received JSON: %s", string(result))
	}

	annotation := &Annotation{}
	if err := json.Unmarshal(result, annotation); err != nil {
		return nil, err
	}

	return annotation, nil
}

func ( a * API ) FetchAnnotation ( cid CIDType ) ( * Annotation , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } annotationCID := string ( * cid ) matched , err := regexp . MatchString ( config . AnnotationCIDRegex , annotationCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , annotationCID ) } result , err := a . Get ( annotationCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } annotation := & Annotation { } if err := json . Unmarshal ( result , annotation ) ; err != nil { return nil , err } return annotation , nil }

// FetchAnnotation retrieves annotation with passed cid.

FetchAnnotation retrieves annotation with passed cid .


func (a *API) FetchAnnotations() (*[]Annotation, error) {
	result, err := a.Get(config.AnnotationPrefix)
	if err != nil {
		return nil, err
	}

	var annotations []Annotation
	if err := json.Unmarshal(result, &annotations); err != nil {
		return nil, err
	}

	return &annotations, nil
}

func ( a * API ) FetchAnnotations ( ) ( * [ ] Annotation , error ) { result , err := a . Get ( config . AnnotationPrefix ) if err != nil { return nil , err } var annotations [ ] Annotation if err := json . Unmarshal ( result , & annotations ) ; err != nil { return nil , err } return & annotations , nil }

// FetchAnnotations retrieves all annotations available to the API Token.

FetchAnnotations retrieves all annotations available to the API Token .


func (a *API) UpdateAnnotation(cfg *Annotation) (*Annotation, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid annotation config [nil]")
	}

	annotationCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.AnnotationCIDRegex, annotationCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid annotation CID [%s]", annotationCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update annotation, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(annotationCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	annotation := &Annotation{}
	if err := json.Unmarshal(result, annotation); err != nil {
		return nil, err
	}

	return annotation, nil
}

func ( a * API ) UpdateAnnotation ( cfg * Annotation ) ( * Annotation , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } annotationCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . AnnotationCIDRegex , annotationCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , annotationCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( annotationCID , jsonCfg ) if err != nil { return nil , err } annotation := & Annotation { } if err := json . Unmarshal ( result , annotation ) ; err != nil { return nil , err } return annotation , nil }

// UpdateAnnotation updates passed annotation.

UpdateAnnotation updates passed annotation .


func (a *API) CreateAnnotation(cfg *Annotation) (*Annotation, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid annotation config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create annotation, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.AnnotationPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	annotation := &Annotation{}
	if err := json.Unmarshal(result, annotation); err != nil {
		return nil, err
	}

	return annotation, nil
}

func ( a * API ) CreateAnnotation ( cfg * Annotation ) ( * Annotation , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . AnnotationPrefix , jsonCfg ) if err != nil { return nil , err } annotation := & Annotation { } if err := json . Unmarshal ( result , annotation ) ; err != nil { return nil , err } return annotation , nil }

// CreateAnnotation creates a new annotation.

CreateAnnotation creates a new annotation .


func (a *API) DeleteAnnotation(cfg *Annotation) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid annotation config [nil]")
	}

	return a.DeleteAnnotationByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteAnnotation ( cfg * Annotation ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteAnnotationByCID ( CIDType ( & cfg . CID ) ) }

// DeleteAnnotation deletes passed annotation.

DeleteAnnotation deletes passed annotation .


func (a *API) DeleteAnnotationByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid annotation CID [none]")
	}

	annotationCID := string(*cid)

	matched, err := regexp.MatchString(config.AnnotationCIDRegex, annotationCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid annotation CID [%s]", annotationCID)
	}

	_, err = a.Delete(annotationCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteAnnotationByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } annotationCID := string ( * cid ) matched , err := regexp . MatchString ( config . AnnotationCIDRegex , annotationCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , annotationCID ) } _ , err = a . Delete ( annotationCID ) if err != nil { return false , err } return true , nil }

// DeleteAnnotationByCID deletes annotation with passed cid.

DeleteAnnotationByCID deletes annotation with passed cid .


func (a *API) FetchOutlierReport(cid CIDType) (*OutlierReport, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid outlier report CID [none]")
	}

	reportCID := string(*cid)

	matched, err := regexp.MatchString(config.OutlierReportCIDRegex, reportCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid outlier report CID [%s]", reportCID)
	}

	result, err := a.Get(reportCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch outlier report, received JSON: %s", string(result))
	}

	report := &OutlierReport{}
	if err := json.Unmarshal(result, report); err != nil {
		return nil, err
	}

	return report, nil
}

func ( a * API ) FetchOutlierReport ( cid CIDType ) ( * OutlierReport , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } reportCID := string ( * cid ) matched , err := regexp . MatchString ( config . OutlierReportCIDRegex , reportCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , reportCID ) } result , err := a . Get ( reportCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } report := & OutlierReport { } if err := json . Unmarshal ( result , report ) ; err != nil { return nil , err } return report , nil }

// FetchOutlierReport retrieves outlier report with passed cid.

FetchOutlierReport retrieves outlier report with passed cid .


func (a *API) FetchOutlierReports() (*[]OutlierReport, error) {
	result, err := a.Get(config.OutlierReportPrefix)
	if err != nil {
		return nil, err
	}

	var reports []OutlierReport
	if err := json.Unmarshal(result, &reports); err != nil {
		return nil, err
	}

	return &reports, nil
}

func ( a * API ) FetchOutlierReports ( ) ( * [ ] OutlierReport , error ) { result , err := a . Get ( config . OutlierReportPrefix ) if err != nil { return nil , err } var reports [ ] OutlierReport if err := json . Unmarshal ( result , & reports ) ; err != nil { return nil , err } return & reports , nil }

// FetchOutlierReports retrieves all outlier reports available to API Token.

FetchOutlierReports retrieves all outlier reports available to API Token .


func (a *API) UpdateOutlierReport(cfg *OutlierReport) (*OutlierReport, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid outlier report config [nil]")
	}

	reportCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.OutlierReportCIDRegex, reportCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid outlier report CID [%s]", reportCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update outlier report, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(reportCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	report := &OutlierReport{}
	if err := json.Unmarshal(result, report); err != nil {
		return nil, err
	}

	return report, nil
}

func ( a * API ) UpdateOutlierReport ( cfg * OutlierReport ) ( * OutlierReport , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } reportCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . OutlierReportCIDRegex , reportCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , reportCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( reportCID , jsonCfg ) if err != nil { return nil , err } report := & OutlierReport { } if err := json . Unmarshal ( result , report ) ; err != nil { return nil , err } return report , nil }

// UpdateOutlierReport updates passed outlier report.

UpdateOutlierReport updates passed outlier report .


func (a *API) CreateOutlierReport(cfg *OutlierReport) (*OutlierReport, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid outlier report config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create outlier report, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.OutlierReportPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	report := &OutlierReport{}
	if err := json.Unmarshal(result, report); err != nil {
		return nil, err
	}

	return report, nil
}

func ( a * API ) CreateOutlierReport ( cfg * OutlierReport ) ( * OutlierReport , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . OutlierReportPrefix , jsonCfg ) if err != nil { return nil , err } report := & OutlierReport { } if err := json . Unmarshal ( result , report ) ; err != nil { return nil , err } return report , nil }

// CreateOutlierReport creates a new outlier report.

CreateOutlierReport creates a new outlier report .


func (a *API) DeleteOutlierReport(cfg *OutlierReport) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid outlier report config [nil]")
	}
	return a.DeleteOutlierReportByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteOutlierReport ( cfg * OutlierReport ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteOutlierReportByCID ( CIDType ( & cfg . CID ) ) }

// DeleteOutlierReport deletes passed outlier report.

DeleteOutlierReport deletes passed outlier report .


func (a *API) DeleteOutlierReportByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid outlier report CID [none]")
	}

	reportCID := string(*cid)

	matched, err := regexp.MatchString(config.OutlierReportCIDRegex, reportCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid outlier report CID [%s]", reportCID)
	}

	_, err = a.Delete(reportCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteOutlierReportByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } reportCID := string ( * cid ) matched , err := regexp . MatchString ( config . OutlierReportCIDRegex , reportCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , reportCID ) } _ , err = a . Delete ( reportCID ) if err != nil { return false , err } return true , nil }

// DeleteOutlierReportByCID deletes outlier report with passed cid.

DeleteOutlierReportByCID deletes outlier report with passed cid .


func (a *API) FetchUsers() (*[]User, error) {
	result, err := a.Get(config.UserPrefix)
	if err != nil {
		return nil, err
	}

	var users []User
	if err := json.Unmarshal(result, &users); err != nil {
		return nil, err
	}

	return &users, nil
}

func ( a * API ) FetchUsers ( ) ( * [ ] User , error ) { result , err := a . Get ( config . UserPrefix ) if err != nil { return nil , err } var users [ ] User if err := json . Unmarshal ( result , & users ) ; err != nil { return nil , err } return & users , nil }

// FetchUsers retrieves all users available to API Token.

FetchUsers retrieves all users available to API Token .


func (a *API) UpdateUser(cfg *User) (*User, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid user config [nil]")
	}

	userCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.UserCIDRegex, userCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid user CID [%s]", userCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update user, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(userCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	user := &User{}
	if err := json.Unmarshal(result, user); err != nil {
		return nil, err
	}

	return user, nil
}

func ( a * API ) UpdateUser ( cfg * User ) ( * User , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } userCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . UserCIDRegex , userCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , userCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( userCID , jsonCfg ) if err != nil { return nil , err } user := & User { } if err := json . Unmarshal ( result , user ) ; err != nil { return nil , err } return user , nil }


func (m *CirconusMetrics) SetMetricTags(name string, tags []string) bool {
	return m.check.AddMetricTags(name, tags, false)
}

func ( m * CirconusMetrics ) SetMetricTags ( name string , tags [ ] string ) bool { return m . check . AddMetricTags ( name , tags , false ) }

// SetMetricTags sets the tags for the named metric and flags a check update is needed


func (m *CirconusMetrics) AddMetricTags(name string, tags []string) bool {
	return m.check.AddMetricTags(name, tags, true)
}

func ( m * CirconusMetrics ) AddMetricTags ( name string , tags [ ] string ) bool { return m . check . AddMetricTags ( name , tags , true ) }

// AddMetricTags appends tags to any existing tags for the named metric and flags a check update is needed


func (a *API) FetchMetric(cid CIDType) (*Metric, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid metric CID [none]")
	}

	metricCID := string(*cid)

	matched, err := regexp.MatchString(config.MetricCIDRegex, metricCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid metric CID [%s]", metricCID)
	}

	result, err := a.Get(metricCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch metric, received JSON: %s", string(result))
	}

	metric := &Metric{}
	if err := json.Unmarshal(result, metric); err != nil {
		return nil, err
	}

	return metric, nil
}

func ( a * API ) FetchMetric ( cid CIDType ) ( * Metric , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } metricCID := string ( * cid ) matched , err := regexp . MatchString ( config . MetricCIDRegex , metricCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , metricCID ) } result , err := a . Get ( metricCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } metric := & Metric { } if err := json . Unmarshal ( result , metric ) ; err != nil { return nil , err } return metric , nil }

// FetchMetric retrieves metric with passed cid.

FetchMetric retrieves metric with passed cid .


func (a *API) FetchMetrics() (*[]Metric, error) {
	result, err := a.Get(config.MetricPrefix)
	if err != nil {
		return nil, err
	}

	var metrics []Metric
	if err := json.Unmarshal(result, &metrics); err != nil {
		return nil, err
	}

	return &metrics, nil
}

func ( a * API ) FetchMetrics ( ) ( * [ ] Metric , error ) { result , err := a . Get ( config . MetricPrefix ) if err != nil { return nil , err } var metrics [ ] Metric if err := json . Unmarshal ( result , & metrics ) ; err != nil { return nil , err } return & metrics , nil }

// FetchMetrics retrieves all metrics available to API Token.

FetchMetrics retrieves all metrics available to API Token .


func (a *API) UpdateMetric(cfg *Metric) (*Metric, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid metric config [nil]")
	}

	metricCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.MetricCIDRegex, metricCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid metric CID [%s]", metricCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update metric, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(metricCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	metric := &Metric{}
	if err := json.Unmarshal(result, metric); err != nil {
		return nil, err
	}

	return metric, nil
}

func ( a * API ) UpdateMetric ( cfg * Metric ) ( * Metric , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } metricCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . MetricCIDRegex , metricCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , metricCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( metricCID , jsonCfg ) if err != nil { return nil , err } metric := & Metric { } if err := json . Unmarshal ( result , metric ) ; err != nil { return nil , err } return metric , nil }


func (a *API) FetchAcknowledgement(cid CIDType) (*Acknowledgement, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid acknowledgement CID [none]")
	}

	acknowledgementCID := string(*cid)

	matched, err := regexp.MatchString(config.AcknowledgementCIDRegex, acknowledgementCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid acknowledgement CID [%s]", acknowledgementCID)
	}

	result, err := a.Get(acknowledgementCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] acknowledgement fetch, received JSON: %s", string(result))
	}

	acknowledgement := &Acknowledgement{}
	if err := json.Unmarshal(result, acknowledgement); err != nil {
		return nil, err
	}

	return acknowledgement, nil
}

func ( a * API ) FetchAcknowledgement ( cid CIDType ) ( * Acknowledgement , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } acknowledgementCID := string ( * cid ) matched , err := regexp . MatchString ( config . AcknowledgementCIDRegex , acknowledgementCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , acknowledgementCID ) } result , err := a . Get ( acknowledgementCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } acknowledgement := & Acknowledgement { } if err := json . Unmarshal ( result , acknowledgement ) ; err != nil { return nil , err } return acknowledgement , nil }

// FetchAcknowledgement retrieves acknowledgement with passed cid.

FetchAcknowledgement retrieves acknowledgement with passed cid .


func (a *API) FetchAcknowledgements() (*[]Acknowledgement, error) {
	result, err := a.Get(config.AcknowledgementPrefix)
	if err != nil {
		return nil, err
	}

	var acknowledgements []Acknowledgement
	if err := json.Unmarshal(result, &acknowledgements); err != nil {
		return nil, err
	}

	return &acknowledgements, nil
}

func ( a * API ) FetchAcknowledgements ( ) ( * [ ] Acknowledgement , error ) { result , err := a . Get ( config . AcknowledgementPrefix ) if err != nil { return nil , err } var acknowledgements [ ] Acknowledgement if err := json . Unmarshal ( result , & acknowledgements ) ; err != nil { return nil , err } return & acknowledgements , nil }

// FetchAcknowledgements retrieves all acknowledgements available to the API Token.

FetchAcknowledgements retrieves all acknowledgements available to the API Token .


func (a *API) UpdateAcknowledgement(cfg *Acknowledgement) (*Acknowledgement, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid acknowledgement config [nil]")
	}

	acknowledgementCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.AcknowledgementCIDRegex, acknowledgementCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid acknowledgement CID [%s]", acknowledgementCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] acknowledgement update, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(acknowledgementCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	acknowledgement := &Acknowledgement{}
	if err := json.Unmarshal(result, acknowledgement); err != nil {
		return nil, err
	}

	return acknowledgement, nil
}

func ( a * API ) UpdateAcknowledgement ( cfg * Acknowledgement ) ( * Acknowledgement , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } acknowledgementCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . AcknowledgementCIDRegex , acknowledgementCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , acknowledgementCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( acknowledgementCID , jsonCfg ) if err != nil { return nil , err } acknowledgement := & Acknowledgement { } if err := json . Unmarshal ( result , acknowledgement ) ; err != nil { return nil , err } return acknowledgement , nil }

// UpdateAcknowledgement updates passed acknowledgement.

UpdateAcknowledgement updates passed acknowledgement .


func (a *API) CreateAcknowledgement(cfg *Acknowledgement) (*Acknowledgement, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid acknowledgement config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	result, err := a.Post(config.AcknowledgementPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] acknowledgement create, sending JSON: %s", string(jsonCfg))
	}

	acknowledgement := &Acknowledgement{}
	if err := json.Unmarshal(result, acknowledgement); err != nil {
		return nil, err
	}

	return acknowledgement, nil
}

func ( a * API ) CreateAcknowledgement ( cfg * Acknowledgement ) ( * Acknowledgement , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } result , err := a . Post ( config . AcknowledgementPrefix , jsonCfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } acknowledgement := & Acknowledgement { } if err := json . Unmarshal ( result , acknowledgement ) ; err != nil { return nil , err } return acknowledgement , nil }

// CreateAcknowledgement creates a new acknowledgement.

CreateAcknowledgement creates a new acknowledgement .


func (m *CirconusMetrics) Reset() {
	m.cm.Lock()
	defer m.cm.Unlock()

	m.cfm.Lock()
	defer m.cfm.Unlock()

	m.gm.Lock()
	defer m.gm.Unlock()

	m.gfm.Lock()
	defer m.gfm.Unlock()

	m.hm.Lock()
	defer m.hm.Unlock()

	m.tm.Lock()
	defer m.tm.Unlock()

	m.tfm.Lock()
	defer m.tfm.Unlock()

	m.counters = make(map[string]uint64)
	m.counterFuncs = make(map[string]func() uint64)
	m.gauges = make(map[string]interface{})
	m.gaugeFuncs = make(map[string]func() int64)
	m.histograms = make(map[string]*Histogram)
	m.text = make(map[string]string)
	m.textFuncs = make(map[string]func() string)
}

func ( m * CirconusMetrics ) Reset ( ) { m . cm . Lock ( ) defer m . cm . Unlock ( ) m . cfm . Lock ( ) defer m . cfm . Unlock ( ) m . gm . Lock ( ) defer m . gm . Unlock ( ) m . gfm . Lock ( ) defer m . gfm . Unlock ( ) m . hm . Lock ( ) defer m . hm . Unlock ( ) m . tm . Lock ( ) defer m . tm . Unlock ( ) m . tfm . Lock ( ) defer m . tfm . Unlock ( ) m . counters = make ( map [ string ] uint64 ) m . counterFuncs = make ( map [ string ] func ( ) uint64 ) m . gauges = make ( map [ string ] interface { } ) m . gaugeFuncs = make ( map [ string ] func ( ) int64 ) m . histograms = make ( map [ string ] * Histogram ) m . text = make ( map [ string ] string ) m . textFuncs = make ( map [ string ] func ( ) string ) }

// Reset removes all existing counters and gauges.

Reset removes all existing counters and gauges .


func (m *CirconusMetrics) snapshot() (c map[string]uint64, g map[string]interface{}, h map[string]*circonusllhist.Histogram, t map[string]string) {
	c = m.snapCounters()
	g = m.snapGauges()
	h = m.snapHistograms()
	t = m.snapText()

	return
}

func ( m * CirconusMetrics ) snapshot ( ) ( c map [ string ] uint64 , g map [ string ] interface { } , h map [ string ] * circonusllhist . Histogram , t map [ string ] string ) { c = m . snapCounters ( ) g = m . snapGauges ( ) h = m . snapHistograms ( ) t = m . snapText ( ) return }

// snapshot returns a copy of the values of all registered counters and gauges.

snapshot returns a copy of the values of all registered counters and gauges .


func (m *CirconusMetrics) Timing(metric string, val float64) {
	m.SetHistogramValue(metric, val)
}

func ( m * CirconusMetrics ) Timing ( metric string , val float64 ) { m . SetHistogramValue ( metric , val ) }


func (m *CirconusMetrics) RecordValue(metric string, val float64) {
	m.SetHistogramValue(metric, val)
}

func ( m * CirconusMetrics ) RecordValue ( metric string , val float64 ) { m . SetHistogramValue ( metric , val ) }

// RecordValue adds a value to a histogram


func (m *CirconusMetrics) RecordCountForValue(metric string, val float64, n int64) {
	hist := m.NewHistogram(metric)

	m.hm.Lock()
	hist.rw.Lock()
	hist.hist.RecordValues(val, n)
	hist.rw.Unlock()
	m.hm.Unlock()
}

func ( m * CirconusMetrics ) RecordCountForValue ( metric string , val float64 , n int64 ) { hist := m . NewHistogram ( metric ) m . hm . Lock ( ) hist . rw . Lock ( ) hist . hist . RecordValues ( val , n ) hist . rw . Unlock ( ) m . hm . Unlock ( ) }

// RecordCountForValue adds count n for value to a histogram


func (m *CirconusMetrics) SetHistogramValue(metric string, val float64) {
	hist := m.NewHistogram(metric)

	m.hm.Lock()
	hist.rw.Lock()
	hist.hist.RecordValue(val)
	hist.rw.Unlock()
	m.hm.Unlock()
}

func ( m * CirconusMetrics ) SetHistogramValue ( metric string , val float64 ) { hist := m . NewHistogram ( metric ) m . hm . Lock ( ) hist . rw . Lock ( ) hist . hist . RecordValue ( val ) hist . rw . Unlock ( ) m . hm . Unlock ( ) }

// SetHistogramValue adds a value to a histogram


func (m *CirconusMetrics) RemoveHistogram(metric string) {
	m.hm.Lock()
	delete(m.histograms, metric)
	m.hm.Unlock()
}

func ( m * CirconusMetrics ) RemoveHistogram ( metric string ) { m . hm . Lock ( ) delete ( m . histograms , metric ) m . hm . Unlock ( ) }


func (m *CirconusMetrics) NewHistogram(metric string) *Histogram {
	m.hm.Lock()
	defer m.hm.Unlock()

	if hist, ok := m.histograms[metric]; ok {
		return hist
	}

	hist := &Histogram{
		name: metric,
		hist: circonusllhist.New(),
	}

	m.histograms[metric] = hist

	return hist
}

func ( m * CirconusMetrics ) NewHistogram ( metric string ) * Histogram { m . hm . Lock ( ) defer m . hm . Unlock ( ) if hist , ok := m . histograms [ metric ] ; ok { return hist } hist := & Histogram { name : metric , hist : circonusllhist . New ( ) , } m . histograms [ metric ] = hist return hist }

// NewHistogram returns a histogram instance.

NewHistogram returns a histogram instance .


func (h *Histogram) RecordValue(v float64) {
	h.rw.Lock()
	h.hist.RecordValue(v)
	h.rw.Unlock()
}

func ( h * Histogram ) RecordValue ( v float64 ) { h . rw . Lock ( ) h . hist . RecordValue ( v ) h . rw . Unlock ( ) }

// RecordValue records the given value to a histogram instance


func (cm *CheckManager) checkBundleSearch(criteria string, filter map[string][]string) (*api.CheckBundle, error) {
	search := api.SearchQueryType(criteria)
	checkBundles, err := cm.apih.SearchCheckBundles(&search, &filter)
	if err != nil {
		return nil, err
	}

	if len(*checkBundles) == 0 {
		return nil, nil // trigger creation of a new check
	}

	numActive := 0
	checkID := -1

	for idx, check := range *checkBundles {
		if check.Status == statusActive {
			numActive++
			checkID = idx
		}
	}

	if numActive > 1 {
		return nil, fmt.Errorf("[ERROR] multiple check bundles match criteria %s", criteria)
	}

	bundle := (*checkBundles)[checkID]

	return &bundle, nil
}

func
(
cm
*
CheckManager
)
checkBundleSearch
(
criteria
string
,
filter
map
[
string
]
[
]
string
)
(
*
api
.
CheckBundle
,
error
)
{
search
:=
api
.
SearchQueryType
(
criteria
)
checkBundles
,
err
:=
cm
.
apih
.
SearchCheckBundles
(
&
search
,
&
filter
)
if
err
!=
{
return
,
err
}
if
len
(
*
checkBundles
)
==
0
{
return
,
// trigger creation of a new check
}
numActive
:=
0
checkID
:=
1
for
idx
,
check
:=
range
*
checkBundles
{
if
check
.
Status
==
statusActive
{
numActive
++
checkID
=
idx
}
}
if
numActive
>
1
{
return
,
fmt
.
Errorf
(
"
"
,
criteria
)
}
bundle
:=
(
*
checkBundles
)
[
checkID
]
return
&
bundle
,
}

// Search for a check bundle given a predetermined set of criteria


func (cm *CheckManager) createNewCheck() (*api.CheckBundle, *api.Broker, error) {
	checkSecret := string(cm.checkSecret)
	if checkSecret == "" {
		secret, err := cm.makeSecret()
		if err != nil {
			secret = "myS3cr3t"
		}
		checkSecret = secret
	}

	broker, err := cm.getBroker()
	if err != nil {
		return nil, nil, err
	}

	chkcfg := &api.CheckBundle{
		Brokers:     []string{broker.CID},
		Config:      make(map[config.Key]string),
		DisplayName: string(cm.checkDisplayName),
		Metrics:     []api.CheckBundleMetric{},
		MetricLimit: config.DefaultCheckBundleMetricLimit,
		Notes:       cm.getNotes(),
		Period:      60,
		Status:      statusActive,
		Tags:        append(cm.checkSearchTag, cm.checkTags...),
		Target:      string(cm.checkTarget),
		Timeout:     10,
		Type:        string(cm.checkType),
	}

	if len(cm.customConfigFields) > 0 {
		for fld, val := range cm.customConfigFields {
			chkcfg.Config[config.Key(fld)] = val
		}
	}

	//
	// use the default config settings if these are NOT set by user configuration
	//
	if val, ok := chkcfg.Config[config.AsyncMetrics]; !ok || val == "" {
		chkcfg.Config[config.AsyncMetrics] = "true"
	}

	if val, ok := chkcfg.Config[config.Secret]; !ok || val == "" {
		chkcfg.Config[config.Secret] = checkSecret
	}

	checkBundle, err := cm.apih.CreateCheckBundle(chkcfg)
	if err != nil {
		return nil, nil, err
	}

	return checkBundle, broker, nil
}

// Create a new check to receive metrics


func (cm *CheckManager) makeSecret() (string, error) {
	hash := sha256.New()
	x := make([]byte, 2048)
	if _, err := rand.Read(x); err != nil {
		return "", err
	}
	hash.Write(x)
	return hex.EncodeToString(hash.Sum(nil))[0:16], nil
}

func ( cm * CheckManager ) makeSecret ( ) ( string , error ) { hash := sha256 . New ( ) x := make ( [ ] byte , 2048 ) if _ , err := rand . Read ( x ) ; err != nil { return " " , err } hash . Write ( x ) return hex . EncodeToString ( hash . Sum ( nil ) ) [ 0 : 16 ] , nil }

// Create a dynamic secret to use with a new check


func (cm *CheckManager) fetchCheckBySubmissionURL(submissionURL api.URLType) (*api.Check, error) {
	if string(submissionURL) == "" {
		return nil, errors.New("[ERROR] Invalid submission URL (blank)")
	}

	u, err := url.Parse(string(submissionURL))
	if err != nil {
		return nil, err
	}

	// valid trap url: scheme://host[:port]/module/httptrap/UUID/secret

	// does it smell like a valid trap url path
	if !strings.Contains(u.Path, "/module/httptrap/") {
		return nil, fmt.Errorf("[ERROR] Invalid submission URL '%s', unrecognized path", submissionURL)
	}

	// extract uuid
	pathParts := strings.Split(strings.Replace(u.Path, "/module/httptrap/", "", 1), "/")
	if len(pathParts) != 2 {
		return nil, fmt.Errorf("[ERROR] Invalid submission URL '%s', UUID not where expected", submissionURL)
	}
	uuid := pathParts[0]

	filter := api.SearchFilterType{"f__check_uuid": []string{uuid}}

	checks, err := cm.apih.SearchChecks(nil, &filter)
	if err != nil {
		return nil, err
	}

	if len(*checks) == 0 {
		return nil, fmt.Errorf("[ERROR] No checks found with UUID %s", uuid)
	}

	numActive := 0
	checkID := -1

	for idx, check := range *checks {
		if check.Active {
			numActive++
			checkID = idx
		}
	}

	if numActive > 1 {
		return nil, fmt.Errorf("[ERROR] Multiple checks with same UUID %s", uuid)
	}

	check := (*checks)[checkID]

	return &check, nil

}

// FetchCheckBySubmissionURL fetch a check configuration by submission_url


func (cm *CheckManager) Initialize() {

	// if not managing the check, quicker initialization
	if !cm.enabled {
		err := cm.initializeTrapURL()
		if err == nil {
			cm.initializedmu.Lock()
			cm.initialized = true
			cm.initializedmu.Unlock()
		} else {
			cm.Log.Printf("[WARN] error initializing trap %s", err.Error())
		}
		return
	}

	// background initialization when we have to reach out to the api
	go func() {
		cm.apih.EnableExponentialBackoff()
		err := cm.initializeTrapURL()
		if err == nil {
			cm.initializedmu.Lock()
			cm.initialized = true
			cm.initializedmu.Unlock()
		} else {
			cm.Log.Printf("[WARN] error initializing trap %s", err.Error())
		}
		cm.apih.DisableExponentialBackoff()
	}()
}


func (cm *CheckManager) IsReady() bool {
	cm.initializedmu.RLock()
	defer cm.initializedmu.RUnlock()
	return cm.initialized
}

func ( cm * CheckManager ) IsReady ( ) bool { cm . initializedmu . RLock ( ) defer cm . initializedmu . RUnlock ( ) return cm . initialized }

// IsReady reflects if the check has been initialied and metrics can be sent to Circonus


func (cm *CheckManager) GetSubmissionURL() (*Trap, error) {
	if cm.trapURL == "" {
		return nil, errors.Errorf("get submission url - submission url unavailable")
	}

	trap := &Trap{}

	u, err := url.Parse(string(cm.trapURL))
	if err != nil {
		return nil, errors.Wrap(err, "get submission url")
	}
	trap.URL = u

	if u.Scheme == "http+unix" {
		service := "circonus-agent"
		sockPath := ""
		metricID := ""

		subNames := cm.sockRx.SubexpNames()
		matches := cm.sockRx.FindAllStringSubmatch(string(cm.trapURL), -1)
		for _, match := range matches {
			for idx, val := range match {
				switch subNames[idx] {
				case "sockfile":
					sockPath = val
				case "id":
					metricID = val
				}
			}
		}

		if sockPath == "" || metricID == "" {
			return nil, errors.Errorf("get submission url - invalid socket url (%s)", cm.trapURL)
		}

		u, err = url.Parse(fmt.Sprintf("http+unix://%s/write/%s", service, metricID))
		if err != nil {
			return nil, errors.Wrap(err, "get submission url")
		}
		trap.URL = u

		trap.SockTransport = &httpunix.Transport{
			DialTimeout:           100 * time.Millisecond,
			RequestTimeout:        1 * time.Second,
			ResponseHeaderTimeout: 1 * time.Second,
		}
		trap.SockTransport.RegisterLocation(service, sockPath)
		trap.IsSocket = true
	}

	if u.Scheme == "https" {
		// preference user-supplied TLS configuration
		if cm.brokerTLS != nil {
			trap.TLS = cm.brokerTLS
			return trap, nil
		}

		// api.circonus.com uses a public CA signed certificate
		// trap.noit.circonus.net uses Circonus CA private certificate
		// enterprise brokers use private CA certificate
		if trap.URL.Hostname() == "api.circonus.com" {
			return trap, nil
		}

		if cm.certPool == nil {
			if err := cm.loadCACert(); err != nil {
				return nil, errors.Wrap(err, "get submission url")
			}
		}
		t := &tls.Config{
			RootCAs: cm.certPool,
		}
		if cm.trapCN != "" {
			t.ServerName = string(cm.trapCN)
		}
		trap.TLS = t
	}

	return trap, nil
}

// GetSubmissionURL returns submission url for circonus


func (cm *CheckManager) ResetTrap() error {
	if cm.trapURL == "" {
		return nil
	}

	cm.trapURL = ""
	cm.certPool = nil // force re-fetching CA cert (if custom TLS config not supplied)
	return cm.initializeTrapURL()
}

// ResetTrap URL, force request to the API for the submission URL and broker ca cert

ResetTrap URL force request to the API for the submission URL and broker ca cert


func (cm *CheckManager) RefreshTrap() error {
	if cm.trapURL == "" {
		return nil
	}

	if time.Since(cm.trapLastUpdate) >= cm.trapMaxURLAge {
		return cm.ResetTrap()
	}

	return nil
}

func ( cm * CheckManager ) RefreshTrap ( ) error { if cm . trapURL == " " { return nil } if time . Since ( cm . trapLastUpdate ) >= cm . trapMaxURLAge { return cm . ResetTrap ( ) } return nil }

// RefreshTrap check when the last time the URL was reset, reset if needed

RefreshTrap check when the last time the URL was reset reset if needed


func (a *API) FetchRuleSetGroup(cid CIDType) (*RuleSetGroup, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid rule set group CID [none]")
	}

	groupCID := string(*cid)

	matched, err := regexp.MatchString(config.RuleSetGroupCIDRegex, groupCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid rule set group CID [%s]", groupCID)
	}

	result, err := a.Get(groupCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch rule set group, received JSON: %s", string(result))
	}

	rulesetGroup := &RuleSetGroup{}
	if err := json.Unmarshal(result, rulesetGroup); err != nil {
		return nil, err
	}

	return rulesetGroup, nil
}

func ( a * API ) FetchRuleSetGroup ( cid CIDType ) ( * RuleSetGroup , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } groupCID := string ( * cid ) matched , err := regexp . MatchString ( config . RuleSetGroupCIDRegex , groupCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , groupCID ) } result , err := a . Get ( groupCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } rulesetGroup := & RuleSetGroup { } if err := json . Unmarshal ( result , rulesetGroup ) ; err != nil { return nil , err } return rulesetGroup , nil }

// FetchRuleSetGroup retrieves rule set group with passed cid.

FetchRuleSetGroup retrieves rule set group with passed cid .


func (a *API) FetchRuleSetGroups() (*[]RuleSetGroup, error) {
	result, err := a.Get(config.RuleSetGroupPrefix)
	if err != nil {
		return nil, err
	}

	var rulesetGroups []RuleSetGroup
	if err := json.Unmarshal(result, &rulesetGroups); err != nil {
		return nil, err
	}

	return &rulesetGroups, nil
}

func ( a * API ) FetchRuleSetGroups ( ) ( * [ ] RuleSetGroup , error ) { result , err := a . Get ( config . RuleSetGroupPrefix ) if err != nil { return nil , err } var rulesetGroups [ ] RuleSetGroup if err := json . Unmarshal ( result , & rulesetGroups ) ; err != nil { return nil , err } return & rulesetGroups , nil }

// FetchRuleSetGroups retrieves all rule set groups available to API Token.

FetchRuleSetGroups retrieves all rule set groups available to API Token .


func (a *API) UpdateRuleSetGroup(cfg *RuleSetGroup) (*RuleSetGroup, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid rule set group config [nil]")
	}

	groupCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.RuleSetGroupCIDRegex, groupCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid rule set group CID [%s]", groupCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update rule set group, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(groupCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	groups := &RuleSetGroup{}
	if err := json.Unmarshal(result, groups); err != nil {
		return nil, err
	}

	return groups, nil
}

func ( a * API ) UpdateRuleSetGroup ( cfg * RuleSetGroup ) ( * RuleSetGroup , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } groupCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . RuleSetGroupCIDRegex , groupCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , groupCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( groupCID , jsonCfg ) if err != nil { return nil , err } groups := & RuleSetGroup { } if err := json . Unmarshal ( result , groups ) ; err != nil { return nil , err } return groups , nil }

// UpdateRuleSetGroup updates passed rule set group.

UpdateRuleSetGroup updates passed rule set group .


func (a *API) CreateRuleSetGroup(cfg *RuleSetGroup) (*RuleSetGroup, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid rule set group config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create rule set group, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.RuleSetGroupPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	group := &RuleSetGroup{}
	if err := json.Unmarshal(result, group); err != nil {
		return nil, err
	}

	return group, nil
}

func ( a * API ) CreateRuleSetGroup ( cfg * RuleSetGroup ) ( * RuleSetGroup , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . RuleSetGroupPrefix , jsonCfg ) if err != nil { return nil , err } group := & RuleSetGroup { } if err := json . Unmarshal ( result , group ) ; err != nil { return nil , err } return group , nil }

// CreateRuleSetGroup creates a new rule set group.

CreateRuleSetGroup creates a new rule set group .


func (a *API) DeleteRuleSetGroup(cfg *RuleSetGroup) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid rule set group config [nil]")
	}
	return a.DeleteRuleSetGroupByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteRuleSetGroup ( cfg * RuleSetGroup ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteRuleSetGroupByCID ( CIDType ( & cfg . CID ) ) }

// DeleteRuleSetGroup deletes passed rule set group.

DeleteRuleSetGroup deletes passed rule set group .


func (a *API) DeleteRuleSetGroupByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid rule set group CID [none]")
	}

	groupCID := string(*cid)

	matched, err := regexp.MatchString(config.RuleSetGroupCIDRegex, groupCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid rule set group CID [%s]", groupCID)
	}

	_, err = a.Delete(groupCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteRuleSetGroupByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } groupCID := string ( * cid ) matched , err := regexp . MatchString ( config . RuleSetGroupCIDRegex , groupCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , groupCID ) } _ , err = a . Delete ( groupCID ) if err != nil { return false , err } return true , nil }

// DeleteRuleSetGroupByCID deletes rule set group with passed cid.

DeleteRuleSetGroupByCID deletes rule set group with passed cid .


func (a *API) FetchDashboard(cid CIDType) (*Dashboard, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid dashboard CID [none]")
	}

	dashboardCID := string(*cid)

	matched, err := regexp.MatchString(config.DashboardCIDRegex, dashboardCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid dashboard CID [%s]", dashboardCID)
	}

	result, err := a.Get(string(*cid))
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch dashboard, received JSON: %s", string(result))
	}

	dashboard := new(Dashboard)
	if err := json.Unmarshal(result, dashboard); err != nil {
		return nil, err
	}

	return dashboard, nil
}

func ( a * API ) FetchDashboard ( cid CIDType ) ( * Dashboard , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } dashboardCID := string ( * cid ) matched , err := regexp . MatchString ( config . DashboardCIDRegex , dashboardCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , dashboardCID ) } result , err := a . Get ( string ( * cid ) ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } dashboard := new ( Dashboard ) if err := json . Unmarshal ( result , dashboard ) ; err != nil { return nil , err } return dashboard , nil }

// FetchDashboard retrieves dashboard with passed cid.

FetchDashboard retrieves dashboard with passed cid .


func (a *API) FetchDashboards() (*[]Dashboard, error) {
	result, err := a.Get(config.DashboardPrefix)
	if err != nil {
		return nil, err
	}

	var dashboards []Dashboard
	if err := json.Unmarshal(result, &dashboards); err != nil {
		return nil, err
	}

	return &dashboards, nil
}

func ( a * API ) FetchDashboards ( ) ( * [ ] Dashboard , error ) { result , err := a . Get ( config . DashboardPrefix ) if err != nil { return nil , err } var dashboards [ ] Dashboard if err := json . Unmarshal ( result , & dashboards ) ; err != nil { return nil , err } return & dashboards , nil }

// FetchDashboards retrieves all dashboards available to the API Token.

FetchDashboards retrieves all dashboards available to the API Token .


func (a *API) UpdateDashboard(cfg *Dashboard) (*Dashboard, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid dashboard config [nil]")
	}

	dashboardCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.DashboardCIDRegex, dashboardCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid dashboard CID [%s]", dashboardCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update dashboard, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(dashboardCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	dashboard := &Dashboard{}
	if err := json.Unmarshal(result, dashboard); err != nil {
		return nil, err
	}

	return dashboard, nil
}

func ( a * API ) UpdateDashboard ( cfg * Dashboard ) ( * Dashboard , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } dashboardCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . DashboardCIDRegex , dashboardCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , dashboardCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( dashboardCID , jsonCfg ) if err != nil { return nil , err } dashboard := & Dashboard { } if err := json . Unmarshal ( result , dashboard ) ; err != nil { return nil , err } return dashboard , nil }

// UpdateDashboard updates passed dashboard.

UpdateDashboard updates passed dashboard .


func (a *API) CreateDashboard(cfg *Dashboard) (*Dashboard, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid dashboard config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create dashboard, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.DashboardPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	dashboard := &Dashboard{}
	if err := json.Unmarshal(result, dashboard); err != nil {
		return nil, err
	}

	return dashboard, nil
}

func ( a * API ) CreateDashboard ( cfg * Dashboard ) ( * Dashboard , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . DashboardPrefix , jsonCfg ) if err != nil { return nil , err } dashboard := & Dashboard { } if err := json . Unmarshal ( result , dashboard ) ; err != nil { return nil , err } return dashboard , nil }

// CreateDashboard creates a new dashboard.

CreateDashboard creates a new dashboard .


func (a *API) DeleteDashboard(cfg *Dashboard) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid dashboard config [nil]")
	}
	return a.DeleteDashboardByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteDashboard ( cfg * Dashboard ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteDashboardByCID ( CIDType ( & cfg . CID ) ) }

// DeleteDashboard deletes passed dashboard.

DeleteDashboard deletes passed dashboard .


func (a *API) DeleteDashboardByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid dashboard CID [none]")
	}

	dashboardCID := string(*cid)

	matched, err := regexp.MatchString(config.DashboardCIDRegex, dashboardCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid dashboard CID [%s]", dashboardCID)
	}

	_, err = a.Delete(dashboardCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteDashboardByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } dashboardCID := string ( * cid ) matched , err := regexp . MatchString ( config . DashboardCIDRegex , dashboardCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , dashboardCID ) } _ , err = a . Delete ( dashboardCID ) if err != nil { return false , err } return true , nil }

// DeleteDashboardByCID deletes dashboard with passed cid.

DeleteDashboardByCID deletes dashboard with passed cid .


func (m *CirconusMetrics) SetText(metric string, val string) {
	m.SetTextValue(metric, val)
}

func ( m * CirconusMetrics ) SetText ( metric string , val string ) { m . SetTextValue ( metric , val ) }

// A Text metric is an arbitrary string
//
// SetText sets a text metric

A Text metric is an arbitrary string SetText sets a text metric


func (m *CirconusMetrics) SetTextValue(metric string, val string) {
	m.tm.Lock()
	defer m.tm.Unlock()
	m.text[metric] = val
}

func ( m * CirconusMetrics ) SetTextValue ( metric string , val string ) { m . tm . Lock ( ) defer m . tm . Unlock ( ) m . text [ metric ] = val }


func (m *CirconusMetrics) RemoveText(metric string) {
	m.tm.Lock()
	defer m.tm.Unlock()
	delete(m.text, metric)
}

func ( m * CirconusMetrics ) RemoveText ( metric string ) { m . tm . Lock ( ) defer m . tm . Unlock ( ) delete ( m . text , metric ) }


func (m *CirconusMetrics) RemoveTextFunc(metric string) {
	m.tfm.Lock()
	defer m.tfm.Unlock()
	delete(m.textFuncs, metric)
}

func ( m * CirconusMetrics ) RemoveTextFunc ( metric string ) { m . tfm . Lock ( ) defer m . tfm . Unlock ( ) delete ( m . textFuncs , metric ) }

// RemoveTextFunc a text metric function


func (a *API) FetchAlert(cid CIDType) (*Alert, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid alert CID [none]")
	}

	alertCID := string(*cid)

	matched, err := regexp.MatchString(config.AlertCIDRegex, alertCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid alert CID [%s]", alertCID)
	}

	result, err := a.Get(alertCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch alert, received JSON: %s", string(result))
	}

	alert := &Alert{}
	if err := json.Unmarshal(result, alert); err != nil {
		return nil, err
	}

	return alert, nil
}

func ( a * API ) FetchAlert ( cid CIDType ) ( * Alert , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } alertCID := string ( * cid ) matched , err := regexp . MatchString ( config . AlertCIDRegex , alertCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , alertCID ) } result , err := a . Get ( alertCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } alert := & Alert { } if err := json . Unmarshal ( result , alert ) ; err != nil { return nil , err } return alert , nil }

// FetchAlert retrieves alert with passed cid.

FetchAlert retrieves alert with passed cid .


func (a *API) FetchAlerts() (*[]Alert, error) {
	result, err := a.Get(config.AlertPrefix)
	if err != nil {
		return nil, err
	}

	var alerts []Alert
	if err := json.Unmarshal(result, &alerts); err != nil {
		return nil, err
	}

	return &alerts, nil
}

func ( a * API ) FetchAlerts ( ) ( * [ ] Alert , error ) { result , err := a . Get ( config . AlertPrefix ) if err != nil { return nil , err } var alerts [ ] Alert if err := json . Unmarshal ( result , & alerts ) ; err != nil { return nil , err } return & alerts , nil }

// FetchAlerts retrieves all alerts available to the API Token.

FetchAlerts retrieves all alerts available to the API Token .


func (a *API) FetchRuleSet(cid CIDType) (*RuleSet, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid rule set CID [none]")
	}

	rulesetCID := string(*cid)

	matched, err := regexp.MatchString(config.RuleSetCIDRegex, rulesetCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid rule set CID [%s]", rulesetCID)
	}

	result, err := a.Get(rulesetCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch rule set, received JSON: %s", string(result))
	}

	ruleset := &RuleSet{}
	if err := json.Unmarshal(result, ruleset); err != nil {
		return nil, err
	}

	return ruleset, nil
}

func ( a * API ) FetchRuleSet ( cid CIDType ) ( * RuleSet , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } rulesetCID := string ( * cid ) matched , err := regexp . MatchString ( config . RuleSetCIDRegex , rulesetCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , rulesetCID ) } result , err := a . Get ( rulesetCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } ruleset := & RuleSet { } if err := json . Unmarshal ( result , ruleset ) ; err != nil { return nil , err } return ruleset , nil }

// FetchRuleSet retrieves rule set with passed cid.

FetchRuleSet retrieves rule set with passed cid .


func (a *API) FetchRuleSets() (*[]RuleSet, error) {
	result, err := a.Get(config.RuleSetPrefix)
	if err != nil {
		return nil, err
	}

	var rulesets []RuleSet
	if err := json.Unmarshal(result, &rulesets); err != nil {
		return nil, err
	}

	return &rulesets, nil
}

func ( a * API ) FetchRuleSets ( ) ( * [ ] RuleSet , error ) { result , err := a . Get ( config . RuleSetPrefix ) if err != nil { return nil , err } var rulesets [ ] RuleSet if err := json . Unmarshal ( result , & rulesets ) ; err != nil { return nil , err } return & rulesets , nil }

// FetchRuleSets retrieves all rule sets available to API Token.

FetchRuleSets retrieves all rule sets available to API Token .


func (a *API) UpdateRuleSet(cfg *RuleSet) (*RuleSet, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid rule set config [nil]")
	}

	rulesetCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.RuleSetCIDRegex, rulesetCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid rule set CID [%s]", rulesetCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update rule set, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(rulesetCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	ruleset := &RuleSet{}
	if err := json.Unmarshal(result, ruleset); err != nil {
		return nil, err
	}

	return ruleset, nil
}

func ( a * API ) UpdateRuleSet ( cfg * RuleSet ) ( * RuleSet , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } rulesetCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . RuleSetCIDRegex , rulesetCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , rulesetCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( rulesetCID , jsonCfg ) if err != nil { return nil , err } ruleset := & RuleSet { } if err := json . Unmarshal ( result , ruleset ) ; err != nil { return nil , err } return ruleset , nil }

// UpdateRuleSet updates passed rule set.


func (a *API) CreateRuleSet(cfg *RuleSet) (*RuleSet, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid rule set config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create rule set, sending JSON: %s", string(jsonCfg))
	}

	resp, err := a.Post(config.RuleSetPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	ruleset := &RuleSet{}
	if err := json.Unmarshal(resp, ruleset); err != nil {
		return nil, err
	}

	return ruleset, nil
}

func ( a * API ) CreateRuleSet ( cfg * RuleSet ) ( * RuleSet , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } resp , err := a . Post ( config . RuleSetPrefix , jsonCfg ) if err != nil { return nil , err } ruleset := & RuleSet { } if err := json . Unmarshal ( resp , ruleset ) ; err != nil { return nil , err } return ruleset , nil }

// CreateRuleSet creates a new rule set.


func (a *API) DeleteRuleSet(cfg *RuleSet) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid rule set config [nil]")
	}
	return a.DeleteRuleSetByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteRuleSet ( cfg * RuleSet ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteRuleSetByCID ( CIDType ( & cfg . CID ) ) }

// DeleteRuleSet deletes passed rule set.


func (a *API) DeleteRuleSetByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid rule set CID [none]")
	}

	rulesetCID := string(*cid)

	matched, err := regexp.MatchString(config.RuleSetCIDRegex, rulesetCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid rule set CID [%s]", rulesetCID)
	}

	_, err = a.Delete(rulesetCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteRuleSetByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } rulesetCID := string ( * cid ) matched , err := regexp . MatchString ( config . RuleSetCIDRegex , rulesetCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , rulesetCID ) } _ , err = a . Delete ( rulesetCID ) if err != nil { return false , err } return true , nil }

// DeleteRuleSetByCID deletes rule set with passed cid.

DeleteRuleSetByCID deletes rule set with passed cid .


func (m *CirconusMetrics) IncrementByValue(metric string, val uint64) {
	m.Add(metric, val)
}

func ( m * CirconusMetrics ) IncrementByValue ( metric string , val uint64 ) { m . Add ( metric , val ) }

// IncrementByValue updates counter by supplied value


func (m *CirconusMetrics) Set(metric string, val uint64) {
	m.cm.Lock()
	defer m.cm.Unlock()
	m.counters[metric] = val
}

func ( m * CirconusMetrics ) Set ( metric string , val uint64 ) { m . cm . Lock ( ) defer m . cm . Unlock ( ) m . counters [ metric ] = val }


func (m *CirconusMetrics) RemoveCounter(metric string) {
	m.cm.Lock()
	defer m.cm.Unlock()
	delete(m.counters, metric)
}

func ( m * CirconusMetrics ) RemoveCounter ( metric string ) { m . cm . Lock ( ) defer m . cm . Unlock ( ) delete ( m . counters , metric ) }

// RemoveCounter removes the named counter


func (m *CirconusMetrics) RemoveCounterFunc(metric string) {
	m.cfm.Lock()
	defer m.cfm.Unlock()
	delete(m.counterFuncs, metric)
}

func ( m * CirconusMetrics ) RemoveCounterFunc ( metric string ) { m . cfm . Lock ( ) defer m . cfm . Unlock ( ) delete ( m . counterFuncs , metric ) }

// RemoveCounterFunc removes the named counter function


func (m *CirconusMetrics) PromOutput() (*bytes.Buffer, error) {
	m.lastMetrics.metricsmu.Lock()
	defer m.lastMetrics.metricsmu.Unlock()

	if m.lastMetrics.metrics == nil {
		return nil, errors.New("no metrics available")
	}

	var b bytes.Buffer
	w := bufio.NewWriter(&b)

	ts := m.lastMetrics.ts.UnixNano() / int64(time.Millisecond)

	for name, metric := range *m.lastMetrics.metrics {
		switch metric.Type {
		case "n":
			if strings.HasPrefix(fmt.Sprintf("%v", metric.Value), "[H[") {
				continue // circonus histogram != prom "histogram" (aka percentile)
			}
		case "s":
			continue // text metrics unsupported
		}
		fmt.Fprintf(w, "%s %v %d\n", name, metric.Value, ts)
	}

	err := w.Flush()
	if err != nil {
		return nil, errors.Wrap(err, "flushing metric buffer")
	}

	return &b, err
}

// PromOutput returns lines of metrics in prom format


func (m *CirconusMetrics) Flush() {
	m.flushmu.Lock()
	if m.flushing {
		m.flushmu.Unlock()
		return
	}

	m.flushing = true
	m.flushmu.Unlock()

	newMetrics, output := m.packageMetrics()

	if len(output) > 0 {
		m.submit(output, newMetrics)
	} else {
		if m.Debug {
			m.Log.Println("[DEBUG] No metrics to send, skipping")
		}
	}

	m.flushmu.Lock()
	m.flushing = false
	m.flushmu.Unlock()
}

func ( m * CirconusMetrics ) Flush ( ) { m . flushmu . Lock ( ) if m . flushing { m . flushmu . Unlock ( ) return } m . flushing = true m . flushmu . Unlock ( ) newMetrics , output := m . packageMetrics ( ) if len ( output ) > 0 { m . submit ( output , newMetrics ) } else { if m . Debug { m . Log . Println ( " " ) } } m . flushmu . Lock ( ) m . flushing = false m . flushmu . Unlock ( ) }

// Flush metrics kicks off the process of sending metrics to Circonus


func (a *API) FetchWorksheet(cid CIDType) (*Worksheet, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid worksheet CID [none]")
	}

	worksheetCID := string(*cid)

	matched, err := regexp.MatchString(config.WorksheetCIDRegex, worksheetCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid worksheet CID [%s]", worksheetCID)
	}

	result, err := a.Get(string(*cid))
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch worksheet, received JSON: %s", string(result))
	}

	worksheet := new(Worksheet)
	if err := json.Unmarshal(result, worksheet); err != nil {
		return nil, err
	}

	return worksheet, nil
}

func ( a * API ) FetchWorksheet ( cid CIDType ) ( * Worksheet , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } worksheetCID := string ( * cid ) matched , err := regexp . MatchString ( config . WorksheetCIDRegex , worksheetCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , worksheetCID ) } result , err := a . Get ( string ( * cid ) ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } worksheet := new ( Worksheet ) if err := json . Unmarshal ( result , worksheet ) ; err != nil { return nil , err } return worksheet , nil }

// FetchWorksheet retrieves worksheet with passed cid.

FetchWorksheet retrieves worksheet with passed cid .


func (a *API) FetchWorksheets() (*[]Worksheet, error) {
	result, err := a.Get(config.WorksheetPrefix)
	if err != nil {
		return nil, err
	}

	var worksheets []Worksheet
	if err := json.Unmarshal(result, &worksheets); err != nil {
		return nil, err
	}

	return &worksheets, nil
}

func ( a * API ) FetchWorksheets ( ) ( * [ ] Worksheet , error ) { result , err := a . Get ( config . WorksheetPrefix ) if err != nil { return nil , err } var worksheets [ ] Worksheet if err := json . Unmarshal ( result , & worksheets ) ; err != nil { return nil , err } return & worksheets , nil }

// FetchWorksheets retrieves all worksheets available to API Token.

FetchWorksheets retrieves all worksheets available to API Token .


func (a *API) UpdateWorksheet(cfg *Worksheet) (*Worksheet, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid worksheet config [nil]")
	}

	worksheetCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.WorksheetCIDRegex, worksheetCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid worksheet CID [%s]", worksheetCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update worksheet, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(worksheetCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	worksheet := &Worksheet{}
	if err := json.Unmarshal(result, worksheet); err != nil {
		return nil, err
	}

	return worksheet, nil
}

func ( a * API ) UpdateWorksheet ( cfg * Worksheet ) ( * Worksheet , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } worksheetCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . WorksheetCIDRegex , worksheetCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , worksheetCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( worksheetCID , jsonCfg ) if err != nil { return nil , err } worksheet := & Worksheet { } if err := json . Unmarshal ( result , worksheet ) ; err != nil { return nil , err } return worksheet , nil }

// UpdateWorksheet updates passed worksheet.

UpdateWorksheet updates passed worksheet .


func (a *API) CreateWorksheet(cfg *Worksheet) (*Worksheet, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid worksheet config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create annotation, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.WorksheetPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	worksheet := &Worksheet{}
	if err := json.Unmarshal(result, worksheet); err != nil {
		return nil, err
	}

	return worksheet, nil
}

func ( a * API ) CreateWorksheet ( cfg * Worksheet ) ( * Worksheet , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . WorksheetPrefix , jsonCfg ) if err != nil { return nil , err } worksheet := & Worksheet { } if err := json . Unmarshal ( result , worksheet ) ; err != nil { return nil , err } return worksheet , nil }

// CreateWorksheet creates a new worksheet.

CreateWorksheet creates a new worksheet .


func (a *API) DeleteWorksheet(cfg *Worksheet) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid worksheet config [nil]")
	}
	return a.DeleteWorksheetByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteWorksheet ( cfg * Worksheet ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteWorksheetByCID ( CIDType ( & cfg . CID ) ) }

// DeleteWorksheet deletes passed worksheet.

DeleteWorksheet deletes passed worksheet .


func (a *API) DeleteWorksheetByCID(cid CIDType) (bool, error) {
	if cid == nil || *cid == "" {
		return false, fmt.Errorf("Invalid worksheet CID [none]")
	}

	worksheetCID := string(*cid)

	matched, err := regexp.MatchString(config.WorksheetCIDRegex, worksheetCID)
	if err != nil {
		return false, err
	}
	if !matched {
		return false, fmt.Errorf("Invalid worksheet CID [%s]", worksheetCID)
	}

	_, err = a.Delete(worksheetCID)
	if err != nil {
		return false, err
	}

	return true, nil
}

func ( a * API ) DeleteWorksheetByCID ( cid CIDType ) ( bool , error ) { if cid == nil || * cid == " " { return false , fmt . Errorf ( " " ) } worksheetCID := string ( * cid ) matched , err := regexp . MatchString ( config . WorksheetCIDRegex , worksheetCID ) if err != nil { return false , err } if ! matched { return false , fmt . Errorf ( " " , worksheetCID ) } _ , err = a . Delete ( worksheetCID ) if err != nil { return false , err } return true , nil }

// DeleteWorksheetByCID deletes worksheet with passed cid.

DeleteWorksheetByCID deletes worksheet with passed cid .


func (a *API) FetchContactGroup(cid CIDType) (*ContactGroup, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid contact group CID [none]")
	}

	groupCID := string(*cid)

	matched, err := regexp.MatchString(config.ContactGroupCIDRegex, groupCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid contact group CID [%s]", groupCID)
	}

	result, err := a.Get(groupCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch contact group, received JSON: %s", string(result))
	}

	group := new(ContactGroup)
	if err := json.Unmarshal(result, group); err != nil {
		return nil, err
	}

	return group, nil
}

func ( a * API ) FetchContactGroup ( cid CIDType ) ( * ContactGroup , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } groupCID := string ( * cid ) matched , err := regexp . MatchString ( config . ContactGroupCIDRegex , groupCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , groupCID ) } result , err := a . Get ( groupCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } group := new ( ContactGroup ) if err := json . Unmarshal ( result , group ) ; err != nil { return nil , err } return group , nil }

// FetchContactGroup retrieves contact group with passed cid.

FetchContactGroup retrieves contact group with passed cid .


func (a *API) FetchContactGroups() (*[]ContactGroup, error) {
	result, err := a.Get(config.ContactGroupPrefix)
	if err != nil {
		return nil, err
	}

	var groups []ContactGroup
	if err := json.Unmarshal(result, &groups); err != nil {
		return nil, err
	}

	return &groups, nil
}

func ( a * API ) FetchContactGroups ( ) ( * [ ] ContactGroup , error ) { result , err := a . Get ( config . ContactGroupPrefix ) if err != nil { return nil , err } var groups [ ] ContactGroup if err := json . Unmarshal ( result , & groups ) ; err != nil { return nil , err } return & groups , nil }

// FetchContactGroups retrieves all contact groups available to the API Token.

FetchContactGroups retrieves all contact groups available to the API Token .


func (a *API) UpdateContactGroup(cfg *ContactGroup) (*ContactGroup, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid contact group config [nil]")
	}

	groupCID := string(cfg.CID)

	matched, err := regexp.MatchString(config.ContactGroupCIDRegex, groupCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid contact group CID [%s]", groupCID)
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] update contact group, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Put(groupCID, jsonCfg)
	if err != nil {
		return nil, err
	}

	group := &ContactGroup{}
	if err := json.Unmarshal(result, group); err != nil {
		return nil, err
	}

	return group, nil
}

func ( a * API ) UpdateContactGroup ( cfg * ContactGroup ) ( * ContactGroup , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } groupCID := string ( cfg . CID ) matched , err := regexp . MatchString ( config . ContactGroupCIDRegex , groupCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , groupCID ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Put ( groupCID , jsonCfg ) if err != nil { return nil , err } group := & ContactGroup { } if err := json . Unmarshal ( result , group ) ; err != nil { return nil , err } return group , nil }

// UpdateContactGroup updates passed contact group.

UpdateContactGroup updates passed contact group .


func (a *API) CreateContactGroup(cfg *ContactGroup) (*ContactGroup, error) {
	if cfg == nil {
		return nil, fmt.Errorf("Invalid contact group config [nil]")
	}

	jsonCfg, err := json.Marshal(cfg)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] create contact group, sending JSON: %s", string(jsonCfg))
	}

	result, err := a.Post(config.ContactGroupPrefix, jsonCfg)
	if err != nil {
		return nil, err
	}

	group := &ContactGroup{}
	if err := json.Unmarshal(result, group); err != nil {
		return nil, err
	}

	return group, nil
}

func ( a * API ) CreateContactGroup ( cfg * ContactGroup ) ( * ContactGroup , error ) { if cfg == nil { return nil , fmt . Errorf ( " " ) } jsonCfg , err := json . Marshal ( cfg ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( jsonCfg ) ) } result , err := a . Post ( config . ContactGroupPrefix , jsonCfg ) if err != nil { return nil , err } group := & ContactGroup { } if err := json . Unmarshal ( result , group ) ; err != nil { return nil , err } return group , nil }

// CreateContactGroup creates a new contact group.

CreateContactGroup creates a new contact group .


func (a *API) DeleteContactGroup(cfg *ContactGroup) (bool, error) {
	if cfg == nil {
		return false, fmt.Errorf("Invalid contact group config [nil]")
	}
	return a.DeleteContactGroupByCID(CIDType(&cfg.CID))
}

func ( a * API ) DeleteContactGroup ( cfg * ContactGroup ) ( bool , error ) { if cfg == nil { return false , fmt . Errorf ( " " ) } return a . DeleteContactGroupByCID ( CIDType ( & cfg . CID ) ) }

// DeleteContactGroup deletes passed contact group.

DeleteContactGroup deletes passed contact group .


func (a *API) FetchBroker(cid CIDType) (*Broker, error) {
	if cid == nil || *cid == "" {
		return nil, fmt.Errorf("Invalid broker CID [none]")
	}

	brokerCID := string(*cid)

	matched, err := regexp.MatchString(config.BrokerCIDRegex, brokerCID)
	if err != nil {
		return nil, err
	}
	if !matched {
		return nil, fmt.Errorf("Invalid broker CID [%s]", brokerCID)
	}

	result, err := a.Get(brokerCID)
	if err != nil {
		return nil, err
	}

	if a.Debug {
		a.Log.Printf("[DEBUG] fetch broker, received JSON: %s", string(result))
	}

	response := new(Broker)
	if err := json.Unmarshal(result, &response); err != nil {
		return nil, err
	}

	return response, nil

}

func ( a * API ) FetchBroker ( cid CIDType ) ( * Broker , error ) { if cid == nil || * cid == " " { return nil , fmt . Errorf ( " " ) } brokerCID := string ( * cid ) matched , err := regexp . MatchString ( config . BrokerCIDRegex , brokerCID ) if err != nil { return nil , err } if ! matched { return nil , fmt . Errorf ( " " , brokerCID ) } result , err := a . Get ( brokerCID ) if err != nil { return nil , err } if a . Debug { a . Log . Printf ( " " , string ( result ) ) } response := new ( Broker ) if err := json . Unmarshal ( result , & response ) ; err != nil { return nil , err } return response , nil }

// FetchBroker retrieves broker with passed cid.

FetchBroker retrieves broker with passed cid .