github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/pkg/alertmanager/merger/v1_silence_id.go (about)

     1  package merger
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  
     8  	v2_models "github.com/prometheus/alertmanager/api/v2/models"
     9  )
    10  
    11  // V1Silences implements the Merger interface for GET /v1/silences. This re-uses the logic for
    12  // merging /v2/silences, with additional handling for the enclosing status/data fields. Unlike for
    13  // alerts, the API definitions for silences are almost identical between v1 and v2. The differences
    14  // are that the fields in the JSON output are ordered differently, and the timestamps have more
    15  // precision in v1, but these differences should not be problematic to clients.
    16  type V1SilenceID struct{}
    17  
    18  func (V1SilenceID) MergeResponses(in [][]byte) ([]byte, error) {
    19  	type bodyType struct {
    20  		Status string                     `json:"status"`
    21  		Data   *v2_models.GettableSilence `json:"data"`
    22  	}
    23  
    24  	silences := make(v2_models.GettableSilences, 0)
    25  	for _, body := range in {
    26  		parsed := bodyType{}
    27  		if err := json.Unmarshal(body, &parsed); err != nil {
    28  			return nil, err
    29  		}
    30  		if parsed.Status != statusSuccess {
    31  			return nil, fmt.Errorf("unable to merge response of status: %s", parsed.Status)
    32  		}
    33  		silences = append(silences, parsed.Data)
    34  	}
    35  
    36  	merged, err := mergeV2Silences(silences)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	if len(merged) != 1 {
    42  		return nil, errors.New("unexpected mismatched silence ids")
    43  	}
    44  
    45  	body := bodyType{
    46  		Status: statusSuccess,
    47  		Data:   merged[0],
    48  	}
    49  
    50  	return json.Marshal(body)
    51  }