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.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() }
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) default: err := binary.Write(buf, binary.LittleEndian, p) if err != nil { return nil, ProtocolError(err) } } } return buf.Bytes(), nil }
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(err) } } } return nil }
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, DelayJitter: 0, MethodDelay: nil, }, } }
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 "Datastore": count.Datastore++ case "HostSystem": count.Host++ case "VirtualMachine": count.Machine++ case "ResourcePool": count.Pool++ case "VirtualApp": count.App++ case "Folder": count.Folder++ case "StoragePod": count.Pod++ } } return count }
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.HostSystem) // We need to defer VM creation until after the datastores are created. var vms []func() error // 1 DVS per DC, added to all hosts var dvs *object.DistributedVirtualSwitch // 1 NIC per VM, backed by a DVPG if Model.Portgroup > 0 vmnet := esx.EthernetCard.Backing // addHost adds a cluster host or a stanalone host. addHost := func(name string, f func(types.HostConnectSpec) (*object.Task, error)) (*object.HostSystem, error) { spec := types.HostConnectSpec{ HostName: name, } task, err := f(spec) if err != nil { return nil, err } info, err := task.WaitForResult(context.Background(), nil) if err != nil { return nil, err } host := object.NewHostSystem(client, info.Result.(types.ManagedObjectReference)) hosts = append(hosts, host) if dvs != nil { config := &types.DVSConfigSpec{ Host: []types.DistributedVirtualSwitchHostMemberConfigSpec{{ Operation: string(types.ConfigSpecOperationAdd), Host: host.Reference(), }}, } _, _ = dvs.Reconfigure(ctx, config) } return host, nil } // addMachine returns a func to create a VM. addMachine := func(prefix string, host *object.HostSystem, pool *object.ResourcePool, folders *object.DatacenterFolders) { nic := esx.EthernetCard nic.Backing = vmnet ds := types.ManagedObjectReference{} f := func() error { for i := 0; i < m.Machine; i++ { name := m.fmtName(prefix+"_VM", i) config := types.VirtualMachineConfigSpec{ Name: name, GuestId: string(types.VirtualMachineGuestOsIdentifierOtherGuest), Files: &types.VirtualMachineFileInfo{ VmPathName: "[LocalDS_0]", }, } if pool == nil { pool, _ = host.ResourcePool(ctx) } var devices object.VirtualDeviceList scsi, _ := devices.CreateSCSIController("pvscsi") ide, _ := devices.CreateIDEController() cdrom, _ := devices.CreateCdrom(ide.(*types.VirtualIDEController)) disk := devices.CreateDisk(scsi.(types.BaseVirtualController), ds, config.Files.VmPathName+" "+path.Join(name, "disk1.vmdk")) disk.CapacityInKB = 1024 devices = append(devices, scsi, cdrom, disk, &nic) config.DeviceChange, _ = devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd) task, err := folders.VmFolder.CreateVM(ctx, config, pool, host) if err != nil { return err } info, err := task.WaitForResult(ctx, nil) if err != nil { return err } vm := object.NewVirtualMachine(client, info.Result.(types.ManagedObjectReference)) if m.Autostart { _, _ = vm.PowerOn(ctx) } } return nil } vms = append(vms, f) } nfolder := 0 for ndc := 0; ndc < m.Datacenter; ndc++ { dcName := m.fmtName("DC", ndc) folder := root fName := m.fmtName("F", nfolder) // If Datacenter > Folder, don't create folders for the first N DCs. if nfolder < m.Folder && ndc >= (m.Datacenter-m.Folder) { f, err := folder.CreateFolder(ctx, fName) if err != nil { return err } folder = f } dc, err := folder.CreateDatacenter(ctx, dcName) if err != nil { return err } folders, err := dc.Folders(ctx) if err != nil { return err } if m.Pod > 0 { for pod := 0; pod < m.Pod; pod++ { _, _ = folders.DatastoreFolder.CreateStoragePod(ctx, m.fmtName(dcName+"_POD", pod)) } } if folder != root { // Create sub-folders and use them to create any resources that follow subs := []**object.Folder{&folders.DatastoreFolder, &folders.HostFolder, &folders.NetworkFolder, &folders.VmFolder} for _, sub := range subs { f, err := (*sub).CreateFolder(ctx, fName) if err != nil { return err } *sub = f } nfolder++ } if m.Portgroup > 0 { var spec types.DVSCreateSpec spec.ConfigSpec = &types.VMwareDVSConfigSpec{} spec.ConfigSpec.GetDVSConfigSpec().Name = m.fmtName("DVS", 0) task, err := folders.NetworkFolder.CreateDVS(ctx, spec) if err != nil { return err } info, err := task.WaitForResult(ctx, nil) if err != nil { return err } dvs = object.NewDistributedVirtualSwitch(client, info.Result.(types.ManagedObjectReference)) for npg := 0; npg < m.Portgroup; npg++ { name := m.fmtName(dcName+"_DVPG", npg) task, err = dvs.AddPortgroup(ctx, []types.DVPortgroupConfigSpec{{Name: name}}) if err != nil { return err } err = task.Wait(ctx) if err != nil { return err } // Use the 1st DVPG for the VMs eth0 backing if npg == 0 { // AddPortgroup_Task does not return the moid, so we look it up by name net := Map.Get(folders.NetworkFolder.Reference()).(*Folder) pg := Map.FindByName(name, net.ChildEntity) vmnet, _ = object.NewDistributedVirtualPortgroup(client, pg.Reference()).EthernetCardBackingInfo(ctx) } } } for nhost := 0; nhost < m.Host; nhost++ { name := m.fmtName(dcName+"_H", nhost) host, err := addHost(name, func(spec types.HostConnectSpec) (*object.Task, error) { return folders.HostFolder.AddStandaloneHost(ctx, spec, true, nil, nil) }) if err != nil { return err } addMachine(name, host, nil, folders) } for ncluster := 0; ncluster < m.Cluster; ncluster++ { clusterName := m.fmtName(dcName+"_C", ncluster) cluster, err := folders.HostFolder.CreateCluster(ctx, clusterName, types.ClusterConfigSpecEx{}) if err != nil { return err } for nhost := 0; nhost < m.ClusterHost; nhost++ { name := m.fmtName(clusterName+"_H", nhost) _, err = addHost(name, func(spec types.HostConnectSpec) (*object.Task, error) { return cluster.AddHost(ctx, spec, true, nil, nil) }) if err != nil { return err } } pool, err := cluster.ResourcePool(ctx) if err != nil { return err } prefix := clusterName + "_RP" addMachine(prefix+"0", nil, pool, folders) for npool := 1; npool <= m.Pool; npool++ { spec := types.DefaultResourceConfigSpec() _, err = pool.Create(ctx, m.fmtName(prefix, npool), spec) if err != nil { return err } } prefix = clusterName + "_APP" for napp := 0; napp < m.App; napp++ { rspec := types.DefaultResourceConfigSpec() vspec := NewVAppConfigSpec() name := m.fmtName(prefix, napp) vapp, err := pool.CreateVApp(ctx, name, rspec, vspec, nil) if err != nil { return err } addMachine(name, nil, vapp.ResourcePool, folders) } } hostMap[dcName] = hosts hosts = nil } if m.ServiceContent.RootFolder == esx.RootFolder.Reference() { // ESX model host := object.NewHostSystem(client, esx.HostSystem.Reference()) dc := object.NewDatacenter(client, esx.Datacenter.Reference()) folders, err := dc.Folders(ctx) if err != nil { return err } hostMap[dc.Reference().Value] = append(hosts, host) addMachine(host.Reference().Value, host, nil, folders) } for dc, dchosts := range hostMap { for i := 0; i < m.Datastore; i++ { err := m.createLocalDatastore(dc, m.fmtName("LocalDS_", i), dchosts) if err != nil { return err } } } for _, createVM := range vms { err := createVM() if err != nil { return err } } // Turn on delay AFTER we're done building the service content m.Service.delay = &m.DelayConfig return nil }
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.VirtualMachine, error)
{ 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 = append(out, vms...) } return out, nil }
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 false, 0 } if !nerr.Temporary() { return false, 0 } // Don't retry if we're out of tries. if n--; n <= 0 { return false, 0 } return true, 0 } }
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(roundTripper soap.RoundTripper, fn RetryFunc) soap.RoundTripper
{ 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.Start += int32(len(h.LineText)) if l.Start >= h.LineEnd { break } } return written, nil }
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 _ = binary.Write(buf, binary.LittleEndian, p.data.Int32) case vixPropertyTypeInt64: // #nosec: Errors unhandled _ = binary.Write(buf, binary.LittleEndian, p.data.Int64) case vixPropertyTypeString: // #nosec: Errors unhandled _, _ = buf.WriteString(p.data.String) // #nosec: Errors unhandled _ = buf.WriteByte(0) case vixPropertyTypeBlob: // #nosec: Errors unhandled _, _ = buf.Write(p.data.Blob) } return buf.Bytes(), nil }
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.Int32) case vixPropertyTypeInt64: return binary.Read(buf, binary.LittleEndian, &p.data.Int64) case vixPropertyTypeString: s := make([]byte, p.header.Length) if _, err := buf.Read(s); err != nil { return err } p.data.String = string(bytes.TrimRight(s, "\x00")) case vixPropertyTypeBlob: p.data.Blob = make([]byte, p.header.Length) if _, err := buf.Read(p.data.Blob); err != nil { return err } default: return errors.New("VIX_E_UNRECOGNIZED_PROPERTY") } return nil }
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 := 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 f, ok := err.(types.HasFault); ok { if _, ok = f.Fault().(*types.InvalidPowerState); !ok { return nil, err } } } } return nil, nil }
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 NewReference(s.c, *res.Returnval), nil }
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 { 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#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) } // handle the signals and gracefully shutdown the service sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) go func() { log.Printf("signal %s received", <-sig) service.Stop() }() service.Wait() }
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 := flag.SetRootCAs(sc); err != nil { return nil, err } if err := sc.LoadThumbprints(flag.tlsKnownHosts); err != nil { return nil, err } if t, ok := sc.Transport.(*http.Transport); ok { var err error value := os.Getenv("GOVC_TLS_HANDSHAKE_TIMEOUT") if value != "" { t.TLSHandshakeTimeout, err = time.ParseDuration(value) if err != nil { return nil, err } } } // Retry twice when a temporary I/O error occurs. // This means a maximum of 3 attempts. return vim25.Retry(sc, vim25.TemporaryNetworkError(3)), nil }
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) } minVersion, err := ParseVersion(minVersionString) if err != nil { return fmt.Errorf("error parsing %s=%q: %s", envMinAPIVersion, minVersionString, err) } if !minVersion.Lte(realVersion) { err = fmt.Errorf("require API version %q, connected to API version %q (set %s to override)", minVersionString, c.ServiceContent.About.ApiVersion, envMinAPIVersion) return err } return nil }
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 = "" u.RawQuery = "" add(envURL, strings.TrimPrefix(u.String(), "https://")) keys := []string{ envCertificate, envPrivateKey, envInsecure, envPersist, envMinAPIVersion, envVimNamespace, envVimVersion, } for _, k := range keys { if v := os.Getenv(k); v != "" { add(k, v) } } if extra { add("GOVC_URL_SCHEME", flag.url.Scheme) v := strings.SplitN(u.Host, ":", 2) add("GOVC_URL_HOST", v[0]) if len(v) == 2 { add("GOVC_URL_PORT", v[1]) } add("GOVC_URL_PATH", flag.url.Path) if f := flag.url.Fragment; f != "" { add("GOVC_URL_FRAGMENT", f) } if q := flag.url.RawQuery; q != "" { add("GOVC_URL_QUERY", q) } } return env }
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: } return werr }
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 = host.Name cr.Host = append(cr.Host, host.Reference()) host.Network = cr.Network Map.PutEntity(cr, host) pool := NewResourcePool() cr.ResourcePool = &pool.Self Map.PutEntity(cr, pool) pool.Owner = cr.Self Map.Get(dc.HostFolder).(*Folder).putChild(cr) }
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.ComputeResourceSummary) addComputeResource(summary, host) cr := &mo.ComputeResource{ ConfigurationEx: &types.ComputeResourceConfigInfo{ VmSwapPlacement: string(types.VirtualMachineConfigInfoSwapPlacementTypeVmDirectory), }, Summary: summary, EnvironmentBrowser: newEnvironmentBrowser(), } Map.PutEntity(cr, Map.NewEntity(host)) host.Summary.Host = &host.Self Map.PutEntity(cr, Map.NewEntity(pool)) cr.Name = host.Name cr.Network = Map.getEntityDatacenter(f).defaultNetwork() cr.Host = append(cr.Host, host.Reference()) cr.ResourcePool = &pool.Self f.putChild(cr) pool.Owner = cr.Self host.Network = cr.Network return host, nil }
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] if !ok { log.Printf("invalid NFC device id: %s", name) http.NotFound(w, r) return } status := http.StatusOK var dst io.Writer var src io.ReadCloser switch r.Method { case http.MethodPut, http.MethodPost: dst = ioutil.Discard src = r.Body case http.MethodGet: f, err := os.Open(file) if err != nil { http.NotFound(w, r) return } src = f default: status = http.StatusMethodNotAllowed } n, err := io.Copy(dst, src) _ = src.Close() msg := fmt.Sprintf("transferred %d bytes", n) if err != nil { status = http.StatusInternalServerError msg = err.Error() } log.Printf("nfc %s %s: %s", r.Method, file, msg) w.WriteHeader(status) }
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 own signature.
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 own signature. func (r *RequestSecurityToken) toString(c14n bool) string
{ 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/200802">%s</wst:ActAs>`, token) } body := []string{ fmt.Sprintf(`<RequestSecurityToken xmlns="http://docs.oasis-open.org/ws-sx/ws-trust/200512">`), fmt.Sprintf(`<TokenType>%s</TokenType>`, r.TokenType), fmt.Sprintf(`<RequestType>%s</RequestType>`, r.RequestType), r.Lifetime.C14N(), } if r.RenewTarget == nil { body = append(body, fmt.Sprintf(`<Renewing Allow="%t" OK="%t"></Renewing>`, r.Renewing.Allow, r.Renewing.OK), fmt.Sprintf(`<Delegatable>%t</Delegatable>`, r.Delegatable), actas, fmt.Sprintf(`<KeyType>%s</KeyType>`, r.KeyType), fmt.Sprintf(`<SignatureAlgorithm>%s</SignatureAlgorithm>`, r.SignatureAlgorithm), fmt.Sprintf(`<UseKey Sig="%s"></UseKey>`, r.UseKey.Sig)) } else { token := r.RenewTarget.Token if c14n { var a Assertion err := Unmarshal([]byte(r.RenewTarget.Token), &a) if err != nil { log.Printf("decode Renew: %s", err) } token = a.C14N() } body = append(body, fmt.Sprintf(`<UseKey Sig="%s"></UseKey>`, r.UseKey.Sig), fmt.Sprintf(`<RenewTarget>%s</RenewTarget>`, token)) } return strings.Join(append(body, `</RequestSecurityToken>`), "") }
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 = []string{"ManagedEntity"} } for _, t := range kind { spec := types.PropertySpec{ Type: t, } if len(ps) == 0 { spec.All = types.NewBool(true) } else { spec.PathSet = ps } pspec = append(pspec, spec) } req := types.RetrieveProperties{ SpecSet: []types.PropertyFilterSpec{ { ObjectSet: []types.ObjectSpec{ospec}, PropSet: pspec, }, }, } res, err := pc.RetrieveProperties(ctx, req) if err != nil { return err } if d, ok := dst.(*[]types.ObjectContent); ok { *d = res.Returnval return nil } return mo.LoadRetrievePropertiesResponse(res, dst) }
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, dst) }
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), nil }
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.Backing.(*types.VirtualDiskFlatVer2BackingInfo) diskLayout := &types.VirtualMachineFileLayoutDiskLayout{Key: disk.Key} diskLayoutEx := &types.VirtualMachineFileLayoutExDiskLayout{Key: disk.Key} // Iterate through disk and its parents for { dFileName := diskBacking.GetVirtualDeviceFileBackingInfo().FileName var fileKeys []int32 dm := Map.VirtualDiskManager() // Add disk descriptor and extent files for _, diskName := range dm.names(dFileName) { // get full path including datastore location p, fault := parseDatastorePath(diskName) if fault != nil { return fault } datastore := vm.useDatastore(p.Datastore) dFilePath := path.Join(datastore.Info.GetDatastoreInfo().Url, p.Path) var fileSize int64 // If file can not be opened - fileSize will be 0 if dFileInfo, err := os.Stat(dFilePath); err == nil { fileSize = dFileInfo.Size() } diskKey := vm.addFileLayoutEx(*p, fileSize) fileKeys = append(fileKeys, diskKey) } diskLayout.DiskFile = append(diskLayout.DiskFile, dFileName) diskLayoutEx.Chain = append(diskLayoutEx.Chain, types.VirtualMachineFileLayoutExDiskUnit{ FileKey: fileKeys, }) if parent := diskBacking.Parent; parent != nil { diskBacking = parent } else { break } } disksLayout = append(disksLayout, *diskLayout) disksLayoutEx = append(disksLayoutEx, *diskLayoutEx) } vm.Layout.Disk = disksLayout vm.LayoutEx.Disk = disksLayoutEx vm.LayoutEx.Timestamp = time.Now() vm.updateStorage() return nil }
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 virtual machine UUID is based on a hash calculated by using the UUID of the // ESXi physical machine and the path to the configuration file (.vmx) of the virtual machine."
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 virtual machine UUID is based on a hash calculated by using the UUID of the // ESXi physical machine and the path to the configuration file (.vmx) of the virtual machine." func (vm *VirtualMachine) generateMAC() string
{ 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("\r%s", p.prefix) p.flag.Log(line) } } if err != nil && err != io.EOF { p.flag.Log(fmt.Sprintf("\r%sError: %s\n", p.prefix, err)) } else if called { p.flag.Log(fmt.Sprintf("\r%sOK\n", p.prefix)) } }
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 != "" { line += fmt.Sprintf(", %s", detail) } line += ")" } p.flag.Log(line) } } return err }
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 properties, such as 'guest.ipAddress' or 'config.hardware'.
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 properties, such as 'guest.ipAddress' or 'config.hardware'. func ObjectContentToType(o types.ObjectContent) (interface{}, error)
{ // 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().Interface(), nil }
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 type") } if isSlice { for _, p := range res.Returnval { v, err := ObjectContentToType(p) if err != nil { return err } vt := reflect.TypeOf(v) if !rv.Type().AssignableTo(vt) { // For example: dst is []ManagedEntity, res is []HostSystem if field, ok := vt.FieldByName(rt.Elem().Elem().Name()); ok && field.Anonymous { rv.Set(reflect.Append(rv, reflect.ValueOf(v).FieldByIndex(field.Index))) continue } } rv.Set(reflect.Append(rv, reflect.ValueOf(v))) } } else { switch len(res.Returnval) { case 0: case 1: v, err := ObjectContentToType(res.Returnval[0]) if err != nil { return err } vt := reflect.TypeOf(v) if !rv.Type().AssignableTo(vt) { // For example: dst is ComputeResource, res is ClusterComputeResource if field, ok := vt.FieldByName(rt.Elem().Name()); ok && field.Anonymous { rv.Set(reflect.ValueOf(v).FieldByIndex(field.Index)) return nil } } rv.Set(reflect.ValueOf(v)) default: // If dst is not a slice, expect to receive 0 or 1 results panic("more than 1 result") } } return nil }
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, }, }, }, }, } return RetrievePropertiesForRequest(ctx, r, req, dst) }
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){ OpCreateSessionV4: s.CreateSessionV4, OpDestroySessionV4: s.DestroySessionV4, OpGetattrV2: s.GetattrV2, OpSetattrV2: s.SetattrV2, OpOpen: s.Open, OpClose: s.Close, OpOpenV3: s.OpenV3, OpReadV3: s.ReadV3, OpWriteV3: s.WriteV3, } for op := range s.handlers { s.Capabilities = append(s.Capabilities, Capability{Op: op, Flags: 0x1}) } return s }
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: StatusOperationNotSupported, Err: fmt.Errorf("unsupported Op(%d)", req.Op), } } return req.Reply(res, err) }
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 hgfs errors if err != nil { u = &url.URL{Path: name} } if u.Scheme == "" { ix := strings.Index(u.Path, "/") if ix > 0 { u.Scheme = u.Path[:ix] u.Path = u.Path[ix:] } } return u }
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.OpenFile(name, flag, 0600) default: return nil, &Status{ Err: fmt.Errorf("open mode(%d) not supported for file %q", mode, name), Code: StatusAccessDenied, } } }
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 only concerned with: // - does the file exist? // - size: // + used for UI progress with desktop Drag-N-Drop operations, which toolbox does not support. // + sent to as Content-Length header in response to GET of FileTransferInformation.Url, // if the first ReadV3 size is > HGFS_LARGE_PACKET_MAX
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 only concerned with: // - does the file exist? // - size: // + used for UI progress with desktop Drag-N-Drop operations, which toolbox does not support. // + sent to as Content-Length header in response to GET of FileTransferInformation.Url, // if the first ReadV3 size is > HGFS_LARGE_PACKET_MAX func (s *Server) Stat(name string) (os.FileInfo, error)
{ 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: SessionMaxPacketSizeValid, Capabilities: s.Capabilities, } s.mu.Lock() defer s.mu.Unlock() if len(s.sessions) > maxSessions { return nil, &Status{Code: StatusTooManySessions} } s.sessions[res.SessionID] = newSession() return res, nil }
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&AttrValidUserID == AttrValidUserID { uid = int(req.Attr.UserID) } gid := -1 if req.Attr.Mask&AttrValidGroupID == AttrValidGroupID { gid = int(req.Attr.GroupID) } err = s.chown(name, uid, gid) if err != nil { return nil, err } var perm os.FileMode if req.Attr.Mask&AttrValidOwnerPerms == AttrValidOwnerPerms { perm |= os.FileMode(req.Attr.OwnerPerms) << 6 } if req.Attr.Mask&AttrValidGroupPerms == AttrValidGroupPerms { perm |= os.FileMode(req.Attr.GroupPerms) << 3 } if req.Attr.Mask&AttrValidOtherPerms == AttrValidOtherPerms { perm |= os.FileMode(req.Attr.OtherPerms) } if perm != 0 { err = s.chmod(name, perm) if err != nil { return nil, err } } return res, nil }
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) not supported for file %q", mode, name), Code: StatusAccessDenied, } } file, err := s.OpenFile(name, mode) if err != nil { return nil, err } res := &ReplyOpen{ Handle: s.newHandle(), } session.mu.Lock() session.files[res.Handle] = file session.mu.Unlock() return res, nil }
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 { err = file.Close() } else { return nil, &Status{Code: StatusInvalidHandle} } return &ReplyClose{}, err }
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 for file %q", req.DesiredLock, name), Code: StatusOperationNotSupported, } } file, err := s.OpenFile(name, req.OpenMode) if err != nil { return nil, err } res := &ReplyOpenV3{ Handle: s.newHandle(), } session.mu.Lock() session.files[res.Handle] = file session.mu.Unlock() return res, nil }
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} } buf := make([]byte, req.RequiredSize) // Use ReadFull as Read() of an archive io.Pipe may return much smaller chunks, // such as when we've read a tar header. n, err := io.ReadFull(file, buf) if err != nil && n == 0 { if err != io.EOF { return nil, err } } res := &ReplyReadV3{ ActualSize: uint32(n), Payload: buf[:n], } return res, nil }
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} } n, err := file.Write(req.Payload) if err != nil { return nil, err } res := &ReplyWriteV3{ ActualSize: uint32(n), } return res, nil }
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.Handler, serve string) *Server
{ 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 != nil { s.TLS = existingConfig.Clone() } else { s.TLS = new(tls.Config) } if s.TLS.NextProtos == nil { s.TLS.NextProtos = []string{"http/1.1"} } if len(s.TLS.Certificates) == 0 { s.TLS.Certificates = []tls.Certificate{cert} } s.certificate, err = x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0]) if err != nil { panic(fmt.Sprintf("httptest: NewTLSServer: %v", err)) } certpool := x509.NewCertPool() certpool.AddCert(s.certificate) s.client.Transport = &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: certpool, }, } s.Listener = tls.NewListener(s.Listener, s.TLS) s.URL = "https://" + 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#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 // super rare and have only been seen (in // previously-flaky tests) in the case of // socket-late-binding races from the http Client // dialing this server and then getting an idle // connection before the dial completed. There is thus // a connected connection in StateNew with no // associated Request. We only close StateIdle and // StateNew because they're not doing anything. It's // possible StateNew is about to do something in a few // milliseconds, but a previous CL to check again in a // few milliseconds wasn't liked (early versions of // https://golang.org/cl/15151) so now we just // forcefully close StateNew. The docs for Server.Close say // we wait for "outstanding requests", so we don't close things // in StateActive. if st == http.StateIdle || st == http.StateNew { s.closeConn(c) } } // If this server doesn't shut down in 5 seconds, tell the user why. t := time.AfterFunc(5*time.Second, s.logCloseHangDebugInfo) defer t.Stop() } s.mu.Unlock() // Not part of httptest.Server's correctness, but assume most // users of httptest.Server will be using the standard // transport, so help them out and close any idle connections for them. if t, ok := http.DefaultTransport.(closeIdleTransport); ok { t.CloseIdleConnections() } // Also close the client idle connections. if s.client != nil { if t, ok := s.client.Transport.(closeIdleTransport); ok { t.CloseIdleConnections() } } s.wg.Wait() }
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 // isn't fully understood yet. At least this should only be used // in tests. timer := time.NewTimer(5 * time.Second) defer timer.Stop() for i := 0; i < nconn; i++ { select { case <-ch: case <-timer.C: // Too slow. Give up. return } } }
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]http.ConnState) } s.conns[c] = cs if s.closed { // Probably just a socket-late-binding dial from // the default transport that lost the race (and // thus this connection is now idle and will // never be used). s.closeConn(c) } case http.StateActive: if oldState, ok := s.conns[c]; ok { if oldState != http.StateNew && oldState != http.StateIdle { panic("invalid state transition") } s.conns[c] = cs } case http.StateIdle: if oldState, ok := s.conns[c]; ok { if oldState != http.StateActive { panic("invalid state transition") } s.conns[c] = cs } if s.closed { s.closeConn(c) } case http.StateHijacked, http.StateClosed: s.forgetConn(c) } if oldHook != nil { oldHook(c, cs) } } }
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.All) { return true } for _, name := range p.PathSet { if name == change.Name { return true } // strings.HasPrefix("runtime.powerState", "runtime") == parent field matches if strings.HasPrefix(change.Name, name) { if obj := ctx.Map.Get(ref); obj != nil { // object may have since been deleted change.Name = name change.Val, _ = fieldValue(reflect.ValueOf(obj), name) } return true } } } return false }
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 } parents[p.Name] = true } change.ChangeSet = append(change.ChangeSet, p) } } return change }
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(), []string{"name"}, &e) if err != nil { return nil, err } backing := &types.VirtualEthernetCardNetworkBackingInfo{ VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{ DeviceName: e.Name, }, } return backing, nil }
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 // Private field } // For embedded structs, embed its fields. if f.Anonymous { t := f.Type if t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() == reflect.Struct { inner, err := getTypeInfo(t) if err != nil { return nil, err } if tinfo.xmlname == nil { tinfo.xmlname = inner.xmlname } for _, finfo := range inner.fields { finfo.idx = append([]int{i}, finfo.idx...) if err := addFieldInfo(typ, tinfo, &finfo); err != nil { return nil, err } } continue } } finfo, err := structFieldInfo(typ, &f) if err != nil { return nil, err } if f.Name == "XMLName" { tinfo.xmlname = finfo continue } // Add the field if it doesn't conflict with other fields. if err := addFieldInfo(typ, tinfo, finfo); err != nil { return nil, err } } } tinfoLock.Lock() tinfoMap[typ] = tinfo tinfoLock.Unlock() return tinfo, nil }
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 { tag = tokens[0] for _, flag := range tokens[1:] { switch flag { case "attr": finfo.flags |= fAttr case "chardata": finfo.flags |= fCharData case "innerxml": finfo.flags |= fInnerXml case "comment": finfo.flags |= fComment case "any": finfo.flags |= fAny case "omitempty": finfo.flags |= fOmitEmpty case "typeattr": finfo.flags |= fTypeAttr } } // Validate the flags used. valid := true switch mode := finfo.flags & fMode; mode { case 0: finfo.flags |= fElement case fAttr, fCharData, fInnerXml, fComment, fAny: if f.Name == "XMLName" || tag != "" && mode != fAttr { valid = false } default: // This will also catch multiple modes in a single field. valid = false } if finfo.flags&fMode == fAny { finfo.flags |= fElement } if finfo.flags&fOmitEmpty != 0 && finfo.flags&(fElement|fAttr) == 0 { valid = false } if !valid { return nil, fmt.Errorf("xml: invalid tag in field %s of type %s: %q", f.Name, typ, f.Tag.Get("xml")) } } // Use of xmlns without a name is not allowed. if finfo.xmlns != "" && tag == "" { return nil, fmt.Errorf("xml: namespace without name in field %s of type %s: %q", f.Name, typ, f.Tag.Get("xml")) } if f.Name == "XMLName" { // The XMLName field records the XML element name. Don't // process it as usual because its name should default to // empty rather than to the field name. finfo.name = tag return finfo, nil } if tag == "" { // If the name part of the tag is completely empty, get // default from XMLName of underlying struct if feasible, // or field name otherwise. if xmlname := lookupXMLName(f.Type); xmlname != nil { finfo.xmlns, finfo.name = xmlname.xmlns, xmlname.name } else { finfo.name = f.Name } return finfo, nil } // Prepare field name and parents. parents := strings.Split(tag, ">") if parents[0] == "" { parents[0] = f.Name } if parents[len(parents)-1] == "" { return nil, fmt.Errorf("xml: trailing '>' in field %s of type %s", f.Name, typ) } finfo.name = parents[len(parents)-1] if len(parents) > 1 { if (finfo.flags & fElement) == 0 { return nil, fmt.Errorf("xml: %s chain not valid with %s flag", tag, strings.Join(tokens[1:], ",")) } finfo.parents = parents[:len(parents)-1] } // If the field type has an XMLName field, the names must match // so that the behavior of both marshalling and unmarshalling // is straightforward and unambiguous. if finfo.flags&fElement != 0 { ftyp := f.Type xmlname := lookupXMLName(ftyp) if xmlname != nil && xmlname.name != finfo.name { return nil, fmt.Errorf("xml: name %q in tag of %s.%s conflicts with name %q in %s.XMLName", finfo.name, typ, f.Name, xmlname.name, ftyp) } } return finfo, nil }
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 } // Also consider errors as a non-existent field tag // and let getTypeInfo itself report the error. break } return nil }
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 prefix of another path, or when two paths match exactly. // It is okay for field paths to share a common, shorter prefix.
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 prefix of another path, or when two paths match exactly. // It is okay for field paths to share a common, shorter prefix. func addFieldInfo(typ reflect.Type, tinfo *typeInfo, newf *fieldInfo) error
{ 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(newf.parents), len(oldf.parents)) for p := 0; p < minl; p++ { if oldf.parents[p] != newf.parents[p] { continue Loop } } if len(oldf.parents) > len(newf.parents) { if oldf.parents[len(newf.parents)] == newf.name { conflicts = append(conflicts, i) } } else if len(oldf.parents) < len(newf.parents) { if newf.parents[len(oldf.parents)] == oldf.name { conflicts = append(conflicts, i) } } else { if newf.name == oldf.name { conflicts = append(conflicts, i) } } } // Without conflicts, add the new field and return. if conflicts == nil { tinfo.fields = append(tinfo.fields, *newf) return nil } // If any conflict is shallower, ignore the new field. // This matches the Go field resolution on embedding. for _, i := range conflicts { if len(tinfo.fields[i].idx) < len(newf.idx) { return nil } } // Otherwise, if any of them is at the same depth level, it's an error. for _, i := range conflicts { oldf := &tinfo.fields[i] if len(oldf.idx) == len(newf.idx) { f1 := typ.FieldByIndex(oldf.idx) f2 := typ.FieldByIndex(newf.idx) return &TagPathError{typ, f1.Name, f1.Tag.Get("xml"), f2.Name, f2.Tag.Get("xml")} } } // Otherwise, the new field is shallower, and thus takes precedence, // so drop the conflicting fields from tinfo and append the new one. for c := len(conflicts) - 1; c >= 0; c-- { i := conflicts[c] copy(tinfo.fields[i:], tinfo.fields[i+1:]) tinfo.fields = tinfo.fields[:len(tinfo.fields)-1] } tinfo.fields = append(tinfo.fields, *newf) return nil }
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.AssociableTypes { if !c.hasType(kind) { c.AssociableTypes = append(c.AssociableTypes, kind) } } }
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"` AssociableTypes []string `json:"associable_types"` } spec := struct { Category create `json:"create_spec"` }{ Category: create{ Name: category.Name, Description: category.Description, Cardinality: category.Cardinality, AssociableTypes: category.AssociableTypes, }, } if spec.Category.AssociableTypes == nil { // otherwise create fails with invalid_argument spec.Category.AssociableTypes = []string{} } url := internal.URL(c, internal.CategoryPath) var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }