Skip to content

Commit 5ce820f

Browse files
🚧 修复Check ElasticSearch数据源时未携带认证参数 (#109)
1 parent b4a7eb3 commit 5ce820f

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

pkg/provider/logs_elasticsearch.go

+16-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package provider
22

33
import (
44
"context"
5+
"encoding/base64"
56
"encoding/json"
7+
"fmt"
68
"github.com/olivere/elastic/v7"
79
"watchAlert/internal/models"
810
utilsHttp "watchAlert/pkg/tools"
@@ -11,6 +13,8 @@ import (
1113
type ElasticSearchDsProvider struct {
1214
cli *elastic.Client
1315
url string
16+
username string
17+
password string
1418
ExternalLabels map[string]interface{}
1519
}
1620

@@ -27,6 +31,8 @@ func NewElasticSearchClient(ctx context.Context, ds models.AlertDataSource) (Log
2731
return ElasticSearchDsProvider{
2832
cli: client,
2933
url: ds.ElasticSearch.Url,
34+
username: ds.ElasticSearch.Username,
35+
password: ds.ElasticSearch.Password,
3036
ExternalLabels: ds.Labels,
3137
}, nil
3238
}
@@ -87,13 +93,21 @@ func (e ElasticSearchDsProvider) Query(options LogQueryOptions) ([]Logs, int, er
8793
}
8894

8995
func (e ElasticSearchDsProvider) Check() (bool, error) {
90-
res, err := utilsHttp.Get(nil, e.url+"/_cat/health", 10)
96+
header := make(map[string]string)
97+
url := fmt.Sprintf("%s/_cat/health", e.url)
98+
if e.username != "" {
99+
auth := e.username + ":" + e.password
100+
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
101+
header["Authorization"] = basicAuth
102+
url = fmt.Sprintf("%s/_cat/health", e.url)
103+
}
104+
res, err := utilsHttp.Get(header, url, 10)
91105
if err != nil {
92106
return false, err
93107
}
94108

95109
if res.StatusCode != 200 {
96-
return false, err
110+
return false, fmt.Errorf("状态码非200, 当前: %d", res.StatusCode)
97111
}
98112
return true, nil
99113
}

0 commit comments

Comments
 (0)