|
| 1 | +/* |
| 2 | +Copyright 2024 The Flux authors |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package providers |
| 18 | + |
| 19 | +import ( |
| 20 | + "cmp" |
| 21 | + "context" |
| 22 | + "fmt" |
| 23 | + "io" |
| 24 | + "net/http" |
| 25 | + "slices" |
| 26 | + "strings" |
| 27 | + "time" |
| 28 | + |
| 29 | + "github.com/signalfx/signalflow-client-go/signalflow" |
| 30 | + "github.com/signalfx/signalflow-client-go/signalflow/messages" |
| 31 | + |
| 32 | + flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" |
| 33 | +) |
| 34 | + |
| 35 | +// https://dev.splunk.com/observability/reference |
| 36 | +const ( |
| 37 | + signalFxSignalFlowApiPath = "/v2/signalflow" |
| 38 | + signalFxValidationPath = "/v2/metric?limit=1" |
| 39 | + |
| 40 | + signalFxTokenSecretKey = "sf_token_key" |
| 41 | + |
| 42 | + signalFxTokenHeaderKey = "X-SF-Token" |
| 43 | + |
| 44 | + signalFxFromDeltaMultiplierOnMetricInterval = 10 |
| 45 | +) |
| 46 | + |
| 47 | +// SplunkProvider executes signalfx queries |
| 48 | +type SplunkProvider struct { |
| 49 | + metricsQueryEndpoint string |
| 50 | + apiValidationEndpoint string |
| 51 | + |
| 52 | + timeout time.Duration |
| 53 | + token string |
| 54 | + fromDelta int64 |
| 55 | +} |
| 56 | + |
| 57 | +type splunkResponse struct { |
| 58 | +} |
| 59 | + |
| 60 | +// NewSplunkProvider takes a canary spec, a provider spec and the credentials map, and |
| 61 | +// returns a Splunk client ready to execute queries against the API |
| 62 | +func NewSplunkProvider(metricInterval string, |
| 63 | + provider flaggerv1.MetricTemplateProvider, |
| 64 | + credentials map[string][]byte) (*SplunkProvider, error) { |
| 65 | + |
| 66 | + address := provider.Address |
| 67 | + if address == "" { |
| 68 | + return nil, fmt.Errorf("splunk endpoint is not set") |
| 69 | + } |
| 70 | + |
| 71 | + sp := SplunkProvider{ |
| 72 | + timeout: 5 * time.Second, |
| 73 | + // Convert the configured address to match the protocol of the respective API |
| 74 | + // ex. |
| 75 | + // https://api.<REALM>.signalfx.com -> wss://stream.<REALM>.signalfx.com |
| 76 | + // wss://stream.<REALM>.signalfx.com -> wss://stream.<REALM>.signalfx.com |
| 77 | + metricsQueryEndpoint: strings.Replace(strings.Replace(address+signalFxSignalFlowApiPath, "http", "ws", 1), "api", "stream", 1), |
| 78 | + // ex. |
| 79 | + // https://api.<REALM>.signalfx.com -> https://api.<REALM>.signalfx.com |
| 80 | + // wss://stream.<REALM>.signalfx.com -> https://api.<REALM>.signalfx.com |
| 81 | + apiValidationEndpoint: strings.Replace(strings.Replace(address+signalFxValidationPath, "ws", "http", 1), "stream", "api", 1), |
| 82 | + } |
| 83 | + |
| 84 | + if b, ok := credentials[signalFxTokenSecretKey]; ok { |
| 85 | + sp.token = string(b) |
| 86 | + } else { |
| 87 | + return nil, fmt.Errorf("splunk credentials does not contain sf_token_key") |
| 88 | + } |
| 89 | + |
| 90 | + md, err := time.ParseDuration(metricInterval) |
| 91 | + if err != nil { |
| 92 | + return nil, fmt.Errorf("error parsing metric interval: %w", err) |
| 93 | + } |
| 94 | + |
| 95 | + sp.fromDelta = int64(signalFxFromDeltaMultiplierOnMetricInterval * md.Milliseconds()) |
| 96 | + return &sp, nil |
| 97 | +} |
| 98 | + |
| 99 | +// RunQuery executes the query and converts the first result to float64 |
| 100 | +func (p *SplunkProvider) RunQuery(query string) (float64, error) { |
| 101 | + c, err := signalflow.NewClient(signalflow.StreamURL(p.metricsQueryEndpoint), signalflow.AccessToken(p.token)) |
| 102 | + if err != nil { |
| 103 | + return 0, fmt.Errorf("error creating signalflow client: %w", err) |
| 104 | + } |
| 105 | + |
| 106 | + ctx, cancel := context.WithTimeout(context.Background(), p.timeout) |
| 107 | + defer cancel() |
| 108 | + |
| 109 | + now := time.Now().UnixMilli() |
| 110 | + comp, err := c.Execute(ctx, &signalflow.ExecuteRequest{ |
| 111 | + Program: query, |
| 112 | + Start: time.UnixMilli(now - p.fromDelta), |
| 113 | + Stop: time.UnixMilli(now), |
| 114 | + Immediate: true, |
| 115 | + }) |
| 116 | + if err != nil { |
| 117 | + return 0, fmt.Errorf("error executing query: %w", err) |
| 118 | + } |
| 119 | + |
| 120 | + payloads := p.receivePaylods(comp) |
| 121 | + |
| 122 | + if comp.Err() != nil { |
| 123 | + return 0, fmt.Errorf("error executing query: %w", comp.Err()) |
| 124 | + } |
| 125 | + |
| 126 | + payloads = slices.DeleteFunc(payloads, func(msg messages.DataPayload) bool { |
| 127 | + return msg.Value() == nil |
| 128 | + }) |
| 129 | + if len(payloads) < 1 { |
| 130 | + return 0, fmt.Errorf("invalid response: %w", ErrNoValuesFound) |
| 131 | + } |
| 132 | + |
| 133 | + // Error when a SignalFlow query returns two or more results. |
| 134 | + // Since a different TSID is set for each metrics to be retrieved, eliminate duplicate TSIDs and determine if two or more TSIDs exist. |
| 135 | + _payloads := slices.Clone(payloads) |
| 136 | + slices.SortFunc(_payloads, func(i, j messages.DataPayload) int { |
| 137 | + return cmp.Compare(i.TSID, j.TSID) |
| 138 | + }) |
| 139 | + if len(slices.CompactFunc(_payloads, func(i, j messages.DataPayload) bool { return i.TSID == j.TSID })) > 1 { |
| 140 | + return 0, fmt.Errorf("invalid response: %w", ErrMultipleValuesReturned) |
| 141 | + } |
| 142 | + |
| 143 | + payload := payloads[len(payloads)-1] |
| 144 | + switch payload.Type { |
| 145 | + case messages.ValTypeLong: |
| 146 | + return float64(payload.Int64()), nil |
| 147 | + case messages.ValTypeDouble: |
| 148 | + return payload.Float64(), nil |
| 149 | + case messages.ValTypeInt: |
| 150 | + return float64(payload.Int32()), nil |
| 151 | + default: |
| 152 | + return 0, fmt.Errorf("invalid response: UnsupportedValueType") |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +func (p *SplunkProvider) receivePaylods(comp *signalflow.Computation) []messages.DataPayload { |
| 157 | + payloads := []messages.DataPayload{} |
| 158 | + for dataMsg := range comp.Data() { |
| 159 | + if dataMsg == nil { |
| 160 | + continue |
| 161 | + } |
| 162 | + payloads = append(payloads, dataMsg.Payloads...) |
| 163 | + } |
| 164 | + return payloads |
| 165 | +} |
| 166 | + |
| 167 | +// IsOnline calls the provider endpoint and returns an error if the API is unreachable |
| 168 | +func (p *SplunkProvider) IsOnline() (bool, error) { |
| 169 | + req, err := http.NewRequest("GET", p.apiValidationEndpoint, nil) |
| 170 | + if err != nil { |
| 171 | + return false, fmt.Errorf("error http.NewRequest: %w", err) |
| 172 | + } |
| 173 | + |
| 174 | + req.Header.Add(signalFxTokenHeaderKey, p.token) |
| 175 | + |
| 176 | + ctx, cancel := context.WithTimeout(req.Context(), p.timeout) |
| 177 | + defer cancel() |
| 178 | + r, err := http.DefaultClient.Do(req.WithContext(ctx)) |
| 179 | + if err != nil { |
| 180 | + return false, fmt.Errorf("request failed: %w", err) |
| 181 | + } |
| 182 | + |
| 183 | + defer r.Body.Close() |
| 184 | + |
| 185 | + b, err := io.ReadAll(r.Body) |
| 186 | + if err != nil { |
| 187 | + return false, fmt.Errorf("error reading body: %w", err) |
| 188 | + } |
| 189 | + |
| 190 | + if r.StatusCode != http.StatusOK { |
| 191 | + return false, fmt.Errorf("error response: %s", string(b)) |
| 192 | + } |
| 193 | + |
| 194 | + return true, nil |
| 195 | +} |
0 commit comments