-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdatadog.go
More file actions
69 lines (58 loc) · 2.01 KB
/
Copy pathdatadog.go
File metadata and controls
69 lines (58 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package fetchers
import (
"encoding/json"
"fmt"
"net/http"
"sort"
)
// DatadogFetcher implements the IPRangeFetcher interface for Datadog.
type DatadogFetcher struct{}
func (f DatadogFetcher) Name() string {
return "Datadog"
}
func (f DatadogFetcher) Description() string {
return "Fetches IP ranges used by Datadog services like the agent, APM, logs, and synthetics."
}
func (f DatadogFetcher) FetchIPRanges() ([]string, error) {
// https://docs.datadoghq.com/api/latest/ip-ranges/
const url = "https://ip-ranges.datadoghq.com/"
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to fetch Datadog IP ranges: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("received non-200 status code from Datadog: %d", resp.StatusCode)
}
// The payload is keyed by service (agents, api, apm, logs, synthetics, ...)
// alongside a couple of metadata fields (version, modified). Decode into raw
// messages so new services get picked up automatically, and skip anything
// that doesn't fit the prefixes shape.
var payload map[string]json.RawMessage
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return nil, fmt.Errorf("failed to unmarshal Datadog JSON: %v", err)
}
var ipRanges []string
for _, raw := range payload {
var prefixes struct {
PrefixesIPv4 []string `json:"prefixes_ipv4"`
PrefixesIPv6 []string `json:"prefixes_ipv6"`
}
if err := json.Unmarshal(raw, &prefixes); err != nil {
// version and modified are not objects, so they land here.
continue
}
ipRanges = append(ipRanges, prefixes.PrefixesIPv4...)
ipRanges = append(ipRanges, prefixes.PrefixesIPv6...)
}
// Services overlap and map iteration order isn't stable, so sort for a
// deterministic result and drop the duplicates that sorting makes adjacent.
sort.Strings(ipRanges)
unique := make([]string, 0, len(ipRanges))
for i, r := range ipRanges {
if i == 0 || r != ipRanges[i-1] {
unique = append(unique, r)
}
}
return unique, nil
}