2020-04-27 18:25:45 +02:00
|
|
|
package ec2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
2020-09-21 17:42:53 +02:00
|
|
|
"sync"
|
2020-04-29 16:27:08 +02:00
|
|
|
|
2022-05-04 19:24:19 +02:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/awsapi"
|
2020-04-29 16:27:08 +02:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/promscrape/discoveryutils"
|
2020-04-27 18:25:45 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type apiConfig struct {
|
2022-05-04 19:24:19 +02:00
|
|
|
awsConfig *awsapi.Config
|
|
|
|
port int
|
2021-08-03 12:26:28 +02:00
|
|
|
|
|
|
|
// A map from AZ name to AZ id.
|
|
|
|
azMap map[string]string
|
|
|
|
azMapLock sync.Mutex
|
2020-09-21 15:04:15 +02:00
|
|
|
}
|
|
|
|
|
2020-05-04 15:21:24 +02:00
|
|
|
var configMap = discoveryutils.NewConfigMap()
|
2020-04-27 18:25:45 +02:00
|
|
|
|
2020-05-04 15:21:24 +02:00
|
|
|
func getAPIConfig(sdc *SDConfig) (*apiConfig, error) {
|
2020-09-21 17:42:53 +02:00
|
|
|
v, err := configMap.Get(sdc, func() (interface{}, error) { return newAPIConfig(sdc) })
|
2020-04-27 18:25:45 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-05-04 15:21:24 +02:00
|
|
|
return v.(*apiConfig), nil
|
2020-04-27 18:25:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func newAPIConfig(sdc *SDConfig) (*apiConfig, error) {
|
2022-05-04 19:24:19 +02:00
|
|
|
fqs := getFiltersQueryString(sdc.Filters)
|
2020-04-27 18:25:45 +02:00
|
|
|
port := 80
|
|
|
|
if sdc.Port != nil {
|
|
|
|
port = *sdc.Port
|
|
|
|
}
|
2022-05-04 19:24:19 +02:00
|
|
|
awsCfg, err := awsapi.NewConfig(sdc.Region, sdc.RoleARN, sdc.AccessKey, sdc.SecretKey.String(), fqs)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2020-09-21 15:04:15 +02:00
|
|
|
}
|
2022-05-04 19:24:19 +02:00
|
|
|
cfg := &apiConfig{
|
|
|
|
awsConfig: awsCfg,
|
|
|
|
port: port,
|
2020-09-21 15:04:15 +02:00
|
|
|
}
|
|
|
|
return cfg, nil
|
2020-04-27 18:25:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func getFiltersQueryString(filters []Filter) string {
|
|
|
|
// See how to build filters query string at examples at https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html
|
|
|
|
var args []string
|
|
|
|
for i, f := range filters {
|
|
|
|
args = append(args, fmt.Sprintf("Filter.%d.Name=%s", i+1, url.QueryEscape(f.Name)))
|
|
|
|
for j, v := range f.Values {
|
|
|
|
args = append(args, fmt.Sprintf("Filter.%d.Value.%d=%s", i+1, j+1, url.QueryEscape(v)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return strings.Join(args, "&")
|
|
|
|
}
|