背景
使用 client-go与k8s交互
前提
k8s能外网访问,本地pc有kubeconfig文件
代码
package getResource
import (
"flag"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog"
"os"
"path/filepath"
"time"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func GetNode() {
clientset,err:=createClient()
if err!=nil{
klog.Error(err)
}
opts :=v1.ListOptions{
Limit: 100,
}
nodes,err:= clientset.CoreV1().Nodes().List(opts)
if err!=nil{
klog.Error(err)
}
for _,v:=range nodes.Items{
klog.Info(v.Name)
}
}
func GetPod(){
clientset,err:=createClient()
if err!=nil{
klog.Error(err)
}
opts :=v1.ListOptions{
Limit: 100,
}
podwatch,err:= clientset.CoreV1().Pods("default").Watch(opts)
if err!=nil{
klog.Error(err)
}
for {
select {
case e, ok := <-podwatch.ResultChan():
if !ok {
// 说明该通道已经被close掉了
klog.Warning("!!!!!podWatch chan has been close!!!!")
klog.Info("clean chan over!")
time.Sleep(time.Second * 5)
}
if e.Object != nil {
klog.Info("chan is ok")
klog.Info(e.Type)
klog.Info(e.Object.DeepCopyObject())
}
}
}
}
func GetDeployment(ns string){
clientset,err:=createClient()
if err!=nil{
klog.Error(err)
}
opts :=v1.ListOptions{
Watch: false,
}
dp, err := clientset.AppsV1().Deployments(ns).List(opts)
for _,v:=range dp.Items{
klog.Info(v.Name,v.Status,v.APIVersion)
}
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
func createClient()(clientset *kubernetes.Clientset ,err error){
var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
}
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err = kubernetes.NewForConfig(config)
return
}
func GetNamespace(){
clientset,err:=createClient()
if err!=nil{
klog.Error(err)
}
opts :=v1.ListOptions{
Watch: false,
}
ns, err := clientset.CoreV1().Namespaces().List(opts)
for _,v:=range ns.Items{
klog.Info(v.Name)
}
}
func GetCs(){
clientset,err:=createClient()
if err!=nil{
klog.Error(err)
}
opts :=v1.ListOptions{
Watch: false,
}
ns, err := clientset.CoreV1().ComponentStatuses().List(opts)
for _,v:=range ns.Items{
klog.Infof(v.Name,v.String())
}
}
func GetResource(){
GetPod()
//GetNamespace()
//GetCs()
}
执行结果
调用getpod的时候拿到了 watch信息,中间在集群中创建pod ,ResultChan就会输出相关pod信息
podwatch.ResultChan()
go run main.go
I1010 11:03:42.833273 78771 getNode.go:53] chan is ok
I1010 11:03:42.833385 78771 getNode.go:54] ADDED
I1010 11:03:42.833453 78771 getNode.go:55] &Pod{ObjectMeta:{qq-8b68b4978-nts68 qq-8b68b4978- default /api/v1/namespaces/default/pods/qq-8b68b4978-nts68 33882d9d-19a9-4eee-a719-c269cf9c6b09 270179437 0 2020-10-09 20:31:31 +0800 CST <nil> <nil> map[k8s-app:qq pod-template-hash:8b68b4978 qcloud-app:qq] map[tke.cloud.tencent.com/networks-status:[{
"name": "tke-bridge",
"ips": [
"172.20.0.5"
],
"default": true,
"dns": {}
}]] [{apps/v1 ReplicaSet qq-8b68b4978 49505799-9bfb-45cc-a1a4-ecb04668b954 0xc00059a050 0xc00059a051}] [] []},Spec:PodSpec{Volumes:[]Volume{Volume{Name:default-token-nxg8n,VolumeSource:VolumeSource{HostPath:nil,EmptyDir:nil,GCEPersistentDisk:nil,AWSElasticBlockStore:nil,GitRepo:nil,Secret:&SecretVolumeSource{SecretName:default-token-nxg8n,Items:[]KeyToPath{},DefaultMode:*420,Optional:nil,},NFS:nil,ISCSI:nil,Glusterfs:nil,PersistentVolumeClaim:nil,RBD:nil,FlexVolume:nil,Cinder:nil,CephFS:nil,Flocker:nil,DownwardAPI:nil,FC:nil,AzureFile:nil,ConfigMap:nil,VsphereVolume:nil,Quobyte:nil,AzureDisk:nil,PhotonPersistentDisk:nil,PortworxVolume:nil,ScaleIO:nil,Projected:nil,StorageOS:nil,CSI:nil,},},},Containers:[]Container{Container{Name:qq,Image:nginx,Command:[],Args:[],WorkingDir:,Ports:[]ContainerPort{},Env:[]EnvVar{},Resources:ResourceRequirements{Limits:ResourceList{cpu: {{500 -3} {<nil>} 500m DecimalSI},memory: {{1073741824 0} {<nil>} 1Gi BinarySI},},Requests:ResourceList{cpu: {{250 -3} {<nil>} 250m DecimalSI},memory: {{268435456 0} {<nil>} BinarySI},},},VolumeMounts:[]VolumeMount{VolumeMount{Name:default-token-nxg8n,ReadOnly:true,MountPath:/var/run/secrets/kubernetes.io/serviceaccount,SubPath:,MountPropagation:nil,SubPathExpr:,},},LivenessProbe:nil,ReadinessProbe:nil,Lifecycle:nil,TerminationMessagePath:/dev/termination-log,ImagePullPolicy:Always,SecurityContext:&SecurityContext{Capabilities:nil,Privileged:*false,SELinuxOptions:nil,RunAsUser:nil,RunAsNonRoot:nil,ReadOnlyRootFilesystem:nil,AllowPrivilegeEscalation:nil,RunAsGroup:nil,ProcMount:nil,WindowsOptions:nil,},Stdin:false,StdinOnce:false,TTY:false,EnvFrom:[]EnvFromSource{},TerminationMessagePolicy:File,VolumeDevices:[]VolumeDevice{},StartupProbe:nil,},},RestartPolicy:Always,TerminationGracePeriodSeconds:*30,ActiveDeadlineSeconds:nil,DNSPolicy:ClusterFirst,NodeSelector:map[string]string{},ServiceAccountName:default,DeprecatedServiceAccount:default,NodeName:10.0.11.122,HostNetwork:false,HostPID:false,HostIPC:false,SecurityContext:&PodSecurityContext{SELinuxOptions:nil,RunAsUser:nil,RunAsNonRoot:nil,SupplementalGroups:[],FSGroup:nil,RunAsGroup:nil,Sysctls:[]Sysctl{},WindowsOptions:nil,},ImagePullSecrets:[]LocalObjectReference{LocalObjectReference{Name:qcloudregistrykey,},},Hostname:,Subdomain:,Affinity:nil,SchedulerName:default-scheduler,InitContainers:[]Container{},AutomountServiceAccountToken:nil,Tolerations:[]Toleration{},HostAliases:[]HostAlias{},PriorityClassName:,Priority:nil,DNSConfig:nil,ShareProcessNamespace:nil,ReadinessGates:[]PodReadinessGate{},RuntimeClassName:nil,EnableServiceLinks:*true,PreemptionPolicy:nil,Overhead:ResourceList{},TopologySpreadConstraints:[]TopologySpreadConstraint{},EphemeralContainers:[]EphemeralContainer{},},Status:PodStatus{Phase:Running,Conditions:[]PodCondition{PodCondition{Type:Initialized,Status:True,LastProbeTime:0001-01-01 00:00:00 +0000 UTC,LastTransitionTime:2020-10-09 20:31:31 +0800 CST,Reason:,Message:,},PodCondition{Type:Ready,Status:True,LastProbeTime:0001-01-01 00:00:00 +0000 UTC,LastTransitionTime:2020-10-09 20:31:33 +0800 CST,Reason:,Message:,},PodCondition{Type:ContainersReady,Status:True,LastProbeTime:0001-01-01 00:00:00 +0000 UTC,LastTransitionTime:2020-10-09 20:31:33 +0800 CST,Reason:,Message:,},PodCondition{Type:PodScheduled,Status:True,LastProbeTime:0001-01-01 00:00:00 +0000 UTC,LastTransitionTime:2020-10-09 20:31:31 +0800 CST,Reason:,Message:,},},Message:,Reason:,HostIP:10.0.11.122,PodIP:172.20.0.5,StartTime:2020-10-09 20:31:31 +0800 CST,ContainerStatuses:[]ContainerStatus{ContainerStatus{Name:qq,State:ContainerState{Waiting:nil,Running:&ContainerStateRunning{StartedAt:2020-10-09 20:31:32 +0800 CST,},Terminated:nil,},LastTerminationState:ContainerState{Waiting:nil,Running:nil,Terminated:nil,},Ready:true,RestartCount:0,Image:nginx:latest,ImageID:docker-pullable://nginx@sha256:fc66cdef5ca33809823182c9c5d72ea86fd2cef7713cf3363e1a0b12a5d77500,ContainerID:docker://1b23a19956b852002848f2c5ecb88c7b87a9633ee79faf98a7a3d9ce003abdeb,Started:*true,},},QOSClass:Burstable,InitContainerStatuses:[]ContainerStatus{},NominatedNodeName:,PodIPs:[]PodIP{PodIP{IP:172.20.0.5,},},EphemeralContainerStatuses:[]ContainerStatus{},},}