Skip to content

Instantly share code, notes, and snippets.

@mohatb
Created April 29, 2023 11:32
Show Gist options
  • Select an option

  • Save mohatb/d14059913cb8a2c4e3ec13cf5d396261 to your computer and use it in GitHub Desktop.

Select an option

Save mohatb/d14059913cb8a2c4e3ec13cf5d396261 to your computer and use it in GitHub Desktop.
script that calls containerd api and prints the labels
package main
import (
"context"
"fmt"
"strings"
"github.com/containerd/containerd"
"github.com/containerd/containerd/namespaces"
)
func getContainersPrometheusLabels(containerdSocket, namespace string) (map[string]map[string]string, error) {
client, err := containerd.New(containerdSocket)
if err != nil {
return nil, fmt.Errorf("failed to connect to containerd: %v", err)
}
defer client.Close()
ctx := namespaces.WithNamespace(context.Background(), namespace)
containerService := client.ContainerService()
containers, err := containerService.List(ctx)
if err != nil {
return nil, fmt.Errorf("failed to list containers: %v", err)
}
containerLabels := make(map[string]map[string]string)
for _, container := range containers {
containerID := container.ID
labels := make(map[string]string)
ids := make(map[string]string)
ids["containerd_namespace"] = containerID
ids["containerd_pod_sandbox_id"] = container.Labels["io.kubernetes.pod.uid"]
containerName := container.Labels["io.kubernetes.container.name"]
containerPrometheusLabelsFunc := func(labels, ids map[string]string, name string) map[string]string {
labels["id"] = name
labels["containerd_namespace"] = ids["containerd_namespace"]
labels["containerd_pod_sandbox_id"] = ids["containerd_pod_sandbox_id"]
labels["container_name"] = name
for k, v := range container.Labels {
labels[k] = v
}
return labels
}
containerLabels[containerID] = containerPrometheusLabelsFunc(labels, ids, containerName)
// Print the labels for this container
fmt.Printf("Labels for container %s:\n", containerID)
for k, v := range container.Labels {
fmt.Printf("%s=%s\n", k, v)
}
fmt.Println()
}
return containerLabels, nil
}
func main() {
containerdSocket := "/run/containerd/containerd.sock"
namespace := "k8s.io"
containerLabels, err := getContainersPrometheusLabels(containerdSocket, namespace)
if err != nil {
fmt.Printf("Error fetching container labels: %v\n", err)
return
}
fmt.Printf("Labels for containers in namespace %s:\n\n", namespace)
fmt.Printf("%-70s %-25s %-40s %-25s\n", "Container ID", "Container Name", "Container Namespace", "Pod Sandbox ID")
fmt.Println(strings.Repeat("-", 160))
for containerID, labels := range containerLabels {
fmt.Printf("%-70s %-25s %-40s %-25s\n",
containerID,
labels["container_name"],
labels["containerd_namespace"],
labels["containerd_pod_sandbox_id"],
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment