|
| 1 | +// Copyright (c) The Thanos Authors. |
| 2 | +// Licensed under the Apache License 2.0. |
| 3 | + |
| 4 | +package main |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "sync" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/go-kit/log" |
| 13 | + "github.com/go-kit/log/level" |
| 14 | + "github.com/oklog/run" |
| 15 | + "google.golang.org/grpc" |
| 16 | + "gopkg.in/yaml.v3" |
| 17 | + |
| 18 | + "github.com/prometheus/client_golang/prometheus" |
| 19 | + "github.com/prometheus/client_golang/prometheus/promauto" |
| 20 | + "github.com/prometheus/common/model" |
| 21 | + "github.com/prometheus/prometheus/discovery" |
| 22 | + "github.com/prometheus/prometheus/discovery/file" |
| 23 | + "github.com/prometheus/prometheus/discovery/targetgroup" |
| 24 | + |
| 25 | + "github.com/thanos-io/thanos/pkg/component" |
| 26 | + "github.com/thanos-io/thanos/pkg/discovery/cache" |
| 27 | + "github.com/thanos-io/thanos/pkg/discovery/dns" |
| 28 | + "github.com/thanos-io/thanos/pkg/errors" |
| 29 | + "github.com/thanos-io/thanos/pkg/extgrpc" |
| 30 | + "github.com/thanos-io/thanos/pkg/extkingpin" |
| 31 | + "github.com/thanos-io/thanos/pkg/extprom" |
| 32 | + "github.com/thanos-io/thanos/pkg/query" |
| 33 | + "github.com/thanos-io/thanos/pkg/runutil" |
| 34 | +) |
| 35 | + |
| 36 | +// fileContent is the interface of methods that we need from extkingpin.PathOrContent. |
| 37 | +// We need to abstract it for now so we can implement a default if the user does not provide one. |
| 38 | +type fileContent interface { |
| 39 | + Content() ([]byte, error) |
| 40 | + Path() string |
| 41 | +} |
| 42 | + |
| 43 | +type endpointSettings struct { |
| 44 | + Strict bool `yaml:"strict"` |
| 45 | + Group bool `yaml:"group"` |
| 46 | + Address string `yaml:"address"` |
| 47 | +} |
| 48 | + |
| 49 | +type EndpointConfig struct { |
| 50 | + Endpoints []endpointSettings `yaml:"endpoints"` |
| 51 | +} |
| 52 | + |
| 53 | +type endpointConfigProvider struct { |
| 54 | + mu sync.Mutex |
| 55 | + cfg EndpointConfig |
| 56 | + |
| 57 | + // statically defined endpoints from flags for backwards compatibility |
| 58 | + endpoints []string |
| 59 | + endpointGroups []string |
| 60 | + strictEndpoints []string |
| 61 | + strictEndpointGroups []string |
| 62 | +} |
| 63 | + |
| 64 | +func (er *endpointConfigProvider) config() EndpointConfig { |
| 65 | + er.mu.Lock() |
| 66 | + defer er.mu.Unlock() |
| 67 | + |
| 68 | + res := EndpointConfig{Endpoints: make([]endpointSettings, len(er.cfg.Endpoints))} |
| 69 | + copy(res.Endpoints, er.cfg.Endpoints) |
| 70 | + return res |
| 71 | +} |
| 72 | + |
| 73 | +func (er *endpointConfigProvider) parse(configFile fileContent) (EndpointConfig, error) { |
| 74 | + content, err := configFile.Content() |
| 75 | + if err != nil { |
| 76 | + return EndpointConfig{}, errors.Wrapf(err, "unable to load config content: %s", configFile.Path()) |
| 77 | + } |
| 78 | + var cfg EndpointConfig |
| 79 | + if err := yaml.Unmarshal(content, &cfg); err != nil { |
| 80 | + return EndpointConfig{}, errors.Wrapf(err, "unable to unmarshal config content: %s", configFile.Path()) |
| 81 | + } |
| 82 | + return cfg, nil |
| 83 | +} |
| 84 | + |
| 85 | +func (er *endpointConfigProvider) addStaticEndpoints(cfg *EndpointConfig) { |
| 86 | + for _, e := range er.endpoints { |
| 87 | + cfg.Endpoints = append(cfg.Endpoints, endpointSettings{ |
| 88 | + Address: e, |
| 89 | + }) |
| 90 | + } |
| 91 | + for _, e := range er.endpointGroups { |
| 92 | + cfg.Endpoints = append(cfg.Endpoints, endpointSettings{ |
| 93 | + Address: e, |
| 94 | + Group: true, |
| 95 | + }) |
| 96 | + } |
| 97 | + for _, e := range er.strictEndpoints { |
| 98 | + cfg.Endpoints = append(cfg.Endpoints, endpointSettings{ |
| 99 | + Address: e, |
| 100 | + Strict: true, |
| 101 | + }) |
| 102 | + } |
| 103 | + for _, e := range er.strictEndpointGroups { |
| 104 | + cfg.Endpoints = append(cfg.Endpoints, endpointSettings{ |
| 105 | + Address: e, |
| 106 | + Group: true, |
| 107 | + Strict: true, |
| 108 | + }) |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +func validateEndpointConfig(cfg EndpointConfig) error { |
| 113 | + for _, ecfg := range cfg.Endpoints { |
| 114 | + if dns.IsDynamicNode(ecfg.Address) && ecfg.Strict { |
| 115 | + return errors.Newf("%s is a dynamically specified endpoint i.e. it uses SD and that is not permitted under strict mode.", ecfg.Address) |
| 116 | + } |
| 117 | + } |
| 118 | + return nil |
| 119 | +} |
| 120 | + |
| 121 | +func newEndpointConfigProvider( |
| 122 | + logger log.Logger, |
| 123 | + configFile fileContent, |
| 124 | + configReloadInterval time.Duration, |
| 125 | + staticEndpoints []string, |
| 126 | + staticEndpointGroups []string, |
| 127 | + staticStrictEndpoints []string, |
| 128 | + staticStrictEndpointGroups []string, |
| 129 | +) (*endpointConfigProvider, error) { |
| 130 | + res := &endpointConfigProvider{ |
| 131 | + endpoints: staticEndpoints, |
| 132 | + endpointGroups: staticEndpointGroups, |
| 133 | + strictEndpoints: staticStrictEndpoints, |
| 134 | + strictEndpointGroups: staticStrictEndpointGroups, |
| 135 | + } |
| 136 | + |
| 137 | + if configFile == nil { |
| 138 | + configFile = extkingpin.NewNopConfig() |
| 139 | + } |
| 140 | + |
| 141 | + cfg, err := res.parse(configFile) |
| 142 | + if err != nil { |
| 143 | + return nil, errors.Wrapf(err, "unable to load config file") |
| 144 | + } |
| 145 | + res.addStaticEndpoints(&cfg) |
| 146 | + res.cfg = cfg |
| 147 | + if err := validateEndpointConfig(cfg); err != nil { |
| 148 | + return nil, errors.Wrapf(err, "unable to validate endpoints") |
| 149 | + } |
| 150 | + |
| 151 | + // only static endpoints |
| 152 | + if len(configFile.Path()) == 0 { |
| 153 | + return res, nil |
| 154 | + } |
| 155 | + |
| 156 | + if err := extkingpin.PathContentReloader(context.Background(), configFile, logger, func() { |
| 157 | + res.mu.Lock() |
| 158 | + defer res.mu.Unlock() |
| 159 | + |
| 160 | + level.Info(logger).Log("msg", "reloading endpoint config") |
| 161 | + cfg, err := res.parse(configFile) |
| 162 | + if err != nil { |
| 163 | + level.Error(logger).Log("msg", "failed to reload endpoint config", "err", err) |
| 164 | + return |
| 165 | + } |
| 166 | + res.addStaticEndpoints(&cfg) |
| 167 | + if err := validateEndpointConfig(cfg); err != nil { |
| 168 | + level.Error(logger).Log("msg", "failed to validate endpoint config", "err", err) |
| 169 | + return |
| 170 | + } |
| 171 | + res.cfg = cfg |
| 172 | + }, configReloadInterval); err != nil { |
| 173 | + return nil, errors.Wrapf(err, "unable to create config reloader") |
| 174 | + } |
| 175 | + return res, nil |
| 176 | +} |
| 177 | + |
| 178 | +func setupEndpointSet( |
| 179 | + g *run.Group, |
| 180 | + comp component.Component, |
| 181 | + reg prometheus.Registerer, |
| 182 | + logger log.Logger, |
| 183 | + configFile fileContent, |
| 184 | + configReloadInterval time.Duration, |
| 185 | + legacyFileSDFiles []string, |
| 186 | + legacyFileSDInterval time.Duration, |
| 187 | + legacyEndpoints []string, |
| 188 | + legacyEndpointGroups []string, |
| 189 | + legacyStrictEndpoints []string, |
| 190 | + legacyStrictEndpointGroups []string, |
| 191 | + dnsSDResolver string, |
| 192 | + dnsSDInterval time.Duration, |
| 193 | + unhealthyTimeout time.Duration, |
| 194 | + endpointTimeout time.Duration, |
| 195 | + dialOpts []grpc.DialOption, |
| 196 | + queryConnMetricLabels ...string, |
| 197 | +) (*query.EndpointSet, error) { |
| 198 | + configProvider, err := newEndpointConfigProvider( |
| 199 | + logger, |
| 200 | + configFile, |
| 201 | + configReloadInterval, |
| 202 | + legacyEndpoints, |
| 203 | + legacyEndpointGroups, |
| 204 | + legacyStrictEndpoints, |
| 205 | + legacyStrictEndpointGroups, |
| 206 | + ) |
| 207 | + if err != nil { |
| 208 | + return nil, errors.Wrapf(err, "unable to load config initially") |
| 209 | + } |
| 210 | + // Register resolver for the "thanos:///" scheme for endpoint-groups |
| 211 | + dns.RegisterGRPCResolver( |
| 212 | + logger, |
| 213 | + dns.NewProvider( |
| 214 | + logger, |
| 215 | + extprom.WrapRegistererWithPrefix(fmt.Sprintf("thanos_%s_endpoint_groups_", comp), reg), |
| 216 | + dns.ResolverType(dnsSDResolver), |
| 217 | + ), |
| 218 | + dnsSDInterval, |
| 219 | + ) |
| 220 | + dnsEndpointProvider := dns.NewProvider( |
| 221 | + logger, |
| 222 | + extprom.WrapRegistererWithPrefix(fmt.Sprintf("thanos_%s_endpoints_", comp), reg), |
| 223 | + dns.ResolverType(dnsSDResolver), |
| 224 | + ) |
| 225 | + duplicatedEndpoints := promauto.With(reg).NewCounter(prometheus.CounterOpts{ |
| 226 | + Name: fmt.Sprintf("thanos_%s_duplicated_endpoint_addresses_total", comp), |
| 227 | + Help: "The number of times a duplicated endpoint addresses is detected from the different configs", |
| 228 | + }) |
| 229 | + |
| 230 | + removeDuplicateEndpointSpecs := func(specs []*query.GRPCEndpointSpec) []*query.GRPCEndpointSpec { |
| 231 | + set := make(map[string]*query.GRPCEndpointSpec) |
| 232 | + for _, spec := range specs { |
| 233 | + addr := spec.Addr() |
| 234 | + if _, ok := set[addr]; ok { |
| 235 | + level.Warn(logger).Log("msg", "Duplicate endpoint address is provided", "addr", addr) |
| 236 | + duplicatedEndpoints.Inc() |
| 237 | + } |
| 238 | + set[addr] = spec |
| 239 | + } |
| 240 | + deduplicated := make([]*query.GRPCEndpointSpec, 0, len(set)) |
| 241 | + for _, value := range set { |
| 242 | + deduplicated = append(deduplicated, value) |
| 243 | + } |
| 244 | + return deduplicated |
| 245 | + } |
| 246 | + var fileSD *file.Discovery |
| 247 | + if len(legacyFileSDFiles) > 0 { |
| 248 | + conf := &file.SDConfig{ |
| 249 | + Files: legacyFileSDFiles, |
| 250 | + RefreshInterval: model.Duration(legacyFileSDInterval), |
| 251 | + } |
| 252 | + var err error |
| 253 | + if fileSD, err = file.NewDiscovery(conf, logger, conf.NewDiscovererMetrics(reg, discovery.NewRefreshMetrics(reg))); err != nil { |
| 254 | + return nil, fmt.Errorf("unable to create new legacy file sd config: %w", err) |
| 255 | + } |
| 256 | + } |
| 257 | + legacyFileSDCache := cache.New() |
| 258 | + |
| 259 | + ctx, cancel := context.WithCancel(context.Background()) |
| 260 | + |
| 261 | + if fileSD != nil { |
| 262 | + fileSDUpdates := make(chan []*targetgroup.Group) |
| 263 | + |
| 264 | + g.Add(func() error { |
| 265 | + fileSD.Run(ctx, fileSDUpdates) |
| 266 | + return nil |
| 267 | + |
| 268 | + }, func(err error) { |
| 269 | + cancel() |
| 270 | + }) |
| 271 | + |
| 272 | + g.Add(func() error { |
| 273 | + for { |
| 274 | + select { |
| 275 | + case update := <-fileSDUpdates: |
| 276 | + // Discoverers sometimes send nil updates so need to check for it to avoid panics. |
| 277 | + if update == nil { |
| 278 | + continue |
| 279 | + } |
| 280 | + legacyFileSDCache.Update(update) |
| 281 | + case <-ctx.Done(): |
| 282 | + return nil |
| 283 | + } |
| 284 | + } |
| 285 | + }, func(err error) { |
| 286 | + cancel() |
| 287 | + }) |
| 288 | + } |
| 289 | + |
| 290 | + { |
| 291 | + g.Add(func() error { |
| 292 | + return runutil.Repeat(dnsSDInterval, ctx.Done(), func() error { |
| 293 | + ctxUpdateIter, cancelUpdateIter := context.WithTimeout(ctx, dnsSDInterval) |
| 294 | + defer cancelUpdateIter() |
| 295 | + |
| 296 | + endpointConfig := configProvider.config() |
| 297 | + |
| 298 | + addresses := make([]string, 0, len(endpointConfig.Endpoints)) |
| 299 | + for _, ecfg := range endpointConfig.Endpoints { |
| 300 | + if addr := ecfg.Address; !ecfg.Group && !ecfg.Strict { |
| 301 | + // originally only "--endpoint" addresses got resolved |
| 302 | + addresses = append(addresses, addr) |
| 303 | + } |
| 304 | + } |
| 305 | + addresses = append(addresses, legacyFileSDCache.Addresses()...) |
| 306 | + if err := dnsEndpointProvider.Resolve(ctxUpdateIter, addresses, true); err != nil { |
| 307 | + level.Error(logger).Log("msg", "failed to resolve addresses for endpoints", "err", err) |
| 308 | + } |
| 309 | + return nil |
| 310 | + }) |
| 311 | + }, func(error) { |
| 312 | + cancel() |
| 313 | + }) |
| 314 | + } |
| 315 | + |
| 316 | + endpointset := query.NewEndpointSet(time.Now, logger, reg, func() []*query.GRPCEndpointSpec { |
| 317 | + endpointConfig := configProvider.config() |
| 318 | + |
| 319 | + specs := make([]*query.GRPCEndpointSpec, 0) |
| 320 | + for _, ecfg := range endpointConfig.Endpoints { |
| 321 | + strict, group, addr := ecfg.Strict, ecfg.Group, ecfg.Address |
| 322 | + if dns.IsDynamicNode(addr) { |
| 323 | + continue |
| 324 | + } |
| 325 | + if group { |
| 326 | + specs = append(specs, query.NewGRPCEndpointSpec(fmt.Sprintf("thanos:///%s", addr), strict, append(dialOpts, extgrpc.EndpointGroupGRPCOpts()...)...)) |
| 327 | + } else { |
| 328 | + specs = append(specs, query.NewGRPCEndpointSpec(addr, strict, dialOpts...)) |
| 329 | + } |
| 330 | + } |
| 331 | + for _, addr := range dnsEndpointProvider.Addresses() { |
| 332 | + specs = append(specs, query.NewGRPCEndpointSpec(addr, false, dialOpts...)) |
| 333 | + } |
| 334 | + return removeDuplicateEndpointSpecs(specs) |
| 335 | + }, unhealthyTimeout, endpointTimeout, queryConnMetricLabels...) |
| 336 | + |
| 337 | + g.Add(func() error { |
| 338 | + return runutil.Repeat(endpointTimeout, ctx.Done(), func() error { |
| 339 | + ctxIter, cancelIter := context.WithTimeout(ctx, endpointTimeout) |
| 340 | + defer cancelIter() |
| 341 | + |
| 342 | + endpointset.Update(ctxIter) |
| 343 | + return nil |
| 344 | + }) |
| 345 | + }, func(error) { |
| 346 | + cancel() |
| 347 | + }) |
| 348 | + |
| 349 | + return endpointset, nil |
| 350 | +} |
0 commit comments