1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| package main
import ( "bytes" "fmt" "io" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml" "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/restmapper" "kube-base3/lib/kubeConfig" "log" "os/exec" )
func kust(path string) []byte { cmd := exec.Command("kustomize", "build", path) var ret bytes.Buffer cmd.Stdout = &ret if err := cmd.Run(); err != nil { fmt.Println(err) return nil } return ret.Bytes() } func main() { client := kubeConfig.InitClient() b := kust("pkg/deploy") decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(b), len(b))
for { var rawObj runtime.RawExtension err := decoder.Decode(&rawObj)
if err != nil { if err == io.EOF { break } else { log.Fatal(err) }
} fmt.Println("这个是raw", rawObj, "raw结束")
obj, gvk, err := syaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme). Decode(rawObj.Raw, nil, nil) if err != nil { log.Fatal(err) } fmt.Println("这个是obj", obj, "obj结束") fmt.Println("这个是gvk", gvk, "gvk结束")
unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) if err != nil { log.Fatal(err) } fmt.Println("这个是unstructuredMap", unstructuredMap, "unstructured结束")
unstructuredObj := &unstructured.Unstructured{Object: unstructuredMap} fmt.Println("这个是unstructuredobj", unstructuredObj, "unstructuredobj结束")
gr, err := restmapper.GetAPIGroupResources(client.Discovery()) if err != nil { log.Fatal(err) }
mapper := restmapper.NewDiscoveryRESTMapper(gr) mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) if err != nil { log.Fatal(err) }
gvr := schema.GroupVersionResource{ Group: mapping.Resource.Group, Version: mapping.Resource.Version, Resource: mapping.Resource.Resource, }
gvk1, err := mapper.KindFor(gvr) if err != nil { log.Fatal(err) } fmt.Println("这是gvk1", gvk1, "gvk1结束")
} }
|