github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/pkg/util/validation/notifications_limit_flag.go (about)

     1  package validation
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  
     7  	"github.com/pkg/errors"
     8  
     9  	"github.com/cortexproject/cortex/pkg/util"
    10  )
    11  
    12  var allowedIntegrationNames = []string{
    13  	"webhook", "email", "pagerduty", "opsgenie", "wechat", "slack", "victorops", "pushover", "sns",
    14  }
    15  
    16  type NotificationRateLimitMap map[string]float64
    17  
    18  // String implements flag.Value
    19  func (m NotificationRateLimitMap) String() string {
    20  	out, err := json.Marshal(map[string]float64(m))
    21  	if err != nil {
    22  		return fmt.Sprintf("failed to marshal: %v", err)
    23  	}
    24  	return string(out)
    25  }
    26  
    27  // Set implements flag.Value
    28  func (m NotificationRateLimitMap) Set(s string) error {
    29  	newMap := map[string]float64{}
    30  	return m.updateMap(json.Unmarshal([]byte(s), &newMap), newMap)
    31  }
    32  
    33  // UnmarshalYAML implements yaml.Unmarshaler.
    34  func (m NotificationRateLimitMap) UnmarshalYAML(unmarshal func(interface{}) error) error {
    35  	newMap := map[string]float64{}
    36  	return m.updateMap(unmarshal(newMap), newMap)
    37  }
    38  
    39  func (m NotificationRateLimitMap) updateMap(unmarshalErr error, newMap map[string]float64) error {
    40  	if unmarshalErr != nil {
    41  		return unmarshalErr
    42  	}
    43  
    44  	for k, v := range newMap {
    45  		if !util.StringsContain(allowedIntegrationNames, k) {
    46  			return errors.Errorf("unknown integration name: %s", k)
    47  		}
    48  		m[k] = v
    49  	}
    50  	return nil
    51  }
    52  
    53  // MarshalYAML implements yaml.Marshaler.
    54  func (m NotificationRateLimitMap) MarshalYAML() (interface{}, error) {
    55  	return map[string]float64(m), nil
    56  }