Skip to content

Commit c62a026

Browse files
committed
updated provider.go to handle elastic
1 parent a02dfb2 commit c62a026

File tree

2 files changed

+22
-43
lines changed

2 files changed

+22
-43
lines changed

metrics-operator/controllers/common/providers/elastic/elastic.go

Lines changed: 13 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -34,64 +34,43 @@ type ElasticsearchResponse struct {
3434
} `json:"hits"`
3535
}
3636

37-
func NewElasticProvider(log logr.Logger, k8sClient client.Client, elasticURL string) (*KeptnElasticProvider, error) {
38-
log.Info("Initializing Elasticsearch client with TLS disabled...")
39-
40-
// Custom Transport to Skip TLS Verification
41-
transport := &http.Transport{
42-
TLSClientConfig: &tls.Config{
43-
InsecureSkipVerify: true,
37+
func GetElasticClient(provider metricsapi.KeptnMetricsProvider) (*elastic.Client, error) {
38+
es, err := elastic.NewClient(elastic.Config{
39+
Addresses: []string{provider.Spec.TargetServer},
40+
APIKey: provider.Spec.SecretKeyRef.Key,
41+
Transport: &http.Transport{
42+
TLSClientConfig: &tls.Config{
43+
InsecureSkipVerify: provider.Spec.InsecureSkipTlsVerify,
44+
},
4445
},
45-
}
46-
47-
// Elasticsearch Client Config
48-
cfg := elastic.Config{
49-
Addresses: []string{"https://quickstart-es-http:9200"},
50-
Username: "elastic",
51-
Password: "073wS1l5ct65LdktJ03M9oqa",
52-
Transport: transport,
53-
}
54-
55-
// Create Elasticsearch Client
56-
es, err := elastic.NewClient(cfg)
46+
})
5747
if err != nil {
58-
log.Error(err, "Failed to create Elasticsearch client")
5948
return nil, fmt.Errorf("failed to create Elasticsearch client: %w", err)
6049
}
61-
62-
log.Info("Successfully initialized Elasticsearch client with TLS disabled")
63-
return &KeptnElasticProvider{
64-
Log: log,
65-
K8sClient: k8sClient,
66-
Elastic: es,
67-
}, nil
50+
return es, nil
6851
}
6952

7053
func (r *KeptnElasticProvider) FetchAnalysisValue(ctx context.Context, query string, analysis metricsapi.Analysis, provider *metricsapi.KeptnMetricsProvider) (string, error) {
71-
r.Log.Info("Fetching analysis value from Elasticsearch", "query", query)
7254
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
7355
defer cancel()
7456

7557
result, err := r.runElasticQuery(ctx, query, analysis.GetFrom(), analysis.GetTo())
7658
if err != nil {
77-
r.Log.Error(err, "Failed to fetch analysis value")
7859
return "", err
7960
}
8061

81-
r.Log.Info("Elasticsearch query result", "result", result)
62+
r.Log.Info(fmt.Sprintf("Elasticsearch query result: %v", result))
8263
return r.extractMetric(result)
8364
}
8465

8566
func (r *KeptnElasticProvider) EvaluateQuery(ctx context.Context, metric metricsapi.KeptnMetric, provider metricsapi.KeptnMetricsProvider) (string, []byte, error) {
86-
r.Log.Info("Evaluating query for KeptnMetric", "metric", metric.Name)
8767
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
8868
defer cancel()
8969

9070
timeRange := getTimeRangeFromSpec(metric.Spec.Range)
9171

9272
result, err := r.runElasticQuery(ctx, metric.Spec.Query, time.Now().Add(-timeRange), time.Now())
9373
if err != nil {
94-
r.Log.Error(err, "Failed to evaluate query")
9574
return "", nil, err
9675
}
9776

@@ -100,7 +79,6 @@ func (r *KeptnElasticProvider) EvaluateQuery(ctx context.Context, metric metrics
10079
return "", nil, err
10180
}
10281

103-
r.Log.Info("Successfully evaluated metric", "value", metricValue)
10482
return metricValue, []byte{}, nil
10583
}
10684

@@ -113,16 +91,16 @@ func getTimeRangeFromSpec(rangeSpec *metricsapi.RangeSpec) time.Duration {
11391
if rangeSpec == nil || rangeSpec.Interval == "" {
11492
return defaultTimeRange
11593
}
94+
11695
duration, err := time.ParseDuration(rangeSpec.Interval)
11796
if err != nil {
11897
return defaultTimeRange
11998
}
99+
120100
return duration
121101
}
122102

123103
func (r *KeptnElasticProvider) runElasticQuery(ctx context.Context, query string, from, to time.Time) (map[string]interface{}, error) {
124-
r.Log.Info("Running Elasticsearch query", "query", query, "from", from, "to", to)
125-
126104
queryBody := fmt.Sprintf(`
127105
{
128106
"query": {
@@ -147,7 +125,6 @@ func (r *KeptnElasticProvider) runElasticQuery(ctx context.Context, query string
147125
r.Elastic.Search.WithBody(strings.NewReader(queryBody)),
148126
)
149127
if err != nil {
150-
r.Log.Error(err, "Failed to execute Elasticsearch query")
151128
return nil, fmt.Errorf("failed to execute Elasticsearch query: %w", err)
152129
}
153130
defer res.Body.Close()
@@ -158,29 +135,23 @@ func (r *KeptnElasticProvider) runElasticQuery(ctx context.Context, query string
158135

159136
var result map[string]interface{}
160137
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
161-
r.Log.Error(err, "Failed to parse Elasticsearch response")
162138
return nil, fmt.Errorf("failed to parse Elasticsearch response: %w", err)
163139
}
164140

165-
r.Log.Info("Successfully executed query", "result", result)
166141
return result, nil
167142
}
168143

169144
func (r *KeptnElasticProvider) extractMetric(result map[string]interface{}) (string, error) {
170-
r.Log.Info("Extracting metric from Elasticsearch response")
171145
var response ElasticsearchResponse
172146
jsonData, err := json.Marshal(result)
173147
if err != nil {
174-
r.Log.Error(err, "Failed to marshal Elasticsearch result")
175148
return "", fmt.Errorf("failed to marshal result: %w", err)
176149
}
177150

178151
if err := json.Unmarshal(jsonData, &response); err != nil {
179-
r.Log.Error(err, "Failed to unmarshal result into struct")
180152
return "", fmt.Errorf("failed to unmarshal result into struct: %w", err)
181153
}
182154

183155
value := fmt.Sprintf("%d", response.Hits.Total.Value)
184-
r.Log.Info("Extracted metric successfully", "value", value)
185156
return value, nil
186157
}

metrics-operator/controllers/common/providers/provider.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,15 @@ func NewProvider(provider *metricsapi.KeptnMetricsProvider, log logr.Logger, k8s
6464
K8sClient: k8sClient,
6565
}, nil
6666
case ElasticProviderType:
67-
return elastic.NewElasticProvider(log, k8sClient, "")
67+
es, err := elastic.GetElasticClient(*provider)
68+
if err != nil {
69+
return nil, err
70+
}
71+
return &elastic.KeptnElasticProvider{
72+
Log: log,
73+
K8sClient: k8sClient,
74+
Elastic: es,
75+
}, nil
6876
default:
6977
return nil, fmt.Errorf("provider %s not supported", provider.Spec.Type)
7078
}

0 commit comments

Comments
 (0)