Jack Moore

Email: jack(at)jmoore53.com
Project Updates

Go!

20 Feb 2022 » kubernetes, golang, programming, software
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Note: the example only works with the code within the same release/branch.
package main

import (
    "context"
    "flag"
    "fmt"
    "path/filepath"

    "k8s.io/apimachinery/pkg/api/errors"
    "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    "k8s.io/apimachinery/pkg/runtime/schema"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/homedir"

    "k8s.io/client-go/dynamic"
    //Uncomment to load all auth plugins
    // _ "k8s.io/client-go/plugin/pkg/client/auth"
    //Or uncomment to load specific auth plugins
    // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
    // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
    // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
    // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()

    // use the current context in kubeconfig
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err.Error())
    }

    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }

    // Get all deployments
    namespace := "minecraft"
    resource := "deployments"
    fmt.Printf("Listing %q in all namespaces:\n", resource)
    //deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    client, err := dynamic.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    list, err := client.Resource(deploymentRes).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})
    if err != nil {
        panic(err)
    }
    for _, d := range list.Items {
        namespaces, found, err := unstructured.NestedString(d.Object, "metadata", "name")
        if err != nil || !found {
            fmt.Printf("Replicas not found for deployment %s: error=%s", d.GetName(), err)
            continue
        }
        fmt.Printf(" * %s \n", namespaces)
    }

    // Get all pods
    namespace := "minecraft"
    resource := "deployments"
    fmt.Printf("Listing %q in all namespaces:\n", resource)
    //deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    client, err := dynamic.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    list, err := client.Resource(deploymentRes).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})
    if err != nil {
        panic(err)
    }
    for _, d := range list.Items {
        namespaces, found, err := unstructured.NestedString(d.Object, "metadata", "name")
        if err != nil || !found {
            fmt.Printf("Replicas not found for deployment %s: error=%s", d.GetName(), err)
            continue
        }
        fmt.Printf(" * %s \n", namespaces)
    }

    // Get all pvc
    namespace = "minecraft"
    resource = "PersistentVolume"
    fmt.Printf("Listing %q in all namespaces:\n", resource)
    //deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    deploymentRes = schema.GroupVersionResource{Version: "v1", Resource: "services"}
    client, err = dynamic.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    list, err = client.Resource(deploymentRes).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})
    if err != nil {
        panic(err)
    }
    for _, d := range list.Items {
        namespaces, found, err := unstructured.NestedString(d.Object, "metadata", "name")
        if err != nil || !found {
            fmt.Printf("Replicas not found for deployment %s: error=%s", d.GetName(), err)
            continue
        }
        fmt.Printf(" * %s \n", namespaces)
    }

    // List deployments in namespace
    namespace = "minecraft"
    resource = "PVC"
    fmt.Printf("Listing %q in all namespaces:\n", resource)
    //deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    //deploymentRes = schema.GroupVersionResource{Group: "core", Version: "v1", Resource: "PersistentVolumeClaim"}
    client, err = dynamic.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    pvcs, err := clientset.CoreV1().PersistentVolumeClaims(namespace).List(context.TODO(), metav1.ListOptions{})
    //list, err = client.Resource(deploymentRes).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})
    if err != nil {
        panic(err)
    }
    for _, d := range pvcs.Items {
        //pvcs, found, err := unstructured.NestedStringMap(d, "metadata", "name")
        //if err != nil || !found {
        //  fmt.Printf("Replicas not found for deployment %s: error=%s", d.GetName(), err)
        //  continue
        //}
        fmt.Printf(" * %s :: PVC is located in :: %s \n", d.Name, d.Namespace)
    }
    fmt.Printf("There are %d pvc's in the cluster\n", len(pvcs.Items))

    //for {
    pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))

    // Examples for error handling:
    // - Use helper functions like e.g. errors.IsNotFound()
    // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
    namespace = "minecraft"
    pod := "minecraft-server-world0-6b74d9ffdf-9cvz6"
    _, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{})
    if errors.IsNotFound(err) {
        fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)
    } else if statusError, isStatus := err.(*errors.StatusError); isStatus {
        fmt.Printf("Error getting pod %s in namespace %s: %v\n",
            pod, namespace, statusError.ErrStatus.Message)
    } else if err != nil {
    panic(err.Error())
    } else {
        fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)
    }

    //time.Sleep(10 * time.Second)
    //}
}
© Jack Moore