utils.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. package esxi
  15. import (
  16. "context"
  17. "reflect"
  18. "github.com/vmware/govmomi/property"
  19. "github.com/vmware/govmomi/vim25"
  20. "github.com/vmware/govmomi/vim25/types"
  21. "yunion.io/x/log"
  22. )
  23. func Properties(c *vim25.Client, ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error {
  24. return property.DefaultCollector(c).RetrieveOne(ctx, r, ps, dst)
  25. }
  26. func moRefId(ref types.ManagedObjectReference) string {
  27. return ref.Value
  28. }
  29. func moRefType(ref types.ManagedObjectReference) string {
  30. return ref.Type
  31. }
  32. func FetchAnonymousFieldValue(val interface{}, target interface{}) bool {
  33. return fetchAnonymousFieldValue(reflect.Indirect(reflect.ValueOf(val)),
  34. reflect.Indirect(reflect.ValueOf(target)))
  35. }
  36. func fetchAnonymousFieldValue(value reflect.Value, target reflect.Value) bool {
  37. for i := 0; i < value.NumField(); i += 1 {
  38. fieldValue := value.Field(i)
  39. fieldStruct := value.Type().Field(i)
  40. if fieldStruct.Anonymous && fieldStruct.Type.Kind() == reflect.Struct {
  41. if fieldStruct.Type == target.Type() {
  42. target.Set(fieldValue)
  43. return true
  44. }
  45. succ := fetchAnonymousFieldValue(fieldValue, target)
  46. if succ {
  47. return true
  48. }
  49. }
  50. }
  51. return false
  52. }
  53. func reverseArray(array interface{}) {
  54. arrayValue := reflect.Indirect(reflect.ValueOf(array))
  55. if arrayValue.Kind() != reflect.Slice && arrayValue.Kind() != reflect.Array {
  56. log.Errorf("reverse non array or slice")
  57. return
  58. }
  59. tmp := reflect.Indirect(reflect.New(arrayValue.Type().Elem()))
  60. for i, j := 0, arrayValue.Len()-1; i < j; i, j = i+1, j-1 {
  61. tmpi := arrayValue.Index(i)
  62. tmpj := arrayValue.Index(j)
  63. tmp.Set(tmpi)
  64. tmpi.Set(tmpj)
  65. tmpj.Set(tmp)
  66. }
  67. }