2021-06-25 10:20:18 +00:00
|
|
|
package dockerswarm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/promscrape/discoveryutils"
|
2022-11-30 05:22:12 +00:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/promutils"
|
2021-06-25 10:20:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2022-11-30 05:22:12 +00:00
|
|
|
func getNetworksLabelsByNetworkID(cfg *apiConfig) (map[string]*promutils.Labels, error) {
|
2021-06-25 10:20:18 +00:00
|
|
|
networks, err := getNetworks(cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return getNetworkLabelsByNetworkID(networks), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getNetworks(cfg *apiConfig) ([]network, error) {
|
2023-01-12 06:50:34 +00:00
|
|
|
resp, err := cfg.getAPIResponse("/networks", "")
|
2021-06-25 10:20:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot query dockerswarm api for networks: %w", err)
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-11-30 05:22:12 +00:00
|
|
|
func getNetworkLabelsByNetworkID(networks []network) map[string]*promutils.Labels {
|
|
|
|
ms := make(map[string]*promutils.Labels)
|
2021-06-25 10:20:18 +00:00
|
|
|
for _, network := range networks {
|
2022-11-30 05:22:12 +00:00
|
|
|
m := promutils.NewLabels(8)
|
|
|
|
m.Add("__meta_dockerswarm_network_id", network.ID)
|
|
|
|
m.Add("__meta_dockerswarm_network_name", network.Name)
|
|
|
|
m.Add("__meta_dockerswarm_network_internal", strconv.FormatBool(network.Internal))
|
|
|
|
m.Add("__meta_dockerswarm_network_ingress", strconv.FormatBool(network.Ingress))
|
|
|
|
m.Add("__meta_dockerswarm_network_scope", network.Scope)
|
2021-06-25 10:20:18 +00:00
|
|
|
for k, v := range network.Labels {
|
2022-11-30 05:22:12 +00:00
|
|
|
m.Add(discoveryutils.SanitizeLabelName("__meta_dockerswarm_network_label_"+k), v)
|
2021-06-25 10:20:18 +00:00
|
|
|
}
|
|
|
|
ms[network.ID] = m
|
|
|
|
}
|
|
|
|
return ms
|
|
|
|
}
|