github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/aagent/watchers/metricwatcher/state_notification.go (about)

     1  // Copyright (c) 2020-2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package metricwatcher
     6  
     7  import (
     8  	"encoding/json"
     9  	"fmt"
    10  	"strings"
    11  
    12  	cloudevents "github.com/cloudevents/sdk-go/v2"
    13  
    14  	"github.com/choria-io/go-choria/aagent/watchers/event"
    15  )
    16  
    17  // StateNotification describes the current state of the watcher
    18  // described by io.choria.machine.watcher.metric.v1.state
    19  type StateNotification struct {
    20  	event.Event
    21  
    22  	Metrics Metric `json:"metrics"`
    23  }
    24  
    25  // JSON creates a JSON representation of the notification
    26  func (s *StateNotification) JSON() ([]byte, error) {
    27  	return json.Marshal(s.CloudEvent())
    28  }
    29  
    30  // CloudEvent creates a CloudEvent from the state notification
    31  func (s *StateNotification) CloudEvent() cloudevents.Event {
    32  	return s.Event.CloudEvent(s)
    33  }
    34  
    35  // String is a string representation of the notification suitable for printing
    36  func (s *StateNotification) String() string {
    37  	metrics := []string{}
    38  
    39  	for k, v := range s.Metrics.Metrics {
    40  		metrics = append(metrics, fmt.Sprintf("%s=%0.3f", k, v))
    41  	}
    42  
    43  	return fmt.Sprintf("%s %s#%s metrics: %s", s.Identity, s.Machine, s.Name, strings.Join(metrics, ", "))
    44  }