2021-06-25 08:42:47 +00:00
|
|
|
package docker
|
2020-10-12 10:38:21 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/promscrape/discoveryutils"
|
|
|
|
)
|
|
|
|
|
|
|
|
// See https://docs.docker.com/engine/api/v1.40/#tag/Network
|
|
|
|
type network struct {
|
|
|
|
ID string
|
|
|
|
Name string
|
|
|
|
Scope string
|
|
|
|
Internal bool
|
|
|
|
Ingress bool
|
|
|
|
Labels map[string]string
|
|
|
|
}
|
|
|
|
|
2021-06-25 10:20:18 +00:00
|
|
|
func getNetworksLabelsByNetworkID(cfg *apiConfig) (map[string]map[string]string, error) {
|
2020-10-12 10:38:21 +00:00
|
|
|
networks, err := getNetworks(cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-06-25 10:20:18 +00:00
|
|
|
return getNetworkLabelsByNetworkID(networks), nil
|
2020-10-12 10:38:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func getNetworks(cfg *apiConfig) ([]network, error) {
|
2020-11-23 14:26:52 +00:00
|
|
|
resp, err := cfg.getAPIResponse("/networks")
|
2020-10-12 10:38:21 +00:00
|
|
|
if err != nil {
|
2021-06-25 10:20:18 +00:00
|
|
|
return nil, fmt.Errorf("cannot query dockerswarm api for networks: %w", err)
|
2020-10-12 10:38:21 +00:00
|
|
|
}
|
|
|
|
return parseNetworks(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseNetworks(data []byte) ([]network, error) {
|
|
|
|
var networks []network
|
|
|
|
if err := json.Unmarshal(data, &networks); err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot parse networks: %w", err)
|
|
|
|
}
|
|
|
|
return networks, nil
|
|
|
|
}
|
|
|
|
|
2021-06-25 10:20:18 +00:00
|
|
|
func getNetworkLabelsByNetworkID(networks []network) map[string]map[string]string {
|
2020-10-12 13:12:36 +00:00
|
|
|
ms := make(map[string]map[string]string)
|
2020-10-12 10:38:21 +00:00
|
|
|
for _, network := range networks {
|
|
|
|
m := map[string]string{
|
2021-06-25 10:20:18 +00:00
|
|
|
"__meta_docker_network_id": network.ID,
|
|
|
|
"__meta_docker_network_name": network.Name,
|
|
|
|
"__meta_docker_network_internal": strconv.FormatBool(network.Internal),
|
|
|
|
"__meta_docker_network_ingress": strconv.FormatBool(network.Ingress),
|
|
|
|
"__meta_docker_network_scope": network.Scope,
|
2020-10-12 10:38:21 +00:00
|
|
|
}
|
|
|
|
for k, v := range network.Labels {
|
2022-08-26 21:12:39 +00:00
|
|
|
m[discoveryutils.SanitizeLabelName("__meta_docker_network_label_"+k)] = v
|
2020-10-12 10:38:21 +00:00
|
|
|
}
|
2020-10-12 13:12:36 +00:00
|
|
|
ms[network.ID] = m
|
2020-10-12 10:38:21 +00:00
|
|
|
}
|
|
|
|
return ms
|
|
|
|
}
|