@@ -2,7 +2,9 @@ package provider
2
2
3
3
import (
4
4
"context"
5
+ "encoding/base64"
5
6
"encoding/json"
7
+ "fmt"
6
8
"github.com/olivere/elastic/v7"
7
9
"watchAlert/internal/models"
8
10
utilsHttp "watchAlert/pkg/tools"
@@ -11,6 +13,8 @@ import (
11
13
type ElasticSearchDsProvider struct {
12
14
cli * elastic.Client
13
15
url string
16
+ username string
17
+ password string
14
18
ExternalLabels map [string ]interface {}
15
19
}
16
20
@@ -27,6 +31,8 @@ func NewElasticSearchClient(ctx context.Context, ds models.AlertDataSource) (Log
27
31
return ElasticSearchDsProvider {
28
32
cli : client ,
29
33
url : ds .ElasticSearch .Url ,
34
+ username : ds .ElasticSearch .Username ,
35
+ password : ds .ElasticSearch .Password ,
30
36
ExternalLabels : ds .Labels ,
31
37
}, nil
32
38
}
@@ -87,13 +93,21 @@ func (e ElasticSearchDsProvider) Query(options LogQueryOptions) ([]Logs, int, er
87
93
}
88
94
89
95
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 )
91
105
if err != nil {
92
106
return false , err
93
107
}
94
108
95
109
if res .StatusCode != 200 {
96
- return false , err
110
+ return false , fmt . Errorf ( "状态码非200, 当前: %d" , res . StatusCode )
97
111
}
98
112
return true , nil
99
113
}
0 commit comments