Created
April 30, 2023 13:32
-
-
Save mohatb/a9abb0465a9977f2869d8067595e8d47 to your computer and use it in GitHub Desktop.
collect containerd k8s labels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "fmt" | |
| "log" | |
| "github.com/containerd/containerd" | |
| "github.com/containerd/containerd/namespaces" | |
| cadvisorapi "github.com/google/cadvisor/info/v1" | |
| ) | |
| const ( | |
| socketPath = "/run/containerd/containerd.sock" | |
| ) | |
| func main() { | |
| // Set the namespace to "k8s.io" | |
| ctx := namespaces.WithNamespace(context.Background(), "k8s.io") | |
| // Connect to containerd | |
| client, err := containerd.New(socketPath) | |
| if err != nil { | |
| log.Fatalf("Failed to connect to containerd: %v", err) | |
| } | |
| defer client.Close() | |
| // List all containers in the specified namespace | |
| containers, err := client.Containers(ctx) | |
| if err != nil { | |
| log.Fatalf("Failed to list containers: %v", err) | |
| } | |
| // Iterate through the containers | |
| for _, container := range containers { | |
| // Get labels for the container | |
| labels, err := getLabels(ctx, container) | |
| if err != nil { | |
| log.Printf("Failed to get labels for container %s: %v", container.ID(), err) | |
| continue | |
| } | |
| // Create a cAdvisor ContainerInfo struct with the container's information | |
| info := cadvisorapi.ContainerInfo{ | |
| ContainerReference: cadvisorapi.ContainerReference{ | |
| Name: container.ID(), | |
| }, | |
| Spec: cadvisorapi.ContainerSpec{ | |
| Labels: labels, | |
| }, | |
| } | |
| // Print the container information | |
| fmt.Printf("Container Info: %+v\n", info) | |
| fmt.Printf("%#v\n", cadvisorapi.ContainerInfo{}) | |
| fmt.Println() | |
| } | |
| } | |
| // getLabels collects labels from a container and returns them as a map | |
| func getLabels(ctx context.Context, container containerd.Container) (map[string]string, error) { | |
| labels := make(map[string]string) | |
| // Get container information | |
| info, err := container.Info(ctx) | |
| if err != nil { | |
| return nil, err | |
| } | |
| // Iterate through the labels and add them to the map | |
| for k, v := range info.Labels { | |
| labels[k] = v | |
| } | |
| return labels, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment