repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/progress/scale.go | vendor/github.com/vmware/govmomi/vim25/progress/scale.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package progress
type scaledReport struct {
Report
n int
i int
}
func (r scaledReport) Percentage() float32 {
b := 100 * float32(r.i) / float32(r.n)
return b + (r.Report.Percentage() / float32(r.n))
}
type scaleOne struct {
s Sinker
n int
i int
}
func (s scaleOne) Sink() chan<- Report {
upstream := make(chan Report)
downstream := s.s.Sink()
go s.loop(upstream, downstream)
return upstream
}
func (s scaleOne) loop(upstream <-chan Report, downstream chan<- Report) {
defer close(downstream)
for r := range upstream {
downstream <- scaledReport{
Report: r,
n: s.n,
i: s.i,
}
}
}
type scaleMany struct {
s Sinker
n int
i int
}
func Scale(s Sinker, n int) Sinker {
return &scaleMany{
s: s,
n: n,
}
}
func (s *scaleMany) Sink() chan<- Report {
if s.i == s.n {
s.n++
}
ch := scaleOne{s: s.s, n: s.n, i: s.i}.Sink()
s.i++
return ch
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/progress/loger.go | vendor/github.com/vmware/govmomi/vim25/progress/loger.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package progress
import (
"fmt"
"io"
"sync"
"time"
)
type LogFunc func(msg string) (int, error)
type ProgressLogger struct {
log LogFunc
prefix string
wg sync.WaitGroup
sink chan chan Report
done chan struct{}
}
func NewProgressLogger(log LogFunc, prefix string) *ProgressLogger {
p := &ProgressLogger{
log: log,
prefix: prefix,
sink: make(chan chan Report),
done: make(chan struct{}),
}
p.wg.Add(1)
go p.loopA()
return p
}
// loopA runs before Sink() has been called.
func (p *ProgressLogger) loopA() {
var err error
defer p.wg.Done()
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
called := false
for stop := false; !stop; {
select {
case ch := <-p.sink:
err = p.loopB(tick, ch)
stop = true
called = true
case <-p.done:
stop = true
case <-tick.C:
line := fmt.Sprintf("\r%s", p.prefix)
p.log(line)
}
}
if err != nil && err != io.EOF {
p.log(fmt.Sprintf("\r%sError: %s\n", p.prefix, err))
} else if called {
p.log(fmt.Sprintf("\r%sOK\n", p.prefix))
}
}
// loopA runs after Sink() has been called.
func (p *ProgressLogger) loopB(tick *time.Ticker, ch <-chan Report) error {
var r Report
var ok bool
var err error
for ok = true; ok; {
select {
case r, ok = <-ch:
if !ok {
break
}
err = r.Error()
case <-tick.C:
line := fmt.Sprintf("\r%s", p.prefix)
if r != nil {
line += fmt.Sprintf("(%.0f%%", r.Percentage())
detail := r.Detail()
if detail != "" {
line += fmt.Sprintf(", %s", detail)
}
line += ")"
}
p.log(line)
}
}
return err
}
func (p *ProgressLogger) Sink() chan<- Report {
ch := make(chan Report)
p.sink <- ch
return ch
}
func (p *ProgressLogger) Wait() {
close(p.done)
p.wg.Wait()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/progress/report.go | vendor/github.com/vmware/govmomi/vim25/progress/report.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package progress
// Report defines the interface for types that can deliver progress reports.
// Examples include uploads/downloads in the http client and the task info
// field in the task managed object.
type Report interface {
Percentage() float32
Detail() string
Error() error
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/progress/doc.go | vendor/github.com/vmware/govmomi/vim25/progress/doc.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package progress
/*
The progress package contains functionality to deal with progress reporting.
The functionality is built to serve progress reporting for infrastructure
operations when talking the vSphere API, but is generic enough to be used
elsewhere.
At the core of this progress reporting API lies the Sinker interface. This
interface is implemented by any object that can act as a sink for progress
reports. Callers of the Sink() function receives a send-only channel for
progress reports. They are responsible for closing the channel when done.
This semantic makes it easy to keep track of multiple progress report channels;
they are only created when Sink() is called and assumed closed when any
function that receives a Sinker parameter returns.
*/
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/json.go | vendor/github.com/vmware/govmomi/vim25/types/json.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"bytes"
"io"
"reflect"
"time"
"github.com/vmware/govmomi/vim25/json"
)
const (
discriminatorMemberName = "_typeName"
primitiveValueMemberName = "_value"
)
var discriminatorTypeRegistry = map[string]reflect.Type{
"boolean": reflect.TypeOf(true),
"byte": reflect.TypeOf(uint8(0)),
"short": reflect.TypeOf(int16(0)),
"int": reflect.TypeOf(int32(0)),
"long": reflect.TypeOf(int64(0)),
"float": reflect.TypeOf(float32(0)),
"double": reflect.TypeOf(float64(0)),
"string": reflect.TypeOf(""),
"binary": reflect.TypeOf([]byte{}),
"dateTime": reflect.TypeOf(time.Now()),
}
// NewJSONDecoder creates JSON decoder configured for VMOMI.
func NewJSONDecoder(r io.Reader) *json.Decoder {
res := json.NewDecoder(r)
res.SetDiscriminator(
discriminatorMemberName,
primitiveValueMemberName,
json.DiscriminatorToTypeFunc(func(name string) (reflect.Type, bool) {
if res, ok := TypeFunc()(name); ok {
return res, true
}
if res, ok := discriminatorTypeRegistry[name]; ok {
return res, true
}
return nil, false
}),
)
return res
}
// VMOMI primitive names
var discriminatorNamesRegistry = map[reflect.Type]string{
reflect.TypeOf(true): "boolean",
reflect.TypeOf(uint8(0)): "byte",
reflect.TypeOf(int16(0)): "short",
reflect.TypeOf(int32(0)): "int",
reflect.TypeOf(int64(0)): "long",
reflect.TypeOf(float32(0)): "float",
reflect.TypeOf(float64(0)): "double",
reflect.TypeOf(""): "string",
reflect.TypeOf([]byte{}): "binary",
reflect.TypeOf(time.Now()): "dateTime",
}
// NewJSONEncoder creates JSON encoder configured for VMOMI.
func NewJSONEncoder(w *bytes.Buffer) *json.Encoder {
enc := json.NewEncoder(w)
enc.SetDiscriminator(
discriminatorMemberName,
primitiveValueMemberName,
json.DiscriminatorEncodeTypeNameRootValue|
json.DiscriminatorEncodeTypeNameAllObjects,
)
enc.SetTypeToDiscriminatorFunc(VmomiTypeName)
return enc
}
// VmomiTypeName computes the VMOMI type name of a go type. It uses a lookup
// table for VMOMI primitive types and the default discriminator function for
// other types.
func VmomiTypeName(t reflect.Type) (discriminator string) {
// Look up primitive type names from VMOMI protocol
if name, ok := discriminatorNamesRegistry[t]; ok {
return name
}
name := json.DefaultDiscriminatorFunc(t)
return name
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/byte_slice.go | vendor/github.com/vmware/govmomi/vim25/types/byte_slice.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"fmt"
"io"
"math"
"strconv"
"github.com/vmware/govmomi/vim25/xml"
)
// ByteSlice implements vCenter compatibile xml encoding and decoding for a byte slice.
// vCenter encodes each byte of the array in its own xml element, whereas
// Go encodes the entire byte array in a single xml element.
type ByteSlice []byte
// MarshalXML implements xml.Marshaler
func (b ByteSlice) MarshalXML(e *xml.Encoder, field xml.StartElement) error {
start := xml.StartElement{
Name: field.Name,
}
for i := range b {
// Using int8() here to output a signed byte (issue #3615)
if err := e.EncodeElement(int8(b[i]), start); err != nil {
return err
}
}
return nil
}
// UnmarshalXML implements xml.Unmarshaler
func (b *ByteSlice) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
for {
t, err := d.Token()
if err == io.EOF {
break
}
if c, ok := t.(xml.CharData); ok {
n, err := strconv.ParseInt(string(c), 10, 16)
if err != nil {
return err
}
if n > math.MaxUint8 {
return fmt.Errorf("parsing %q: uint8 overflow", start.Name.Local)
}
*b = append(*b, byte(n))
}
}
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/base.go | vendor/github.com/vmware/govmomi/vim25/types/base.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
type AnyType any
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/registry.go | vendor/github.com/vmware/govmomi/vim25/types/registry.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"reflect"
"strings"
)
var (
t = map[string]reflect.Type{}
// minAPIVersionForType is used to lookup the minimum API version for which
// a type is valid.
minAPIVersionForType = map[string]string{}
// minAPIVersionForEnumValue is used to lookup the minimum API version for
// which an enum value is valid.
minAPIVersionForEnumValue = map[string]map[string]string{}
)
func Add(name string, kind reflect.Type) {
t[name] = kind
}
func AddMinAPIVersionForType(name, minAPIVersion string) {
minAPIVersionForType[name] = minAPIVersion
}
func AddMinAPIVersionForEnumValue(enumName, enumValue, minAPIVersion string) {
if v, ok := minAPIVersionForEnumValue[enumName]; ok {
v[enumValue] = minAPIVersion
} else {
minAPIVersionForEnumValue[enumName] = map[string]string{
enumValue: minAPIVersion,
}
}
}
type Func func(string) (reflect.Type, bool)
func TypeFunc() Func {
return func(name string) (reflect.Type, bool) {
typ, ok := t[name]
if !ok {
// The /sdk endpoint does not prefix types with the namespace,
// but extension endpoints, such as /pbm/sdk do.
name = strings.TrimPrefix(name, "vim25:")
typ, ok = t[name]
}
return typ, ok
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/types.go | vendor/github.com/vmware/govmomi/vim25/types/types.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"reflect"
"time"
)
type AbandonHciWorkflow AbandonHciWorkflowRequestType
func init() {
t["AbandonHciWorkflow"] = reflect.TypeOf((*AbandonHciWorkflow)(nil)).Elem()
}
type AbandonHciWorkflowRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
}
func init() {
t["AbandonHciWorkflowRequestType"] = reflect.TypeOf((*AbandonHciWorkflowRequestType)(nil)).Elem()
}
type AbandonHciWorkflowResponse struct {
}
type AbdicateDomOwnership AbdicateDomOwnershipRequestType
func init() {
t["AbdicateDomOwnership"] = reflect.TypeOf((*AbdicateDomOwnership)(nil)).Elem()
}
// The parameters of `HostVsanInternalSystem.AbdicateDomOwnership`.
type AbdicateDomOwnershipRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// List of VSAN/DOM object UUIDs.
Uuids []string `xml:"uuids" json:"uuids"`
}
func init() {
t["AbdicateDomOwnershipRequestType"] = reflect.TypeOf((*AbdicateDomOwnershipRequestType)(nil)).Elem()
}
type AbdicateDomOwnershipResponse struct {
Returnval []string `xml:"returnval,omitempty" json:"returnval,omitempty"`
}
// The parameters of `VirtualMachineGuestCustomizationManager.AbortCustomization_Task`.
type AbortCustomizationRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The Virtual Machine managed object reference.
//
// Refers instance of `VirtualMachine`.
Vm ManagedObjectReference `xml:"vm" json:"vm"`
// The guest authentication data. See
// `GuestAuthentication`.
Auth BaseGuestAuthentication `xml:"auth,typeattr" json:"auth"`
}
func init() {
t["AbortCustomizationRequestType"] = reflect.TypeOf((*AbortCustomizationRequestType)(nil)).Elem()
}
type AbortCustomization_Task AbortCustomizationRequestType
func init() {
t["AbortCustomization_Task"] = reflect.TypeOf((*AbortCustomization_Task)(nil)).Elem()
}
type AbortCustomization_TaskResponse struct {
Returnval ManagedObjectReference `xml:"returnval" json:"returnval"`
}
// This data object type describes system information
// including the name, type, version, and build number.
type AboutInfo struct {
DynamicData
// Short form of the product name.
Name string `xml:"name" json:"name"`
// The complete product name, including the version information.
FullName string `xml:"fullName" json:"fullName"`
// Name of the vendor of this product.
Vendor string `xml:"vendor" json:"vendor"`
// Dot-separated product version string.
//
// For example, "10.0.2.0".
Version string `xml:"version" json:"version"`
// Patch level for the server.
PatchLevel string `xml:"patchLevel,omitempty" json:"patchLevel,omitempty" vim:"7.0.2.0"`
// Build string for the server on which this call is made.
//
// For example, x.y.z-num.
// This string does not apply to the API.
Build string `xml:"build" json:"build"`
// Version of the message catalog for the current session's locale.
LocaleVersion string `xml:"localeVersion,omitempty" json:"localeVersion,omitempty"`
// Build number for the current session's locale.
//
// Typically, this is a small number reflecting a
// localization change from the normal product build.
LocaleBuild string `xml:"localeBuild,omitempty" json:"localeBuild,omitempty"`
// Operating system type and architecture.
//
// Examples of values are:
// - "win32-x86" - For x86-based Windows systems.
// - "linux-x86" - For x86-based Linux systems.
// - "vmnix-x86" - For the x86 ESX Server microkernel.
// - "vmnix-arm64" - For the arm64 ESX Server microkernel.
OsType string `xml:"osType" json:"osType"`
// The product ID is a unique identifier for a product line.
//
// Examples of values are:
// - "gsx" - For the VMware Server product.
// - "esx" - For the ESX product.
// - "embeddedEsx" - For the ESXi product.
// - "esxio" - For the ESXio product.
// - "vpx" - For the VirtualCenter product.
ProductLineId string `xml:"productLineId" json:"productLineId"`
// Indicates whether or not the service instance represents a
// standalone host.
//
// If the service instance represents a standalone host, then the physical
// inventory for that service instance is fixed to that single host.
// VirtualCenter server provides additional features over single hosts.
// For example, VirtualCenter offers multi-host management.
//
// Examples of values are:
// - "VirtualCenter" - For a VirtualCenter instance.
// - "HostAgent" - For host agent on an ESX Server or VMware Server host.
ApiType string `xml:"apiType" json:"apiType"`
// The newest long-term supported API version provided by the server.
//
// The version format is "x.y.z.a", where "x", "y", and "z" are numbers
// that do not exceed 99, and "a" does not exceed 9999.
ApiVersion string `xml:"apiVersion" json:"apiVersion"`
// A globally unique identifier associated with this service instance.
InstanceUuid string `xml:"instanceUuid,omitempty" json:"instanceUuid,omitempty"`
// The license product name
LicenseProductName string `xml:"licenseProductName,omitempty" json:"licenseProductName,omitempty"`
// The license product version
LicenseProductVersion string `xml:"licenseProductVersion,omitempty" json:"licenseProductVersion,omitempty"`
}
func init() {
t["AboutInfo"] = reflect.TypeOf((*AboutInfo)(nil)).Elem()
}
// This event records that an account was created on a host.
type AccountCreatedEvent struct {
HostEvent
Spec BaseHostAccountSpec `xml:"spec,typeattr" json:"spec"`
Group bool `xml:"group" json:"group"`
}
func init() {
t["AccountCreatedEvent"] = reflect.TypeOf((*AccountCreatedEvent)(nil)).Elem()
}
// This event records that an account was removed from a host.
type AccountRemovedEvent struct {
HostEvent
Account string `xml:"account" json:"account"`
Group bool `xml:"group" json:"group"`
}
func init() {
t["AccountRemovedEvent"] = reflect.TypeOf((*AccountRemovedEvent)(nil)).Elem()
}
// This event records that an account was updated on a host.
type AccountUpdatedEvent struct {
HostEvent
Spec BaseHostAccountSpec `xml:"spec,typeattr" json:"spec"`
Group bool `xml:"group" json:"group"`
// The previous account description
PrevDescription string `xml:"prevDescription,omitempty" json:"prevDescription,omitempty"`
}
func init() {
t["AccountUpdatedEvent"] = reflect.TypeOf((*AccountUpdatedEvent)(nil)).Elem()
}
type AcknowledgeAlarm AcknowledgeAlarmRequestType
func init() {
t["AcknowledgeAlarm"] = reflect.TypeOf((*AcknowledgeAlarm)(nil)).Elem()
}
// The parameters of `AlarmManager.AcknowledgeAlarm`.
type AcknowledgeAlarmRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The Alarm to acknowledge.
//
// Required privileges: Alarm.Acknowledge
//
// Refers instance of `Alarm`.
Alarm ManagedObjectReference `xml:"alarm" json:"alarm"`
// The ManagedEntity for which to acknowledge the Alarm.
//
// Required privileges: System.Read
//
// Refers instance of `ManagedEntity`.
Entity ManagedObjectReference `xml:"entity" json:"entity"`
}
func init() {
t["AcknowledgeAlarmRequestType"] = reflect.TypeOf((*AcknowledgeAlarmRequestType)(nil)).Elem()
}
type AcknowledgeAlarmResponse struct {
}
type AcquireCimServicesTicket AcquireCimServicesTicketRequestType
func init() {
t["AcquireCimServicesTicket"] = reflect.TypeOf((*AcquireCimServicesTicket)(nil)).Elem()
}
type AcquireCimServicesTicketRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
}
func init() {
t["AcquireCimServicesTicketRequestType"] = reflect.TypeOf((*AcquireCimServicesTicketRequestType)(nil)).Elem()
}
type AcquireCimServicesTicketResponse struct {
Returnval HostServiceTicket `xml:"returnval" json:"returnval"`
}
type AcquireCloneTicket AcquireCloneTicketRequestType
func init() {
t["AcquireCloneTicket"] = reflect.TypeOf((*AcquireCloneTicket)(nil)).Elem()
}
type AcquireCloneTicketRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
}
func init() {
t["AcquireCloneTicketRequestType"] = reflect.TypeOf((*AcquireCloneTicketRequestType)(nil)).Elem()
}
type AcquireCloneTicketResponse struct {
Returnval string `xml:"returnval" json:"returnval"`
}
type AcquireCredentialsInGuest AcquireCredentialsInGuestRequestType
func init() {
t["AcquireCredentialsInGuest"] = reflect.TypeOf((*AcquireCredentialsInGuest)(nil)).Elem()
}
// The parameters of `GuestAuthManager.AcquireCredentialsInGuest`.
type AcquireCredentialsInGuestRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// MoRef of the VM to perform the operation on.
//
// Required privileges: VirtualMachine.GuestOperations.Query
//
// Refers instance of `VirtualMachine`.
Vm ManagedObjectReference `xml:"vm" json:"vm"`
// The guest authentication data used to acquire credentials.
// See `GuestAuthentication`.
RequestedAuth BaseGuestAuthentication `xml:"requestedAuth,typeattr" json:"requestedAuth"`
// The sessionID number should be provided only when
// responding to a server challenge. The sessionID number to be used with
// the challenge is found in the
// `GuestAuthenticationChallenge` object.
SessionID int64 `xml:"sessionID,omitempty" json:"sessionID,omitempty"`
}
func init() {
t["AcquireCredentialsInGuestRequestType"] = reflect.TypeOf((*AcquireCredentialsInGuestRequestType)(nil)).Elem()
}
type AcquireCredentialsInGuestResponse struct {
Returnval BaseGuestAuthentication `xml:"returnval,typeattr" json:"returnval"`
}
type AcquireGenericServiceTicket AcquireGenericServiceTicketRequestType
func init() {
t["AcquireGenericServiceTicket"] = reflect.TypeOf((*AcquireGenericServiceTicket)(nil)).Elem()
}
// The parameters of `SessionManager.AcquireGenericServiceTicket`.
type AcquireGenericServiceTicketRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// specification for the service request which will be
// invoked with the ticket.
Spec BaseSessionManagerServiceRequestSpec `xml:"spec,typeattr" json:"spec"`
}
func init() {
t["AcquireGenericServiceTicketRequestType"] = reflect.TypeOf((*AcquireGenericServiceTicketRequestType)(nil)).Elem()
}
type AcquireGenericServiceTicketResponse struct {
Returnval SessionManagerGenericServiceTicket `xml:"returnval" json:"returnval"`
}
type AcquireLocalTicket AcquireLocalTicketRequestType
func init() {
t["AcquireLocalTicket"] = reflect.TypeOf((*AcquireLocalTicket)(nil)).Elem()
}
// The parameters of `SessionManager.AcquireLocalTicket`.
type AcquireLocalTicketRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// User requesting one-time password.
UserName string `xml:"userName" json:"userName"`
}
func init() {
t["AcquireLocalTicketRequestType"] = reflect.TypeOf((*AcquireLocalTicketRequestType)(nil)).Elem()
}
type AcquireLocalTicketResponse struct {
Returnval SessionManagerLocalTicket `xml:"returnval" json:"returnval"`
}
type AcquireMksTicket AcquireMksTicketRequestType
func init() {
t["AcquireMksTicket"] = reflect.TypeOf((*AcquireMksTicket)(nil)).Elem()
}
type AcquireMksTicketRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
}
func init() {
t["AcquireMksTicketRequestType"] = reflect.TypeOf((*AcquireMksTicketRequestType)(nil)).Elem()
}
type AcquireMksTicketResponse struct {
Returnval VirtualMachineMksTicket `xml:"returnval" json:"returnval"`
}
type AcquireTicket AcquireTicketRequestType
func init() {
t["AcquireTicket"] = reflect.TypeOf((*AcquireTicket)(nil)).Elem()
}
// The parameters of `VirtualMachine.AcquireTicket`.
type AcquireTicketRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The type of service to acquire, the set of possible
// values is described in `VirtualMachineTicketType_enum`.
TicketType string `xml:"ticketType" json:"ticketType"`
}
func init() {
t["AcquireTicketRequestType"] = reflect.TypeOf((*AcquireTicketRequestType)(nil)).Elem()
}
type AcquireTicketResponse struct {
Returnval VirtualMachineTicket `xml:"returnval" json:"returnval"`
}
// This data object type defines the action initiated by a scheduled task or alarm.
//
// This is an abstract type.
// A client creates a scheduled task or an alarm each of which triggers
// an action, defined by a subclass of this type.
type Action struct {
DynamicData
}
func init() {
t["Action"] = reflect.TypeOf((*Action)(nil)).Elem()
}
// Base fault for Active Directory related problems.
type ActiveDirectoryFault struct {
VimFault
// The error code reported by the Active Directory API.
ErrorCode int32 `xml:"errorCode,omitempty" json:"errorCode,omitempty"`
}
func init() {
t["ActiveDirectoryFault"] = reflect.TypeOf((*ActiveDirectoryFault)(nil)).Elem()
}
type ActiveDirectoryFaultFault BaseActiveDirectoryFault
func init() {
t["ActiveDirectoryFaultFault"] = reflect.TypeOf((*ActiveDirectoryFaultFault)(nil)).Elem()
}
// The `ActiveDirectoryProfile` data object represents Active Directory
// configuration.
//
// Use the `ApplyProfile.policy` list for
// access to configuration data for the Active Directory profile. Use the
// `ApplyProfile.property` list for access to subprofiles, if any.
type ActiveDirectoryProfile struct {
ApplyProfile
}
func init() {
t["ActiveDirectoryProfile"] = reflect.TypeOf((*ActiveDirectoryProfile)(nil)).Elem()
}
// An attempt to enable Enhanced VMotion Compatibility on a cluster, or to
// select a less-featureful EVC mode for a cluster where EVC is already
// enabled, has failed for the following reason:
// - The cluster contains hosts that expose additional compatibility-
// relevant CPU features beyond those present in the baseline of the
// requested EVC mode.
// - Those hosts have powered-on or suspended virtual machines.
//
// Therefore the EVC configuration has been rejected since it may suppress
// CPU features that are currently in-use.
type ActiveVMsBlockingEVC struct {
EVCConfigFault
// The requested EVC mode.
EvcMode string `xml:"evcMode,omitempty" json:"evcMode,omitempty"`
// Hosts with active virtual machines that are blocking the operation,
// because the hosts expose compatibility-relevant CPU features not present
// in the baseline of the requested EVC mode.
//
// Note that in rare cases, a host may be on this list even if its
// `maxEVCModeKey` corresponds to the
// requested EVC mode. This means that even though that EVC mode is the
// best match for the host's hardware, the host still has some features
// beyond those present in the baseline for that EVC mode.
//
// Refers instances of `HostSystem`.
Host []ManagedObjectReference `xml:"host,omitempty" json:"host,omitempty"`
// The names of the hosts in the host array.
HostName []string `xml:"hostName,omitempty" json:"hostName,omitempty"`
}
func init() {
t["ActiveVMsBlockingEVC"] = reflect.TypeOf((*ActiveVMsBlockingEVC)(nil)).Elem()
}
type ActiveVMsBlockingEVCFault ActiveVMsBlockingEVC
func init() {
t["ActiveVMsBlockingEVCFault"] = reflect.TypeOf((*ActiveVMsBlockingEVCFault)(nil)).Elem()
}
type AddAuthorizationRole AddAuthorizationRoleRequestType
func init() {
t["AddAuthorizationRole"] = reflect.TypeOf((*AddAuthorizationRole)(nil)).Elem()
}
// The parameters of `AuthorizationManager.AddAuthorizationRole`.
type AddAuthorizationRoleRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// Name of the new role.
Name string `xml:"name" json:"name"`
// List of privileges to assign to the role.
PrivIds []string `xml:"privIds,omitempty" json:"privIds,omitempty"`
}
func init() {
t["AddAuthorizationRoleRequestType"] = reflect.TypeOf((*AddAuthorizationRoleRequestType)(nil)).Elem()
}
type AddAuthorizationRoleResponse struct {
Returnval int32 `xml:"returnval" json:"returnval"`
}
type AddCustomFieldDef AddCustomFieldDefRequestType
func init() {
t["AddCustomFieldDef"] = reflect.TypeOf((*AddCustomFieldDef)(nil)).Elem()
}
// The parameters of `CustomFieldsManager.AddCustomFieldDef`.
type AddCustomFieldDefRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The name of the field.
Name string `xml:"name" json:"name"`
// The managed object type to which this field
// will apply
MoType string `xml:"moType,omitempty" json:"moType,omitempty"`
// Privilege policy to apply to FieldDef being
// created
FieldDefPolicy *PrivilegePolicyDef `xml:"fieldDefPolicy,omitempty" json:"fieldDefPolicy,omitempty"`
// Privilege policy to apply to instances of field
FieldPolicy *PrivilegePolicyDef `xml:"fieldPolicy,omitempty" json:"fieldPolicy,omitempty"`
}
func init() {
t["AddCustomFieldDefRequestType"] = reflect.TypeOf((*AddCustomFieldDefRequestType)(nil)).Elem()
}
type AddCustomFieldDefResponse struct {
Returnval CustomFieldDef `xml:"returnval" json:"returnval"`
}
// The parameters of `DistributedVirtualSwitch.AddDVPortgroup_Task`.
type AddDVPortgroupRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The specification for the portgroup.
Spec []DVPortgroupConfigSpec `xml:"spec" json:"spec"`
}
func init() {
t["AddDVPortgroupRequestType"] = reflect.TypeOf((*AddDVPortgroupRequestType)(nil)).Elem()
}
type AddDVPortgroup_Task AddDVPortgroupRequestType
func init() {
t["AddDVPortgroup_Task"] = reflect.TypeOf((*AddDVPortgroup_Task)(nil)).Elem()
}
type AddDVPortgroup_TaskResponse struct {
Returnval ManagedObjectReference `xml:"returnval" json:"returnval"`
}
// The parameters of `HostVsanSystem.AddDisks_Task`.
type AddDisksRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// list of disks to add for use by the VSAN service
Disk []HostScsiDisk `xml:"disk" json:"disk"`
}
func init() {
t["AddDisksRequestType"] = reflect.TypeOf((*AddDisksRequestType)(nil)).Elem()
}
type AddDisks_Task AddDisksRequestType
func init() {
t["AddDisks_Task"] = reflect.TypeOf((*AddDisks_Task)(nil)).Elem()
}
type AddDisks_TaskResponse struct {
Returnval ManagedObjectReference `xml:"returnval" json:"returnval"`
}
type AddFilter AddFilterRequestType
func init() {
t["AddFilter"] = reflect.TypeOf((*AddFilter)(nil)).Elem()
}
type AddFilterEntities AddFilterEntitiesRequestType
func init() {
t["AddFilterEntities"] = reflect.TypeOf((*AddFilterEntities)(nil)).Elem()
}
// The parameters of `HealthUpdateManager.AddFilterEntities`.
type AddFilterEntitiesRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The filter id.
FilterId string `xml:"filterId" json:"filterId"`
// The list of additional managed entities. Only
// entities of type HostSystem or
// ClusterComputeResource are valid.
//
// Refers instances of `ManagedEntity`.
Entities []ManagedObjectReference `xml:"entities,omitempty" json:"entities,omitempty"`
}
func init() {
t["AddFilterEntitiesRequestType"] = reflect.TypeOf((*AddFilterEntitiesRequestType)(nil)).Elem()
}
type AddFilterEntitiesResponse struct {
}
// The parameters of `HealthUpdateManager.AddFilter`.
type AddFilterRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The provider identifier.
ProviderId string `xml:"providerId" json:"providerId"`
// The filter name.
FilterName string `xml:"filterName" json:"filterName"`
// The list of HealthUpdateInfo IDs that should be
// filtered.
InfoIds []string `xml:"infoIds,omitempty" json:"infoIds,omitempty"`
}
func init() {
t["AddFilterRequestType"] = reflect.TypeOf((*AddFilterRequestType)(nil)).Elem()
}
type AddFilterResponse struct {
Returnval string `xml:"returnval" json:"returnval"`
}
type AddGuestAlias AddGuestAliasRequestType
func init() {
t["AddGuestAlias"] = reflect.TypeOf((*AddGuestAlias)(nil)).Elem()
}
// The parameters of `GuestAliasManager.AddGuestAlias`.
type AddGuestAliasRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// Virtual machine to perform the operation on.
//
// Required privileges: VirtualMachine.GuestOperations.ModifyAliases
//
// Refers instance of `VirtualMachine`.
Vm ManagedObjectReference `xml:"vm" json:"vm"`
// The guest authentication data for this operation. See
// `GuestAuthentication`. These credentials must satisfy
// authentication requirements
// for a guest account on the specified virtual machine.
Auth BaseGuestAuthentication `xml:"auth,typeattr" json:"auth"`
// Username for the guest account on the virtual machine.
Username string `xml:"username" json:"username"`
// Indicates whether the certificate associated with the
// alias should be mapped. If an alias certificate is mapped,
// guest operation requests that use that alias do not have
// to specify the guest account username in the
// `SAMLTokenAuthentication` object. If mapCert is
// false, the request must specify the username.
MapCert bool `xml:"mapCert" json:"mapCert"`
// X.509 certificate from the VMware SSO Server,
// in base64 encoded DER format. The ESXi
// Server uses this certificate to authenticate guest
// operation requests.
Base64Cert string `xml:"base64Cert" json:"base64Cert"`
// Specifies the subject name for authentication.
// The subject name (when present) corresponds to
// the value of the Subject element
// in SAML tokens. The ESXi Server uses the subject
// name to authenticate guest operation requests.
AliasInfo GuestAuthAliasInfo `xml:"aliasInfo" json:"aliasInfo"`
}
func init() {
t["AddGuestAliasRequestType"] = reflect.TypeOf((*AddGuestAliasRequestType)(nil)).Elem()
}
type AddGuestAliasResponse struct {
}
// The parameters of `ClusterComputeResource.AddHost_Task`.
type AddHostRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// Specifies the parameters needed to add a single host.
Spec HostConnectSpec `xml:"spec" json:"spec"`
// Flag to specify whether or not the host should be connected
// immediately after it is added. The host will not be added if
// a connection attempt is made and fails.
AsConnected bool `xml:"asConnected" json:"asConnected"`
// the resource pool for the root resource pool from the host.
//
// Required privileges: Resource.AssignVMToPool
//
// Refers instance of `ResourcePool`.
ResourcePool *ManagedObjectReference `xml:"resourcePool,omitempty" json:"resourcePool,omitempty"`
// Provide a licenseKey or licenseKeyType. See `LicenseManager`
License string `xml:"license,omitempty" json:"license,omitempty"`
}
func init() {
t["AddHostRequestType"] = reflect.TypeOf((*AddHostRequestType)(nil)).Elem()
}
type AddHost_Task AddHostRequestType
func init() {
t["AddHost_Task"] = reflect.TypeOf((*AddHost_Task)(nil)).Elem()
}
type AddHost_TaskResponse struct {
Returnval ManagedObjectReference `xml:"returnval" json:"returnval"`
}
type AddInternetScsiSendTargets AddInternetScsiSendTargetsRequestType
func init() {
t["AddInternetScsiSendTargets"] = reflect.TypeOf((*AddInternetScsiSendTargets)(nil)).Elem()
}
// The parameters of `HostStorageSystem.AddInternetScsiSendTargets`.
type AddInternetScsiSendTargetsRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The device of the Internet SCSI HBA adapter.
IScsiHbaDevice string `xml:"iScsiHbaDevice" json:"iScsiHbaDevice"`
// An array of iSCSI send targets.
Targets []HostInternetScsiHbaSendTarget `xml:"targets" json:"targets"`
}
func init() {
t["AddInternetScsiSendTargetsRequestType"] = reflect.TypeOf((*AddInternetScsiSendTargetsRequestType)(nil)).Elem()
}
type AddInternetScsiSendTargetsResponse struct {
}
type AddInternetScsiStaticTargets AddInternetScsiStaticTargetsRequestType
func init() {
t["AddInternetScsiStaticTargets"] = reflect.TypeOf((*AddInternetScsiStaticTargets)(nil)).Elem()
}
// The parameters of `HostStorageSystem.AddInternetScsiStaticTargets`.
type AddInternetScsiStaticTargetsRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The device of the Internet SCSI HBA adapter.
IScsiHbaDevice string `xml:"iScsiHbaDevice" json:"iScsiHbaDevice"`
// An array of iSCSI static targets to add.
Targets []HostInternetScsiHbaStaticTarget `xml:"targets" json:"targets"`
}
func init() {
t["AddInternetScsiStaticTargetsRequestType"] = reflect.TypeOf((*AddInternetScsiStaticTargetsRequestType)(nil)).Elem()
}
type AddInternetScsiStaticTargetsResponse struct {
}
type AddKey AddKeyRequestType
func init() {
t["AddKey"] = reflect.TypeOf((*AddKey)(nil)).Elem()
}
// The parameters of `CryptoManager.AddKey`.
type AddKeyRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// \[in\] The cryptographic key to add.
Key CryptoKeyPlain `xml:"key" json:"key"`
}
func init() {
t["AddKeyRequestType"] = reflect.TypeOf((*AddKeyRequestType)(nil)).Elem()
}
type AddKeyResponse struct {
}
type AddKeys AddKeysRequestType
func init() {
t["AddKeys"] = reflect.TypeOf((*AddKeys)(nil)).Elem()
}
// The parameters of `CryptoManager.AddKeys`.
type AddKeysRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// \[in\] List of cryptographic keys to add.
Keys []CryptoKeyPlain `xml:"keys,omitempty" json:"keys,omitempty"`
}
func init() {
t["AddKeysRequestType"] = reflect.TypeOf((*AddKeysRequestType)(nil)).Elem()
}
type AddKeysResponse struct {
Returnval []CryptoKeyResult `xml:"returnval,omitempty" json:"returnval,omitempty"`
}
type AddLicense AddLicenseRequestType
func init() {
t["AddLicense"] = reflect.TypeOf((*AddLicense)(nil)).Elem()
}
// The parameters of `LicenseManager.AddLicense`.
type AddLicenseRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// A license. E.g. a serial license.
LicenseKey string `xml:"licenseKey" json:"licenseKey"`
// array of key-value labels. Ignored by ESX Server.
Labels []KeyValue `xml:"labels,omitempty" json:"labels,omitempty"`
}
func init() {
t["AddLicenseRequestType"] = reflect.TypeOf((*AddLicenseRequestType)(nil)).Elem()
}
type AddLicenseResponse struct {
Returnval LicenseManagerLicenseInfo `xml:"returnval" json:"returnval"`
}
type AddMonitoredEntities AddMonitoredEntitiesRequestType
func init() {
t["AddMonitoredEntities"] = reflect.TypeOf((*AddMonitoredEntities)(nil)).Elem()
}
// The parameters of `HealthUpdateManager.AddMonitoredEntities`.
type AddMonitoredEntitiesRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// The provider id.
ProviderId string `xml:"providerId" json:"providerId"`
// The entities that are newly monitored by this
// provider.
//
// Refers instances of `ManagedEntity`.
Entities []ManagedObjectReference `xml:"entities,omitempty" json:"entities,omitempty"`
}
func init() {
t["AddMonitoredEntitiesRequestType"] = reflect.TypeOf((*AddMonitoredEntitiesRequestType)(nil)).Elem()
}
type AddMonitoredEntitiesResponse struct {
}
type AddNetworkResourcePool AddNetworkResourcePoolRequestType
func init() {
t["AddNetworkResourcePool"] = reflect.TypeOf((*AddNetworkResourcePool)(nil)).Elem()
}
// The parameters of `DistributedVirtualSwitch.AddNetworkResourcePool`.
type AddNetworkResourcePoolRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// the network resource pool configuration specification.
ConfigSpec []DVSNetworkResourcePoolConfigSpec `xml:"configSpec" json:"configSpec"`
}
func init() {
t["AddNetworkResourcePoolRequestType"] = reflect.TypeOf((*AddNetworkResourcePoolRequestType)(nil)).Elem()
}
type AddNetworkResourcePoolResponse struct {
}
type AddPortGroup AddPortGroupRequestType
func init() {
t["AddPortGroup"] = reflect.TypeOf((*AddPortGroup)(nil)).Elem()
}
// The parameters of `HostNetworkSystem.AddPortGroup`.
type AddPortGroupRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
Portgrp HostPortGroupSpec `xml:"portgrp" json:"portgrp"`
}
func init() {
t["AddPortGroupRequestType"] = reflect.TypeOf((*AddPortGroupRequestType)(nil)).Elem()
}
type AddPortGroupResponse struct {
}
type AddServiceConsoleVirtualNic AddServiceConsoleVirtualNicRequestType
func init() {
t["AddServiceConsoleVirtualNic"] = reflect.TypeOf((*AddServiceConsoleVirtualNic)(nil)).Elem()
}
// The parameters of `HostNetworkSystem.AddServiceConsoleVirtualNic`.
type AddServiceConsoleVirtualNicRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
Portgroup string `xml:"portgroup" json:"portgroup"`
Nic HostVirtualNicSpec `xml:"nic" json:"nic"`
}
func init() {
t["AddServiceConsoleVirtualNicRequestType"] = reflect.TypeOf((*AddServiceConsoleVirtualNicRequestType)(nil)).Elem()
}
type AddServiceConsoleVirtualNicResponse struct {
Returnval string `xml:"returnval" json:"returnval"`
}
// The parameters of `Folder.AddStandaloneHost_Task`.
type AddStandaloneHostRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// Specifies the parameters needed to add a single host.
Spec HostConnectSpec `xml:"spec" json:"spec"`
// Optionally specify the configuration for the compute
// resource that will be created to contain the host.
CompResSpec BaseComputeResourceConfigSpec `xml:"compResSpec,omitempty,typeattr" json:"compResSpec,omitempty"`
// Flag to specify whether or not the host should be
// connected as soon as it is added. The host will not
// be added if a connection attempt is made and fails.
AddConnected bool `xml:"addConnected" json:"addConnected"`
// Provide a licenseKey or licenseKeyType. See `LicenseManager`
License string `xml:"license,omitempty" json:"license,omitempty"`
}
func init() {
t["AddStandaloneHostRequestType"] = reflect.TypeOf((*AddStandaloneHostRequestType)(nil)).Elem()
}
type AddStandaloneHost_Task AddStandaloneHostRequestType
func init() {
t["AddStandaloneHost_Task"] = reflect.TypeOf((*AddStandaloneHost_Task)(nil)).Elem()
}
type AddStandaloneHost_TaskResponse struct {
Returnval ManagedObjectReference `xml:"returnval" json:"returnval"`
}
type AddVirtualNic AddVirtualNicRequestType
func init() {
t["AddVirtualNic"] = reflect.TypeOf((*AddVirtualNic)(nil)).Elem()
}
// The parameters of `HostNetworkSystem.AddVirtualNic`.
type AddVirtualNicRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
// Note: Must be the empty string in case nic.distributedVirtualPort
// is set.
Portgroup string `xml:"portgroup" json:"portgroup"`
Nic HostVirtualNicSpec `xml:"nic" json:"nic"`
}
func init() {
t["AddVirtualNicRequestType"] = reflect.TypeOf((*AddVirtualNicRequestType)(nil)).Elem()
}
type AddVirtualNicResponse struct {
Returnval string `xml:"returnval" json:"returnval"`
}
type AddVirtualSwitch AddVirtualSwitchRequestType
func init() {
t["AddVirtualSwitch"] = reflect.TypeOf((*AddVirtualSwitch)(nil)).Elem()
}
// The parameters of `HostNetworkSystem.AddVirtualSwitch`.
type AddVirtualSwitchRequestType struct {
This ManagedObjectReference `xml:"_this" json:"-"`
VswitchName string `xml:"vswitchName" json:"vswitchName"`
Spec *HostVirtualSwitchSpec `xml:"spec,omitempty" json:"spec,omitempty"`
}
func init() {
t["AddVirtualSwitchRequestType"] = reflect.TypeOf((*AddVirtualSwitchRequestType)(nil)).Elem()
}
type AddVirtualSwitchResponse struct {
}
// Fault thrown if an attempt to disable the Administrator permission
// on a host of which the Administator permission has already been disabled.
type AdminDisabled struct {
HostConfigFault
}
func init() {
t["AdminDisabled"] = reflect.TypeOf((*AdminDisabled)(nil)).Elem()
}
type AdminDisabledFault AdminDisabled
func init() {
t["AdminDisabledFault"] = reflect.TypeOf((*AdminDisabledFault)(nil)).Elem()
}
// Fault thrown if an attempt to enable the Administrator permission
// on a host of which the Administator permission is not disabled.
type AdminNotDisabled struct {
HostConfigFault
}
func init() {
t["AdminNotDisabled"] = reflect.TypeOf((*AdminNotDisabled)(nil)).Elem()
}
type AdminNotDisabledFault AdminNotDisabled
func init() {
t["AdminNotDisabledFault"] = reflect.TypeOf((*AdminNotDisabledFault)(nil)).Elem()
}
// Default password for the Admin user on the host has not been changed.
type AdminPasswordNotChangedEvent struct {
HostEvent
}
func init() {
t["AdminPasswordNotChangedEvent"] = reflect.TypeOf((*AdminPasswordNotChangedEvent)(nil)).Elem()
}
// Virtual machine has a configured memory and/or CPU affinity that will
// prevent VMotion.
//
// This is an error for powered-on virtual machines.
type AffinityConfigured struct {
MigrationFault
// Configured affinity types for the virtual machine.
//
// See `AffinityType_enum` for valid values.
ConfiguredAffinity []string `xml:"configuredAffinity" json:"configuredAffinity"`
}
func init() {
t["AffinityConfigured"] = reflect.TypeOf((*AffinityConfigured)(nil)).Elem()
}
type AffinityConfiguredFault AffinityConfigured
func init() {
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/esxi_version.go | vendor/github.com/vmware/govmomi/vim25/types/esxi_version.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"fmt"
"regexp"
"strconv"
)
// ESXiVersion is an ESXi version.
type ESXiVersion uint8
const (
esxiVersionBegin ESXiVersion = iota
ESXi2000
ESXi3000
ESXi4000
ESXi5000
ESXi5100
ESXi5500
ESXi6000
ESXi6500
ESXi6700
ESXi6720
ESXi7000
ESXi7010
ESXi7020
ESXi8000
ESXi8010
ESXi8020
esxiVersionEnd
)
// HardwareVersion returns the maximum hardware version supported by this
// version of ESXi, per https://knowledge.broadcom.com/external/article?articleNumber=315655.
func (ev ESXiVersion) HardwareVersion() HardwareVersion {
switch ev {
case ESXi2000:
return VMX3
case ESXi3000:
return VMX4
case ESXi4000:
return VMX7
case ESXi5000:
return VMX8
case ESXi5100:
return VMX9
case ESXi5500:
return VMX10
case ESXi6000:
return VMX11
case ESXi6500:
return VMX13
case ESXi6700:
return VMX14
case ESXi6720:
return VMX15
case ESXi7000:
return VMX17
case ESXi7010:
return VMX18
case ESXi7020:
return VMX19
case ESXi8000, ESXi8010:
return VMX20
case ESXi8020:
return VMX21
}
return 0
}
// IsHardwareVersionSupported returns true if the provided hardware version is
// supported by the given version of ESXi.
func (ev ESXiVersion) IsHardwareVersionSupported(hv HardwareVersion) bool {
return hv <= ev.HardwareVersion()
}
func (ev ESXiVersion) IsValid() bool {
return ev.String() != ""
}
func (ev ESXiVersion) String() string {
switch ev {
case ESXi2000:
return "2"
case ESXi3000:
return "3"
case ESXi4000:
return "4"
case ESXi5000:
return "5.0"
case ESXi5100:
return "5.1"
case ESXi5500:
return "5.5"
case ESXi6000:
return "6.0"
case ESXi6500:
return "6.5"
case ESXi6700:
return "6.7"
case ESXi6720:
return "6.7.2"
case ESXi7000:
return "7.0"
case ESXi7010:
return "7.0.1"
case ESXi7020:
return "7.0.2"
case ESXi8000:
return "8.0"
case ESXi8010:
return "8.0.1"
case ESXi8020:
return "8.0.2"
}
return ""
}
func (ev ESXiVersion) MarshalText() ([]byte, error) {
return []byte(ev.String()), nil
}
func (ev *ESXiVersion) UnmarshalText(text []byte) error {
v, err := ParseESXiVersion(string(text))
if err != nil {
return err
}
*ev = v
return nil
}
// MustParseESXiVersion parses the provided string into an ESXi version.
func MustParseESXiVersion(s string) ESXiVersion {
v, err := ParseESXiVersion(s)
if err != nil {
panic(err)
}
return v
}
var esxiRe = regexp.MustCompile(`(?i)^v?(\d)(?:\.(\d))?(?:\.(\d))?(?:\s*u(\d))?$`)
// ParseESXiVersion parses the provided string into an ESXi version.
func ParseESXiVersion(s string) (ESXiVersion, error) {
if m := esxiRe.FindStringSubmatch(s); len(m) > 0 {
var (
major int64
minor int64
patch int64
update int64
)
major, _ = strconv.ParseInt(m[1], 0, 0)
if len(m) > 2 {
minor, _ = strconv.ParseInt(m[2], 0, 0)
}
if len(m) > 3 {
patch, _ = strconv.ParseInt(m[3], 0, 0)
}
if len(m) > 4 {
update, _ = strconv.ParseInt(m[4], 0, 0)
}
switch {
case major == 2 && minor == 0 && patch == 0 && update == 0:
return ESXi2000, nil
case major == 3 && minor == 0 && patch == 0 && update == 0:
return ESXi3000, nil
case major == 4 && minor == 0 && patch == 0 && update == 0:
return ESXi4000, nil
case major == 5 && minor == 0 && patch == 0 && update == 0:
return ESXi5000, nil
case major == 5 && minor == 1 && patch == 0 && update == 0:
return ESXi5100, nil
case major == 5 && minor == 5 && patch == 0 && update == 0:
return ESXi5500, nil
case major == 6 && minor == 0 && patch == 0 && update == 0:
return ESXi6000, nil
case major == 6 && minor == 5 && patch == 0 && update == 0:
return ESXi6500, nil
case major == 6 && minor == 7 && patch == 0 && update == 0:
return ESXi6700, nil
case major == 6 && minor == 7 && patch == 2 && update == 0,
major == 6 && minor == 7 && patch == 0 && update == 2:
return ESXi6720, nil
case major == 7 && minor == 0 && patch == 0 && update == 0:
return ESXi7000, nil
case major == 7 && minor == 0 && patch == 1 && update == 0,
major == 7 && minor == 0 && patch == 0 && update == 1:
return ESXi7010, nil
case major == 7 && minor == 0 && patch == 2 && update == 0,
major == 7 && minor == 0 && patch == 0 && update == 2:
return ESXi7020, nil
case major == 8 && minor == 0 && patch == 0 && update == 0:
return ESXi8000, nil
case major == 8 && minor == 0 && patch == 1 && update == 0,
major == 8 && minor == 0 && patch == 0 && update == 1:
return ESXi8010, nil
case major == 8 && minor == 0 && patch == 2 && update == 0,
major == 8 && minor == 0 && patch == 0 && update == 2:
return ESXi8020, nil
}
}
return 0, fmt.Errorf("invalid version: %q", s)
}
// GetESXiVersions returns a list of ESXi versions.
func GetESXiVersions() []ESXiVersion {
dst := make([]ESXiVersion, esxiVersionEnd-1)
for i := esxiVersionBegin + 1; i < esxiVersionEnd; i++ {
dst[i-1] = i
}
return dst
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/unreleased.go | vendor/github.com/vmware/govmomi/vim25/types/unreleased.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import "reflect"
type ArrayOfPlaceVmsXClusterResultPlacementFaults struct {
PlaceVmsXClusterResultPlacementFaults []PlaceVmsXClusterResultPlacementFaults `xml:"PlaceVmsXClusterResultPlacementFaults,omitempty"`
}
func init() {
t["ArrayOfPlaceVmsXClusterResultPlacementFaults"] = reflect.TypeOf((*ArrayOfPlaceVmsXClusterResultPlacementFaults)(nil)).Elem()
}
type ArrayOfPlaceVmsXClusterResultPlacementInfo struct {
PlaceVmsXClusterResultPlacementInfo []PlaceVmsXClusterResultPlacementInfo `xml:"PlaceVmsXClusterResultPlacementInfo,omitempty"`
}
func init() {
t["ArrayOfPlaceVmsXClusterResultPlacementInfo"] = reflect.TypeOf((*ArrayOfPlaceVmsXClusterResultPlacementInfo)(nil)).Elem()
}
type ArrayOfPlaceVmsXClusterSpecVmPlacementSpec struct {
PlaceVmsXClusterSpecVmPlacementSpec []PlaceVmsXClusterSpecVmPlacementSpec `xml:"PlaceVmsXClusterSpecVmPlacementSpec,omitempty"`
}
func init() {
t["ArrayOfPlaceVmsXClusterSpecVmPlacementSpec"] = reflect.TypeOf((*ArrayOfPlaceVmsXClusterSpecVmPlacementSpec)(nil)).Elem()
}
type PlaceVmsXCluster PlaceVmsXClusterRequestType
func init() {
t["PlaceVmsXCluster"] = reflect.TypeOf((*PlaceVmsXCluster)(nil)).Elem()
}
type PlaceVmsXClusterRequestType struct {
This ManagedObjectReference `xml:"_this"`
PlacementSpec PlaceVmsXClusterSpec `xml:"placementSpec"`
}
func init() {
t["PlaceVmsXClusterRequestType"] = reflect.TypeOf((*PlaceVmsXClusterRequestType)(nil)).Elem()
}
type PlaceVmsXClusterResponse struct {
Returnval PlaceVmsXClusterResult `xml:"returnval"`
}
type PlaceVmsXClusterResult struct {
DynamicData
PlacementInfos []PlaceVmsXClusterResultPlacementInfo `xml:"placementInfos,omitempty"`
Faults []PlaceVmsXClusterResultPlacementFaults `xml:"faults,omitempty"`
}
func init() {
t["PlaceVmsXClusterResult"] = reflect.TypeOf((*PlaceVmsXClusterResult)(nil)).Elem()
}
type PlaceVmsXClusterResultPlacementFaults struct {
DynamicData
ResourcePool ManagedObjectReference `xml:"resourcePool"`
VmName string `xml:"vmName"`
Faults []LocalizedMethodFault `xml:"faults,omitempty"`
Vm *ManagedObjectReference `xml:"vm,omitempty"`
}
func init() {
t["PlaceVmsXClusterResultPlacementFaults"] = reflect.TypeOf((*PlaceVmsXClusterResultPlacementFaults)(nil)).Elem()
}
type PlaceVmsXClusterResultPlacementInfo struct {
DynamicData
VmName string `xml:"vmName"`
Recommendation ClusterRecommendation `xml:"recommendation"`
Vm *ManagedObjectReference `xml:"vm,omitempty"`
}
func init() {
t["PlaceVmsXClusterResultPlacementInfo"] = reflect.TypeOf((*PlaceVmsXClusterResultPlacementInfo)(nil)).Elem()
}
type PlaceVmsXClusterSpec struct {
DynamicData
ResourcePools []ManagedObjectReference `xml:"resourcePools,omitempty"`
PlacementType string `xml:"placementType,omitempty"`
VmPlacementSpecs []PlaceVmsXClusterSpecVmPlacementSpec `xml:"vmPlacementSpecs,omitempty"`
HostRecommRequired *bool `xml:"hostRecommRequired"`
DatastoreRecommRequired *bool `xml:"datastoreRecommRequired"`
}
func init() {
t["PlaceVmsXClusterSpec"] = reflect.TypeOf((*PlaceVmsXClusterSpec)(nil)).Elem()
}
type PlaceVmsXClusterSpecVmPlacementSpec struct {
DynamicData
Vm *ManagedObjectReference `xml:"vm,omitempty"`
ConfigSpec VirtualMachineConfigSpec `xml:"configSpec"`
RelocateSpec *VirtualMachineRelocateSpec `xml:"relocateSpec,omitempty"`
}
func init() {
t["PlaceVmsXClusterSpecVmPlacementSpec"] = reflect.TypeOf((*PlaceVmsXClusterSpecVmPlacementSpec)(nil)).Elem()
}
const RecommendationReasonCodeXClusterPlacement = RecommendationReasonCode("xClusterPlacement")
type ClusterClusterReconfigurePlacementAction struct {
ClusterAction
TargetHost *ManagedObjectReference `xml:"targetHost,omitempty"`
Pool ManagedObjectReference `xml:"pool"`
ConfigSpec *VirtualMachineConfigSpec `xml:"configSpec,omitempty"`
}
func init() {
t["ClusterClusterReconfigurePlacementAction"] = reflect.TypeOf((*ClusterClusterReconfigurePlacementAction)(nil)).Elem()
}
type ClusterClusterRelocatePlacementAction struct {
ClusterAction
TargetHost *ManagedObjectReference `xml:"targetHost,omitempty"`
Pool ManagedObjectReference `xml:"pool"`
RelocateSpec *VirtualMachineRelocateSpec `xml:"relocateSpec,omitempty"`
}
func init() {
t["ClusterClusterRelocatePlacementAction"] = reflect.TypeOf((*ClusterClusterRelocatePlacementAction)(nil)).Elem()
}
func init() {
Add("PodVMOverheadInfo", reflect.TypeOf((*PodVMOverheadInfo)(nil)).Elem())
}
type PodVMOverheadInfo struct {
CrxPageSharingSupported bool `xml:"crxPageSharingSupported"`
PodVMOverheadWithoutPageSharing int32 `xml:"podVMOverheadWithoutPageSharing"`
PodVMOverheadWithPageSharing int32 `xml:"podVMOverheadWithPageSharing"`
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/if.go | vendor/github.com/vmware/govmomi/vim25/types/if.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import "reflect"
func (b *Action) GetAction() *Action { return b }
type BaseAction interface {
GetAction() *Action
}
func init() {
t["BaseAction"] = reflect.TypeOf((*Action)(nil)).Elem()
}
func (b *ActiveDirectoryFault) GetActiveDirectoryFault() *ActiveDirectoryFault { return b }
type BaseActiveDirectoryFault interface {
GetActiveDirectoryFault() *ActiveDirectoryFault
}
func init() {
t["BaseActiveDirectoryFault"] = reflect.TypeOf((*ActiveDirectoryFault)(nil)).Elem()
}
func (b *AlarmAction) GetAlarmAction() *AlarmAction { return b }
type BaseAlarmAction interface {
GetAlarmAction() *AlarmAction
}
func init() {
t["BaseAlarmAction"] = reflect.TypeOf((*AlarmAction)(nil)).Elem()
}
func (b *AlarmEvent) GetAlarmEvent() *AlarmEvent { return b }
type BaseAlarmEvent interface {
GetAlarmEvent() *AlarmEvent
}
func init() {
t["BaseAlarmEvent"] = reflect.TypeOf((*AlarmEvent)(nil)).Elem()
}
func (b *AlarmExpression) GetAlarmExpression() *AlarmExpression { return b }
type BaseAlarmExpression interface {
GetAlarmExpression() *AlarmExpression
}
func init() {
t["BaseAlarmExpression"] = reflect.TypeOf((*AlarmExpression)(nil)).Elem()
}
func (b *AlarmSpec) GetAlarmSpec() *AlarmSpec { return b }
type BaseAlarmSpec interface {
GetAlarmSpec() *AlarmSpec
}
func init() {
t["BaseAlarmSpec"] = reflect.TypeOf((*AlarmSpec)(nil)).Elem()
}
func (b *AnswerFileCreateSpec) GetAnswerFileCreateSpec() *AnswerFileCreateSpec { return b }
type BaseAnswerFileCreateSpec interface {
GetAnswerFileCreateSpec() *AnswerFileCreateSpec
}
func init() {
t["BaseAnswerFileCreateSpec"] = reflect.TypeOf((*AnswerFileCreateSpec)(nil)).Elem()
}
func (b *ApplyProfile) GetApplyProfile() *ApplyProfile { return b }
type BaseApplyProfile interface {
GetApplyProfile() *ApplyProfile
}
func init() {
t["BaseApplyProfile"] = reflect.TypeOf((*ApplyProfile)(nil)).Elem()
}
func (b *ArrayUpdateSpec) GetArrayUpdateSpec() *ArrayUpdateSpec { return b }
type BaseArrayUpdateSpec interface {
GetArrayUpdateSpec() *ArrayUpdateSpec
}
func init() {
t["BaseArrayUpdateSpec"] = reflect.TypeOf((*ArrayUpdateSpec)(nil)).Elem()
}
func (b *AuthorizationEvent) GetAuthorizationEvent() *AuthorizationEvent { return b }
type BaseAuthorizationEvent interface {
GetAuthorizationEvent() *AuthorizationEvent
}
func init() {
t["BaseAuthorizationEvent"] = reflect.TypeOf((*AuthorizationEvent)(nil)).Elem()
}
func (b *BaseConfigInfo) GetBaseConfigInfo() *BaseConfigInfo { return b }
type BaseBaseConfigInfo interface {
GetBaseConfigInfo() *BaseConfigInfo
}
func init() {
t["BaseBaseConfigInfo"] = reflect.TypeOf((*BaseConfigInfo)(nil)).Elem()
}
func (b *BaseConfigInfoBackingInfo) GetBaseConfigInfoBackingInfo() *BaseConfigInfoBackingInfo {
return b
}
type BaseBaseConfigInfoBackingInfo interface {
GetBaseConfigInfoBackingInfo() *BaseConfigInfoBackingInfo
}
func init() {
t["BaseBaseConfigInfoBackingInfo"] = reflect.TypeOf((*BaseConfigInfoBackingInfo)(nil)).Elem()
}
func (b *BaseConfigInfoFileBackingInfo) GetBaseConfigInfoFileBackingInfo() *BaseConfigInfoFileBackingInfo {
return b
}
type BaseBaseConfigInfoFileBackingInfo interface {
GetBaseConfigInfoFileBackingInfo() *BaseConfigInfoFileBackingInfo
}
func init() {
t["BaseBaseConfigInfoFileBackingInfo"] = reflect.TypeOf((*BaseConfigInfoFileBackingInfo)(nil)).Elem()
}
func (b *CannotAccessNetwork) GetCannotAccessNetwork() *CannotAccessNetwork { return b }
type BaseCannotAccessNetwork interface {
GetCannotAccessNetwork() *CannotAccessNetwork
}
func init() {
t["BaseCannotAccessNetwork"] = reflect.TypeOf((*CannotAccessNetwork)(nil)).Elem()
}
func (b *CannotAccessVmComponent) GetCannotAccessVmComponent() *CannotAccessVmComponent { return b }
type BaseCannotAccessVmComponent interface {
GetCannotAccessVmComponent() *CannotAccessVmComponent
}
func init() {
t["BaseCannotAccessVmComponent"] = reflect.TypeOf((*CannotAccessVmComponent)(nil)).Elem()
}
func (b *CannotAccessVmDevice) GetCannotAccessVmDevice() *CannotAccessVmDevice { return b }
type BaseCannotAccessVmDevice interface {
GetCannotAccessVmDevice() *CannotAccessVmDevice
}
func init() {
t["BaseCannotAccessVmDevice"] = reflect.TypeOf((*CannotAccessVmDevice)(nil)).Elem()
}
func (b *CannotAccessVmDisk) GetCannotAccessVmDisk() *CannotAccessVmDisk { return b }
type BaseCannotAccessVmDisk interface {
GetCannotAccessVmDisk() *CannotAccessVmDisk
}
func init() {
t["BaseCannotAccessVmDisk"] = reflect.TypeOf((*CannotAccessVmDisk)(nil)).Elem()
}
func (b *CannotMoveVsanEnabledHost) GetCannotMoveVsanEnabledHost() *CannotMoveVsanEnabledHost {
return b
}
type BaseCannotMoveVsanEnabledHost interface {
GetCannotMoveVsanEnabledHost() *CannotMoveVsanEnabledHost
}
func init() {
t["BaseCannotMoveVsanEnabledHost"] = reflect.TypeOf((*CannotMoveVsanEnabledHost)(nil)).Elem()
}
func (b *ClusterAction) GetClusterAction() *ClusterAction { return b }
type BaseClusterAction interface {
GetClusterAction() *ClusterAction
}
func init() {
t["BaseClusterAction"] = reflect.TypeOf((*ClusterAction)(nil)).Elem()
}
func (b *ClusterComputeResourceValidationResultBase) GetClusterComputeResourceValidationResultBase() *ClusterComputeResourceValidationResultBase {
return b
}
type BaseClusterComputeResourceValidationResultBase interface {
GetClusterComputeResourceValidationResultBase() *ClusterComputeResourceValidationResultBase
}
func init() {
t["BaseClusterComputeResourceValidationResultBase"] = reflect.TypeOf((*ClusterComputeResourceValidationResultBase)(nil)).Elem()
}
func (b *ClusterDasAdmissionControlInfo) GetClusterDasAdmissionControlInfo() *ClusterDasAdmissionControlInfo {
return b
}
type BaseClusterDasAdmissionControlInfo interface {
GetClusterDasAdmissionControlInfo() *ClusterDasAdmissionControlInfo
}
func init() {
t["BaseClusterDasAdmissionControlInfo"] = reflect.TypeOf((*ClusterDasAdmissionControlInfo)(nil)).Elem()
}
func (b *ClusterDasAdmissionControlPolicy) GetClusterDasAdmissionControlPolicy() *ClusterDasAdmissionControlPolicy {
return b
}
type BaseClusterDasAdmissionControlPolicy interface {
GetClusterDasAdmissionControlPolicy() *ClusterDasAdmissionControlPolicy
}
func init() {
t["BaseClusterDasAdmissionControlPolicy"] = reflect.TypeOf((*ClusterDasAdmissionControlPolicy)(nil)).Elem()
}
func (b *ClusterDasAdvancedRuntimeInfo) GetClusterDasAdvancedRuntimeInfo() *ClusterDasAdvancedRuntimeInfo {
return b
}
type BaseClusterDasAdvancedRuntimeInfo interface {
GetClusterDasAdvancedRuntimeInfo() *ClusterDasAdvancedRuntimeInfo
}
func init() {
t["BaseClusterDasAdvancedRuntimeInfo"] = reflect.TypeOf((*ClusterDasAdvancedRuntimeInfo)(nil)).Elem()
}
func (b *ClusterDasData) GetClusterDasData() *ClusterDasData { return b }
type BaseClusterDasData interface {
GetClusterDasData() *ClusterDasData
}
func init() {
t["BaseClusterDasData"] = reflect.TypeOf((*ClusterDasData)(nil)).Elem()
}
func (b *ClusterDasHostInfo) GetClusterDasHostInfo() *ClusterDasHostInfo { return b }
type BaseClusterDasHostInfo interface {
GetClusterDasHostInfo() *ClusterDasHostInfo
}
func init() {
t["BaseClusterDasHostInfo"] = reflect.TypeOf((*ClusterDasHostInfo)(nil)).Elem()
}
func (b *ClusterDrsFaultsFaultsByVm) GetClusterDrsFaultsFaultsByVm() *ClusterDrsFaultsFaultsByVm {
return b
}
type BaseClusterDrsFaultsFaultsByVm interface {
GetClusterDrsFaultsFaultsByVm() *ClusterDrsFaultsFaultsByVm
}
func init() {
t["BaseClusterDrsFaultsFaultsByVm"] = reflect.TypeOf((*ClusterDrsFaultsFaultsByVm)(nil)).Elem()
}
func (b *ClusterEvent) GetClusterEvent() *ClusterEvent { return b }
type BaseClusterEvent interface {
GetClusterEvent() *ClusterEvent
}
func init() {
t["BaseClusterEvent"] = reflect.TypeOf((*ClusterEvent)(nil)).Elem()
}
func (b *ClusterGroupInfo) GetClusterGroupInfo() *ClusterGroupInfo { return b }
type BaseClusterGroupInfo interface {
GetClusterGroupInfo() *ClusterGroupInfo
}
func init() {
t["BaseClusterGroupInfo"] = reflect.TypeOf((*ClusterGroupInfo)(nil)).Elem()
}
func (b *ClusterOvercommittedEvent) GetClusterOvercommittedEvent() *ClusterOvercommittedEvent {
return b
}
type BaseClusterOvercommittedEvent interface {
GetClusterOvercommittedEvent() *ClusterOvercommittedEvent
}
func init() {
t["BaseClusterOvercommittedEvent"] = reflect.TypeOf((*ClusterOvercommittedEvent)(nil)).Elem()
}
func (b *ClusterProfileConfigSpec) GetClusterProfileConfigSpec() *ClusterProfileConfigSpec { return b }
type BaseClusterProfileConfigSpec interface {
GetClusterProfileConfigSpec() *ClusterProfileConfigSpec
}
func init() {
t["BaseClusterProfileConfigSpec"] = reflect.TypeOf((*ClusterProfileConfigSpec)(nil)).Elem()
}
func (b *ClusterProfileCreateSpec) GetClusterProfileCreateSpec() *ClusterProfileCreateSpec { return b }
type BaseClusterProfileCreateSpec interface {
GetClusterProfileCreateSpec() *ClusterProfileCreateSpec
}
func init() {
t["BaseClusterProfileCreateSpec"] = reflect.TypeOf((*ClusterProfileCreateSpec)(nil)).Elem()
}
func (b *ClusterRuleInfo) GetClusterRuleInfo() *ClusterRuleInfo { return b }
type BaseClusterRuleInfo interface {
GetClusterRuleInfo() *ClusterRuleInfo
}
func init() {
t["BaseClusterRuleInfo"] = reflect.TypeOf((*ClusterRuleInfo)(nil)).Elem()
}
func (b *ClusterSlotPolicy) GetClusterSlotPolicy() *ClusterSlotPolicy { return b }
type BaseClusterSlotPolicy interface {
GetClusterSlotPolicy() *ClusterSlotPolicy
}
func init() {
t["BaseClusterSlotPolicy"] = reflect.TypeOf((*ClusterSlotPolicy)(nil)).Elem()
}
func (b *ClusterStatusChangedEvent) GetClusterStatusChangedEvent() *ClusterStatusChangedEvent {
return b
}
type BaseClusterStatusChangedEvent interface {
GetClusterStatusChangedEvent() *ClusterStatusChangedEvent
}
func init() {
t["BaseClusterStatusChangedEvent"] = reflect.TypeOf((*ClusterStatusChangedEvent)(nil)).Elem()
}
func (b *ComputeResourceConfigInfo) GetComputeResourceConfigInfo() *ComputeResourceConfigInfo {
return b
}
type BaseComputeResourceConfigInfo interface {
GetComputeResourceConfigInfo() *ComputeResourceConfigInfo
}
func init() {
t["BaseComputeResourceConfigInfo"] = reflect.TypeOf((*ComputeResourceConfigInfo)(nil)).Elem()
}
func (b *ComputeResourceConfigSpec) GetComputeResourceConfigSpec() *ComputeResourceConfigSpec {
return b
}
type BaseComputeResourceConfigSpec interface {
GetComputeResourceConfigSpec() *ComputeResourceConfigSpec
}
func init() {
t["BaseComputeResourceConfigSpec"] = reflect.TypeOf((*ComputeResourceConfigSpec)(nil)).Elem()
}
func (b *ComputeResourceSummary) GetComputeResourceSummary() *ComputeResourceSummary { return b }
type BaseComputeResourceSummary interface {
GetComputeResourceSummary() *ComputeResourceSummary
}
func init() {
t["BaseComputeResourceSummary"] = reflect.TypeOf((*ComputeResourceSummary)(nil)).Elem()
}
func (b *CpuIncompatible) GetCpuIncompatible() *CpuIncompatible { return b }
type BaseCpuIncompatible interface {
GetCpuIncompatible() *CpuIncompatible
}
func init() {
t["BaseCpuIncompatible"] = reflect.TypeOf((*CpuIncompatible)(nil)).Elem()
}
func (b *CryptoManagerKmipCryptoKeyStatusKeyInfo) GetCryptoManagerKmipCryptoKeyStatusKeyInfo() *CryptoManagerKmipCryptoKeyStatusKeyInfo {
return b
}
type BaseCryptoManagerKmipCryptoKeyStatusKeyInfo interface {
GetCryptoManagerKmipCryptoKeyStatusKeyInfo() *CryptoManagerKmipCryptoKeyStatusKeyInfo
}
func init() {
t["BaseCryptoManagerKmipCryptoKeyStatusKeyInfo"] = reflect.TypeOf((*CryptoManagerKmipCryptoKeyStatusKeyInfo)(nil)).Elem()
}
func (b *CryptoSpec) GetCryptoSpec() *CryptoSpec { return b }
type BaseCryptoSpec interface {
GetCryptoSpec() *CryptoSpec
}
func init() {
t["BaseCryptoSpec"] = reflect.TypeOf((*CryptoSpec)(nil)).Elem()
}
func (b *CryptoSpecNoOp) GetCryptoSpecNoOp() *CryptoSpecNoOp { return b }
type BaseCryptoSpecNoOp interface {
GetCryptoSpecNoOp() *CryptoSpecNoOp
}
func init() {
t["BaseCryptoSpecNoOp"] = reflect.TypeOf((*CryptoSpecNoOp)(nil)).Elem()
}
func (b *CustomFieldDefEvent) GetCustomFieldDefEvent() *CustomFieldDefEvent { return b }
type BaseCustomFieldDefEvent interface {
GetCustomFieldDefEvent() *CustomFieldDefEvent
}
func init() {
t["BaseCustomFieldDefEvent"] = reflect.TypeOf((*CustomFieldDefEvent)(nil)).Elem()
}
func (b *CustomFieldEvent) GetCustomFieldEvent() *CustomFieldEvent { return b }
type BaseCustomFieldEvent interface {
GetCustomFieldEvent() *CustomFieldEvent
}
func init() {
t["BaseCustomFieldEvent"] = reflect.TypeOf((*CustomFieldEvent)(nil)).Elem()
}
func (b *CustomFieldValue) GetCustomFieldValue() *CustomFieldValue { return b }
type BaseCustomFieldValue interface {
GetCustomFieldValue() *CustomFieldValue
}
func init() {
t["BaseCustomFieldValue"] = reflect.TypeOf((*CustomFieldValue)(nil)).Elem()
}
func (b *CustomizationEvent) GetCustomizationEvent() *CustomizationEvent { return b }
type BaseCustomizationEvent interface {
GetCustomizationEvent() *CustomizationEvent
}
func init() {
t["BaseCustomizationEvent"] = reflect.TypeOf((*CustomizationEvent)(nil)).Elem()
}
func (b *CustomizationFailed) GetCustomizationFailed() *CustomizationFailed { return b }
type BaseCustomizationFailed interface {
GetCustomizationFailed() *CustomizationFailed
}
func init() {
t["BaseCustomizationFailed"] = reflect.TypeOf((*CustomizationFailed)(nil)).Elem()
}
func (b *CustomizationFault) GetCustomizationFault() *CustomizationFault { return b }
type BaseCustomizationFault interface {
GetCustomizationFault() *CustomizationFault
}
func init() {
t["BaseCustomizationFault"] = reflect.TypeOf((*CustomizationFault)(nil)).Elem()
}
func (b *CustomizationIdentitySettings) GetCustomizationIdentitySettings() *CustomizationIdentitySettings {
return b
}
type BaseCustomizationIdentitySettings interface {
GetCustomizationIdentitySettings() *CustomizationIdentitySettings
}
func init() {
t["BaseCustomizationIdentitySettings"] = reflect.TypeOf((*CustomizationIdentitySettings)(nil)).Elem()
}
func (b *CustomizationIpGenerator) GetCustomizationIpGenerator() *CustomizationIpGenerator { return b }
type BaseCustomizationIpGenerator interface {
GetCustomizationIpGenerator() *CustomizationIpGenerator
}
func init() {
t["BaseCustomizationIpGenerator"] = reflect.TypeOf((*CustomizationIpGenerator)(nil)).Elem()
}
func (b *CustomizationIpV6Generator) GetCustomizationIpV6Generator() *CustomizationIpV6Generator {
return b
}
type BaseCustomizationIpV6Generator interface {
GetCustomizationIpV6Generator() *CustomizationIpV6Generator
}
func init() {
t["BaseCustomizationIpV6Generator"] = reflect.TypeOf((*CustomizationIpV6Generator)(nil)).Elem()
}
func (b *CustomizationName) GetCustomizationName() *CustomizationName { return b }
type BaseCustomizationName interface {
GetCustomizationName() *CustomizationName
}
func init() {
t["BaseCustomizationName"] = reflect.TypeOf((*CustomizationName)(nil)).Elem()
}
func (b *CustomizationOptions) GetCustomizationOptions() *CustomizationOptions { return b }
type BaseCustomizationOptions interface {
GetCustomizationOptions() *CustomizationOptions
}
func init() {
t["BaseCustomizationOptions"] = reflect.TypeOf((*CustomizationOptions)(nil)).Elem()
}
func (b *DVPortSetting) GetDVPortSetting() *DVPortSetting { return b }
type BaseDVPortSetting interface {
GetDVPortSetting() *DVPortSetting
}
func init() {
t["BaseDVPortSetting"] = reflect.TypeOf((*DVPortSetting)(nil)).Elem()
}
func (b *DVPortgroupEvent) GetDVPortgroupEvent() *DVPortgroupEvent { return b }
type BaseDVPortgroupEvent interface {
GetDVPortgroupEvent() *DVPortgroupEvent
}
func init() {
t["BaseDVPortgroupEvent"] = reflect.TypeOf((*DVPortgroupEvent)(nil)).Elem()
}
func (b *DVPortgroupPolicy) GetDVPortgroupPolicy() *DVPortgroupPolicy { return b }
type BaseDVPortgroupPolicy interface {
GetDVPortgroupPolicy() *DVPortgroupPolicy
}
func init() {
t["BaseDVPortgroupPolicy"] = reflect.TypeOf((*DVPortgroupPolicy)(nil)).Elem()
}
func (b *DVSConfigInfo) GetDVSConfigInfo() *DVSConfigInfo { return b }
type BaseDVSConfigInfo interface {
GetDVSConfigInfo() *DVSConfigInfo
}
func init() {
t["BaseDVSConfigInfo"] = reflect.TypeOf((*DVSConfigInfo)(nil)).Elem()
}
func (b *DVSConfigSpec) GetDVSConfigSpec() *DVSConfigSpec { return b }
type BaseDVSConfigSpec interface {
GetDVSConfigSpec() *DVSConfigSpec
}
func init() {
t["BaseDVSConfigSpec"] = reflect.TypeOf((*DVSConfigSpec)(nil)).Elem()
}
func (b *DVSFeatureCapability) GetDVSFeatureCapability() *DVSFeatureCapability { return b }
type BaseDVSFeatureCapability interface {
GetDVSFeatureCapability() *DVSFeatureCapability
}
func init() {
t["BaseDVSFeatureCapability"] = reflect.TypeOf((*DVSFeatureCapability)(nil)).Elem()
}
func (b *DVSFilterSpecConnecteeSpec) GetDVSFilterSpecConnecteeSpec() *DVSFilterSpecConnecteeSpec {
return b
}
type BaseDVSFilterSpecConnecteeSpec interface {
GetDVSFilterSpecConnecteeSpec() *DVSFilterSpecConnecteeSpec
}
func init() {
t["BaseDVSFilterSpecConnecteeSpec"] = reflect.TypeOf((*DVSFilterSpecConnecteeSpec)(nil)).Elem()
}
func (b *DVSFilterSpecVlanSpec) GetDVSFilterSpecVlanSpec() *DVSFilterSpecVlanSpec { return b }
type BaseDVSFilterSpecVlanSpec interface {
GetDVSFilterSpecVlanSpec() *DVSFilterSpecVlanSpec
}
func init() {
t["BaseDVSFilterSpecVlanSpec"] = reflect.TypeOf((*DVSFilterSpecVlanSpec)(nil)).Elem()
}
func (b *DVSHealthCheckCapability) GetDVSHealthCheckCapability() *DVSHealthCheckCapability { return b }
type BaseDVSHealthCheckCapability interface {
GetDVSHealthCheckCapability() *DVSHealthCheckCapability
}
func init() {
t["BaseDVSHealthCheckCapability"] = reflect.TypeOf((*DVSHealthCheckCapability)(nil)).Elem()
}
func (b *DVSHealthCheckConfig) GetDVSHealthCheckConfig() *DVSHealthCheckConfig { return b }
type BaseDVSHealthCheckConfig interface {
GetDVSHealthCheckConfig() *DVSHealthCheckConfig
}
func init() {
t["BaseDVSHealthCheckConfig"] = reflect.TypeOf((*DVSHealthCheckConfig)(nil)).Elem()
}
func (b *DVSUplinkPortPolicy) GetDVSUplinkPortPolicy() *DVSUplinkPortPolicy { return b }
type BaseDVSUplinkPortPolicy interface {
GetDVSUplinkPortPolicy() *DVSUplinkPortPolicy
}
func init() {
t["BaseDVSUplinkPortPolicy"] = reflect.TypeOf((*DVSUplinkPortPolicy)(nil)).Elem()
}
func (b *DailyTaskScheduler) GetDailyTaskScheduler() *DailyTaskScheduler { return b }
type BaseDailyTaskScheduler interface {
GetDailyTaskScheduler() *DailyTaskScheduler
}
func init() {
t["BaseDailyTaskScheduler"] = reflect.TypeOf((*DailyTaskScheduler)(nil)).Elem()
}
func (b *DatacenterEvent) GetDatacenterEvent() *DatacenterEvent { return b }
type BaseDatacenterEvent interface {
GetDatacenterEvent() *DatacenterEvent
}
func init() {
t["BaseDatacenterEvent"] = reflect.TypeOf((*DatacenterEvent)(nil)).Elem()
}
func (b *DatastoreEvent) GetDatastoreEvent() *DatastoreEvent { return b }
type BaseDatastoreEvent interface {
GetDatastoreEvent() *DatastoreEvent
}
func init() {
t["BaseDatastoreEvent"] = reflect.TypeOf((*DatastoreEvent)(nil)).Elem()
}
func (b *DatastoreFileEvent) GetDatastoreFileEvent() *DatastoreFileEvent { return b }
type BaseDatastoreFileEvent interface {
GetDatastoreFileEvent() *DatastoreFileEvent
}
func init() {
t["BaseDatastoreFileEvent"] = reflect.TypeOf((*DatastoreFileEvent)(nil)).Elem()
}
func (b *DatastoreInfo) GetDatastoreInfo() *DatastoreInfo { return b }
type BaseDatastoreInfo interface {
GetDatastoreInfo() *DatastoreInfo
}
func init() {
t["BaseDatastoreInfo"] = reflect.TypeOf((*DatastoreInfo)(nil)).Elem()
}
func (b *DatastoreNotWritableOnHost) GetDatastoreNotWritableOnHost() *DatastoreNotWritableOnHost {
return b
}
type BaseDatastoreNotWritableOnHost interface {
GetDatastoreNotWritableOnHost() *DatastoreNotWritableOnHost
}
func init() {
t["BaseDatastoreNotWritableOnHost"] = reflect.TypeOf((*DatastoreNotWritableOnHost)(nil)).Elem()
}
func (b *Description) GetDescription() *Description { return b }
type BaseDescription interface {
GetDescription() *Description
}
func init() {
t["BaseDescription"] = reflect.TypeOf((*Description)(nil)).Elem()
}
func (b *DeviceBackingNotSupported) GetDeviceBackingNotSupported() *DeviceBackingNotSupported {
return b
}
type BaseDeviceBackingNotSupported interface {
GetDeviceBackingNotSupported() *DeviceBackingNotSupported
}
func init() {
t["BaseDeviceBackingNotSupported"] = reflect.TypeOf((*DeviceBackingNotSupported)(nil)).Elem()
}
func (b *DeviceNotSupported) GetDeviceNotSupported() *DeviceNotSupported { return b }
type BaseDeviceNotSupported interface {
GetDeviceNotSupported() *DeviceNotSupported
}
func init() {
t["BaseDeviceNotSupported"] = reflect.TypeOf((*DeviceNotSupported)(nil)).Elem()
}
func (b *DirectPathProfileManagerCapacityQuerySpec) GetDirectPathProfileManagerCapacityQuerySpec() *DirectPathProfileManagerCapacityQuerySpec {
return b
}
type BaseDirectPathProfileManagerCapacityQuerySpec interface {
GetDirectPathProfileManagerCapacityQuerySpec() *DirectPathProfileManagerCapacityQuerySpec
}
func init() {
t["BaseDirectPathProfileManagerCapacityQuerySpec"] = reflect.TypeOf((*DirectPathProfileManagerCapacityQuerySpec)(nil)).Elem()
}
func (b *DirectPathProfileManagerCapacityResult) GetDirectPathProfileManagerCapacityResult() *DirectPathProfileManagerCapacityResult {
return b
}
type BaseDirectPathProfileManagerCapacityResult interface {
GetDirectPathProfileManagerCapacityResult() *DirectPathProfileManagerCapacityResult
}
func init() {
t["BaseDirectPathProfileManagerCapacityResult"] = reflect.TypeOf((*DirectPathProfileManagerCapacityResult)(nil)).Elem()
}
func (b *DirectPathProfileManagerDirectPathConfig) GetDirectPathProfileManagerDirectPathConfig() *DirectPathProfileManagerDirectPathConfig {
return b
}
type BaseDirectPathProfileManagerDirectPathConfig interface {
GetDirectPathProfileManagerDirectPathConfig() *DirectPathProfileManagerDirectPathConfig
}
func init() {
t["BaseDirectPathProfileManagerDirectPathConfig"] = reflect.TypeOf((*DirectPathProfileManagerDirectPathConfig)(nil)).Elem()
}
func (b *DirectPathProfileManagerTargetEntity) GetDirectPathProfileManagerTargetEntity() *DirectPathProfileManagerTargetEntity {
return b
}
type BaseDirectPathProfileManagerTargetEntity interface {
GetDirectPathProfileManagerTargetEntity() *DirectPathProfileManagerTargetEntity
}
func init() {
t["BaseDirectPathProfileManagerTargetEntity"] = reflect.TypeOf((*DirectPathProfileManagerTargetEntity)(nil)).Elem()
}
func (b *DiskNotSupported) GetDiskNotSupported() *DiskNotSupported { return b }
type BaseDiskNotSupported interface {
GetDiskNotSupported() *DiskNotSupported
}
func init() {
t["BaseDiskNotSupported"] = reflect.TypeOf((*DiskNotSupported)(nil)).Elem()
}
func (b *DistributedVirtualSwitchHostMemberBacking) GetDistributedVirtualSwitchHostMemberBacking() *DistributedVirtualSwitchHostMemberBacking {
return b
}
type BaseDistributedVirtualSwitchHostMemberBacking interface {
GetDistributedVirtualSwitchHostMemberBacking() *DistributedVirtualSwitchHostMemberBacking
}
func init() {
t["BaseDistributedVirtualSwitchHostMemberBacking"] = reflect.TypeOf((*DistributedVirtualSwitchHostMemberBacking)(nil)).Elem()
}
func (b *DistributedVirtualSwitchManagerHostDvsFilterSpec) GetDistributedVirtualSwitchManagerHostDvsFilterSpec() *DistributedVirtualSwitchManagerHostDvsFilterSpec {
return b
}
type BaseDistributedVirtualSwitchManagerHostDvsFilterSpec interface {
GetDistributedVirtualSwitchManagerHostDvsFilterSpec() *DistributedVirtualSwitchManagerHostDvsFilterSpec
}
func init() {
t["BaseDistributedVirtualSwitchManagerHostDvsFilterSpec"] = reflect.TypeOf((*DistributedVirtualSwitchManagerHostDvsFilterSpec)(nil)).Elem()
}
func (b *DvsEvent) GetDvsEvent() *DvsEvent { return b }
type BaseDvsEvent interface {
GetDvsEvent() *DvsEvent
}
func init() {
t["BaseDvsEvent"] = reflect.TypeOf((*DvsEvent)(nil)).Elem()
}
func (b *DvsFault) GetDvsFault() *DvsFault { return b }
type BaseDvsFault interface {
GetDvsFault() *DvsFault
}
func init() {
t["BaseDvsFault"] = reflect.TypeOf((*DvsFault)(nil)).Elem()
}
func (b *DvsFilterConfig) GetDvsFilterConfig() *DvsFilterConfig { return b }
type BaseDvsFilterConfig interface {
GetDvsFilterConfig() *DvsFilterConfig
}
func init() {
t["BaseDvsFilterConfig"] = reflect.TypeOf((*DvsFilterConfig)(nil)).Elem()
}
func (b *DvsHealthStatusChangeEvent) GetDvsHealthStatusChangeEvent() *DvsHealthStatusChangeEvent {
return b
}
type BaseDvsHealthStatusChangeEvent interface {
GetDvsHealthStatusChangeEvent() *DvsHealthStatusChangeEvent
}
func init() {
t["BaseDvsHealthStatusChangeEvent"] = reflect.TypeOf((*DvsHealthStatusChangeEvent)(nil)).Elem()
}
func (b *DvsIpPort) GetDvsIpPort() *DvsIpPort { return b }
type BaseDvsIpPort interface {
GetDvsIpPort() *DvsIpPort
}
func init() {
t["BaseDvsIpPort"] = reflect.TypeOf((*DvsIpPort)(nil)).Elem()
}
func (b *DvsNetworkRuleAction) GetDvsNetworkRuleAction() *DvsNetworkRuleAction { return b }
type BaseDvsNetworkRuleAction interface {
GetDvsNetworkRuleAction() *DvsNetworkRuleAction
}
func init() {
t["BaseDvsNetworkRuleAction"] = reflect.TypeOf((*DvsNetworkRuleAction)(nil)).Elem()
}
func (b *DvsNetworkRuleQualifier) GetDvsNetworkRuleQualifier() *DvsNetworkRuleQualifier { return b }
type BaseDvsNetworkRuleQualifier interface {
GetDvsNetworkRuleQualifier() *DvsNetworkRuleQualifier
}
func init() {
t["BaseDvsNetworkRuleQualifier"] = reflect.TypeOf((*DvsNetworkRuleQualifier)(nil)).Elem()
}
func (b *DvsTrafficFilterConfig) GetDvsTrafficFilterConfig() *DvsTrafficFilterConfig { return b }
type BaseDvsTrafficFilterConfig interface {
GetDvsTrafficFilterConfig() *DvsTrafficFilterConfig
}
func init() {
t["BaseDvsTrafficFilterConfig"] = reflect.TypeOf((*DvsTrafficFilterConfig)(nil)).Elem()
}
func (b *DvsVNicProfile) GetDvsVNicProfile() *DvsVNicProfile { return b }
type BaseDvsVNicProfile interface {
GetDvsVNicProfile() *DvsVNicProfile
}
func init() {
t["BaseDvsVNicProfile"] = reflect.TypeOf((*DvsVNicProfile)(nil)).Elem()
}
func (b *DynamicData) GetDynamicData() *DynamicData { return b }
type BaseDynamicData interface {
GetDynamicData() *DynamicData
}
func init() {
t["BaseDynamicData"] = reflect.TypeOf((*DynamicData)(nil)).Elem()
}
func (b *EVCAdmissionFailed) GetEVCAdmissionFailed() *EVCAdmissionFailed { return b }
type BaseEVCAdmissionFailed interface {
GetEVCAdmissionFailed() *EVCAdmissionFailed
}
func init() {
t["BaseEVCAdmissionFailed"] = reflect.TypeOf((*EVCAdmissionFailed)(nil)).Elem()
}
func (b *EVCConfigFault) GetEVCConfigFault() *EVCConfigFault { return b }
type BaseEVCConfigFault interface {
GetEVCConfigFault() *EVCConfigFault
}
func init() {
t["BaseEVCConfigFault"] = reflect.TypeOf((*EVCConfigFault)(nil)).Elem()
}
func (b *ElementDescription) GetElementDescription() *ElementDescription { return b }
type BaseElementDescription interface {
GetElementDescription() *ElementDescription
}
func init() {
t["BaseElementDescription"] = reflect.TypeOf((*ElementDescription)(nil)).Elem()
}
func (b *EnteredStandbyModeEvent) GetEnteredStandbyModeEvent() *EnteredStandbyModeEvent { return b }
type BaseEnteredStandbyModeEvent interface {
GetEnteredStandbyModeEvent() *EnteredStandbyModeEvent
}
func init() {
t["BaseEnteredStandbyModeEvent"] = reflect.TypeOf((*EnteredStandbyModeEvent)(nil)).Elem()
}
func (b *EnteringStandbyModeEvent) GetEnteringStandbyModeEvent() *EnteringStandbyModeEvent { return b }
type BaseEnteringStandbyModeEvent interface {
GetEnteringStandbyModeEvent() *EnteringStandbyModeEvent
}
func init() {
t["BaseEnteringStandbyModeEvent"] = reflect.TypeOf((*EnteringStandbyModeEvent)(nil)).Elem()
}
func (b *EntityEventArgument) GetEntityEventArgument() *EntityEventArgument { return b }
type BaseEntityEventArgument interface {
GetEntityEventArgument() *EntityEventArgument
}
func init() {
t["BaseEntityEventArgument"] = reflect.TypeOf((*EntityEventArgument)(nil)).Elem()
}
func (b *Event) GetEvent() *Event { return b }
type BaseEvent interface {
GetEvent() *Event
}
func init() {
t["BaseEvent"] = reflect.TypeOf((*Event)(nil)).Elem()
}
func (b *EventArgument) GetEventArgument() *EventArgument { return b }
type BaseEventArgument interface {
GetEventArgument() *EventArgument
}
func init() {
t["BaseEventArgument"] = reflect.TypeOf((*EventArgument)(nil)).Elem()
}
func (b *EventManagerEventViewSpec) GetEventManagerEventViewSpec() *EventManagerEventViewSpec {
return b
}
type BaseEventManagerEventViewSpec interface {
GetEventManagerEventViewSpec() *EventManagerEventViewSpec
}
func init() {
t["BaseEventManagerEventViewSpec"] = reflect.TypeOf((*EventManagerEventViewSpec)(nil)).Elem()
}
func (b *ExitStandbyModeFailedEvent) GetExitStandbyModeFailedEvent() *ExitStandbyModeFailedEvent {
return b
}
type BaseExitStandbyModeFailedEvent interface {
GetExitStandbyModeFailedEvent() *ExitStandbyModeFailedEvent
}
func init() {
t["BaseExitStandbyModeFailedEvent"] = reflect.TypeOf((*ExitStandbyModeFailedEvent)(nil)).Elem()
}
func (b *ExitedStandbyModeEvent) GetExitedStandbyModeEvent() *ExitedStandbyModeEvent { return b }
type BaseExitedStandbyModeEvent interface {
GetExitedStandbyModeEvent() *ExitedStandbyModeEvent
}
func init() {
t["BaseExitedStandbyModeEvent"] = reflect.TypeOf((*ExitedStandbyModeEvent)(nil)).Elem()
}
func (b *ExitingStandbyModeEvent) GetExitingStandbyModeEvent() *ExitingStandbyModeEvent { return b }
type BaseExitingStandbyModeEvent interface {
GetExitingStandbyModeEvent() *ExitingStandbyModeEvent
}
func init() {
t["BaseExitingStandbyModeEvent"] = reflect.TypeOf((*ExitingStandbyModeEvent)(nil)).Elem()
}
func (b *ExpiredFeatureLicense) GetExpiredFeatureLicense() *ExpiredFeatureLicense { return b }
type BaseExpiredFeatureLicense interface {
GetExpiredFeatureLicense() *ExpiredFeatureLicense
}
func init() {
t["BaseExpiredFeatureLicense"] = reflect.TypeOf((*ExpiredFeatureLicense)(nil)).Elem()
}
func (b *FaultToleranceConfigInfo) GetFaultToleranceConfigInfo() *FaultToleranceConfigInfo { return b }
type BaseFaultToleranceConfigInfo interface {
GetFaultToleranceConfigInfo() *FaultToleranceConfigInfo
}
func init() {
t["BaseFaultToleranceConfigInfo"] = reflect.TypeOf((*FaultToleranceConfigInfo)(nil)).Elem()
}
func (b *FcoeFault) GetFcoeFault() *FcoeFault { return b }
type BaseFcoeFault interface {
GetFcoeFault() *FcoeFault
}
func init() {
t["BaseFcoeFault"] = reflect.TypeOf((*FcoeFault)(nil)).Elem()
}
func (b *FileBackedVirtualDiskSpec) GetFileBackedVirtualDiskSpec() *FileBackedVirtualDiskSpec {
return b
}
type BaseFileBackedVirtualDiskSpec interface {
GetFileBackedVirtualDiskSpec() *FileBackedVirtualDiskSpec
}
func init() {
t["BaseFileBackedVirtualDiskSpec"] = reflect.TypeOf((*FileBackedVirtualDiskSpec)(nil)).Elem()
}
func (b *FileFault) GetFileFault() *FileFault { return b }
type BaseFileFault interface {
GetFileFault() *FileFault
}
func init() {
t["BaseFileFault"] = reflect.TypeOf((*FileFault)(nil)).Elem()
}
func (b *FileInfo) GetFileInfo() *FileInfo { return b }
type BaseFileInfo interface {
GetFileInfo() *FileInfo
}
func init() {
t["BaseFileInfo"] = reflect.TypeOf((*FileInfo)(nil)).Elem()
}
func (b *FileQuery) GetFileQuery() *FileQuery { return b }
type BaseFileQuery interface {
GetFileQuery() *FileQuery
}
func init() {
t["BaseFileQuery"] = reflect.TypeOf((*FileQuery)(nil)).Elem()
}
func (b *GatewayConnectFault) GetGatewayConnectFault() *GatewayConnectFault { return b }
type BaseGatewayConnectFault interface {
GetGatewayConnectFault() *GatewayConnectFault
}
func init() {
t["BaseGatewayConnectFault"] = reflect.TypeOf((*GatewayConnectFault)(nil)).Elem()
}
func (b *GatewayToHostConnectFault) GetGatewayToHostConnectFault() *GatewayToHostConnectFault {
return b
}
type BaseGatewayToHostConnectFault interface {
GetGatewayToHostConnectFault() *GatewayToHostConnectFault
}
func init() {
t["BaseGatewayToHostConnectFault"] = reflect.TypeOf((*GatewayToHostConnectFault)(nil)).Elem()
}
func (b *GeneralEvent) GetGeneralEvent() *GeneralEvent { return b }
type BaseGeneralEvent interface {
GetGeneralEvent() *GeneralEvent
}
func init() {
t["BaseGeneralEvent"] = reflect.TypeOf((*GeneralEvent)(nil)).Elem()
}
func (b *GuestAuthSubject) GetGuestAuthSubject() *GuestAuthSubject { return b }
type BaseGuestAuthSubject interface {
GetGuestAuthSubject() *GuestAuthSubject
}
func init() {
t["BaseGuestAuthSubject"] = reflect.TypeOf((*GuestAuthSubject)(nil)).Elem()
}
func (b *GuestAuthentication) GetGuestAuthentication() *GuestAuthentication { return b }
type BaseGuestAuthentication interface {
GetGuestAuthentication() *GuestAuthentication
}
func init() {
t["BaseGuestAuthentication"] = reflect.TypeOf((*GuestAuthentication)(nil)).Elem()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/configspec.go | vendor/github.com/vmware/govmomi/vim25/types/configspec.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"fmt"
)
// EnsureDisksHaveControllers ensures that all disks in the provided
// ConfigSpec point to a controller. If no controller exists, LSILogic SCSI
// controllers are added to the ConfigSpec as necessary for the disks.
//
// Please note the following table for the number of controllers of each type
// that are supported as well as how many disks (per controller) each supports:
//
// SATA
// - controllers 4
// - disks 30
//
// SCSI
// - controllers 4
// - disks (non-paravirtual) 16
// - disks (paravirtual, hardware version <14) 16
// - disks (paravirtual, hardware version >=14) 256
//
// NVME
// - controllers 4
// - disks (hardware version <20) 15
// - disks (hardware version >=21) 255
func (cs *VirtualMachineConfigSpec) EnsureDisksHaveControllers(
existingDevices ...BaseVirtualDevice) error {
if cs == nil {
panic("configSpec is nil")
}
var (
disks []*VirtualDisk
newDeviceKey int32
pciController *VirtualPCIController
diskControllers = ensureDiskControllerData{
controllerKeys: map[int32]BaseVirtualController{},
controllerKeysToAttachedDisks: map[int32]int{},
}
)
// Inspect the ConfigSpec
for i := range cs.DeviceChange {
var (
bdc BaseVirtualDeviceConfigSpec
bvd BaseVirtualDevice
dc *VirtualDeviceConfigSpec
d *VirtualDevice
)
if bdc = cs.DeviceChange[i]; bdc == nil {
continue
}
if dc = bdc.GetVirtualDeviceConfigSpec(); dc == nil {
continue
}
if dc.Operation == VirtualDeviceConfigSpecOperationRemove {
// Do not consider devices being removed.
continue
}
bvd = dc.Device
if bvd == nil {
continue
}
if d = bvd.GetVirtualDevice(); d == nil {
continue
}
switch tvd := bvd.(type) {
case *VirtualPCIController:
pciController = tvd
case
// SCSI
*ParaVirtualSCSIController,
*VirtualBusLogicController,
*VirtualLsiLogicController,
*VirtualLsiLogicSASController,
*VirtualSCSIController,
// SATA
*VirtualSATAController,
*VirtualAHCIController,
// NVME
*VirtualNVMEController:
diskControllers.add(bvd)
case *VirtualDisk:
disks = append(disks, tvd)
if controllerKey := d.ControllerKey; controllerKey != 0 {
// If the disk points to a controller key, then increment
// the number of devices attached to that controller.
//
// Please note that at this point it is not yet known if the
// controller key is a *valid* controller.
diskControllers.attach(controllerKey)
}
}
// Keep track of the smallest device key used. Please note, because
// device keys in a ConfigSpec are negative numbers, -200 going to be
// smaller than -1.
if d.Key < newDeviceKey {
newDeviceKey = d.Key
}
}
if len(disks) == 0 {
// If there are no disks, then go ahead and return early.
return nil
}
// Categorize any controllers that already exist.
for i := range existingDevices {
var (
d *VirtualDevice
bvd = existingDevices[i]
)
if bvd == nil {
continue
}
if d = bvd.GetVirtualDevice(); d == nil {
continue
}
switch tvd := bvd.(type) {
case *VirtualPCIController:
pciController = tvd
case
// SCSI
*ParaVirtualSCSIController,
*VirtualBusLogicController,
*VirtualLsiLogicController,
*VirtualLsiLogicSASController,
*VirtualSCSIController,
// SATA
*VirtualSATAController,
*VirtualAHCIController,
// NVME
*VirtualNVMEController:
diskControllers.add(bvd)
case *VirtualDisk:
diskControllers.attach(tvd.ControllerKey)
}
}
// Decrement the newDeviceKey so the next device has a unique key.
newDeviceKey--
if pciController == nil {
// Add a PCI controller if one is not present.
pciController = &VirtualPCIController{
VirtualController: VirtualController{
VirtualDevice: VirtualDevice{
Key: newDeviceKey,
},
},
}
// Decrement the newDeviceKey so the next device has a unique key.
newDeviceKey--
// Add the new PCI controller to the ConfigSpec.
cs.DeviceChange = append(
cs.DeviceChange,
&VirtualDeviceConfigSpec{
Operation: VirtualDeviceConfigSpecOperationAdd,
Device: pciController,
})
}
// Ensure all the recorded controller keys that point to disks are actually
// valid controller keys.
diskControllers.validateAttachments()
for i := range disks {
disk := disks[i]
// If the disk already points to a controller then skip to the next
// disk.
if diskControllers.exists(disk.ControllerKey) {
continue
}
// The disk does not point to a controller, so try to locate one.
if ensureDiskControllerFind(disk, &diskControllers) {
// A controller was located for the disk, so go ahead and skip to
// the next disk.
continue
}
// No controller was located for the disk, so a controller must be
// created.
if err := ensureDiskControllerCreate(
cs,
pciController,
newDeviceKey,
&diskControllers); err != nil {
return err
}
// Point the disk to the new controller.
disk.ControllerKey = newDeviceKey
// Add the controller key to the map that tracks how many disks are
// attached to a given controller.
diskControllers.attach(newDeviceKey)
// Decrement the newDeviceKey so the next device has a unique key.
newDeviceKey--
}
return nil
}
const (
maxSCSIControllers = 4
maxSATAControllers = 4
maxNVMEControllers = 4
maxDisksPerSCSIController = 16
maxDisksPerPVSCSIControllerHWVersion14 = 256 // TODO(akutz)
maxDisksPerSATAController = 30
maxDisksPerNVMEController = 15
maxDisksPerNVMEControllerHWVersion21 = 255 // TODO(akutz)
)
type ensureDiskControllerBusNumbers struct {
zero bool
one bool
two bool
}
func (d ensureDiskControllerBusNumbers) free() int32 {
switch {
case !d.zero:
return 0
case !d.one:
return 1
case !d.two:
return 2
default:
return 3
}
}
func (d *ensureDiskControllerBusNumbers) set(busNumber int32) {
switch busNumber {
case 0:
d.zero = true
case 1:
d.one = true
case 2:
d.two = true
}
}
type ensureDiskControllerData struct {
// TODO(akutz) Use the hardware version when calculating the max disks for
// a given controller type.
// hardwareVersion int
controllerKeys map[int32]BaseVirtualController
controllerKeysToAttachedDisks map[int32]int
// SCSI
scsiBusNumbers ensureDiskControllerBusNumbers
pvSCSIControllerKeys []int32
busLogicSCSIControllerKeys []int32
lsiLogicControllerKeys []int32
lsiLogicSASControllerKeys []int32
scsiControllerKeys []int32
// SATA
sataBusNumbers ensureDiskControllerBusNumbers
sataControllerKeys []int32
ahciControllerKeys []int32
// NVME
nvmeBusNumbers ensureDiskControllerBusNumbers
nvmeControllerKeys []int32
}
func (d ensureDiskControllerData) numSCSIControllers() int {
return len(d.pvSCSIControllerKeys) +
len(d.busLogicSCSIControllerKeys) +
len(d.lsiLogicControllerKeys) +
len(d.lsiLogicSASControllerKeys) +
len(d.scsiControllerKeys)
}
func (d ensureDiskControllerData) numSATAControllers() int {
return len(d.sataControllerKeys) + len(d.ahciControllerKeys)
}
func (d ensureDiskControllerData) numNVMEControllers() int {
return len(d.nvmeControllerKeys)
}
// validateAttachments ensures the attach numbers are correct by removing any
// keys from controllerKeysToAttachedDisks that do not also exist in
// controllerKeys.
func (d ensureDiskControllerData) validateAttachments() {
// Remove any invalid controllers from controllerKeyToNumDiskMap.
for key := range d.controllerKeysToAttachedDisks {
if _, ok := d.controllerKeys[key]; !ok {
delete(d.controllerKeysToAttachedDisks, key)
}
}
}
// exists returns true if a controller with the provided key exists.
func (d ensureDiskControllerData) exists(key int32) bool {
return d.controllerKeys[key] != nil
}
// add records the provided controller in the map that relates keys to
// controllers as well as appends the key to the list of controllers of that
// given type.
func (d *ensureDiskControllerData) add(controller BaseVirtualDevice) {
// Get the controller's device key.
bvc := controller.(BaseVirtualController)
key := bvc.GetVirtualController().Key
busNumber := bvc.GetVirtualController().BusNumber
// Record the controller's device key in the controller key map.
d.controllerKeys[key] = bvc
// Record the controller's device key in the list for that type of
// controller.
switch controller.(type) {
// SCSI
case *ParaVirtualSCSIController:
d.pvSCSIControllerKeys = append(d.pvSCSIControllerKeys, key)
d.scsiBusNumbers.set(busNumber)
case *VirtualBusLogicController:
d.busLogicSCSIControllerKeys = append(d.busLogicSCSIControllerKeys, key)
d.scsiBusNumbers.set(busNumber)
case *VirtualLsiLogicController:
d.lsiLogicControllerKeys = append(d.lsiLogicControllerKeys, key)
d.scsiBusNumbers.set(busNumber)
case *VirtualLsiLogicSASController:
d.lsiLogicSASControllerKeys = append(d.lsiLogicSASControllerKeys, key)
d.scsiBusNumbers.set(busNumber)
case *VirtualSCSIController:
d.scsiControllerKeys = append(d.scsiControllerKeys, key)
d.scsiBusNumbers.set(busNumber)
// SATA
case *VirtualSATAController:
d.sataControllerKeys = append(d.sataControllerKeys, key)
d.sataBusNumbers.set(busNumber)
case *VirtualAHCIController:
d.ahciControllerKeys = append(d.ahciControllerKeys, key)
d.sataBusNumbers.set(busNumber)
// NVME
case *VirtualNVMEController:
d.nvmeControllerKeys = append(d.nvmeControllerKeys, key)
d.nvmeBusNumbers.set(busNumber)
}
}
// attach increments the number of disks attached to the controller identified
// by the provided controller key.
func (d *ensureDiskControllerData) attach(controllerKey int32) {
d.controllerKeysToAttachedDisks[controllerKey]++
}
// hasFreeSlot returns whether or not the controller identified by the provided
// controller key has a free slot to attach a disk.
//
// TODO(akutz) Consider the hardware version when calculating these values.
func (d *ensureDiskControllerData) hasFreeSlot(controllerKey int32) bool {
var maxDisksForType int
switch d.controllerKeys[controllerKey].(type) {
case
// SCSI (paravirtual)
*ParaVirtualSCSIController:
maxDisksForType = maxDisksPerSCSIController
case
// SCSI (non-paravirtual)
*VirtualBusLogicController,
*VirtualLsiLogicController,
*VirtualLsiLogicSASController,
*VirtualSCSIController:
maxDisksForType = maxDisksPerSCSIController
case
// SATA
*VirtualSATAController,
*VirtualAHCIController:
maxDisksForType = maxDisksPerSATAController
case
// NVME
*VirtualNVMEController:
maxDisksForType = maxDisksPerNVMEController
}
return d.controllerKeysToAttachedDisks[controllerKey] < maxDisksForType-1
}
// ensureDiskControllerFind attempts to locate a controller for the provided
// disk.
//
// Please note this function is written to preserve the order in which
// controllers are located by preferring controller types in the order in which
// they are listed in this function. This prevents the following situation:
//
// - A ConfigSpec has three controllers in the following order: PVSCSI-1,
// NVME-1, and PVSCSI-2.
// - The controller PVSCSI-1 is full while NVME-1 and PVSCSI-2 have free
// slots.
// - The *desired* behavior is to look at all, possible PVSCSI controllers
// before moving onto SATA and then finally NVME controllers.
// - If the function iterated over the device list in list-order, then the
// NVME-1 controller would be located first.
// - Instead, this function iterates over each *type* of controller first
// before moving onto the next type.
// - This means that even though NVME-1 has free slots, PVSCSI-2 is checked
// first.
//
// The order of preference is as follows:
//
// * SCSI
// - ParaVirtualSCSIController
// - VirtualBusLogicController
// - VirtualLsiLogicController
// - VirtualLsiLogicSASController
// - VirtualSCSIController
//
// * SATA
// - VirtualSATAController
// - VirtualAHCIController
//
// * NVME
// - VirtualNVMEController
func ensureDiskControllerFind(
disk *VirtualDisk,
diskControllers *ensureDiskControllerData) bool {
return false ||
// SCSI
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.pvSCSIControllerKeys) ||
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.busLogicSCSIControllerKeys) ||
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.lsiLogicControllerKeys) ||
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.lsiLogicSASControllerKeys) ||
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.scsiControllerKeys) ||
// SATA
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.sataControllerKeys) ||
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.ahciControllerKeys) ||
// NVME
ensureDiskControllerFindWith(
disk,
diskControllers,
diskControllers.nvmeControllerKeys)
}
func ensureDiskControllerFindWith(
disk *VirtualDisk,
diskControllers *ensureDiskControllerData,
controllerKeys []int32) bool {
for i := range controllerKeys {
controllerKey := controllerKeys[i]
if diskControllers.hasFreeSlot(controllerKey) {
// If the controller has room for another disk, then use this
// controller for the current disk.
disk.ControllerKey = controllerKey
diskControllers.attach(controllerKey)
return true
}
}
return false
}
func ensureDiskControllerCreate(
configSpec *VirtualMachineConfigSpec,
pciController *VirtualPCIController,
newDeviceKey int32,
diskControllers *ensureDiskControllerData) error {
var controller BaseVirtualDevice
switch {
case diskControllers.numSCSIControllers() < maxSCSIControllers:
// Prefer creating a new SCSI controller.
controller = &ParaVirtualSCSIController{
VirtualSCSIController: VirtualSCSIController{
VirtualController: VirtualController{
VirtualDevice: VirtualDevice{
ControllerKey: pciController.Key,
Key: newDeviceKey,
},
BusNumber: diskControllers.scsiBusNumbers.free(),
},
HotAddRemove: NewBool(true),
SharedBus: VirtualSCSISharingNoSharing,
},
}
case diskControllers.numSATAControllers() < maxSATAControllers:
// If there are no more SCSI controllers, create a SATA
// controller.
controller = &VirtualAHCIController{
VirtualSATAController: VirtualSATAController{
VirtualController: VirtualController{
VirtualDevice: VirtualDevice{
ControllerKey: pciController.Key,
Key: newDeviceKey,
},
BusNumber: diskControllers.sataBusNumbers.free(),
},
},
}
case diskControllers.numNVMEControllers() < maxNVMEControllers:
// If there are no more SATA controllers, create an NVME
// controller.
controller = &VirtualNVMEController{
VirtualController: VirtualController{
VirtualDevice: VirtualDevice{
ControllerKey: pciController.Key,
Key: newDeviceKey,
},
BusNumber: diskControllers.nvmeBusNumbers.free(),
},
SharedBus: string(VirtualNVMEControllerSharingNoSharing),
}
default:
return fmt.Errorf("no controllers available")
}
// Add the new controller to the ConfigSpec.
configSpec.DeviceChange = append(
configSpec.DeviceChange,
&VirtualDeviceConfigSpec{
Operation: VirtualDeviceConfigSpecOperationAdd,
Device: controller,
})
// Record the new controller.
diskControllers.add(controller)
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/deep_copy.go | vendor/github.com/vmware/govmomi/vim25/types/deep_copy.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"bytes"
)
// DeepCopyInto creates a deep-copy of src by encoding it to JSON and then
// decoding that into dst.
// Please note, empty slices or maps in src that are set to omitempty will be
// nil in the copied object.
func DeepCopyInto[T AnyType](dst *T, src T) error {
var w bytes.Buffer
e := NewJSONEncoder(&w)
if err := e.Encode(src); err != nil {
return err
}
d := NewJSONDecoder(&w)
if err := d.Decode(dst); err != nil {
return err
}
return nil
}
// MustDeepCopyInto panics if DeepCopyInto returns an error.
func MustDeepCopyInto[T AnyType](dst *T, src T) error {
if err := DeepCopyInto(dst, src); err != nil {
panic(err)
}
return nil
}
// DeepCopy creates a deep-copy of src by encoding it to JSON and then decoding
// that into a new instance of T.
// Please note, empty slices or maps in src that are set to omitempty will be
// nil in the copied object.
func DeepCopy[T AnyType](src T) (T, error) {
var dst T
err := DeepCopyInto(&dst, src)
return dst, err
}
// MustDeepCopy panics if DeepCopy returns an error.
func MustDeepCopy[T AnyType](src T) T {
dst, err := DeepCopy(src)
if err != nil {
panic(err)
}
return dst
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/enum.go | vendor/github.com/vmware/govmomi/vim25/types/enum.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import "reflect"
// These constant strings can be used as parameters in user-specified
// email subject and body templates as well as in scripts.
//
// The action processor
// in VirtualCenter substitutes the run-time values for the parameters.
// For example, an email subject provided by the client could be the string:
// `Alarm - {alarmName} Description:\n{eventDescription}`.
// Or a script action provided could be: `myScript {alarmName}`.
type ActionParameter string
const (
// The name of the entity where the alarm is triggered.
ActionParameterTargetName = ActionParameter("targetName")
// The name of the triggering alarm.
ActionParameterAlarmName = ActionParameter("alarmName")
// The status prior to the alarm being triggered.
ActionParameterOldStatus = ActionParameter("oldStatus")
// The status after the alarm is triggered.
ActionParameterNewStatus = ActionParameter("newStatus")
// A summary of information involved in triggering the alarm.
ActionParameterTriggeringSummary = ActionParameter("triggeringSummary")
// A summary of declarations made during the triggering of the alarm.
ActionParameterDeclaringSummary = ActionParameter("declaringSummary")
// The event description.
ActionParameterEventDescription = ActionParameter("eventDescription")
// The object of the entity where the alarm is associated.
ActionParameterTarget = ActionParameter("target")
// The object of the triggering alarm.
ActionParameterAlarm = ActionParameter("alarm")
)
func (e ActionParameter) Values() []ActionParameter {
return []ActionParameter{
ActionParameterTargetName,
ActionParameterAlarmName,
ActionParameterOldStatus,
ActionParameterNewStatus,
ActionParameterTriggeringSummary,
ActionParameterDeclaringSummary,
ActionParameterEventDescription,
ActionParameterTarget,
ActionParameterAlarm,
}
}
func (e ActionParameter) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ActionParameter"] = reflect.TypeOf((*ActionParameter)(nil)).Elem()
}
// Pre-defined constants for possible action types.
//
// Virtual Center
// uses this information to coordinate with the clients.
type ActionType string
const (
// Migration action type
ActionTypeMigrationV1 = ActionType("MigrationV1")
// Virtual machine power action type
ActionTypeVmPowerV1 = ActionType("VmPowerV1")
// Host power action type
ActionTypeHostPowerV1 = ActionType("HostPowerV1")
// Host entering maintenance mode action type
ActionTypeHostMaintenanceV1 = ActionType("HostMaintenanceV1")
// Storage migration action type
ActionTypeStorageMigrationV1 = ActionType("StorageMigrationV1")
// Initial placement action for a virtual machine or a virtual disk
ActionTypeStoragePlacementV1 = ActionType("StoragePlacementV1")
// Initial placement action for a virtual machine and its virtual disks
ActionTypePlacementV1 = ActionType("PlacementV1")
// Host changing infrastructure update ha mode action type.
ActionTypeHostInfraUpdateHaV1 = ActionType("HostInfraUpdateHaV1")
)
func (e ActionType) Values() []ActionType {
return []ActionType{
ActionTypeMigrationV1,
ActionTypeVmPowerV1,
ActionTypeHostPowerV1,
ActionTypeHostMaintenanceV1,
ActionTypeStorageMigrationV1,
ActionTypeStoragePlacementV1,
ActionTypePlacementV1,
ActionTypeHostInfraUpdateHaV1,
}
}
func (e ActionType) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ActionType"] = reflect.TypeOf((*ActionType)(nil)).Elem()
}
// Types of affinities.
type AffinityType string
const (
AffinityTypeMemory = AffinityType("memory")
AffinityTypeCpu = AffinityType("cpu")
)
func (e AffinityType) Values() []AffinityType {
return []AffinityType{
AffinityTypeMemory,
AffinityTypeCpu,
}
}
func (e AffinityType) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AffinityType"] = reflect.TypeOf((*AffinityType)(nil)).Elem()
}
type AgentInstallFailedReason string
const (
// There is not enough storage space on the host to install the agent.
AgentInstallFailedReasonNotEnoughSpaceOnDevice = AgentInstallFailedReason("NotEnoughSpaceOnDevice")
// Failed to initialize the upgrade directory on the host.
AgentInstallFailedReasonPrepareToUpgradeFailed = AgentInstallFailedReason("PrepareToUpgradeFailed")
// The agent was installed but is not running.
AgentInstallFailedReasonAgentNotRunning = AgentInstallFailedReason("AgentNotRunning")
// The agent was installed but did not respond to requests.
AgentInstallFailedReasonAgentNotReachable = AgentInstallFailedReason("AgentNotReachable")
// The agent install took too long.
AgentInstallFailedReasonInstallTimedout = AgentInstallFailedReason("InstallTimedout")
// The signature verification for the installer failed.
AgentInstallFailedReasonSignatureVerificationFailed = AgentInstallFailedReason("SignatureVerificationFailed")
// Failed to upload the agent installer.
AgentInstallFailedReasonAgentUploadFailed = AgentInstallFailedReason("AgentUploadFailed")
// The agent upload took too long.
AgentInstallFailedReasonAgentUploadTimedout = AgentInstallFailedReason("AgentUploadTimedout")
// The agent installer failed for an unknown reason.
AgentInstallFailedReasonUnknownInstallerError = AgentInstallFailedReason("UnknownInstallerError")
)
func (e AgentInstallFailedReason) Values() []AgentInstallFailedReason {
return []AgentInstallFailedReason{
AgentInstallFailedReasonNotEnoughSpaceOnDevice,
AgentInstallFailedReasonPrepareToUpgradeFailed,
AgentInstallFailedReasonAgentNotRunning,
AgentInstallFailedReasonAgentNotReachable,
AgentInstallFailedReasonInstallTimedout,
AgentInstallFailedReasonSignatureVerificationFailed,
AgentInstallFailedReasonAgentUploadFailed,
AgentInstallFailedReasonAgentUploadTimedout,
AgentInstallFailedReasonUnknownInstallerError,
}
}
func (e AgentInstallFailedReason) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AgentInstallFailedReason"] = reflect.TypeOf((*AgentInstallFailedReason)(nil)).Elem()
}
// Alarm entity type
type AlarmFilterSpecAlarmTypeByEntity string
const (
// Alarms on all entity types.
AlarmFilterSpecAlarmTypeByEntityEntityTypeAll = AlarmFilterSpecAlarmTypeByEntity("entityTypeAll")
// Host alarms
AlarmFilterSpecAlarmTypeByEntityEntityTypeHost = AlarmFilterSpecAlarmTypeByEntity("entityTypeHost")
// VM alarms
AlarmFilterSpecAlarmTypeByEntityEntityTypeVm = AlarmFilterSpecAlarmTypeByEntity("entityTypeVm")
)
func (e AlarmFilterSpecAlarmTypeByEntity) Values() []AlarmFilterSpecAlarmTypeByEntity {
return []AlarmFilterSpecAlarmTypeByEntity{
AlarmFilterSpecAlarmTypeByEntityEntityTypeAll,
AlarmFilterSpecAlarmTypeByEntityEntityTypeHost,
AlarmFilterSpecAlarmTypeByEntityEntityTypeVm,
}
}
func (e AlarmFilterSpecAlarmTypeByEntity) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AlarmFilterSpecAlarmTypeByEntity"] = reflect.TypeOf((*AlarmFilterSpecAlarmTypeByEntity)(nil)).Elem()
}
// Alarm triggering type.
//
// The main divisions are event triggered and
// metric- or state-based alarms.
type AlarmFilterSpecAlarmTypeByTrigger string
const (
// All alarm types.
AlarmFilterSpecAlarmTypeByTriggerTriggerTypeAll = AlarmFilterSpecAlarmTypeByTrigger("triggerTypeAll")
// Event based alarms
AlarmFilterSpecAlarmTypeByTriggerTriggerTypeEvent = AlarmFilterSpecAlarmTypeByTrigger("triggerTypeEvent")
// Metric or state alarms
AlarmFilterSpecAlarmTypeByTriggerTriggerTypeMetric = AlarmFilterSpecAlarmTypeByTrigger("triggerTypeMetric")
)
func (e AlarmFilterSpecAlarmTypeByTrigger) Values() []AlarmFilterSpecAlarmTypeByTrigger {
return []AlarmFilterSpecAlarmTypeByTrigger{
AlarmFilterSpecAlarmTypeByTriggerTriggerTypeAll,
AlarmFilterSpecAlarmTypeByTriggerTriggerTypeEvent,
AlarmFilterSpecAlarmTypeByTriggerTriggerTypeMetric,
}
}
func (e AlarmFilterSpecAlarmTypeByTrigger) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AlarmFilterSpecAlarmTypeByTrigger"] = reflect.TypeOf((*AlarmFilterSpecAlarmTypeByTrigger)(nil)).Elem()
}
// Defines the result status values for a validating answer file.
type AnswerFileValidationInfoStatus string
const (
// Answer File validation was successful.
AnswerFileValidationInfoStatusSuccess = AnswerFileValidationInfoStatus("success")
// Answer File validation failed.
AnswerFileValidationInfoStatusFailed = AnswerFileValidationInfoStatus("failed")
// Answer File validation failed to generate default.
AnswerFileValidationInfoStatusFailed_defaults = AnswerFileValidationInfoStatus("failed_defaults")
)
func (e AnswerFileValidationInfoStatus) Values() []AnswerFileValidationInfoStatus {
return []AnswerFileValidationInfoStatus{
AnswerFileValidationInfoStatusSuccess,
AnswerFileValidationInfoStatusFailed,
AnswerFileValidationInfoStatusFailed_defaults,
}
}
func (e AnswerFileValidationInfoStatus) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AnswerFileValidationInfoStatus"] = reflect.TypeOf((*AnswerFileValidationInfoStatus)(nil)).Elem()
}
type ApplyHostProfileConfigurationResultStatus string
const (
// Remediation succeeded.
ApplyHostProfileConfigurationResultStatusSuccess = ApplyHostProfileConfigurationResultStatus("success")
// Remediation failed.
ApplyHostProfileConfigurationResultStatusFailed = ApplyHostProfileConfigurationResultStatus("failed")
// Remediation succeeded but reboot after remediation failed.
//
// May treat this as a warning.
ApplyHostProfileConfigurationResultStatusReboot_failed = ApplyHostProfileConfigurationResultStatus("reboot_failed")
// Stateless reboot for remediation failed.
ApplyHostProfileConfigurationResultStatusStateless_reboot_failed = ApplyHostProfileConfigurationResultStatus("stateless_reboot_failed")
// Remediation and reboot succeeded but check compliance after reboot
// failed.
//
// May treat this as a warning.
ApplyHostProfileConfigurationResultStatusCheck_compliance_failed = ApplyHostProfileConfigurationResultStatus("check_compliance_failed")
// The required state is not satisfied so host profiel apply cannot
// be done.
ApplyHostProfileConfigurationResultStatusState_not_satisfied = ApplyHostProfileConfigurationResultStatus("state_not_satisfied")
// Exit maintenance mode failed.
ApplyHostProfileConfigurationResultStatusExit_maintenancemode_failed = ApplyHostProfileConfigurationResultStatus("exit_maintenancemode_failed")
// The remediation was canceled.
ApplyHostProfileConfigurationResultStatusCanceled = ApplyHostProfileConfigurationResultStatus("canceled")
)
func (e ApplyHostProfileConfigurationResultStatus) Values() []ApplyHostProfileConfigurationResultStatus {
return []ApplyHostProfileConfigurationResultStatus{
ApplyHostProfileConfigurationResultStatusSuccess,
ApplyHostProfileConfigurationResultStatusFailed,
ApplyHostProfileConfigurationResultStatusReboot_failed,
ApplyHostProfileConfigurationResultStatusStateless_reboot_failed,
ApplyHostProfileConfigurationResultStatusCheck_compliance_failed,
ApplyHostProfileConfigurationResultStatusState_not_satisfied,
ApplyHostProfileConfigurationResultStatusExit_maintenancemode_failed,
ApplyHostProfileConfigurationResultStatusCanceled,
}
}
func (e ApplyHostProfileConfigurationResultStatus) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ApplyHostProfileConfigurationResultStatus"] = reflect.TypeOf((*ApplyHostProfileConfigurationResultStatus)(nil)).Elem()
}
// This list specifies the type of operation being performed on the array.
type ArrayUpdateOperation string
const (
// indicates an addition to the array.
ArrayUpdateOperationAdd = ArrayUpdateOperation("add")
// indicates the removal of an element in the
// array.
//
// In this case the key field must contain the key of the element
// to be removed.
ArrayUpdateOperationRemove = ArrayUpdateOperation("remove")
// indicates changes to an element in the array.
ArrayUpdateOperationEdit = ArrayUpdateOperation("edit")
)
func (e ArrayUpdateOperation) Values() []ArrayUpdateOperation {
return []ArrayUpdateOperation{
ArrayUpdateOperationAdd,
ArrayUpdateOperationRemove,
ArrayUpdateOperationEdit,
}
}
func (e ArrayUpdateOperation) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ArrayUpdateOperation"] = reflect.TypeOf((*ArrayUpdateOperation)(nil)).Elem()
}
type AutoStartAction string
const (
// No action is taken for this virtual machine.
//
// This virtual machine is
// not a part of the auto-start sequence. This can be used for both auto-start
// and auto-start settings.
AutoStartActionNone = AutoStartAction("none")
// The default system action is taken for this virtual machine when it is next in
// the auto-start order.
//
// This can be used for both auto-start and auto-start
// settings.
AutoStartActionSystemDefault = AutoStartAction("systemDefault")
// This virtual machine is powered on when it is next in the auto-start order.
AutoStartActionPowerOn = AutoStartAction("powerOn")
// This virtual machine is powered off when it is next in the auto-stop order.
//
// This is the default stopAction.
AutoStartActionPowerOff = AutoStartAction("powerOff")
// The guest operating system for a virtual machine is shut down when that
// virtual machine in next in the auto-stop order.
AutoStartActionGuestShutdown = AutoStartAction("guestShutdown")
// This virtual machine is suspended when it is next in the auto-stop order.
AutoStartActionSuspend = AutoStartAction("suspend")
)
func (e AutoStartAction) Values() []AutoStartAction {
return []AutoStartAction{
AutoStartActionNone,
AutoStartActionSystemDefault,
AutoStartActionPowerOn,
AutoStartActionPowerOff,
AutoStartActionGuestShutdown,
AutoStartActionSuspend,
}
}
func (e AutoStartAction) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AutoStartAction"] = reflect.TypeOf((*AutoStartAction)(nil)).Elem()
}
// Determines if the virtual machine should start after receiving a heartbeat,
// ignore heartbeats and start after the startDelay has elapsed, or follow the
// system default before powering on.
//
// When a virtual machine is next in the start
// order, the system either waits a specified period of time for a virtual
// machine to power on or it waits until it receives a successful heartbeat from a
// powered on virtual machine. By default, this is set to no.
type AutoStartWaitHeartbeatSetting string
const (
// The system waits until receiving a heartbeat before powering on the next
// machine in the order.
AutoStartWaitHeartbeatSettingYes = AutoStartWaitHeartbeatSetting("yes")
// The system does not wait to receive a heartbeat before powering on the next
// machine in the order.
//
// This is the default setting.
AutoStartWaitHeartbeatSettingNo = AutoStartWaitHeartbeatSetting("no")
// The system uses the default value to determine whether or not to wait to
// receive a heartbeat before powering on the next machine in the order.
AutoStartWaitHeartbeatSettingSystemDefault = AutoStartWaitHeartbeatSetting("systemDefault")
)
func (e AutoStartWaitHeartbeatSetting) Values() []AutoStartWaitHeartbeatSetting {
return []AutoStartWaitHeartbeatSetting{
AutoStartWaitHeartbeatSettingYes,
AutoStartWaitHeartbeatSettingNo,
AutoStartWaitHeartbeatSettingSystemDefault,
}
}
func (e AutoStartWaitHeartbeatSetting) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["AutoStartWaitHeartbeatSetting"] = reflect.TypeOf((*AutoStartWaitHeartbeatSetting)(nil)).Elem()
}
// Provisioning type constants.
type BaseConfigInfoDiskFileBackingInfoProvisioningType string
const (
// Space required for thin-provisioned virtual disk is allocated
// and zeroed on demand as the space is used.
BaseConfigInfoDiskFileBackingInfoProvisioningTypeThin = BaseConfigInfoDiskFileBackingInfoProvisioningType("thin")
// An eager zeroed thick virtual disk has all space allocated and
// wiped clean of any previous contents on the physical media at
// creation time.
//
// Such virtual disk may take longer time
// during creation compared to other provisioning formats.
BaseConfigInfoDiskFileBackingInfoProvisioningTypeEagerZeroedThick = BaseConfigInfoDiskFileBackingInfoProvisioningType("eagerZeroedThick")
// A thick virtual disk has all space allocated at creation time.
//
// This space may contain stale data on the physical media.
BaseConfigInfoDiskFileBackingInfoProvisioningTypeLazyZeroedThick = BaseConfigInfoDiskFileBackingInfoProvisioningType("lazyZeroedThick")
)
func (e BaseConfigInfoDiskFileBackingInfoProvisioningType) Values() []BaseConfigInfoDiskFileBackingInfoProvisioningType {
return []BaseConfigInfoDiskFileBackingInfoProvisioningType{
BaseConfigInfoDiskFileBackingInfoProvisioningTypeThin,
BaseConfigInfoDiskFileBackingInfoProvisioningTypeEagerZeroedThick,
BaseConfigInfoDiskFileBackingInfoProvisioningTypeLazyZeroedThick,
}
}
func (e BaseConfigInfoDiskFileBackingInfoProvisioningType) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["BaseConfigInfoDiskFileBackingInfoProvisioningType"] = reflect.TypeOf((*BaseConfigInfoDiskFileBackingInfoProvisioningType)(nil)).Elem()
}
// Enum representing result of batch-APis.
type BatchResultResult string
const (
BatchResultResultSuccess = BatchResultResult("success")
BatchResultResultFail = BatchResultResult("fail")
)
func (e BatchResultResult) Values() []BatchResultResult {
return []BatchResultResult{
BatchResultResultSuccess,
BatchResultResultFail,
}
}
func (e BatchResultResult) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["BatchResultResult"] = reflect.TypeOf((*BatchResultResult)(nil)).Elem()
}
type CannotEnableVmcpForClusterReason string
const (
// APD timeout has been disabled on one of the host
CannotEnableVmcpForClusterReasonAPDTimeoutDisabled = CannotEnableVmcpForClusterReason("APDTimeoutDisabled")
)
func (e CannotEnableVmcpForClusterReason) Values() []CannotEnableVmcpForClusterReason {
return []CannotEnableVmcpForClusterReason{
CannotEnableVmcpForClusterReasonAPDTimeoutDisabled,
}
}
func (e CannotEnableVmcpForClusterReason) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["CannotEnableVmcpForClusterReason"] = reflect.TypeOf((*CannotEnableVmcpForClusterReason)(nil)).Elem()
}
type CannotMoveFaultToleranceVmMoveType string
const (
// Move out of the resouce pool
CannotMoveFaultToleranceVmMoveTypeResourcePool = CannotMoveFaultToleranceVmMoveType("resourcePool")
// Move out of the cluster
CannotMoveFaultToleranceVmMoveTypeCluster = CannotMoveFaultToleranceVmMoveType("cluster")
)
func (e CannotMoveFaultToleranceVmMoveType) Values() []CannotMoveFaultToleranceVmMoveType {
return []CannotMoveFaultToleranceVmMoveType{
CannotMoveFaultToleranceVmMoveTypeResourcePool,
CannotMoveFaultToleranceVmMoveTypeCluster,
}
}
func (e CannotMoveFaultToleranceVmMoveType) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["CannotMoveFaultToleranceVmMoveType"] = reflect.TypeOf((*CannotMoveFaultToleranceVmMoveType)(nil)).Elem()
}
type CannotPowerOffVmInClusterOperation string
const (
// suspend
CannotPowerOffVmInClusterOperationSuspend = CannotPowerOffVmInClusterOperation("suspend")
// power off
CannotPowerOffVmInClusterOperationPowerOff = CannotPowerOffVmInClusterOperation("powerOff")
// guest shutdown
CannotPowerOffVmInClusterOperationGuestShutdown = CannotPowerOffVmInClusterOperation("guestShutdown")
// guest suspend
CannotPowerOffVmInClusterOperationGuestSuspend = CannotPowerOffVmInClusterOperation("guestSuspend")
)
func (e CannotPowerOffVmInClusterOperation) Values() []CannotPowerOffVmInClusterOperation {
return []CannotPowerOffVmInClusterOperation{
CannotPowerOffVmInClusterOperationSuspend,
CannotPowerOffVmInClusterOperationPowerOff,
CannotPowerOffVmInClusterOperationGuestShutdown,
CannotPowerOffVmInClusterOperationGuestSuspend,
}
}
func (e CannotPowerOffVmInClusterOperation) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["CannotPowerOffVmInClusterOperation"] = reflect.TypeOf((*CannotPowerOffVmInClusterOperation)(nil)).Elem()
}
type CannotUseNetworkReason string
const (
// Network does not support reservation
CannotUseNetworkReasonNetworkReservationNotSupported = CannotUseNetworkReason("NetworkReservationNotSupported")
// Source and destination networks do not have same security policies
CannotUseNetworkReasonMismatchedNetworkPolicies = CannotUseNetworkReason("MismatchedNetworkPolicies")
// Source and destination DVS do not have same version or vendor
CannotUseNetworkReasonMismatchedDvsVersionOrVendor = CannotUseNetworkReason("MismatchedDvsVersionOrVendor")
// VMotion to unsupported destination network type
CannotUseNetworkReasonVMotionToUnsupportedNetworkType = CannotUseNetworkReason("VMotionToUnsupportedNetworkType")
// The network is under maintenance
CannotUseNetworkReasonNetworkUnderMaintenance = CannotUseNetworkReason("NetworkUnderMaintenance")
// Source and destination networks do not have same ENS(Enhanced Network Stack) mode
CannotUseNetworkReasonMismatchedEnsMode = CannotUseNetworkReason("MismatchedEnsMode")
// Source and destination networks do not have the same real-time flag
CannotUseNetworkReasonMismatchedRealTimeDvs = CannotUseNetworkReason("MismatchedRealTimeDvs")
)
func (e CannotUseNetworkReason) Values() []CannotUseNetworkReason {
return []CannotUseNetworkReason{
CannotUseNetworkReasonNetworkReservationNotSupported,
CannotUseNetworkReasonMismatchedNetworkPolicies,
CannotUseNetworkReasonMismatchedDvsVersionOrVendor,
CannotUseNetworkReasonVMotionToUnsupportedNetworkType,
CannotUseNetworkReasonNetworkUnderMaintenance,
CannotUseNetworkReasonMismatchedEnsMode,
CannotUseNetworkReasonMismatchedRealTimeDvs,
}
}
func (e CannotUseNetworkReason) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["CannotUseNetworkReason"] = reflect.TypeOf((*CannotUseNetworkReason)(nil)).Elem()
minAPIVersionForEnumValue["CannotUseNetworkReason"] = map[string]string{
"MismatchedRealTimeDvs": "8.0.3.1",
}
}
// The types of tests which can requested by any of the methods in either
// `VirtualMachineCompatibilityChecker` or `VirtualMachineProvisioningChecker`.
type CheckTestType string
const (
// Tests that examine only the configuration
// of the virtual machine and its current host; the destination
// resource pool and host or cluster are irrelevant.
CheckTestTypeSourceTests = CheckTestType("sourceTests")
// Tests that examine both the virtual
// machine and the destination host or cluster; the destination
// resource pool is irrelevant.
//
// This set excludes tests that fall
// into the datastoreTests group.
CheckTestTypeHostTests = CheckTestType("hostTests")
// Tests that check that the destination resource
// pool can support the virtual machine if it is powered on.
//
// The
// destination host or cluster is relevant because it will affect the
// amount of overhead memory required to run the virtual machine.
CheckTestTypeResourcePoolTests = CheckTestType("resourcePoolTests")
// Tests that check that the
// destination host or cluster can see the datastores where the virtual
// machine's virtual disks are going to be located.
//
// The destination
// resource pool is irrelevant.
CheckTestTypeDatastoreTests = CheckTestType("datastoreTests")
// Tests that check that the
// destination host or cluster can see the networks that the virtual
// machine's virtual nic devices are going to be connected.
CheckTestTypeNetworkTests = CheckTestType("networkTests")
)
func (e CheckTestType) Values() []CheckTestType {
return []CheckTestType{
CheckTestTypeSourceTests,
CheckTestTypeHostTests,
CheckTestTypeResourcePoolTests,
CheckTestTypeDatastoreTests,
CheckTestTypeNetworkTests,
}
}
func (e CheckTestType) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["CheckTestType"] = reflect.TypeOf((*CheckTestType)(nil)).Elem()
}
// HCIWorkflowState identifies the state of the cluser from the perspective of HCI
// workflow.
//
// The workflow begins with in\_progress mode and can transition
// to 'done' or 'invalid', both of which are terminal states.
type ClusterComputeResourceHCIWorkflowState string
const (
// Indicates cluster is getting configured or will be configured.
ClusterComputeResourceHCIWorkflowStateIn_progress = ClusterComputeResourceHCIWorkflowState("in_progress")
// Indicates cluster configuration is complete.
ClusterComputeResourceHCIWorkflowStateDone = ClusterComputeResourceHCIWorkflowState("done")
// Indicates the workflow was abandoned on the cluster before the
// configuration could complete.
ClusterComputeResourceHCIWorkflowStateInvalid = ClusterComputeResourceHCIWorkflowState("invalid")
)
func (e ClusterComputeResourceHCIWorkflowState) Values() []ClusterComputeResourceHCIWorkflowState {
return []ClusterComputeResourceHCIWorkflowState{
ClusterComputeResourceHCIWorkflowStateIn_progress,
ClusterComputeResourceHCIWorkflowStateDone,
ClusterComputeResourceHCIWorkflowStateInvalid,
}
}
func (e ClusterComputeResourceHCIWorkflowState) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ClusterComputeResourceHCIWorkflowState"] = reflect.TypeOf((*ClusterComputeResourceHCIWorkflowState)(nil)).Elem()
}
type ClusterComputeResourceVcsHealthStatus string
const (
// Indicates vCS health status is normal.
ClusterComputeResourceVcsHealthStatusHealthy = ClusterComputeResourceVcsHealthStatus("healthy")
// Indicates only vCS is unhealthy.
ClusterComputeResourceVcsHealthStatusDegraded = ClusterComputeResourceVcsHealthStatus("degraded")
// Indicates vCS is unhealthy and other cluster services are impacted.
ClusterComputeResourceVcsHealthStatusNonhealthy = ClusterComputeResourceVcsHealthStatus("nonhealthy")
)
func (e ClusterComputeResourceVcsHealthStatus) Values() []ClusterComputeResourceVcsHealthStatus {
return []ClusterComputeResourceVcsHealthStatus{
ClusterComputeResourceVcsHealthStatusHealthy,
ClusterComputeResourceVcsHealthStatusDegraded,
ClusterComputeResourceVcsHealthStatusNonhealthy,
}
}
func (e ClusterComputeResourceVcsHealthStatus) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ClusterComputeResourceVcsHealthStatus"] = reflect.TypeOf((*ClusterComputeResourceVcsHealthStatus)(nil)).Elem()
minAPIVersionForType["ClusterComputeResourceVcsHealthStatus"] = "7.0.1.1"
}
type ClusterCryptoConfigInfoCryptoMode string
const (
// Put each host into the crypto safe state automatically when needed.
ClusterCryptoConfigInfoCryptoModeOnDemand = ClusterCryptoConfigInfoCryptoMode("onDemand")
// Put each host into the crypto safe state immediately.
ClusterCryptoConfigInfoCryptoModeForceEnable = ClusterCryptoConfigInfoCryptoMode("forceEnable")
)
func (e ClusterCryptoConfigInfoCryptoMode) Values() []ClusterCryptoConfigInfoCryptoMode {
return []ClusterCryptoConfigInfoCryptoMode{
ClusterCryptoConfigInfoCryptoModeOnDemand,
ClusterCryptoConfigInfoCryptoModeForceEnable,
}
}
func (e ClusterCryptoConfigInfoCryptoMode) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ClusterCryptoConfigInfoCryptoMode"] = reflect.TypeOf((*ClusterCryptoConfigInfoCryptoMode)(nil)).Elem()
}
// The `ClusterDasAamNodeStateDasState_enum` enumerated type defines
// values for host HA configuration and runtime state properties
// (`ClusterDasAamNodeState.configState` and
// `ClusterDasAamNodeState.runtimeState`).
type ClusterDasAamNodeStateDasState string
const (
// HA has never been enabled on the the host.
ClusterDasAamNodeStateDasStateUninitialized = ClusterDasAamNodeStateDasState("uninitialized")
// HA agents have been installed but are not running on the the host.
ClusterDasAamNodeStateDasStateInitialized = ClusterDasAamNodeStateDasState("initialized")
// HA configuration is in progress.
ClusterDasAamNodeStateDasStateConfiguring = ClusterDasAamNodeStateDasState("configuring")
// HA configuration is being removed.
ClusterDasAamNodeStateDasStateUnconfiguring = ClusterDasAamNodeStateDasState("unconfiguring")
// HA agent is running on this host.
ClusterDasAamNodeStateDasStateRunning = ClusterDasAamNodeStateDasState("running")
// There is an error condition.
//
// This can represent a configuration
// error or a host agent runtime error.
ClusterDasAamNodeStateDasStateError = ClusterDasAamNodeStateDasState("error")
// The HA agent has been shut down.
ClusterDasAamNodeStateDasStateAgentShutdown = ClusterDasAamNodeStateDasState("agentShutdown")
// The host is not reachable.
//
// This can represent a host failure
// or an isolated host.
ClusterDasAamNodeStateDasStateNodeFailed = ClusterDasAamNodeStateDasState("nodeFailed")
)
func (e ClusterDasAamNodeStateDasState) Values() []ClusterDasAamNodeStateDasState {
return []ClusterDasAamNodeStateDasState{
ClusterDasAamNodeStateDasStateUninitialized,
ClusterDasAamNodeStateDasStateInitialized,
ClusterDasAamNodeStateDasStateConfiguring,
ClusterDasAamNodeStateDasStateUnconfiguring,
ClusterDasAamNodeStateDasStateRunning,
ClusterDasAamNodeStateDasStateError,
ClusterDasAamNodeStateDasStateAgentShutdown,
ClusterDasAamNodeStateDasStateNodeFailed,
}
}
func (e ClusterDasAamNodeStateDasState) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ClusterDasAamNodeStateDasState"] = reflect.TypeOf((*ClusterDasAamNodeStateDasState)(nil)).Elem()
}
// The policy to determine the candidates from which vCenter Server can
// choose heartbeat datastores.
type ClusterDasConfigInfoHBDatastoreCandidate string
const (
// vCenter Server chooses heartbeat datastores from the set specified
// by the user (see `ClusterDasConfigInfo.heartbeatDatastore`).
//
// More specifically,
// datastores not included in the set will not be chosen. Note that if
// `ClusterDasConfigInfo.heartbeatDatastore` is empty, datastore heartbeating will
// be disabled for HA.
ClusterDasConfigInfoHBDatastoreCandidateUserSelectedDs = ClusterDasConfigInfoHBDatastoreCandidate("userSelectedDs")
// vCenter Server chooses heartbeat datastores from all the feasible ones,
// i.e., the datastores that are accessible to more than one host in
// the cluster.
//
// The choice will be made without giving preference to those
// specified by the user (see `ClusterDasConfigInfo.heartbeatDatastore`).
ClusterDasConfigInfoHBDatastoreCandidateAllFeasibleDs = ClusterDasConfigInfoHBDatastoreCandidate("allFeasibleDs")
// vCenter Server chooses heartbeat datastores from all the feasible ones
// while giving preference to those specified by the user (see `ClusterDasConfigInfo.heartbeatDatastore`).
//
// More specifically, the datastores not included in `ClusterDasConfigInfo.heartbeatDatastore` will be
// chosen if and only if the specified ones are not sufficient.
ClusterDasConfigInfoHBDatastoreCandidateAllFeasibleDsWithUserPreference = ClusterDasConfigInfoHBDatastoreCandidate("allFeasibleDsWithUserPreference")
)
func (e ClusterDasConfigInfoHBDatastoreCandidate) Values() []ClusterDasConfigInfoHBDatastoreCandidate {
return []ClusterDasConfigInfoHBDatastoreCandidate{
ClusterDasConfigInfoHBDatastoreCandidateUserSelectedDs,
ClusterDasConfigInfoHBDatastoreCandidateAllFeasibleDs,
ClusterDasConfigInfoHBDatastoreCandidateAllFeasibleDsWithUserPreference,
}
}
func (e ClusterDasConfigInfoHBDatastoreCandidate) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
t["ClusterDasConfigInfoHBDatastoreCandidate"] = reflect.TypeOf((*ClusterDasConfigInfoHBDatastoreCandidate)(nil)).Elem()
}
// Possible states of an HA service.
//
// All services support the
// disabled and enabled states.
type ClusterDasConfigInfoServiceState string
const (
// HA service is disabled.
ClusterDasConfigInfoServiceStateDisabled = ClusterDasConfigInfoServiceState("disabled")
// HA service is enabled.
ClusterDasConfigInfoServiceStateEnabled = ClusterDasConfigInfoServiceState("enabled")
)
func (e ClusterDasConfigInfoServiceState) Values() []ClusterDasConfigInfoServiceState {
return []ClusterDasConfigInfoServiceState{
ClusterDasConfigInfoServiceStateDisabled,
ClusterDasConfigInfoServiceStateEnabled,
}
}
func (e ClusterDasConfigInfoServiceState) Strings() []string {
return EnumValuesAsStrings(e.Values())
}
func init() {
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/fault.go | vendor/github.com/vmware/govmomi/vim25/types/fault.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
type HasFault interface {
Fault() BaseMethodFault
}
func IsFileNotFound(err error) bool {
if f, ok := err.(HasFault); ok {
switch f.Fault().(type) {
case *FileNotFound:
return true
}
}
return false
}
func IsAlreadyExists(err error) bool {
if f, ok := err.(HasFault); ok {
switch f.Fault().(type) {
case *AlreadyExists:
return true
}
}
return false
}
// HasLocalizedMethodFault is any type that has a LocalizedMethodFault.
type HasLocalizedMethodFault interface {
// GetLocalizedMethodFault returns the LocalizedMethodFault instance.
GetLocalizedMethodFault() *LocalizedMethodFault
}
// GetLocalizedMethodFault returns this LocalizedMethodFault.
func (f *LocalizedMethodFault) GetLocalizedMethodFault() *LocalizedMethodFault {
return f
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/helpers.go | vendor/github.com/vmware/govmomi/vim25/types/helpers.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"reflect"
"strings"
"time"
)
func EnumValuesAsStrings[T ~string](enumValues []T) []string {
stringValues := make([]string, len(enumValues))
for i := range enumValues {
stringValues[i] = string(enumValues[i])
}
return stringValues
}
func New[T any](t T) *T {
return &t
}
func NewBool(v bool) *bool {
return &v
}
func NewInt32(v int32) *int32 {
return &v
}
func NewInt64(v int64) *int64 {
return &v
}
func NewTime(v time.Time) *time.Time {
return &v
}
func NewReference(r ManagedObjectReference) *ManagedObjectReference {
return &r
}
func (r ManagedObjectReference) Reference() ManagedObjectReference {
return r
}
func (r ManagedObjectReference) String() string {
return strings.Join([]string{r.Type, r.Value}, ":")
}
func (r *ManagedObjectReference) FromString(o string) bool {
s := strings.SplitN(o, ":", 2)
if len(s) != 2 {
return false
}
r.Type = s[0]
r.Value = s[1]
return true
}
// Encode ManagedObjectReference for use with URL and File paths
func (r ManagedObjectReference) Encode() string {
return strings.Join([]string{r.Type, url.QueryEscape(r.Value)}, "-")
}
func (c *PerfCounterInfo) Name() string {
return c.GroupInfo.GetElementDescription().Key + "." + c.NameInfo.GetElementDescription().Key + "." + string(c.RollupType)
}
func defaultResourceAllocationInfo() ResourceAllocationInfo {
return ResourceAllocationInfo{
Reservation: NewInt64(0),
ExpandableReservation: NewBool(true),
Limit: NewInt64(-1),
Shares: &SharesInfo{
Level: SharesLevelNormal,
},
}
}
// DefaultResourceConfigSpec returns a ResourceConfigSpec populated with the same default field values as vCenter.
// Note that the wsdl marks these fields as optional, but they are required to be set when creating a resource pool.
// They are only optional when updating a resource pool.
func DefaultResourceConfigSpec() ResourceConfigSpec {
return ResourceConfigSpec{
CpuAllocation: defaultResourceAllocationInfo(),
MemoryAllocation: defaultResourceAllocationInfo(),
}
}
// ToConfigSpec returns a VirtualMachineConfigSpec based on the
// VirtualMachineConfigInfo.
func (ci VirtualMachineConfigInfo) ToConfigSpec() VirtualMachineConfigSpec {
cs := VirtualMachineConfigSpec{
ChangeVersion: ci.ChangeVersion,
Name: ci.Name,
Version: ci.Version,
CreateDate: ci.CreateDate,
Uuid: ci.Uuid,
InstanceUuid: ci.InstanceUuid,
NpivNodeWorldWideName: ci.NpivNodeWorldWideName,
NpivPortWorldWideName: ci.NpivPortWorldWideName,
NpivWorldWideNameType: ci.NpivWorldWideNameType,
NpivDesiredNodeWwns: ci.NpivDesiredNodeWwns,
NpivDesiredPortWwns: ci.NpivDesiredPortWwns,
NpivTemporaryDisabled: ci.NpivTemporaryDisabled,
NpivOnNonRdmDisks: ci.NpivOnNonRdmDisks,
LocationId: ci.LocationId,
GuestId: ci.GuestId,
AlternateGuestName: ci.AlternateGuestName,
Annotation: ci.Annotation,
Files: &ci.Files,
Tools: ci.Tools,
Flags: &ci.Flags,
ConsolePreferences: ci.ConsolePreferences,
PowerOpInfo: &ci.DefaultPowerOps,
RebootPowerOff: ci.RebootPowerOff,
NumCPUs: ci.Hardware.NumCPU,
VcpuConfig: ci.VcpuConfig,
NumCoresPerSocket: ci.Hardware.NumCoresPerSocket,
MemoryMB: int64(ci.Hardware.MemoryMB),
MemoryHotAddEnabled: ci.MemoryHotAddEnabled,
CpuHotAddEnabled: ci.CpuHotAddEnabled,
CpuHotRemoveEnabled: ci.CpuHotRemoveEnabled,
VirtualICH7MPresent: ci.Hardware.VirtualICH7MPresent,
VirtualSMCPresent: ci.Hardware.VirtualSMCPresent,
DeviceChange: nil, // See below
CpuAllocation: ci.CpuAllocation,
MemoryAllocation: ci.MemoryAllocation,
LatencySensitivity: ci.LatencySensitivity,
CpuAffinity: ci.CpuAffinity,
MemoryAffinity: ci.MemoryAffinity,
NetworkShaper: ci.NetworkShaper,
CpuFeatureMask: nil, // See below
ExtraConfig: ci.ExtraConfig,
SwapPlacement: ci.SwapPlacement,
BootOptions: ci.BootOptions,
FtInfo: ci.FtInfo,
RepConfig: ci.RepConfig,
VAssertsEnabled: ci.VAssertsEnabled,
ChangeTrackingEnabled: ci.ChangeTrackingEnabled,
Firmware: ci.Firmware,
MaxMksConnections: ci.MaxMksConnections,
GuestAutoLockEnabled: ci.GuestAutoLockEnabled,
ManagedBy: ci.ManagedBy,
MemoryReservationLockedToMax: ci.MemoryReservationLockedToMax,
NestedHVEnabled: ci.NestedHVEnabled,
VPMCEnabled: ci.VPMCEnabled,
MessageBusTunnelEnabled: ci.MessageBusTunnelEnabled,
MigrateEncryption: ci.MigrateEncryption,
FtEncryptionMode: ci.FtEncryptionMode,
SevEnabled: ci.SevEnabled,
MotherboardLayout: ci.Hardware.MotherboardLayout,
ScheduledHardwareUpgradeInfo: ci.ScheduledHardwareUpgradeInfo,
SgxInfo: ci.SgxInfo,
GuestMonitoringModeInfo: ci.GuestMonitoringModeInfo,
PmemFailoverEnabled: ci.PmemFailoverEnabled,
VmxStatsCollectionEnabled: ci.VmxStatsCollectionEnabled,
VmOpNotificationToAppEnabled: ci.VmOpNotificationToAppEnabled,
VmOpNotificationTimeout: ci.VmOpNotificationTimeout,
DeviceSwap: ci.DeviceSwap,
SimultaneousThreads: ci.Hardware.SimultaneousThreads,
Pmem: ci.Pmem,
DeviceGroups: ci.DeviceGroups,
FixedPassthruHotPlugEnabled: ci.FixedPassthruHotPlugEnabled,
MetroFtEnabled: ci.MetroFtEnabled,
MetroFtHostGroup: ci.MetroFtHostGroup,
}
// Unassign the Files field if all of its fields are empty.
if ci.Files.FtMetadataDirectory == "" && ci.Files.LogDirectory == "" &&
ci.Files.SnapshotDirectory == "" && ci.Files.SuspendDirectory == "" &&
ci.Files.VmPathName == "" {
cs.Files = nil
}
// Unassign the Flags field if all of its fields are empty.
if ci.Flags.CbrcCacheEnabled == nil &&
ci.Flags.DisableAcceleration == nil &&
ci.Flags.DiskUuidEnabled == nil &&
ci.Flags.EnableLogging == nil &&
ci.Flags.FaultToleranceType == "" &&
ci.Flags.HtSharing == "" &&
ci.Flags.MonitorType == "" &&
ci.Flags.RecordReplayEnabled == nil &&
ci.Flags.RunWithDebugInfo == nil &&
ci.Flags.SnapshotDisabled == nil &&
ci.Flags.SnapshotLocked == nil &&
ci.Flags.SnapshotPowerOffBehavior == "" &&
ci.Flags.UseToe == nil &&
ci.Flags.VbsEnabled == nil &&
ci.Flags.VirtualExecUsage == "" &&
ci.Flags.VirtualMmuUsage == "" &&
ci.Flags.VvtdEnabled == nil {
cs.Flags = nil
}
// Unassign the PowerOps field if all of its fields are empty.
if ci.DefaultPowerOps.DefaultPowerOffType == "" &&
ci.DefaultPowerOps.DefaultResetType == "" &&
ci.DefaultPowerOps.DefaultSuspendType == "" &&
ci.DefaultPowerOps.PowerOffType == "" &&
ci.DefaultPowerOps.ResetType == "" &&
ci.DefaultPowerOps.StandbyAction == "" &&
ci.DefaultPowerOps.SuspendType == "" {
cs.PowerOpInfo = nil
}
if l := len(ci.CpuFeatureMask); l > 0 {
cs.CpuFeatureMask = make([]VirtualMachineCpuIdInfoSpec, l)
for i := 0; i < l; i++ {
cs.CpuFeatureMask[i] = VirtualMachineCpuIdInfoSpec{
ArrayUpdateSpec: ArrayUpdateSpec{
Operation: ArrayUpdateOperationAdd,
},
Info: &HostCpuIdInfo{
Level: ci.CpuFeatureMask[i].Level,
Vendor: ci.CpuFeatureMask[i].Vendor,
Eax: ci.CpuFeatureMask[i].Eax,
Ebx: ci.CpuFeatureMask[i].Ebx,
Ecx: ci.CpuFeatureMask[i].Ecx,
Edx: ci.CpuFeatureMask[i].Edx,
},
}
}
}
if l := len(ci.Hardware.Device); l > 0 {
cs.DeviceChange = make([]BaseVirtualDeviceConfigSpec, l)
for i := 0; i < l; i++ {
cs.DeviceChange[i] = &VirtualDeviceConfigSpec{
Operation: VirtualDeviceConfigSpecOperationAdd,
FileOperation: VirtualDeviceConfigSpecFileOperationCreate,
Device: ci.Hardware.Device[i],
Profile: nil,
Backing: nil,
FilterSpec: nil,
}
}
}
if ni := ci.NumaInfo; ni != nil {
cs.VirtualNuma = &VirtualMachineVirtualNuma{
CoresPerNumaNode: ni.CoresPerNumaNode,
ExposeVnumaOnCpuHotadd: ni.VnumaOnCpuHotaddExposed,
}
}
if civa, ok := ci.VAppConfig.(*VmConfigInfo); ok {
var csva VmConfigSpec
csva.Eula = civa.Eula
csva.InstallBootRequired = &civa.InstallBootRequired
csva.InstallBootStopDelay = civa.InstallBootStopDelay
ipAssignment := civa.IpAssignment
csva.IpAssignment = &ipAssignment
csva.OvfEnvironmentTransport = civa.OvfEnvironmentTransport
for i := range civa.OvfSection {
s := civa.OvfSection[i]
csva.OvfSection = append(
csva.OvfSection,
VAppOvfSectionSpec{
ArrayUpdateSpec: ArrayUpdateSpec{
Operation: ArrayUpdateOperationAdd,
},
Info: &s,
},
)
}
for i := range civa.Product {
p := civa.Product[i]
csva.Product = append(
csva.Product,
VAppProductSpec{
ArrayUpdateSpec: ArrayUpdateSpec{
Operation: ArrayUpdateOperationAdd,
},
Info: &p,
},
)
}
for i := range civa.Property {
p := civa.Property[i]
csva.Property = append(
csva.Property,
VAppPropertySpec{
ArrayUpdateSpec: ArrayUpdateSpec{
Operation: ArrayUpdateOperationAdd,
},
Info: &p,
},
)
}
cs.VAppConfig = &csva
}
return cs
}
// ToString returns the string-ified version of the provided input value by
// first attempting to encode the value to JSON using the vimtype JSON encoder,
// and if that should fail, using the standard JSON encoder, and if that fails,
// returning the value formatted with Sprintf("%v").
//
// Please note, this function is not intended to replace marshaling the data
// to JSON using the normal workflows. This function is for when a string-ified
// version of the data is needed for things like logging.
func ToString(in AnyType) (s string) {
if in == nil {
return "null"
}
marshalWithSprintf := func() string {
return fmt.Sprintf("%v", in)
}
defer func() {
if err := recover(); err != nil {
s = marshalWithSprintf()
}
}()
rv := reflect.ValueOf(in)
switch rv.Kind() {
case reflect.Bool,
reflect.Complex64, reflect.Complex128,
reflect.Float32, reflect.Float64:
return fmt.Sprintf("%v", in)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Uintptr:
return fmt.Sprintf("%d", in)
case reflect.String:
return in.(string)
case reflect.Interface, reflect.Pointer:
if rv.IsZero() {
return "null"
}
return ToString(rv.Elem().Interface())
}
marshalWithStdlibJSONEncoder := func() string {
data, err := json.Marshal(in)
if err != nil {
return marshalWithSprintf()
}
return string(data)
}
defer func() {
if err := recover(); err != nil {
s = marshalWithStdlibJSONEncoder()
}
}()
var w bytes.Buffer
enc := NewJSONEncoder(&w)
if err := enc.Encode(in); err != nil {
return marshalWithStdlibJSONEncoder()
}
// Do not include the newline character added by the vimtype JSON encoder.
return strings.TrimSuffix(w.String(), "\n")
}
func init() {
// Known 6.5 issue where this event type is sent even though it is internal.
// This workaround allows us to unmarshal and avoid NPEs.
t["HostSubSpecificationUpdateEvent"] = reflect.TypeOf((*HostEvent)(nil)).Elem()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/types/hardware_version.go | vendor/github.com/vmware/govmomi/vim25/types/hardware_version.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"fmt"
"regexp"
"strconv"
)
// HardwareVersion is a VMX hardware version.
type HardwareVersion uint8
const (
invalidHardwareVersion HardwareVersion = 0
)
const (
VMX3 HardwareVersion = iota + 3
VMX4
vmx5 // invalid
VMX6
VMX7
VMX8
VMX9
VMX10
VMX11
VMX12
VMX13
VMX14
VMX15
VMX16
VMX17
VMX18
VMX19
VMX20
VMX21
)
const (
// MinValidHardwareVersion is the minimum, valid hardware version supported
// by VMware hypervisors in the wild.
MinValidHardwareVersion = VMX3
// MaxValidHardwareVersion is the maximum, valid hardware version supported
// by VMware hypervisors in the wild.
MaxValidHardwareVersion = VMX21
)
// IsSupported returns true if the hardware version is known to and supported by
// GoVmomi's generated types.
func (hv HardwareVersion) IsSupported() bool {
return hv.IsValid() &&
hv != vmx5 &&
hv >= MinValidHardwareVersion &&
hv <= MaxValidHardwareVersion
}
// IsValid returns true if the hardware version is not valid.
// Unlike IsSupported, this function returns true as long as the hardware
// version is greater than 0.
// For example, the result of parsing "abc" or "vmx-abc" is an invalid hardware
// version, whereas the result of parsing "vmx-99" is valid, just not supported.
func (hv HardwareVersion) IsValid() bool {
return hv != invalidHardwareVersion
}
func (hv HardwareVersion) String() string {
if hv.IsValid() {
return fmt.Sprintf("vmx-%d", hv)
}
return ""
}
func (hv HardwareVersion) MarshalText() ([]byte, error) {
return []byte(hv.String()), nil
}
func (hv *HardwareVersion) UnmarshalText(text []byte) error {
v, err := ParseHardwareVersion(string(text))
if err != nil {
return err
}
*hv = v
return nil
}
var (
vmxRe = regexp.MustCompile(`(?i)^vmx-(\d+)$`)
vmxNumOnlyRe = regexp.MustCompile(`^(\d+)$`)
)
// MustParseHardwareVersion parses the provided string into a hardware version.
func MustParseHardwareVersion(s string) HardwareVersion {
v, err := ParseHardwareVersion(s)
if err != nil {
panic(err)
}
return v
}
// ParseHardwareVersion parses the provided string into a hardware version.
// Supported formats include vmx-123 or 123. Please note that the parser will
// only return an error if the supplied version does not match the supported
// formats.
// Once parsed, use the function IsSupported to determine if the hardware
// version falls into the range of versions known to GoVmomi.
func ParseHardwareVersion(s string) (HardwareVersion, error) {
if m := vmxRe.FindStringSubmatch(s); len(m) > 0 {
u, err := strconv.ParseUint(m[1], 10, 8)
if err != nil {
return invalidHardwareVersion, fmt.Errorf(
"failed to parse %s from %q as uint8: %w", m[1], s, err)
}
return HardwareVersion(u), nil
} else if m := vmxNumOnlyRe.FindStringSubmatch(s); len(m) > 0 {
u, err := strconv.ParseUint(m[1], 10, 8)
if err != nil {
return invalidHardwareVersion, fmt.Errorf(
"failed to parse %s as uint8: %w", m[1], err)
}
return HardwareVersion(u), nil
}
return invalidHardwareVersion, fmt.Errorf("invalid version: %q", s)
}
var hardwareVersions []HardwareVersion
func init() {
for i := MinValidHardwareVersion; i <= MaxValidHardwareVersion; i++ {
if i.IsSupported() {
hardwareVersions = append(hardwareVersions, i)
}
}
}
// GetHardwareVersions returns a list of hardware versions.
func GetHardwareVersions() []HardwareVersion {
dst := make([]HardwareVersion, len(hardwareVersions))
copy(dst, hardwareVersions)
return dst
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/debug/file.go | vendor/github.com/vmware/govmomi/vim25/debug/file.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package debug
import (
"io"
"os"
"path"
"sync"
)
// FileProvider implements a debugging provider that creates a real file for
// every call to NewFile. It maintains a list of all files that it creates,
// such that it can close them when its Flush function is called.
type FileProvider struct {
Path string
mu sync.Mutex
files []*os.File
}
func (fp *FileProvider) NewFile(p string) io.WriteCloser {
f, err := os.Create(path.Join(fp.Path, p))
if err != nil {
panic(err)
}
fp.mu.Lock()
defer fp.mu.Unlock()
fp.files = append(fp.files, f)
return NewFileWriterCloser(f, p)
}
func (fp *FileProvider) Flush() {
fp.mu.Lock()
defer fp.mu.Unlock()
for _, f := range fp.files {
f.Close()
}
}
type FileWriterCloser struct {
f *os.File
p string
}
func NewFileWriterCloser(f *os.File, p string) *FileWriterCloser {
return &FileWriterCloser{
f,
p,
}
}
func (fwc *FileWriterCloser) Write(p []byte) (n int, err error) {
return fwc.f.Write(Scrub(p))
}
func (fwc *FileWriterCloser) Close() error {
return fwc.f.Close()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/debug/log.go | vendor/github.com/vmware/govmomi/vim25/debug/log.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package debug
import (
"fmt"
"io"
"os"
)
type LogWriterCloser struct {
}
func NewLogWriterCloser() *LogWriterCloser {
return &LogWriterCloser{}
}
func (lwc *LogWriterCloser) Write(p []byte) (n int, err error) {
fmt.Fprint(os.Stderr, string(Scrub(p)))
return len(p), nil
}
func (lwc *LogWriterCloser) Close() error {
return nil
}
type LogProvider struct {
}
func (s *LogProvider) NewFile(p string) io.WriteCloser {
return NewLogWriterCloser()
}
func (s *LogProvider) Flush() {
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vim25/debug/debug.go | vendor/github.com/vmware/govmomi/vim25/debug/debug.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package debug
import (
"io"
"regexp"
)
// Provider specified the interface types must implement to be used as a
// debugging sink. Having multiple such sink implementations allows it to be
// changed externally (for example when running tests).
type Provider interface {
NewFile(s string) io.WriteCloser
Flush()
}
// ReadCloser is a struct that satisfies the io.ReadCloser interface
type ReadCloser struct {
io.Reader
io.Closer
}
// NewTeeReader wraps io.TeeReader and patches through the Close() function.
func NewTeeReader(rc io.ReadCloser, w io.Writer) io.ReadCloser {
return ReadCloser{
Reader: io.TeeReader(rc, w),
Closer: rc,
}
}
var currentProvider Provider = nil
var scrubPassword = regexp.MustCompile(`<password>(.*)</password>`)
func SetProvider(p Provider) {
if currentProvider != nil {
currentProvider.Flush()
}
currentProvider = p
}
// Enabled returns whether debugging is enabled or not.
func Enabled() bool {
return currentProvider != nil
}
// NewFile dispatches to the current provider's NewFile function.
func NewFile(s string) io.WriteCloser {
return currentProvider.NewFile(s)
}
// Flush dispatches to the current provider's Flush function.
func Flush() {
currentProvider.Flush()
}
func Scrub(in []byte) []byte {
return scrubPassword.ReplaceAll(in, []byte(`<password>********</password>`))
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vapi/internal/internal.go | vendor/github.com/vmware/govmomi/vapi/internal/internal.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package internal
import (
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
// VAPI REST Paths
const (
SessionPath = "/com/vmware/cis/session"
CategoryPath = "/com/vmware/cis/tagging/category"
TagPath = "/com/vmware/cis/tagging/tag"
AssociationPath = "/com/vmware/cis/tagging/tag-association"
LibraryPath = "/com/vmware/content/library"
LibraryItemFileData = "/com/vmware/cis/data"
LibraryItemPath = "/com/vmware/content/library/item"
LibraryItemFilePath = "/com/vmware/content/library/item/file"
LibraryItemStoragePath = "/com/vmware/content/library/item/storage"
LibraryItemUpdateSession = "/com/vmware/content/library/item/update-session"
LibraryItemUpdateSessionFile = "/com/vmware/content/library/item/updatesession/file"
LibraryItemDownloadSession = "/com/vmware/content/library/item/download-session"
LibraryItemDownloadSessionFile = "/com/vmware/content/library/item/downloadsession/file"
LocalLibraryPath = "/com/vmware/content/local-library"
SubscribedLibraryPath = "/com/vmware/content/subscribed-library"
SecurityPoliciesPath = "/api/content/security-policies"
SubscribedLibraryItem = "/com/vmware/content/library/subscribed-item"
Subscriptions = "/com/vmware/content/library/subscriptions"
TrustedCertificatesPath = "/api/content/trusted-certificates"
VCenterOVFLibraryItem = "/com/vmware/vcenter/ovf/library-item"
VCenterVMTXLibraryItem = "/vcenter/vm-template/library-items"
SessionCookieName = "vmware-api-session-id"
UseHeaderAuthn = "vmware-use-header-authn"
DebugEcho = "/vc-sim/debug/echo"
)
// AssociatedObject is the same structure as types.ManagedObjectReference,
// just with a different field name (ID instead of Value).
// In the API we use mo.Reference, this type is only used for wire transfer.
type AssociatedObject struct {
Type string `json:"type"`
Value string `json:"id"`
}
// Reference implements mo.Reference
func (o AssociatedObject) Reference() types.ManagedObjectReference {
return types.ManagedObjectReference{
Type: o.Type,
Value: o.Value,
}
}
// Association for tag-association requests.
type Association struct {
ObjectID *AssociatedObject `json:"object_id,omitempty"`
}
// NewAssociation returns an Association, converting ref to an AssociatedObject.
func NewAssociation(ref mo.Reference) Association {
return Association{
ObjectID: &AssociatedObject{
Type: ref.Reference().Type,
Value: ref.Reference().Value,
},
}
}
type SubscriptionDestination struct {
ID string `json:"subscription"`
}
type SubscriptionDestinationSpec struct {
Subscriptions []SubscriptionDestination `json:"subscriptions,omitempty"`
}
type SubscriptionItemDestinationSpec struct {
Force bool `json:"force_sync_content"`
Subscriptions []SubscriptionDestination `json:"subscriptions,omitempty"`
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vapi/rest/client.go | vendor/github.com/vmware/govmomi/vapi/rest/client.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package rest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/vmware/govmomi/vapi/internal"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// Client extends soap.Client to support JSON encoding, while inheriting security features, debug tracing and session persistence.
type Client struct {
mu sync.Mutex
*soap.Client
sessionID string
}
// Session information
type Session struct {
User string `json:"user"`
Created time.Time `json:"created_time"`
LastAccessed time.Time `json:"last_accessed_time"`
}
// LocalizableMessage represents a localizable error
type LocalizableMessage struct {
Args []string `json:"args,omitempty"`
DefaultMessage string `json:"default_message,omitempty"`
ID string `json:"id,omitempty"`
}
func (m *LocalizableMessage) Error() string {
return m.DefaultMessage
}
// NewClient creates a new Client instance.
func NewClient(c *vim25.Client) *Client {
sc := c.Client.NewServiceClient(Path, "")
return &Client{Client: sc}
}
// SessionID is set by calling Login() or optionally with the given id param
func (c *Client) SessionID(id ...string) string {
c.mu.Lock()
defer c.mu.Unlock()
if len(id) != 0 {
c.sessionID = id[0]
}
return c.sessionID
}
type marshaledClient struct {
SoapClient *soap.Client
SessionID string
}
func (c *Client) MarshalJSON() ([]byte, error) {
m := marshaledClient{
SoapClient: c.Client,
SessionID: c.sessionID,
}
return json.Marshal(m)
}
func (c *Client) UnmarshalJSON(b []byte) error {
var m marshaledClient
err := json.Unmarshal(b, &m)
if err != nil {
return err
}
*c = Client{
Client: m.SoapClient,
sessionID: m.SessionID,
}
return nil
}
// isAPI returns true if path starts with "/api"
// This hack allows helpers to support both endpoints:
// "/rest" - value wrapped responses and structured error responses
// "/api" - raw responses and no structured error responses
func isAPI(path string) bool {
return strings.HasPrefix(path, "/api")
}
// Resource helper for the given path.
func (c *Client) Resource(path string) *Resource {
r := &Resource{u: c.URL()}
if !isAPI(path) {
path = Path + path
}
r.u.Path = path
return r
}
type Signer interface {
SignRequest(*http.Request) error
}
type signerContext struct{}
func (c *Client) WithSigner(ctx context.Context, s Signer) context.Context {
return context.WithValue(ctx, signerContext{}, s)
}
type headersContext struct{}
// WithHeader returns a new Context populated with the provided headers map.
// Calls to a VAPI REST client with this context will populate the HTTP headers
// map using the provided headers.
func (c *Client) WithHeader(
ctx context.Context,
headers http.Header) context.Context {
return context.WithValue(ctx, headersContext{}, headers)
}
type statusError struct {
res *http.Response
}
func (e *statusError) Error() string {
return fmt.Sprintf("%s %s: %s", e.res.Request.Method, e.res.Request.URL, e.res.Status)
}
func IsStatusError(err error, code int) bool {
statusErr, ok := err.(*statusError)
if !ok || statusErr == nil || statusErr.res == nil {
return false
}
return statusErr.res.StatusCode == code
}
// RawResponse may be used with the Do method as the resBody argument in order
// to capture the raw response data.
type RawResponse struct {
bytes.Buffer
}
// Do sends the http.Request, decoding resBody if provided.
func (c *Client) Do(ctx context.Context, req *http.Request, resBody any) error {
switch req.Method {
case http.MethodPost, http.MethodPatch, http.MethodPut:
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
if id := c.SessionID(); id != "" {
req.Header.Set(internal.SessionCookieName, id)
}
if s, ok := ctx.Value(signerContext{}).(Signer); ok {
if err := s.SignRequest(req); err != nil {
return err
}
}
// OperationID (see soap.Client.soapRoundTrip)
if id, ok := ctx.Value(types.ID{}).(string); ok {
req.Header.Add("X-Request-ID", id)
}
if headers, ok := ctx.Value(headersContext{}).(http.Header); ok {
for k, v := range headers {
for _, v := range v {
req.Header.Add(k, v)
}
}
}
return c.Client.Do(ctx, req, func(res *http.Response) error {
switch res.StatusCode {
case http.StatusOK:
case http.StatusCreated:
case http.StatusAccepted:
case http.StatusNoContent:
case http.StatusBadRequest:
// TODO: structured error types
detail, err := io.ReadAll(res.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", res.Status, bytes.TrimSpace(detail))
default:
return &statusError{res}
}
if resBody == nil {
return nil
}
switch b := resBody.(type) {
case *RawResponse:
return res.Write(b)
case io.Writer:
_, err := io.Copy(b, res.Body)
return err
default:
d := json.NewDecoder(res.Body)
if isAPI(req.URL.Path) {
// Responses from the /api endpoint are not wrapped
return d.Decode(resBody)
}
// Responses from the /rest endpoint are wrapped in this structure
val := struct {
Value any `json:"value,omitempty"`
}{
resBody,
}
return d.Decode(&val)
}
})
}
// authHeaders ensures the given map contains a REST auth header
func (c *Client) authHeaders(h map[string]string) map[string]string {
if _, exists := h[internal.SessionCookieName]; exists {
return h
}
if h == nil {
h = make(map[string]string)
}
h[internal.SessionCookieName] = c.SessionID()
return h
}
// Download wraps soap.Client.Download, adding the REST authentication header
func (c *Client) Download(ctx context.Context, u *url.URL, param *soap.Download) (io.ReadCloser, int64, error) {
p := *param
p.Headers = c.authHeaders(p.Headers)
return c.Client.Download(ctx, u, &p)
}
// DownloadFile wraps soap.Client.DownloadFile, adding the REST authentication header
func (c *Client) DownloadFile(ctx context.Context, file string, u *url.URL, param *soap.Download) error {
p := *param
p.Headers = c.authHeaders(p.Headers)
return c.Client.DownloadFile(ctx, file, u, &p)
}
// DownloadAttachment writes the response to given filename, defaulting to Content-Disposition filename in the response.
// A filename of "-" writes the response to stdout.
func (c *Client) DownloadAttachment(ctx context.Context, req *http.Request, filename string) error {
return c.Client.Do(ctx, req, func(res *http.Response) error {
if filename == "" {
d := res.Header.Get("Content-Disposition")
_, params, err := mime.ParseMediaType(d)
if err == nil {
filename = params["filename"]
}
}
var w io.Writer
if filename == "-" {
w = os.Stdout
} else {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
w = f
}
_, err := io.Copy(w, res.Body)
return err
})
}
// Upload wraps soap.Client.Upload, adding the REST authentication header
func (c *Client) Upload(ctx context.Context, f io.Reader, u *url.URL, param *soap.Upload) error {
p := *param
p.Headers = c.authHeaders(p.Headers)
return c.Client.Upload(ctx, f, u, &p)
}
// Login creates a new session via Basic Authentication with the given url.Userinfo.
func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {
req := c.Resource(internal.SessionPath).Request(http.MethodPost)
req.Header.Set(internal.UseHeaderAuthn, "true")
if user != nil {
if password, ok := user.Password(); ok {
req.SetBasicAuth(user.Username(), password)
}
}
var id string
err := c.Do(ctx, req, &id)
if err != nil {
return err
}
c.SessionID(id)
return nil
}
func (c *Client) LoginByToken(ctx context.Context) error {
return c.Login(ctx, nil)
}
// Session returns the user's current session.
// Nil is returned if the session is not authenticated.
func (c *Client) Session(ctx context.Context) (*Session, error) {
var s Session
req := c.Resource(internal.SessionPath).WithAction("get").Request(http.MethodPost)
err := c.Do(ctx, req, &s)
if err != nil {
if e, ok := err.(*statusError); ok {
if e.res.StatusCode == http.StatusUnauthorized {
return nil, nil
}
}
return nil, err
}
return &s, nil
}
// Logout deletes the current session.
func (c *Client) Logout(ctx context.Context) error {
req := c.Resource(internal.SessionPath).Request(http.MethodDelete)
return c.Do(ctx, req, nil)
}
// Valid returns whether or not the client is valid and ready for use.
// This should be called after unmarshalling the client.
func (c *Client) Valid() bool {
if c == nil {
return false
}
if c.Client == nil {
return false
}
return true
}
// Path returns rest.Path (see cache.Client)
func (c *Client) Path() string {
return Path
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/vapi/rest/resource.go | vendor/github.com/vmware/govmomi/vapi/rest/resource.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package rest
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
)
const (
Path = "/rest"
)
// Resource wraps url.URL with helpers
type Resource struct {
u *url.URL
}
func (r *Resource) String() string {
return r.u.String()
}
// WithSubpath appends the provided subpath to the URL.Path
func (r *Resource) WithSubpath(subpath string) *Resource {
r.u.Path += "/" + subpath
return r
}
// WithID appends id to the URL.Path
func (r *Resource) WithID(id string) *Resource {
r.u.Path += "/id:" + id
return r
}
// WithAction sets adds action to the URL.RawQuery
func (r *Resource) WithAction(action string) *Resource {
return r.WithParam("~action", action)
}
// WithParam adds one parameter on the URL.RawQuery
func (r *Resource) WithParam(name string, value string) *Resource {
// ParseQuery handles empty case, and we control access to query string so shouldn't encounter an error case
params, err := url.ParseQuery(r.u.RawQuery)
if err != nil {
panic(err)
}
params[name] = append(params[name], value)
r.u.RawQuery = params.Encode()
return r
}
// WithPathEncodedParam appends a parameter on the URL.RawQuery,
// For special cases where URL Path-style encoding is needed
func (r *Resource) WithPathEncodedParam(name string, value string) *Resource {
t := &url.URL{Path: value}
encodedValue := t.String()
t = &url.URL{Path: name}
encodedName := t.String()
// ParseQuery handles empty case, and we control access to query string so shouldn't encounter an error case
params, err := url.ParseQuery(r.u.RawQuery)
if err != nil {
panic(err)
}
// Values.Encode() doesn't escape exactly how we want, so we need to build the query string ourselves
if len(params) >= 1 {
r.u.RawQuery = r.u.RawQuery + "&" + encodedName + "=" + encodedValue
} else {
r.u.RawQuery = r.u.RawQuery + encodedName + "=" + encodedValue
}
return r
}
// Request returns a new http.Request for the given method.
// An optional body can be provided for POST and PATCH methods.
func (r *Resource) Request(method string, body ...any) *http.Request {
rdr := io.MultiReader() // empty body by default
if len(body) != 0 {
rdr = encode(body[0])
}
req, err := http.NewRequest(method, r.u.String(), rdr)
if err != nil {
panic(err)
}
return req
}
type errorReader struct {
e error
}
func (e errorReader) Read([]byte) (int, error) {
return -1, e.e
}
// encode body as JSON, deferring any errors until io.Reader is used.
func encode(body any) io.Reader {
var b bytes.Buffer
err := json.NewEncoder(&b).Encode(body)
if err != nil {
return errorReader{err}
}
return &b
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/nfc/lease.go | vendor/github.com/vmware/govmomi/nfc/lease.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package nfc
import (
"context"
"fmt"
"io"
"path"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/task"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type Lease struct {
types.ManagedObjectReference
c *vim25.Client
}
func NewLease(c *vim25.Client, ref types.ManagedObjectReference) *Lease {
return &Lease{ref, c}
}
// Abort wraps methods.Abort
func (l *Lease) Abort(ctx context.Context, fault *types.LocalizedMethodFault) error {
req := types.HttpNfcLeaseAbort{
This: l.Reference(),
Fault: fault,
}
_, err := methods.HttpNfcLeaseAbort(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
// Complete wraps methods.Complete
func (l *Lease) Complete(ctx context.Context) error {
req := types.HttpNfcLeaseComplete{
This: l.Reference(),
}
_, err := methods.HttpNfcLeaseComplete(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
// GetManifest wraps methods.GetManifest
func (l *Lease) GetManifest(ctx context.Context) ([]types.HttpNfcLeaseManifestEntry, error) {
req := types.HttpNfcLeaseGetManifest{
This: l.Reference(),
}
res, err := methods.HttpNfcLeaseGetManifest(ctx, l.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// Progress wraps methods.Progress
func (l *Lease) Progress(ctx context.Context, percent int32) error {
req := types.HttpNfcLeaseProgress{
This: l.Reference(),
Percent: percent,
}
_, err := methods.HttpNfcLeaseProgress(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
// Properties returns a mo.HttpNfcLease with the specified properties.
// If no properties are requested, all properties are returned.
func (l *Lease) Properties(
ctx context.Context,
props ...string) (mo.HttpNfcLease, error) {
if len(props) == 0 {
props = []string{
"initializeProgress",
"transferProgress",
"mode",
"capabilities",
"info",
"state",
"error",
}
}
var o mo.HttpNfcLease
pc := property.DefaultCollector(l.c)
return o, pc.RetrieveOne(ctx, l.Reference(), props, &o)
}
type LeaseInfo struct {
types.HttpNfcLeaseInfo
Items []FileItem
}
func (l *Lease) newLeaseInfo(li *types.HttpNfcLeaseInfo, items []types.OvfFileItem) (*LeaseInfo, error) {
info := &LeaseInfo{
HttpNfcLeaseInfo: *li,
}
for _, device := range li.DeviceUrl {
u, err := l.c.ParseURL(device.Url)
if err != nil {
return nil, err
}
if device.SslThumbprint != "" {
// TODO: prefer host management IP
l.c.SetThumbprint(u.Host, device.SslThumbprint)
}
if len(items) == 0 {
// this is an export
item := types.OvfFileItem{
DeviceId: device.Key,
Path: device.TargetId,
Size: device.FileSize,
}
if item.Size == 0 {
item.Size = li.TotalDiskCapacityInKB * 1024
}
if item.Path == "" {
item.Path = path.Base(device.Url)
}
info.Items = append(info.Items, NewFileItem(u, item))
continue
}
// this is an import
for _, item := range items {
if device.ImportKey == item.DeviceId {
fi := NewFileItem(u, item)
fi.Thumbprint = device.SslThumbprint
info.Items = append(info.Items, fi)
break
}
}
}
return info, nil
}
func (l *Lease) Wait(ctx context.Context, items []types.OvfFileItem) (*LeaseInfo, error) {
var lease mo.HttpNfcLease
pc := property.DefaultCollector(l.c)
err := property.Wait(ctx, pc, l.Reference(), []string{"state", "info", "error"}, func(pc []types.PropertyChange) bool {
done := false
for _, c := range pc {
if c.Val == nil {
continue
}
switch c.Name {
case "error":
val := c.Val.(types.LocalizedMethodFault)
lease.Error = &val
done = true
case "info":
val := c.Val.(types.HttpNfcLeaseInfo)
lease.Info = &val
case "state":
lease.State = c.Val.(types.HttpNfcLeaseState)
if lease.State != types.HttpNfcLeaseStateInitializing {
done = true
}
}
}
return done
})
if err != nil {
return nil, err
}
if lease.State == types.HttpNfcLeaseStateReady {
return l.newLeaseInfo(lease.Info, items)
}
if lease.Error != nil {
return nil, &task.Error{LocalizedMethodFault: lease.Error}
}
return nil, fmt.Errorf("unexpected nfc lease state: %s", lease.State)
}
func (l *Lease) StartUpdater(ctx context.Context, info *LeaseInfo) *LeaseUpdater {
return newLeaseUpdater(ctx, l, info)
}
func (l *Lease) Upload(ctx context.Context, item FileItem, f io.Reader, opts soap.Upload) error {
if opts.Progress == nil {
opts.Progress = item
}
// Non-disk files (such as .iso) use the PUT method.
// Overwrite: t header is also required in this case (ovftool does the same)
if item.Create {
opts.Method = "PUT"
opts.Headers = map[string]string{
"Overwrite": "t",
}
} else {
opts.Method = "POST"
opts.Type = "application/x-vnd.vmware-streamVmdk"
}
return l.c.Upload(ctx, f, item.URL, &opts)
}
func (l *Lease) DownloadFile(ctx context.Context, file string, item FileItem, opts soap.Download) error {
if opts.Progress == nil {
opts.Progress = item
}
return l.c.DownloadFile(ctx, file, item.URL, &opts)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/nfc/lease_updater.go | vendor/github.com/vmware/govmomi/nfc/lease_updater.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package nfc
import (
"context"
"log"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/types"
)
type FileItem struct {
types.OvfFileItem
URL *url.URL
Thumbprint string
ch chan progress.Report
}
func NewFileItem(u *url.URL, item types.OvfFileItem) FileItem {
return FileItem{
OvfFileItem: item,
URL: u,
ch: make(chan progress.Report),
}
}
func (o FileItem) Sink() chan<- progress.Report {
return o.ch
}
// File converts the FileItem.OvfFileItem to an OvfFile
func (o FileItem) File() types.OvfFile {
return types.OvfFile{
DeviceId: o.DeviceId,
Path: o.Path,
Size: o.Size,
}
}
type LeaseUpdater struct {
pos int64 // Number of bytes (keep first to ensure 64 bit alignment)
total int64 // Total number of bytes (keep first to ensure 64 bit alignment)
lease *Lease
done chan struct{} // When lease updater should stop
wg sync.WaitGroup // Track when update loop is done
}
func newLeaseUpdater(ctx context.Context, lease *Lease, info *LeaseInfo) *LeaseUpdater {
l := LeaseUpdater{
lease: lease,
done: make(chan struct{}),
}
for _, item := range info.Items {
l.total += item.Size
go l.waitForProgress(item)
}
// Kickstart update loop
l.wg.Add(1)
go l.run()
return &l
}
func (l *LeaseUpdater) waitForProgress(item FileItem) {
var pos, total int64
total = item.Size
for {
select {
case <-l.done:
return
case p, ok := <-item.ch:
// Return in case of error
if ok && p.Error() != nil {
return
}
if !ok {
// Last element on the channel, add to total
atomic.AddInt64(&l.pos, total-pos)
return
}
// Approximate progress in number of bytes
x := int64(float32(total) * (p.Percentage() / 100.0))
atomic.AddInt64(&l.pos, x-pos)
pos = x
}
}
}
func (l *LeaseUpdater) run() {
defer l.wg.Done()
tick := time.NewTicker(2 * time.Second)
defer tick.Stop()
for {
select {
case <-l.done:
return
case <-tick.C:
// From the vim api HttpNfcLeaseProgress(percent) doc, percent ==
// "Completion status represented as an integer in the 0-100 range."
// Always report the current value of percent, as it will renew the
// lease even if the value hasn't changed or is 0.
percent := int32(float32(100*atomic.LoadInt64(&l.pos)) / float32(l.total))
err := l.lease.Progress(context.TODO(), percent)
if err != nil {
log.Printf("NFC lease progress: %s", err)
return
}
}
}
}
func (l *LeaseUpdater) Done() {
close(l.done)
l.wg.Wait()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/list/path.go | vendor/github.com/vmware/govmomi/list/path.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package list
import (
"path"
"strings"
)
func ToParts(p string) []string {
p = path.Clean(p)
if p == "/" {
return []string{}
}
if len(p) > 0 {
// Prefix ./ if relative
if p[0] != '/' && p[0] != '.' {
p = "./" + p
}
}
ps := strings.Split(p, "/")
if ps[0] == "" {
// Start at root
ps = ps[1:]
}
return ps
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/list/lister.go | vendor/github.com/vmware/govmomi/list/lister.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package list
import (
"context"
"fmt"
"path"
"reflect"
"github.com/vmware/govmomi/fault"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type Element struct {
Path string
Object mo.Reference
}
func (e Element) String() string {
return fmt.Sprintf("%s @ %s", e.Object.Reference(), e.Path)
}
func ToElement(r mo.Reference, prefix string) Element {
var name string
// Comments about types to be expected in folders copied from the
// documentation of the Folder managed object:
// https://developer.broadcom.com/xapis/vsphere-web-services-api/latest/vim.Folder.html
switch m := r.(type) {
case mo.Folder:
name = m.Name
case mo.StoragePod:
name = m.Name
// { "vim.Datacenter" } - Identifies the root folder and its descendant
// folders. Data center folders can contain child data center folders and
// Datacenter managed objects. Datacenter objects contain virtual machine,
// compute resource, network entity, and datastore folders.
case mo.Datacenter:
name = m.Name
// { "vim.Virtualmachine", "vim.VirtualApp" } - Identifies a virtual machine
// folder. A virtual machine folder may contain child virtual machine
// folders. It also can contain VirtualMachine managed objects, templates,
// and VirtualApp managed objects.
case mo.VirtualMachine:
name = m.Name
case mo.VirtualApp:
name = m.Name
// { "vim.ComputeResource" } - Identifies a compute resource
// folder, which contains child compute resource folders and ComputeResource
// hierarchies.
case mo.ComputeResource:
name = m.Name
case mo.ClusterComputeResource:
name = m.Name
case mo.HostSystem:
name = m.Name
case mo.ResourcePool:
name = m.Name
// { "vim.Network" } - Identifies a network entity folder.
// Network entity folders on a vCenter Server can contain Network,
// DistributedVirtualSwitch, and DistributedVirtualPortgroup managed objects.
// Network entity folders on an ESXi host can contain only Network objects.
case mo.Network:
name = m.Name
case mo.OpaqueNetwork:
name = m.Name
case mo.DistributedVirtualSwitch:
name = m.Name
case mo.DistributedVirtualPortgroup:
name = m.Name
case mo.VmwareDistributedVirtualSwitch:
name = m.Name
// { "vim.Datastore" } - Identifies a datastore folder. Datastore folders can
// contain child datastore folders and Datastore managed objects.
case mo.Datastore:
name = m.Name
default:
panic("not implemented for type " + reflect.TypeOf(r).String())
}
e := Element{
Path: path.Join(prefix, name),
Object: r,
}
return e
}
type Lister struct {
Collector *property.Collector
Reference types.ManagedObjectReference
Prefix string
All bool
}
func (l Lister) retrieveProperties(ctx context.Context, req types.RetrieveProperties, dst *[]any) error {
res, err := l.Collector.RetrieveProperties(ctx, req)
if err != nil {
return err
}
// Instead of using mo.LoadRetrievePropertiesResponse, use a custom loop to
// iterate over the results and ignore entries that have properties that
// could not be retrieved (a non-empty `missingSet` property). Since the
// returned objects are enumerated by vSphere in the first place, any object
// that has a non-empty `missingSet` property is indicative of a race
// condition in vSphere where the object was enumerated initially, but was
// removed before its properties could be collected.
for _, p := range res.Returnval {
v, err := mo.ObjectContentToType(p)
if err != nil {
if fault.Is(err, &types.ManagedObjectNotFound{}) {
continue
}
return err
}
*dst = append(*dst, v)
}
return nil
}
func (l Lister) List(ctx context.Context) ([]Element, error) {
switch l.Reference.Type {
case "Folder", "StoragePod":
return l.ListFolder(ctx)
case "Datacenter":
return l.ListDatacenter(ctx)
case "ComputeResource", "ClusterComputeResource":
// Treat ComputeResource and ClusterComputeResource as one and the same.
// It doesn't matter from the perspective of the lister.
return l.ListComputeResource(ctx)
case "ResourcePool":
return l.ListResourcePool(ctx)
case "HostSystem":
return l.ListHostSystem(ctx)
case "VirtualApp":
return l.ListVirtualApp(ctx)
case "VmwareDistributedVirtualSwitch", "DistributedVirtualSwitch":
return l.ListDistributedVirtualSwitch(ctx)
default:
return nil, fmt.Errorf("cannot traverse type " + l.Reference.Type)
}
}
func (l Lister) ListFolder(ctx context.Context) ([]Element, error) {
spec := types.PropertyFilterSpec{
ObjectSet: []types.ObjectSpec{
{
Obj: l.Reference,
SelectSet: []types.BaseSelectionSpec{
&types.TraversalSpec{
Path: "childEntity",
Skip: types.NewBool(false),
Type: "Folder",
},
},
Skip: types.NewBool(true),
},
},
}
// Retrieve all objects that we can deal with
childTypes := []string{
"Folder",
"Datacenter",
"VirtualApp",
"VirtualMachine",
"Network",
"ComputeResource",
"ClusterComputeResource",
"Datastore",
"DistributedVirtualSwitch",
}
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
// Additional basic properties.
switch t {
case "Folder":
pspec.PathSet = append(pspec.PathSet, "childType")
case "ComputeResource", "ClusterComputeResource":
// The ComputeResource and ClusterComputeResource are dereferenced in
// the ResourcePoolFlag. Make sure they always have their resourcePool
// field populated.
pspec.PathSet = append(pspec.PathSet, "resourcePool")
}
}
spec.PropSet = append(spec.PropSet, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{spec},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListDatacenter(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
// Include every datastore folder in the select set
fields := []string{
"vmFolder",
"hostFolder",
"datastoreFolder",
"networkFolder",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "Datacenter",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
pspec := types.PropertySpec{
Type: "Folder",
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name", "childType"}
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: []types.PropertySpec{pspec},
},
},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListComputeResource(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"host",
"network",
"resourcePool",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "ComputeResource",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"HostSystem",
"Network",
"ResourcePool",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListResourcePool(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"resourcePool",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "ResourcePool",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"ResourcePool",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListHostSystem(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"datastore",
"network",
"vm",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "HostSystem",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"Datastore",
"Network",
"VirtualMachine",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListDistributedVirtualSwitch(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"portgroup",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "DistributedVirtualSwitch",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"DistributedVirtualPortgroup",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
func (l Lister) ListVirtualApp(ctx context.Context) ([]Element, error) {
ospec := types.ObjectSpec{
Obj: l.Reference,
Skip: types.NewBool(true),
}
fields := []string{
"resourcePool",
"vm",
}
for _, f := range fields {
tspec := types.TraversalSpec{
Path: f,
Skip: types.NewBool(false),
Type: "VirtualApp",
}
ospec.SelectSet = append(ospec.SelectSet, &tspec)
}
childTypes := []string{
"ResourcePool",
"VirtualMachine",
}
var pspecs []types.PropertySpec
for _, t := range childTypes {
pspec := types.PropertySpec{
Type: t,
}
if l.All {
pspec.All = types.NewBool(true)
} else {
pspec.PathSet = []string{"name"}
}
pspecs = append(pspecs, pspec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspecs,
},
},
}
var dst []any
err := l.retrieveProperties(ctx, req, &dst)
if err != nil {
return nil, err
}
es := []Element{}
for _, v := range dst {
es = append(es, ToElement(v.(mo.Reference), l.Prefix))
}
return es, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/history/collector.go | vendor/github.com/vmware/govmomi/history/collector.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package history
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type Collector struct {
r types.ManagedObjectReference
c *vim25.Client
}
func NewCollector(c *vim25.Client, ref types.ManagedObjectReference) *Collector {
return &Collector{
r: ref,
c: c,
}
}
// Reference returns the managed object reference of this collector
func (c Collector) Reference() types.ManagedObjectReference {
return c.r
}
// Client returns the vim25 client used by this collector
func (c Collector) Client() *vim25.Client {
return c.c
}
// Properties wraps property.DefaultCollector().RetrieveOne() and returns
// properties for the specified managed object reference
func (c Collector) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst any) error {
return property.DefaultCollector(c.c).RetrieveOne(ctx, r, ps, dst)
}
func (c Collector) Destroy(ctx context.Context) error {
req := types.DestroyCollector{
This: c.r,
}
_, err := methods.DestroyCollector(ctx, c.c, &req)
return err
}
func (c Collector) Reset(ctx context.Context) error {
req := types.ResetCollector{
This: c.r,
}
_, err := methods.ResetCollector(ctx, c.c, &req)
return err
}
func (c Collector) Rewind(ctx context.Context) error {
req := types.RewindCollector{
This: c.r,
}
_, err := methods.RewindCollector(ctx, c.c, &req)
return err
}
func (c Collector) SetPageSize(ctx context.Context, maxCount int32) error {
req := types.SetCollectorPageSize{
This: c.r,
MaxCount: maxCount,
}
_, err := methods.SetCollectorPageSize(ctx, c.c, &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_network_system.go | vendor/github.com/vmware/govmomi/object/host_network_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostNetworkSystem struct {
Common
}
func NewHostNetworkSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostNetworkSystem {
return &HostNetworkSystem{
Common: NewCommon(c, ref),
}
}
// AddPortGroup wraps methods.AddPortGroup
func (o HostNetworkSystem) AddPortGroup(ctx context.Context, portgrp types.HostPortGroupSpec) error {
req := types.AddPortGroup{
This: o.Reference(),
Portgrp: portgrp,
}
_, err := methods.AddPortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// AddServiceConsoleVirtualNic wraps methods.AddServiceConsoleVirtualNic
func (o HostNetworkSystem) AddServiceConsoleVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error) {
req := types.AddServiceConsoleVirtualNic{
This: o.Reference(),
Portgroup: portgroup,
Nic: nic,
}
res, err := methods.AddServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// AddVirtualNic wraps methods.AddVirtualNic
func (o HostNetworkSystem) AddVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error) {
req := types.AddVirtualNic{
This: o.Reference(),
Portgroup: portgroup,
Nic: nic,
}
res, err := methods.AddVirtualNic(ctx, o.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// AddVirtualSwitch wraps methods.AddVirtualSwitch
func (o HostNetworkSystem) AddVirtualSwitch(ctx context.Context, vswitchName string, spec *types.HostVirtualSwitchSpec) error {
req := types.AddVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
Spec: spec,
}
_, err := methods.AddVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// QueryNetworkHint wraps methods.QueryNetworkHint
func (o HostNetworkSystem) QueryNetworkHint(ctx context.Context, device []string) ([]types.PhysicalNicHintInfo, error) {
req := types.QueryNetworkHint{
This: o.Reference(),
Device: device,
}
res, err := methods.QueryNetworkHint(ctx, o.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, err
}
// RefreshNetworkSystem wraps methods.RefreshNetworkSystem
func (o HostNetworkSystem) RefreshNetworkSystem(ctx context.Context) error {
req := types.RefreshNetworkSystem{
This: o.Reference(),
}
_, err := methods.RefreshNetworkSystem(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemovePortGroup wraps methods.RemovePortGroup
func (o HostNetworkSystem) RemovePortGroup(ctx context.Context, pgName string) error {
req := types.RemovePortGroup{
This: o.Reference(),
PgName: pgName,
}
_, err := methods.RemovePortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveServiceConsoleVirtualNic wraps methods.RemoveServiceConsoleVirtualNic
func (o HostNetworkSystem) RemoveServiceConsoleVirtualNic(ctx context.Context, device string) error {
req := types.RemoveServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RemoveServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveVirtualNic wraps methods.RemoveVirtualNic
func (o HostNetworkSystem) RemoveVirtualNic(ctx context.Context, device string) error {
req := types.RemoveVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RemoveVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveVirtualSwitch wraps methods.RemoveVirtualSwitch
func (o HostNetworkSystem) RemoveVirtualSwitch(ctx context.Context, vswitchName string) error {
req := types.RemoveVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
}
_, err := methods.RemoveVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RestartServiceConsoleVirtualNic wraps methods.RestartServiceConsoleVirtualNic
func (o HostNetworkSystem) RestartServiceConsoleVirtualNic(ctx context.Context, device string) error {
req := types.RestartServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RestartServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateConsoleIpRouteConfig wraps methods.UpdateConsoleIpRouteConfig
func (o HostNetworkSystem) UpdateConsoleIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error {
req := types.UpdateConsoleIpRouteConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateConsoleIpRouteConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateDnsConfig wraps methods.UpdateDnsConfig
func (o HostNetworkSystem) UpdateDnsConfig(ctx context.Context, config types.BaseHostDnsConfig) error {
req := types.UpdateDnsConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateDnsConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateIpRouteConfig wraps methods.UpdateIpRouteConfig
func (o HostNetworkSystem) UpdateIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error {
req := types.UpdateIpRouteConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateIpRouteConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateIpRouteTableConfig wraps methods.UpdateIpRouteTableConfig
func (o HostNetworkSystem) UpdateIpRouteTableConfig(ctx context.Context, config types.HostIpRouteTableConfig) error {
req := types.UpdateIpRouteTableConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateIpRouteTableConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateNetworkConfig wraps methods.UpdateNetworkConfig
func (o HostNetworkSystem) UpdateNetworkConfig(ctx context.Context, config types.HostNetworkConfig, changeMode string) (*types.HostNetworkConfigResult, error) {
req := types.UpdateNetworkConfig{
This: o.Reference(),
Config: config,
ChangeMode: changeMode,
}
res, err := methods.UpdateNetworkConfig(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// UpdatePhysicalNicLinkSpeed wraps methods.UpdatePhysicalNicLinkSpeed
func (o HostNetworkSystem) UpdatePhysicalNicLinkSpeed(ctx context.Context, device string, linkSpeed *types.PhysicalNicLinkInfo) error {
req := types.UpdatePhysicalNicLinkSpeed{
This: o.Reference(),
Device: device,
LinkSpeed: linkSpeed,
}
_, err := methods.UpdatePhysicalNicLinkSpeed(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdatePortGroup wraps methods.UpdatePortGroup
func (o HostNetworkSystem) UpdatePortGroup(ctx context.Context, pgName string, portgrp types.HostPortGroupSpec) error {
req := types.UpdatePortGroup{
This: o.Reference(),
PgName: pgName,
Portgrp: portgrp,
}
_, err := methods.UpdatePortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateServiceConsoleVirtualNic wraps methods.UpdateServiceConsoleVirtualNic
func (o HostNetworkSystem) UpdateServiceConsoleVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error {
req := types.UpdateServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
Nic: nic,
}
_, err := methods.UpdateServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateVirtualNic wraps methods.UpdateVirtualNic
func (o HostNetworkSystem) UpdateVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error {
req := types.UpdateVirtualNic{
This: o.Reference(),
Device: device,
Nic: nic,
}
_, err := methods.UpdateVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateVirtualSwitch wraps methods.UpdateVirtualSwitch
func (o HostNetworkSystem) UpdateVirtualSwitch(ctx context.Context, vswitchName string, spec types.HostVirtualSwitchSpec) error {
req := types.UpdateVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
Spec: spec,
}
_, err := methods.UpdateVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/datastore.go | vendor/github.com/vmware/govmomi/object/datastore.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"strings"
"github.com/vmware/govmomi/internal"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/session"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// DatastoreNoSuchDirectoryError is returned when a directory could not be found.
type DatastoreNoSuchDirectoryError struct {
verb string
subject string
}
func (e DatastoreNoSuchDirectoryError) Error() string {
return fmt.Sprintf("cannot %s '%s': No such directory", e.verb, e.subject)
}
// DatastoreNoSuchFileError is returned when a file could not be found.
type DatastoreNoSuchFileError struct {
verb string
subject string
}
func (e DatastoreNoSuchFileError) Error() string {
return fmt.Sprintf("cannot %s '%s': No such file", e.verb, e.subject)
}
type Datastore struct {
Common
DatacenterPath string
}
func NewDatastore(c *vim25.Client, ref types.ManagedObjectReference) *Datastore {
return &Datastore{
Common: NewCommon(c, ref),
}
}
// FindInventoryPath sets InventoryPath and DatacenterPath,
// needed by NewURL() to compose an upload/download endpoint URL
func (d *Datastore) FindInventoryPath(ctx context.Context) error {
entities, err := mo.Ancestors(ctx, d.c, d.c.ServiceContent.PropertyCollector, d.r)
if err != nil {
return err
}
val := "/"
for _, entity := range entities {
if entity.Parent == nil {
continue // root folder
}
val = path.Join(val, entity.Name)
if entity.Self.Type == "Datacenter" {
d.DatacenterPath = val
}
}
d.InventoryPath = val
return nil
}
func (d Datastore) Path(path string) string {
var p DatastorePath
if p.FromString(path) {
return p.String() // already in "[datastore] path" format
}
return (&DatastorePath{
Datastore: d.Name(),
Path: path,
}).String()
}
// NewDatastoreURL constructs a url.URL with the given file path for datastore access over HTTP.
func NewDatastoreURL(base url.URL, dcPath, dsName, path string) *url.URL {
scheme := base.Scheme
// In rare cases where vCenter and ESX are accessed using different schemes.
if overrideScheme := os.Getenv("GOVMOMI_DATASTORE_ACCESS_SCHEME"); overrideScheme != "" {
scheme = overrideScheme
}
base.Scheme = scheme
base.Path = fmt.Sprintf("/folder/%s", path)
base.RawQuery = url.Values{
"dcPath": []string{dcPath},
"dsName": []string{dsName},
}.Encode()
return &base
}
// NewURL constructs a url.URL with the given file path for datastore access over HTTP.
// The Datastore object is used to derive url, dcPath and dsName params to NewDatastoreURL.
// For dcPath, Datastore.DatacenterPath must be set and for dsName, Datastore.InventoryPath.
// This is the case when the object.Datastore instance is created by Finder.
// Otherwise, Datastore.FindInventoryPath should be called first, to set DatacenterPath
// and InventoryPath.
func (d Datastore) NewURL(path string) *url.URL {
u := d.c.URL()
return NewDatastoreURL(*u, d.DatacenterPath, d.Name(), path)
}
func (d Datastore) Browser(ctx context.Context) (*HostDatastoreBrowser, error) {
var do mo.Datastore
err := d.Properties(ctx, d.Reference(), []string{"browser"}, &do)
if err != nil {
return nil, err
}
return NewHostDatastoreBrowser(d.c, do.Browser), nil
}
func (d Datastore) useServiceTicket() bool {
// If connected to workstation, service ticketing not supported
// If connected to ESX, service ticketing not needed
if !d.c.IsVC() {
return false
}
key := "GOVMOMI_USE_SERVICE_TICKET"
val := d.c.URL().Query().Get(key)
if val == "" {
val = os.Getenv(key)
}
if val == "1" || val == "true" {
return true
}
return false
}
func (d Datastore) useServiceTicketHostName(name string) bool {
// No need if talking directly to ESX.
if !d.c.IsVC() {
return false
}
// If version happens to be < 5.1
if name == "" {
return false
}
// If the HostSystem is using DHCP on a network without dynamic DNS,
// HostSystem.Config.Network.DnsConfig.HostName is set to "localhost" by default.
// This resolves to "localhost.localdomain" by default via /etc/hosts on ESX.
// In that case, we will stick with the HostSystem.Name which is the IP address that
// was used to connect the host to VC.
if name == "localhost.localdomain" {
return false
}
// Still possible to have HostName that don't resolve via DNS,
// so we default to false.
key := "GOVMOMI_USE_SERVICE_TICKET_HOSTNAME"
val := d.c.URL().Query().Get(key)
if val == "" {
val = os.Getenv(key)
}
if val == "1" || val == "true" {
return true
}
return false
}
type datastoreServiceTicketHostKey struct{}
// HostContext returns a Context where the given host will be used for datastore HTTP access
// via the ServiceTicket method.
func (d Datastore) HostContext(ctx context.Context, host *HostSystem) context.Context {
return context.WithValue(ctx, datastoreServiceTicketHostKey{}, host)
}
// ServiceTicket obtains a ticket via AcquireGenericServiceTicket and returns it an http.Cookie with the url.URL
// that can be used along with the ticket cookie to access the given path. An host is chosen at random unless the
// the given Context was created with a specific host via the HostContext method.
func (d Datastore) ServiceTicket(ctx context.Context, path string, method string) (*url.URL, *http.Cookie, error) {
if d.InventoryPath == "" {
_ = d.FindInventoryPath(ctx)
}
u := d.NewURL(path)
host, ok := ctx.Value(datastoreServiceTicketHostKey{}).(*HostSystem)
if !ok {
if !d.useServiceTicket() {
return u, nil, nil
}
hosts, err := d.AttachedHosts(ctx)
if err != nil {
return nil, nil, err
}
if len(hosts) == 0 {
// Fallback to letting vCenter choose a host
return u, nil, nil
}
// Pick a random attached host
host = hosts[rand.Intn(len(hosts))]
}
ips, err := host.ManagementIPs(ctx)
if err != nil {
return nil, nil, err
}
if len(ips) > 0 {
// prefer a ManagementIP
u.Host = ips[0].String()
} else {
// fallback to inventory name
u.Host, err = host.ObjectName(ctx)
if err != nil {
return nil, nil, err
}
}
// VC datacenter path will not be valid against ESX
q := u.Query()
delete(q, "dcPath")
u.RawQuery = q.Encode()
// Now that we have a host selected, take a copy of the URL.
transferURL := *u
if internal.UsingEnvoySidecar(d.Client()) {
// Rewrite the host URL to go through the Envoy sidecar on VC.
// Reciever must use a custom dialer.
u = internal.HostGatewayTransferURL(u, host.Reference())
}
spec := types.SessionManagerHttpServiceRequestSpec{
// Use the original URL (without rewrites) for the session ticket.
Url: transferURL.String(),
// See SessionManagerHttpServiceRequestSpecMethod enum
Method: fmt.Sprintf("http%s%s", method[0:1], strings.ToLower(method[1:])),
}
sm := session.NewManager(d.Client())
ticket, err := sm.AcquireGenericServiceTicket(ctx, &spec)
if err != nil {
return nil, nil, err
}
cookie := &http.Cookie{
Name: "vmware_cgi_ticket",
Value: ticket.Id,
}
if d.useServiceTicketHostName(ticket.HostName) {
u.Host = ticket.HostName
}
d.Client().SetThumbprint(u.Host, ticket.SslThumbprint)
return u, cookie, nil
}
func (d Datastore) uploadTicket(ctx context.Context, path string, param *soap.Upload) (*url.URL, *soap.Upload, error) {
p := soap.DefaultUpload
if param != nil {
p = *param // copy
}
u, ticket, err := d.ServiceTicket(ctx, path, p.Method)
if err != nil {
return nil, nil, err
}
if ticket != nil {
p.Ticket = ticket
p.Close = true // disable Keep-Alive connection to ESX
}
return u, &p, nil
}
func (d Datastore) downloadTicket(ctx context.Context, path string, param *soap.Download) (*url.URL, *soap.Download, error) {
p := soap.DefaultDownload
if param != nil {
p = *param // copy
}
u, ticket, err := d.ServiceTicket(ctx, path, p.Method)
if err != nil {
return nil, nil, err
}
if ticket != nil {
p.Ticket = ticket
p.Close = true // disable Keep-Alive connection to ESX
}
return u, &p, nil
}
// Upload via soap.Upload with an http service ticket
func (d Datastore) Upload(ctx context.Context, f io.Reader, path string, param *soap.Upload) error {
u, p, err := d.uploadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().Upload(ctx, f, u, p)
}
// UploadFile via soap.Upload with an http service ticket
func (d Datastore) UploadFile(ctx context.Context, file string, path string, param *soap.Upload) error {
u, p, err := d.uploadTicket(ctx, path, param)
if err != nil {
return err
}
vc := d.Client()
if internal.UsingEnvoySidecar(vc) {
// Override the vim client with a new one that wraps a Unix socket transport.
// Using HTTP here so secure means nothing.
vc = internal.ClientWithEnvoyHostGateway(vc)
}
return vc.UploadFile(ctx, file, u, p)
}
// Download via soap.Download with an http service ticket
func (d Datastore) Download(ctx context.Context, path string, param *soap.Download) (io.ReadCloser, int64, error) {
u, p, err := d.downloadTicket(ctx, path, param)
if err != nil {
return nil, 0, err
}
return d.Client().Download(ctx, u, p)
}
// DownloadFile via soap.Download with an http service ticket
func (d Datastore) DownloadFile(ctx context.Context, path string, file string, param *soap.Download) error {
u, p, err := d.downloadTicket(ctx, path, param)
if err != nil {
return err
}
vc := d.Client()
if internal.UsingEnvoySidecar(vc) {
// Override the vim client with a new one that wraps a Unix socket transport.
// Using HTTP here so secure means nothing.
vc = internal.ClientWithEnvoyHostGateway(vc)
}
return vc.DownloadFile(ctx, file, u, p)
}
// AttachedHosts returns hosts that have this Datastore attached, accessible and writable.
func (d Datastore) AttachedHosts(ctx context.Context) ([]*HostSystem, error) {
var ds mo.Datastore
var hosts []*HostSystem
pc := property.DefaultCollector(d.Client())
err := pc.RetrieveOne(ctx, d.Reference(), []string{"host"}, &ds)
if err != nil {
return nil, err
}
mounts := make(map[types.ManagedObjectReference]types.DatastoreHostMount)
var refs []types.ManagedObjectReference
for _, host := range ds.Host {
refs = append(refs, host.Key)
mounts[host.Key] = host
}
var hs []mo.HostSystem
err = pc.Retrieve(ctx, refs, []string{"runtime.connectionState", "runtime.powerState"}, &hs)
if err != nil {
return nil, err
}
for _, host := range hs {
if host.Runtime.ConnectionState == types.HostSystemConnectionStateConnected &&
host.Runtime.PowerState == types.HostSystemPowerStatePoweredOn {
mount := mounts[host.Reference()]
info := mount.MountInfo
if *info.Mounted && *info.Accessible && info.AccessMode == string(types.HostMountModeReadWrite) {
hosts = append(hosts, NewHostSystem(d.Client(), mount.Key))
}
}
}
return hosts, nil
}
// AttachedClusterHosts returns hosts that have this Datastore attached, accessible and writable and are members of the given cluster.
func (d Datastore) AttachedClusterHosts(ctx context.Context, cluster *ComputeResource) ([]*HostSystem, error) {
var hosts []*HostSystem
clusterHosts, err := cluster.Hosts(ctx)
if err != nil {
return nil, err
}
attachedHosts, err := d.AttachedHosts(ctx)
if err != nil {
return nil, err
}
refs := make(map[types.ManagedObjectReference]bool)
for _, host := range attachedHosts {
refs[host.Reference()] = true
}
for _, host := range clusterHosts {
if refs[host.Reference()] {
hosts = append(hosts, host)
}
}
return hosts, nil
}
func (d Datastore) Stat(ctx context.Context, file string) (types.BaseFileInfo, error) {
b, err := d.Browser(ctx)
if err != nil {
return nil, err
}
spec := types.HostDatastoreBrowserSearchSpec{
Details: &types.FileQueryFlags{
FileType: true,
FileSize: true,
Modification: true,
FileOwner: types.NewBool(true),
},
MatchPattern: []string{path.Base(file)},
}
dsPath := d.Path(path.Dir(file))
task, err := b.SearchDatastore(ctx, dsPath, &spec)
if err != nil {
return nil, err
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
if types.IsFileNotFound(err) {
// FileNotFound means the base path doesn't exist.
return nil, DatastoreNoSuchDirectoryError{"stat", dsPath}
}
return nil, err
}
res := info.Result.(types.HostDatastoreBrowserSearchResults)
if len(res.File) == 0 {
// File doesn't exist
return nil, DatastoreNoSuchFileError{"stat", d.Path(file)}
}
return res.File[0], nil
}
// Type returns the type of file system volume.
func (d Datastore) Type(ctx context.Context) (types.HostFileSystemVolumeFileSystemType, error) {
var mds mo.Datastore
if err := d.Properties(ctx, d.Reference(), []string{"summary.type"}, &mds); err != nil {
return types.HostFileSystemVolumeFileSystemType(""), err
}
return types.HostFileSystemVolumeFileSystemType(mds.Summary.Type), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/distributed_virtual_switch.go | vendor/github.com/vmware/govmomi/object/distributed_virtual_switch.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type DistributedVirtualSwitch struct {
Common
}
func NewDistributedVirtualSwitch(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualSwitch {
return &DistributedVirtualSwitch{
Common: NewCommon(c, ref),
}
}
func (s DistributedVirtualSwitch) GetInventoryPath() string {
return s.InventoryPath
}
func (s DistributedVirtualSwitch) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
ref := s.Reference()
name := s.InventoryPath
if name == "" {
name = ref.String()
}
return nil, fmt.Errorf("type %s (%s) cannot be used for EthernetCardBackingInfo", ref.Type, name)
}
func (s DistributedVirtualSwitch) Reconfigure(ctx context.Context, spec types.BaseDVSConfigSpec) (*Task, error) {
req := types.ReconfigureDvs_Task{
This: s.Reference(),
Spec: spec,
}
res, err := methods.ReconfigureDvs_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) AddPortgroup(ctx context.Context, spec []types.DVPortgroupConfigSpec) (*Task, error) {
req := types.AddDVPortgroup_Task{
This: s.Reference(),
Spec: spec,
}
res, err := methods.AddDVPortgroup_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) FetchDVPorts(ctx context.Context, criteria *types.DistributedVirtualSwitchPortCriteria) ([]types.DistributedVirtualPort, error) {
req := &types.FetchDVPorts{
This: s.Reference(),
Criteria: criteria,
}
res, err := methods.FetchDVPorts(ctx, s.Client(), req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s DistributedVirtualSwitch) ReconfigureDVPort(ctx context.Context, spec []types.DVPortConfigSpec) (*Task, error) {
req := types.ReconfigureDVPort_Task{
This: s.Reference(),
Port: spec,
}
res, err := methods.ReconfigureDVPort_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) ReconfigureLACP(ctx context.Context, spec []types.VMwareDvsLacpGroupSpec) (*Task, error) {
req := types.UpdateDVSLacpGroupConfig_Task{
This: s.Reference(),
LacpGroupSpec: spec,
}
res, err := methods.UpdateDVSLacpGroupConfig_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/network.go | vendor/github.com/vmware/govmomi/object/network.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type Network struct {
Common
}
func NewNetwork(c *vim25.Client, ref types.ManagedObjectReference) *Network {
return &Network{
Common: NewCommon(c, ref),
}
}
func (n Network) GetInventoryPath() string {
return n.InventoryPath
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n Network) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
name, err := n.ObjectName(ctx)
if err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: name,
},
}
return backing, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_firewall_system.go | vendor/github.com/vmware/govmomi/object/host_firewall_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"errors"
"fmt"
"strings"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostFirewallSystem struct {
Common
}
func NewHostFirewallSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostFirewallSystem {
return &HostFirewallSystem{
Common: NewCommon(c, ref),
}
}
func (s HostFirewallSystem) DisableRuleset(ctx context.Context, id string) error {
req := types.DisableRuleset{
This: s.Reference(),
Id: id,
}
_, err := methods.DisableRuleset(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) EnableRuleset(ctx context.Context, id string) error {
req := types.EnableRuleset{
This: s.Reference(),
Id: id,
}
_, err := methods.EnableRuleset(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) Refresh(ctx context.Context) error {
req := types.RefreshFirewall{
This: s.Reference(),
}
_, err := methods.RefreshFirewall(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) Info(ctx context.Context) (*types.HostFirewallInfo, error) {
var fs mo.HostFirewallSystem
err := s.Properties(ctx, s.Reference(), []string{"firewallInfo"}, &fs)
if err != nil {
return nil, err
}
return fs.FirewallInfo, nil
}
// HostFirewallRulesetList provides helpers for a slice of types.HostFirewallRuleset
type HostFirewallRulesetList []types.HostFirewallRuleset
// ByRule returns a HostFirewallRulesetList where Direction, PortType and Protocol are equal and Port is within range
func (l HostFirewallRulesetList) ByRule(rule types.HostFirewallRule) HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
for _, r := range rs.Rule {
if r.PortType != rule.PortType ||
r.Protocol != rule.Protocol ||
r.Direction != rule.Direction {
continue
}
if r.EndPort == 0 && rule.Port == r.Port ||
rule.Port >= r.Port && rule.Port <= r.EndPort {
matches = append(matches, rs)
break
}
}
}
return matches
}
// EnabledByRule returns a HostFirewallRulesetList with Match(rule) applied and filtered via Enabled()
// if enabled param is true, otherwise filtered via Disabled().
// An error is returned if the resulting list is empty.
func (l HostFirewallRulesetList) EnabledByRule(rule types.HostFirewallRule, enabled bool) (HostFirewallRulesetList, error) {
var matched, skipped HostFirewallRulesetList
var matchedKind, skippedKind string
l = l.ByRule(rule)
if enabled {
matched = l.Enabled()
matchedKind = "enabled"
skipped = l.Disabled()
skippedKind = "disabled"
} else {
matched = l.Disabled()
matchedKind = "disabled"
skipped = l.Enabled()
skippedKind = "enabled"
}
if len(matched) == 0 {
msg := fmt.Sprintf("%d %s firewall rulesets match %s %s %s %d, %d %s rulesets match",
len(matched), matchedKind,
rule.Direction, rule.Protocol, rule.PortType, rule.Port,
len(skipped), skippedKind)
if len(skipped) != 0 {
msg += fmt.Sprintf(": %s", strings.Join(skipped.Keys(), ", "))
}
return nil, errors.New(msg)
}
return matched, nil
}
// Enabled returns a HostFirewallRulesetList with enabled rules
func (l HostFirewallRulesetList) Enabled() HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
if rs.Enabled {
matches = append(matches, rs)
}
}
return matches
}
// Disabled returns a HostFirewallRulesetList with disabled rules
func (l HostFirewallRulesetList) Disabled() HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
if !rs.Enabled {
matches = append(matches, rs)
}
}
return matches
}
// Keys returns the HostFirewallRuleset.Key for each ruleset in the list
func (l HostFirewallRulesetList) Keys() []string {
var keys []string
for _, rs := range l {
keys = append(keys, rs.Key)
}
return keys
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/extension_manager.go | vendor/github.com/vmware/govmomi/object/extension_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ExtensionManager struct {
Common
}
// GetExtensionManager wraps NewExtensionManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetExtensionManager(c *vim25.Client) (*ExtensionManager, error) {
if c.ServiceContent.ExtensionManager == nil {
return nil, ErrNotSupported
}
return NewExtensionManager(c), nil
}
func NewExtensionManager(c *vim25.Client) *ExtensionManager {
o := ExtensionManager{
Common: NewCommon(c, *c.ServiceContent.ExtensionManager),
}
return &o
}
func (m ExtensionManager) List(ctx context.Context) ([]types.Extension, error) {
var em mo.ExtensionManager
err := m.Properties(ctx, m.Reference(), []string{"extensionList"}, &em)
if err != nil {
return nil, err
}
return em.ExtensionList, nil
}
func (m ExtensionManager) Find(ctx context.Context, key string) (*types.Extension, error) {
req := types.FindExtension{
This: m.Reference(),
ExtensionKey: key,
}
res, err := methods.FindExtension(ctx, m.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m ExtensionManager) Register(ctx context.Context, extension types.Extension) error {
req := types.RegisterExtension{
This: m.Reference(),
Extension: extension,
}
_, err := methods.RegisterExtension(ctx, m.c, &req)
return err
}
func (m ExtensionManager) SetCertificate(ctx context.Context, key string, certificatePem string) error {
req := types.SetExtensionCertificate{
This: m.Reference(),
ExtensionKey: key,
CertificatePem: certificatePem,
}
_, err := methods.SetExtensionCertificate(ctx, m.c, &req)
return err
}
func (m ExtensionManager) Unregister(ctx context.Context, key string) error {
req := types.UnregisterExtension{
This: m.Reference(),
ExtensionKey: key,
}
_, err := methods.UnregisterExtension(ctx, m.c, &req)
return err
}
func (m ExtensionManager) Update(ctx context.Context, extension types.Extension) error {
req := types.UpdateExtension{
This: m.Reference(),
Extension: extension,
}
_, err := methods.UpdateExtension(ctx, m.c, &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/tenant_manager.go | vendor/github.com/vmware/govmomi/object/tenant_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type TenantManager struct {
Common
}
func NewTenantManager(c *vim25.Client) *TenantManager {
t := TenantManager{
Common: NewCommon(c, *c.ServiceContent.TenantManager),
}
return &t
}
func (t TenantManager) MarkServiceProviderEntities(ctx context.Context, entities []types.ManagedObjectReference) error {
req := types.MarkServiceProviderEntities{
This: t.Reference(),
Entity: entities,
}
_, err := methods.MarkServiceProviderEntities(ctx, t.Client(), &req)
if err != nil {
return err
}
return nil
}
func (t TenantManager) UnmarkServiceProviderEntities(ctx context.Context, entities []types.ManagedObjectReference) error {
req := types.UnmarkServiceProviderEntities{
This: t.Reference(),
Entity: entities,
}
_, err := methods.UnmarkServiceProviderEntities(ctx, t.Client(), &req)
if err != nil {
return err
}
return nil
}
func (t TenantManager) RetrieveServiceProviderEntities(ctx context.Context) ([]types.ManagedObjectReference, error) {
req := types.RetrieveServiceProviderEntities{
This: t.Reference(),
}
res, err := methods.RetrieveServiceProviderEntities(ctx, t.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/option_manager.go | vendor/github.com/vmware/govmomi/object/option_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type OptionManager struct {
Common
}
func NewOptionManager(c *vim25.Client, ref types.ManagedObjectReference) *OptionManager {
return &OptionManager{
Common: NewCommon(c, ref),
}
}
func (m OptionManager) Query(ctx context.Context, name string) ([]types.BaseOptionValue, error) {
req := types.QueryOptions{
This: m.Reference(),
Name: name,
}
res, err := methods.QueryOptions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m OptionManager) Update(ctx context.Context, value []types.BaseOptionValue) error {
req := types.UpdateOptions{
This: m.Reference(),
ChangedValue: value,
}
_, err := methods.UpdateOptions(ctx, m.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/datastore_file.go | vendor/github.com/vmware/govmomi/object/datastore_file.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"sync"
"time"
"github.com/vmware/govmomi/vim25/soap"
)
// DatastoreFile implements io.Reader, io.Seeker and io.Closer interfaces for datastore file access.
type DatastoreFile struct {
d Datastore
ctx context.Context
name string
buf io.Reader
body io.ReadCloser
length int64
offset struct {
read, seek int64
}
}
// Open opens the named file relative to the Datastore.
func (d Datastore) Open(ctx context.Context, name string) (*DatastoreFile, error) {
return &DatastoreFile{
d: d,
name: name,
length: -1,
ctx: ctx,
}, nil
}
// Read reads up to len(b) bytes from the DatastoreFile.
func (f *DatastoreFile) Read(b []byte) (int, error) {
if f.offset.read != f.offset.seek {
// A Seek() call changed the offset, we need to issue a new GET
_ = f.Close()
f.offset.read = f.offset.seek
} else if f.buf != nil {
// f.buf + f behaves like an io.MultiReader
n, err := f.buf.Read(b)
if err == io.EOF {
f.buf = nil // buffer has been drained
}
if n > 0 {
return n, nil
}
}
body, err := f.get()
if err != nil {
return 0, err
}
n, err := body.Read(b)
f.offset.read += int64(n)
f.offset.seek += int64(n)
return n, err
}
// Close closes the DatastoreFile.
func (f *DatastoreFile) Close() error {
var err error
if f.body != nil {
err = f.body.Close()
f.body = nil
}
f.buf = nil
return err
}
// Seek sets the offset for the next Read on the DatastoreFile.
func (f *DatastoreFile) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
case io.SeekCurrent:
offset += f.offset.seek
case io.SeekEnd:
if f.length < 0 {
_, err := f.Stat()
if err != nil {
return 0, err
}
}
offset += f.length
default:
return 0, errors.New("Seek: invalid whence")
}
// allow negative SeekStart for initial Range request
if offset < 0 {
return 0, errors.New("Seek: invalid offset")
}
f.offset.seek = offset
return offset, nil
}
type fileStat struct {
file *DatastoreFile
header http.Header
}
func (s *fileStat) Name() string {
return path.Base(s.file.name)
}
func (s *fileStat) Size() int64 {
return s.file.length
}
func (s *fileStat) Mode() os.FileMode {
return 0
}
func (s *fileStat) ModTime() time.Time {
return time.Now() // no Last-Modified
}
func (s *fileStat) IsDir() bool {
return false
}
func (s *fileStat) Sys() any {
return s.header
}
func statusError(res *http.Response) error {
if res.StatusCode == http.StatusNotFound {
return os.ErrNotExist
}
return errors.New(res.Status)
}
// Stat returns the os.FileInfo interface describing file.
func (f *DatastoreFile) Stat() (os.FileInfo, error) {
// TODO: consider using Datastore.Stat() instead
u, p, err := f.d.downloadTicket(f.ctx, f.name, &soap.Download{Method: "HEAD"})
if err != nil {
return nil, err
}
res, err := f.d.Client().DownloadRequest(f.ctx, u, p)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, statusError(res)
}
f.length = res.ContentLength
return &fileStat{f, res.Header}, nil
}
func (f *DatastoreFile) get() (io.Reader, error) {
if f.body != nil {
return f.body, nil
}
u, p, err := f.d.downloadTicket(f.ctx, f.name, nil)
if err != nil {
return nil, err
}
if f.offset.read != 0 {
p.Headers = map[string]string{
"Range": fmt.Sprintf("bytes=%d-", f.offset.read),
}
}
res, err := f.d.Client().DownloadRequest(f.ctx, u, p)
if err != nil {
return nil, err
}
switch res.StatusCode {
case http.StatusOK:
f.length = res.ContentLength
case http.StatusPartialContent:
var start, end int
cr := res.Header.Get("Content-Range")
_, err = fmt.Sscanf(cr, "bytes %d-%d/%d", &start, &end, &f.length)
if err != nil {
f.length = -1
}
case http.StatusRequestedRangeNotSatisfiable:
// ok: Read() will return io.EOF
default:
return nil, statusError(res)
}
if f.length < 0 {
_ = res.Body.Close()
return nil, errors.New("unable to determine file size")
}
f.body = res.Body
return f.body, nil
}
func lastIndexLines(s []byte, line *int, include func(l int, m string) bool) (int64, bool) {
i := len(s) - 1
done := false
for i > 0 {
o := bytes.LastIndexByte(s[:i], '\n')
if o < 0 {
break
}
msg := string(s[o+1 : i+1])
if !include(*line, msg) {
done = true
break
} else {
i = o
*line++
}
}
return int64(i), done
}
// Tail seeks to the position of the last N lines of the file.
func (f *DatastoreFile) Tail(n int) error {
return f.TailFunc(n, func(line int, _ string) bool { return n > line })
}
// TailFunc will seek backwards in the datastore file until it hits a line that does
// not satisfy the supplied `include` function.
func (f *DatastoreFile) TailFunc(lines int, include func(line int, message string) bool) error {
// Read the file in reverse using bsize chunks
const bsize = int64(1024 * 16)
fsize, err := f.Seek(0, io.SeekEnd)
if err != nil {
return err
}
if lines == 0 {
return nil
}
chunk := int64(-1)
buf := bytes.NewBuffer(make([]byte, 0, bsize))
line := 0
for {
var eof bool
var pos int64
nread := bsize
offset := chunk * bsize
remain := fsize + offset
if remain < 0 {
if pos, err = f.Seek(0, io.SeekStart); err != nil {
return err
}
nread = bsize + remain
eof = true
} else if pos, err = f.Seek(offset, io.SeekEnd); err != nil {
return err
}
if _, err = io.CopyN(buf, f, nread); err != nil {
if err != io.EOF {
return err
}
}
b := buf.Bytes()
idx, done := lastIndexLines(b, &line, include)
if done {
if chunk == -1 {
// We found all N lines in the last chunk of the file.
// The seek offset is also now at the current end of file.
// Save this buffer to avoid another GET request when Read() is called.
buf.Next(int(idx + 1))
f.buf = buf
return nil
}
if _, err = f.Seek(pos+idx+1, io.SeekStart); err != nil {
return err
}
break
}
if eof {
if remain < 0 {
// We found < N lines in the entire file, so seek to the start.
_, _ = f.Seek(0, io.SeekStart)
}
break
}
chunk--
buf.Reset()
}
return nil
}
type followDatastoreFile struct {
r *DatastoreFile
c chan struct{}
i time.Duration
o sync.Once
}
// Read reads up to len(b) bytes from the DatastoreFile being followed.
// This method will block until data is read, an error other than io.EOF is returned or Close() is called.
func (f *followDatastoreFile) Read(p []byte) (int, error) {
offset := f.r.offset.seek
stop := false
for {
n, err := f.r.Read(p)
if err != nil && err == io.EOF {
_ = f.r.Close() // GET request body has been drained.
if stop {
return n, err
}
err = nil
}
if n > 0 {
return n, err
}
select {
case <-f.c:
// Wake up and stop polling once the body has been drained
stop = true
case <-time.After(f.i):
}
info, serr := f.r.Stat()
if serr != nil {
// Return EOF rather than 404 if the file goes away
if serr == os.ErrNotExist {
_ = f.r.Close()
return 0, io.EOF
}
return 0, serr
}
if info.Size() < offset {
// assume file has be truncated
offset, err = f.r.Seek(0, io.SeekStart)
if err != nil {
return 0, err
}
}
}
}
// Close will stop Follow polling and close the underlying DatastoreFile.
func (f *followDatastoreFile) Close() error {
f.o.Do(func() { close(f.c) })
return nil
}
// Follow returns an io.ReadCloser to stream the file contents as data is appended.
func (f *DatastoreFile) Follow(interval time.Duration) io.ReadCloser {
return &followDatastoreFile{
r: f,
c: make(chan struct{}),
i: interval,
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/resource_pool.go | vendor/github.com/vmware/govmomi/object/resource_pool.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/nfc"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ResourcePool struct {
Common
}
func NewResourcePool(c *vim25.Client, ref types.ManagedObjectReference) *ResourcePool {
return &ResourcePool{
Common: NewCommon(c, ref),
}
}
// Owner returns the ResourcePool owner as a ClusterComputeResource or ComputeResource.
func (p ResourcePool) Owner(ctx context.Context) (Reference, error) {
var pool mo.ResourcePool
err := p.Properties(ctx, p.Reference(), []string{"owner"}, &pool)
if err != nil {
return nil, err
}
return NewReference(p.Client(), pool.Owner), nil
}
func (p ResourcePool) ImportVApp(ctx context.Context, spec types.BaseImportSpec, folder *Folder, host *HostSystem) (*nfc.Lease, error) {
req := types.ImportVApp{
This: p.Reference(),
Spec: spec,
}
if folder != nil {
ref := folder.Reference()
req.Folder = &ref
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.ImportVApp(ctx, p.c, &req)
if err != nil {
return nil, err
}
return nfc.NewLease(p.c, res.Returnval), nil
}
func (p ResourcePool) Create(ctx context.Context, name string, spec types.ResourceConfigSpec) (*ResourcePool, error) {
req := types.CreateResourcePool{
This: p.Reference(),
Name: name,
Spec: spec,
}
res, err := methods.CreateResourcePool(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewResourcePool(p.c, res.Returnval), nil
}
func (p ResourcePool) CreateVApp(ctx context.Context, name string, resSpec types.ResourceConfigSpec, configSpec types.VAppConfigSpec, folder *Folder) (*VirtualApp, error) {
req := types.CreateVApp{
This: p.Reference(),
Name: name,
ResSpec: resSpec,
ConfigSpec: configSpec,
}
if folder != nil {
ref := folder.Reference()
req.VmFolder = &ref
}
res, err := methods.CreateVApp(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewVirtualApp(p.c, res.Returnval), nil
}
func (p ResourcePool) UpdateConfig(ctx context.Context, name string, config *types.ResourceConfigSpec) error {
req := types.UpdateConfig{
This: p.Reference(),
Name: name,
Config: config,
}
if config != nil && config.Entity == nil {
ref := p.Reference()
// Create copy of config so changes won't leak back to the caller
newConfig := *config
newConfig.Entity = &ref
req.Config = &newConfig
}
_, err := methods.UpdateConfig(ctx, p.c, &req)
return err
}
func (p ResourcePool) DestroyChildren(ctx context.Context) error {
req := types.DestroyChildren{
This: p.Reference(),
}
_, err := methods.DestroyChildren(ctx, p.c, &req)
return err
}
func (p ResourcePool) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: p.Reference(),
}
res, err := methods.Destroy_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_certificate_manager.go | vendor/github.com/vmware/govmomi/object/host_certificate_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/fault"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
// HostCertificateManager provides helper methods around the HostSystem.ConfigManager.CertificateManager
type HostCertificateManager struct {
Common
Host *HostSystem
}
// NewHostCertificateManager creates a new HostCertificateManager helper
func NewHostCertificateManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostCertificateManager {
return &HostCertificateManager{
Common: NewCommon(c, ref),
Host: NewHostSystem(c, host),
}
}
// CertificateInfo wraps the host CertificateManager certificateInfo property with the HostCertificateInfo helper.
// The ThumbprintSHA1 field is set to HostSystem.Summary.Config.SslThumbprint if the host system is managed by a vCenter.
func (m HostCertificateManager) CertificateInfo(ctx context.Context) (*HostCertificateInfo, error) {
var hs mo.HostSystem
var cm mo.HostCertificateManager
pc := property.DefaultCollector(m.Client())
err := pc.RetrieveOne(ctx, m.Reference(), []string{"certificateInfo"}, &cm)
if err != nil {
return nil, err
}
_ = pc.RetrieveOne(ctx, m.Host.Reference(), []string{"summary.config.sslThumbprint"}, &hs)
return &HostCertificateInfo{
HostCertificateManagerCertificateInfo: cm.CertificateInfo,
ThumbprintSHA1: hs.Summary.Config.SslThumbprint,
}, nil
}
// GenerateCertificateSigningRequest requests the host system to generate a certificate-signing request (CSR) for itself.
// The CSR is then typically provided to a Certificate Authority to sign and issue the SSL certificate for the host system.
// Use InstallServerCertificate to import this certificate.
func (m HostCertificateManager) GenerateCertificateSigningRequest(ctx context.Context, useIPAddressAsCommonName bool) (string, error) {
req := types.GenerateCertificateSigningRequest{
This: m.Reference(),
UseIpAddressAsCommonName: useIPAddressAsCommonName,
}
res, err := methods.GenerateCertificateSigningRequest(ctx, m.Client(), &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// GenerateCertificateSigningRequestByDn requests the host system to generate a certificate-signing request (CSR) for itself.
// Alternative version similar to GenerateCertificateSigningRequest but takes a Distinguished Name (DN) as a parameter.
func (m HostCertificateManager) GenerateCertificateSigningRequestByDn(ctx context.Context, distinguishedName string) (string, error) {
req := types.GenerateCertificateSigningRequestByDn{
This: m.Reference(),
DistinguishedName: distinguishedName,
}
res, err := methods.GenerateCertificateSigningRequestByDn(ctx, m.Client(), &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// InstallServerCertificate imports the given SSL certificate to the host system.
func (m HostCertificateManager) InstallServerCertificate(ctx context.Context, cert string) error {
req := types.InstallServerCertificate{
This: m.Reference(),
Cert: cert,
}
_, err := methods.InstallServerCertificate(ctx, m.Client(), &req)
if err != nil {
return err
}
// NotifyAffectedService is internal, not exposing as we don't have a use case other than with InstallServerCertificate
// Without this call, hostd needs to be restarted to use the updated certificate
// Note: using Refresh as it has the same struct/signature, we just need to use different xml name tags
body := struct {
Req *types.Refresh `xml:"urn:vim25 NotifyAffectedServices,omitempty"`
Res *types.RefreshResponse `xml:"urn:vim25 NotifyAffectedServicesResponse,omitempty"`
methods.RefreshBody
}{
Req: &types.Refresh{This: m.Reference()},
}
err = m.Client().RoundTrip(ctx, &body, &body)
if err != nil && fault.Is(err, &types.MethodNotFound{}) {
return nil
}
return err
}
// ListCACertificateRevocationLists returns the SSL CRLs of Certificate Authorities that are trusted by the host system.
func (m HostCertificateManager) ListCACertificateRevocationLists(ctx context.Context) ([]string, error) {
req := types.ListCACertificateRevocationLists{
This: m.Reference(),
}
res, err := methods.ListCACertificateRevocationLists(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// ListCACertificates returns the SSL certificates of Certificate Authorities that are trusted by the host system.
func (m HostCertificateManager) ListCACertificates(ctx context.Context) ([]string, error) {
req := types.ListCACertificates{
This: m.Reference(),
}
res, err := methods.ListCACertificates(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// ReplaceCACertificatesAndCRLs replaces the trusted CA certificates and CRL used by the host system.
// These determine whether the server can verify the identity of an external entity.
func (m HostCertificateManager) ReplaceCACertificatesAndCRLs(ctx context.Context, caCert []string, caCrl []string) error {
req := types.ReplaceCACertificatesAndCRLs{
This: m.Reference(),
CaCert: caCert,
CaCrl: caCrl,
}
_, err := methods.ReplaceCACertificatesAndCRLs(ctx, m.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/authorization_manager_internal.go | vendor/github.com/vmware/govmomi/object/authorization_manager_internal.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type DisabledMethodRequest struct {
Method string `xml:"method"`
Reason string `xml:"reasonId"`
}
type disableMethodsRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Entity []types.ManagedObjectReference `xml:"entity"`
Method []DisabledMethodRequest `xml:"method"`
Source string `xml:"sourceId"`
Scope bool `xml:"sessionScope,omitempty"`
}
type disableMethodsBody struct {
Req *disableMethodsRequest `xml:"urn:internalvim25 DisableMethods,omitempty"`
Res any `xml:"urn:vim25 DisableMethodsResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *disableMethodsBody) Fault() *soap.Fault { return b.Err }
func (m AuthorizationManager) DisableMethods(ctx context.Context, entity []types.ManagedObjectReference, method []DisabledMethodRequest, source string) error {
var reqBody, resBody disableMethodsBody
reqBody.Req = &disableMethodsRequest{
This: m.Reference(),
Entity: entity,
Method: method,
Source: source,
}
return m.Client().RoundTrip(ctx, &reqBody, &resBody)
}
type enableMethodsRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Entity []types.ManagedObjectReference `xml:"entity"`
Method []string `xml:"method"`
Source string `xml:"sourceId"`
}
type enableMethodsBody struct {
Req *enableMethodsRequest `xml:"urn:internalvim25 EnableMethods,omitempty"`
Res any `xml:"urn:vim25 EnableMethodsResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *enableMethodsBody) Fault() *soap.Fault { return b.Err }
func (m AuthorizationManager) EnableMethods(ctx context.Context, entity []types.ManagedObjectReference, method []string, source string) error {
var reqBody, resBody enableMethodsBody
reqBody.Req = &enableMethodsRequest{
This: m.Reference(),
Entity: entity,
Method: method,
Source: source,
}
return m.Client().RoundTrip(ctx, &reqBody, &resBody)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/types.go | vendor/github.com/vmware/govmomi/object/types.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type Reference interface {
Reference() types.ManagedObjectReference
}
func NewReference(c *vim25.Client, e types.ManagedObjectReference) Reference {
switch e.Type {
case "Folder":
return NewFolder(c, e)
case "StoragePod":
return &StoragePod{
NewFolder(c, e),
}
case "Datacenter":
return NewDatacenter(c, e)
case "VirtualMachine":
return NewVirtualMachine(c, e)
case "VirtualApp":
return &VirtualApp{
NewResourcePool(c, e),
}
case "ComputeResource":
return NewComputeResource(c, e)
case "ClusterComputeResource":
return NewClusterComputeResource(c, e)
case "HostSystem":
return NewHostSystem(c, e)
case "Network":
return NewNetwork(c, e)
case "OpaqueNetwork":
return NewOpaqueNetwork(c, e)
case "ResourcePool":
return NewResourcePool(c, e)
case "DistributedVirtualSwitch":
return NewDistributedVirtualSwitch(c, e)
case "VmwareDistributedVirtualSwitch":
return &VmwareDistributedVirtualSwitch{*NewDistributedVirtualSwitch(c, e)}
case "DistributedVirtualPortgroup":
return NewDistributedVirtualPortgroup(c, e)
case "Datastore":
return NewDatastore(c, e)
default:
panic("Unknown managed entity: " + e.Type)
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_storage_system.go | vendor/github.com/vmware/govmomi/object/host_storage_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"errors"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostStorageSystem struct {
Common
}
func NewHostStorageSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostStorageSystem {
return &HostStorageSystem{
Common: NewCommon(c, ref),
}
}
func (s HostStorageSystem) RetrieveDiskPartitionInfo(ctx context.Context, devicePath string) (*types.HostDiskPartitionInfo, error) {
req := types.RetrieveDiskPartitionInfo{
This: s.Reference(),
DevicePath: []string{devicePath},
}
res, err := methods.RetrieveDiskPartitionInfo(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil || len(res.Returnval) == 0 {
return nil, errors.New("no partition info")
}
return &res.Returnval[0], nil
}
func (s HostStorageSystem) ComputeDiskPartitionInfo(ctx context.Context, devicePath string, layout types.HostDiskPartitionLayout) (*types.HostDiskPartitionInfo, error) {
req := types.ComputeDiskPartitionInfo{
This: s.Reference(),
DevicePath: devicePath,
Layout: layout,
}
res, err := methods.ComputeDiskPartitionInfo(ctx, s.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (s HostStorageSystem) UpdateDiskPartitionInfo(ctx context.Context, devicePath string, spec types.HostDiskPartitionSpec) error {
req := types.UpdateDiskPartitions{
This: s.Reference(),
DevicePath: devicePath,
Spec: spec,
}
_, err := methods.UpdateDiskPartitions(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) RescanAllHba(ctx context.Context) error {
req := types.RescanAllHba{
This: s.Reference(),
}
_, err := methods.RescanAllHba(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) Refresh(ctx context.Context) error {
req := types.RefreshStorageSystem{
This: s.Reference(),
}
_, err := methods.RefreshStorageSystem(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) RescanVmfs(ctx context.Context) error {
req := types.RescanVmfs{
This: s.Reference(),
}
_, err := methods.RescanVmfs(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) MarkAsSsd(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsSsd_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsSsd_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) MarkAsNonSsd(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsNonSsd_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsNonSsd_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) MarkAsLocal(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsLocal_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsLocal_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) MarkAsNonLocal(ctx context.Context, uuid string) (*Task, error) {
req := types.MarkAsNonLocal_Task{
This: s.Reference(),
ScsiDiskUuid: uuid,
}
res, err := methods.MarkAsNonLocal_Task(ctx, s.c, &req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
func (s HostStorageSystem) AttachScsiLun(ctx context.Context, uuid string) error {
req := types.AttachScsiLun{
This: s.Reference(),
LunUuid: uuid,
}
_, err := methods.AttachScsiLun(ctx, s.c, &req)
return err
}
func (s HostStorageSystem) QueryUnresolvedVmfsVolumes(ctx context.Context) ([]types.HostUnresolvedVmfsVolume, error) {
req := &types.QueryUnresolvedVmfsVolume{
This: s.Reference(),
}
res, err := methods.QueryUnresolvedVmfsVolume(ctx, s.Client(), req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostStorageSystem) UnmountVmfsVolume(ctx context.Context, vmfsUuid string) error {
req := &types.UnmountVmfsVolume{
This: s.Reference(),
VmfsUuid: vmfsUuid,
}
_, err := methods.UnmountVmfsVolume(ctx, s.Client(), req)
if err != nil {
return err
}
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/datastore_file_manager.go | vendor/github.com/vmware/govmomi/object/datastore_file_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"log"
"path"
"strings"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/soap"
)
// DatastoreFileManager combines FileManager and VirtualDiskManager to manage files on a Datastore
type DatastoreFileManager struct {
Datacenter *Datacenter
Datastore *Datastore
FileManager *FileManager
VirtualDiskManager *VirtualDiskManager
Force bool
DatacenterTarget *Datacenter
}
// NewFileManager creates a new instance of DatastoreFileManager
func (d Datastore) NewFileManager(dc *Datacenter, force bool) *DatastoreFileManager {
c := d.Client()
m := &DatastoreFileManager{
Datacenter: dc,
Datastore: &d,
FileManager: NewFileManager(c),
VirtualDiskManager: NewVirtualDiskManager(c),
Force: force,
DatacenterTarget: dc,
}
return m
}
func (m *DatastoreFileManager) WithProgress(ctx context.Context, s progress.Sinker) context.Context {
return context.WithValue(ctx, m, s)
}
func (m *DatastoreFileManager) wait(ctx context.Context, task *Task) error {
var logger progress.Sinker
if s, ok := ctx.Value(m).(progress.Sinker); ok {
logger = s
}
_, err := task.WaitForResult(ctx, logger)
return err
}
// Delete dispatches to the appropriate Delete method based on file name extension
func (m *DatastoreFileManager) Delete(ctx context.Context, name string) error {
switch path.Ext(name) {
case ".vmdk":
return m.DeleteVirtualDisk(ctx, name)
default:
return m.DeleteFile(ctx, name)
}
}
// DeleteFile calls FileManager.DeleteDatastoreFile
func (m *DatastoreFileManager) DeleteFile(ctx context.Context, name string) error {
p := m.Path(name)
task, err := m.FileManager.DeleteDatastoreFile(ctx, p.String(), m.Datacenter)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// DeleteVirtualDisk calls VirtualDiskManager.DeleteVirtualDisk
// Regardless of the Datastore type, DeleteVirtualDisk will fail if 'ddb.deletable=false',
// so if Force=true this method attempts to set 'ddb.deletable=true' before starting the delete task.
func (m *DatastoreFileManager) DeleteVirtualDisk(ctx context.Context, name string) error {
p := m.Path(name)
var merr error
if m.Force {
merr = m.markDiskAsDeletable(ctx, p)
}
task, err := m.VirtualDiskManager.DeleteVirtualDisk(ctx, p.String(), m.Datacenter)
if err != nil {
log.Printf("markDiskAsDeletable(%s): %s", p, merr)
return err
}
return m.wait(ctx, task)
}
// CopyFile calls FileManager.CopyDatastoreFile
func (m *DatastoreFileManager) CopyFile(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
task, err := m.FileManager.CopyDatastoreFile(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// Copy dispatches to the appropriate FileManager or VirtualDiskManager Copy method based on file name extension
func (m *DatastoreFileManager) Copy(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
f := m.FileManager.CopyDatastoreFile
if srcp.IsVMDK() {
// types.VirtualDiskSpec=nil as it is not implemented by vCenter
f = func(ctx context.Context, src string, srcDC *Datacenter, dst string, dstDC *Datacenter, force bool) (*Task, error) {
return m.VirtualDiskManager.CopyVirtualDisk(ctx, src, srcDC, dst, dstDC, nil, force)
}
}
task, err := f(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// MoveFile calls FileManager.MoveDatastoreFile
func (m *DatastoreFileManager) MoveFile(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
task, err := m.FileManager.MoveDatastoreFile(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// Move dispatches to the appropriate FileManager or VirtualDiskManager Move method based on file name extension
func (m *DatastoreFileManager) Move(ctx context.Context, src string, dst string) error {
srcp := m.Path(src)
dstp := m.Path(dst)
f := m.FileManager.MoveDatastoreFile
if srcp.IsVMDK() {
f = m.VirtualDiskManager.MoveVirtualDisk
}
task, err := f(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
// Path converts path name to a DatastorePath
func (m *DatastoreFileManager) Path(name string) *DatastorePath {
var p DatastorePath
if !p.FromString(name) {
p.Path = name
p.Datastore = m.Datastore.Name()
}
return &p
}
func (m *DatastoreFileManager) markDiskAsDeletable(ctx context.Context, path *DatastorePath) error {
r, _, err := m.Datastore.Download(ctx, path.Path, &soap.DefaultDownload)
if err != nil {
return err
}
defer r.Close()
hasFlag := false
buf := new(bytes.Buffer)
s := bufio.NewScanner(&io.LimitedReader{R: r, N: 2048}) // should be only a few hundred bytes, limit to be sure
for s.Scan() {
line := s.Text()
if strings.HasPrefix(line, "ddb.deletable") {
hasFlag = true
continue
}
fmt.Fprintln(buf, line)
}
if err := s.Err(); err != nil {
return err // any error other than EOF
}
if !hasFlag {
return nil // already deletable, so leave as-is
}
// rewrite the .vmdk with ddb.deletable flag removed (the default is true)
return m.Datastore.Upload(ctx, buf, path.Path, &soap.DefaultUpload)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/vm_compatability_checker.go | vendor/github.com/vmware/govmomi/object/vm_compatability_checker.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
// VmCompatibilityChecker models the CompatibilityChecker, a singleton managed
// object that can answer questions about compatibility of a virtual machine
// with a host.
//
// For more information, see:
// https://dp-downloads.broadcom.com/api-content/apis/API_VWSA_001/8.0U3/html/ReferenceGuides/vim.vm.check.CompatibilityChecker.html
type VmCompatibilityChecker struct {
Common
}
func NewVmCompatibilityChecker(c *vim25.Client) *VmCompatibilityChecker {
return &VmCompatibilityChecker{
Common: NewCommon(c, *c.ServiceContent.VmCompatibilityChecker),
}
}
func (c VmCompatibilityChecker) CheckCompatibility(
ctx context.Context,
vm types.ManagedObjectReference,
host *types.ManagedObjectReference,
pool *types.ManagedObjectReference,
testTypes ...types.CheckTestType) ([]types.CheckResult, error) {
req := types.CheckCompatibility_Task{
This: c.Reference(),
Vm: vm,
Host: host,
Pool: pool,
TestType: checkTestTypesToStrings(testTypes),
}
res, err := methods.CheckCompatibility_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
ti, err := NewTask(c.c, res.Returnval).WaitForResult(ctx)
if err != nil {
return nil, err
}
return ti.Result.(types.ArrayOfCheckResult).CheckResult, nil
}
func (c VmCompatibilityChecker) CheckVmConfig(
ctx context.Context,
spec types.VirtualMachineConfigSpec,
vm *types.ManagedObjectReference,
host *types.ManagedObjectReference,
pool *types.ManagedObjectReference,
testTypes ...types.CheckTestType) ([]types.CheckResult, error) {
req := types.CheckVmConfig_Task{
This: c.Reference(),
Spec: spec,
Vm: vm,
Host: host,
Pool: pool,
TestType: checkTestTypesToStrings(testTypes),
}
res, err := methods.CheckVmConfig_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
ti, err := NewTask(c.c, res.Returnval).WaitForResult(ctx)
if err != nil {
return nil, err
}
return ti.Result.(types.ArrayOfCheckResult).CheckResult, nil
}
func checkTestTypesToStrings(testTypes []types.CheckTestType) []string {
if len(testTypes) == 0 {
return nil
}
s := make([]string, len(testTypes))
for i := range testTypes {
s[i] = string(testTypes[i])
}
return s
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/virtual_disk_manager.go | vendor/github.com/vmware/govmomi/object/virtual_disk_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type VirtualDiskManager struct {
Common
}
func NewVirtualDiskManager(c *vim25.Client) *VirtualDiskManager {
m := VirtualDiskManager{
Common: NewCommon(c, *c.ServiceContent.VirtualDiskManager),
}
return &m
}
// CopyVirtualDisk copies a virtual disk, performing conversions as specified in the spec.
func (m VirtualDiskManager) CopyVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
destSpec types.BaseVirtualDiskSpec, force bool) (*Task, error) {
req := types.CopyVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
DestSpec: destSpec,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.CopyVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// CreateVirtualDisk creates a new virtual disk.
func (m VirtualDiskManager) CreateVirtualDisk(
ctx context.Context,
name string, datacenter *Datacenter,
spec types.BaseVirtualDiskSpec) (*Task, error) {
req := types.CreateVirtualDisk_Task{
This: m.Reference(),
Name: name,
Spec: spec,
}
if datacenter != nil {
ref := datacenter.Reference()
req.Datacenter = &ref
}
res, err := methods.CreateVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// ExtendVirtualDisk extends an existing virtual disk.
func (m VirtualDiskManager) ExtendVirtualDisk(
ctx context.Context,
name string, datacenter *Datacenter,
capacityKb int64,
eagerZero *bool) (*Task, error) {
req := types.ExtendVirtualDisk_Task{
This: m.Reference(),
Name: name,
NewCapacityKb: capacityKb,
EagerZero: eagerZero,
}
if datacenter != nil {
ref := datacenter.Reference()
req.Datacenter = &ref
}
res, err := methods.ExtendVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// MoveVirtualDisk moves a virtual disk.
func (m VirtualDiskManager) MoveVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
force bool) (*Task, error) {
req := types.MoveVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.MoveVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// DeleteVirtualDisk deletes a virtual disk.
func (m VirtualDiskManager) DeleteVirtualDisk(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.DeleteVirtualDisk_Task{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.DeleteVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// InflateVirtualDisk inflates a virtual disk.
func (m VirtualDiskManager) InflateVirtualDisk(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.InflateVirtualDisk_Task{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.InflateVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// ShrinkVirtualDisk shrinks a virtual disk.
func (m VirtualDiskManager) ShrinkVirtualDisk(ctx context.Context, name string, dc *Datacenter, copy *bool) (*Task, error) {
req := types.ShrinkVirtualDisk_Task{
This: m.Reference(),
Name: name,
Copy: copy,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.ShrinkVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// Queries virtual disk uuid
func (m VirtualDiskManager) QueryVirtualDiskUuid(ctx context.Context, name string, dc *Datacenter) (string, error) {
req := types.QueryVirtualDiskUuid{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.QueryVirtualDiskUuid(ctx, m.c, &req)
if err != nil {
return "", err
}
if res == nil {
return "", nil
}
return res.Returnval, nil
}
func (m VirtualDiskManager) SetVirtualDiskUuid(ctx context.Context, name string, dc *Datacenter, uuid string) error {
req := types.SetVirtualDiskUuid{
This: m.Reference(),
Name: name,
Uuid: uuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
_, err := methods.SetVirtualDiskUuid(ctx, m.c, &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/virtual_disk_manager_internal.go | vendor/github.com/vmware/govmomi/object/virtual_disk_manager_internal.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/internal"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type VirtualDiskInfo = internal.VirtualDiskInfo
func (m VirtualDiskManager) QueryVirtualDiskInfo(ctx context.Context, name string, dc *Datacenter, includeParents bool) ([]VirtualDiskInfo, error) {
req := internal.QueryVirtualDiskInfoTaskRequest{
This: m.Reference(),
Name: name,
IncludeParents: includeParents,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := internal.QueryVirtualDiskInfoTask(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
info, err := NewTask(m.Client(), res.Returnval).WaitForResult(ctx, nil)
if err != nil {
return nil, err
}
return info.Result.(internal.ArrayOfVirtualDiskInfo).VirtualDiskInfo, nil
}
type createChildDiskTaskRequest struct {
This types.ManagedObjectReference `xml:"_this"`
ChildName string `xml:"childName"`
ChildDatacenter *types.ManagedObjectReference `xml:"childDatacenter,omitempty"`
ParentName string `xml:"parentName"`
ParentDatacenter *types.ManagedObjectReference `xml:"parentDatacenter,omitempty"`
IsLinkedClone bool `xml:"isLinkedClone"`
}
type createChildDiskTaskResponse struct {
Returnval types.ManagedObjectReference `xml:"returnval"`
}
type createChildDiskTaskBody struct {
Req *createChildDiskTaskRequest `xml:"urn:internalvim25 CreateChildDisk_Task,omitempty"`
Res *createChildDiskTaskResponse `xml:"urn:vim25 CreateChildDisk_TaskResponse,omitempty"`
InternalRes *createChildDiskTaskResponse `xml:"urn:internalvim25 CreateChildDisk_TaskResponse,omitempty"`
Err *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *createChildDiskTaskBody) Fault() *soap.Fault { return b.Err }
func createChildDiskTask(ctx context.Context, r soap.RoundTripper, req *createChildDiskTaskRequest) (*createChildDiskTaskResponse, error) {
var reqBody, resBody createChildDiskTaskBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
if resBody.Res != nil {
return resBody.Res, nil // vim-version <= 6.5
}
return resBody.InternalRes, nil // vim-version >= 6.7
}
func (m VirtualDiskManager) CreateChildDisk(ctx context.Context, parent string, pdc *Datacenter, name string, dc *Datacenter, linked bool) (*Task, error) {
req := createChildDiskTaskRequest{
This: m.Reference(),
ChildName: name,
ParentName: parent,
IsLinkedClone: linked,
}
if dc != nil {
ref := dc.Reference()
req.ChildDatacenter = &ref
}
if pdc != nil {
ref := pdc.Reference()
req.ParentDatacenter = &ref
}
res, err := createChildDiskTask(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(m.Client(), res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/vmware_distributed_virtual_switch.go | vendor/github.com/vmware/govmomi/object/vmware_distributed_virtual_switch.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
type VmwareDistributedVirtualSwitch struct {
DistributedVirtualSwitch
}
func (s VmwareDistributedVirtualSwitch) GetInventoryPath() string {
return s.InventoryPath
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/option_value_list.go | vendor/github.com/vmware/govmomi/object/option_value_list.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"fmt"
"reflect"
"slices"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
// OptionValueList simplifies manipulation of properties that are arrays of
// types.BaseOptionValue, such as ExtraConfig.
type OptionValueList []types.BaseOptionValue
// OptionValueListFromMap returns a new OptionValueList object from the provided
// map.
func OptionValueListFromMap[T any](in map[string]T) OptionValueList {
if len(in) == 0 {
return nil
}
var (
i int
out = make(OptionValueList, len(in))
)
for k, v := range in {
out[i] = &types.OptionValue{Key: k, Value: v}
i++
}
return out
}
// IsTrue returns true if the specified key exists with an empty value or value
// equal to 1, "1", "on", "t", true, "true", "y", or "yes".
// All string comparisons are case-insensitive.
func (ov OptionValueList) IsTrue(key string) bool {
return ov.isTrueOrFalse(key, true, 1, "", "1", "on", "t", "true", "y", "yes")
}
// IsFalse returns true if the specified key exists and has a value equal to
// 0, "0", "f", false, "false", "n", "no", or "off".
// All string comparisons are case-insensitive.
func (ov OptionValueList) IsFalse(key string) bool {
return ov.isTrueOrFalse(key, false, 0, "0", "f", "false", "n", "no", "off")
}
func (ov OptionValueList) isTrueOrFalse(
key string,
boolVal bool,
numVal int,
strVals ...string) bool {
val, ok := ov.Get(key)
if !ok {
return false
}
switch tval := val.(type) {
case string:
return slices.Contains(strVals, strings.ToLower(tval))
case bool:
return tval == boolVal
case uint:
return tval == uint(numVal)
case uint8:
return tval == uint8(numVal)
case uint16:
return tval == uint16(numVal)
case uint32:
return tval == uint32(numVal)
case uint64:
return tval == uint64(numVal)
case int:
return tval == int(numVal)
case int8:
return tval == int8(numVal)
case int16:
return tval == int16(numVal)
case int32:
return tval == int32(numVal)
case int64:
return tval == int64(numVal)
case float32:
return tval == float32(numVal)
case float64:
return tval == float64(numVal)
}
return false
}
// Get returns the value if exists, otherwise nil is returned. The second return
// value is a flag indicating whether the value exists or nil was the actual
// value.
func (ov OptionValueList) Get(key string) (any, bool) {
if ov == nil {
return nil, false
}
for i := range ov {
if optVal := ov[i].GetOptionValue(); optVal != nil {
if optVal.Key == key {
return optVal.Value, true
}
}
}
return nil, false
}
// GetString returns the value as a string if the value exists.
func (ov OptionValueList) GetString(key string) (string, bool) {
if ov == nil {
return "", false
}
for i := range ov {
if optVal := ov[i].GetOptionValue(); optVal != nil {
if optVal.Key == key {
return getOptionValueAsString(optVal.Value), true
}
}
}
return "", false
}
// Additions returns a diff that includes only the elements from the provided
// list that do not already exist.
func (ov OptionValueList) Additions(in ...types.BaseOptionValue) OptionValueList {
return ov.diff(in, true)
}
// Diff returns a diff that includes the elements from the provided list that do
// not already exist or have different values.
func (ov OptionValueList) Diff(in ...types.BaseOptionValue) OptionValueList {
return ov.diff(in, false)
}
func (ov OptionValueList) diff(in OptionValueList, addOnly bool) OptionValueList {
if ov == nil && in == nil {
return nil
}
var (
out OptionValueList
leftOptVals = ov.Map()
)
for i := range in {
if rightOptVal := in[i].GetOptionValue(); rightOptVal != nil {
k, v := rightOptVal.Key, rightOptVal.Value
if ov == nil {
out = append(out, &types.OptionValue{Key: k, Value: v})
} else if leftOptVal, ok := leftOptVals[k]; !ok {
out = append(out, &types.OptionValue{Key: k, Value: v})
} else if !addOnly && v != leftOptVal {
out = append(out, &types.OptionValue{Key: k, Value: v})
}
}
}
if len(out) == 0 {
return nil
}
return out
}
// Join combines this list with the provided one and returns the result, joining
// the two lists on their shared keys.
// Please note, Join(left, right) means the values from right will be appended
// to left, without overwriting any values that have shared keys. To overwrite
// the shared keys in left from right, use Join(right, left) instead.
func (ov OptionValueList) Join(in ...types.BaseOptionValue) OptionValueList {
var (
out OptionValueList
outKeys map[string]struct{}
)
// Init the out slice from the left side.
if len(ov) > 0 {
outKeys = map[string]struct{}{}
for i := range ov {
if optVal := ov[i].GetOptionValue(); optVal != nil {
kv := &types.OptionValue{Key: optVal.Key, Value: optVal.Value}
out = append(out, kv)
outKeys[optVal.Key] = struct{}{}
}
}
}
// Join the values from the right side.
for i := range in {
if rightOptVal := in[i].GetOptionValue(); rightOptVal != nil {
k, v := rightOptVal.Key, rightOptVal.Value
if _, ok := outKeys[k]; !ok {
out = append(out, &types.OptionValue{Key: k, Value: v})
}
}
}
if len(out) == 0 {
return nil
}
return out
}
// Map returns the list of option values as a map. A nil value is returned if
// the list is empty.
func (ov OptionValueList) Map() map[string]any {
if len(ov) == 0 {
return nil
}
out := map[string]any{}
for i := range ov {
if optVal := ov[i].GetOptionValue(); optVal != nil {
out[optVal.Key] = optVal.Value
}
}
if len(out) == 0 {
return nil
}
return out
}
// StringMap returns the list of option values as a map where the values are
// strings. A nil value is returned if the list is empty.
func (ov OptionValueList) StringMap() map[string]string {
if len(ov) == 0 {
return nil
}
out := map[string]string{}
for i := range ov {
if optVal := ov[i].GetOptionValue(); optVal != nil {
out[optVal.Key] = getOptionValueAsString(optVal.Value)
}
}
if len(out) == 0 {
return nil
}
return out
}
func getOptionValueAsString(val any) string {
switch tval := val.(type) {
case string:
return tval
default:
if rv := reflect.ValueOf(val); rv.Kind() == reflect.Pointer {
if rv.IsNil() {
return ""
}
return fmt.Sprintf("%v", rv.Elem().Interface())
}
return fmt.Sprintf("%v", tval)
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_certificate_info.go | vendor/github.com/vmware/govmomi/object/host_certificate_info.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"io"
"net/url"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// HostCertificateInfo provides helpers for types.HostCertificateManagerCertificateInfo
type HostCertificateInfo struct {
types.HostCertificateManagerCertificateInfo
ThumbprintSHA1 string `json:"thumbprintSHA1"`
ThumbprintSHA256 string `json:"thumbprintSHA256"`
Err error `json:"err"`
Certificate *x509.Certificate `json:"-"`
subjectName *pkix.Name
issuerName *pkix.Name
}
// FromCertificate converts x509.Certificate to HostCertificateInfo
func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo {
info.Certificate = cert
info.subjectName = &cert.Subject
info.issuerName = &cert.Issuer
info.Issuer = info.fromName(info.issuerName)
info.NotBefore = &cert.NotBefore
info.NotAfter = &cert.NotAfter
info.Subject = info.fromName(info.subjectName)
info.ThumbprintSHA1 = soap.ThumbprintSHA1(cert)
info.ThumbprintSHA256 = soap.ThumbprintSHA256(cert)
if info.Status == "" {
info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusUnknown)
}
return info
}
func (info *HostCertificateInfo) FromPEM(cert []byte) (*HostCertificateInfo, error) {
block, _ := pem.Decode(cert)
if block == nil {
return nil, errors.New("failed to pem.Decode cert")
}
x, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return info.FromCertificate(x), nil
}
// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState. If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error {
addr := u.Host
if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
addr += ":443"
}
conn, err := tls.Dial("tcp", addr, config)
if err != nil {
if !soap.IsCertificateUntrusted(err) {
return err
}
info.Err = err
conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return err
}
} else {
info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
}
state := conn.ConnectionState()
_ = conn.Close()
info.FromCertificate(state.PeerCertificates[0])
return nil
}
var emailAddressOID = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}
func (info *HostCertificateInfo) fromName(name *pkix.Name) string {
var attrs []string
oids := map[string]string{
emailAddressOID.String(): "emailAddress",
}
for _, attr := range name.Names {
if key, ok := oids[attr.Type.String()]; ok {
attrs = append(attrs, fmt.Sprintf("%s=%s", key, attr.Value))
}
}
attrs = append(attrs, fmt.Sprintf("CN=%s", name.CommonName))
add := func(key string, vals []string) {
for _, val := range vals {
attrs = append(attrs, fmt.Sprintf("%s=%s", key, val))
}
}
elts := []struct {
key string
val []string
}{
{"OU", name.OrganizationalUnit},
{"O", name.Organization},
{"L", name.Locality},
{"ST", name.Province},
{"C", name.Country},
}
for _, elt := range elts {
add(elt.key, elt.val)
}
return strings.Join(attrs, ",")
}
func (info *HostCertificateInfo) toName(s string) *pkix.Name {
var name pkix.Name
for _, pair := range strings.Split(s, ",") {
attr := strings.SplitN(pair, "=", 2)
if len(attr) != 2 {
continue
}
v := attr[1]
switch strings.ToLower(attr[0]) {
case "cn":
name.CommonName = v
case "ou":
name.OrganizationalUnit = append(name.OrganizationalUnit, v)
case "o":
name.Organization = append(name.Organization, v)
case "l":
name.Locality = append(name.Locality, v)
case "st":
name.Province = append(name.Province, v)
case "c":
name.Country = append(name.Country, v)
case "emailaddress":
name.Names = append(name.Names, pkix.AttributeTypeAndValue{Type: emailAddressOID, Value: v})
}
}
return &name
}
// SubjectName parses Subject into a pkix.Name
func (info *HostCertificateInfo) SubjectName() *pkix.Name {
if info.subjectName != nil {
return info.subjectName
}
return info.toName(info.Subject)
}
// IssuerName parses Issuer into a pkix.Name
func (info *HostCertificateInfo) IssuerName() *pkix.Name {
if info.issuerName != nil {
return info.issuerName
}
return info.toName(info.Issuer)
}
// Write outputs info similar to the Chrome Certificate Viewer.
func (info *HostCertificateInfo) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
s := func(val string) string {
if val != "" {
return val
}
return "<Not Part Of Certificate>"
}
ss := func(val []string) string {
return s(strings.Join(val, ","))
}
name := func(n *pkix.Name) {
fmt.Fprintf(tw, " Common Name (CN):\t%s\n", s(n.CommonName))
fmt.Fprintf(tw, " Organization (O):\t%s\n", ss(n.Organization))
fmt.Fprintf(tw, " Organizational Unit (OU):\t%s\n", ss(n.OrganizationalUnit))
}
status := info.Status
if info.Err != nil {
status = fmt.Sprintf("ERROR %s", info.Err)
}
fmt.Fprintf(tw, "Certificate Status:\t%s\n", status)
fmt.Fprintln(tw, "Issued To:\t")
name(info.SubjectName())
fmt.Fprintln(tw, "Issued By:\t")
name(info.IssuerName())
fmt.Fprintln(tw, "Validity Period:\t")
fmt.Fprintf(tw, " Issued On:\t%s\n", info.NotBefore)
fmt.Fprintf(tw, " Expires On:\t%s\n", info.NotAfter)
if info.ThumbprintSHA1 != "" {
fmt.Fprintln(tw, "Thumbprints:\t")
if info.ThumbprintSHA256 != "" {
fmt.Fprintf(tw, " SHA-256 Thumbprint:\t%s\n", info.ThumbprintSHA256)
}
fmt.Fprintf(tw, " SHA-1 Thumbprint:\t%s\n", info.ThumbprintSHA1)
}
return tw.Flush()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/storage_resource_manager.go | vendor/github.com/vmware/govmomi/object/storage_resource_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type StorageResourceManager struct {
Common
}
func NewStorageResourceManager(c *vim25.Client) *StorageResourceManager {
sr := StorageResourceManager{
Common: NewCommon(c, *c.ServiceContent.StorageResourceManager),
}
return &sr
}
func (sr StorageResourceManager) ApplyStorageDrsRecommendation(ctx context.Context, key []string) (*Task, error) {
req := types.ApplyStorageDrsRecommendation_Task{
This: sr.Reference(),
Key: key,
}
res, err := methods.ApplyStorageDrsRecommendation_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) ApplyStorageDrsRecommendationToPod(ctx context.Context, pod *StoragePod, key string) (*Task, error) {
req := types.ApplyStorageDrsRecommendationToPod_Task{
This: sr.Reference(),
Key: key,
}
if pod != nil {
req.Pod = pod.Reference()
}
res, err := methods.ApplyStorageDrsRecommendationToPod_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) CancelStorageDrsRecommendation(ctx context.Context, key []string) error {
req := types.CancelStorageDrsRecommendation{
This: sr.Reference(),
Key: key,
}
_, err := methods.CancelStorageDrsRecommendation(ctx, sr.c, &req)
return err
}
func (sr StorageResourceManager) ConfigureDatastoreIORM(ctx context.Context, datastore *Datastore, spec types.StorageIORMConfigSpec, key string) (*Task, error) {
req := types.ConfigureDatastoreIORM_Task{
This: sr.Reference(),
Spec: spec,
}
if datastore != nil {
req.Datastore = datastore.Reference()
}
res, err := methods.ConfigureDatastoreIORM_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) ConfigureStorageDrsForPod(ctx context.Context, pod *StoragePod, spec types.StorageDrsConfigSpec, modify bool) (*Task, error) {
req := types.ConfigureStorageDrsForPod_Task{
This: sr.Reference(),
Spec: spec,
Modify: modify,
}
if pod != nil {
req.Pod = pod.Reference()
}
res, err := methods.ConfigureStorageDrsForPod_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) QueryDatastorePerformanceSummary(ctx context.Context, datastore *Datastore) ([]types.StoragePerformanceSummary, error) {
req := types.QueryDatastorePerformanceSummary{
This: sr.Reference(),
}
if datastore != nil {
req.Datastore = datastore.Reference()
}
res, err := methods.QueryDatastorePerformanceSummary(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (sr StorageResourceManager) QueryIORMConfigOption(ctx context.Context, host *HostSystem) (*types.StorageIORMConfigOption, error) {
req := types.QueryIORMConfigOption{
This: sr.Reference(),
}
if host != nil {
req.Host = host.Reference()
}
res, err := methods.QueryIORMConfigOption(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sr StorageResourceManager) RecommendDatastores(ctx context.Context, storageSpec types.StoragePlacementSpec) (*types.StoragePlacementResult, error) {
req := types.RecommendDatastores{
This: sr.Reference(),
StorageSpec: storageSpec,
}
res, err := methods.RecommendDatastores(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sr StorageResourceManager) RefreshStorageDrsRecommendation(ctx context.Context, pod *StoragePod) error {
req := types.RefreshStorageDrsRecommendation{
This: sr.Reference(),
}
if pod != nil {
req.Pod = pod.Reference()
}
_, err := methods.RefreshStorageDrsRecommendation(ctx, sr.c, &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_datastore_system.go | vendor/github.com/vmware/govmomi/object/host_datastore_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostDatastoreSystem struct {
Common
}
func NewHostDatastoreSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostDatastoreSystem {
return &HostDatastoreSystem{
Common: NewCommon(c, ref),
}
}
func (s HostDatastoreSystem) CreateLocalDatastore(ctx context.Context, name string, path string) (*Datastore, error) {
req := types.CreateLocalDatastore{
This: s.Reference(),
Name: name,
Path: path,
}
res, err := methods.CreateLocalDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) CreateNasDatastore(ctx context.Context, spec types.HostNasVolumeSpec) (*Datastore, error) {
req := types.CreateNasDatastore{
This: s.Reference(),
Spec: spec,
}
res, err := methods.CreateNasDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) CreateVmfsDatastore(ctx context.Context, spec types.VmfsDatastoreCreateSpec) (*Datastore, error) {
req := types.CreateVmfsDatastore{
This: s.Reference(),
Spec: spec,
}
res, err := methods.CreateVmfsDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) Remove(ctx context.Context, ds *Datastore) error {
req := types.RemoveDatastore{
This: s.Reference(),
Datastore: ds.Reference(),
}
_, err := methods.RemoveDatastore(ctx, s.Client(), &req)
if err != nil {
return err
}
return nil
}
func (s HostDatastoreSystem) QueryAvailableDisksForVmfs(ctx context.Context) ([]types.HostScsiDisk, error) {
req := types.QueryAvailableDisksForVmfs{
This: s.Reference(),
}
res, err := methods.QueryAvailableDisksForVmfs(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostDatastoreSystem) QueryVmfsDatastoreCreateOptions(ctx context.Context, devicePath string) ([]types.VmfsDatastoreOption, error) {
req := types.QueryVmfsDatastoreCreateOptions{
This: s.Reference(),
DevicePath: devicePath,
}
res, err := methods.QueryVmfsDatastoreCreateOptions(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostDatastoreSystem) ResignatureUnresolvedVmfsVolumes(ctx context.Context, devicePaths []string) (*Task, error) {
req := &types.ResignatureUnresolvedVmfsVolume_Task{
This: s.Reference(),
ResolutionSpec: types.HostUnresolvedVmfsResignatureSpec{
ExtentDevicePath: devicePaths,
},
}
res, err := methods.ResignatureUnresolvedVmfsVolume_Task(ctx, s.Client(), req)
if err != nil {
return nil, err
}
return NewTask(s.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_datastore_browser.go | vendor/github.com/vmware/govmomi/object/host_datastore_browser.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostDatastoreBrowser struct {
Common
}
func NewHostDatastoreBrowser(c *vim25.Client, ref types.ManagedObjectReference) *HostDatastoreBrowser {
return &HostDatastoreBrowser{
Common: NewCommon(c, ref),
}
}
func (b HostDatastoreBrowser) SearchDatastore(ctx context.Context, datastorePath string, searchSpec *types.HostDatastoreBrowserSearchSpec) (*Task, error) {
req := types.SearchDatastore_Task{
This: b.Reference(),
DatastorePath: datastorePath,
SearchSpec: searchSpec,
}
res, err := methods.SearchDatastore_Task(ctx, b.c, &req)
if err != nil {
return nil, err
}
return NewTask(b.c, res.Returnval), nil
}
func (b HostDatastoreBrowser) SearchDatastoreSubFolders(ctx context.Context, datastorePath string, searchSpec *types.HostDatastoreBrowserSearchSpec) (*Task, error) {
req := types.SearchDatastoreSubFolders_Task{
This: b.Reference(),
DatastorePath: datastorePath,
SearchSpec: searchSpec,
}
res, err := methods.SearchDatastoreSubFolders_Task(ctx, b.c, &req)
if err != nil {
return nil, err
}
return NewTask(b.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/compute_resource.go | vendor/github.com/vmware/govmomi/object/compute_resource.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"path"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ComputeResource struct {
Common
}
func NewComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ComputeResource {
return &ComputeResource{
Common: NewCommon(c, ref),
}
}
func (c ComputeResource) Hosts(ctx context.Context) ([]*HostSystem, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"host"}, &cr)
if err != nil {
return nil, err
}
if len(cr.Host) == 0 {
return nil, nil
}
var hs []mo.HostSystem
pc := property.DefaultCollector(c.Client())
err = pc.Retrieve(ctx, cr.Host, []string{"name"}, &hs)
if err != nil {
return nil, err
}
var hosts []*HostSystem
for _, h := range hs {
host := NewHostSystem(c.Client(), h.Reference())
host.InventoryPath = path.Join(c.InventoryPath, h.Name)
hosts = append(hosts, host)
}
return hosts, nil
}
func (c ComputeResource) Datastores(ctx context.Context) ([]*Datastore, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"datastore"}, &cr)
if err != nil {
return nil, err
}
var dss []*Datastore
for _, ref := range cr.Datastore {
ds := NewDatastore(c.c, ref)
dss = append(dss, ds)
}
return dss, nil
}
func (c ComputeResource) EnvironmentBrowser(ctx context.Context) (*EnvironmentBrowser, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"environmentBrowser"}, &cr)
if err != nil {
return nil, err
}
if cr.EnvironmentBrowser == nil {
return nil, fmt.Errorf("%s: nil environmentBrowser", c.Reference())
}
return NewEnvironmentBrowser(c.c, *cr.EnvironmentBrowser), nil
}
func (c ComputeResource) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"resourcePool"}, &cr)
if err != nil {
return nil, err
}
return NewResourcePool(c.c, *cr.ResourcePool), nil
}
func (c ComputeResource) Reconfigure(ctx context.Context, spec types.BaseComputeResourceConfigSpec, modify bool) (*Task, error) {
req := types.ReconfigureComputeResource_Task{
This: c.Reference(),
Spec: spec,
Modify: modify,
}
res, err := methods.ReconfigureComputeResource_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/virtual_device_list.go | vendor/github.com/vmware/govmomi/object/virtual_device_list.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"errors"
"fmt"
"math/rand"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
// Type values for use in BootOrder
const (
DeviceTypeNone = "-"
DeviceTypeCdrom = "cdrom"
DeviceTypeDisk = "disk"
DeviceTypeEthernet = "ethernet"
DeviceTypeFloppy = "floppy"
)
// VirtualDeviceList provides helper methods for working with a list of virtual devices.
type VirtualDeviceList []types.BaseVirtualDevice
// SCSIControllerTypes are used for adding a new SCSI controller to a VM.
func SCSIControllerTypes() VirtualDeviceList {
// Return a mutable list of SCSI controller types, initialized with defaults.
return VirtualDeviceList([]types.BaseVirtualDevice{
&types.VirtualLsiLogicController{},
&types.VirtualBusLogicController{},
&types.ParaVirtualSCSIController{},
&types.VirtualLsiLogicSASController{},
}).Select(func(device types.BaseVirtualDevice) bool {
c := device.(types.BaseVirtualSCSIController).GetVirtualSCSIController()
c.SharedBus = types.VirtualSCSISharingNoSharing
c.BusNumber = -1
return true
})
}
// EthernetCardTypes are used for adding a new ethernet card to a VM.
func EthernetCardTypes() VirtualDeviceList {
return VirtualDeviceList([]types.BaseVirtualDevice{
&types.VirtualE1000{},
&types.VirtualE1000e{},
&types.VirtualVmxnet2{},
&types.VirtualVmxnet3{},
&types.VirtualVmxnet3Vrdma{},
&types.VirtualPCNet32{},
&types.VirtualSriovEthernetCard{},
}).Select(func(device types.BaseVirtualDevice) bool {
c := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
c.GetVirtualDevice().Key = VirtualDeviceList{}.newRandomKey()
return true
})
}
// Select returns a new list containing all elements of the list for which the given func returns true.
func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList {
var found VirtualDeviceList
for _, device := range l {
if f(device) {
found = append(found, device)
}
}
return found
}
// SelectByType returns a new list with devices that are equal to or extend the given type.
func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList {
dtype := reflect.TypeOf(deviceType)
if dtype == nil {
return nil
}
dname := dtype.Elem().Name()
return l.Select(func(device types.BaseVirtualDevice) bool {
t := reflect.TypeOf(device)
if t == dtype {
return true
}
_, ok := t.Elem().FieldByName(dname)
return ok
})
}
// SelectByBackingInfo returns a new list with devices matching the given backing info.
// If the value of backing is nil, any device with a backing of the same type will be returned.
func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList {
t := reflect.TypeOf(backing)
return l.Select(func(device types.BaseVirtualDevice) bool {
db := device.GetVirtualDevice().Backing
if db == nil {
return false
}
if reflect.TypeOf(db) != t {
return false
}
if reflect.ValueOf(backing).IsNil() {
// selecting by backing type
return true
}
switch a := db.(type) {
case *types.VirtualEthernetCardNetworkBackingInfo:
b := backing.(*types.VirtualEthernetCardNetworkBackingInfo)
return a.DeviceName == b.DeviceName
case *types.VirtualEthernetCardDistributedVirtualPortBackingInfo:
b := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo)
return a.Port.SwitchUuid == b.Port.SwitchUuid &&
a.Port.PortgroupKey == b.Port.PortgroupKey
case *types.VirtualEthernetCardOpaqueNetworkBackingInfo:
b := backing.(*types.VirtualEthernetCardOpaqueNetworkBackingInfo)
return a.OpaqueNetworkId == b.OpaqueNetworkId
case *types.VirtualDiskFlatVer2BackingInfo:
b := backing.(*types.VirtualDiskFlatVer2BackingInfo)
if a.Parent != nil && b.Parent != nil {
return a.Parent.FileName == b.Parent.FileName
}
return a.FileName == b.FileName
case *types.VirtualSerialPortURIBackingInfo:
b := backing.(*types.VirtualSerialPortURIBackingInfo)
return a.ServiceURI == b.ServiceURI
case types.BaseVirtualDeviceFileBackingInfo:
b := backing.(types.BaseVirtualDeviceFileBackingInfo)
return a.GetVirtualDeviceFileBackingInfo().FileName == b.GetVirtualDeviceFileBackingInfo().FileName
case *types.VirtualPCIPassthroughVmiopBackingInfo:
b := backing.(*types.VirtualPCIPassthroughVmiopBackingInfo)
return a.Vgpu == b.Vgpu
case *types.VirtualPCIPassthroughDynamicBackingInfo:
b := backing.(*types.VirtualPCIPassthroughDynamicBackingInfo)
if b.CustomLabel != "" && b.CustomLabel != a.CustomLabel {
return false
}
if len(b.AllowedDevice) == 0 {
return true
}
for _, x := range a.AllowedDevice {
for _, y := range b.AllowedDevice {
if x.DeviceId == y.DeviceId && x.VendorId == y.VendorId {
return true
}
}
}
return false
default:
return false
}
})
}
// Find returns the device matching the given name.
func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice {
for _, device := range l {
if l.Name(device) == name {
return device
}
}
return nil
}
// FindByKey returns the device matching the given key.
func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice {
for _, device := range l {
if device.GetVirtualDevice().Key == key {
return device
}
}
return nil
}
// FindIDEController will find the named IDE controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an IDE controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualIDEController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not an IDE controller", name)
}
c := l.PickController((*types.VirtualIDEController)(nil))
if c == nil {
return nil, errors.New("no available IDE controller")
}
return c.(*types.VirtualIDEController), nil
}
// CreateIDEController creates a new IDE controller.
func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error) {
ide := &types.VirtualIDEController{}
ide.Key = l.NewKey()
return ide, nil
}
// FindSCSIController will find the named SCSI controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an SCSI controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(types.BaseVirtualSCSIController); ok {
return c.GetVirtualSCSIController(), nil
}
return nil, fmt.Errorf("%s is not an SCSI controller", name)
}
c := l.PickController((*types.VirtualSCSIController)(nil))
if c == nil {
return nil, errors.New("no available SCSI controller")
}
return c.(types.BaseVirtualSCSIController).GetVirtualSCSIController(), nil
}
// CreateSCSIController creates a new SCSI controller of type name if given, otherwise defaults to lsilogic.
func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error) {
ctypes := SCSIControllerTypes()
if name == "" || name == "scsi" {
name = ctypes.Type(ctypes[0])
} else if name == "virtualscsi" {
name = "pvscsi" // ovf VirtualSCSI mapping
}
found := ctypes.Select(func(device types.BaseVirtualDevice) bool {
return l.Type(device) == name
})
if len(found) == 0 {
return nil, fmt.Errorf("unknown SCSI controller type '%s'", name)
}
c, ok := found[0].(types.BaseVirtualSCSIController)
if !ok {
return nil, fmt.Errorf("invalid SCSI controller type '%s'", name)
}
scsi := c.GetVirtualSCSIController()
scsi.BusNumber = l.newSCSIBusNumber()
scsi.Key = l.NewKey()
scsi.ScsiCtlrUnitNumber = 7
return c.(types.BaseVirtualDevice), nil
}
var scsiBusNumbers = []int{0, 1, 2, 3}
// newSCSIBusNumber returns the bus number to use for adding a new SCSI bus device.
// -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newSCSIBusNumber() int32 {
var used []int
for _, d := range l.SelectByType((*types.VirtualSCSIController)(nil)) {
num := d.(types.BaseVirtualSCSIController).GetVirtualSCSIController().BusNumber
if num >= 0 {
used = append(used, int(num))
} // else caller is creating a new vm using SCSIControllerTypes
}
sort.Ints(used)
for i, n := range scsiBusNumbers {
if i == len(used) || n != used[i] {
return int32(n)
}
}
return -1
}
// FindNVMEController will find the named NVME controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an NVME controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindNVMEController(name string) (*types.VirtualNVMEController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualNVMEController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not an NVME controller", name)
}
c := l.PickController((*types.VirtualNVMEController)(nil))
if c == nil {
return nil, errors.New("no available NVME controller")
}
return c.(*types.VirtualNVMEController), nil
}
// CreateNVMEController creates a new NVMWE controller.
func (l VirtualDeviceList) CreateNVMEController() (types.BaseVirtualDevice, error) {
nvme := &types.VirtualNVMEController{}
nvme.BusNumber = l.newNVMEBusNumber()
nvme.Key = l.NewKey()
return nvme, nil
}
var nvmeBusNumbers = []int{0, 1, 2, 3}
// newNVMEBusNumber returns the bus number to use for adding a new NVME bus device.
// -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newNVMEBusNumber() int32 {
var used []int
for _, d := range l.SelectByType((*types.VirtualNVMEController)(nil)) {
num := d.(types.BaseVirtualController).GetVirtualController().BusNumber
if num >= 0 {
used = append(used, int(num))
} // else caller is creating a new vm using NVMEControllerTypes
}
sort.Ints(used)
for i, n := range nvmeBusNumbers {
if i == len(used) || n != used[i] {
return int32(n)
}
}
return -1
}
// FindSATAController will find the named SATA or AHCI controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not a SATA or AHCI controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindSATAController(name string) (types.BaseVirtualController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
switch c := d.(type) {
case *types.VirtualSATAController:
return c, nil
case *types.VirtualAHCIController:
return c, nil
default:
return nil, fmt.Errorf("%s is not a SATA or AHCI controller", name)
}
}
c := l.PickController((*types.VirtualSATAController)(nil))
if c == nil {
c = l.PickController((*types.VirtualAHCIController)(nil))
}
if c == nil {
return nil, errors.New("no available SATA or AHCI controller")
}
switch c := c.(type) {
case *types.VirtualSATAController:
return c, nil
case *types.VirtualAHCIController:
return c, nil
}
return nil, errors.New("unexpected controller type")
}
// CreateSATAController creates a new SATA controller.
func (l VirtualDeviceList) CreateSATAController() (types.BaseVirtualDevice, error) {
sata := &types.VirtualAHCIController{}
sata.BusNumber = l.newSATABusNumber()
if sata.BusNumber == -1 {
return nil, errors.New("no bus numbers available")
}
sata.Key = l.NewKey()
return sata, nil
}
var sataBusNumbers = []int{0, 1, 2, 3}
// newSATABusNumber returns the bus number to use for adding a new SATA bus device.
// -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newSATABusNumber() int32 {
var used []int
for _, d := range l.SelectByType((*types.VirtualSATAController)(nil)) {
num := d.(types.BaseVirtualController).GetVirtualController().BusNumber
if num >= 0 {
used = append(used, int(num))
} // else caller is creating a new vm using SATAControllerTypes
}
sort.Ints(used)
for i, n := range sataBusNumbers {
if i == len(used) || n != used[i] {
return int32(n)
}
}
return -1
}
// FindDiskController will find an existing ide or scsi disk controller.
func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error) {
switch {
case name == "ide":
return l.FindIDEController("")
case name == "scsi" || name == "":
return l.FindSCSIController("")
case name == "nvme":
return l.FindNVMEController("")
case name == "sata":
return l.FindSATAController("")
default:
if c, ok := l.Find(name).(types.BaseVirtualController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a valid controller", name)
}
}
// PickController returns a controller of the given type(s).
// If no controllers are found or have no available slots, then nil is returned.
func (l VirtualDeviceList) PickController(kind types.BaseVirtualController) types.BaseVirtualController {
l = l.SelectByType(kind.(types.BaseVirtualDevice)).Select(func(device types.BaseVirtualDevice) bool {
num := len(device.(types.BaseVirtualController).GetVirtualController().Device)
switch device.(type) {
case types.BaseVirtualSCSIController:
return num < 15
case *types.VirtualIDEController:
return num < 2
case types.BaseVirtualSATAController:
return num < 30
case *types.VirtualNVMEController:
return num < 8
default:
return true
}
})
if len(l) == 0 {
return nil
}
return l[0].(types.BaseVirtualController)
}
// newUnitNumber returns the unit number to use for attaching a new device to the given controller.
func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController, offset int) int32 {
units := make([]bool, 30)
for i := 0; i < offset; i++ {
units[i] = true
}
switch sc := c.(type) {
case types.BaseVirtualSCSIController:
// The SCSI controller sits on its own bus
units[sc.GetVirtualSCSIController().ScsiCtlrUnitNumber] = true
}
key := c.GetVirtualController().Key
for _, device := range l {
d := device.GetVirtualDevice()
if d.ControllerKey == key && d.UnitNumber != nil {
units[int(*d.UnitNumber)] = true
}
}
for unit, used := range units {
if !used {
return int32(unit)
}
}
return -1
}
// NewKey returns the key to use for adding a new device to the device list.
// The device list we're working with here may not be complete (e.g. when
// we're only adding new devices), so any positive keys could conflict with device keys
// that are already in use. To avoid this type of conflict, we can use negative keys
// here, which will be resolved to positive keys by vSphere as the reconfiguration is done.
func (l VirtualDeviceList) NewKey() int32 {
var key int32 = -200
for _, device := range l {
d := device.GetVirtualDevice()
if d.Key < key {
key = d.Key
}
}
return key - 1
}
// AssignController assigns a device to a controller.
func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController) {
d := device.GetVirtualDevice()
d.ControllerKey = c.GetVirtualController().Key
d.UnitNumber = new(int32)
offset := 0
switch device.(type) {
case types.BaseVirtualEthernetCard:
offset = 7
}
*d.UnitNumber = l.newUnitNumber(c, offset)
if d.Key == 0 {
d.Key = l.newRandomKey()
}
c.GetVirtualController().Device = append(c.GetVirtualController().Device, d.Key)
}
// newRandomKey returns a random negative device key.
// The generated key can be used for devices you want to add so that it does not collide with existing ones.
func (l VirtualDeviceList) newRandomKey() int32 {
// NOTE: rand.Uint32 cannot be used here because conversion from uint32 to int32 may change the sign
key := rand.Int31() * -1
if key == 0 {
return -1
}
return key
}
// CreateDisk creates a new VirtualDisk device which can be added to a VM.
func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk {
// If name is not specified, one will be chosen for you.
// But if when given, make sure it ends in .vmdk, otherwise it will be treated as a directory.
if len(name) > 0 && filepath.Ext(name) != ".vmdk" {
name += ".vmdk"
}
bi := types.VirtualDeviceFileBackingInfo{
FileName: name,
}
if ds.Value != "" {
bi.Datastore = &ds
}
device := &types.VirtualDisk{
VirtualDevice: types.VirtualDevice{
Backing: &types.VirtualDiskFlatVer2BackingInfo{
DiskMode: string(types.VirtualDiskModePersistent),
ThinProvisioned: types.NewBool(true),
VirtualDeviceFileBackingInfo: bi,
},
},
}
l.AssignController(device, c)
return device
}
// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM.
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk {
disk := *parent
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
p := new(DatastorePath)
p.FromString(backing.FileName)
p.Path = ""
// Use specified disk as parent backing to a new disk.
disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: p.String(),
Datastore: backing.Datastore,
},
Parent: backing,
DiskMode: backing.DiskMode,
ThinProvisioned: backing.ThinProvisioned,
}
return &disk
}
func (l VirtualDeviceList) connectivity(device types.BaseVirtualDevice, v bool) error {
c := device.GetVirtualDevice().Connectable
if c == nil {
return fmt.Errorf("%s is not connectable", l.Name(device))
}
c.Connected = v
c.StartConnected = v
return nil
}
// Connect changes the device to connected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error {
return l.connectivity(device, true)
}
// Disconnect changes the device to disconnected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error {
return l.connectivity(device, false)
}
// FindCdrom finds a cdrom device with the given name, defaulting to the first cdrom device if any.
func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualCdrom); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a cdrom device", name)
}
c := l.SelectByType((*types.VirtualCdrom)(nil))
if len(c) == 0 {
return nil, errors.New("no cdrom device found")
}
return c[0].(*types.VirtualCdrom), nil
}
// CreateCdrom creates a new VirtualCdrom device which can be added to a VM.
func (l VirtualDeviceList) CreateCdrom(c types.BaseVirtualController) (*types.VirtualCdrom, error) {
device := &types.VirtualCdrom{}
l.AssignController(device, c)
l.setDefaultCdromBacking(device)
device.Connectable = &types.VirtualDeviceConnectInfo{
AllowGuestControl: true,
Connected: true,
StartConnected: true,
}
return device, nil
}
// InsertIso changes the cdrom device backing to use the given iso file.
func (l VirtualDeviceList) InsertIso(device *types.VirtualCdrom, iso string) *types.VirtualCdrom {
device.Backing = &types.VirtualCdromIsoBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: iso,
},
}
return device
}
// EjectIso removes the iso file based backing and replaces with the default cdrom backing.
func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom {
l.setDefaultCdromBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultCdromBacking(device *types.VirtualCdrom) {
device.Backing = &types.VirtualCdromAtapiBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: fmt.Sprintf("%s-%d-%d", DeviceTypeCdrom, device.ControllerKey, device.UnitNumber),
UseAutoDetect: types.NewBool(false),
},
}
}
// FindFloppy finds a floppy device with the given name, defaulting to the first floppy device if any.
func (l VirtualDeviceList) FindFloppy(name string) (*types.VirtualFloppy, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualFloppy); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a floppy device", name)
}
c := l.SelectByType((*types.VirtualFloppy)(nil))
if len(c) == 0 {
return nil, errors.New("no floppy device found")
}
return c[0].(*types.VirtualFloppy), nil
}
// CreateFloppy creates a new VirtualFloppy device which can be added to a VM.
func (l VirtualDeviceList) CreateFloppy() (*types.VirtualFloppy, error) {
device := &types.VirtualFloppy{}
c := l.PickController((*types.VirtualSIOController)(nil))
if c == nil {
return nil, errors.New("no available SIO controller")
}
l.AssignController(device, c)
l.setDefaultFloppyBacking(device)
device.Connectable = &types.VirtualDeviceConnectInfo{
AllowGuestControl: true,
Connected: true,
StartConnected: true,
}
return device, nil
}
// InsertImg changes the floppy device backing to use the given img file.
func (l VirtualDeviceList) InsertImg(device *types.VirtualFloppy, img string) *types.VirtualFloppy {
device.Backing = &types.VirtualFloppyImageBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: img,
},
}
return device
}
// EjectImg removes the img file based backing and replaces with the default floppy backing.
func (l VirtualDeviceList) EjectImg(device *types.VirtualFloppy) *types.VirtualFloppy {
l.setDefaultFloppyBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultFloppyBacking(device *types.VirtualFloppy) {
device.Backing = &types.VirtualFloppyDeviceBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: fmt.Sprintf("%s-%d", DeviceTypeFloppy, device.UnitNumber),
UseAutoDetect: types.NewBool(false),
},
}
}
// FindSerialPort finds a serial port device with the given name, defaulting to the first serial port device if any.
func (l VirtualDeviceList) FindSerialPort(name string) (*types.VirtualSerialPort, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualSerialPort); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a serial port device", name)
}
c := l.SelectByType((*types.VirtualSerialPort)(nil))
if len(c) == 0 {
return nil, errors.New("no serial port device found")
}
return c[0].(*types.VirtualSerialPort), nil
}
// CreateSerialPort creates a new VirtualSerialPort device which can be added to a VM.
func (l VirtualDeviceList) CreateSerialPort() (*types.VirtualSerialPort, error) {
device := &types.VirtualSerialPort{
YieldOnPoll: true,
}
c := l.PickController((*types.VirtualSIOController)(nil))
if c == nil {
return nil, errors.New("no available SIO controller")
}
l.AssignController(device, c)
l.setDefaultSerialPortBacking(device)
return device, nil
}
// ConnectSerialPort connects a serial port to a server or client uri.
func (l VirtualDeviceList) ConnectSerialPort(device *types.VirtualSerialPort, uri string, client bool, proxyuri string) *types.VirtualSerialPort {
if strings.HasPrefix(uri, "[") {
device.Backing = &types.VirtualSerialPortFileBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: uri,
},
}
return device
}
direction := types.VirtualDeviceURIBackingOptionDirectionServer
if client {
direction = types.VirtualDeviceURIBackingOptionDirectionClient
}
device.Backing = &types.VirtualSerialPortURIBackingInfo{
VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{
Direction: string(direction),
ServiceURI: uri,
ProxyURI: proxyuri,
},
}
return device
}
// DisconnectSerialPort disconnects the serial port backing.
func (l VirtualDeviceList) DisconnectSerialPort(device *types.VirtualSerialPort) *types.VirtualSerialPort {
l.setDefaultSerialPortBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultSerialPortBacking(device *types.VirtualSerialPort) {
device.Backing = &types.VirtualSerialPortURIBackingInfo{
VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{
Direction: "client",
ServiceURI: "localhost:0",
},
}
}
// CreateEthernetCard creates a new VirtualEthernetCard of the given name name and initialized with the given backing.
func (l VirtualDeviceList) CreateEthernetCard(name string, backing types.BaseVirtualDeviceBackingInfo) (types.BaseVirtualDevice, error) {
ctypes := EthernetCardTypes()
if name == "" {
name = ctypes.deviceName(ctypes[0])
}
found := ctypes.Select(func(device types.BaseVirtualDevice) bool {
return l.deviceName(device) == name
})
if len(found) == 0 {
return nil, fmt.Errorf("unknown ethernet card type '%s'", name)
}
c, ok := found[0].(types.BaseVirtualEthernetCard)
if !ok {
return nil, fmt.Errorf("invalid ethernet card type '%s'", name)
}
c.GetVirtualEthernetCard().Backing = backing
return c.(types.BaseVirtualDevice), nil
}
// PrimaryMacAddress returns the MacAddress field of the primary VirtualEthernetCard
func (l VirtualDeviceList) PrimaryMacAddress() string {
eth0 := l.Find("ethernet-0")
if eth0 == nil {
return ""
}
return eth0.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard().MacAddress
}
// convert a BaseVirtualDevice to a BaseVirtualMachineBootOptionsBootableDevice
var bootableDevices = map[string]func(device types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice{
DeviceTypeNone: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableDevice{}
},
DeviceTypeCdrom: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableCdromDevice{}
},
DeviceTypeDisk: func(d types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableDiskDevice{
DeviceKey: d.GetVirtualDevice().Key,
}
},
DeviceTypeEthernet: func(d types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableEthernetDevice{
DeviceKey: d.GetVirtualDevice().Key,
}
},
DeviceTypeFloppy: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableFloppyDevice{}
},
}
// BootOrder returns a list of devices which can be used to set boot order via VirtualMachine.SetBootOptions.
// The order can be any of "ethernet", "cdrom", "floppy" or "disk" or by specific device name.
// A value of "-" will clear the existing boot order on the VC/ESX side.
func (l VirtualDeviceList) BootOrder(order []string) []types.BaseVirtualMachineBootOptionsBootableDevice {
var devices []types.BaseVirtualMachineBootOptionsBootableDevice
for _, name := range order {
if kind, ok := bootableDevices[name]; ok {
if name == DeviceTypeNone {
// Not covered in the API docs, nor obvious, but this clears the boot order on the VC/ESX side.
devices = append(devices, new(types.VirtualMachineBootOptionsBootableDevice))
continue
}
for _, device := range l {
if l.Type(device) == name {
devices = append(devices, kind(device))
}
}
continue
}
if d := l.Find(name); d != nil {
if kind, ok := bootableDevices[l.Type(d)]; ok {
devices = append(devices, kind(d))
}
}
}
return devices
}
// SelectBootOrder returns an ordered list of devices matching the given bootable device order
func (l VirtualDeviceList) SelectBootOrder(order []types.BaseVirtualMachineBootOptionsBootableDevice) VirtualDeviceList {
var devices VirtualDeviceList
for _, bd := range order {
for _, device := range l {
if kind, ok := bootableDevices[l.Type(device)]; ok {
if reflect.DeepEqual(kind(device), bd) {
devices = append(devices, device)
}
}
}
}
return devices
}
// TypeName returns the vmodl type name of the device
func (l VirtualDeviceList) TypeName(device types.BaseVirtualDevice) string {
dtype := reflect.TypeOf(device)
if dtype == nil {
return ""
}
return dtype.Elem().Name()
}
var deviceNameRegexp = regexp.MustCompile(`(?:Virtual)?(?:Machine)?(\w+?)(?:Card|EthernetCard|Device|Controller)?$`)
func (l VirtualDeviceList) deviceName(device types.BaseVirtualDevice) string {
name := "device"
typeName := l.TypeName(device)
m := deviceNameRegexp.FindStringSubmatch(typeName)
if len(m) == 2 {
name = strings.ToLower(m[1])
}
return name
}
// Type returns a human-readable name for the given device
func (l VirtualDeviceList) Type(device types.BaseVirtualDevice) string {
switch device.(type) {
case types.BaseVirtualEthernetCard:
return DeviceTypeEthernet
case *types.ParaVirtualSCSIController:
return "pvscsi"
case *types.VirtualLsiLogicSASController:
return "lsilogic-sas"
case *types.VirtualPrecisionClock:
return "clock"
default:
return l.deviceName(device)
}
}
// Name returns a stable, human-readable name for the given device
func (l VirtualDeviceList) Name(device types.BaseVirtualDevice) string {
var key string
var UnitNumber int32
d := device.GetVirtualDevice()
if d.UnitNumber != nil {
UnitNumber = *d.UnitNumber
}
dtype := l.Type(device)
switch dtype {
case DeviceTypeEthernet:
// Ethernet devices of UnitNumber 7-19 are non-SRIOV. Ethernet devices of
// UnitNumber 45-36 descending are SRIOV
if UnitNumber <= 45 && UnitNumber >= 36 {
key = fmt.Sprintf("sriov-%d", 45-UnitNumber)
} else {
key = fmt.Sprintf("%d", UnitNumber-7)
}
case DeviceTypeDisk:
key = fmt.Sprintf("%d-%d", d.ControllerKey, UnitNumber)
default:
key = fmt.Sprintf("%d", d.Key)
}
return fmt.Sprintf("%s-%s", dtype, key)
}
// ConfigSpec creates a virtual machine configuration spec for
// the specified operation, for the list of devices in the device list.
func (l VirtualDeviceList) ConfigSpec(op types.VirtualDeviceConfigSpecOperation) ([]types.BaseVirtualDeviceConfigSpec, error) {
var fop types.VirtualDeviceConfigSpecFileOperation
switch op {
case types.VirtualDeviceConfigSpecOperationAdd:
fop = types.VirtualDeviceConfigSpecFileOperationCreate
case types.VirtualDeviceConfigSpecOperationEdit:
fop = types.VirtualDeviceConfigSpecFileOperationReplace
case types.VirtualDeviceConfigSpecOperationRemove:
fop = types.VirtualDeviceConfigSpecFileOperationDestroy
default:
panic("unknown op")
}
var res []types.BaseVirtualDeviceConfigSpec
for _, device := range l {
config := &types.VirtualDeviceConfigSpec{
Device: device,
Operation: op,
FileOperation: diskFileOperation(op, fop, device),
}
res = append(res, config)
}
return res, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_system.go | vendor/github.com/vmware/govmomi/object/host_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"net"
"github.com/vmware/govmomi/internal"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostSystem struct {
Common
}
func NewHostSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostSystem {
return &HostSystem{
Common: NewCommon(c, ref),
}
}
func (h HostSystem) ConfigManager() *HostConfigManager {
return NewHostConfigManager(h.c, h.Reference())
}
func (h HostSystem) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"parent"}, &mh)
if err != nil {
return nil, err
}
var mcr *mo.ComputeResource
var parent any
switch mh.Parent.Type {
case "ComputeResource":
mcr = new(mo.ComputeResource)
parent = mcr
case "ClusterComputeResource":
mcc := new(mo.ClusterComputeResource)
mcr = &mcc.ComputeResource
parent = mcc
default:
return nil, fmt.Errorf("unknown host parent type: %s", mh.Parent.Type)
}
err = h.Properties(ctx, *mh.Parent, []string{"resourcePool"}, parent)
if err != nil {
return nil, err
}
pool := NewResourcePool(h.c, *mcr.ResourcePool)
return pool, nil
}
func (h HostSystem) ManagementIPs(ctx context.Context) ([]net.IP, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"config.virtualNicManagerInfo.netConfig"}, &mh)
if err != nil {
return nil, err
}
config := mh.Config
if config == nil {
return nil, nil
}
info := config.VirtualNicManagerInfo
if info == nil {
return nil, nil
}
return internal.HostSystemManagementIPs(info.NetConfig), nil
}
func (h HostSystem) Disconnect(ctx context.Context) (*Task, error) {
req := types.DisconnectHost_Task{
This: h.Reference(),
}
res, err := methods.DisconnectHost_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) Reconnect(ctx context.Context, cnxSpec *types.HostConnectSpec, reconnectSpec *types.HostSystemReconnectSpec) (*Task, error) {
req := types.ReconnectHost_Task{
This: h.Reference(),
CnxSpec: cnxSpec,
ReconnectSpec: reconnectSpec,
}
res, err := methods.ReconnectHost_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) EnterMaintenanceMode(ctx context.Context, timeout int32, evacuate bool, spec *types.HostMaintenanceSpec) (*Task, error) {
req := types.EnterMaintenanceMode_Task{
This: h.Reference(),
Timeout: timeout,
EvacuatePoweredOffVms: types.NewBool(evacuate),
MaintenanceSpec: spec,
}
res, err := methods.EnterMaintenanceMode_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) ExitMaintenanceMode(ctx context.Context, timeout int32) (*Task, error) {
req := types.ExitMaintenanceMode_Task{
This: h.Reference(),
Timeout: timeout,
}
res, err := methods.ExitMaintenanceMode_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/vm_provisioning_checker.go | vendor/github.com/vmware/govmomi/object/vm_provisioning_checker.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
// VmProvisioningChecker models the ProvisioningChecker, a singleton managed
// object that can answer questions about the feasibility of certain
// provisioning operations.
//
// For more information, see:
// https://dp-downloads.broadcom.com/api-content/apis/API_VWSA_001/8.0U3/html/ReferenceGuides/vim.vm.check.ProvisioningChecker.html
type VmProvisioningChecker struct {
Common
}
func NewVmProvisioningChecker(c *vim25.Client) *VmProvisioningChecker {
return &VmProvisioningChecker{
Common: NewCommon(c, *c.ServiceContent.VmProvisioningChecker),
}
}
func (c VmProvisioningChecker) CheckRelocate(
ctx context.Context,
vm types.ManagedObjectReference,
spec types.VirtualMachineRelocateSpec,
testTypes ...types.CheckTestType) ([]types.CheckResult, error) {
req := types.CheckRelocate_Task{
This: c.Reference(),
Vm: vm,
Spec: spec,
TestType: checkTestTypesToStrings(testTypes),
}
res, err := methods.CheckRelocate_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
ti, err := NewTask(c.c, res.Returnval).WaitForResult(ctx)
if err != nil {
return nil, err
}
return ti.Result.(types.ArrayOfCheckResult).CheckResult, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/distributed_virtual_portgroup.go | vendor/github.com/vmware/govmomi/object/distributed_virtual_portgroup.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type DistributedVirtualPortgroup struct {
Common
}
func NewDistributedVirtualPortgroup(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualPortgroup {
return &DistributedVirtualPortgroup{
Common: NewCommon(c, ref),
}
}
func (p DistributedVirtualPortgroup) GetInventoryPath() string {
return p.InventoryPath
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this DistributedVirtualPortgroup
func (p DistributedVirtualPortgroup) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
var dvp mo.DistributedVirtualPortgroup
var dvs mo.DistributedVirtualSwitch
prop := "config.distributedVirtualSwitch"
if err := p.Properties(ctx, p.Reference(), []string{"key", prop}, &dvp); err != nil {
return nil, err
}
// From the docs at https://developer.broadcom.com/xapis/vsphere-web-services-api/latest/vim.dvs.DistributedVirtualPortgroup.ConfigInfo.html:
// "This property should always be set unless the user's setting does not have System.Read privilege on the object referred to by this property."
// Note that "the object" refers to the Switch, not the PortGroup.
if dvp.Config.DistributedVirtualSwitch == nil {
name := p.InventoryPath
if name == "" {
name = p.Reference().String()
}
return nil, fmt.Errorf("failed to create EthernetCardBackingInfo for %s: System.Read privilege required for %s", name, prop)
}
if err := p.Properties(ctx, *dvp.Config.DistributedVirtualSwitch, []string{"uuid"}, &dvs); err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{
Port: types.DistributedVirtualSwitchPortConnection{
PortgroupKey: dvp.Key,
SwitchUuid: dvs.Uuid,
},
}
return backing, nil
}
func (p DistributedVirtualPortgroup) Reconfigure(ctx context.Context, spec types.DVPortgroupConfigSpec) (*Task, error) {
req := types.ReconfigureDVPortgroup_Task{
This: p.Reference(),
Spec: spec,
}
res, err := methods.ReconfigureDVPortgroup_Task(ctx, p.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(p.Client(), res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/authorization_manager.go | vendor/github.com/vmware/govmomi/object/authorization_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type AuthorizationManager struct {
Common
}
func NewAuthorizationManager(c *vim25.Client) *AuthorizationManager {
m := AuthorizationManager{
Common: NewCommon(c, *c.ServiceContent.AuthorizationManager),
}
return &m
}
type AuthorizationRoleList []types.AuthorizationRole
func (l AuthorizationRoleList) ById(id int32) *types.AuthorizationRole {
for _, role := range l {
if role.RoleId == id {
return &role
}
}
return nil
}
func (l AuthorizationRoleList) ByName(name string) *types.AuthorizationRole {
for _, role := range l {
if role.Name == name {
return &role
}
}
return nil
}
func (m AuthorizationManager) RoleList(ctx context.Context) (AuthorizationRoleList, error) {
var am mo.AuthorizationManager
err := m.Properties(ctx, m.Reference(), []string{"roleList"}, &am)
if err != nil {
return nil, err
}
return AuthorizationRoleList(am.RoleList), nil
}
func (m AuthorizationManager) RetrieveEntityPermissions(ctx context.Context, entity types.ManagedObjectReference, inherited bool) ([]types.Permission, error) {
req := types.RetrieveEntityPermissions{
This: m.Reference(),
Entity: entity,
Inherited: inherited,
}
res, err := methods.RetrieveEntityPermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RemoveEntityPermission(ctx context.Context, entity types.ManagedObjectReference, user string, isGroup bool) error {
req := types.RemoveEntityPermission{
This: m.Reference(),
Entity: entity,
User: user,
IsGroup: isGroup,
}
_, err := methods.RemoveEntityPermission(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) SetEntityPermissions(ctx context.Context, entity types.ManagedObjectReference, permission []types.Permission) error {
req := types.SetEntityPermissions{
This: m.Reference(),
Entity: entity,
Permission: permission,
}
_, err := methods.SetEntityPermissions(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) RetrieveRolePermissions(ctx context.Context, id int32) ([]types.Permission, error) {
req := types.RetrieveRolePermissions{
This: m.Reference(),
RoleId: id,
}
res, err := methods.RetrieveRolePermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RetrieveAllPermissions(ctx context.Context) ([]types.Permission, error) {
req := types.RetrieveAllPermissions{
This: m.Reference(),
}
res, err := methods.RetrieveAllPermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) AddRole(ctx context.Context, name string, ids []string) (int32, error) {
req := types.AddAuthorizationRole{
This: m.Reference(),
Name: name,
PrivIds: ids,
}
res, err := methods.AddAuthorizationRole(ctx, m.Client(), &req)
if err != nil {
return -1, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RemoveRole(ctx context.Context, id int32, failIfUsed bool) error {
req := types.RemoveAuthorizationRole{
This: m.Reference(),
RoleId: id,
FailIfUsed: failIfUsed,
}
_, err := methods.RemoveAuthorizationRole(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) UpdateRole(ctx context.Context, id int32, name string, ids []string) error {
req := types.UpdateAuthorizationRole{
This: m.Reference(),
RoleId: id,
NewName: name,
PrivIds: ids,
}
_, err := methods.UpdateAuthorizationRole(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) HasUserPrivilegeOnEntities(ctx context.Context, entities []types.ManagedObjectReference, userName string, privID []string) ([]types.EntityPrivilege, error) {
req := types.HasUserPrivilegeOnEntities{
This: m.Reference(),
Entities: entities,
UserName: userName,
PrivId: privID,
}
res, err := methods.HasUserPrivilegeOnEntities(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) HasPrivilegeOnEntity(ctx context.Context, entity types.ManagedObjectReference, sessionID string, privID []string) ([]bool, error) {
req := types.HasPrivilegeOnEntity{
This: m.Reference(),
Entity: entity,
SessionId: sessionID,
PrivId: privID,
}
res, err := methods.HasPrivilegeOnEntity(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) FetchUserPrivilegeOnEntities(ctx context.Context, entities []types.ManagedObjectReference, userName string) ([]types.UserPrivilegeResult, error) {
req := types.FetchUserPrivilegeOnEntities{
This: m.Reference(),
Entities: entities,
UserName: userName,
}
res, err := methods.FetchUserPrivilegeOnEntities(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_vsan_system.go | vendor/github.com/vmware/govmomi/object/host_vsan_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostVsanSystem struct {
Common
}
func NewHostVsanSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostVsanSystem {
return &HostVsanSystem{
Common: NewCommon(c, ref),
}
}
func (s HostVsanSystem) Update(ctx context.Context, config types.VsanHostConfigInfo) (*Task, error) {
req := types.UpdateVsan_Task{
This: s.Reference(),
Config: config,
}
res, err := methods.UpdateVsan_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
// updateVnic in support of the HostVirtualNicManager.{SelectVnic,DeselectVnic} methods
func (s HostVsanSystem) updateVnic(ctx context.Context, device string, enable bool) error {
var vsan mo.HostVsanSystem
err := s.Properties(ctx, s.Reference(), []string{"config.networkInfo.port"}, &vsan)
if err != nil {
return err
}
info := vsan.Config
var port []types.VsanHostConfigInfoNetworkInfoPortConfig
for _, p := range info.NetworkInfo.Port {
if p.Device == device {
continue
}
port = append(port, p)
}
if enable {
port = append(port, types.VsanHostConfigInfoNetworkInfoPortConfig{
Device: device,
})
}
info.NetworkInfo.Port = port
task, err := s.Update(ctx, info)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/virtual_app.go | vendor/github.com/vmware/govmomi/object/virtual_app.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type VirtualApp struct {
*ResourcePool
}
func NewVirtualApp(c *vim25.Client, ref types.ManagedObjectReference) *VirtualApp {
return &VirtualApp{
ResourcePool: NewResourcePool(c, ref),
}
}
func (p VirtualApp) CreateChildVM(ctx context.Context, config types.VirtualMachineConfigSpec, host *HostSystem) (*Task, error) {
req := types.CreateChildVM_Task{
This: p.Reference(),
Config: config,
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.CreateChildVM_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) UpdateConfig(ctx context.Context, spec types.VAppConfigSpec) error {
req := types.UpdateVAppConfig{
This: p.Reference(),
Spec: spec,
}
_, err := methods.UpdateVAppConfig(ctx, p.c, &req)
return err
}
func (p VirtualApp) PowerOn(ctx context.Context) (*Task, error) {
req := types.PowerOnVApp_Task{
This: p.Reference(),
}
res, err := methods.PowerOnVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) PowerOff(ctx context.Context, force bool) (*Task, error) {
req := types.PowerOffVApp_Task{
This: p.Reference(),
Force: force,
}
res, err := methods.PowerOffVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) Suspend(ctx context.Context) (*Task, error) {
req := types.SuspendVApp_Task{
This: p.Reference(),
}
res, err := methods.SuspendVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) Clone(ctx context.Context, name string, target types.ManagedObjectReference, spec types.VAppCloneSpec) (*Task, error) {
req := types.CloneVApp_Task{
This: p.Reference(),
Name: name,
Target: target,
Spec: spec,
}
res, err := methods.CloneVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/opaque_network.go | vendor/github.com/vmware/govmomi/object/opaque_network.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type OpaqueNetwork struct {
Common
}
func NewOpaqueNetwork(c *vim25.Client, ref types.ManagedObjectReference) *OpaqueNetwork {
return &OpaqueNetwork{
Common: NewCommon(c, ref),
}
}
func (n OpaqueNetwork) GetInventoryPath() string {
return n.InventoryPath
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n OpaqueNetwork) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
summary, err := n.Summary(ctx)
if err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardOpaqueNetworkBackingInfo{
OpaqueNetworkId: summary.OpaqueNetworkId,
OpaqueNetworkType: summary.OpaqueNetworkType,
}
return backing, nil
}
// Summary returns the mo.OpaqueNetwork.Summary property
func (n OpaqueNetwork) Summary(ctx context.Context) (*types.OpaqueNetworkSummary, error) {
var props mo.OpaqueNetwork
err := n.Properties(ctx, n.Reference(), []string{"summary"}, &props)
if err != nil {
return nil, err
}
summary, ok := props.Summary.(*types.OpaqueNetworkSummary)
if !ok {
return nil, fmt.Errorf("%s unsupported network summary type: %T", n, props.Summary)
}
return summary, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/folder.go | vendor/github.com/vmware/govmomi/object/folder.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type Folder struct {
Common
}
func NewFolder(c *vim25.Client, ref types.ManagedObjectReference) *Folder {
return &Folder{
Common: NewCommon(c, ref),
}
}
func NewRootFolder(c *vim25.Client) *Folder {
f := NewFolder(c, c.ServiceContent.RootFolder)
f.InventoryPath = "/"
return f
}
func (f Folder) Children(ctx context.Context) ([]Reference, error) {
var mf mo.Folder
err := f.Properties(ctx, f.Reference(), []string{"childEntity"}, &mf)
if err != nil {
return nil, err
}
var rs []Reference
for _, e := range mf.ChildEntity {
if r := NewReference(f.c, e); r != nil {
rs = append(rs, r)
}
}
return rs, nil
}
func (f Folder) CreateDatacenter(ctx context.Context, datacenter string) (*Datacenter, error) {
req := types.CreateDatacenter{
This: f.Reference(),
Name: datacenter,
}
res, err := methods.CreateDatacenter(ctx, f.c, &req)
if err != nil {
return nil, err
}
// Response will be nil if this is an ESX host that does not belong to a vCenter
if res == nil {
return nil, nil
}
return NewDatacenter(f.c, res.Returnval), nil
}
func (f Folder) CreateCluster(ctx context.Context, cluster string, spec types.ClusterConfigSpecEx) (*ClusterComputeResource, error) {
req := types.CreateClusterEx{
This: f.Reference(),
Name: cluster,
Spec: spec,
}
res, err := methods.CreateClusterEx(ctx, f.c, &req)
if err != nil {
return nil, err
}
// Response will be nil if this is an ESX host that does not belong to a vCenter
if res == nil {
return nil, nil
}
return NewClusterComputeResource(f.c, res.Returnval), nil
}
func (f Folder) CreateFolder(ctx context.Context, name string) (*Folder, error) {
req := types.CreateFolder{
This: f.Reference(),
Name: name,
}
res, err := methods.CreateFolder(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewFolder(f.c, res.Returnval), err
}
func (f Folder) CreateStoragePod(ctx context.Context, name string) (*StoragePod, error) {
req := types.CreateStoragePod{
This: f.Reference(),
Name: name,
}
res, err := methods.CreateStoragePod(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewStoragePod(f.c, res.Returnval), err
}
func (f Folder) AddStandaloneHost(ctx context.Context, spec types.HostConnectSpec, addConnected bool, license *string, compResSpec *types.BaseComputeResourceConfigSpec) (*Task, error) {
req := types.AddStandaloneHost_Task{
This: f.Reference(),
Spec: spec,
AddConnected: addConnected,
}
if license != nil {
req.License = *license
}
if compResSpec != nil {
req.CompResSpec = *compResSpec
}
res, err := methods.AddStandaloneHost_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) CreateVM(ctx context.Context, config types.VirtualMachineConfigSpec, pool *ResourcePool, host *HostSystem) (*Task, error) {
req := types.CreateVM_Task{
This: f.Reference(),
Config: config,
Pool: pool.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.CreateVM_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) RegisterVM(ctx context.Context, path string, name string, asTemplate bool, pool *ResourcePool, host *HostSystem) (*Task, error) {
req := types.RegisterVM_Task{
This: f.Reference(),
Path: path,
AsTemplate: asTemplate,
}
if name != "" {
req.Name = name
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
if pool != nil {
ref := pool.Reference()
req.Pool = &ref
}
res, err := methods.RegisterVM_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) CreateDVS(ctx context.Context, spec types.DVSCreateSpec) (*Task, error) {
req := types.CreateDVS_Task{
This: f.Reference(),
Spec: spec,
}
res, err := methods.CreateDVS_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) MoveInto(ctx context.Context, list []types.ManagedObjectReference) (*Task, error) {
req := types.MoveIntoFolder_Task{
This: f.Reference(),
List: list,
}
res, err := methods.MoveIntoFolder_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) PlaceVmsXCluster(ctx context.Context, spec types.PlaceVmsXClusterSpec) (*types.PlaceVmsXClusterResult, error) {
req := types.PlaceVmsXCluster{
This: f.Reference(),
PlacementSpec: spec,
}
res, err := methods.PlaceVmsXCluster(ctx, f.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_virtual_nic_manager.go | vendor/github.com/vmware/govmomi/object/host_virtual_nic_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostVirtualNicManager struct {
Common
Host *HostSystem
}
func NewHostVirtualNicManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostVirtualNicManager {
return &HostVirtualNicManager{
Common: NewCommon(c, ref),
Host: NewHostSystem(c, host),
}
}
func (m HostVirtualNicManager) Info(ctx context.Context) (*types.HostVirtualNicManagerInfo, error) {
var vnm mo.HostVirtualNicManager
err := m.Properties(ctx, m.Reference(), []string{"info"}, &vnm)
if err != nil {
return nil, err
}
return &vnm.Info, nil
}
func (m HostVirtualNicManager) DeselectVnic(ctx context.Context, nicType string, device string) error {
if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
// Avoid fault.NotSupported:
// "Error deselecting device '$device': VSAN interfaces must be deselected using vim.host.VsanSystem"
s, err := m.Host.ConfigManager().VsanSystem(ctx)
if err != nil {
return err
}
return s.updateVnic(ctx, device, false)
}
req := types.DeselectVnicForNicType{
This: m.Reference(),
NicType: nicType,
Device: device,
}
_, err := methods.DeselectVnicForNicType(ctx, m.Client(), &req)
return err
}
func (m HostVirtualNicManager) SelectVnic(ctx context.Context, nicType string, device string) error {
if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
// Avoid fault.NotSupported:
// "Error selecting device '$device': VSAN interfaces must be selected using vim.host.VsanSystem"
s, err := m.Host.ConfigManager().VsanSystem(ctx)
if err != nil {
return err
}
return s.updateVnic(ctx, device, true)
}
req := types.SelectVnicForNicType{
This: m.Reference(),
NicType: nicType,
Device: device,
}
_, err := methods.SelectVnicForNicType(ctx, m.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_service_system.go | vendor/github.com/vmware/govmomi/object/host_service_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type HostServiceSystem struct {
Common
}
func NewHostServiceSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostServiceSystem {
return &HostServiceSystem{
Common: NewCommon(c, ref),
}
}
func (s HostServiceSystem) Service(ctx context.Context) ([]types.HostService, error) {
var ss mo.HostServiceSystem
err := s.Properties(ctx, s.Reference(), []string{"serviceInfo.service"}, &ss)
if err != nil {
return nil, err
}
return ss.ServiceInfo.Service, nil
}
func (s HostServiceSystem) Start(ctx context.Context, id string) error {
req := types.StartService{
This: s.Reference(),
Id: id,
}
_, err := methods.StartService(ctx, s.Client(), &req)
return err
}
func (s HostServiceSystem) Stop(ctx context.Context, id string) error {
req := types.StopService{
This: s.Reference(),
Id: id,
}
_, err := methods.StopService(ctx, s.Client(), &req)
return err
}
func (s HostServiceSystem) Restart(ctx context.Context, id string) error {
req := types.RestartService{
This: s.Reference(),
Id: id,
}
_, err := methods.RestartService(ctx, s.Client(), &req)
return err
}
func (s HostServiceSystem) UpdatePolicy(ctx context.Context, id string, policy string) error {
req := types.UpdateServicePolicy{
This: s.Reference(),
Id: id,
Policy: policy,
}
_, err := methods.UpdateServicePolicy(ctx, s.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/customization_spec_manager.go | vendor/github.com/vmware/govmomi/object/customization_spec_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type CustomizationSpecManager struct {
Common
}
func NewCustomizationSpecManager(c *vim25.Client) *CustomizationSpecManager {
cs := CustomizationSpecManager{
Common: NewCommon(c, *c.ServiceContent.CustomizationSpecManager),
}
return &cs
}
func (cs CustomizationSpecManager) Info(ctx context.Context) ([]types.CustomizationSpecInfo, error) {
var m mo.CustomizationSpecManager
err := cs.Properties(ctx, cs.Reference(), []string{"info"}, &m)
return m.Info, err
}
func (cs CustomizationSpecManager) DoesCustomizationSpecExist(ctx context.Context, name string) (bool, error) {
req := types.DoesCustomizationSpecExist{
This: cs.Reference(),
Name: name,
}
res, err := methods.DoesCustomizationSpecExist(ctx, cs.c, &req)
if err != nil {
return false, err
}
return res.Returnval, nil
}
func (cs CustomizationSpecManager) GetCustomizationSpec(ctx context.Context, name string) (*types.CustomizationSpecItem, error) {
req := types.GetCustomizationSpec{
This: cs.Reference(),
Name: name,
}
res, err := methods.GetCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (cs CustomizationSpecManager) CreateCustomizationSpec(ctx context.Context, item types.CustomizationSpecItem) error {
req := types.CreateCustomizationSpec{
This: cs.Reference(),
Item: item,
}
_, err := methods.CreateCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) OverwriteCustomizationSpec(ctx context.Context, item types.CustomizationSpecItem) error {
req := types.OverwriteCustomizationSpec{
This: cs.Reference(),
Item: item,
}
_, err := methods.OverwriteCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) DeleteCustomizationSpec(ctx context.Context, name string) error {
req := types.DeleteCustomizationSpec{
This: cs.Reference(),
Name: name,
}
_, err := methods.DeleteCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) DuplicateCustomizationSpec(ctx context.Context, name string, newName string) error {
req := types.DuplicateCustomizationSpec{
This: cs.Reference(),
Name: name,
NewName: newName,
}
_, err := methods.DuplicateCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) RenameCustomizationSpec(ctx context.Context, name string, newName string) error {
req := types.RenameCustomizationSpec{
This: cs.Reference(),
Name: name,
NewName: newName,
}
_, err := methods.RenameCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) CustomizationSpecItemToXml(ctx context.Context, item types.CustomizationSpecItem) (string, error) {
req := types.CustomizationSpecItemToXml{
This: cs.Reference(),
Item: item,
}
res, err := methods.CustomizationSpecItemToXml(ctx, cs.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
func (cs CustomizationSpecManager) XmlToCustomizationSpecItem(ctx context.Context, xml string) (*types.CustomizationSpecItem, error) {
req := types.XmlToCustomizationSpecItem{
This: cs.Reference(),
SpecItemXml: xml,
}
res, err := methods.XmlToCustomizationSpecItem(ctx, cs.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_config_manager.go | vendor/github.com/vmware/govmomi/object/host_config_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type HostConfigManager struct {
Common
}
func NewHostConfigManager(c *vim25.Client, ref types.ManagedObjectReference) *HostConfigManager {
return &HostConfigManager{
Common: NewCommon(c, ref),
}
}
// reference returns the ManagedObjectReference for the given HostConfigManager property name.
// An error is returned if the field is nil, of type ErrNotSupported if versioned is true.
func (m HostConfigManager) reference(ctx context.Context, name string, versioned ...bool) (types.ManagedObjectReference, error) {
prop := "configManager." + name
var content []types.ObjectContent
err := m.Properties(ctx, m.Reference(), []string{prop}, &content)
if err != nil {
return types.ManagedObjectReference{}, err
}
for _, c := range content {
for _, p := range c.PropSet {
if p.Name != prop {
continue
}
if ref, ok := p.Val.(types.ManagedObjectReference); ok {
return ref, nil
}
}
}
err = fmt.Errorf("%s %s is nil", m.Reference(), prop)
if len(versioned) == 1 && versioned[0] {
err = ErrNotSupported
}
return types.ManagedObjectReference{}, err
}
func (m HostConfigManager) DatastoreSystem(ctx context.Context) (*HostDatastoreSystem, error) {
ref, err := m.reference(ctx, "datastoreSystem")
if err != nil {
return nil, err
}
return NewHostDatastoreSystem(m.c, ref), nil
}
func (m HostConfigManager) NetworkSystem(ctx context.Context) (*HostNetworkSystem, error) {
ref, err := m.reference(ctx, "networkSystem")
if err != nil {
return nil, err
}
return NewHostNetworkSystem(m.c, ref), nil
}
func (m HostConfigManager) FirewallSystem(ctx context.Context) (*HostFirewallSystem, error) {
ref, err := m.reference(ctx, "firewallSystem")
if err != nil {
return nil, err
}
return NewHostFirewallSystem(m.c, ref), nil
}
func (m HostConfigManager) StorageSystem(ctx context.Context) (*HostStorageSystem, error) {
ref, err := m.reference(ctx, "storageSystem")
if err != nil {
return nil, err
}
return NewHostStorageSystem(m.c, ref), nil
}
func (m HostConfigManager) VirtualNicManager(ctx context.Context) (*HostVirtualNicManager, error) {
ref, err := m.reference(ctx, "virtualNicManager")
if err != nil {
return nil, err
}
return NewHostVirtualNicManager(m.c, ref, m.Reference()), nil
}
func (m HostConfigManager) VsanSystem(ctx context.Context) (*HostVsanSystem, error) {
ref, err := m.reference(ctx, "vsanSystem", true) // Added in 5.5
if err != nil {
return nil, err
}
return NewHostVsanSystem(m.c, ref), nil
}
func (m HostConfigManager) VsanInternalSystem(ctx context.Context) (*HostVsanInternalSystem, error) {
ref, err := m.reference(ctx, "vsanInternalSystem", true) // Added in 5.5
if err != nil {
return nil, err
}
return NewHostVsanInternalSystem(m.c, ref), nil
}
func (m HostConfigManager) AccountManager(ctx context.Context) (*HostAccountManager, error) {
ref, err := m.reference(ctx, "accountManager", true) // Added in 5.5
if err != nil {
if err == ErrNotSupported {
// Versions < 5.5 can use the ServiceContent ref,
// but only when connected directly to ESX.
if m.c.ServiceContent.AccountManager == nil {
return nil, err
}
ref = *m.c.ServiceContent.AccountManager
} else {
return nil, err
}
}
return NewHostAccountManager(m.c, ref), nil
}
func (m HostConfigManager) OptionManager(ctx context.Context) (*OptionManager, error) {
ref, err := m.reference(ctx, "advancedOption")
if err != nil {
return nil, err
}
return NewOptionManager(m.c, ref), nil
}
func (m HostConfigManager) ServiceSystem(ctx context.Context) (*HostServiceSystem, error) {
ref, err := m.reference(ctx, "serviceSystem")
if err != nil {
return nil, err
}
return NewHostServiceSystem(m.c, ref), nil
}
func (m HostConfigManager) CertificateManager(ctx context.Context) (*HostCertificateManager, error) {
ref, err := m.reference(ctx, "certificateManager", true) // Added in 6.0
if err != nil {
return nil, err
}
return NewHostCertificateManager(m.c, ref, m.Reference()), nil
}
func (m HostConfigManager) DateTimeSystem(ctx context.Context) (*HostDateTimeSystem, error) {
ref, err := m.reference(ctx, "dateTimeSystem")
if err != nil {
return nil, err
}
return NewHostDateTimeSystem(m.c, ref), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/cluster_compute_resource.go | vendor/github.com/vmware/govmomi/object/cluster_compute_resource.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ClusterComputeResource struct {
ComputeResource
}
func NewClusterComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ClusterComputeResource {
return &ClusterComputeResource{
ComputeResource: *NewComputeResource(c, ref),
}
}
func (c ClusterComputeResource) Configuration(ctx context.Context) (*types.ClusterConfigInfoEx, error) {
var obj mo.ClusterComputeResource
err := c.Properties(ctx, c.Reference(), []string{"configurationEx"}, &obj)
if err != nil {
return nil, err
}
return obj.ConfigurationEx.(*types.ClusterConfigInfoEx), nil
}
func (c ClusterComputeResource) AddHost(ctx context.Context, spec types.HostConnectSpec, asConnected bool, license *string, resourcePool *types.ManagedObjectReference) (*Task, error) {
req := types.AddHost_Task{
This: c.Reference(),
Spec: spec,
AsConnected: asConnected,
}
if license != nil {
req.License = *license
}
if resourcePool != nil {
req.ResourcePool = resourcePool
}
res, err := methods.AddHost_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ClusterComputeResource) MoveInto(ctx context.Context, hosts ...*HostSystem) (*Task, error) {
req := types.MoveInto_Task{
This: c.Reference(),
}
hostReferences := make([]types.ManagedObjectReference, len(hosts))
for i, host := range hosts {
hostReferences[i] = host.Reference()
}
req.Host = hostReferences
res, err := methods.MoveInto_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ClusterComputeResource) PlaceVm(ctx context.Context, spec types.PlacementSpec) (*types.PlacementResult, error) {
req := types.PlaceVm{
This: c.Reference(),
PlacementSpec: spec,
}
res, err := methods.PlaceVm(ctx, c.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_vsan_internal_system.go | vendor/github.com/vmware/govmomi/object/host_vsan_internal_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"encoding/json"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostVsanInternalSystem struct {
Common
}
func NewHostVsanInternalSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostVsanInternalSystem {
m := HostVsanInternalSystem{
Common: NewCommon(c, ref),
}
return &m
}
// QueryVsanObjectUuidsByFilter returns vSAN DOM object uuids by filter.
func (m HostVsanInternalSystem) QueryVsanObjectUuidsByFilter(ctx context.Context, uuids []string, limit int32, version int32) ([]string, error) {
req := types.QueryVsanObjectUuidsByFilter{
This: m.Reference(),
Uuids: uuids,
Limit: &limit,
Version: version,
}
res, err := methods.QueryVsanObjectUuidsByFilter(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
type VsanObjExtAttrs struct {
Type string `json:"Object type"`
Class string `json:"Object class"`
Size string `json:"Object size"`
Path string `json:"Object path"`
Name string `json:"User friendly name"`
}
func (a *VsanObjExtAttrs) DatastorePath(dir string) string {
l := len(dir)
path := a.Path
if len(path) >= l {
path = a.Path[l:]
}
if path != "" {
return path
}
return a.Name // vmnamespace
}
// GetVsanObjExtAttrs is internal and intended for troubleshooting/debugging situations in the field.
// WARNING: This API can be slow because we do IOs (reads) to all the objects.
func (m HostVsanInternalSystem) GetVsanObjExtAttrs(ctx context.Context, uuids []string) (map[string]VsanObjExtAttrs, error) {
req := types.GetVsanObjExtAttrs{
This: m.Reference(),
Uuids: uuids,
}
res, err := methods.GetVsanObjExtAttrs(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
var attrs map[string]VsanObjExtAttrs
err = json.Unmarshal([]byte(res.Returnval), &attrs)
return attrs, err
}
// DeleteVsanObjects is internal and intended for troubleshooting/debugging only.
// WARNING: This API can be slow because we do IOs to all the objects.
// DOM won't allow access to objects which have lost quorum. Such objects can be deleted with the optional "force" flag.
// These objects may however re-appear with quorum if the absent components come back (network partition gets resolved, etc.)
func (m HostVsanInternalSystem) DeleteVsanObjects(ctx context.Context, uuids []string, force *bool) ([]types.HostVsanInternalSystemDeleteVsanObjectsResult, error) {
req := types.DeleteVsanObjects{
This: m.Reference(),
Uuids: uuids,
Force: force,
}
res, err := methods.DeleteVsanObjects(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_account_manager.go | vendor/github.com/vmware/govmomi/object/host_account_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostAccountManager struct {
Common
}
func NewHostAccountManager(c *vim25.Client, ref types.ManagedObjectReference) *HostAccountManager {
return &HostAccountManager{
Common: NewCommon(c, ref),
}
}
func (m HostAccountManager) Create(ctx context.Context, user *types.HostAccountSpec) error {
req := types.CreateUser{
This: m.Reference(),
User: user,
}
_, err := methods.CreateUser(ctx, m.Client(), &req)
return err
}
func (m HostAccountManager) Update(ctx context.Context, user *types.HostAccountSpec) error {
req := types.UpdateUser{
This: m.Reference(),
User: user,
}
_, err := methods.UpdateUser(ctx, m.Client(), &req)
return err
}
func (m HostAccountManager) Remove(ctx context.Context, userName string) error {
req := types.RemoveUser{
This: m.Reference(),
UserName: userName,
}
_, err := methods.RemoveUser(ctx, m.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/task.go | vendor/github.com/vmware/govmomi/object/task.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/task"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/types"
)
// Task is a convenience wrapper around task.Task that keeps a reference to
// the client that was used to create it. This allows users to call the Wait()
// function with only a context parameter, instead of a context parameter, a
// soap.RoundTripper, and reference to the root property collector.
type Task struct {
Common
}
func NewTask(c *vim25.Client, ref types.ManagedObjectReference) *Task {
t := Task{
Common: NewCommon(c, ref),
}
return &t
}
// Wait waits for a task to complete.
// NOTE: This method create a thread-safe PropertyCollector instance per-call, so it is thread safe.
// The downside of this approach is the additional resource usage on the vCenter side for each call.
func (t *Task) Wait(ctx context.Context) error {
_, err := t.WaitForResult(ctx, nil)
return err
}
// WaitForResult wait for a task to complete.
// NOTE: This method create a thread-safe PropertyCollector instance per-call, so it is thread safe.
// The downside of this approach is the additional resource usage on the vCenter side for each call.
func (t *Task) WaitForResult(ctx context.Context, s ...progress.Sinker) (taskInfo *types.TaskInfo, result error) {
var pr progress.Sinker
if len(s) == 1 {
pr = s[0]
}
p, err := property.DefaultCollector(t.c).Create(ctx)
if err != nil {
return nil, err
}
// Attempt to destroy the collector using the background context, as the
// specified context may have timed out or have been canceled.
defer func() {
if err := p.Destroy(context.Background()); err != nil {
if result == nil {
result = err
} else {
result = fmt.Errorf(
"destroy property collector failed with %s after failing to wait for updates: %w",
err,
result)
}
}
}()
return task.WaitEx(ctx, t.Reference(), p, pr)
}
// WaitEx waits for a task to complete.
// NOTE: This method use the same PropertyCollector instance in each call, thus reducing resource usage on the vCenter side.
// The downside of this approach is that this method is not thread safe.
func (t *Task) WaitEx(ctx context.Context) error {
_, err := t.WaitForResultEx(ctx, nil)
return err
}
// WaitForResultEx waits for a task to complete.
// NOTE: This method use the same PropertyCollector instance in each call, thus reducing resource usage on the vCenter side.
// The downside of this approach is that this method is not thread safe.
func (t *Task) WaitForResultEx(ctx context.Context, s ...progress.Sinker) (*types.TaskInfo, error) {
var pr progress.Sinker
if len(s) == 1 {
pr = s[0]
}
p := property.DefaultCollector(t.c)
return task.WaitEx(ctx, t.Reference(), p, pr)
}
func (t *Task) Cancel(ctx context.Context) error {
_, err := methods.CancelTask(ctx, t.Client(), &types.CancelTask{
This: t.Reference(),
})
return err
}
// SetState sets task state and optionally sets results or fault, as appropriate for state.
func (t *Task) SetState(ctx context.Context, state types.TaskInfoState, result types.AnyType, fault *types.LocalizedMethodFault) error {
req := types.SetTaskState{
This: t.Reference(),
State: state,
Result: result,
Fault: fault,
}
_, err := methods.SetTaskState(ctx, t.Common.Client(), &req)
return err
}
// SetDescription updates task description to describe the current phase of the task.
func (t *Task) SetDescription(ctx context.Context, description types.LocalizableMessage) error {
req := types.SetTaskDescription{
This: t.Reference(),
Description: description,
}
_, err := methods.SetTaskDescription(ctx, t.Common.Client(), &req)
return err
}
// UpdateProgress Sets percentage done for this task and recalculates overall percentage done.
// If a percentDone value of less than zero or greater than 100 is specified,
// a value of zero or 100 respectively is used.
func (t *Task) UpdateProgress(ctx context.Context, percentDone int) error {
req := types.UpdateProgress{
This: t.Reference(),
PercentDone: int32(percentDone),
}
_, err := methods.UpdateProgress(ctx, t.Common.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/network_reference.go | vendor/github.com/vmware/govmomi/object/network_reference.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25/types"
)
// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
Reference
GetInventoryPath() string
EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/environment_browser.go | vendor/github.com/vmware/govmomi/object/environment_browser.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type EnvironmentBrowser struct {
Common
}
func NewEnvironmentBrowser(c *vim25.Client, ref types.ManagedObjectReference) *EnvironmentBrowser {
return &EnvironmentBrowser{
Common: NewCommon(c, ref),
}
}
func (b EnvironmentBrowser) QueryConfigTarget(ctx context.Context, host *HostSystem) (*types.ConfigTarget, error) {
req := types.QueryConfigTarget{
This: b.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.QueryConfigTarget(ctx, b.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (b EnvironmentBrowser) QueryTargetCapabilities(ctx context.Context, host *HostSystem) (*types.HostCapability, error) {
req := types.QueryTargetCapabilities{
This: b.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.QueryTargetCapabilities(ctx, b.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (b EnvironmentBrowser) QueryConfigOption(ctx context.Context, spec *types.EnvironmentBrowserConfigOptionQuerySpec) (*types.VirtualMachineConfigOption, error) {
req := types.QueryConfigOptionEx{
This: b.Reference(),
Spec: spec,
}
res, err := methods.QueryConfigOptionEx(ctx, b.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (b EnvironmentBrowser) QueryConfigOptionDescriptor(ctx context.Context) ([]types.VirtualMachineConfigOptionDescriptor, error) {
req := types.QueryConfigOptionDescriptor{
This: b.Reference(),
}
res, err := methods.QueryConfigOptionDescriptor(ctx, b.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/diagnostic_log.go | vendor/github.com/vmware/govmomi/object/diagnostic_log.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"fmt"
"io"
"math"
)
// DiagnosticLog wraps DiagnosticManager.BrowseLog
type DiagnosticLog struct {
m DiagnosticManager
Key string
Host *HostSystem
Start int32
}
// Seek to log position starting at the last nlines of the log
func (l *DiagnosticLog) Seek(ctx context.Context, nlines int32) error {
h, err := l.m.BrowseLog(ctx, l.Host, l.Key, math.MaxInt32, 0)
if err != nil {
return err
}
l.Start = h.LineEnd - nlines
return nil
}
// Copy log starting from l.Start to the given io.Writer
// Returns on error or when end of log is reached.
func (l *DiagnosticLog) Copy(ctx context.Context, w io.Writer) (int, error) {
const max = 500 // VC max == 500, ESX max == 1000
written := 0
for {
h, err := l.m.BrowseLog(ctx, l.Host, l.Key, l.Start, max)
if err != nil {
return 0, err
}
for _, line := range h.LineText {
n, err := fmt.Fprintln(w, line)
written += n
if err != nil {
return written, err
}
}
l.Start += int32(len(h.LineText))
if l.Start >= h.LineEnd {
break
}
}
return written, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/diagnostic_manager.go | vendor/github.com/vmware/govmomi/object/diagnostic_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type DiagnosticManager struct {
Common
}
func NewDiagnosticManager(c *vim25.Client) *DiagnosticManager {
m := DiagnosticManager{
Common: NewCommon(c, *c.ServiceContent.DiagnosticManager),
}
return &m
}
func (m DiagnosticManager) Log(ctx context.Context, host *HostSystem, key string) *DiagnosticLog {
return &DiagnosticLog{
m: m,
Key: key,
Host: host,
}
}
func (m DiagnosticManager) BrowseLog(ctx context.Context, host *HostSystem, key string, start, lines int32) (*types.DiagnosticManagerLogHeader, error) {
req := types.BrowseDiagnosticLog{
This: m.Reference(),
Key: key,
Start: start,
Lines: lines,
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.BrowseDiagnosticLog(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (m DiagnosticManager) GenerateLogBundles(ctx context.Context, includeDefault bool, host []*HostSystem) (*Task, error) {
req := types.GenerateLogBundles_Task{
This: m.Reference(),
IncludeDefault: includeDefault,
}
for _, h := range host {
req.Host = append(req.Host, h.Reference())
}
res, err := methods.GenerateLogBundles_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
func (m DiagnosticManager) QueryDescriptions(ctx context.Context, host *HostSystem) ([]types.DiagnosticManagerLogDescriptor, error) {
req := types.QueryDescriptions{
This: m.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.QueryDescriptions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/storage_pod.go | vendor/github.com/vmware/govmomi/object/storage_pod.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type StoragePod struct {
*Folder
}
func NewStoragePod(c *vim25.Client, ref types.ManagedObjectReference) *StoragePod {
return &StoragePod{
Folder: &Folder{
Common: NewCommon(c, ref),
},
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/host_date_time_system.go | vendor/github.com/vmware/govmomi/object/host_date_time_system.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"time"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type HostDateTimeSystem struct {
Common
}
func NewHostDateTimeSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostDateTimeSystem {
return &HostDateTimeSystem{
Common: NewCommon(c, ref),
}
}
func (s HostDateTimeSystem) UpdateConfig(ctx context.Context, config types.HostDateTimeConfig) error {
req := types.UpdateDateTimeConfig{
This: s.Reference(),
Config: config,
}
_, err := methods.UpdateDateTimeConfig(ctx, s.c, &req)
return err
}
func (s HostDateTimeSystem) Update(ctx context.Context, date time.Time) error {
req := types.UpdateDateTime{
This: s.Reference(),
DateTime: date,
}
_, err := methods.UpdateDateTime(ctx, s.c, &req)
return err
}
func (s HostDateTimeSystem) Query(ctx context.Context) (*time.Time, error) {
req := types.QueryDateTime{
This: s.Reference(),
}
res, err := methods.QueryDateTime(ctx, s.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/file_manager.go | vendor/github.com/vmware/govmomi/object/file_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type FileManager struct {
Common
}
func NewFileManager(c *vim25.Client) *FileManager {
f := FileManager{
Common: NewCommon(c, *c.ServiceContent.FileManager),
}
return &f
}
func (f FileManager) CopyDatastoreFile(ctx context.Context, sourceName string, sourceDatacenter *Datacenter, destinationName string, destinationDatacenter *Datacenter, force bool) (*Task, error) {
req := types.CopyDatastoreFile_Task{
This: f.Reference(),
SourceName: sourceName,
DestinationName: destinationName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destinationDatacenter != nil {
ref := destinationDatacenter.Reference()
req.DestinationDatacenter = &ref
}
res, err := methods.CopyDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
// DeleteDatastoreFile deletes the specified file or folder from the datastore.
func (f FileManager) DeleteDatastoreFile(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.DeleteDatastoreFile_Task{
This: f.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.DeleteDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
// MakeDirectory creates a folder using the specified name.
func (f FileManager) MakeDirectory(ctx context.Context, name string, dc *Datacenter, createParentDirectories bool) error {
req := types.MakeDirectory{
This: f.Reference(),
Name: name,
CreateParentDirectories: types.NewBool(createParentDirectories),
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
_, err := methods.MakeDirectory(ctx, f.c, &req)
return err
}
func (f FileManager) MoveDatastoreFile(ctx context.Context, sourceName string, sourceDatacenter *Datacenter, destinationName string, destinationDatacenter *Datacenter, force bool) (*Task, error) {
req := types.MoveDatastoreFile_Task{
This: f.Reference(),
SourceName: sourceName,
DestinationName: destinationName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destinationDatacenter != nil {
ref := destinationDatacenter.Reference()
req.DestinationDatacenter = &ref
}
res, err := methods.MoveDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/datacenter.go | vendor/github.com/vmware/govmomi/object/datacenter.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"path"
"github.com/vmware/govmomi/fault"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type DatacenterFolders struct {
VmFolder *Folder
HostFolder *Folder
DatastoreFolder *Folder
NetworkFolder *Folder
}
type Datacenter struct {
Common
}
func NewDatacenter(c *vim25.Client, ref types.ManagedObjectReference) *Datacenter {
return &Datacenter{
Common: NewCommon(c, ref),
}
}
func (d *Datacenter) Folders(ctx context.Context) (*DatacenterFolders, error) {
var md mo.Datacenter
ps := []string{"name", "vmFolder", "hostFolder", "datastoreFolder", "networkFolder"}
err := d.Properties(ctx, d.Reference(), ps, &md)
if err != nil {
return nil, err
}
df := &DatacenterFolders{
VmFolder: NewFolder(d.c, md.VmFolder),
HostFolder: NewFolder(d.c, md.HostFolder),
DatastoreFolder: NewFolder(d.c, md.DatastoreFolder),
NetworkFolder: NewFolder(d.c, md.NetworkFolder),
}
paths := []struct {
name string
path *string
}{
{"vm", &df.VmFolder.InventoryPath},
{"host", &df.HostFolder.InventoryPath},
{"datastore", &df.DatastoreFolder.InventoryPath},
{"network", &df.NetworkFolder.InventoryPath},
}
dcPath := d.InventoryPath
if dcPath == "" {
dcPath = "/" + md.Name
}
for _, p := range paths {
*p.path = path.Join(dcPath, p.name)
}
return df, nil
}
func (d Datacenter) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: d.Reference(),
}
res, err := methods.Destroy_Task(ctx, d.c, &req)
if err != nil {
return nil, err
}
return NewTask(d.c, res.Returnval), nil
}
// PowerOnVM powers on multiple virtual machines with a single vCenter call.
// If called against ESX, serially powers on the list of VMs and the returned *Task will always be nil.
func (d Datacenter) PowerOnVM(ctx context.Context, vm []types.ManagedObjectReference, option ...types.BaseOptionValue) (*Task, error) {
if d.Client().IsVC() {
req := types.PowerOnMultiVM_Task{
This: d.Reference(),
Vm: vm,
Option: option,
}
res, err := methods.PowerOnMultiVM_Task(ctx, d.c, &req)
if err != nil {
return nil, err
}
return NewTask(d.c, res.Returnval), nil
}
for _, ref := range vm {
obj := NewVirtualMachine(d.Client(), ref)
task, err := obj.PowerOn(ctx)
if err != nil {
return nil, err
}
err = task.Wait(ctx)
if err != nil {
// Ignore any InvalidPowerState fault, as it indicates the VM is already powered on
if !fault.Is(err, &types.InvalidPowerState{}) {
return nil, err
}
}
}
return nil, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/datastore_path.go | vendor/github.com/vmware/govmomi/object/datastore_path.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"fmt"
"path"
"strings"
)
// DatastorePath contains the components of a datastore path.
type DatastorePath struct {
Datastore string
Path string
}
// FromString parses a datastore path.
// Returns true if the path could be parsed, false otherwise.
func (p *DatastorePath) FromString(s string) bool {
if s == "" {
return false
}
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, "[") {
return false
}
s = s[1:]
ix := strings.Index(s, "]")
if ix < 0 {
return false
}
p.Datastore = s[:ix]
p.Path = strings.TrimSpace(s[ix+1:])
return true
}
// String formats a datastore path.
func (p *DatastorePath) String() string {
s := fmt.Sprintf("[%s]", p.Datastore)
if p.Path == "" {
return s
}
return strings.Join([]string{s, p.Path}, " ")
}
// IsVMDK returns true if Path has a ".vmdk" extension
func (p *DatastorePath) IsVMDK() bool {
return path.Ext(p.Path) == ".vmdk"
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/virtual_machine.go | vendor/github.com/vmware/govmomi/object/virtual_machine.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"errors"
"fmt"
"net"
"path"
"strings"
"github.com/vmware/govmomi/nfc"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
const (
PropRuntimePowerState = "summary.runtime.powerState"
PropConfigTemplate = "summary.config.template"
)
type VirtualMachine struct {
Common
}
// extractDiskLayoutFiles is a helper function used to extract file keys for
// all disk files attached to the virtual machine at the current point of
// running.
func extractDiskLayoutFiles(diskLayoutList []types.VirtualMachineFileLayoutExDiskLayout) []int {
var result []int
for _, layoutExDisk := range diskLayoutList {
for _, link := range layoutExDisk.Chain {
for i := range link.FileKey { // diskDescriptor, diskExtent pairs
result = append(result, int(link.FileKey[i]))
}
}
}
return result
}
// removeKey is a helper function for removing a specific file key from a list
// of keys associated with disks attached to a virtual machine.
func removeKey(l *[]int, key int) {
for i, k := range *l {
if k == key {
*l = append((*l)[:i], (*l)[i+1:]...)
break
}
}
}
func NewVirtualMachine(c *vim25.Client, ref types.ManagedObjectReference) *VirtualMachine {
return &VirtualMachine{
Common: NewCommon(c, ref),
}
}
func (v VirtualMachine) PowerState(ctx context.Context) (types.VirtualMachinePowerState, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{PropRuntimePowerState}, &o)
if err != nil {
return "", err
}
return o.Summary.Runtime.PowerState, nil
}
func (v VirtualMachine) IsTemplate(ctx context.Context) (bool, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{PropConfigTemplate}, &o)
if err != nil {
return false, err
}
return o.Summary.Config.Template, nil
}
func (v VirtualMachine) PowerOn(ctx context.Context) (*Task, error) {
req := types.PowerOnVM_Task{
This: v.Reference(),
}
res, err := methods.PowerOnVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) PowerOff(ctx context.Context) (*Task, error) {
req := types.PowerOffVM_Task{
This: v.Reference(),
}
res, err := methods.PowerOffVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) PutUsbScanCodes(ctx context.Context, spec types.UsbScanCodeSpec) (int32, error) {
req := types.PutUsbScanCodes{
This: v.Reference(),
Spec: spec,
}
res, err := methods.PutUsbScanCodes(ctx, v.c, &req)
if err != nil {
return 0, err
}
return res.Returnval, nil
}
func (v VirtualMachine) Reset(ctx context.Context) (*Task, error) {
req := types.ResetVM_Task{
This: v.Reference(),
}
res, err := methods.ResetVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Suspend(ctx context.Context) (*Task, error) {
req := types.SuspendVM_Task{
This: v.Reference(),
}
res, err := methods.SuspendVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) ShutdownGuest(ctx context.Context) error {
req := types.ShutdownGuest{
This: v.Reference(),
}
_, err := methods.ShutdownGuest(ctx, v.c, &req)
return err
}
func (v VirtualMachine) StandbyGuest(ctx context.Context) error {
req := types.StandbyGuest{
This: v.Reference(),
}
_, err := methods.StandbyGuest(ctx, v.c, &req)
return err
}
func (v VirtualMachine) RebootGuest(ctx context.Context) error {
req := types.RebootGuest{
This: v.Reference(),
}
_, err := methods.RebootGuest(ctx, v.c, &req)
return err
}
func (v VirtualMachine) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: v.Reference(),
}
res, err := methods.Destroy_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Clone(ctx context.Context, folder *Folder, name string, config types.VirtualMachineCloneSpec) (*Task, error) {
req := types.CloneVM_Task{
This: v.Reference(),
Folder: folder.Reference(),
Name: name,
Spec: config,
}
res, err := methods.CloneVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) InstantClone(ctx context.Context, config types.VirtualMachineInstantCloneSpec) (*Task, error) {
req := types.InstantClone_Task{
This: v.Reference(),
Spec: config,
}
res, err := methods.InstantClone_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Customize(ctx context.Context, spec types.CustomizationSpec) (*Task, error) {
req := types.CustomizeVM_Task{
This: v.Reference(),
Spec: spec,
}
res, err := methods.CustomizeVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Relocate(ctx context.Context, config types.VirtualMachineRelocateSpec, priority types.VirtualMachineMovePriority) (*Task, error) {
req := types.RelocateVM_Task{
This: v.Reference(),
Spec: config,
Priority: priority,
}
res, err := methods.RelocateVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Reconfigure(ctx context.Context, config types.VirtualMachineConfigSpec) (*Task, error) {
req := types.ReconfigVM_Task{
This: v.Reference(),
Spec: config,
}
res, err := methods.ReconfigVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) RefreshStorageInfo(ctx context.Context) error {
req := types.RefreshStorageInfo{
This: v.Reference(),
}
_, err := methods.RefreshStorageInfo(ctx, v.c, &req)
return err
}
// WaitForIP waits for the VM guest.ipAddress property to report an IP address.
// Waits for an IPv4 address if the v4 param is true.
func (v VirtualMachine) WaitForIP(ctx context.Context, v4 ...bool) (string, error) {
var ip string
p := property.DefaultCollector(v.c)
err := property.Wait(ctx, p, v.Reference(), []string{"guest.ipAddress"}, func(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Name != "guest.ipAddress" {
continue
}
if c.Op != types.PropertyChangeOpAssign {
continue
}
if c.Val == nil {
continue
}
ip = c.Val.(string)
if len(v4) == 1 && v4[0] {
if net.ParseIP(ip).To4() == nil {
return false
}
}
return true
}
return false
})
if err != nil {
return "", err
}
return ip, nil
}
// WaitForNetIP waits for the VM guest.net property to report an IP address for all VM NICs.
// Only consider IPv4 addresses if the v4 param is true.
// By default, wait for all NICs to get an IP address, unless 1 or more device is given.
// A device can be specified by the MAC address or the device name, e.g. "ethernet-0".
// Returns a map with MAC address as the key and IP address list as the value.
func (v VirtualMachine) WaitForNetIP(ctx context.Context, v4 bool, device ...string) (map[string][]string, error) {
macs := make(map[string][]string)
eths := make(map[string]string)
p := property.DefaultCollector(v.c)
// Wait for all NICs to have a MacAddress, which may not be generated yet.
err := property.Wait(ctx, p, v.Reference(), []string{"config.hardware.device"}, func(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Op != types.PropertyChangeOpAssign {
continue
}
devices := VirtualDeviceList(c.Val.(types.ArrayOfVirtualDevice).VirtualDevice)
for _, d := range devices {
if nic, ok := d.(types.BaseVirtualEthernetCard); ok {
// Convert to lower so that e.g. 00:50:56:83:3A:5D is treated the
// same as 00:50:56:83:3a:5d
mac := strings.ToLower(nic.GetVirtualEthernetCard().MacAddress)
if mac == "" {
return false
}
macs[mac] = nil
eths[devices.Name(d)] = mac
}
}
}
return true
})
if err != nil {
return nil, err
}
if len(device) != 0 {
// Only wait for specific NIC(s)
macs = make(map[string][]string)
for _, mac := range device {
if eth, ok := eths[mac]; ok {
mac = eth // device name, e.g. "ethernet-0"
}
macs[mac] = nil
}
}
err = property.Wait(ctx, p, v.Reference(), []string{"guest.net"}, func(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Op != types.PropertyChangeOpAssign {
continue
}
nics := c.Val.(types.ArrayOfGuestNicInfo).GuestNicInfo
for _, nic := range nics {
// Convert to lower so that e.g. 00:50:56:83:3A:5D is treated the
// same as 00:50:56:83:3a:5d
mac := strings.ToLower(nic.MacAddress)
if mac == "" || nic.IpConfig == nil {
continue
}
for _, ip := range nic.IpConfig.IpAddress {
if _, ok := macs[mac]; !ok {
continue // Ignore any that don't correspond to a VM device
}
if v4 && net.ParseIP(ip.IpAddress).To4() == nil {
continue // Ignore non IPv4 address
}
macs[mac] = append(macs[mac], ip.IpAddress)
}
}
}
for _, ips := range macs {
if len(ips) == 0 {
return false
}
}
return true
})
if err != nil {
return nil, err
}
return macs, nil
}
// Device returns the VirtualMachine's config.hardware.device property.
func (v VirtualMachine) Device(ctx context.Context) (VirtualDeviceList, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"config.hardware.device", "summary.runtime.connectionState"}, &o)
if err != nil {
return nil, err
}
// Quoting the SDK doc:
// The virtual machine configuration is not guaranteed to be available.
// For example, the configuration information would be unavailable if the server
// is unable to access the virtual machine files on disk, and is often also unavailable
// during the initial phases of virtual machine creation.
if o.Config == nil {
return nil, fmt.Errorf("%s Config is not available, connectionState=%s",
v.Reference(), o.Summary.Runtime.ConnectionState)
}
return VirtualDeviceList(o.Config.Hardware.Device), nil
}
func (v VirtualMachine) EnvironmentBrowser(ctx context.Context) (*EnvironmentBrowser, error) {
var vm mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"environmentBrowser"}, &vm)
if err != nil {
return nil, err
}
return NewEnvironmentBrowser(v.c, vm.EnvironmentBrowser), nil
}
func (v VirtualMachine) HostSystem(ctx context.Context) (*HostSystem, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"summary.runtime.host"}, &o)
if err != nil {
return nil, err
}
host := o.Summary.Runtime.Host
if host == nil {
return nil, errors.New("VM doesn't have a HostSystem")
}
return NewHostSystem(v.c, *host), nil
}
func (v VirtualMachine) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"resourcePool"}, &o)
if err != nil {
return nil, err
}
rp := o.ResourcePool
if rp == nil {
return nil, errors.New("VM doesn't have a resourcePool")
}
return NewResourcePool(v.c, *rp), nil
}
func diskFileOperation(op types.VirtualDeviceConfigSpecOperation, fop types.VirtualDeviceConfigSpecFileOperation, device types.BaseVirtualDevice) types.VirtualDeviceConfigSpecFileOperation {
if disk, ok := device.(*types.VirtualDisk); ok {
// Special case to attach an existing disk
if op == types.VirtualDeviceConfigSpecOperationAdd && disk.CapacityInKB == 0 && disk.CapacityInBytes == 0 {
childDisk := false
if b, ok := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {
childDisk = b.Parent != nil
}
if !childDisk {
fop = "" // existing disk
}
}
return fop
}
return ""
}
func (v VirtualMachine) configureDevice(ctx context.Context, profile []types.BaseVirtualMachineProfileSpec, op types.VirtualDeviceConfigSpecOperation, fop types.VirtualDeviceConfigSpecFileOperation, devices ...types.BaseVirtualDevice) error {
spec := types.VirtualMachineConfigSpec{}
for _, device := range devices {
config := &types.VirtualDeviceConfigSpec{
Device: device,
Operation: op,
FileOperation: diskFileOperation(op, fop, device),
Profile: profile,
}
spec.DeviceChange = append(spec.DeviceChange, config)
}
task, err := v.Reconfigure(ctx, spec)
if err != nil {
return err
}
return task.Wait(ctx)
}
// AddDevice adds the given devices to the VirtualMachine
func (v VirtualMachine) AddDevice(ctx context.Context, device ...types.BaseVirtualDevice) error {
return v.AddDeviceWithProfile(ctx, nil, device...)
}
// AddDeviceWithProfile adds the given devices to the VirtualMachine with the given profile
func (v VirtualMachine) AddDeviceWithProfile(ctx context.Context, profile []types.BaseVirtualMachineProfileSpec, device ...types.BaseVirtualDevice) error {
return v.configureDevice(ctx, profile, types.VirtualDeviceConfigSpecOperationAdd, types.VirtualDeviceConfigSpecFileOperationCreate, device...)
}
// EditDevice edits the given (existing) devices on the VirtualMachine
func (v VirtualMachine) EditDevice(ctx context.Context, device ...types.BaseVirtualDevice) error {
return v.EditDeviceWithProfile(ctx, nil, device...)
}
// EditDeviceWithProfile edits the given (existing) devices on the VirtualMachine with the given profile
func (v VirtualMachine) EditDeviceWithProfile(ctx context.Context, profile []types.BaseVirtualMachineProfileSpec, device ...types.BaseVirtualDevice) error {
return v.configureDevice(ctx, profile, types.VirtualDeviceConfigSpecOperationEdit, types.VirtualDeviceConfigSpecFileOperationReplace, device...)
}
// RemoveDevice removes the given devices on the VirtualMachine
func (v VirtualMachine) RemoveDevice(ctx context.Context, keepFiles bool, device ...types.BaseVirtualDevice) error {
fop := types.VirtualDeviceConfigSpecFileOperationDestroy
if keepFiles {
fop = ""
}
return v.configureDevice(ctx, nil, types.VirtualDeviceConfigSpecOperationRemove, fop, device...)
}
// AttachDisk attaches the given disk to the VirtualMachine
func (v VirtualMachine) AttachDisk(ctx context.Context, id string, datastore *Datastore, controllerKey int32, unitNumber *int32) error {
req := types.AttachDisk_Task{
This: v.Reference(),
DiskId: types.ID{Id: id},
Datastore: datastore.Reference(),
ControllerKey: controllerKey,
UnitNumber: unitNumber,
}
res, err := methods.AttachDisk_Task(ctx, v.c, &req)
if err != nil {
return err
}
task := NewTask(v.c, res.Returnval)
return task.Wait(ctx)
}
// DetachDisk detaches the given disk from the VirtualMachine
func (v VirtualMachine) DetachDisk(ctx context.Context, id string) error {
req := types.DetachDisk_Task{
This: v.Reference(),
DiskId: types.ID{Id: id},
}
res, err := methods.DetachDisk_Task(ctx, v.c, &req)
if err != nil {
return err
}
task := NewTask(v.c, res.Returnval)
return task.Wait(ctx)
}
// BootOptions returns the VirtualMachine's config.bootOptions property.
func (v VirtualMachine) BootOptions(ctx context.Context) (*types.VirtualMachineBootOptions, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"config.bootOptions"}, &o)
if err != nil {
return nil, err
}
return o.Config.BootOptions, nil
}
// SetBootOptions reconfigures the VirtualMachine with the given options.
func (v VirtualMachine) SetBootOptions(ctx context.Context, options *types.VirtualMachineBootOptions) error {
spec := types.VirtualMachineConfigSpec{}
spec.BootOptions = options
task, err := v.Reconfigure(ctx, spec)
if err != nil {
return err
}
return task.Wait(ctx)
}
// Answer answers a pending question.
func (v VirtualMachine) Answer(ctx context.Context, id, answer string) error {
req := types.AnswerVM{
This: v.Reference(),
QuestionId: id,
AnswerChoice: answer,
}
_, err := methods.AnswerVM(ctx, v.c, &req)
if err != nil {
return err
}
return nil
}
func (v VirtualMachine) AcquireTicket(ctx context.Context, kind string) (*types.VirtualMachineTicket, error) {
req := types.AcquireTicket{
This: v.Reference(),
TicketType: kind,
}
res, err := methods.AcquireTicket(ctx, v.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// CreateSnapshot creates a new snapshot of a virtual machine.
func (v VirtualMachine) CreateSnapshot(ctx context.Context, name string, description string, memory bool, quiesce bool) (*Task, error) {
req := types.CreateSnapshot_Task{
This: v.Reference(),
Name: name,
Description: description,
Memory: memory,
Quiesce: quiesce,
}
res, err := methods.CreateSnapshot_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
// RemoveAllSnapshot removes all snapshots of a virtual machine
func (v VirtualMachine) RemoveAllSnapshot(ctx context.Context, consolidate *bool) (*Task, error) {
req := types.RemoveAllSnapshots_Task{
This: v.Reference(),
Consolidate: consolidate,
}
res, err := methods.RemoveAllSnapshots_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
type snapshotMap map[string][]types.ManagedObjectReference
func (m snapshotMap) add(parent string, tree []types.VirtualMachineSnapshotTree) {
for i, st := range tree {
sname := st.Name
names := []string{sname, st.Snapshot.Value}
if parent != "" {
sname = path.Join(parent, sname)
// Add full path as an option to resolve duplicate names
names = append(names, sname)
}
for _, name := range names {
m[name] = append(m[name], tree[i].Snapshot)
}
m.add(sname, st.ChildSnapshotList)
}
}
// SnapshotSize calculates the size of a given snapshot in bytes. If the
// snapshot is current, disk files not associated with any parent snapshot are
// included in size calculations. This allows for measuring and including the
// growth from the last fixed snapshot to the present state.
func SnapshotSize(info types.ManagedObjectReference, parent *types.ManagedObjectReference, vmlayout *types.VirtualMachineFileLayoutEx, isCurrent bool) int {
var fileKeyList []int
var parentFiles []int
var allSnapshotFiles []int
diskFiles := extractDiskLayoutFiles(vmlayout.Disk)
for _, layout := range vmlayout.Snapshot {
diskLayout := extractDiskLayoutFiles(layout.Disk)
allSnapshotFiles = append(allSnapshotFiles, diskLayout...)
if layout.Key.Value == info.Value {
fileKeyList = append(fileKeyList, int(layout.DataKey)) // The .vmsn file
fileKeyList = append(fileKeyList, diskLayout...) // The .vmdk files
} else if parent != nil && layout.Key.Value == parent.Value {
parentFiles = append(parentFiles, diskLayout...)
}
}
for _, parentFile := range parentFiles {
removeKey(&fileKeyList, parentFile)
}
for _, file := range allSnapshotFiles {
removeKey(&diskFiles, file)
}
fileKeyMap := make(map[int]types.VirtualMachineFileLayoutExFileInfo)
for _, file := range vmlayout.File {
fileKeyMap[int(file.Key)] = file
}
size := 0
for _, fileKey := range fileKeyList {
file := fileKeyMap[fileKey]
if parent != nil ||
(file.Type != string(types.VirtualMachineFileLayoutExFileTypeDiskDescriptor) &&
file.Type != string(types.VirtualMachineFileLayoutExFileTypeDiskExtent)) {
size += int(file.Size)
}
}
if isCurrent {
for _, diskFile := range diskFiles {
file := fileKeyMap[diskFile]
size += int(file.Size)
}
}
return size
}
// FindSnapshot supports snapshot lookup by name, where name can be:
// 1) snapshot ManagedObjectReference.Value (unique)
// 2) snapshot name (may not be unique)
// 3) snapshot tree path (may not be unique)
func (v VirtualMachine) FindSnapshot(ctx context.Context, name string) (*types.ManagedObjectReference, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"snapshot"}, &o)
if err != nil {
return nil, err
}
if o.Snapshot == nil || len(o.Snapshot.RootSnapshotList) == 0 {
return nil, errors.New("no snapshots for this VM")
}
m := make(snapshotMap)
m.add("", o.Snapshot.RootSnapshotList)
s := m[name]
switch len(s) {
case 0:
return nil, fmt.Errorf("snapshot %q not found", name)
case 1:
return &s[0], nil
default:
return nil, fmt.Errorf("%q resolves to %d snapshots", name, len(s))
}
}
// RemoveSnapshot removes a named snapshot
func (v VirtualMachine) RemoveSnapshot(ctx context.Context, name string, removeChildren bool, consolidate *bool) (*Task, error) {
snapshot, err := v.FindSnapshot(ctx, name)
if err != nil {
return nil, err
}
req := types.RemoveSnapshot_Task{
This: snapshot.Reference(),
RemoveChildren: removeChildren,
Consolidate: consolidate,
}
res, err := methods.RemoveSnapshot_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
// RevertToCurrentSnapshot reverts to the current snapshot
func (v VirtualMachine) RevertToCurrentSnapshot(ctx context.Context, suppressPowerOn bool) (*Task, error) {
req := types.RevertToCurrentSnapshot_Task{
This: v.Reference(),
SuppressPowerOn: types.NewBool(suppressPowerOn),
}
res, err := methods.RevertToCurrentSnapshot_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
// RevertToSnapshot reverts to a named snapshot
func (v VirtualMachine) RevertToSnapshot(ctx context.Context, name string, suppressPowerOn bool) (*Task, error) {
snapshot, err := v.FindSnapshot(ctx, name)
if err != nil {
return nil, err
}
req := types.RevertToSnapshot_Task{
This: snapshot.Reference(),
SuppressPowerOn: types.NewBool(suppressPowerOn),
}
res, err := methods.RevertToSnapshot_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
// IsToolsRunning returns true if VMware Tools is currently running in the guest OS, and false otherwise.
func (v VirtualMachine) IsToolsRunning(ctx context.Context) (bool, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"guest.toolsRunningStatus"}, &o)
if err != nil {
return false, err
}
return o.Guest.ToolsRunningStatus == string(types.VirtualMachineToolsRunningStatusGuestToolsRunning), nil
}
// Wait for the VirtualMachine to change to the desired power state.
func (v VirtualMachine) WaitForPowerState(ctx context.Context, state types.VirtualMachinePowerState) error {
p := property.DefaultCollector(v.c)
err := property.Wait(ctx, p, v.Reference(), []string{PropRuntimePowerState}, func(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Name != PropRuntimePowerState {
continue
}
if c.Val == nil {
continue
}
ps := c.Val.(types.VirtualMachinePowerState)
if ps == state {
return true
}
}
return false
})
return err
}
func (v VirtualMachine) MarkAsTemplate(ctx context.Context) error {
req := types.MarkAsTemplate{
This: v.Reference(),
}
_, err := methods.MarkAsTemplate(ctx, v.c, &req)
if err != nil {
return err
}
return nil
}
func (v VirtualMachine) MarkAsVirtualMachine(ctx context.Context, pool ResourcePool, host *HostSystem) error {
req := types.MarkAsVirtualMachine{
This: v.Reference(),
Pool: pool.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
_, err := methods.MarkAsVirtualMachine(ctx, v.c, &req)
if err != nil {
return err
}
return nil
}
func (v VirtualMachine) Migrate(ctx context.Context, pool *ResourcePool, host *HostSystem, priority types.VirtualMachineMovePriority, state types.VirtualMachinePowerState) (*Task, error) {
req := types.MigrateVM_Task{
This: v.Reference(),
Priority: priority,
State: state,
}
if pool != nil {
ref := pool.Reference()
req.Pool = &ref
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.MigrateVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Unregister(ctx context.Context) error {
req := types.UnregisterVM{
This: v.Reference(),
}
_, err := methods.UnregisterVM(ctx, v.Client(), &req)
return err
}
func (v VirtualMachine) MountToolsInstaller(ctx context.Context) error {
req := types.MountToolsInstaller{
This: v.Reference(),
}
_, err := methods.MountToolsInstaller(ctx, v.Client(), &req)
return err
}
func (v VirtualMachine) UnmountToolsInstaller(ctx context.Context) error {
req := types.UnmountToolsInstaller{
This: v.Reference(),
}
_, err := methods.UnmountToolsInstaller(ctx, v.Client(), &req)
return err
}
func (v VirtualMachine) UpgradeTools(ctx context.Context, options string) (*Task, error) {
req := types.UpgradeTools_Task{
This: v.Reference(),
InstallerOptions: options,
}
res, err := methods.UpgradeTools_Task(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Export(ctx context.Context) (*nfc.Lease, error) {
req := types.ExportVm{
This: v.Reference(),
}
res, err := methods.ExportVm(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return nfc.NewLease(v.c, res.Returnval), nil
}
func (v VirtualMachine) UpgradeVM(ctx context.Context, version string) (*Task, error) {
req := types.UpgradeVM_Task{
This: v.Reference(),
Version: version,
}
res, err := methods.UpgradeVM_Task(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
// UUID is a helper to get the UUID of the VirtualMachine managed object.
// This method returns an empty string if an error occurs when retrieving UUID from the VirtualMachine object.
func (v VirtualMachine) UUID(ctx context.Context) string {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"config.uuid"}, &o)
if err != nil {
return ""
}
if o.Config != nil {
return o.Config.Uuid
}
return ""
}
func (v VirtualMachine) QueryChangedDiskAreas(ctx context.Context, baseSnapshot, curSnapshot *types.ManagedObjectReference, disk *types.VirtualDisk, offset int64) (types.DiskChangeInfo, error) {
var noChange types.DiskChangeInfo
var err error
if offset > disk.CapacityInBytes {
return noChange, fmt.Errorf("offset is greater than the disk size (%#x and %#x)", offset, disk.CapacityInBytes)
} else if offset == disk.CapacityInBytes {
return types.DiskChangeInfo{StartOffset: offset, Length: 0}, nil
}
var b mo.VirtualMachineSnapshot
err = v.Properties(ctx, baseSnapshot.Reference(), []string{"config.hardware"}, &b)
if err != nil {
return noChange, fmt.Errorf("failed to fetch config.hardware of snapshot %s: %s", baseSnapshot, err)
}
var changeId *string
for _, vd := range b.Config.Hardware.Device {
d := vd.GetVirtualDevice()
if d.Key != disk.Key {
continue
}
// As per VDDK programming guide, these are the four types of disks
// that support CBT, see "Gathering Changed Block Information".
if b, ok := d.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {
changeId = &b.ChangeId
break
}
if b, ok := d.Backing.(*types.VirtualDiskSparseVer2BackingInfo); ok {
changeId = &b.ChangeId
break
}
if b, ok := d.Backing.(*types.VirtualDiskRawDiskMappingVer1BackingInfo); ok {
changeId = &b.ChangeId
break
}
if b, ok := d.Backing.(*types.VirtualDiskRawDiskVer2BackingInfo); ok {
changeId = &b.ChangeId
break
}
return noChange, fmt.Errorf("disk %d has backing info without .ChangeId: %t", disk.Key, d.Backing)
}
if changeId == nil || *changeId == "" {
return noChange, fmt.Errorf("CBT is not enabled on disk %d", disk.Key)
}
req := types.QueryChangedDiskAreas{
This: v.Reference(),
Snapshot: curSnapshot,
DeviceKey: disk.Key,
StartOffset: offset,
ChangeId: *changeId,
}
res, err := methods.QueryChangedDiskAreas(ctx, v.Client(), &req)
if err != nil {
return noChange, err
}
return res.Returnval, nil
}
// ExportSnapshot exports all VMDK-files up to (but not including) a specified snapshot. This
// is useful when exporting a running VM.
func (v *VirtualMachine) ExportSnapshot(ctx context.Context, snapshot *types.ManagedObjectReference) (*nfc.Lease, error) {
req := types.ExportSnapshot{
This: *snapshot,
}
resp, err := methods.ExportSnapshot(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return nfc.NewLease(v.c, resp.Returnval), nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/search_index.go | vendor/github.com/vmware/govmomi/object/search_index.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type SearchIndex struct {
Common
}
func NewSearchIndex(c *vim25.Client) *SearchIndex {
s := SearchIndex{
Common: NewCommon(c, *c.ServiceContent.SearchIndex),
}
return &s
}
// FindByDatastorePath finds a virtual machine by its location on a datastore.
func (s SearchIndex) FindByDatastorePath(ctx context.Context, dc *Datacenter, path string) (Reference, error) {
req := types.FindByDatastorePath{
This: s.Reference(),
Datacenter: dc.Reference(),
Path: path,
}
res, err := methods.FindByDatastorePath(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByDnsName finds a virtual machine or host by DNS name.
func (s SearchIndex) FindByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) (Reference, error) {
req := types.FindByDnsName{
This: s.Reference(),
DnsName: dnsName,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByDnsName(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByInventoryPath finds a managed entity based on its location in the inventory.
func (s SearchIndex) FindByInventoryPath(ctx context.Context, path string) (Reference, error) {
req := types.FindByInventoryPath{
This: s.Reference(),
InventoryPath: path,
}
res, err := methods.FindByInventoryPath(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
r := NewReference(s.c, *res.Returnval)
type common interface {
SetInventoryPath(string)
}
if c, ok := r.(common); ok {
c.SetInventoryPath(path)
}
return r, nil
}
// FindByIp finds a virtual machine or host by IP address.
func (s SearchIndex) FindByIp(ctx context.Context, dc *Datacenter, ip string, vmSearch bool) (Reference, error) {
req := types.FindByIp{
This: s.Reference(),
Ip: ip,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByIp(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByUuid finds a virtual machine or host by UUID.
func (s SearchIndex) FindByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) (Reference, error) {
req := types.FindByUuid{
This: s.Reference(),
Uuid: uuid,
VmSearch: vmSearch,
InstanceUuid: instanceUuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByUuid(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindChild finds a particular child based on a managed entity name.
func (s SearchIndex) FindChild(ctx context.Context, entity Reference, name string) (Reference, error) {
req := types.FindChild{
This: s.Reference(),
Entity: entity.Reference(),
Name: name,
}
res, err := methods.FindChild(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindAllByDnsName finds all virtual machines or hosts by DNS name.
func (s SearchIndex) FindAllByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) ([]Reference, error) {
req := types.FindAllByDnsName{
This: s.Reference(),
DnsName: dnsName,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindAllByDnsName(ctx, s.c, &req)
if err != nil {
return nil, err
}
if len(res.Returnval) == 0 {
return nil, nil
}
var references []Reference
for _, returnval := range res.Returnval {
references = append(references, NewReference(s.c, returnval))
}
return references, nil
}
// FindAllByIp finds all virtual machines or hosts by IP address.
func (s SearchIndex) FindAllByIp(ctx context.Context, dc *Datacenter, ip string, vmSearch bool) ([]Reference, error) {
req := types.FindAllByIp{
This: s.Reference(),
Ip: ip,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindAllByIp(ctx, s.c, &req)
if err != nil {
return nil, err
}
if len(res.Returnval) == 0 {
return nil, nil
}
var references []Reference
for _, returnval := range res.Returnval {
references = append(references, NewReference(s.c, returnval))
}
return references, nil
}
// FindAllByUuid finds all virtual machines or hosts by UUID.
func (s SearchIndex) FindAllByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) ([]Reference, error) {
req := types.FindAllByUuid{
This: s.Reference(),
Uuid: uuid,
VmSearch: vmSearch,
InstanceUuid: instanceUuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindAllByUuid(ctx, s.c, &req)
if err != nil {
return nil, err
}
if len(res.Returnval) == 0 {
return nil, nil
}
var references []Reference
for _, returnval := range res.Returnval {
references = append(references, NewReference(s.c, returnval))
}
return references, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/custom_fields_manager.go | vendor/github.com/vmware/govmomi/object/custom_fields_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"errors"
"math"
"strconv"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
var (
ErrKeyNameNotFound = errors.New("key name not found")
)
type CustomFieldsManager struct {
Common
}
// GetCustomFieldsManager wraps NewCustomFieldsManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetCustomFieldsManager(c *vim25.Client) (*CustomFieldsManager, error) {
if c.ServiceContent.CustomFieldsManager == nil {
return nil, ErrNotSupported
}
return NewCustomFieldsManager(c), nil
}
func NewCustomFieldsManager(c *vim25.Client) *CustomFieldsManager {
m := CustomFieldsManager{
Common: NewCommon(c, *c.ServiceContent.CustomFieldsManager),
}
return &m
}
func (m CustomFieldsManager) Add(ctx context.Context, name string, moType string, fieldDefPolicy *types.PrivilegePolicyDef, fieldPolicy *types.PrivilegePolicyDef) (*types.CustomFieldDef, error) {
req := types.AddCustomFieldDef{
This: m.Reference(),
Name: name,
MoType: moType,
FieldDefPolicy: fieldDefPolicy,
FieldPolicy: fieldPolicy,
}
res, err := methods.AddCustomFieldDef(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (m CustomFieldsManager) Remove(ctx context.Context, key int32) error {
req := types.RemoveCustomFieldDef{
This: m.Reference(),
Key: key,
}
_, err := methods.RemoveCustomFieldDef(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Rename(ctx context.Context, key int32, name string) error {
req := types.RenameCustomFieldDef{
This: m.Reference(),
Key: key,
Name: name,
}
_, err := methods.RenameCustomFieldDef(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Set(ctx context.Context, entity types.ManagedObjectReference, key int32, value string) error {
req := types.SetField{
This: m.Reference(),
Entity: entity,
Key: key,
Value: value,
}
_, err := methods.SetField(ctx, m.c, &req)
return err
}
type CustomFieldDefList []types.CustomFieldDef
func (m CustomFieldsManager) Field(ctx context.Context) (CustomFieldDefList, error) {
var fm mo.CustomFieldsManager
err := m.Properties(ctx, m.Reference(), []string{"field"}, &fm)
if err != nil {
return nil, err
}
return fm.Field, nil
}
func (m CustomFieldsManager) FindKey(ctx context.Context, name string) (int32, error) {
field, err := m.Field(ctx)
if err != nil {
return -1, err
}
for _, def := range field {
if def.Name == name {
return def.Key, nil
}
}
k, err := strconv.ParseInt(name, 10, 32)
if err != nil {
return -1, ErrKeyNameNotFound
}
if k >= math.MinInt32 && k <= math.MaxInt32 {
return int32(k), nil
}
return -1, ErrKeyNameNotFound
}
func (l CustomFieldDefList) ByKey(key int32) *types.CustomFieldDef {
for _, def := range l {
if def.Key == key {
return &def
}
}
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/common.go | vendor/github.com/vmware/govmomi/object/common.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"errors"
"fmt"
"path"
"strings"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
var (
ErrNotSupported = errors.New("product/version specific feature not supported by target")
)
// Common contains the fields and functions common to all objects.
type Common struct {
InventoryPath string
c *vim25.Client
r types.ManagedObjectReference
}
func (c Common) String() string {
ref := fmt.Sprintf("%v", c.Reference())
if c.InventoryPath == "" {
return ref
}
return fmt.Sprintf("%s @ %s", ref, c.InventoryPath)
}
func NewCommon(c *vim25.Client, r types.ManagedObjectReference) Common {
return Common{c: c, r: r}
}
func (c Common) Reference() types.ManagedObjectReference {
return c.r
}
func (c Common) Client() *vim25.Client {
return c.c
}
// Name returns the base name of the InventoryPath field
func (c Common) Name() string {
if c.InventoryPath == "" {
return ""
}
return path.Base(c.InventoryPath)
}
func (c *Common) SetInventoryPath(p string) {
c.InventoryPath = p
}
// ObjectName fetches the mo.ManagedEntity.Name field via the property collector.
func (c Common) ObjectName(ctx context.Context) (string, error) {
var content []types.ObjectContent
err := c.Properties(ctx, c.Reference(), []string{"name"}, &content)
if err != nil {
return "", err
}
for i := range content {
for _, prop := range content[i].PropSet {
return prop.Val.(string), nil
}
}
return "", nil
}
// Properties is a wrapper for property.DefaultCollector().RetrieveOne()
func (c Common) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst any) error {
return property.DefaultCollector(c.c).RetrieveOne(ctx, r, ps, dst)
}
func (c Common) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: c.Reference(),
}
res, err := methods.Destroy_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c Common) Rename(ctx context.Context, name string) (*Task, error) {
req := types.Rename_Task{
This: c.Reference(),
NewName: name,
}
res, err := methods.Rename_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c Common) SetCustomValue(ctx context.Context, key string, value string) error {
req := types.SetCustomValue{
This: c.Reference(),
Key: key,
Value: value,
}
_, err := methods.SetCustomValue(ctx, c.c, &req)
return err
}
var refTypeMap = map[string]string{
"datacenter": "Datacenter",
"datastore": "Datastore",
"domain": "ComputeResource",
"dvportgroup": "DistributedVirtualPortgroup",
"dvs": "DistributedVirtualSwitch",
"group": "Folder",
"host": "HostSystem",
"network": "Network",
"resgroup": "ResourcePool",
"vm": "VirtualMachine",
}
// sub types
var prefixTypeMap = map[string]struct{ prefix, kind string }{
"domain": {"c", "ClusterComputeResource"}, // extends ComputeResource
"group": {"p", "StoragePod"}, // extends Folder
"resgroup": {"v", "VirtualApp"}, // extends ResourcePool
}
// ReferenceFromString converts a string to ManagedObjectReference.
// First checks for ManagedObjectReference (MOR), in the format of:
// "$Type:$ID", e.g. "Datacenter:datacenter-3"
// Next checks for Managed Object ID (MOID), where type is derived from the ID.
// For example, "datacenter-3" is converted to a MOR "Datacenter:datacenter-3"
// Returns nil if string is not in either format.
func ReferenceFromString(s string) *types.ManagedObjectReference {
var ref types.ManagedObjectReference
if ref.FromString(s) && mo.IsManagedObjectType(ref.Type) {
return &ref
}
id := strings.SplitN(s, "-", 2)
if len(id) != 2 {
return nil
}
if kind, ok := refTypeMap[id[0]]; ok {
if p, ok := prefixTypeMap[id[0]]; ok {
if strings.HasPrefix(id[1], p.prefix) {
return &types.ManagedObjectReference{
Type: p.kind,
Value: s,
}
}
}
return &types.ManagedObjectReference{
Type: kind,
Value: s,
}
}
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/object/namespace_manager.go | vendor/github.com/vmware/govmomi/object/namespace_manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type DatastoreNamespaceManager struct {
Common
}
func NewDatastoreNamespaceManager(c *vim25.Client) *DatastoreNamespaceManager {
n := DatastoreNamespaceManager{
Common: NewCommon(c, *c.ServiceContent.DatastoreNamespaceManager),
}
return &n
}
// CreateDirectory creates a top-level directory on the given vsan datastore, using
// the given user display name hint and opaque storage policy.
func (nm DatastoreNamespaceManager) CreateDirectory(ctx context.Context, ds *Datastore, displayName string, policy string) (string, error) {
req := &types.CreateDirectory{
This: nm.Reference(),
Datastore: ds.Reference(),
DisplayName: displayName,
Policy: policy,
}
resp, err := methods.CreateDirectory(ctx, nm.c, req)
if err != nil {
return "", err
}
return resp.Returnval, nil
}
// DeleteDirectory deletes the given top-level directory from a vsan datastore.
func (nm DatastoreNamespaceManager) DeleteDirectory(ctx context.Context, dc *Datacenter, datastorePath string) error {
req := &types.DeleteDirectory{
This: nm.Reference(),
DatastorePath: datastorePath,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
if _, err := methods.DeleteDirectory(ctx, nm.c, req); err != nil {
return err
}
return nil
}
func (nm DatastoreNamespaceManager) ConvertNamespacePathToUuidPath(ctx context.Context, dc *Datacenter, datastoreURL string) (string, error) {
req := &types.ConvertNamespacePathToUuidPath{
This: nm.Reference(),
NamespaceUrl: datastoreURL,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.ConvertNamespacePathToUuidPath(ctx, nm.c, req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/property/match.go | vendor/github.com/vmware/govmomi/property/match.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package property
import (
"fmt"
"path"
"reflect"
"strconv"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
// Match provides methods for matching against types.DynamicProperty
type Match map[string]types.AnyType
// Keys returns the Match map keys as a []string
func (m Match) Keys() []string {
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
return keys
}
// Property returns true if an entry matches the given prop.
func (m Match) Property(prop types.DynamicProperty) bool {
if prop.Val == nil {
return false
}
match, ok := m[prop.Name]
if !ok {
return false
}
if match == prop.Val {
return true
}
ptype := reflect.TypeOf(prop.Val)
if strings.HasPrefix(ptype.Name(), "ArrayOf") {
pval := reflect.ValueOf(prop.Val).Field(0)
for i := 0; i < pval.Len(); i++ {
prop.Val = pval.Index(i).Interface()
if m.Property(prop) {
return true
}
}
return false
}
if reflect.TypeOf(match) != ptype {
s, ok := match.(string)
if !ok {
return false
}
// convert if we can
switch val := prop.Val.(type) {
case bool:
match, _ = strconv.ParseBool(s)
case int16:
x, _ := strconv.ParseInt(s, 10, 16)
match = int16(x)
case int32:
x, _ := strconv.ParseInt(s, 10, 32)
match = int32(x)
case int64:
match, _ = strconv.ParseInt(s, 10, 64)
case float32:
x, _ := strconv.ParseFloat(s, 32)
match = float32(x)
case float64:
match, _ = strconv.ParseFloat(s, 64)
case fmt.Stringer:
prop.Val = val.String()
case *types.CustomFieldStringValue:
prop.Val = fmt.Sprintf("%d:%s", val.Key, val.Value)
default:
if ptype.Kind() != reflect.String {
return false
}
// An enum type we can convert to a string type
prop.Val = reflect.ValueOf(prop.Val).String()
}
}
switch pval := prop.Val.(type) {
case string:
s := match.(string)
if s == "*" {
return true // TODO: path.Match fails if s contains a '/'
}
m, _ := path.Match(s, pval)
return m
default:
return reflect.DeepEqual(match, pval)
}
}
// List returns true if all given props match.
func (m Match) List(props []types.DynamicProperty) bool {
for _, p := range props {
if !m.Property(p) {
return false
}
}
return len(m) == len(props) // false if a property such as VM "guest" is unset
}
// ObjectContent returns a list of ObjectContent.Obj where the
// ObjectContent.PropSet matches all properties the Filter.
func (m Match) ObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference {
var refs []types.ManagedObjectReference
for _, o := range objects {
if m.List(o.PropSet) {
refs = append(refs, o.Obj)
}
}
return refs
}
// AnyList returns true if any given props match.
func (m Match) AnyList(props []types.DynamicProperty) bool {
for _, p := range props {
if m.Property(p) {
return true
}
}
return false
}
// AnyObjectContent returns a list of ObjectContent.Obj where the
// ObjectContent.PropSet matches any property.
func (m Match) AnyObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference {
var refs []types.ManagedObjectReference
for _, o := range objects {
if m.AnyList(o.PropSet) {
refs = append(refs, o.Obj)
}
}
return refs
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/property/filter.go | vendor/github.com/vmware/govmomi/property/filter.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package property
import (
"context"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// Filter models the Filter managed object.
//
// For more information, see:
// https://vdc-download.vmware.com/vmwb-repository/dcr-public/184bb3ba-6fa8-4574-a767-d0c96e2a38f4/ba9422ef-405c-47dd-8553-e11b619185b2/SDK/vsphere-ws/docs/ReferenceGuide/vmodl.query.PropertyCollector.Filter.html.
type Filter struct {
roundTripper soap.RoundTripper
reference types.ManagedObjectReference
}
func (f Filter) Reference() types.ManagedObjectReference {
return f.reference
}
// Destroy destroys this filter.
//
// This operation can be called explicitly, or it can take place implicitly when
// the session that created the filter is closed.
func (f *Filter) Destroy(ctx context.Context) error {
if _, err := methods.DestroyPropertyFilter(
ctx,
f.roundTripper,
&types.DestroyPropertyFilter{This: f.Reference()}); err != nil {
return err
}
f.reference = types.ManagedObjectReference{}
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/property/wait.go | vendor/github.com/vmware/govmomi/property/wait.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package property
import (
"context"
"fmt"
"github.com/vmware/govmomi/vim25/types"
)
// WaitOptions defines options for a property collector's WaitForUpdatesEx
// method.
type WaitOptions struct {
Options *types.WaitOptions
PropagateMissing bool
Truncated bool
}
// WaitFilter provides helpers to construct a types.CreateFilter for use with property.Wait
type WaitFilter struct {
types.CreateFilter
WaitOptions
}
// Add a new ObjectSpec and PropertySpec to the WaitFilter
func (f *WaitFilter) Add(obj types.ManagedObjectReference, kind string, ps []string, set ...types.BaseSelectionSpec) *WaitFilter {
spec := types.ObjectSpec{
Obj: obj,
SelectSet: set,
}
pset := types.PropertySpec{
Type: kind,
PathSet: ps,
}
if len(ps) == 0 {
pset.All = types.NewBool(true)
}
f.Spec.ObjectSet = append(f.Spec.ObjectSet, spec)
f.Spec.PropSet = append(f.Spec.PropSet, pset)
return f
}
// Wait creates a new WaitFilter and calls the specified function for each ObjectUpdate via WaitForUpdates
func Wait(ctx context.Context, c *Collector, obj types.ManagedObjectReference, ps []string, f func([]types.PropertyChange) bool) error {
filter := new(WaitFilter).Add(obj, obj.Type, ps)
return WaitForUpdates(ctx, c, filter, func(updates []types.ObjectUpdate) bool {
for _, update := range updates {
if f(update.ChangeSet) {
return true
}
}
return false
})
}
// WaitForUpdates waits for any of the specified properties of the specified
// managed object to change. It calls the specified function for every update it
// receives. If this function returns false, it continues waiting for
// subsequent updates. If this function returns true, it stops waiting and
// returns.
//
// To only receive updates for the specified managed object, the function
// creates a new property collector and calls CreateFilter. A new property
// collector is required because filters can only be added, not removed.
//
// If the Context is canceled, a call to CancelWaitForUpdates() is made and its
// error value is returned. The newly created collector is destroyed before this
// function returns (both in case of success or error).
//
// By default, ObjectUpdate.MissingSet faults are not propagated to the returned
// error, set WaitFilter.PropagateMissing=true to enable MissingSet fault
// propagation.
func WaitForUpdates(
ctx context.Context,
c *Collector,
filter *WaitFilter,
onUpdatesFn func([]types.ObjectUpdate) bool) (result error) {
pc, err := c.Create(ctx)
if err != nil {
return err
}
// Attempt to destroy the collector using the background context, as the
// specified context may have timed out or have been canceled.
defer func() {
if err := pc.Destroy(context.Background()); err != nil {
if result == nil {
result = err
} else {
result = fmt.Errorf(
"destroy property collector failed with %s after failing to wait for updates: %w",
err,
result)
}
}
}()
// Create a property filter for the property collector.
if _, err := pc.CreateFilter(ctx, filter.CreateFilter); err != nil {
return err
}
return pc.WaitForUpdatesEx(ctx, &filter.WaitOptions, onUpdatesFn)
}
// WaitForUpdates waits for any of the specified properties of the specified
// managed object to change. It calls the specified function for every update it
// receives. If this function returns false, it continues waiting for
// subsequent updates. If this function returns true, it stops waiting and
// returns.
//
// If the Context is canceled, a call to CancelWaitForUpdates() is made and its
// error value is returned.
//
// By default, ObjectUpdate.MissingSet faults are not propagated to the returned
// error, set WaitFilter.PropagateMissing=true to enable MissingSet fault
// propagation.
func WaitForUpdatesEx(
ctx context.Context,
pc *Collector,
filter *WaitFilter,
onUpdatesFn func([]types.ObjectUpdate) bool) (result error) {
// Create a property filter for the property collector.
pf, err := pc.CreateFilter(ctx, filter.CreateFilter)
if err != nil {
return err
}
// Destroy the filter using the background context, as the specified context
// may have timed out or have been canceled.
defer func() {
if err := pf.Destroy(context.Background()); err != nil {
if result == nil {
result = err
} else {
result = fmt.Errorf(
"destroy property filter failed with %s after failing to wait for updates: %w",
err,
result)
}
}
}()
return pc.WaitForUpdatesEx(ctx, &filter.WaitOptions, onUpdatesFn)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/property/collector.go | vendor/github.com/vmware/govmomi/property/collector.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package property
import (
"context"
"errors"
"fmt"
"sync"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// ErrConcurrentCollector is returned from WaitForUpdates, WaitForUpdatesEx,
// or CheckForUpdates if any of those calls are unable to obtain an exclusive
// lock for the property collector.
var ErrConcurrentCollector = fmt.Errorf(
"only one goroutine may invoke WaitForUpdates, WaitForUpdatesEx, " +
"or CheckForUpdates on a given PropertyCollector")
// Collector models the PropertyCollector managed object.
//
// For more information, see:
// https://developer.broadcom.com/xapis/vsphere-web-services-api/latest/vmodl.query.PropertyCollector.html
type Collector struct {
mu sync.Mutex
roundTripper soap.RoundTripper
reference types.ManagedObjectReference
}
// DefaultCollector returns the session's default property collector.
func DefaultCollector(c *vim25.Client) *Collector {
p := Collector{
roundTripper: c,
reference: c.ServiceContent.PropertyCollector,
}
return &p
}
func (p *Collector) Reference() types.ManagedObjectReference {
return p.reference
}
// Create creates a new session-specific Collector that can be used to
// retrieve property updates independent of any other Collector.
func (p *Collector) Create(ctx context.Context) (*Collector, error) {
req := types.CreatePropertyCollector{
This: p.Reference(),
}
res, err := methods.CreatePropertyCollector(ctx, p.roundTripper, &req)
if err != nil {
return nil, err
}
newp := Collector{
roundTripper: p.roundTripper,
reference: res.Returnval,
}
return &newp, nil
}
// Destroy destroys this Collector.
func (p *Collector) Destroy(ctx context.Context) error {
req := types.DestroyPropertyCollector{
This: p.Reference(),
}
_, err := methods.DestroyPropertyCollector(ctx, p.roundTripper, &req)
if err != nil {
return err
}
p.reference = types.ManagedObjectReference{}
return nil
}
func (p *Collector) CreateFilter(ctx context.Context, req types.CreateFilter) (*Filter, error) {
req.This = p.Reference()
resp, err := methods.CreateFilter(ctx, p.roundTripper, &req)
if err != nil {
return nil, err
}
return &Filter{roundTripper: p.roundTripper, reference: resp.Returnval}, nil
}
// Deprecated: Please use WaitForUpdatesEx instead.
func (p *Collector) WaitForUpdates(
ctx context.Context,
version string,
opts ...*types.WaitOptions) (*types.UpdateSet, error) {
if !p.mu.TryLock() {
return nil, ErrConcurrentCollector
}
defer p.mu.Unlock()
req := types.WaitForUpdatesEx{
This: p.Reference(),
Version: version,
}
if len(opts) == 1 {
req.Options = opts[0]
} else if len(opts) > 1 {
panic("only one option may be specified")
}
res, err := methods.WaitForUpdatesEx(ctx, p.roundTripper, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (p *Collector) CancelWaitForUpdates(ctx context.Context) error {
req := &types.CancelWaitForUpdates{This: p.Reference()}
_, err := methods.CancelWaitForUpdates(ctx, p.roundTripper, req)
return err
}
// RetrieveProperties wraps RetrievePropertiesEx and ContinueRetrievePropertiesEx to collect properties in batches.
func (p *Collector) RetrieveProperties(
ctx context.Context,
req types.RetrieveProperties,
maxObjectsArgs ...int32) (*types.RetrievePropertiesResponse, error) {
var opts types.RetrieveOptions
if l := len(maxObjectsArgs); l > 1 {
return nil, fmt.Errorf("maxObjectsArgs accepts a single value")
} else if l == 1 {
opts.MaxObjects = maxObjectsArgs[0]
}
objects, err := mo.RetrievePropertiesEx(ctx, p.roundTripper, types.RetrievePropertiesEx{
This: p.Reference(),
SpecSet: req.SpecSet,
Options: opts,
})
if err != nil {
return nil, err
}
return &types.RetrievePropertiesResponse{Returnval: objects}, nil
}
// Retrieve loads properties for a slice of managed objects. The dst argument
// must be a pointer to a []interface{}, which is populated with the instances
// of the specified managed objects, with the relevant properties filled in. If
// the properties slice is nil, all properties are loaded.
// Note that pointer types are optional fields that may be left as a nil value.
// The caller should check such fields for a nil value before dereferencing.
func (p *Collector) Retrieve(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst any) error {
if len(objs) == 0 {
return errors.New("object references is empty")
}
kinds := make(map[string]bool)
var propSet []types.PropertySpec
var objectSet []types.ObjectSpec
for _, obj := range objs {
if _, ok := kinds[obj.Type]; !ok {
spec := types.PropertySpec{
Type: obj.Type,
}
if len(ps) == 0 {
spec.All = types.NewBool(true)
} else {
spec.PathSet = ps
}
propSet = append(propSet, spec)
kinds[obj.Type] = true
}
objectSpec := types.ObjectSpec{
Obj: obj,
Skip: types.NewBool(false),
}
objectSet = append(objectSet, objectSpec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: objectSet,
PropSet: propSet,
},
},
}
res, err := p.RetrieveProperties(ctx, req)
if err != nil {
return err
}
if d, ok := dst.(*[]types.ObjectContent); ok {
*d = res.Returnval
return nil
}
return mo.LoadObjectContent(res.Returnval, dst)
}
// RetrieveWithFilter populates dst as Retrieve does, but only for entities
// that match the specified filter.
func (p *Collector) RetrieveWithFilter(
ctx context.Context,
objs []types.ManagedObjectReference,
ps []string,
dst any,
filter Match) error {
if len(filter) == 0 {
return p.Retrieve(ctx, objs, ps, dst)
}
var content []types.ObjectContent
err := p.Retrieve(ctx, objs, filter.Keys(), &content)
if err != nil {
return err
}
objs = filter.ObjectContent(content)
if len(objs) == 0 {
return nil
}
return p.Retrieve(ctx, objs, ps, dst)
}
// RetrieveOne calls Retrieve with a single managed object reference via Collector.Retrieve().
func (p *Collector) RetrieveOne(ctx context.Context, obj types.ManagedObjectReference, ps []string, dst any) error {
var objs = []types.ManagedObjectReference{obj}
return p.Retrieve(ctx, objs, ps, dst)
}
// WaitForUpdatesEx waits for any of the specified properties of the specified
// managed object to change. It calls the specified function for every update it
// receives an update - including the empty filter set, which can occur if no
// objects are eligible for updates.
//
// If this function returns false, it continues waiting for
// subsequent updates. If this function returns true, it stops waiting and
// returns upon receiving the first non-empty filter set.
//
// If the Context is canceled, a call to CancelWaitForUpdates() is made and its
// error value is returned.
//
// By default, ObjectUpdate.MissingSet faults are not propagated to the returned
// error, set WaitFilter.PropagateMissing=true to enable MissingSet fault
// propagation.
func (p *Collector) WaitForUpdatesEx(
ctx context.Context,
opts *WaitOptions,
onUpdatesFn func([]types.ObjectUpdate) bool) error {
if !p.mu.TryLock() {
return ErrConcurrentCollector
}
defer p.mu.Unlock()
req := types.WaitForUpdatesEx{
This: p.Reference(),
Options: opts.Options,
}
for {
res, err := methods.WaitForUpdatesEx(ctx, p.roundTripper, &req)
if err != nil {
if ctx.Err() == context.Canceled {
return p.CancelWaitForUpdates(context.Background())
}
return err
}
set := res.Returnval
if set == nil {
if req.Options != nil && req.Options.MaxWaitSeconds != nil {
return nil // WaitOptions.MaxWaitSeconds exceeded
}
// Retry if the result came back empty
continue
}
req.Version = set.Version
opts.Truncated = false
if set.Truncated != nil {
opts.Truncated = *set.Truncated
}
if len(set.FilterSet) == 0 {
// Trigger callbacks in case callers need to be notified
// of the empty filter set.
_ = onUpdatesFn(make([]types.ObjectUpdate, 0))
}
for _, fs := range set.FilterSet {
if opts.PropagateMissing {
for i := range fs.ObjectSet {
for _, p := range fs.ObjectSet[i].MissingSet {
// Same behavior as mo.ObjectContentToType()
return soap.WrapVimFault(p.Fault.Fault)
}
}
}
if onUpdatesFn(fs.ObjectSet) {
return nil
}
}
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/find/finder.go | vendor/github.com/vmware/govmomi/find/finder.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package find
import (
"context"
"errors"
"path"
"strings"
"github.com/vmware/govmomi/fault"
"github.com/vmware/govmomi/internal"
"github.com/vmware/govmomi/list"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/view"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type Finder struct {
client *vim25.Client
r recurser
dc *object.Datacenter
si *object.SearchIndex
folders *object.DatacenterFolders
}
func NewFinder(client *vim25.Client, all ...bool) *Finder {
props := false
if len(all) == 1 {
props = all[0]
}
f := &Finder{
client: client,
si: object.NewSearchIndex(client),
r: recurser{
Collector: property.DefaultCollector(client),
All: props,
},
}
if len(all) == 0 {
// attempt to avoid SetDatacenter() requirement
f.dc, _ = f.DefaultDatacenter(context.Background())
}
return f
}
func (f *Finder) SetDatacenter(dc *object.Datacenter) *Finder {
f.dc = dc
f.folders = nil
return f
}
// InventoryPath composes the given object's inventory path.
// There is no vSphere property or method that provides an inventory path directly.
// This method uses the ManagedEntity.Parent field to determine the ancestry tree of the object and
// the ManagedEntity.Name field for each ancestor to compose the path.
func InventoryPath(ctx context.Context, client *vim25.Client, obj types.ManagedObjectReference) (string, error) {
entities, err := mo.Ancestors(ctx, client, client.ServiceContent.PropertyCollector, obj)
if err != nil {
return "", err
}
return internal.InventoryPath(entities), nil
}
// findRoot makes it possible to use "find" mode with a different root path.
// Example: ResourcePoolList("/dc1/host/cluster1/...")
func (f *Finder) findRoot(ctx context.Context, root *list.Element, parts []string) bool {
if len(parts) == 0 {
return false
}
ix := len(parts) - 1
if parts[ix] != "..." {
return false
}
if ix == 0 {
return true // We already have the Object for root.Path
}
// Lookup the Object for the new root.Path
rootPath := path.Join(root.Path, path.Join(parts[:ix]...))
ref, err := f.si.FindByInventoryPath(ctx, rootPath)
if err != nil || ref == nil {
// If we get an error or fail to match, fall through to find() with the original root and path
return false
}
root.Path = rootPath
root.Object = ref
return true
}
func (f *Finder) find(ctx context.Context, arg string, s *spec) ([]list.Element, error) {
isPath := strings.Contains(arg, "/")
if !isPath {
if ref := object.ReferenceFromString(arg); ref != nil {
p, err := InventoryPath(ctx, f.client, *ref)
if err == nil {
if t, ok := mo.Value(*ref); ok {
return []list.Element{{Object: t, Path: p}}, nil
}
} else if !fault.Is(err, &types.ManagedObjectNotFound{}) {
return nil, err
} // else fall through to name based lookup
}
}
root := list.Element{
Object: object.NewRootFolder(f.client),
Path: "/",
}
parts := list.ToParts(arg)
if len(parts) > 0 {
switch parts[0] {
case "..": // Not supported; many edge case, little value
return nil, errors.New("cannot traverse up a tree")
case ".": // Relative to whatever
pivot, err := s.Relative(ctx)
if err != nil {
return nil, err
}
root.Path, err = InventoryPath(ctx, f.client, pivot.Reference())
if err != nil {
return nil, err
}
root.Object = pivot
parts = parts[1:]
}
}
if s.listMode(isPath) {
if f.findRoot(ctx, &root, parts) {
parts = []string{"*"}
} else {
return f.r.List(ctx, s, root, parts)
}
}
s.Parents = append(s.Parents, s.Nested...)
return f.r.Find(ctx, s, root, parts)
}
func (f *Finder) datacenter() (*object.Datacenter, error) {
if f.dc == nil {
return nil, errors.New("please specify a datacenter")
}
return f.dc, nil
}
// datacenterPath returns the absolute path to the Datacenter containing the given ref
func (f *Finder) datacenterPath(ctx context.Context, ref types.ManagedObjectReference) (string, error) {
mes, err := mo.Ancestors(ctx, f.client, f.client.ServiceContent.PropertyCollector, ref)
if err != nil {
return "", err
}
// Chop leaves under the Datacenter
for i := len(mes) - 1; i > 0; i-- {
if mes[i].Self.Type == "Datacenter" {
break
}
mes = mes[:i]
}
var p string
for _, me := range mes {
// Skip root entity in building inventory path.
if me.Parent == nil {
continue
}
p = p + "/" + me.Name
}
return p, nil
}
func (f *Finder) dcFolders(ctx context.Context) (*object.DatacenterFolders, error) {
if f.folders != nil {
return f.folders, nil
}
dc, err := f.datacenter()
if err != nil {
return nil, err
}
folders, err := dc.Folders(ctx)
if err != nil {
return nil, err
}
f.folders = folders
return f.folders, nil
}
func (f *Finder) dcReference(_ context.Context) (object.Reference, error) {
dc, err := f.datacenter()
if err != nil {
return nil, err
}
return dc, nil
}
func (f *Finder) vmFolder(ctx context.Context) (object.Reference, error) {
folders, err := f.dcFolders(ctx)
if err != nil {
return nil, err
}
return folders.VmFolder, nil
}
func (f *Finder) hostFolder(ctx context.Context) (object.Reference, error) {
folders, err := f.dcFolders(ctx)
if err != nil {
return nil, err
}
return folders.HostFolder, nil
}
func (f *Finder) datastoreFolder(ctx context.Context) (object.Reference, error) {
folders, err := f.dcFolders(ctx)
if err != nil {
return nil, err
}
return folders.DatastoreFolder, nil
}
func (f *Finder) networkFolder(ctx context.Context) (object.Reference, error) {
folders, err := f.dcFolders(ctx)
if err != nil {
return nil, err
}
return folders.NetworkFolder, nil
}
func (f *Finder) rootFolder(_ context.Context) (object.Reference, error) {
return object.NewRootFolder(f.client), nil
}
func (f *Finder) managedObjectList(ctx context.Context, path string, tl bool, include []string) ([]list.Element, error) {
fn := f.rootFolder
if f.dc != nil {
fn = f.dcReference
}
if path == "" {
path = "."
}
s := &spec{
Relative: fn,
Parents: []string{"ComputeResource", "ClusterComputeResource", "HostSystem", "VirtualApp", "StoragePod"},
Include: include,
}
if tl {
s.Contents = true
s.ListMode = types.NewBool(true)
}
return f.find(ctx, path, s)
}
// Element is deprecated, use InventoryPath() instead.
func (f *Finder) Element(ctx context.Context, ref types.ManagedObjectReference) (*list.Element, error) {
rl := func(_ context.Context) (object.Reference, error) {
return ref, nil
}
s := &spec{
Relative: rl,
}
e, err := f.find(ctx, "./", s)
if err != nil {
return nil, err
}
if len(e) == 0 {
return nil, &NotFoundError{ref.Type, ref.Value}
}
if len(e) > 1 {
panic("ManagedObjectReference must be unique")
}
return &e[0], nil
}
// ObjectReference converts the given ManagedObjectReference to a type from the object package via object.NewReference
// with the object.Common.InventoryPath field set.
func (f *Finder) ObjectReference(ctx context.Context, ref types.ManagedObjectReference) (object.Reference, error) {
path, err := InventoryPath(ctx, f.client, ref)
if err != nil {
return nil, err
}
r := object.NewReference(f.client, ref)
type common interface {
SetInventoryPath(string)
}
r.(common).SetInventoryPath(path)
if f.dc != nil {
if ds, ok := r.(*object.Datastore); ok {
ds.DatacenterPath = f.dc.InventoryPath
}
}
return r, nil
}
func (f *Finder) ManagedObjectList(ctx context.Context, path string, include ...string) ([]list.Element, error) {
return f.managedObjectList(ctx, path, false, include)
}
func (f *Finder) ManagedObjectListChildren(ctx context.Context, path string, include ...string) ([]list.Element, error) {
return f.managedObjectList(ctx, path, true, include)
}
func (f *Finder) DatacenterList(ctx context.Context, path string) ([]*object.Datacenter, error) {
s := &spec{
Relative: f.rootFolder,
Include: []string{"Datacenter"},
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var dcs []*object.Datacenter
for _, e := range es {
ref := e.Object.Reference()
if ref.Type == "Datacenter" {
dc := object.NewDatacenter(f.client, ref)
dc.InventoryPath = e.Path
dcs = append(dcs, dc)
}
}
if len(dcs) == 0 {
return nil, &NotFoundError{"datacenter", path}
}
return dcs, nil
}
func (f *Finder) Datacenter(ctx context.Context, path string) (*object.Datacenter, error) {
dcs, err := f.DatacenterList(ctx, path)
if err != nil {
return nil, err
}
if len(dcs) > 1 {
return nil, &MultipleFoundError{"datacenter", path}
}
return dcs[0], nil
}
func (f *Finder) DefaultDatacenter(ctx context.Context) (*object.Datacenter, error) {
dc, err := f.Datacenter(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return dc, nil
}
func (f *Finder) DatacenterOrDefault(ctx context.Context, path string) (*object.Datacenter, error) {
if path != "" {
dc, err := f.Datacenter(ctx, path)
if err != nil {
return nil, err
}
return dc, nil
}
return f.DefaultDatacenter(ctx)
}
func (f *Finder) DatastoreList(ctx context.Context, path string) ([]*object.Datastore, error) {
s := &spec{
Relative: f.datastoreFolder,
Parents: []string{"StoragePod"},
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var dss []*object.Datastore
for _, e := range es {
ref := e.Object.Reference()
if ref.Type == "Datastore" {
ds := object.NewDatastore(f.client, ref)
ds.InventoryPath = e.Path
if f.dc == nil {
// In this case SetDatacenter was not called and path is absolute
ds.DatacenterPath, err = f.datacenterPath(ctx, ref)
if err != nil {
return nil, err
}
} else {
ds.DatacenterPath = f.dc.InventoryPath
}
dss = append(dss, ds)
}
}
if len(dss) == 0 {
return nil, &NotFoundError{"datastore", path}
}
return dss, nil
}
func (f *Finder) Datastore(ctx context.Context, path string) (*object.Datastore, error) {
dss, err := f.DatastoreList(ctx, path)
if err != nil {
return nil, err
}
if len(dss) > 1 {
return nil, &MultipleFoundError{"datastore", path}
}
return dss[0], nil
}
func (f *Finder) DefaultDatastore(ctx context.Context) (*object.Datastore, error) {
ds, err := f.Datastore(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return ds, nil
}
func (f *Finder) DatastoreOrDefault(ctx context.Context, path string) (*object.Datastore, error) {
if path != "" {
ds, err := f.Datastore(ctx, path)
if err != nil {
return nil, err
}
return ds, nil
}
return f.DefaultDatastore(ctx)
}
func (f *Finder) DatastoreClusterList(ctx context.Context, path string) ([]*object.StoragePod, error) {
s := &spec{
Relative: f.datastoreFolder,
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var sps []*object.StoragePod
for _, e := range es {
ref := e.Object.Reference()
if ref.Type == "StoragePod" {
sp := object.NewStoragePod(f.client, ref)
sp.InventoryPath = e.Path
sps = append(sps, sp)
}
}
if len(sps) == 0 {
return nil, &NotFoundError{"datastore cluster", path}
}
return sps, nil
}
func (f *Finder) DatastoreCluster(ctx context.Context, path string) (*object.StoragePod, error) {
sps, err := f.DatastoreClusterList(ctx, path)
if err != nil {
return nil, err
}
if len(sps) > 1 {
return nil, &MultipleFoundError{"datastore cluster", path}
}
return sps[0], nil
}
func (f *Finder) DefaultDatastoreCluster(ctx context.Context) (*object.StoragePod, error) {
sp, err := f.DatastoreCluster(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return sp, nil
}
func (f *Finder) DatastoreClusterOrDefault(ctx context.Context, path string) (*object.StoragePod, error) {
if path != "" {
sp, err := f.DatastoreCluster(ctx, path)
if err != nil {
return nil, err
}
return sp, nil
}
return f.DefaultDatastoreCluster(ctx)
}
func (f *Finder) ComputeResourceList(ctx context.Context, path string) ([]*object.ComputeResource, error) {
s := &spec{
Relative: f.hostFolder,
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var crs []*object.ComputeResource
for _, e := range es {
var cr *object.ComputeResource
switch o := e.Object.(type) {
case mo.ComputeResource, mo.ClusterComputeResource:
cr = object.NewComputeResource(f.client, o.Reference())
default:
continue
}
cr.InventoryPath = e.Path
crs = append(crs, cr)
}
if len(crs) == 0 {
return nil, &NotFoundError{"compute resource", path}
}
return crs, nil
}
func (f *Finder) ComputeResource(ctx context.Context, path string) (*object.ComputeResource, error) {
crs, err := f.ComputeResourceList(ctx, path)
if err != nil {
return nil, err
}
if len(crs) > 1 {
return nil, &MultipleFoundError{"compute resource", path}
}
return crs[0], nil
}
func (f *Finder) DefaultComputeResource(ctx context.Context) (*object.ComputeResource, error) {
cr, err := f.ComputeResource(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return cr, nil
}
func (f *Finder) ComputeResourceOrDefault(ctx context.Context, path string) (*object.ComputeResource, error) {
if path != "" {
cr, err := f.ComputeResource(ctx, path)
if err != nil {
return nil, err
}
return cr, nil
}
return f.DefaultComputeResource(ctx)
}
func (f *Finder) ClusterComputeResourceList(ctx context.Context, path string) ([]*object.ClusterComputeResource, error) {
s := &spec{
Relative: f.hostFolder,
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var ccrs []*object.ClusterComputeResource
for _, e := range es {
var ccr *object.ClusterComputeResource
switch o := e.Object.(type) {
case mo.ClusterComputeResource:
ccr = object.NewClusterComputeResource(f.client, o.Reference())
default:
continue
}
ccr.InventoryPath = e.Path
ccrs = append(ccrs, ccr)
}
if len(ccrs) == 0 {
return nil, &NotFoundError{"cluster", path}
}
return ccrs, nil
}
func (f *Finder) DefaultClusterComputeResource(ctx context.Context) (*object.ClusterComputeResource, error) {
cr, err := f.ClusterComputeResource(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return cr, nil
}
func (f *Finder) ClusterComputeResource(ctx context.Context, path string) (*object.ClusterComputeResource, error) {
ccrs, err := f.ClusterComputeResourceList(ctx, path)
if err != nil {
return nil, err
}
if len(ccrs) > 1 {
return nil, &MultipleFoundError{"cluster", path}
}
return ccrs[0], nil
}
func (f *Finder) ClusterComputeResourceOrDefault(ctx context.Context, path string) (*object.ClusterComputeResource, error) {
if path != "" {
cr, err := f.ClusterComputeResource(ctx, path)
if err != nil {
return nil, err
}
return cr, nil
}
return f.DefaultClusterComputeResource(ctx)
}
func (f *Finder) HostSystemList(ctx context.Context, path string) ([]*object.HostSystem, error) {
s := &spec{
Relative: f.hostFolder,
Parents: []string{"ComputeResource", "ClusterComputeResource"},
Include: []string{"HostSystem"},
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var hss []*object.HostSystem
for _, e := range es {
var hs *object.HostSystem
switch o := e.Object.(type) {
case mo.HostSystem:
hs = object.NewHostSystem(f.client, o.Reference())
hs.InventoryPath = e.Path
hss = append(hss, hs)
case mo.ComputeResource, mo.ClusterComputeResource:
cr := object.NewComputeResource(f.client, o.Reference())
cr.InventoryPath = e.Path
hosts, err := cr.Hosts(ctx)
if err != nil {
return nil, err
}
hss = append(hss, hosts...)
}
}
if len(hss) == 0 {
return nil, &NotFoundError{"host", path}
}
return hss, nil
}
func (f *Finder) HostSystem(ctx context.Context, path string) (*object.HostSystem, error) {
hss, err := f.HostSystemList(ctx, path)
if err != nil {
return nil, err
}
if len(hss) > 1 {
return nil, &MultipleFoundError{"host", path}
}
return hss[0], nil
}
func (f *Finder) DefaultHostSystem(ctx context.Context) (*object.HostSystem, error) {
hs, err := f.HostSystem(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return hs, nil
}
func (f *Finder) HostSystemOrDefault(ctx context.Context, path string) (*object.HostSystem, error) {
if path != "" {
hs, err := f.HostSystem(ctx, path)
if err != nil {
return nil, err
}
return hs, nil
}
return f.DefaultHostSystem(ctx)
}
func (f *Finder) NetworkList(ctx context.Context, path string) ([]object.NetworkReference, error) {
s := &spec{
Relative: f.networkFolder,
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var ns []object.NetworkReference
for _, e := range es {
ref := e.Object.Reference()
switch ref.Type {
case "Network":
r := object.NewNetwork(f.client, ref)
r.InventoryPath = e.Path
ns = append(ns, r)
case "OpaqueNetwork":
r := object.NewOpaqueNetwork(f.client, ref)
r.InventoryPath = e.Path
ns = append(ns, r)
case "DistributedVirtualPortgroup":
r := object.NewDistributedVirtualPortgroup(f.client, ref)
r.InventoryPath = e.Path
ns = append(ns, r)
case "DistributedVirtualSwitch", "VmwareDistributedVirtualSwitch":
r := object.NewDistributedVirtualSwitch(f.client, ref)
r.InventoryPath = e.Path
ns = append(ns, r)
}
}
if len(ns) == 0 {
net, nerr := f.networkByID(ctx, path)
if nerr == nil {
return []object.NetworkReference{net}, nil
}
return nil, &NotFoundError{"network", path}
}
return ns, nil
}
// Network finds a NetworkReference using a Name, Inventory Path, ManagedObject ID, Logical Switch UUID or Segment ID.
// With standard vSphere networking, Portgroups cannot have the same name within the same network folder.
// With NSX, Portgroups can have the same name, even within the same Switch. In this case, using an inventory path
// results in a MultipleFoundError. A MOID, switch UUID or segment ID can be used instead, as both are unique.
// See also: https://knowledge.broadcom.com/external/article?articleNumber=320145#Duplicate_names
// Examples:
// - Name: "dvpg-1"
// - Inventory Path: "vds-1/dvpg-1"
// - Cluster Path: "/dc-1/host/cluster-1/dvpg-1"
// - ManagedObject ID: "DistributedVirtualPortgroup:dvportgroup-53"
// - Logical Switch UUID: "da2a59b8-2450-4cb2-b5cc-79c4c1d2144c"
// - Segment ID: "/infra/segments/vnet_ce50e69b-1784-4a14-9206-ffd7f1f146f7"
func (f *Finder) Network(ctx context.Context, path string) (object.NetworkReference, error) {
networks, err := f.NetworkList(ctx, path)
if err != nil {
return nil, err
}
if len(networks) > 1 {
return nil, &MultipleFoundError{"network", path}
}
return networks[0], nil
}
func (f *Finder) networkByID(ctx context.Context, path string) (object.NetworkReference, error) {
kind := []string{"DistributedVirtualPortgroup"}
m := view.NewManager(f.client)
v, err := m.CreateContainerView(ctx, f.client.ServiceContent.RootFolder, kind, true)
if err != nil {
return nil, err
}
defer v.Destroy(ctx)
filter := property.Match{
"config.logicalSwitchUuid": path,
"config.segmentId": path,
}
refs, err := v.FindAny(ctx, kind, filter)
if err != nil {
return nil, err
}
if len(refs) == 0 {
return nil, &NotFoundError{"network", path}
}
if len(refs) > 1 {
return nil, &MultipleFoundError{"network", path}
}
return object.NewReference(f.client, refs[0]).(object.NetworkReference), nil
}
func (f *Finder) DefaultNetwork(ctx context.Context) (object.NetworkReference, error) {
network, err := f.Network(ctx, "*")
if err != nil {
return nil, toDefaultError(err)
}
return network, nil
}
func (f *Finder) NetworkOrDefault(ctx context.Context, path string) (object.NetworkReference, error) {
if path != "" {
network, err := f.Network(ctx, path)
if err != nil {
return nil, err
}
return network, nil
}
return f.DefaultNetwork(ctx)
}
func (f *Finder) ResourcePoolList(ctx context.Context, path string) ([]*object.ResourcePool, error) {
s := &spec{
Relative: f.hostFolder,
Parents: []string{"ComputeResource", "ClusterComputeResource", "VirtualApp"},
Nested: []string{"ResourcePool"},
Contents: true,
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var rps []*object.ResourcePool
for _, e := range es {
var rp *object.ResourcePool
switch o := e.Object.(type) {
case mo.ResourcePool:
rp = object.NewResourcePool(f.client, o.Reference())
rp.InventoryPath = e.Path
rps = append(rps, rp)
}
}
if len(rps) == 0 {
return nil, &NotFoundError{"resource pool", path}
}
return rps, nil
}
func (f *Finder) ResourcePool(ctx context.Context, path string) (*object.ResourcePool, error) {
rps, err := f.ResourcePoolList(ctx, path)
if err != nil {
return nil, err
}
if len(rps) > 1 {
return nil, &MultipleFoundError{"resource pool", path}
}
return rps[0], nil
}
func (f *Finder) DefaultResourcePool(ctx context.Context) (*object.ResourcePool, error) {
rp, err := f.ResourcePool(ctx, "*/Resources")
if err != nil {
return nil, toDefaultError(err)
}
return rp, nil
}
func (f *Finder) ResourcePoolOrDefault(ctx context.Context, path string) (*object.ResourcePool, error) {
if path != "" {
rp, err := f.ResourcePool(ctx, path)
if err != nil {
return nil, err
}
return rp, nil
}
return f.DefaultResourcePool(ctx)
}
// ResourcePoolListAll combines ResourcePoolList and VirtualAppList
// VirtualAppList is only called if ResourcePoolList does not find any pools with the given path.
func (f *Finder) ResourcePoolListAll(ctx context.Context, path string) ([]*object.ResourcePool, error) {
pools, err := f.ResourcePoolList(ctx, path)
if err != nil {
if _, ok := err.(*NotFoundError); !ok {
return nil, err
}
vapps, _ := f.VirtualAppList(ctx, path)
if len(vapps) == 0 {
return nil, err
}
for _, vapp := range vapps {
pools = append(pools, vapp.ResourcePool)
}
}
return pools, nil
}
func (f *Finder) DefaultFolder(ctx context.Context) (*object.Folder, error) {
ref, err := f.vmFolder(ctx)
if err != nil {
return nil, toDefaultError(err)
}
folder := object.NewFolder(f.client, ref.Reference())
// Set the InventoryPath of the newly created folder object
// The default foler becomes the datacenter's "vm" folder.
// The "vm" folder always exists for a datacenter. It cannot be
// removed or replaced
folder.SetInventoryPath(path.Join(f.dc.InventoryPath, "vm"))
return folder, nil
}
func (f *Finder) FolderOrDefault(ctx context.Context, path string) (*object.Folder, error) {
if path != "" {
folder, err := f.Folder(ctx, path)
if err != nil {
return nil, err
}
return folder, nil
}
return f.DefaultFolder(ctx)
}
func (f *Finder) VirtualMachineList(ctx context.Context, path string) ([]*object.VirtualMachine, error) {
s := &spec{
Relative: f.vmFolder,
Parents: []string{"VirtualApp"},
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var vms []*object.VirtualMachine
for _, e := range es {
switch o := e.Object.(type) {
case mo.VirtualMachine:
vm := object.NewVirtualMachine(f.client, o.Reference())
vm.InventoryPath = e.Path
vms = append(vms, vm)
}
}
if len(vms) == 0 {
return nil, &NotFoundError{"vm", path}
}
return vms, nil
}
func (f *Finder) VirtualMachine(ctx context.Context, path string) (*object.VirtualMachine, error) {
vms, err := f.VirtualMachineList(ctx, path)
if err != nil {
return nil, err
}
if len(vms) > 1 {
return nil, &MultipleFoundError{"vm", path}
}
return vms[0], nil
}
func (f *Finder) VirtualAppList(ctx context.Context, path string) ([]*object.VirtualApp, error) {
s := &spec{
Relative: f.vmFolder,
}
es, err := f.find(ctx, path, s)
if err != nil {
return nil, err
}
var apps []*object.VirtualApp
for _, e := range es {
switch o := e.Object.(type) {
case mo.VirtualApp:
app := object.NewVirtualApp(f.client, o.Reference())
app.InventoryPath = e.Path
apps = append(apps, app)
}
}
if len(apps) == 0 {
return nil, &NotFoundError{"app", path}
}
return apps, nil
}
func (f *Finder) VirtualApp(ctx context.Context, path string) (*object.VirtualApp, error) {
apps, err := f.VirtualAppList(ctx, path)
if err != nil {
return nil, err
}
if len(apps) > 1 {
return nil, &MultipleFoundError{"app", path}
}
return apps[0], nil
}
func (f *Finder) FolderList(ctx context.Context, path string) ([]*object.Folder, error) {
es, err := f.ManagedObjectList(ctx, path)
if err != nil {
return nil, err
}
var folders []*object.Folder
for _, e := range es {
switch o := e.Object.(type) {
case mo.Folder, mo.StoragePod:
folder := object.NewFolder(f.client, o.Reference())
folder.InventoryPath = e.Path
folders = append(folders, folder)
case *object.Folder:
// RootFolder
folders = append(folders, o)
}
}
if len(folders) == 0 {
return nil, &NotFoundError{"folder", path}
}
return folders, nil
}
func (f *Finder) Folder(ctx context.Context, path string) (*object.Folder, error) {
folders, err := f.FolderList(ctx, path)
if err != nil {
return nil, err
}
if len(folders) > 1 {
return nil, &MultipleFoundError{"folder", path}
}
return folders[0], nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/find/error.go | vendor/github.com/vmware/govmomi/find/error.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package find
import "fmt"
type NotFoundError struct {
kind string
path string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s '%s' not found", e.kind, e.path)
}
type MultipleFoundError struct {
kind string
path string
}
func (e *MultipleFoundError) Error() string {
return fmt.Sprintf("path '%s' resolves to multiple %ss", e.path, e.kind)
}
type DefaultNotFoundError struct {
kind string
}
func (e *DefaultNotFoundError) Error() string {
return fmt.Sprintf("no default %s found", e.kind)
}
type DefaultMultipleFoundError struct {
kind string
}
func (e DefaultMultipleFoundError) Error() string {
return fmt.Sprintf("default %s resolves to multiple instances, please specify", e.kind)
}
func toDefaultError(err error) error {
switch e := err.(type) {
case *NotFoundError:
return &DefaultNotFoundError{e.kind}
case *MultipleFoundError:
return &DefaultMultipleFoundError{e.kind}
default:
return err
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/find/recurser.go | vendor/github.com/vmware/govmomi/find/recurser.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package find
import (
"context"
"os"
"path"
"strings"
"github.com/vmware/govmomi/list"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
)
// spec is used to specify per-search configuration, independent of the Finder instance.
type spec struct {
// Relative returns the root object to resolve Relative paths (starts with ".")
Relative func(ctx context.Context) (object.Reference, error)
// ListMode can be used to optionally force "ls" behavior, rather than "find" behavior
ListMode *bool
// Contents configures the Recurser to list the Contents of traversable leaf nodes.
// This is typically set to true when used from the ls command, where listing
// a folder means listing its Contents. This is typically set to false for
// commands that take managed entities that are not folders as input.
Contents bool
// Parents specifies the types which can contain the child types being searched for.
// for example, when searching for a HostSystem, parent types can be
// "ComputeResource" or "ClusterComputeResource".
Parents []string
// Include specifies which types to be included in the results, used only in "find" mode.
Include []string
// Nested should be set to types that can be Nested, used only in "find" mode.
Nested []string
// ChildType avoids traversing into folders that can't contain the Include types, used only in "find" mode.
ChildType []string
}
func (s *spec) traversable(o mo.Reference) bool {
ref := o.Reference()
switch ref.Type {
case "Datacenter":
if len(s.Include) == 1 && s.Include[0] == "Datacenter" {
// No point in traversing deeper as Datacenters cannot be nested
return false
}
return true
case "Folder":
if f, ok := o.(mo.Folder); ok {
// TODO: Not making use of this yet, but here we can optimize when searching the entire
// inventory across Datacenters for specific types, for example: 'govc ls -t VirtualMachine /**'
// should not traverse into a Datacenter's host, network or datatore folders.
if !s.traversableChildType(f.ChildType) {
return false
}
}
return true
}
for _, kind := range s.Parents {
if kind == ref.Type {
return true
}
}
return false
}
func (s *spec) traversableChildType(ctypes []string) bool {
if len(s.ChildType) == 0 {
return true
}
for _, t := range ctypes {
for _, c := range s.ChildType {
if t == c {
return true
}
}
}
return false
}
func (s *spec) wanted(e list.Element) bool {
if len(s.Include) == 0 {
return true
}
w := e.Object.Reference().Type
for _, kind := range s.Include {
if w == kind {
return true
}
}
return false
}
// listMode is a global option to revert to the original Finder behavior,
// disabling the newer "find" mode.
var listMode = os.Getenv("GOVMOMI_FINDER_LIST_MODE") == "true"
func (s *spec) listMode(isPath bool) bool {
if listMode {
return true
}
if s.ListMode != nil {
return *s.ListMode
}
return isPath
}
type recurser struct {
Collector *property.Collector
// All configures the recurses to fetch complete objects for leaf nodes.
All bool
}
func (r recurser) List(ctx context.Context, s *spec, root list.Element, parts []string) ([]list.Element, error) {
if len(parts) == 0 {
// Include non-traversable leaf elements in result. For example, consider
// the pattern "./vm/my-vm-*", where the pattern should match the VMs and
// not try to traverse them.
//
// Include traversable leaf elements in result, if the contents
// field is set to false.
//
if !s.Contents || !s.traversable(root.Object.Reference()) {
return []list.Element{root}, nil
}
}
k := list.Lister{
Collector: r.Collector,
Reference: root.Object.Reference(),
Prefix: root.Path,
}
if r.All && len(parts) < 2 {
k.All = true
}
in, err := k.List(ctx)
if err != nil {
return nil, err
}
// This folder is a leaf as far as the glob goes.
if len(parts) == 0 {
return in, nil
}
all := parts
pattern := parts[0]
parts = parts[1:]
var out []list.Element
for _, e := range in {
matched, err := path.Match(pattern, path.Base(e.Path))
if err != nil {
return nil, err
}
if !matched {
matched = strings.HasSuffix(e.Path, "/"+path.Join(all...))
if matched {
// name contains a '/'
out = append(out, e)
}
continue
}
nres, err := r.List(ctx, s, e, parts)
if err != nil {
return nil, err
}
out = append(out, nres...)
}
return out, nil
}
func (r recurser) Find(ctx context.Context, s *spec, root list.Element, parts []string) ([]list.Element, error) {
var out []list.Element
if len(parts) > 0 {
pattern := parts[0]
matched, err := path.Match(pattern, path.Base(root.Path))
if err != nil {
return nil, err
}
if matched && s.wanted(root) {
out = append(out, root)
}
}
if !s.traversable(root.Object) {
return out, nil
}
k := list.Lister{
Collector: r.Collector,
Reference: root.Object.Reference(),
Prefix: root.Path,
}
in, err := k.List(ctx)
if err != nil {
return nil, err
}
for _, e := range in {
nres, err := r.Find(ctx, s, e, parts)
if err != nil {
return nil, err
}
out = append(out, nres...)
}
return out, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/find/doc.go | vendor/github.com/vmware/govmomi/find/doc.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
/*
Package find implements inventory listing and searching.
The Finder is an alternative to the object.SearchIndex FindByInventoryPath() and FindChild() methods.
SearchIndex.FindByInventoryPath requires an absolute path, whereas the Finder also supports relative paths
and patterns via path.Match.
SearchIndex.FindChild requires a parent to find the child, whereas the Finder also supports an ancestor via
recursive object traversal.
The various Finder methods accept a "path" argument, which can absolute or relative to the Folder for the object type.
The Finder supports two modes, "list" and "find". The "list" mode behaves like the "ls" command, only searching within
the immediate path. The "find" mode behaves like the "find" command, with the search starting at the immediate path but
also recursing into sub Folders relative to the Datacenter. The default mode is "list" if the given path contains a "/",
otherwise "find" mode is used.
The exception is to use a "..." wildcard with a path to find all objects recursively underneath any root object.
For example: VirtualMachineList("/DC1/...")
Finder methods can also convert a managed object reference (aka MOID) to an object instance.
For example: VirtualMachine("VirtualMachine:vm-123") or VirtualMachine("vm-123")
See also: https://github.com/vmware/govmomi/blob/main/govc/README.md#usage
*/
package find
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/fault/fault.go | vendor/github.com/vmware/govmomi/fault/fault.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package fault
import (
"reflect"
"github.com/vmware/govmomi/vim25/types"
)
// As finds the first fault in the error's tree that matches target, and if one
// is found, sets the target to that fault value and returns the fault's
// localized message and true. Otherwise, false is returned.
//
// The tree is inspected according to the object type. If the object implements
// Golang's error interface, the Unwrap() error or Unwrap() []error methods are
// repeatedly checked for additional errors. If the object implements GoVmomi's
// BaseMethodFault or HasLocalizedMethodFault interfaces, the object is checked
// for an underlying FaultCause. When err wraps multiple errors or faults, err
// is examined followed by a depth-first traversal of its children.
//
// An error matches target if the error's concrete value is assignable to the
// value pointed to by target, or if the error has a method
// AsFault(BaseMethodFault) (string, bool) such that AsFault(BaseMethodFault)
// returns true. In the latter case, the AsFault method is responsible for
// setting target.
//
// An error type might provide an AsFault method so it can be treated as if it
// were a different error type.
//
// This function panics if err does not implement error, types.BaseMethodFault,
// types.HasLocalizedMethodFault, Fault() types.BaseMethodFault, or if target is
// not a pointer.
func As(err, target any) (localizedMessage string, okay bool) {
if err == nil {
return
}
if target == nil {
panic("fault: target cannot be nil")
}
val := reflect.ValueOf(target)
typ := val.Type()
if typ.Kind() != reflect.Ptr || val.IsNil() {
panic("fault: target must be a non-nil pointer")
}
targetType := typ.Elem()
if targetType.Kind() != reflect.Interface &&
!targetType.Implements(baseMethodFaultType) {
panic("fault: *target must be interface or implement BaseMethodFault")
}
if !as(err, target, val, targetType, &localizedMessage) {
return "", false
}
return localizedMessage, true
}
func as(
err,
target any,
targetVal reflect.Value,
targetType reflect.Type,
localizedMsg *string) bool {
for {
if reflect.TypeOf(err).AssignableTo(targetType) {
targetVal.Elem().Set(reflect.ValueOf(err))
return true
}
if tErr, ok := err.(hasAsFault); ok {
if msg, ok := tErr.AsFault(target); ok {
*localizedMsg = msg
return true
}
return false
}
switch tErr := err.(type) {
case types.HasLocalizedMethodFault:
if fault := tErr.GetLocalizedMethodFault(); fault != nil {
*localizedMsg = fault.LocalizedMessage
if fault.Fault != nil {
return as(
fault.Fault,
target,
targetVal,
targetType,
localizedMsg)
}
}
return false
case types.BaseMethodFault:
if fault := tErr.GetMethodFault(); fault != nil {
if fault.FaultCause != nil {
*localizedMsg = fault.FaultCause.LocalizedMessage
return as(
fault.FaultCause,
target,
targetVal,
targetType,
localizedMsg)
}
}
return false
case hasFault:
if fault := tErr.Fault(); fault != nil {
return as(fault, target, targetVal, targetType, localizedMsg)
}
return false
case unwrappableError:
if err = tErr.Unwrap(); err == nil {
return false
}
case unwrappableErrorSlice:
for _, err := range tErr.Unwrap() {
if err == nil {
continue
}
return as(err, target, targetVal, targetType, localizedMsg)
}
return false
default:
return false
}
}
}
// Is reports whether any fault in err's tree matches target.
//
// The tree is inspected according to the object type. If the object implements
// Golang's error interface, the Unwrap() error or Unwrap() []error methods are
// repeatedly checked for additional errors. If the object implements GoVmomi's
// BaseMethodFault or HasLocalizedMethodFault interfaces, the object is checked
// for an underlying FaultCause. When err wraps multiple errors or faults, err
// is examined followed by a depth-first traversal of its children.
//
// An error is considered to match a target if it is equal to that target or if
// it implements a method IsFault(BaseMethodFault) bool such that
// IsFault(BaseMethodFault) returns true.
//
// An error type might provide an IsFault method so it can be treated as
// equivalent to an existing fault. For example, if MyFault defines:
//
// func (m MyFault) IsFault(target BaseMethodFault) bool {
// return target == &types.NotSupported{}
// }
//
// then IsFault(MyError{}, &types.NotSupported{}) returns true. An IsFault
// method should only shallowly compare err and the target and not unwrap
// either.
func Is(err any, target types.BaseMethodFault) bool {
if target == nil {
return err == target
}
isComparable := reflect.TypeOf(target).Comparable()
return is(err, target, isComparable)
}
func is(err any, target types.BaseMethodFault, targetComparable bool) bool {
for {
if targetComparable && err == target {
return true
}
if tErr, ok := err.(hasIsFault); ok && tErr.IsFault(target) {
return true
}
switch tErr := err.(type) {
case types.HasLocalizedMethodFault:
fault := tErr.GetLocalizedMethodFault()
if fault == nil {
return false
}
err = fault.Fault
case types.BaseMethodFault:
if reflect.ValueOf(err).Type() == reflect.ValueOf(target).Type() {
return true
}
fault := tErr.GetMethodFault()
if fault == nil {
return false
}
err = fault.FaultCause
case hasFault:
if err = tErr.Fault(); err == nil {
return false
}
case unwrappableError:
if err = tErr.Unwrap(); err == nil {
return false
}
case unwrappableErrorSlice:
for _, err := range tErr.Unwrap() {
if is(err, target, targetComparable) {
return true
}
}
return false
default:
return false
}
}
}
// OnFaultFn is called for every fault encountered when inspecting an error
// or fault for a fault tree. The In function returns when the entire tree is
// inspected or the OnFaultFn returns true.
type OnFaultFn func(
fault types.BaseMethodFault,
localizedMessage string,
localizableMessages []types.LocalizableMessage) bool
// In invokes onFaultFn for each fault in err's tree.
//
// The tree is inspected according to the object type. If the object implements
// Golang's error interface, the Unwrap() error or Unwrap() []error methods are
// repeatedly checked for additional errors. If the object implements GoVmomi's
// BaseMethodFault or HasLocalizedMethodFault interfaces, the object is checked
// for an underlying FaultCause. When err wraps multiple errors or faults, err
// is examined followed by a depth-first traversal of its children.
//
// This function panics if err does not implement error, types.BaseMethodFault,
// types.HasLocalizedMethodFault, Fault() types.BaseMethodFault, or if onFaultFn
// is nil.
func In(err any, onFaultFn OnFaultFn) {
if onFaultFn == nil {
panic("fault: onFaultFn must not be nil")
}
switch tErr := err.(type) {
case types.HasLocalizedMethodFault:
inFault(tErr.GetLocalizedMethodFault(), onFaultFn)
case types.BaseMethodFault:
inFault(&types.LocalizedMethodFault{Fault: tErr}, onFaultFn)
case hasFault:
if fault := tErr.Fault(); fault != nil {
inFault(&types.LocalizedMethodFault{Fault: fault}, onFaultFn)
}
case unwrappableError:
In(tErr.Unwrap(), onFaultFn)
case unwrappableErrorSlice:
for _, uErr := range tErr.Unwrap() {
if uErr == nil {
continue
}
In(uErr, onFaultFn)
}
case error:
// No-op
default:
panic("fault: err must implement error, types.BaseMethodFault, or " +
"types.HasLocalizedMethodFault")
}
}
func inFault(
localizedMethodFault *types.LocalizedMethodFault,
onFaultFn OnFaultFn) {
if localizedMethodFault == nil {
return
}
fault := localizedMethodFault.Fault
if fault == nil {
return
}
var (
faultCause *types.LocalizedMethodFault
faultMessages []types.LocalizableMessage
)
if methodFault := fault.GetMethodFault(); methodFault != nil {
faultCause = methodFault.FaultCause
faultMessages = methodFault.FaultMessage
}
if onFaultFn(fault, localizedMethodFault.LocalizedMessage, faultMessages) {
return
}
// Check the fault's children.
inFault(faultCause, onFaultFn)
}
type hasFault interface {
Fault() types.BaseMethodFault
}
type hasAsFault interface {
AsFault(target any) (string, bool)
}
type hasIsFault interface {
IsFault(target types.BaseMethodFault) bool
}
type unwrappableError interface {
Unwrap() error
}
type unwrappableErrorSlice interface {
Unwrap() []error
}
var baseMethodFaultType = reflect.TypeOf((*types.BaseMethodFault)(nil)).Elem()
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/session/keep_alive.go | vendor/github.com/vmware/govmomi/session/keep_alive.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package session
import (
"time"
"github.com/vmware/govmomi/session/keepalive"
"github.com/vmware/govmomi/vim25/soap"
)
// KeepAlive is a backward compatible wrapper around KeepAliveHandler.
func KeepAlive(roundTripper soap.RoundTripper, idleTime time.Duration) soap.RoundTripper {
return KeepAliveHandler(roundTripper, idleTime, nil)
}
// KeepAliveHandler is a backward compatible wrapper around keepalive.NewHandlerSOAP.
func KeepAliveHandler(roundTripper soap.RoundTripper, idleTime time.Duration, handler func(soap.RoundTripper) error) soap.RoundTripper {
var f func() error
if handler != nil {
f = func() error {
return handler(roundTripper)
}
}
return keepalive.NewHandlerSOAP(roundTripper, idleTime, f)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/session/manager.go | vendor/github.com/vmware/govmomi/session/manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package session
import (
"context"
"net/url"
"os"
"strings"
"sync"
"github.com/vmware/govmomi/fault"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
// Locale defaults to "en_US" and can be overridden via this var or the GOVMOMI_LOCALE env var.
// A value of "_" uses the server locale setting.
var Locale = os.Getenv("GOVMOMI_LOCALE")
func init() {
if Locale == "_" {
Locale = ""
} else if Locale == "" {
Locale = "en_US"
}
}
// Secret returns the contents if a file path value is given, otherwise returns value itself.
func Secret(value string) (string, error) {
if len(value) == 0 {
return value, nil
}
contents, err := os.ReadFile(value)
if err != nil {
if os.IsPermission(err) {
return "", err
}
return value, nil
}
return strings.TrimSpace(string(contents)), nil
}
type Manager struct {
client *vim25.Client
userSession *types.UserSession
mu sync.Mutex
}
func NewManager(client *vim25.Client) *Manager {
m := Manager{
client: client,
}
return &m
}
func (sm *Manager) Reference() types.ManagedObjectReference {
return *sm.client.ServiceContent.SessionManager
}
func (sm *Manager) SetLocale(ctx context.Context, locale string) error {
req := types.SetLocale{
This: sm.Reference(),
Locale: locale,
}
_, err := methods.SetLocale(ctx, sm.client, &req)
return err
}
func (sm *Manager) setUserSession(val *types.UserSession) {
sm.mu.Lock()
sm.userSession = val
sm.mu.Unlock()
}
func (sm *Manager) getUserSession() (types.UserSession, bool) {
sm.mu.Lock()
defer sm.mu.Unlock()
if sm.userSession == nil {
return types.UserSession{}, false
}
return *sm.userSession, true
}
func (sm *Manager) Login(ctx context.Context, u *url.Userinfo) error {
req := types.Login{
This: sm.Reference(),
Locale: Locale,
}
if u != nil {
req.UserName = u.Username()
if pw, ok := u.Password(); ok {
req.Password = pw
}
}
login, err := methods.Login(ctx, sm.client, &req)
if err != nil {
return err
}
sm.setUserSession(&login.Returnval)
return nil
}
// LoginExtensionByCertificate uses the vCenter SDK tunnel to login using a client certificate.
// The client certificate can be set using the soap.Client.SetCertificate method.
func (sm *Manager) LoginExtensionByCertificate(ctx context.Context, key string) error {
c := sm.client
u := c.URL()
if u.Hostname() != "sdkTunnel" {
sc := c.Tunnel()
c = &vim25.Client{
Client: sc,
RoundTripper: sc,
ServiceContent: c.ServiceContent,
}
// When http.Transport.Proxy is used, our thumbprint checker is bypassed, resulting in:
// "Post https://sdkTunnel:8089/sdk: x509: certificate is valid for $vcenter_hostname, not sdkTunnel"
// The only easy way around this is to disable verification for the call to LoginExtensionByCertificate().
// TODO: find a way to avoid disabling InsecureSkipVerify.
c.DefaultTransport().TLSClientConfig.InsecureSkipVerify = true
}
req := types.LoginExtensionByCertificate{
This: sm.Reference(),
ExtensionKey: key,
Locale: Locale,
}
login, err := methods.LoginExtensionByCertificate(ctx, c, &req)
if err != nil {
return err
}
// Copy the session cookie
sm.client.Jar.SetCookies(u, c.Jar.Cookies(c.URL()))
sm.setUserSession(&login.Returnval)
return nil
}
func (sm *Manager) LoginByToken(ctx context.Context) error {
req := types.LoginByToken{
This: sm.Reference(),
Locale: Locale,
}
login, err := methods.LoginByToken(ctx, sm.client, &req)
if err != nil {
return err
}
sm.setUserSession(&login.Returnval)
return nil
}
func (sm *Manager) Logout(ctx context.Context) error {
req := types.Logout{
This: sm.Reference(),
}
_, err := methods.Logout(ctx, sm.client, &req)
if err != nil {
return err
}
sm.setUserSession(nil)
return nil
}
// UserSession retrieves and returns the SessionManager's CurrentSession field.
// Nil is returned if the session is not authenticated.
func (sm *Manager) UserSession(ctx context.Context) (*types.UserSession, error) {
var mgr mo.SessionManager
pc := property.DefaultCollector(sm.client)
err := pc.RetrieveOne(ctx, sm.Reference(), []string{"currentSession"}, &mgr)
if err != nil {
// It's OK if we can't retrieve properties because we're not authenticated
if fault.Is(err, &types.NotAuthenticated{}) {
return nil, nil
}
return nil, err
}
return mgr.CurrentSession, nil
}
func (sm *Manager) TerminateSession(ctx context.Context, sessionId []string) error {
req := types.TerminateSession{
This: sm.Reference(),
SessionId: sessionId,
}
_, err := methods.TerminateSession(ctx, sm.client, &req)
return err
}
// SessionIsActive checks whether the session that was created at login is
// still valid. This function only works against vCenter.
func (sm *Manager) SessionIsActive(ctx context.Context) (bool, error) {
userSession, ok := sm.getUserSession()
if !ok {
return false, nil
}
req := types.SessionIsActive{
This: sm.Reference(),
SessionID: userSession.Key,
UserName: userSession.UserName,
}
active, err := methods.SessionIsActive(ctx, sm.client, &req)
if err != nil {
return false, err
}
return active.Returnval, err
}
func (sm *Manager) AcquireGenericServiceTicket(ctx context.Context, spec types.BaseSessionManagerServiceRequestSpec) (*types.SessionManagerGenericServiceTicket, error) {
req := types.AcquireGenericServiceTicket{
This: sm.Reference(),
Spec: spec,
}
res, err := methods.AcquireGenericServiceTicket(ctx, sm.client, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sm *Manager) AcquireLocalTicket(ctx context.Context, userName string) (*types.SessionManagerLocalTicket, error) {
req := types.AcquireLocalTicket{
This: sm.Reference(),
UserName: userName,
}
res, err := methods.AcquireLocalTicket(ctx, sm.client, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sm *Manager) AcquireCloneTicket(ctx context.Context) (string, error) {
req := types.AcquireCloneTicket{
This: sm.Reference(),
}
res, err := methods.AcquireCloneTicket(ctx, sm.client, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
func (sm *Manager) CloneSession(ctx context.Context, ticket string) error {
req := types.CloneSession{
This: sm.Reference(),
CloneTicket: ticket,
}
res, err := methods.CloneSession(ctx, sm.client, &req)
if err != nil {
return err
}
sm.setUserSession(&res.Returnval)
return nil
}
func (sm *Manager) UpdateServiceMessage(ctx context.Context, message string) error {
req := types.UpdateServiceMessage{
This: sm.Reference(),
Message: message,
}
_, err := methods.UpdateServiceMessage(ctx, sm.client, &req)
return err
}
func (sm *Manager) ImpersonateUser(ctx context.Context, name string) error {
req := types.ImpersonateUser{
This: sm.Reference(),
UserName: name,
Locale: Locale,
}
res, err := methods.ImpersonateUser(ctx, sm.client, &req)
if err != nil {
return err
}
sm.setUserSession(&res.Returnval)
return nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/session/keepalive/handler.go | vendor/github.com/vmware/govmomi/session/keepalive/handler.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package keepalive
import (
"context"
"errors"
"net/http"
"sync"
"time"
"github.com/vmware/govmomi/vapi/rest"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/soap"
)
// handler contains the generic keep alive settings and logic
type handler struct {
mu sync.Mutex
notifyStop chan struct{}
notifyWaitGroup sync.WaitGroup
idle time.Duration
send func() error
}
// NewHandlerSOAP returns a soap.RoundTripper for use with a vim25.Client
// The idle time specifies the interval in between send() requests. Defaults to 10 minutes.
// The send func is used to keep a session alive. Defaults to calling vim25 GetCurrentTime().
// The keep alive goroutine starts when a Login method is called and runs until Logout is called or send returns an error.
func NewHandlerSOAP(c soap.RoundTripper, idle time.Duration, send func() error) *HandlerSOAP {
h := &handler{
idle: idle,
send: send,
}
if send == nil {
h.send = func() error {
return h.keepAliveSOAP(c)
}
}
return &HandlerSOAP{h, c}
}
// NewHandlerREST returns an http.RoundTripper for use with a rest.Client
// The idle time specifies the interval in between send() requests. Defaults to 10 minutes.
// The send func is used to keep a session alive. Defaults to calling the rest.Client.Session() method
// The keep alive goroutine starts when a Login method is called and runs until Logout is called or send returns an error.
func NewHandlerREST(c *rest.Client, idle time.Duration, send func() error) *HandlerREST {
h := &handler{
idle: idle,
send: send,
}
if send == nil {
h.send = func() error {
return h.keepAliveREST(c)
}
}
return &HandlerREST{h, c.Transport}
}
func (h *handler) keepAliveSOAP(rt soap.RoundTripper) error {
ctx := context.Background()
_, err := methods.GetCurrentTime(ctx, rt)
return err
}
func (h *handler) keepAliveREST(c *rest.Client) error {
ctx := context.Background()
s, err := c.Session(ctx)
if err != nil {
return err
}
if s != nil {
return nil
}
return errors.New(http.StatusText(http.StatusUnauthorized))
}
// Start explicitly starts the keep alive go routine.
// For use with session cache.Client, as cached sessions may not involve Login/Logout via RoundTripper.
func (h *handler) Start() {
h.mu.Lock()
defer h.mu.Unlock()
if h.notifyStop != nil {
return
}
if h.idle == 0 {
h.idle = time.Minute * 10
}
// This channel must be closed to terminate idle timer.
h.notifyStop = make(chan struct{})
h.notifyWaitGroup.Add(1)
go func() {
for t := time.NewTimer(h.idle); ; {
select {
case <-h.notifyStop:
h.notifyWaitGroup.Done()
t.Stop()
return
case <-t.C:
if err := h.send(); err != nil {
h.notifyWaitGroup.Done()
h.Stop()
return
}
t.Reset(h.idle)
}
}
}()
}
// Stop explicitly stops the keep alive go routine.
// For use with session cache.Client, as cached sessions may not involve Login/Logout via RoundTripper.
func (h *handler) Stop() {
h.mu.Lock()
defer h.mu.Unlock()
if h.notifyStop != nil {
close(h.notifyStop)
h.notifyWaitGroup.Wait()
h.notifyStop = nil
}
}
// HandlerSOAP is a keep alive implementation for use with vim25.Client
type HandlerSOAP struct {
*handler
roundTripper soap.RoundTripper
}
// RoundTrip implements soap.RoundTripper
func (h *HandlerSOAP) RoundTrip(ctx context.Context, req, res soap.HasFault) error {
// Stop ticker on logout.
switch req.(type) {
case *methods.LogoutBody:
h.Stop()
}
err := h.roundTripper.RoundTrip(ctx, req, res)
if err != nil {
return err
}
// Start ticker on login.
switch req.(type) {
case *methods.LoginBody, *methods.LoginExtensionByCertificateBody, *methods.LoginByTokenBody:
h.Start()
}
return nil
}
// HandlerREST is a keep alive implementation for use with rest.Client
type HandlerREST struct {
*handler
roundTripper http.RoundTripper
}
// RoundTrip implements http.RoundTripper
func (h *HandlerREST) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Path != "/rest/com/vmware/cis/session" {
return h.roundTripper.RoundTrip(req)
}
if req.Method == http.MethodDelete { // Logout
h.Stop()
}
res, err := h.roundTripper.RoundTrip(req)
if err != nil {
return res, err
}
if req.Method == http.MethodPost { // Login
h.Start()
}
return res, err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/view/managed_object_view.go | vendor/github.com/vmware/govmomi/view/managed_object_view.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package view
import (
"context"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type ManagedObjectView struct {
object.Common
}
func NewManagedObjectView(c *vim25.Client, ref types.ManagedObjectReference) *ManagedObjectView {
return &ManagedObjectView{
Common: object.NewCommon(c, ref),
}
}
func (v *ManagedObjectView) TraversalSpec() *types.TraversalSpec {
return &types.TraversalSpec{
Path: "view",
Type: v.Reference().Type,
}
}
func (v *ManagedObjectView) Destroy(ctx context.Context) error {
req := types.DestroyView{
This: v.Reference(),
}
_, err := methods.DestroyView(ctx, v.Client(), &req)
return err
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/view/task_view.go | vendor/github.com/vmware/govmomi/view/task_view.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package view
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/types"
)
// TaskView extends ListView such that it can follow a ManagedEntity's recentTask updates.
type TaskView struct {
*ListView
Follow bool
Watch *types.ManagedObjectReference
}
// CreateTaskView creates a new ListView that optionally watches for a ManagedEntity's recentTask updates.
func (m Manager) CreateTaskView(ctx context.Context, watch *types.ManagedObjectReference) (*TaskView, error) {
l, err := m.CreateListView(ctx, nil)
if err != nil {
return nil, err
}
tv := &TaskView{
ListView: l,
Watch: watch,
}
return tv, nil
}
// Collect calls function f for each Task update.
func (v TaskView) Collect(ctx context.Context, f func([]types.TaskInfo)) error {
// Using TaskHistoryCollector would be less clunky, but it isn't supported on ESX at all.
ref := v.Reference()
filter := new(property.WaitFilter).Add(ref, "Task", []string{"info"}, v.TraversalSpec())
if v.Watch != nil {
filter.Add(*v.Watch, v.Watch.Type, []string{"recentTask"})
}
pc := property.DefaultCollector(v.Client())
completed := make(map[string]bool)
return property.WaitForUpdates(ctx, pc, filter, func(updates []types.ObjectUpdate) bool {
var infos []types.TaskInfo
var prune []types.ManagedObjectReference
var tasks []types.ManagedObjectReference
var reset func()
for _, update := range updates {
for _, change := range update.ChangeSet {
if change.Name == "recentTask" {
tasks = change.Val.(types.ArrayOfManagedObjectReference).ManagedObjectReference
if len(tasks) != 0 {
reset = func() {
_, _ = v.Reset(ctx, tasks)
// Remember any tasks we've reported as complete already,
// to avoid reporting multiple times when Reset is triggered.
rtasks := make(map[string]bool)
for i := range tasks {
if _, ok := completed[tasks[i].Value]; ok {
rtasks[tasks[i].Value] = true
}
}
completed = rtasks
}
}
continue
}
info, ok := change.Val.(types.TaskInfo)
if !ok {
continue
}
if !completed[info.Task.Value] {
infos = append(infos, info)
}
if v.Follow && info.CompleteTime != nil {
prune = append(prune, info.Task)
completed[info.Task.Value] = true
}
}
}
if len(infos) != 0 {
f(infos)
}
if reset != nil {
reset()
} else if len(prune) != 0 {
_, _ = v.Remove(ctx, prune)
}
if len(tasks) != 0 && len(infos) == 0 {
return false
}
return !v.Follow
})
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/view/list_view.go | vendor/github.com/vmware/govmomi/view/list_view.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package view
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type ListView struct {
ManagedObjectView
}
func NewListView(c *vim25.Client, ref types.ManagedObjectReference) *ListView {
return &ListView{
ManagedObjectView: *NewManagedObjectView(c, ref),
}
}
func (v ListView) Add(ctx context.Context, refs []types.ManagedObjectReference) ([]types.ManagedObjectReference, error) {
req := types.ModifyListView{
This: v.Reference(),
Add: refs,
}
res, err := methods.ModifyListView(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (v ListView) Remove(ctx context.Context, refs []types.ManagedObjectReference) ([]types.ManagedObjectReference, error) {
req := types.ModifyListView{
This: v.Reference(),
Remove: refs,
}
res, err := methods.ModifyListView(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (v ListView) Reset(ctx context.Context, refs []types.ManagedObjectReference) ([]types.ManagedObjectReference, error) {
req := types.ResetListView{
This: v.Reference(),
Obj: refs,
}
res, err := methods.ResetListView(ctx, v.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.