forked from nudtpc/pcm-kubernetes
82 lines
2.2 KiB
Go
82 lines
2.2 KiB
Go
package pkg
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"github.com/sirupsen/logrus"
|
|
"io"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/util/yaml"
|
|
"k8s.io/client-go/dynamic"
|
|
kubernetes2 "k8s.io/client-go/kubernetes"
|
|
"k8s.io/client-go/restmapper"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
func Delete(yamlString string, clientSet *kubernetes2.Clientset, dynamicClient dynamic.Interface) {
|
|
d := yaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(yamlString), 4096)
|
|
|
|
dc := clientSet.Discovery()
|
|
restMapperRes, err := restmapper.GetAPIGroupResources(dc)
|
|
if err != nil {
|
|
logx.WithContext(context.TODO()).Errorf("delete %v \n", err)
|
|
|
|
}
|
|
restMapper := restmapper.NewDiscoveryRESTMapper(restMapperRes)
|
|
|
|
for {
|
|
ext := runtime.RawExtension{}
|
|
|
|
if err := d.Decode(&ext); err != nil {
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
logx.WithContext(context.TODO()).Errorf("delete %v \n", err)
|
|
}
|
|
|
|
obj, gvk, err := unstructured.UnstructuredJSONScheme.Decode(ext.Raw, nil, nil)
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
}
|
|
|
|
mapping, err := restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
}
|
|
|
|
// runtime.Object转换为unstructed
|
|
unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
}
|
|
|
|
var unstruct unstructured.Unstructured
|
|
|
|
unstruct.Object = unstructuredObj
|
|
|
|
tmpMetadata := unstructuredObj["metadata"].(map[string]interface{})
|
|
tmpName := tmpMetadata["name"].(string)
|
|
tmpKind := unstructuredObj["kind"].(string)
|
|
|
|
if unstruct.GetNamespace() == "" {
|
|
unstruct.SetNamespace("default")
|
|
}
|
|
logrus.Info("deleting resource name: " + tmpName + ", kind: " + tmpKind + ", ns: " + unstruct.GetNamespace())
|
|
|
|
if unstruct.GetNamespace() == "" {
|
|
err := dynamicClient.Resource(mapping.Resource).Delete(context.TODO(), tmpName, metav1.DeleteOptions{})
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
}
|
|
} else {
|
|
err := dynamicClient.Resource(mapping.Resource).Namespace(unstruct.GetNamespace()).Delete(context.TODO(), tmpName, metav1.DeleteOptions{})
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
}
|
|
}
|
|
}
|
|
}
|