repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L196-L202
go
train
// IssuerName parses Issuer into a pkix.Name
func (info *HostCertificateInfo) IssuerName() *pkix.Name
// 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L205-L250
go
train
// Write outputs info similar to the Chrome Certificate Viewer.
func (info *HostCertificateInfo) Write(w io.Writer) error
// 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.Common...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/encoding.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/encoding.go#L26-L51
go
train
// MarshalBinary is a wrapper around binary.Write
func MarshalBinary(fields ...interface{}) ([]byte, error)
// MarshalBinary is a wrapper around binary.Write func MarshalBinary(fields ...interface{}) ([]byte, error)
{ buf := new(bytes.Buffer) for _, p := range fields { switch m := p.(type) { case encoding.BinaryMarshaler: data, err := m.MarshalBinary() if err != nil { return nil, ProtocolError(err) } _, _ = buf.Write(data) case []byte: _, _ = buf.Write(m) case string: _, _ = buf.WriteString(m) ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/encoding.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/encoding.go#L54-L73
go
train
// UnmarshalBinary is a wrapper around binary.Read
func UnmarshalBinary(data []byte, fields ...interface{}) error
// UnmarshalBinary is a wrapper around binary.Read func UnmarshalBinary(data []byte, fields ...interface{}) error
{ buf := bytes.NewBuffer(data) for _, p := range fields { switch m := p.(type) { case encoding.BinaryUnmarshaler: return m.UnmarshalBinary(buf.Bytes()) case *[]byte: *m = buf.Bytes() return nil default: err := binary.Read(buf, binary.LittleEndian, p) if err != nil { return ProtocolError(e...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
ssoadmin/methods/role.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ssoadmin/methods/role.go#L70-L76
go
train
// C14N returns the canonicalized form of LoginBody.Req, for use by sts.Signer
func (b *LoginBody) C14N() string
// C14N returns the canonicalized form of LoginBody.Req, for use by sts.Signer func (b *LoginBody) C14N() string
{ req, err := xml.Marshal(b.Req) if err != nil { panic(err) } return string(req) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/model.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L107-L120
go
train
// ESX is the default Model for a standalone ESX instance
func ESX() *Model
// ESX is the default Model for a standalone ESX instance func ESX() *Model
{ return &Model{ ServiceContent: esx.ServiceContent, RootFolder: esx.RootFolder, Autostart: true, Datastore: 1, Machine: 2, DelayConfig: DelayConfig{ Delay: 0, DelayJitter: 0, MethodDelay: nil, }, } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/model.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L123-L141
go
train
// VPX is the default Model for a vCenter instance
func VPX() *Model
// VPX is the default Model for a vCenter instance func VPX() *Model
{ return &Model{ ServiceContent: vpx.ServiceContent, RootFolder: vpx.RootFolder, Autostart: true, Datacenter: 1, Portgroup: 1, Host: 1, Cluster: 1, ClusterHost: 3, Datastore: 1, Machine: 2, DelayConfig: DelayConfig{ Delay: 0, DelayJit...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/model.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L144-L179
go
train
// Count returns a Model with total number of each existing type
func (m *Model) Count() Model
// Count returns a Model with total number of each existing type func (m *Model) Count() Model
{ count := Model{} for ref, obj := range Map.objects { if _, ok := obj.(mo.Entity); !ok { continue } count.total++ switch ref.Type { case "Datacenter": count.Datacenter++ case "DistributedVirtualPortgroup": count.Portgroup++ case "ClusterComputeResource": count.Cluster++ case "Datastor...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/model.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L186-L489
go
train
// Create populates the Model with the given ModelConfig
func (m *Model) Create() error
// Create populates the Model with the given ModelConfig func (m *Model) Create() error
{ m.Service = New(NewServiceInstance(m.ServiceContent, m.RootFolder)) ctx := context.Background() client := m.Service.client root := object.NewRootFolder(client) // After all hosts are created, this var is used to mount the host datastores. var hosts []*object.HostSystem hostMap := make(map[string][]*object.H...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/model.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L516-L520
go
train
// Remove cleans up items created by the Model, such as local datastore directories
func (m *Model) Remove()
// Remove cleans up items created by the Model, such as local datastore directories func (m *Model) Remove()
{ for _, dir := range m.dirs { _ = os.RemoveAll(dir) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/host/autostart/autostart.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/autostart/autostart.go#L68-L90
go
train
// VirtualMachines returns list of virtual machine objects based on the // arguments specified on the command line. This helper is defined in // flags.SearchFlag as well, but that pulls in other virtual machine flags that // are not relevant here.
func (f *AutostartFlag) VirtualMachines(args []string) ([]*object.VirtualMachine, error)
// VirtualMachines returns list of virtual machine objects based on the // arguments specified on the command line. This helper is defined in // flags.SearchFlag as well, but that pulls in other virtual machine flags that // are not relevant here. func (f *AutostartFlag) VirtualMachines(args []string) ([]*object.Virtua...
{ ctx := context.TODO() if len(args) == 0 { return nil, errors.New("no argument") } finder, err := f.Finder() if err != nil { return nil, err } var out []*object.VirtualMachine for _, arg := range args { vms, err := finder.VirtualMachineList(ctx, arg) if err != nil { return nil, err } out = a...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/retry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/retry.go#L33-L61
go
train
// TemporaryNetworkError returns a RetryFunc that retries up to a maximum of n // times, only if the error returned by the RoundTrip function is a temporary // network error (for example: a connect timeout).
func TemporaryNetworkError(n int) RetryFunc
// TemporaryNetworkError returns a RetryFunc that retries up to a maximum of n // times, only if the error returned by the RoundTrip function is a temporary // network error (for example: a connect timeout). func TemporaryNetworkError(n int) RetryFunc
{ return func(err error) (retry bool, delay time.Duration) { var nerr net.Error var ok bool // Never retry if this is not a network error. switch rerr := err.(type) { case *url.Error: if nerr, ok = rerr.Err.(net.Error); !ok { return false, 0 } case net.Error: nerr = rerr default: return...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/retry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/retry.go#L77-L84
go
train
// Retry wraps the specified soap.RoundTripper and invokes the // specified RetryFunc. The RetryFunc returns whether or not to // retry the call, and if so, how long to wait before retrying. If // the result of this function is to not retry, the original error // is returned from the RoundTrip function.
func Retry(roundTripper soap.RoundTripper, fn RetryFunc) soap.RoundTripper
// Retry wraps the specified soap.RoundTripper and invokes the // specified RetryFunc. The RetryFunc returns whether or not to // retry the call, and if so, how long to wait before retrying. If // the result of this function is to not retry, the original error // is returned from the RoundTrip function. func Retry(roun...
{ r := &retry{ roundTripper: roundTripper, fn: fn, } return r }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/custom_fields_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/custom_fields_manager.go#L40-L45
go
train
// GetCustomFieldsManager wraps NewCustomFieldsManager, returning ErrNotSupported // when the client is not connected to a vCenter instance.
func GetCustomFieldsManager(c *vim25.Client) (*CustomFieldsManager, error)
// 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/diagnostic_log.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/diagnostic_log.go#L37-L46
go
train
// Seek to log position starting at the last nlines of the log
func (l *DiagnosticLog) Seek(ctx context.Context, nlines int32) error
// 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/diagnostic_log.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/diagnostic_log.go#L50-L76
go
train
// 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)
// 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....
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/vm/power.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/vm/power.go#L107-L113
go
train
// this is annoying, but the likely use cases for Datacenter.PowerOnVM outside of this command would // use []types.ManagedObjectReference via ContainerView or field such as ResourcePool.Vm rather than the Finder.
func vmReferences(vms []*object.VirtualMachine) []types.ManagedObjectReference
// this is annoying, but the likely use cases for Datacenter.PowerOnVM outside of this command would // use []types.ManagedObjectReference via ContainerView or field such as ResourcePool.Vm rather than the Finder. func vmReferences(vms []*object.VirtualMachine) []types.ManagedObjectReference
{ refs := make([]types.ManagedObjectReference, len(vms)) for i, vm := range vms { refs[i] = vm.Reference() } return refs }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/vix/property.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/property.go#L137-L164
go
train
// MarshalBinary implements the encoding.BinaryMarshaler interface
func (p *Property) MarshalBinary() ([]byte, error)
// MarshalBinary implements the encoding.BinaryMarshaler interface func (p *Property) MarshalBinary() ([]byte, error)
{ buf := new(bytes.Buffer) // #nosec: Errors unhandled _ = binary.Write(buf, binary.LittleEndian, &p.header) switch p.header.Kind { case vixPropertyTypeBool: // #nosec: Errors unhandled _ = binary.Write(buf, binary.LittleEndian, p.data.Bool) case vixPropertyTypeInt32: // #nosec: Errors unhandled _ = bi...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/vix/property.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/property.go#L167-L199
go
train
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (p *Property) UnmarshalBinary(data []byte) error
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface func (p *Property) UnmarshalBinary(data []byte) error
{ buf := bytes.NewBuffer(data) err := binary.Read(buf, binary.LittleEndian, &p.header) if err != nil { return err } switch p.header.Kind { case vixPropertyTypeBool: return binary.Read(buf, binary.LittleEndian, &p.data.Bool) case vixPropertyTypeInt32: return binary.Read(buf, binary.LittleEndian, &p.data....
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/vix/property.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/property.go#L202-L222
go
train
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (l *PropertyList) UnmarshalBinary(data []byte) error
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface func (l *PropertyList) UnmarshalBinary(data []byte) error
{ headerSize := int32Size * 3 for { p := new(Property) err := p.UnmarshalBinary(data) if err != nil { return err } *l = append(*l, p) offset := headerSize + p.header.Length data = data[offset:] if len(data) == 0 { return nil } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/vix/property.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/property.go#L225-L236
go
train
// MarshalBinary implements the encoding.BinaryMarshaler interface
func (l *PropertyList) MarshalBinary() ([]byte, error)
// MarshalBinary implements the encoding.BinaryMarshaler interface func (l *PropertyList) MarshalBinary() ([]byte, error)
{ var buf bytes.Buffer for _, p := range *l { // #nosec: Errors unhandled b, _ := p.MarshalBinary() // #nosec: Errors unhandled _, _ = buf.Write(b) } return buf.Bytes(), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/datacenter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datacenter.go#L94-L129
go
train
// 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)
// 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 := NewVirtualM...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/search_index.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L40-L56
go
train
// FindByDatastorePath finds a virtual machine by its location on a datastore.
func (s SearchIndex) FindByDatastorePath(ctx context.Context, dc *Datacenter, path string) (Reference, error)
// 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/search_index.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L59-L79
go
train
// 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)
// 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 N...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/search_index.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L82-L97
go
train
// FindByInventoryPath finds a managed entity based on its location in the inventory.
func (s SearchIndex) FindByInventoryPath(ctx context.Context, path string) (Reference, error)
// 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 } return NewReference(s.c, *res.Returnval), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/search_index.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L123-L144
go
train
// 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)
// 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...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/search_index.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L147-L163
go
train
// FindChild finds a particular child based on a managed entity name.
func (s SearchIndex) FindChild(ctx context.Context, entity Reference, name string) (Reference, error)
// 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/toolbox/main.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/toolbox/main.go#L43-L71
go
train
// This example can be run on a VM hosted by ESX, Fusion or Workstation
func main()
// This example can be run on a VM hosted by ESX, Fusion or Workstation func main()
{ flag.Parse() in := toolbox.NewBackdoorChannelIn() out := toolbox.NewBackdoorChannelOut() service := toolbox.NewService(in, out) if os.Getuid() == 0 { service.Power.Halt.Handler = toolbox.Halt service.Power.Reboot.Handler = toolbox.Reboot } err := service.Start() if err != nil { log.Fatal(err) } ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L277-L316
go
train
// configure TLS and retry settings before making any connections
func (flag *ClientFlag) configure(sc *soap.Client) (soap.RoundTripper, error)
// configure TLS and retry settings before making any connections func (flag *ClientFlag) configure(sc *soap.Client) (soap.RoundTripper, error)
{ if flag.cert != "" { cert, err := tls.LoadX509KeyPair(flag.cert, flag.key) if err != nil { return nil, err } sc.SetCertificate(cert) } // Set namespace and version sc.Namespace = "urn:" + flag.vimNamespace sc.Version = flag.vimVersion sc.UserAgent = fmt.Sprintf("govc/%s", Version) if err := fla...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L494-L524
go
train
// apiVersionValid returns whether or not the API version supported by the // server the client is connected to is not recent enough.
func apiVersionValid(c *vim25.Client, minVersionString string) error
// apiVersionValid returns whether or not the API version supported by the // server the client is connected to is not recent enough. func apiVersionValid(c *vim25.Client, minVersionString string) error
{ if minVersionString == "-" { // Disable version check return nil } apiVersion := c.ServiceContent.About.ApiVersion if isDevelopmentVersion(apiVersion) { return nil } realVersion, err := ParseVersion(apiVersion) if err != nil { return fmt.Errorf("error parsing API version %q: %s", apiVersion, err) }...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L606-L668
go
train
// Environ returns the govc environment variables for this connection
func (flag *ClientFlag) Environ(extra bool) []string
// Environ returns the govc environment variables for this connection func (flag *ClientFlag) Environ(extra bool) []string
{ var env []string add := func(k, v string) { env = append(env, fmt.Sprintf("%s=%s", k, v)) } u := *flag.url if u.User != nil { add(envUsername, u.User.Username()) if p, ok := u.User.Password(); ok { add(envPassword, p) } u.User = nil } if u.Path == vim25.Path { u.Path = "" } u.Fragment = "...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L671-L694
go
train
// WithCancel calls the given function, returning when complete or canceled via SIGINT.
func (flag *ClientFlag) WithCancel(ctx context.Context, f func(context.Context) error) error
// WithCancel calls the given function, returning when complete or canceled via SIGINT. func (flag *ClientFlag) WithCancel(ctx context.Context, f func(context.Context) error) error
{ sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT) wctx, cancel := context.WithCancel(ctx) defer cancel() done := make(chan bool) var werr error go func() { defer close(done) werr = f(wctx) }() select { case <-sig: cancel() <-done // Wait for f() to complete case <-done: } re...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/progress/tee.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/tee.go#L21-L31
go
train
// Tee works like Unix tee; it forwards all progress reports it receives to the // specified sinks
func Tee(s1, s2 Sinker) Sinker
// Tee works like Unix tee; it forwards all progress reports it receives to the // specified sinks func Tee(s1, s2 Sinker) Sinker
{ fn := func() chan<- Report { d1 := s1.Sink() d2 := s2.Sink() u := make(chan Report) go tee(u, d1, d2) return u } return SinkFunc(fn) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/vm/change.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/vm/change.go#L61-L79
go
train
// setAllocation sets *info=nil if none of the fields have been set. // We need non-nil fields for use with flag.FlagSet, but we want the // VirtualMachineConfigSpec fields to be nil if none of the related flags were given.
func setAllocation(info **types.ResourceAllocationInfo)
// setAllocation sets *info=nil if none of the fields have been set. // We need non-nil fields for use with flag.FlagSet, but we want the // VirtualMachineConfigSpec fields to be nil if none of the related flags were given. func setAllocation(info **types.ResourceAllocationInfo)
{ r := *info if r.Shares.Level == "" { r.Shares = nil } else { return } if r.Limit != nil { return } if r.Reservation != nil { return } *info = nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/host_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/host_system.go#L136-L161
go
train
// CreateDefaultESX creates a standalone ESX // Adds objects of type: Datacenter, Network, ComputeResource, ResourcePool and HostSystem
func CreateDefaultESX(f *Folder)
// CreateDefaultESX creates a standalone ESX // Adds objects of type: Datacenter, Network, ComputeResource, ResourcePool and HostSystem func CreateDefaultESX(f *Folder)
{ dc := NewDatacenter(f) host := NewHostSystem(esx.HostSystem) summary := new(types.ComputeResourceSummary) addComputeResource(summary, host) cr := &mo.ComputeResource{ Summary: summary, Network: esx.Datacenter.Network, } cr.EnvironmentBrowser = newEnvironmentBrowser() cr.Self = *host.Parent cr.Name = ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/host_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/host_system.go#L165-L203
go
train
// CreateStandaloneHost uses esx.HostSystem as a template, applying the given spec // and creating the ComputeResource parent and ResourcePool sibling.
func CreateStandaloneHost(f *Folder, spec types.HostConnectSpec) (*HostSystem, types.BaseMethodFault)
// CreateStandaloneHost uses esx.HostSystem as a template, applying the given spec // and creating the ComputeResource parent and ResourcePool sibling. func CreateStandaloneHost(f *Folder, spec types.HostConnectSpec) (*HostSystem, types.BaseMethodFault)
{ if spec.HostName == "" { return nil, &types.NoHost{} } pool := NewResourcePool() host := NewHostSystem(esx.HostSystem) host.Summary.Config.Name = spec.HostName host.Name = host.Summary.Config.Name host.Runtime.ConnectionState = types.HostSystemConnectionStateDisconnected summary := new(types.ComputeReso...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item_updatesession.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L43-L50
go
train
// CreateLibraryItemUpdateSession creates a new library item
func (c *Manager) CreateLibraryItemUpdateSession(ctx context.Context, session UpdateSession) (string, error)
// CreateLibraryItemUpdateSession creates a new library item func (c *Manager) CreateLibraryItemUpdateSession(ctx context.Context, session UpdateSession) (string, error)
{ url := internal.URL(c, internal.LibraryItemUpdateSession) spec := struct { CreateSpec UpdateSession `json:"create_spec"` }{session} var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item_updatesession.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L53-L57
go
train
// GetLibraryItemUpdateSession gets the update session information with status
func (c *Manager) GetLibraryItemUpdateSession(ctx context.Context, id string) (*UpdateSession, error)
// GetLibraryItemUpdateSession gets the update session information with status func (c *Manager) GetLibraryItemUpdateSession(ctx context.Context, id string) (*UpdateSession, error)
{ url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id) var res UpdateSession return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item_updatesession.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L60-L64
go
train
// ListLibraryItemUpdateSession gets the list of update sessions
func (c *Manager) ListLibraryItemUpdateSession(ctx context.Context) (*[]string, error)
// ListLibraryItemUpdateSession gets the list of update sessions func (c *Manager) ListLibraryItemUpdateSession(ctx context.Context) (*[]string, error)
{ url := internal.URL(c, internal.LibraryItemUpdateSession) var res []string return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item_updatesession.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L79-L82
go
train
// DeleteLibraryItemUpdateSession deletes an update session
func (c *Manager) DeleteLibraryItemUpdateSession(ctx context.Context, id string) error
// DeleteLibraryItemUpdateSession deletes an update session func (c *Manager) DeleteLibraryItemUpdateSession(ctx context.Context, id string) error
{ url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item_updatesession.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L85-L88
go
train
// FailLibraryItemUpdateSession fails an update session
func (c *Manager) FailLibraryItemUpdateSession(ctx context.Context, id string) error
// FailLibraryItemUpdateSession fails an update session func (c *Manager) FailLibraryItemUpdateSession(ctx context.Context, id string) error
{ url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id).WithAction("fail") return c.Do(ctx, url.Request(http.MethodPost), nil) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item_updatesession.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L98-L116
go
train
// WaitOnLibraryItemUpdateSession blocks until the update session is no longer // in the ACTIVE state.
func (c *Manager) WaitOnLibraryItemUpdateSession( ctx context.Context, sessionID string, interval time.Duration, intervalCallback func()) error
// WaitOnLibraryItemUpdateSession blocks until the update session is no longer // in the ACTIVE state. func (c *Manager) WaitOnLibraryItemUpdateSession( ctx context.Context, sessionID string, interval time.Duration, intervalCallback func()) error
{ // Wait until the upload operation is complete to return. for { session, err := c.GetLibraryItemUpdateSession(ctx, sessionID) if err != nil { return err } if session.State != "ACTIVE" { return nil } time.Sleep(interval) if intervalCallback != nil { intervalCallback() } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/http_nfc_lease.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/http_nfc_lease.go#L46-L93
go
train
// ServeNFC handles NFC file upload/download
func ServeNFC(w http.ResponseWriter, r *http.Request)
// ServeNFC handles NFC file upload/download func ServeNFC(w http.ResponseWriter, r *http.Request)
{ p := strings.Split(r.URL.Path, "/") id, name := p[len(p)-2], p[len(p)-1] ref := types.ManagedObjectReference{Type: "HttpNfcLease", Value: id} l, ok := nfcLease.Load(ref) if !ok { log.Printf("invalid NFC lease: %s", id) http.NotFound(w, r) return } lease := l.(*HttpNfcLease) file, ok := lease.files[name...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
sts/internal/types.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/internal/types.go#L552-L600
go
train
// toString returns an XML encoded RequestSecurityToken. // When c14n is true, returns the canonicalized ActAs.Assertion which is required to sign the Issue request. // When c14n is false, returns the original content of the ActAs.Assertion. // The original content must be used within the request Body, as it has its ow...
func (r *RequestSecurityToken) toString(c14n bool) string
// toString returns an XML encoded RequestSecurityToken. // When c14n is true, returns the canonicalized ActAs.Assertion which is required to sign the Issue request. // When c14n is false, returns the original content of the ActAs.Assertion. // The original content must be used within the request Body, as it has its ow...
{ actas := "" if r.ActAs != nil { token := r.ActAs.Token if c14n { var a Assertion err := Unmarshal([]byte(r.ActAs.Token), &a) if err != nil { log.Printf("decode ActAs: %s", err) } token = a.C14N() } actas = fmt.Sprintf(`<wst:ActAs xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/2008...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
sts/internal/types.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/internal/types.go#L673-L679
go
train
// Marshal panics if xml.Marshal returns an error
func Marshal(val interface{}) string
// Marshal panics if xml.Marshal returns an error func Marshal(val interface{}) string
{ b, err := xml.Marshal(val) if err != nil { panic(err) } return string(b) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
sts/internal/types.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/internal/types.go#L684-L694
go
train
// mkns prepends the given namespace to xml.Name.Local and returns obj encoded as xml. // Note that the namespace is required when encoding, but the namespace prefix must not be // present when decoding as Go's decoding does not handle namespace prefix.
func mkns(ns string, obj interface{}, name ...*xml.Name) string
// mkns prepends the given namespace to xml.Name.Local and returns obj encoded as xml. // Note that the namespace is required when encoding, but the namespace prefix must not be // present when decoding as Go's decoding does not handle namespace prefix. func mkns(ns string, obj interface{}, name ...*xml.Name) string
{ ns += ":" for i := range name { name[i].Space = "" if !strings.HasPrefix(name[i].Local, ns) { name[i].Local = ns + name[i].Local } } return Marshal(obj) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
view/container_view.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/container_view.go#L39-L93
go
train
// Retrieve populates dst as property.Collector.Retrieve does, for all entities in the view of types specified by kind.
func (v ContainerView) Retrieve(ctx context.Context, kind []string, ps []string, dst interface{}) error
// Retrieve populates dst as property.Collector.Retrieve does, for all entities in the view of types specified by kind. func (v ContainerView) Retrieve(ctx context.Context, kind []string, ps []string, dst interface{}) error
{ pc := property.DefaultCollector(v.Client()) ospec := types.ObjectSpec{ Obj: v.Reference(), Skip: types.NewBool(true), SelectSet: []types.BaseSelectionSpec{ &types.TraversalSpec{ Type: v.Reference().Type, Path: "view", }, }, } var pspec []types.PropertySpec if len(kind) == 0 { kind = ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
view/container_view.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/container_view.go#L96-L113
go
train
// RetrieveWithFilter populates dst as Retrieve does, but only for entities matching the given filter.
func (v ContainerView) RetrieveWithFilter(ctx context.Context, kind []string, ps []string, dst interface{}, filter property.Filter) error
// RetrieveWithFilter populates dst as Retrieve does, but only for entities matching the given filter. func (v ContainerView) RetrieveWithFilter(ctx context.Context, kind []string, ps []string, dst interface{}, filter property.Filter) error
{ if len(filter) == 0 { return v.Retrieve(ctx, kind, ps, dst) } var content []types.ObjectContent err := v.Retrieve(ctx, kind, filter.Keys(), &content) if err != nil { return err } objs := filter.MatchObjectContent(content) pc := property.DefaultCollector(v.Client()) return pc.Retrieve(ctx, objs, ps,...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
view/container_view.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/container_view.go#L116-L130
go
train
// Find returns object references for entities of type kind, matching the given filter.
func (v ContainerView) Find(ctx context.Context, kind []string, filter property.Filter) ([]types.ManagedObjectReference, error)
// Find returns object references for entities of type kind, matching the given filter. func (v ContainerView) Find(ctx context.Context, kind []string, filter property.Filter) ([]types.ManagedObjectReference, error)
{ if len(filter) == 0 { // Ensure we have at least 1 filter to avoid retrieving all properties. filter = property.Filter{"name": "*"} } var content []types.ObjectContent err := v.Retrieve(ctx, kind, filter.Keys(), &content) if err != nil { return nil, err } return filter.MatchObjectContent(content), ni...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/virtual_machine.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/virtual_machine.go#L519-L583
go
train
// Updates both vm.Layout.Disk and vm.LayoutEx.Disk
func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault
// Updates both vm.Layout.Disk and vm.LayoutEx.Disk func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault
{ var disksLayout []types.VirtualMachineFileLayoutDiskLayout var disksLayoutEx []types.VirtualMachineFileLayoutExDiskLayout disks := object.VirtualDeviceList(vm.Config.Hardware.Device).SelectByType((*types.VirtualDisk)(nil)) for _, disk := range disks { disk := disk.(*types.VirtualDisk) diskBacking := disk.Ba...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/virtual_machine.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/virtual_machine.go#L805-L813
go
train
// Rather than keep an fd open for each VM, open/close the log for each messages. // This is ok for now as we do not do any heavy VM logging.
func (vm *VirtualMachine) logPrintf(format string, v ...interface{})
// Rather than keep an fd open for each VM, open/close the log for each messages. // This is ok for now as we do not do any heavy VM logging. func (vm *VirtualMachine) logPrintf(format string, v ...interface{})
{ f, err := os.OpenFile(vm.log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0) if err != nil { log.Println(err) return } log.New(f, "vmx ", log.Flags()).Printf(format, v...) _ = f.Close() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/virtual_machine.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/virtual_machine.go#L859-L867
go
train
// From http://pubs.vmware.com/vsphere-60/index.jsp?topic=%2Fcom.vmware.vsphere.networking.doc%2FGUID-DC7478FF-DC44-4625-9AD7-38208C56A552.html // "The host generates generateMAC addresses that consists of the VMware OUI 00:0C:29 and the last three octets in hexadecimal // format of the virtual machine UUID. The virt...
func (vm *VirtualMachine) generateMAC() string
// From http://pubs.vmware.com/vsphere-60/index.jsp?topic=%2Fcom.vmware.vsphere.networking.doc%2FGUID-DC7478FF-DC44-4625-9AD7-38208C56A552.html // "The host generates generateMAC addresses that consists of the VMware OUI 00:0C:29 and the last three octets in hexadecimal // format of the virtual machine UUID. The virt...
{ id := uuid.New() // Random is fine for now. offset := len(id) - len(vmwOUI) mac := append(vmwOUI, id[offset:]...) return mac.String() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/output.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/output.go#L80-L87
go
train
// Log outputs the specified string, prefixed with the current time. // A newline is not automatically added. If the specified string // starts with a '\r', the current line is cleared first.
func (flag *OutputFlag) Log(s string) (int, error)
// Log outputs the specified string, prefixed with the current time. // A newline is not automatically added. If the specified string // starts with a '\r', the current line is cleared first. func (flag *OutputFlag) Log(s string) (int, error)
{ if len(s) > 0 && s[0] == '\r' { flag.Write([]byte{'\r', 033, '[', 'K'}) s = s[1:] } return flag.WriteString(time.Now().Format("[02-01-06 15:04:05] ") + s) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/output.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/output.go#L177-L206
go
train
// loopA runs before Sink() has been called.
func (p *progressLogger) loopA()
// 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("...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/flags/output.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/output.go#L209-L236
go
train
// loopA runs after Sink() has been called.
func (p *progressLogger) loopB(tick *time.Ticker, ch <-chan progress.Report) error
// loopA runs after Sink() has been called. func (p *progressLogger) loopB(tick *time.Ticker, ch <-chan progress.Report) error
{ var r progress.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 ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/retrieve.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L49-L66
go
train
// ObjectContentToType loads an ObjectContent value into the value it // represents. If the ObjectContent value has a non-empty 'MissingSet' field, // it returns the first fault it finds there as error. If the 'MissingSet' // field is empty, it returns a pointer to a reflect.Value. It handles contain // nested properti...
func ObjectContentToType(o types.ObjectContent) (interface{}, error)
// ObjectContentToType loads an ObjectContent value into the value it // represents. If the ObjectContent value has a non-empty 'MissingSet' field, // it returns the first fault it finds there as error. If the 'MissingSet' // field is empty, it returns a pointer to a reflect.Value. It handles contain // nested properti...
{ // Expect no properties in the missing set for _, p := range o.MissingSet { if ignoreMissingProperty(o.Obj, p) { continue } return nil, soap.WrapVimFault(p.Fault.Fault) } ti := typeInfoForType(o.Obj.Type) v, err := ti.LoadFromObjectContent(o) if err != nil { return nil, err } return v.Elem().In...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/retrieve.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L70-L82
go
train
// ApplyPropertyChange converts the response of a call to WaitForUpdates // and applies it to the given managed object.
func ApplyPropertyChange(obj Reference, changes []types.PropertyChange)
// ApplyPropertyChange converts the response of a call to WaitForUpdates // and applies it to the given managed object. func ApplyPropertyChange(obj Reference, changes []types.PropertyChange)
{ t := typeInfoForType(obj.Reference().Type) v := reflect.ValueOf(obj) for _, p := range changes { rv, ok := t.props[p.Name] if !ok { continue } assignValue(v, rv, reflect.ValueOf(p.Val)) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/retrieve.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L86-L152
go
train
// LoadRetrievePropertiesResponse converts the response of a call to // RetrieveProperties to one or more managed objects.
func LoadRetrievePropertiesResponse(res *types.RetrievePropertiesResponse, dst interface{}) error
// LoadRetrievePropertiesResponse converts the response of a call to // RetrieveProperties to one or more managed objects. func LoadRetrievePropertiesResponse(res *types.RetrievePropertiesResponse, dst interface{}) error
{ rt := reflect.TypeOf(dst) if rt == nil || rt.Kind() != reflect.Ptr { panic("need pointer") } rv := reflect.ValueOf(dst).Elem() if !rv.CanSet() { panic("cannot set dst") } isSlice := false switch rt.Elem().Kind() { case reflect.Struct: case reflect.Slice: isSlice = true default: panic("unexpected...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/retrieve.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L157-L164
go
train
// RetrievePropertiesForRequest calls the RetrieveProperties method with the // specified request and decodes the response struct into the value pointed to // by dst.
func RetrievePropertiesForRequest(ctx context.Context, r soap.RoundTripper, req types.RetrieveProperties, dst interface{}) error
// RetrievePropertiesForRequest calls the RetrieveProperties method with the // specified request and decodes the response struct into the value pointed to // by dst. func RetrievePropertiesForRequest(ctx context.Context, r soap.RoundTripper, req types.RetrieveProperties, dst interface{}) error
{ res, err := methods.RetrieveProperties(ctx, r, &req) if err != nil { return err } return LoadRetrievePropertiesResponse(res, dst) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/retrieve.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L168-L190
go
train
// RetrieveProperties retrieves the properties of the managed object specified // as obj and decodes the response struct into the value pointed to by dst.
func RetrieveProperties(ctx context.Context, r soap.RoundTripper, pc, obj types.ManagedObjectReference, dst interface{}) error
// RetrieveProperties retrieves the properties of the managed object specified // as obj and decodes the response struct into the value pointed to by dst. func RetrieveProperties(ctx context.Context, r soap.RoundTripper, pc, obj types.ManagedObjectReference, dst interface{}) error
{ req := types.RetrieveProperties{ This: pc, SpecSet: []types.PropertyFilterSpec{ { ObjectSet: []types.ObjectSpec{ { Obj: obj, Skip: types.NewBool(false), }, }, PropSet: []types.PropertySpec{ { All: types.NewBool(true), Type: obj.Type, }, }, }, ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L57-L86
go
train
// NewServer creates a new Server instance with the default handlers
func NewServer() *Server
// NewServer creates a new Server instance with the default handlers func NewServer() *Server
{ if f := flag.Lookup("toolbox.trace"); f != nil { Trace, _ = strconv.ParseBool(f.Value.String()) } s := &Server{ sessions: make(map[uint64]*session), schemes: make(map[string]FileHandler), chmod: os.Chmod, chown: os.Chown, } s.handlers = map[int32]func(*Packet) (interface{}, error){ OpCreate...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L89-L95
go
train
// RegisterFileHandler enables dispatch to handler for the given scheme.
func (s *Server) RegisterFileHandler(scheme string, handler FileHandler)
// RegisterFileHandler enables dispatch to handler for the given scheme. func (s *Server) RegisterFileHandler(scheme string, handler FileHandler)
{ if handler == nil { delete(s.schemes, scheme) return } s.schemes[scheme] = handler }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L98-L123
go
train
// Dispatch unpacks the given request packet and dispatches to the appropriate handler
func (s *Server) Dispatch(packet []byte) ([]byte, error)
// Dispatch unpacks the given request packet and dispatches to the appropriate handler func (s *Server) Dispatch(packet []byte) ([]byte, error)
{ req := &Packet{} err := req.UnmarshalBinary(packet) if err != nil { return nil, err } if Trace { fmt.Fprintf(os.Stderr, "[hgfs] request %#v\n", req.Header) } var res interface{} handler, ok := s.handlers[req.Op] if ok { res, err = handler(req) } else { err = &Status{ Code: StatusOperationNo...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L142-L168
go
train
// urlParse attempts to convert the given name to a URL with scheme for use as FileHandler dispatch.
func urlParse(name string) *url.URL
// urlParse attempts to convert the given name to a URL with scheme for use as FileHandler dispatch. func urlParse(name string) *url.URL
{ var info os.FileInfo u, err := url.Parse(name) if err == nil && u.Scheme == "" { info, err = os.Stat(u.Path) if err == nil && info.IsDir() { u.Scheme = ArchiveScheme // special case for IsDir() return u } } u, err = url.Parse(strings.TrimPrefix(name, "/")) // must appear to be an absolute path or ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L171-L193
go
train
// OpenFile selects the File implementation based on file type and mode.
func (s *Server) OpenFile(name string, mode int32) (File, error)
// OpenFile selects the File implementation based on file type and mode. func (s *Server) OpenFile(name string, mode int32) (File, error)
{ u := urlParse(name) if h, ok := s.schemes[u.Scheme]; ok { f, serr := h.Open(u, mode) if serr != os.ErrNotExist { return f, serr } } switch mode { case OpenModeReadOnly: return os.Open(filepath.Clean(name)) case OpenModeWriteOnly: flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC return os.OpenFil...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L204-L215
go
train
// Stat wraps os.Stat such that we can report directory types as regular files to support archive streaming. // In the case of standard vmware-tools, attempts to transfer directories result // with a VIX_E_NOT_A_FILE (see InitiateFileTransfer{To,From}Guest). // Note that callers on the VMX side that reach this path are...
func (s *Server) Stat(name string) (os.FileInfo, error)
// Stat wraps os.Stat such that we can report directory types as regular files to support archive streaming. // In the case of standard vmware-tools, attempts to transfer directories result // with a VIX_E_NOT_A_FILE (see InitiateFileTransfer{To,From}Guest). // Note that callers on the VMX side that reach this path are...
{ u := urlParse(name) if h, ok := s.schemes[u.Scheme]; ok { sinfo, serr := h.Stat(u) if serr != os.ErrNotExist { return sinfo, serr } } return os.Stat(name) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L271-L297
go
train
// CreateSessionV4 handls OpCreateSessionV4 requests
func (s *Server) CreateSessionV4(p *Packet) (interface{}, error)
// CreateSessionV4 handls OpCreateSessionV4 requests func (s *Server) CreateSessionV4(p *Packet) (interface{}, error)
{ const SessionMaxPacketSizeValid = 0x1 req := new(RequestCreateSessionV4) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } res := &ReplyCreateSessionV4{ SessionID: uint64(rand.Int63()), NumCapabilities: uint32(len(s.Capabilities)), MaxPacketSize: LargePacketMax, Flags...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L300-L306
go
train
// DestroySessionV4 handls OpDestroySessionV4 requests
func (s *Server) DestroySessionV4(p *Packet) (interface{}, error)
// DestroySessionV4 handls OpDestroySessionV4 requests func (s *Server) DestroySessionV4(p *Packet) (interface{}, error)
{ if s.removeSession(p.SessionID) { return &ReplyDestroySessionV4{}, nil } return nil, &Status{Code: StatusStaleSession} }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L309-L324
go
train
// Stat maps os.FileInfo to AttrV2
func (a *AttrV2) Stat(info os.FileInfo)
// Stat maps os.FileInfo to AttrV2 func (a *AttrV2) Stat(info os.FileInfo)
{ switch { case info.IsDir(): a.Type = FileTypeDirectory case info.Mode()&os.ModeSymlink == os.ModeSymlink: a.Type = FileTypeSymlink default: a.Type = FileTypeRegular } a.Size = uint64(info.Size()) a.Mask = AttrValidType | AttrValidSize a.sysStat(info) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L327-L345
go
train
// GetattrV2 handles OpGetattrV2 requests
func (s *Server) GetattrV2(p *Packet) (interface{}, error)
// GetattrV2 handles OpGetattrV2 requests func (s *Server) GetattrV2(p *Packet) (interface{}, error)
{ res := &ReplyGetattrV2{} req := new(RequestGetattrV2) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } name := req.FileName.Path() info, err := s.Stat(name) if err != nil { return nil, err } res.Attr.Stat(info) return res, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L348-L402
go
train
// SetattrV2 handles OpSetattrV2 requests
func (s *Server) SetattrV2(p *Packet) (interface{}, error)
// SetattrV2 handles OpSetattrV2 requests func (s *Server) SetattrV2(p *Packet) (interface{}, error)
{ res := &ReplySetattrV2{} req := new(RequestSetattrV2) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } name := req.FileName.Path() _, err = os.Stat(name) if err != nil && os.IsNotExist(err) { // assuming this is a virtual file return res, nil } uid := -1 if req.Attr.Mask&...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L409-L445
go
train
// Open handles OpOpen requests
func (s *Server) Open(p *Packet) (interface{}, error)
// Open handles OpOpen requests func (s *Server) Open(p *Packet) (interface{}, error)
{ req := new(RequestOpen) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } session, err := s.getSession(p) if err != nil { return nil, err } name := req.FileName.Path() mode := req.OpenMode if mode != OpenModeReadOnly { return nil, &Status{ Err: fmt.Errorf("open mode(%d) ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L448-L474
go
train
// Close handles OpClose requests
func (s *Server) Close(p *Packet) (interface{}, error)
// Close handles OpClose requests func (s *Server) Close(p *Packet) (interface{}, error)
{ req := new(RequestClose) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } session, err := s.getSession(p) if err != nil { return nil, err } session.mu.Lock() file, ok := session.files[req.Handle] if ok { delete(session.files, req.Handle) } session.mu.Unlock() if ok { e...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L477-L512
go
train
// OpenV3 handles OpOpenV3 requests
func (s *Server) OpenV3(p *Packet) (interface{}, error)
// OpenV3 handles OpOpenV3 requests func (s *Server) OpenV3(p *Packet) (interface{}, error)
{ req := new(RequestOpenV3) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } session, err := s.getSession(p) if err != nil { return nil, err } name := req.FileName.Path() if req.DesiredLock != LockNone { return nil, &Status{ Err: fmt.Errorf("open lock type=%d not supported...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L515-L552
go
train
// ReadV3 handles OpReadV3 requests
func (s *Server) ReadV3(p *Packet) (interface{}, error)
// ReadV3 handles OpReadV3 requests func (s *Server) ReadV3(p *Packet) (interface{}, error)
{ req := new(RequestReadV3) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } session, err := s.getSession(p) if err != nil { return nil, err } session.mu.Lock() file, ok := session.files[req.Handle] session.mu.Unlock() if !ok { return nil, &Status{Code: StatusInvalidHandle} ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L555-L585
go
train
// WriteV3 handles OpWriteV3 requests
func (s *Server) WriteV3(p *Packet) (interface{}, error)
// WriteV3 handles OpWriteV3 requests func (s *Server) WriteV3(p *Packet) (interface{}, error)
{ req := new(RequestWriteV3) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } session, err := s.getSession(p) if err != nil { return nil, err } session.mu.Lock() file, ok := session.files[req.Handle] session.mu.Unlock() if !ok { return nil, &Status{Code: StatusInvalidHandle}...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L71-L75
go
train
// NewServer starts and returns a new Server. // The caller should call Close when finished, to shut it down.
func NewServer(handler http.Handler) *Server
// NewServer starts and returns a new Server. // The caller should call Close when finished, to shut it down. func NewServer(handler http.Handler) *Server
{ ts := NewUnstartedServer(handler, "") ts.Start() return ts }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L84-L89
go
train
// NewUnstartedServer returns a new Server but doesn't start it. // // After changing its configuration, the caller should call Start or // StartTLS. // // The caller should call Close when finished, to shut it down. // serve allows the server's listen address to be specified.
func NewUnstartedServer(handler http.Handler, serve string) *Server
// NewUnstartedServer returns a new Server but doesn't start it. // // After changing its configuration, the caller should call Start or // StartTLS. // // The caller should call Close when finished, to shut it down. // serve allows the server's listen address to be specified. func NewUnstartedServer(handler http.Handl...
{ return &Server{ Listener: newLocalListener(serve), Config: &http.Server{Handler: handler}, } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L92-L102
go
train
// Start starts a server from NewUnstartedServer.
func (s *Server) Start()
// Start starts a server from NewUnstartedServer. func (s *Server) Start()
{ if s.URL != "" { panic("Server already started") } if s.client == nil { s.client = &http.Client{Transport: &http.Transport{}} } s.URL = "http://" + s.Listener.Addr().String() s.wrap() s.goServe() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L105-L144
go
train
// StartTLS starts TLS on a server from NewUnstartedServer.
func (s *Server) StartTLS()
// StartTLS starts TLS on a server from NewUnstartedServer. func (s *Server) StartTLS()
{ if s.URL != "" { panic("Server already started") } if s.client == nil { s.client = &http.Client{Transport: &http.Transport{}} } cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) if err != nil { panic(fmt.Sprintf("httptest: NewTLSServer: %v", err)) } existingConfig := s.TLS if existingConfig !...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L148-L152
go
train
// NewTLSServer starts and returns a new Server using TLS. // The caller should call Close when finished, to shut it down.
func NewTLSServer(handler http.Handler) *Server
// NewTLSServer starts and returns a new Server using TLS. // The caller should call Close when finished, to shut it down. func NewTLSServer(handler http.Handler) *Server
{ ts := NewUnstartedServer(handler, "") ts.StartTLS() return ts }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L160-L210
go
train
// Close shuts down the server and blocks until all outstanding // requests on this server have completed.
func (s *Server) Close()
// Close shuts down the server and blocks until all outstanding // requests on this server have completed. func (s *Server) Close()
{ s.mu.Lock() if !s.closed { s.closed = true s.Listener.Close() s.Config.SetKeepAlivesEnabled(false) for c, st := range s.conns { // Force-close any idle connections (those between // requests) and new connections (those which connected // but never sent a request). StateNew connections are // su...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L224-L249
go
train
// CloseClientConnections closes any open HTTP connections to the test Server.
func (s *Server) CloseClientConnections()
// CloseClientConnections closes any open HTTP connections to the test Server. func (s *Server) CloseClientConnections()
{ s.mu.Lock() nconn := len(s.conns) ch := make(chan struct{}, nconn) for c := range s.conns { go s.closeConnChan(c, ch) } s.mu.Unlock() // Wait for outstanding closes to finish. // // Out of paranoia for making a late change in Go 1.6, we // bound how long this can wait, since golang.org/issue/14291 // i...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L274-L320
go
train
// wrap installs the connection state-tracking hook to know which // connections are idle.
func (s *Server) wrap()
// wrap installs the connection state-tracking hook to know which // connections are idle. func (s *Server) wrap()
{ oldHook := s.Config.ConnState s.Config.ConnState = func(c net.Conn, cs http.ConnState) { s.mu.Lock() defer s.mu.Unlock() switch cs { case http.StateNew: s.wg.Add(1) if _, exists := s.conns[c]; exists { panic("invalid state transition") } if s.conns == nil { s.conns = make(map[net.Conn]h...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L328-L333
go
train
// closeConnChan is like closeConn, but takes an optional channel to receive a value // when the goroutine closing c is done.
func (s *Server) closeConnChan(c net.Conn, done chan<- struct{})
// closeConnChan is like closeConn, but takes an optional channel to receive a value // when the goroutine closing c is done. func (s *Server) closeConnChan(c net.Conn, done chan<- struct{})
{ c.Close() if done != nil { done <- struct{}{} } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/internal/server.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/internal/server.go#L338-L343
go
train
// forgetConn removes c from the set of tracked conns and decrements it from the // waitgroup, unless it was previously removed. // s.mu must be held.
func (s *Server) forgetConn(c net.Conn)
// forgetConn removes c from the set of tracked conns and decrements it from the // waitgroup, unless it was previously removed. // s.mu must be held. func (s *Server) forgetConn(c net.Conn)
{ if _, ok := s.conns[c]; ok { delete(s.conns, c) s.wg.Done() } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/property_filter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/property_filter.go#L49-L86
go
train
// matches returns true if the change matches one of the filter Spec.PropSet
func (f *PropertyFilter) matches(ctx *Context, ref types.ManagedObjectReference, change *types.PropertyChange) bool
// matches returns true if the change matches one of the filter Spec.PropSet func (f *PropertyFilter) matches(ctx *Context, ref types.ManagedObjectReference, change *types.PropertyChange) bool
{ var kind reflect.Type for _, p := range f.Spec.PropSet { if p.Type != ref.Type { if kind == nil { kind = getManagedObject(ctx.Map.Get(ref)).Type() } // e.g. ManagedEntity, ComputeResource field, ok := kind.FieldByName(p.Type) if !(ok && field.Anonymous) { continue } } if isTrue(p....
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/property_filter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/property_filter.go#L89-L108
go
train
// apply the PropertyFilter.Spec to the given ObjectUpdate
func (f *PropertyFilter) apply(ctx *Context, change types.ObjectUpdate) types.ObjectUpdate
// apply the PropertyFilter.Spec to the given ObjectUpdate func (f *PropertyFilter) apply(ctx *Context, change types.ObjectUpdate) types.ObjectUpdate
{ parents := make(map[string]bool) set := change.ChangeSet change.ChangeSet = nil for i, p := range set { if f.matches(ctx, change.Obj, &p) { if p.Name != set[i].Name { // update matches a parent field from the spec. if parents[p.Name] { continue // only return 1 instance of the parent } ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/network.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/network.go#L38-L56
go
train
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n Network) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network func (n Network) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
{ var e mo.Network // Use Network.Name rather than Common.Name as the latter does not return the complete name if it contains a '/' // We can't use Common.ObjectName here either as we need the ManagedEntity.Name field is not set since mo.Network // has its own Name field. err := n.Properties(ctx, n.Reference(), ...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/typeinfo.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/typeinfo.go#L52-L112
go
train
// getTypeInfo returns the typeInfo structure with details necessary // for marshalling and unmarshalling typ.
func getTypeInfo(typ reflect.Type) (*typeInfo, error)
// getTypeInfo returns the typeInfo structure with details necessary // for marshalling and unmarshalling typ. func getTypeInfo(typ reflect.Type) (*typeInfo, error)
{ tinfoLock.RLock() tinfo, ok := tinfoMap[typ] tinfoLock.RUnlock() if ok { return tinfo, nil } tinfo = &typeInfo{} if typ.Kind() == reflect.Struct && typ != nameType { n := typ.NumField() for i := 0; i < n; i++ { f := typ.Field(i) if f.PkgPath != "" || f.Tag.Get("xml") == "-" { continue // Priva...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/typeinfo.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/typeinfo.go#L115-L228
go
train
// structFieldInfo builds and returns a fieldInfo for f.
func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, error)
// structFieldInfo builds and returns a fieldInfo for f. func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, error)
{ finfo := &fieldInfo{idx: f.Index} // Split the tag from the xml namespace if necessary. tag := f.Tag.Get("xml") if i := strings.Index(tag, " "); i >= 0 { finfo.xmlns, tag = tag[:i], tag[i+1:] } // Parse flags. tokens := strings.Split(tag, ",") if len(tokens) == 1 { finfo.flags = fElement } else { ta...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/typeinfo.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/typeinfo.go#L233-L254
go
train
// lookupXMLName returns the fieldInfo for typ's XMLName field // in case it exists and has a valid xml field tag, otherwise // it returns nil.
func lookupXMLName(typ reflect.Type) (xmlname *fieldInfo)
// lookupXMLName returns the fieldInfo for typ's XMLName field // in case it exists and has a valid xml field tag, otherwise // it returns nil. func lookupXMLName(typ reflect.Type) (xmlname *fieldInfo)
{ for typ.Kind() == reflect.Ptr { typ = typ.Elem() } if typ.Kind() != reflect.Struct { return nil } for i, n := 0, typ.NumField(); i < n; i++ { f := typ.Field(i) if f.Name != "XMLName" { continue } finfo, err := structFieldInfo(typ, &f) if finfo.name != "" && err == nil { return finfo } //...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/typeinfo.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/typeinfo.go#L270-L335
go
train
// addFieldInfo adds finfo to tinfo.fields if there are no // conflicts, or if conflicts arise from previous fields that were // obtained from deeper embedded structures than finfo. In the latter // case, the conflicting entries are dropped. // A conflict occurs when the path (parent + name) to a field is // itself a p...
func addFieldInfo(typ reflect.Type, tinfo *typeInfo, newf *fieldInfo) error
// addFieldInfo adds finfo to tinfo.fields if there are no // conflicts, or if conflicts arise from previous fields that were // obtained from deeper embedded structures than finfo. In the latter // case, the conflicting entries are dropped. // A conflict occurs when the path (parent + name) to a field is // itself a p...
{ var conflicts []int Loop: // First, figure all conflicts. Most working code will have none. for i := range tinfo.fields { oldf := &tinfo.fields[i] if oldf.flags&fMode != newf.flags&fMode { continue } if oldf.xmlns != "" && newf.xmlns != "" && oldf.xmlns != newf.xmlns { continue } minl := min(len...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/typeinfo.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/typeinfo.go#L352-L366
go
train
// value returns v's field value corresponding to finfo. // It's equivalent to v.FieldByIndex(finfo.idx), but initializes // and dereferences pointers as necessary.
func (finfo *fieldInfo) value(v reflect.Value) reflect.Value
// value returns v's field value corresponding to finfo. // It's equivalent to v.FieldByIndex(finfo.idx), but initializes // and dereferences pointers as necessary. func (finfo *fieldInfo) value(v reflect.Value) reflect.Value
{ for i, x := range finfo.idx { if i > 0 { t := v.Type() if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct { if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } v = v.Elem() } } v = v.Field(x) } return v }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_file.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_file.go#L42-L46
go
train
// ListLibraryItemFiles returns a list of all the files for a library item.
func (c *Manager) ListLibraryItemFiles(ctx context.Context, id string) ([]File, error)
// ListLibraryItemFiles returns a list of all the files for a library item. func (c *Manager) ListLibraryItemFiles(ctx context.Context, id string) ([]File, error)
{ url := internal.URL(c, internal.LibraryItemFilePath).WithParameter("library_item_id", id) var res []File return res, c.Do(ctx, url.Request(http.MethodGet), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_file.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_file.go#L49-L56
go
train
// GetLibraryItemFile returns a file with the provided name for a library item.
func (c *Manager) GetLibraryItemFile(ctx context.Context, id, fileName string) (*File, error)
// GetLibraryItemFile returns a file with the provided name for a library item. func (c *Manager) GetLibraryItemFile(ctx context.Context, id, fileName string) (*File, error)
{ url := internal.URL(c, internal.LibraryItemFilePath).WithID(id).WithAction("get") spec := struct { Name string `json:"name"` }{fileName} var res File return &res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
nfc/lease_updater.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/nfc/lease_updater.go#L51-L57
go
train
// File converts the FileItem.OvfFileItem to an OvfFile
func (o FileItem) File() types.OvfFile
// 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, } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/datastore/ls.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/datastore/ls.go#L233-L248
go
train
// hasMultiplePaths returns whether or not the slice of search results contains // results from more than one folder path.
func (o *listOutput) hasMultiplePaths() bool
// hasMultiplePaths returns whether or not the slice of search results contains // results from more than one folder path. func (o *listOutput) hasMultiplePaths() bool
{ if len(o.rs) == 0 { return false } p := o.rs[0].FolderPath // Multiple paths if any entry is not equal to the first one. for _, e := range o.rs { if e.FolderPath != p { return true } } return false }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/tags/categories.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L48-L64
go
train
// Patch merges Category changes from the given src. // AssociableTypes can only be appended to and cannot shrink.
func (c *Category) Patch(src *Category)
// Patch merges Category changes from the given src. // AssociableTypes can only be appended to and cannot shrink. func (c *Category) Patch(src *Category)
{ if src.Name != "" { c.Name = src.Name } if src.Description != "" { c.Description = src.Description } if src.Cardinality != "" { c.Cardinality = src.Cardinality } // Note that in order to append to AssociableTypes any existing types must be included in their original order. for _, kind := range src.Asso...
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/tags/categories.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L67-L93
go
train
// CreateCategory creates a new category and returns the category ID.
func (c *Manager) CreateCategory(ctx context.Context, category *Category) (string, error)
// CreateCategory creates a new category and returns the category ID. func (c *Manager) CreateCategory(ctx context.Context, category *Category) (string, error)
{ // create avoids the annoyance of CreateTag requiring field keys to be included in the request, // even though the field value can be empty. type create struct { Name string `json:"name"` Description string `json:"description"` Cardinality string `json:"cardinality"` AssociableTyp...