yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/esxi/utils.go (about)

     1  // Copyright 2019 Yunion
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package esxi
    16  
    17  import (
    18  	"context"
    19  	"reflect"
    20  
    21  	"github.com/vmware/govmomi/property"
    22  	"github.com/vmware/govmomi/vim25"
    23  	"github.com/vmware/govmomi/vim25/types"
    24  
    25  	"yunion.io/x/log"
    26  )
    27  
    28  func Properties(c *vim25.Client, ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error {
    29  	return property.DefaultCollector(c).RetrieveOne(ctx, r, ps, dst)
    30  }
    31  
    32  func moRefId(ref types.ManagedObjectReference) string {
    33  	return ref.Value
    34  }
    35  
    36  func moRefType(ref types.ManagedObjectReference) string {
    37  	return ref.Type
    38  }
    39  
    40  func FetchAnonymousFieldValue(val interface{}, target interface{}) bool {
    41  	return fetchAnonymousFieldValue(reflect.Indirect(reflect.ValueOf(val)),
    42  		reflect.Indirect(reflect.ValueOf(target)))
    43  }
    44  
    45  func fetchAnonymousFieldValue(value reflect.Value, target reflect.Value) bool {
    46  	for i := 0; i < value.NumField(); i += 1 {
    47  		fieldValue := value.Field(i)
    48  		fieldStruct := value.Type().Field(i)
    49  		if fieldStruct.Anonymous && fieldStruct.Type.Kind() == reflect.Struct {
    50  			if fieldStruct.Type == target.Type() {
    51  				target.Set(fieldValue)
    52  				return true
    53  			}
    54  			succ := fetchAnonymousFieldValue(fieldValue, target)
    55  			if succ {
    56  				return true
    57  			}
    58  		}
    59  	}
    60  	return false
    61  }
    62  
    63  func reverseArray(array interface{}) {
    64  	arrayValue := reflect.Indirect(reflect.ValueOf(array))
    65  	if arrayValue.Kind() != reflect.Slice && arrayValue.Kind() != reflect.Array {
    66  		log.Errorf("reverse non array or slice")
    67  		return
    68  	}
    69  	tmp := reflect.Indirect(reflect.New(arrayValue.Type().Elem()))
    70  	for i, j := 0, arrayValue.Len()-1; i < j; i, j = i+1, j-1 {
    71  		tmpi := arrayValue.Index(i)
    72  		tmpj := arrayValue.Index(j)
    73  		tmp.Set(tmpi)
    74  		tmpi.Set(tmpj)
    75  		tmpj.Set(tmp)
    76  	}
    77  }