2020-12-03 17:47:40 +00:00
|
|
|
package consul
|
|
|
|
|
|
|
|
import (
|
2023-01-06 03:34:47 +00:00
|
|
|
"context"
|
2020-12-03 17:47:40 +00:00
|
|
|
"encoding/json"
|
2023-01-06 03:34:47 +00:00
|
|
|
"errors"
|
2020-12-03 17:50:50 +00:00
|
|
|
"flag"
|
2020-12-03 17:47:40 +00:00
|
|
|
"fmt"
|
|
|
|
"net/url"
|
2021-07-02 11:48:16 +00:00
|
|
|
"strings"
|
2020-12-03 17:47:40 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/promscrape/discoveryutils"
|
2020-12-03 17:50:50 +00:00
|
|
|
"github.com/VictoriaMetrics/metrics"
|
2020-12-03 17:47:40 +00:00
|
|
|
)
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
// SDCheckInterval is check interval for Consul service discovery.
|
|
|
|
var SDCheckInterval = flag.Duration("promscrape.consulSDCheckInterval", 30*time.Second, "Interval for checking for changes in Consul. "+
|
2021-03-15 19:59:25 +00:00
|
|
|
"This works only if consul_sd_configs is configured in '-promscrape.config' file. "+
|
2022-08-14 22:40:20 +00:00
|
|
|
"See https://docs.victoriametrics.com/sd_configs.html#consul_sd_configs for details")
|
2020-12-03 17:50:50 +00:00
|
|
|
|
|
|
|
// consulWatcher is a watcher for consul api, updates services map in background with long-polling.
|
|
|
|
type consulWatcher struct {
|
|
|
|
client *discoveryutils.Client
|
|
|
|
|
|
|
|
serviceNamesQueryArgs string
|
|
|
|
serviceNodesQueryArgs string
|
|
|
|
watchServices []string
|
|
|
|
watchTags []string
|
|
|
|
|
2021-03-01 12:13:56 +00:00
|
|
|
// servicesLock protects services
|
|
|
|
servicesLock sync.Mutex
|
|
|
|
services map[string]*serviceWatcher
|
2020-12-03 17:50:50 +00:00
|
|
|
|
2023-01-06 05:52:31 +00:00
|
|
|
stoppedCh chan struct{}
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
type serviceWatcher struct {
|
|
|
|
serviceName string
|
|
|
|
serviceNodes []ServiceNode
|
2023-01-18 05:47:11 +00:00
|
|
|
|
|
|
|
stoppedCh chan struct{}
|
|
|
|
|
|
|
|
requestCtx context.Context
|
|
|
|
requestCancel context.CancelFunc
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
|
2022-02-21 13:32:45 +00:00
|
|
|
// newConsulWatcher creates new watcher and starts background service discovery for Consul.
|
2021-06-22 09:49:44 +00:00
|
|
|
func newConsulWatcher(client *discoveryutils.Client, sdc *SDConfig, datacenter, namespace string) *consulWatcher {
|
2020-12-08 19:49:11 +00:00
|
|
|
baseQueryArgs := "?dc=" + url.QueryEscape(datacenter)
|
2022-08-05 11:41:37 +00:00
|
|
|
if sdc.AllowStale == nil || *sdc.AllowStale {
|
2020-12-03 17:47:40 +00:00
|
|
|
baseQueryArgs += "&stale"
|
|
|
|
}
|
2021-06-22 09:49:44 +00:00
|
|
|
if namespace != "" {
|
2022-11-07 13:25:09 +00:00
|
|
|
baseQueryArgs += "&ns=" + url.QueryEscape(namespace)
|
|
|
|
}
|
|
|
|
if sdc.Partition != "" {
|
|
|
|
baseQueryArgs += "&partition=" + url.QueryEscape(sdc.Partition)
|
2021-06-22 09:49:44 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
for k, v := range sdc.NodeMeta {
|
|
|
|
baseQueryArgs += "&node-meta=" + url.QueryEscape(k+":"+v)
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
serviceNodesQueryArgs := baseQueryArgs
|
|
|
|
for _, tag := range sdc.Tags {
|
|
|
|
serviceNodesQueryArgs += "&tag=" + url.QueryEscape(tag)
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
cw := &consulWatcher{
|
2021-03-01 12:13:56 +00:00
|
|
|
client: client,
|
|
|
|
serviceNamesQueryArgs: baseQueryArgs,
|
|
|
|
serviceNodesQueryArgs: serviceNodesQueryArgs,
|
|
|
|
watchServices: sdc.Services,
|
|
|
|
watchTags: sdc.Tags,
|
|
|
|
services: make(map[string]*serviceWatcher),
|
2023-01-06 05:52:31 +00:00
|
|
|
stoppedCh: make(chan struct{}),
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2022-02-21 13:32:45 +00:00
|
|
|
initCh := make(chan struct{})
|
2023-01-06 05:13:02 +00:00
|
|
|
go func() {
|
|
|
|
cw.watchForServicesUpdates(initCh)
|
2023-01-06 05:52:31 +00:00
|
|
|
close(cw.stoppedCh)
|
2023-01-06 05:13:02 +00:00
|
|
|
}()
|
2022-02-21 13:32:45 +00:00
|
|
|
// wait for initialization to complete
|
|
|
|
<-initCh
|
2020-12-03 17:50:50 +00:00
|
|
|
return cw
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
|
2021-03-01 12:13:56 +00:00
|
|
|
func (cw *consulWatcher) mustStop() {
|
2023-01-06 03:34:47 +00:00
|
|
|
cw.client.Stop()
|
2023-01-06 05:52:31 +00:00
|
|
|
<-cw.stoppedCh
|
2021-03-01 12:13:56 +00:00
|
|
|
}
|
|
|
|
|
2022-02-21 13:32:45 +00:00
|
|
|
func (cw *consulWatcher) updateServices(serviceNames []string) {
|
|
|
|
var initWG sync.WaitGroup
|
2023-01-06 05:52:31 +00:00
|
|
|
|
2022-02-21 13:32:45 +00:00
|
|
|
// Start watchers for new services.
|
|
|
|
cw.servicesLock.Lock()
|
|
|
|
for _, serviceName := range serviceNames {
|
|
|
|
if _, ok := cw.services[serviceName]; ok {
|
|
|
|
// The watcher for serviceName already exists.
|
|
|
|
continue
|
|
|
|
}
|
2023-01-18 05:47:11 +00:00
|
|
|
ctx, cancel := context.WithCancel(cw.client.Context())
|
2022-02-21 13:32:45 +00:00
|
|
|
sw := &serviceWatcher{
|
2023-01-18 05:47:11 +00:00
|
|
|
serviceName: serviceName,
|
|
|
|
stoppedCh: make(chan struct{}),
|
|
|
|
requestCtx: ctx,
|
|
|
|
requestCancel: cancel,
|
2022-02-21 13:32:45 +00:00
|
|
|
}
|
|
|
|
cw.services[serviceName] = sw
|
|
|
|
serviceWatchersCreated.Inc()
|
|
|
|
initWG.Add(1)
|
|
|
|
go func() {
|
|
|
|
serviceWatchersCount.Inc()
|
|
|
|
sw.watchForServiceNodesUpdates(cw, &initWG)
|
|
|
|
serviceWatchersCount.Dec()
|
2023-01-06 05:52:31 +00:00
|
|
|
close(sw.stoppedCh)
|
2022-02-21 13:32:45 +00:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop watchers for removed services.
|
|
|
|
newServiceNamesMap := make(map[string]struct{}, len(serviceNames))
|
|
|
|
for _, serviceName := range serviceNames {
|
|
|
|
newServiceNamesMap[serviceName] = struct{}{}
|
|
|
|
}
|
2023-01-06 05:52:31 +00:00
|
|
|
var swsStopped []*serviceWatcher
|
2022-02-21 13:32:45 +00:00
|
|
|
for serviceName, sw := range cw.services {
|
|
|
|
if _, ok := newServiceNamesMap[serviceName]; ok {
|
|
|
|
continue
|
|
|
|
}
|
2023-01-18 05:47:11 +00:00
|
|
|
sw.requestCancel()
|
2022-02-21 13:32:45 +00:00
|
|
|
delete(cw.services, serviceName)
|
2023-01-06 05:52:31 +00:00
|
|
|
swsStopped = append(swsStopped, sw)
|
2022-02-21 13:32:45 +00:00
|
|
|
}
|
|
|
|
cw.servicesLock.Unlock()
|
|
|
|
|
2023-01-06 05:52:31 +00:00
|
|
|
// Wait until deleted service watchers are stopped.
|
|
|
|
for _, sw := range swsStopped {
|
|
|
|
<-sw.stoppedCh
|
|
|
|
serviceWatchersStopped.Inc()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait until added service watchers are initialized.
|
2022-02-21 13:32:45 +00:00
|
|
|
initWG.Wait()
|
|
|
|
}
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
// watchForServicesUpdates watches for new services and updates it in cw.
|
2022-02-21 13:32:45 +00:00
|
|
|
//
|
|
|
|
// watchForServicesUpdates closes the initCh once the initialization is complete and first discovery iteration is done.
|
|
|
|
func (cw *consulWatcher) watchForServicesUpdates(initCh chan struct{}) {
|
2020-12-03 17:50:50 +00:00
|
|
|
index := int64(0)
|
2023-01-06 05:13:02 +00:00
|
|
|
apiServer := cw.client.APIServer()
|
2020-12-03 17:50:50 +00:00
|
|
|
f := func() {
|
|
|
|
serviceNames, newIndex, err := cw.getBlockingServiceNames(index)
|
|
|
|
if err != nil {
|
2023-01-06 05:13:02 +00:00
|
|
|
if !errors.Is(err, context.Canceled) {
|
|
|
|
logger.Errorf("cannot obtain Consul serviceNames from %q: %s", apiServer, err)
|
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if index == newIndex {
|
|
|
|
// Nothing changed.
|
|
|
|
return
|
|
|
|
}
|
2022-02-21 13:32:45 +00:00
|
|
|
cw.updateServices(serviceNames)
|
2020-12-03 17:50:50 +00:00
|
|
|
index = newIndex
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
|
2023-01-06 05:13:02 +00:00
|
|
|
logger.Infof("started Consul service watcher for %q", apiServer)
|
2020-12-03 17:50:50 +00:00
|
|
|
f()
|
2022-02-21 13:32:45 +00:00
|
|
|
|
|
|
|
// send signal that initialization is complete
|
|
|
|
close(initCh)
|
|
|
|
|
|
|
|
checkInterval := getCheckInterval()
|
|
|
|
ticker := time.NewTicker(checkInterval / 2)
|
|
|
|
defer ticker.Stop()
|
2023-01-18 05:47:11 +00:00
|
|
|
stopCh := cw.client.Context().Done()
|
2021-03-01 12:13:56 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
f()
|
2023-01-18 05:47:11 +00:00
|
|
|
case <-stopCh:
|
2023-01-06 05:13:02 +00:00
|
|
|
logger.Infof("stopping Consul service watchers for %q", apiServer)
|
2020-12-03 18:14:17 +00:00
|
|
|
startTime := time.Now()
|
2023-01-06 05:52:31 +00:00
|
|
|
var swsStopped []*serviceWatcher
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
cw.servicesLock.Lock()
|
|
|
|
for _, sw := range cw.services {
|
2023-01-18 05:47:11 +00:00
|
|
|
sw.requestCancel()
|
2023-01-06 05:52:31 +00:00
|
|
|
swsStopped = append(swsStopped, sw)
|
2020-12-03 17:50:50 +00:00
|
|
|
}
|
|
|
|
cw.servicesLock.Unlock()
|
2023-01-06 05:52:31 +00:00
|
|
|
|
|
|
|
for _, sw := range swsStopped {
|
|
|
|
<-sw.stoppedCh
|
2023-01-18 05:47:11 +00:00
|
|
|
serviceWatchersStopped.Inc()
|
2023-01-06 05:52:31 +00:00
|
|
|
}
|
2023-01-06 05:13:02 +00:00
|
|
|
logger.Infof("stopped Consul service watcher for %q in %.3f seconds", apiServer, time.Since(startTime).Seconds())
|
2020-12-03 17:50:50 +00:00
|
|
|
return
|
|
|
|
}
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
serviceWatchersCreated = metrics.NewCounter("vm_promscrape_discovery_consul_service_watchers_created_total")
|
|
|
|
serviceWatchersStopped = metrics.NewCounter("vm_promscrape_discovery_consul_service_watchers_stopped_total")
|
|
|
|
serviceWatchersCount = metrics.NewCounter("vm_promscrape_discovery_consul_service_watchers")
|
|
|
|
)
|
|
|
|
|
|
|
|
// getBlockingServiceNames obtains serviceNames via blocking request to Consul.
|
|
|
|
//
|
|
|
|
// It returns an empty serviceNames list if response contains the same index.
|
|
|
|
func (cw *consulWatcher) getBlockingServiceNames(index int64) ([]string, int64, error) {
|
|
|
|
path := "/v1/catalog/services" + cw.serviceNamesQueryArgs
|
2023-01-18 05:47:11 +00:00
|
|
|
data, newIndex, err := getBlockingAPIResponse(cw.client.Context(), cw.client, path, index)
|
2020-12-03 17:47:40 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, index, err
|
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
if index == newIndex {
|
|
|
|
// Nothing changed - return an empty serviceNames list.
|
|
|
|
return nil, index, nil
|
|
|
|
}
|
2020-12-03 17:47:40 +00:00
|
|
|
var m map[string][]string
|
|
|
|
if err := json.Unmarshal(data, &m); err != nil {
|
2020-12-03 17:50:50 +00:00
|
|
|
return nil, index, fmt.Errorf("cannot parse response from %q: %w; data=%q", path, err, data)
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
serviceNames := make([]string, 0, len(m))
|
|
|
|
for serviceName, tags := range m {
|
|
|
|
if !shouldCollectServiceByName(cw.watchServices, serviceName) {
|
2020-12-03 17:47:40 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
if !shouldCollectServiceByTags(cw.watchTags, tags) {
|
2020-12-03 17:47:40 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
serviceNames = append(serviceNames, serviceName)
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
return serviceNames, newIndex, nil
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
// watchForServiceNodesUpdates watches for Consul serviceNode changes for the given serviceName.
|
2022-02-21 13:32:45 +00:00
|
|
|
//
|
|
|
|
// watchForServiceNodesUpdates calls initWG.Done() once the initialization is complete and the first discovery iteration is done.
|
|
|
|
func (sw *serviceWatcher) watchForServiceNodesUpdates(cw *consulWatcher, initWG *sync.WaitGroup) {
|
2023-01-06 05:13:02 +00:00
|
|
|
apiServer := cw.client.APIServer()
|
2020-12-03 17:50:50 +00:00
|
|
|
index := int64(0)
|
|
|
|
path := "/v1/health/service/" + sw.serviceName + cw.serviceNodesQueryArgs
|
|
|
|
f := func() {
|
2023-01-18 05:47:11 +00:00
|
|
|
data, newIndex, err := getBlockingAPIResponse(sw.requestCtx, cw.client, path, index)
|
2020-12-03 17:50:50 +00:00
|
|
|
if err != nil {
|
2023-01-06 05:13:02 +00:00
|
|
|
if !errors.Is(err, context.Canceled) {
|
|
|
|
logger.Errorf("cannot obtain Consul serviceNodes for serviceName=%q from %q: %s", sw.serviceName, apiServer, err)
|
2023-01-06 03:34:47 +00:00
|
|
|
}
|
2020-12-03 17:47:40 +00:00
|
|
|
return
|
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
if index == newIndex {
|
|
|
|
// Nothing changed.
|
|
|
|
return
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
sns, err := parseServiceNodes(data)
|
|
|
|
if err != nil {
|
2023-01-06 05:13:02 +00:00
|
|
|
logger.Errorf("cannot parse Consul serviceNodes response for serviceName=%q from %q: %s", sw.serviceName, apiServer, err)
|
2020-12-03 17:50:50 +00:00
|
|
|
return
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
|
2020-12-03 17:47:40 +00:00
|
|
|
cw.servicesLock.Lock()
|
2020-12-03 17:50:50 +00:00
|
|
|
sw.serviceNodes = sns
|
2020-12-03 17:47:40 +00:00
|
|
|
cw.servicesLock.Unlock()
|
2020-12-03 17:50:50 +00:00
|
|
|
|
|
|
|
index = newIndex
|
|
|
|
}
|
|
|
|
|
|
|
|
f()
|
2022-02-21 13:32:45 +00:00
|
|
|
// Notify caller that initialization is complete
|
|
|
|
initWG.Done()
|
|
|
|
|
|
|
|
checkInterval := getCheckInterval()
|
|
|
|
ticker := time.NewTicker(checkInterval / 2)
|
|
|
|
defer ticker.Stop()
|
2023-01-18 05:47:11 +00:00
|
|
|
stopCh := sw.requestCtx.Done()
|
2020-12-03 17:50:50 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
f()
|
2023-01-18 05:47:11 +00:00
|
|
|
case <-stopCh:
|
2020-12-03 17:50:50 +00:00
|
|
|
return
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
}
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
// getServiceNodesSnapshot returns a snapshot of discovered ServiceNodes.
|
2021-03-23 13:35:01 +00:00
|
|
|
func (cw *consulWatcher) getServiceNodesSnapshot() map[string][]ServiceNode {
|
2020-12-03 17:47:40 +00:00
|
|
|
cw.servicesLock.Lock()
|
2021-03-23 13:35:01 +00:00
|
|
|
sns := make(map[string][]ServiceNode, len(cw.services))
|
|
|
|
for svc, sw := range cw.services {
|
|
|
|
sns[svc] = sw.serviceNodes
|
2020-12-03 17:47:40 +00:00
|
|
|
}
|
|
|
|
cw.servicesLock.Unlock()
|
|
|
|
return sns
|
|
|
|
}
|
|
|
|
|
2020-12-03 17:50:50 +00:00
|
|
|
func shouldCollectServiceByName(filterServices []string, serviceName string) bool {
|
2020-12-03 17:47:40 +00:00
|
|
|
if len(filterServices) == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
for _, filterService := range filterServices {
|
2021-07-02 11:48:16 +00:00
|
|
|
// Use case-insensitive comparison for service names according to https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1422
|
|
|
|
if strings.EqualFold(filterService, serviceName) {
|
2020-12-03 17:47:40 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func shouldCollectServiceByTags(filterTags, tags []string) bool {
|
|
|
|
if len(filterTags) == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
for _, filterTag := range filterTags {
|
|
|
|
hasTag := false
|
|
|
|
for _, tag := range tags {
|
|
|
|
if tag == filterTag {
|
|
|
|
hasTag = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !hasTag {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2020-12-03 17:50:50 +00:00
|
|
|
|
|
|
|
func getCheckInterval() time.Duration {
|
|
|
|
d := *SDCheckInterval
|
|
|
|
if d <= time.Second {
|
|
|
|
return time.Second
|
|
|
|
}
|
|
|
|
return d
|
|
|
|
}
|