Skip to content

Instantly share code, notes, and snippets.

@mohatb
Last active April 30, 2023 15:27
Show Gist options
  • Select an option

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

Select an option

Save mohatb/87c48943b227efdb6e0105aaa205eeb9 to your computer and use it in GitHub Desktop.
get container info (omit empty) sample to compare with the map
package main
import (
"context"
"encoding/json"
"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 {
// Create a cAdvisor ContainerInfo struct with the container's information
info := cadvisorapi.ContainerInfo{
ContainerReference: cadvisorapi.ContainerReference{
Name: container.ID(),
},
}
// Marshal the struct into JSON
jsonInfo, err := json.MarshalIndent(info, "", " ")
if err != nil {
log.Fatalf("Failed to marshal container info: %v", err)
}
// Print the JSON string
fmt.Println("Printing JSON info (omit empty values)")
fmt.Println(string(jsonInfo))
fmt.Println()
fmt.Println("Printing golang Map info for comparison:")
fmt.Printf("%+v", info)
fmt.Println()
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment