|
- package tool
-
- import (
- "PCM/adaptor/PCM-CORE/model"
- "bytes"
- "encoding/json"
- "github.com/robfig/cron/v3"
- "io"
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime"
- syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml"
- kyaml "k8s.io/apimachinery/pkg/util/yaml"
- "mime/multipart"
- "sigs.k8s.io/yaml"
- "strconv"
- "strings"
- )
-
- // Convert 通过JSON赋值
- func Convert(source interface{}, target interface{}) {
- jsonByte, _ := json.Marshal(source)
- json.Unmarshal(jsonByte, &target)
- }
-
- // Int64ToString int64转string
- func Int64ToString(value int64) string {
- return strconv.FormatInt(value, 10)
- }
-
- // EntryIdToString EntryID转string
- func EntryIdToString(id cron.EntryID) string {
- return strconv.Itoa(int(id))
- }
-
- func StringToInt(value string) int {
- intValue, _ := strconv.Atoi(value)
- return intValue
- }
-
- func RunTimeToSeconds(runTime string) int {
- time := strings.Split(runTime, ":")
- day, _ := strconv.Atoi(time[0])
- hour, _ := strconv.Atoi(time[1])
- seconds, _ := strconv.Atoi(time[2])
- return day*3600 + hour*60 + seconds
- }
-
- func Yaml2struct(fileHeader *multipart.FileHeader, req interface{}) error {
- file, err := fileHeader.Open()
- if err != nil {
- return err
- }
- fileByte, err := io.ReadAll(file)
- if err != nil {
- return err
- }
- err = yaml.Unmarshal(fileByte, &req)
- if err != nil {
- return err
- }
- return nil
- }
-
- func K8sUnstructured(dataString string, target interface{}) {
- unstructuredList := unstructured.UnstructuredList{}
- json.Unmarshal([]byte(dataString), &unstructuredList)
- runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredList.UnstructuredContent(), target)
- }
-
- func UnMarshalK8sStruct(yamlString string, taskId int64) model.Cloud {
- var cloud model.Cloud
- d := kyaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(yamlString), 4096)
- var err error
- for {
- var rawObj runtime.RawExtension
- err = d.Decode(&rawObj)
- if err == io.EOF {
- break
- }
- if err != nil {
- }
- obj := &unstructured.Unstructured{}
- syaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).Decode(rawObj.Raw, nil, obj)
- if err != nil {
- }
-
- unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
- if err != nil {
- }
-
- unstructureObj := &unstructured.Unstructured{Object: unstructuredMap}
- cloud = model.Cloud{
- TaskId: taskId,
- ApiVersion: unstructureObj.GetAPIVersion(),
- Name: unstructureObj.GetName(),
- Kind: unstructureObj.GetKind(),
- Namespace: unstructureObj.GetNamespace(),
- Status: "Saved",
- ServiceName: "kubeNative",
- }
- }
- return cloud
- }
-
- // removeDuplication_map 去重数组
- func RemoveDuplication_map(arr []string) []string {
- set := make(map[string]struct{}, len(arr))
- j := 0
- for _, v := range arr {
- _, ok := set[v]
- if ok {
- continue
- }
- set[v] = struct{}{}
- arr[j] = v
- j++
- }
- return arr[:j]
- }
|