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/datastore_file_manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file_manager.go#L152-L162
|
go
|
train
|
// MoveFile calls FileManager.MoveDatastoreFile
|
func (m *DatastoreFileManager) MoveFile(ctx context.Context, src string, dst string) error
|
// MoveFile calls FileManager.MoveDatastoreFile
func (m *DatastoreFileManager) MoveFile(ctx context.Context, src string, dst string) error
|
{
srcp := m.Path(src)
dstp := m.Path(dst)
task, err := m.FileManager.MoveDatastoreFile(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file_manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file_manager.go#L165-L181
|
go
|
train
|
// Move dispatches to the appropriate FileManager or VirtualDiskManager Move method based on file name extension
|
func (m *DatastoreFileManager) Move(ctx context.Context, src string, dst string) error
|
// Move dispatches to the appropriate FileManager or VirtualDiskManager Move method based on file name extension
func (m *DatastoreFileManager) Move(ctx context.Context, src string, dst string) error
|
{
srcp := m.Path(src)
dstp := m.Path(dst)
f := m.FileManager.MoveDatastoreFile
if srcp.IsVMDK() {
f = m.VirtualDiskManager.MoveVirtualDisk
}
task, err := f(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
if err != nil {
return err
}
return m.wait(ctx, task)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file_manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file_manager.go#L184-L193
|
go
|
train
|
// Path converts path name to a DatastorePath
|
func (m *DatastoreFileManager) Path(name string) *DatastorePath
|
// Path converts path name to a DatastorePath
func (m *DatastoreFileManager) Path(name string) *DatastorePath
|
{
var p DatastorePath
if !p.FromString(name) {
p.Path = name
p.Datastore = m.Datastore.Name()
}
return &p
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
nfc/lease.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/nfc/lease.go#L45-L57
|
go
|
train
|
// Abort wraps methods.Abort
|
func (l *Lease) Abort(ctx context.Context, fault *types.LocalizedMethodFault) error
|
// Abort wraps methods.Abort
func (l *Lease) Abort(ctx context.Context, fault *types.LocalizedMethodFault) error
|
{
req := types.HttpNfcLeaseAbort{
This: l.Reference(),
Fault: fault,
}
_, err := methods.HttpNfcLeaseAbort(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
nfc/lease.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/nfc/lease.go#L60-L71
|
go
|
train
|
// Complete wraps methods.Complete
|
func (l *Lease) Complete(ctx context.Context) error
|
// Complete wraps methods.Complete
func (l *Lease) Complete(ctx context.Context) error
|
{
req := types.HttpNfcLeaseComplete{
This: l.Reference(),
}
_, err := methods.HttpNfcLeaseComplete(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
nfc/lease.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/nfc/lease.go#L74-L85
|
go
|
train
|
// GetManifest wraps methods.GetManifest
|
func (l *Lease) GetManifest(ctx context.Context) error
|
// GetManifest wraps methods.GetManifest
func (l *Lease) GetManifest(ctx context.Context) error
|
{
req := types.HttpNfcLeaseGetManifest{
This: l.Reference(),
}
_, err := methods.HttpNfcLeaseGetManifest(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
nfc/lease.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/nfc/lease.go#L88-L100
|
go
|
train
|
// Progress wraps methods.Progress
|
func (l *Lease) Progress(ctx context.Context, percent int32) error
|
// Progress wraps methods.Progress
func (l *Lease) Progress(ctx context.Context, percent int32) error
|
{
req := types.HttpNfcLeaseProgress{
This: l.Reference(),
Percent: percent,
}
_, err := methods.HttpNfcLeaseProgress(ctx, l.c, &req)
if err != nil {
return err
}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L45-L55
|
go
|
train
|
// Patch merges updates from the given src.
|
func (l *Library) Patch(src *Library)
|
// Patch merges updates from the given src.
func (l *Library) Patch(src *Library)
|
{
if src.Name != "" {
l.Name = src.Name
}
if src.Description != "" {
l.Description = src.Description
}
if src.Version != "" {
l.Version = src.Version
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L83-L90
|
go
|
train
|
// FindLibrary returns one or more libraries that match the provided search
// criteria.
//
// The provided name is case-insensitive.
//
// Either the name or type of library may be set to empty values in order
// to search for all libraries, all libraries with a specific name, regardless
// of type, or all libraries of a specified type.
|
func (c *Manager) FindLibrary(ctx context.Context, search Find) ([]string, error)
|
// FindLibrary returns one or more libraries that match the provided search
// criteria.
//
// The provided name is case-insensitive.
//
// Either the name or type of library may be set to empty values in order
// to search for all libraries, all libraries with a specific name, regardless
// of type, or all libraries of a specified type.
func (c *Manager) FindLibrary(ctx context.Context, search Find) ([]string, error)
|
{
url := internal.URL(c, internal.LibraryPath).WithAction("find")
spec := struct {
Spec Find `json:"spec"`
}{search}
var res []string
return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L94-L104
|
go
|
train
|
// CreateLibrary creates a new library with the given Type, Name,
// Description, and CategoryID.
|
func (c *Manager) CreateLibrary(ctx context.Context, library Library) (string, error)
|
// CreateLibrary creates a new library with the given Type, Name,
// Description, and CategoryID.
func (c *Manager) CreateLibrary(ctx context.Context, library Library) (string, error)
|
{
if library.Type != "LOCAL" {
return "", fmt.Errorf("unsupported library type: %q", library.Type)
}
spec := struct {
Library Library `json:"create_spec"`
}{library}
url := internal.URL(c, internal.LocalLibraryPath)
var res string
return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L107-L110
|
go
|
train
|
// DeleteLibrary deletes an existing library.
|
func (c *Manager) DeleteLibrary(ctx context.Context, library *Library) error
|
// DeleteLibrary deletes an existing library.
func (c *Manager) DeleteLibrary(ctx context.Context, library *Library) error
|
{
url := internal.URL(c, internal.LocalLibraryPath).WithID(library.ID)
return c.Do(ctx, url.Request(http.MethodDelete), nil)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L113-L117
|
go
|
train
|
// ListLibraries returns a list of all content library IDs in the system.
|
func (c *Manager) ListLibraries(ctx context.Context) ([]string, error)
|
// ListLibraries returns a list of all content library IDs in the system.
func (c *Manager) ListLibraries(ctx context.Context) ([]string, error)
|
{
url := internal.URL(c, internal.LibraryPath)
var res []string
return res, c.Do(ctx, url.Request(http.MethodGet), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L120-L124
|
go
|
train
|
// GetLibraryByID returns information on a library for the given ID.
|
func (c *Manager) GetLibraryByID(ctx context.Context, id string) (*Library, error)
|
// GetLibraryByID returns information on a library for the given ID.
func (c *Manager) GetLibraryByID(ctx context.Context, id string) (*Library, error)
|
{
url := internal.URL(c, internal.LibraryPath).WithID(id)
var res Library
return &res, c.Do(ctx, url.Request(http.MethodGet), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L127-L139
|
go
|
train
|
// GetLibraryByName returns information on a library for the given name.
|
func (c *Manager) GetLibraryByName(ctx context.Context, name string) (*Library, error)
|
// GetLibraryByName returns information on a library for the given name.
func (c *Manager) GetLibraryByName(ctx context.Context, name string) (*Library, error)
|
{
// Lookup by name
libraries, err := c.GetLibraries(ctx)
if err != nil {
return nil, err
}
for i := range libraries {
if libraries[i].Name == name {
return &libraries[i], nil
}
}
return nil, fmt.Errorf("library name (%s) not found", name)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/library/library.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library.go#L142-L159
|
go
|
train
|
// GetLibraries returns a list of all content library details in the system.
|
func (c *Manager) GetLibraries(ctx context.Context) ([]Library, error)
|
// GetLibraries returns a list of all content library details in the system.
func (c *Manager) GetLibraries(ctx context.Context) ([]Library, error)
|
{
ids, err := c.ListLibraries(ctx)
if err != nil {
return nil, fmt.Errorf("get libraries failed for: %s", err)
}
var libraries []Library
for _, id := range ids {
library, err := c.GetLibraryByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("get library %s failed for %s", id, err)
}
libraries = append(libraries, *library)
}
return libraries, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
simulator/property_collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/property_collector.go#L113-L151
|
go
|
train
|
// wrapValue converts slice types to the appropriate ArrayOf type used in property collector responses.
|
func wrapValue(rval reflect.Value, rtype reflect.Type) interface{}
|
// wrapValue converts slice types to the appropriate ArrayOf type used in property collector responses.
func wrapValue(rval reflect.Value, rtype reflect.Type) interface{}
|
{
pval := rval.Interface()
if rval.Kind() == reflect.Slice {
// Convert slice to types.ArrayOf*
switch v := pval.(type) {
case []string:
pval = &types.ArrayOfString{
String: v,
}
case []uint8:
pval = &types.ArrayOfByte{
Byte: v,
}
case []int16:
pval = &types.ArrayOfShort{
Short: v,
}
case []int32:
pval = &types.ArrayOfInt{
Int: v,
}
case []int64:
pval = &types.ArrayOfLong{
Long: v,
}
default:
kind := rtype.Elem().Name()
// Remove govmomi interface prefix name
kind = strings.TrimPrefix(kind, "Base")
akind, _ := defaultMapType("ArrayOf" + kind)
a := reflect.New(akind)
a.Elem().FieldByName(kind).Set(rval)
pval = a.Interface()
}
}
return pval
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
simulator/property_collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/property_collector.go#L531-L548
|
go
|
train
|
// RetrieveProperties is deprecated, but govmomi is still using it at the moment.
|
func (pc *PropertyCollector) RetrieveProperties(ctx *Context, r *types.RetrieveProperties) soap.HasFault
|
// RetrieveProperties is deprecated, but govmomi is still using it at the moment.
func (pc *PropertyCollector) RetrieveProperties(ctx *Context, r *types.RetrieveProperties) soap.HasFault
|
{
body := &methods.RetrievePropertiesBody{}
res := pc.RetrievePropertiesEx(ctx, &types.RetrievePropertiesEx{
This: r.This,
SpecSet: r.SpecSet,
})
if res.Fault() != nil {
body.Fault_ = res.Fault()
} else {
body.Res = &types.RetrievePropertiesResponse{
Returnval: res.(*methods.RetrievePropertiesExBody).Res.Returnval.Objects,
}
}
return body
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
simulator/property_collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/property_collector.go#L759-L776
|
go
|
train
|
// WaitForUpdates is deprecated, but pyvmomi is still using it at the moment.
|
func (pc *PropertyCollector) WaitForUpdates(ctx *Context, r *types.WaitForUpdates) soap.HasFault
|
// WaitForUpdates is deprecated, but pyvmomi is still using it at the moment.
func (pc *PropertyCollector) WaitForUpdates(ctx *Context, r *types.WaitForUpdates) soap.HasFault
|
{
body := &methods.WaitForUpdatesBody{}
res := pc.WaitForUpdatesEx(ctx, &types.WaitForUpdatesEx{
This: r.This,
Version: r.Version,
})
if res.Fault() != nil {
body.Fault_ = res.Fault()
} else {
body.Res = &types.WaitForUpdatesResponse{
Returnval: *res.(*methods.WaitForUpdatesExBody).Res.Returnval,
}
}
return body
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
simulator/property_collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/property_collector.go#L780-L841
|
go
|
train
|
// Fetch is not documented in the vSphere SDK, but ovftool depends on it.
// A Fetch request is converted to a RetrievePropertiesEx method call by vcsim.
|
func (pc *PropertyCollector) Fetch(ctx *Context, req *internal.Fetch) soap.HasFault
|
// Fetch is not documented in the vSphere SDK, but ovftool depends on it.
// A Fetch request is converted to a RetrievePropertiesEx method call by vcsim.
func (pc *PropertyCollector) Fetch(ctx *Context, req *internal.Fetch) soap.HasFault
|
{
body := new(internal.FetchBody)
if req.This == vim25.ServiceInstance && req.Prop == "content" {
content := ctx.Map.content()
// ovftool uses API version for 6.0 and fails when these fields are non-nil; TODO
content.VStorageObjectManager = nil
content.HostProfileManager = nil
content.HostSpecManager = nil
content.CryptoManager = nil
content.HostProfileManager = nil
content.HealthUpdateManager = nil
content.FailoverClusterConfigurator = nil
content.FailoverClusterManager = nil
body.Res = &internal.FetchResponse{
Returnval: content,
}
return body
}
if ctx.Map.Get(req.This) == nil {
// The Fetch method supports use of super class types, this is a quick hack to support the cases used by ovftool
switch req.This.Type {
case "ManagedEntity":
for o := range ctx.Map.objects {
if o.Value == req.This.Value {
req.This.Type = o.Type
break
}
}
case "ComputeResource":
req.This.Type = "Cluster" + req.This.Type
}
}
res := pc.RetrievePropertiesEx(ctx, &types.RetrievePropertiesEx{
SpecSet: []types.PropertyFilterSpec{{
PropSet: []types.PropertySpec{{
Type: req.This.Type,
PathSet: []string{req.Prop},
}},
ObjectSet: []types.ObjectSpec{{
Obj: req.This,
}},
}}})
if res.Fault() != nil {
return res
}
obj := res.(*methods.RetrievePropertiesExBody).Res.Returnval.Objects[0]
if len(obj.PropSet) == 0 {
fault := obj.MissingSet[0].Fault
body.Fault_ = Fault(fault.LocalizedMessage, fault.Fault)
return body
}
body.Res = &internal.FetchResponse{
Returnval: obj.PropSet[0].Val,
}
return body
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_path.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_path.go#L33-L55
|
go
|
train
|
// FromString parses a datastore path.
// Returns true if the path could be parsed, false otherwise.
|
func (p *DatastorePath) FromString(s string) bool
|
// FromString parses a datastore path.
// Returns true if the path could be parsed, false otherwise.
func (p *DatastorePath) FromString(s string) bool
|
{
if s == "" {
return false
}
s = strings.TrimSpace(s)
if !strings.HasPrefix(s, "[") {
return false
}
s = s[1:]
ix := strings.Index(s, "]")
if ix < 0 {
return false
}
p.Datastore = s[:ix]
p.Path = strings.TrimSpace(s[ix+1:])
return true
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_path.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_path.go#L58-L66
|
go
|
train
|
// String formats a datastore path.
|
func (p *DatastorePath) String() string
|
// String formats a datastore path.
func (p *DatastorePath) String() string
|
{
s := fmt.Sprintf("[%s]", p.Datastore)
if p.Path == "" {
return s
}
return strings.Join([]string{s, p.Path}, " ")
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/common.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/common.go#L67-L72
|
go
|
train
|
// Name returns the base name of the InventoryPath field
|
func (c Common) Name() string
|
// Name returns the base name of the InventoryPath field
func (c Common) Name() string
|
{
if c.InventoryPath == "" {
return ""
}
return path.Base(c.InventoryPath)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/common.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/common.go#L80-L101
|
go
|
train
|
// ObjectName returns the base name of the InventoryPath field if set,
// otherwise fetches the mo.ManagedEntity.Name field via the property collector.
|
func (c Common) ObjectName(ctx context.Context) (string, error)
|
// ObjectName returns the base name of the InventoryPath field if set,
// otherwise fetches the mo.ManagedEntity.Name field via the property collector.
func (c Common) ObjectName(ctx context.Context) (string, error)
|
{
var o mo.ManagedEntity
err := c.Properties(ctx, c.Reference(), []string{"name"}, &o)
if err != nil {
return "", err
}
if o.Name != "" {
return o.Name, nil
}
// Network has its own "name" field...
var n mo.Network
err = c.Properties(ctx, c.Reference(), []string{"name"}, &n)
if err != nil {
return "", err
}
return n.Name, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/common.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/common.go#L104-L106
|
go
|
train
|
// Properties is a wrapper for property.DefaultCollector().RetrieveOne()
|
func (c Common) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error
|
// Properties is a wrapper for property.DefaultCollector().RetrieveOne()
func (c Common) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error
|
{
return property.DefaultCollector(c.c).RetrieveOne(ctx, r, ps, dst)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
session/manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/session/manager.go#L96-L129
|
go
|
train
|
// LoginExtensionByCertificate uses the vCenter SDK tunnel to login using a client certificate.
// The client certificate can be set using the soap.Client.SetCertificate method.
// See: https://kb.vmware.com/s/article/2004305
|
func (sm *Manager) LoginExtensionByCertificate(ctx context.Context, key string) error
|
// LoginExtensionByCertificate uses the vCenter SDK tunnel to login using a client certificate.
// The client certificate can be set using the soap.Client.SetCertificate method.
// See: https://kb.vmware.com/s/article/2004305
func (sm *Manager) LoginExtensionByCertificate(ctx context.Context, key string) error
|
{
c := sm.client
u := c.URL()
if u.Hostname() != "sdkTunnel" {
sc := c.Tunnel()
c = &vim25.Client{
Client: sc,
RoundTripper: sc,
ServiceContent: c.ServiceContent,
}
// When http.Transport.Proxy is used, our thumbprint checker is bypassed, resulting in:
// "Post https://sdkTunnel:8089/sdk: x509: certificate is valid for $vcenter_hostname, not sdkTunnel"
// The only easy way around this is to disable verification for the call to LoginExtensionByCertificate().
// TODO: find a way to avoid disabling InsecureSkipVerify.
c.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
}
req := types.LoginExtensionByCertificate{
This: sm.Reference(),
ExtensionKey: key,
Locale: Locale,
}
login, err := methods.LoginExtensionByCertificate(ctx, c, &req)
if err != nil {
return err
}
// Copy the session cookie
sm.client.Jar.SetCookies(u, c.Jar.Cookies(c.URL()))
sm.userSession = &login.Returnval
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
session/manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/session/manager.go#L162-L180
|
go
|
train
|
// UserSession retrieves and returns the SessionManager's CurrentSession field.
// Nil is returned if the session is not authenticated.
|
func (sm *Manager) UserSession(ctx context.Context) (*types.UserSession, error)
|
// UserSession retrieves and returns the SessionManager's CurrentSession field.
// Nil is returned if the session is not authenticated.
func (sm *Manager) UserSession(ctx context.Context) (*types.UserSession, error)
|
{
var mgr mo.SessionManager
pc := property.DefaultCollector(sm.client)
err := pc.RetrieveOne(ctx, sm.Reference(), []string{"currentSession"}, &mgr)
if err != nil {
// It's OK if we can't retrieve properties because we're not authenticated
if f, ok := err.(types.HasFault); ok {
switch f.Fault().(type) {
case *types.NotAuthenticated:
return nil, nil
}
}
return nil, err
}
return mgr.CurrentSession, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
session/manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/session/manager.go#L194-L211
|
go
|
train
|
// SessionIsActive checks whether the session that was created at login is
// still valid. This function only works against vCenter.
|
func (sm *Manager) SessionIsActive(ctx context.Context) (bool, error)
|
// SessionIsActive checks whether the session that was created at login is
// still valid. This function only works against vCenter.
func (sm *Manager) SessionIsActive(ctx context.Context) (bool, error)
|
{
if sm.userSession == nil {
return false, nil
}
req := types.SessionIsActive{
This: sm.Reference(),
SessionID: sm.userSession.Key,
UserName: sm.userSession.UserName,
}
active, err := methods.SessionIsActive(ctx, sm.client, &req)
if err != nil {
return false, err
}
return active.Returnval, err
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/collector.go#L41-L48
|
go
|
train
|
// DefaultCollector returns the session's default property collector.
|
func DefaultCollector(c *vim25.Client) *Collector
|
// DefaultCollector returns the session's default property collector.
func DefaultCollector(c *vim25.Client) *Collector
|
{
p := Collector{
roundTripper: c,
reference: c.ServiceContent.PropertyCollector,
}
return &p
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/collector.go#L56-L72
|
go
|
train
|
// Create creates a new session-specific Collector that can be used to
// retrieve property updates independent of any other Collector.
|
func (p *Collector) Create(ctx context.Context) (*Collector, error)
|
// Create creates a new session-specific Collector that can be used to
// retrieve property updates independent of any other Collector.
func (p *Collector) Create(ctx context.Context) (*Collector, error)
|
{
req := types.CreatePropertyCollector{
This: p.Reference(),
}
res, err := methods.CreatePropertyCollector(ctx, p.roundTripper, &req)
if err != nil {
return nil, err
}
newp := Collector{
roundTripper: p.roundTripper,
reference: res.Returnval,
}
return &newp, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/collector.go#L75-L87
|
go
|
train
|
// Destroy destroys this Collector.
|
func (p *Collector) Destroy(ctx context.Context) error
|
// Destroy destroys this Collector.
func (p *Collector) Destroy(ctx context.Context) error
|
{
req := types.DestroyPropertyCollector{
This: p.Reference(),
}
_, err := methods.DestroyPropertyCollector(ctx, p.roundTripper, &req)
if err != nil {
return err
}
p.reference = types.ManagedObjectReference{}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/collector.go#L131-L183
|
go
|
train
|
// Retrieve loads properties for a slice of managed objects. The dst argument
// must be a pointer to a []interface{}, which is populated with the instances
// of the specified managed objects, with the relevant properties filled in. If
// the properties slice is nil, all properties are loaded.
// Note that pointer types are optional fields that may be left as a nil value.
// The caller should check such fields for a nil value before dereferencing.
|
func (p *Collector) Retrieve(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst interface{}) error
|
// Retrieve loads properties for a slice of managed objects. The dst argument
// must be a pointer to a []interface{}, which is populated with the instances
// of the specified managed objects, with the relevant properties filled in. If
// the properties slice is nil, all properties are loaded.
// Note that pointer types are optional fields that may be left as a nil value.
// The caller should check such fields for a nil value before dereferencing.
func (p *Collector) Retrieve(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst interface{}) error
|
{
if len(objs) == 0 {
return errors.New("object references is empty")
}
kinds := make(map[string]bool)
var propSet []types.PropertySpec
var objectSet []types.ObjectSpec
for _, obj := range objs {
if _, ok := kinds[obj.Type]; !ok {
spec := types.PropertySpec{
Type: obj.Type,
}
if ps == nil {
spec.All = types.NewBool(true)
} else {
spec.PathSet = ps
}
propSet = append(propSet, spec)
kinds[obj.Type] = true
}
objectSpec := types.ObjectSpec{
Obj: obj,
Skip: types.NewBool(false),
}
objectSet = append(objectSet, objectSpec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: objectSet,
PropSet: propSet,
},
},
}
res, err := p.RetrieveProperties(ctx, req)
if err != nil {
return err
}
if d, ok := dst.(*[]types.ObjectContent); ok {
*d = res.Returnval
return nil
}
return mo.LoadRetrievePropertiesResponse(res, dst)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/collector.go#L186-L205
|
go
|
train
|
// RetrieveWithFilter populates dst as Retrieve does, but only for entities matching the given filter.
|
func (p *Collector) RetrieveWithFilter(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst interface{}, filter Filter) error
|
// RetrieveWithFilter populates dst as Retrieve does, but only for entities matching the given filter.
func (p *Collector) RetrieveWithFilter(ctx context.Context, objs []types.ManagedObjectReference, ps []string, dst interface{}, filter Filter) error
|
{
if len(filter) == 0 {
return p.Retrieve(ctx, objs, ps, dst)
}
var content []types.ObjectContent
err := p.Retrieve(ctx, objs, filter.Keys(), &content)
if err != nil {
return err
}
objs = filter.MatchObjectContent(content)
if len(objs) == 0 {
return nil
}
return p.Retrieve(ctx, objs, ps, dst)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/collector.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/collector.go#L208-L211
|
go
|
train
|
// RetrieveOne calls Retrieve with a single managed object reference via Collector.Retrieve().
|
func (p *Collector) RetrieveOne(ctx context.Context, obj types.ManagedObjectReference, ps []string, dst interface{}) error
|
// RetrieveOne calls Retrieve with a single managed object reference via Collector.Retrieve().
func (p *Collector) RetrieveOne(ctx context.Context, obj types.ManagedObjectReference, ps []string, dst interface{}) error
|
{
var objs = []types.ManagedObjectReference{obj}
return p.Retrieve(ctx, objs, ps, dst)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/wait.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/wait.go#L33-L53
|
go
|
train
|
// Add a new ObjectSpec and PropertySpec to the WaitFilter
|
func (f *WaitFilter) Add(obj types.ManagedObjectReference, kind string, ps []string, set ...types.BaseSelectionSpec) *WaitFilter
|
// Add a new ObjectSpec and PropertySpec to the WaitFilter
func (f *WaitFilter) Add(obj types.ManagedObjectReference, kind string, ps []string, set ...types.BaseSelectionSpec) *WaitFilter
|
{
spec := types.ObjectSpec{
Obj: obj,
SelectSet: set,
}
pset := types.PropertySpec{
Type: kind,
PathSet: ps,
}
if len(ps) == 0 {
pset.All = types.NewBool(true)
}
f.Spec.ObjectSet = append(f.Spec.ObjectSet, spec)
f.Spec.PropSet = append(f.Spec.PropSet, pset)
return f
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/wait.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/wait.go#L56-L68
|
go
|
train
|
// Wait creates a new WaitFilter and calls the specified function for each ObjectUpdate via WaitForUpdates
|
func Wait(ctx context.Context, c *Collector, obj types.ManagedObjectReference, ps []string, f func([]types.PropertyChange) bool) error
|
// Wait creates a new WaitFilter and calls the specified function for each ObjectUpdate via WaitForUpdates
func Wait(ctx context.Context, c *Collector, obj types.ManagedObjectReference, ps []string, f func([]types.PropertyChange) bool) error
|
{
filter := new(WaitFilter).Add(obj, obj.Type, ps)
return WaitForUpdates(ctx, c, filter, func(updates []types.ObjectUpdate) bool {
for _, update := range updates {
if f(update.ChangeSet) {
return true
}
}
return false
})
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
property/wait.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/wait.go#L84-L133
|
go
|
train
|
// WaitForUpdates waits for any of the specified properties of the specified managed
// object to change. It calls the specified function for every update it
// receives. If this function returns false, it continues waiting for
// subsequent updates. If this function returns true, it stops waiting and
// returns.
//
// To only receive updates for the specified managed object, the function
// creates a new property collector and calls CreateFilter. A new property
// collector is required because filters can only be added, not removed.
//
// If the Context is canceled, a call to CancelWaitForUpdates() is made and its error value is returned.
// The newly created collector is destroyed before this function returns (both
// in case of success or error).
//
|
func WaitForUpdates(ctx context.Context, c *Collector, filter *WaitFilter, f func([]types.ObjectUpdate) bool) error
|
// WaitForUpdates waits for any of the specified properties of the specified managed
// object to change. It calls the specified function for every update it
// receives. If this function returns false, it continues waiting for
// subsequent updates. If this function returns true, it stops waiting and
// returns.
//
// To only receive updates for the specified managed object, the function
// creates a new property collector and calls CreateFilter. A new property
// collector is required because filters can only be added, not removed.
//
// If the Context is canceled, a call to CancelWaitForUpdates() is made and its error value is returned.
// The newly created collector is destroyed before this function returns (both
// in case of success or error).
//
func WaitForUpdates(ctx context.Context, c *Collector, filter *WaitFilter, f func([]types.ObjectUpdate) bool) error
|
{
p, err := c.Create(ctx)
if err != nil {
return err
}
// Attempt to destroy the collector using the background context, as the
// specified context may have timed out or have been canceled.
defer func() {
_ = p.Destroy(context.Background())
}()
err = p.CreateFilter(ctx, filter.CreateFilter)
if err != nil {
return err
}
req := types.WaitForUpdatesEx{
This: p.Reference(),
Options: filter.Options,
}
for {
res, err := methods.WaitForUpdatesEx(ctx, p.roundTripper, &req)
if err != nil {
if ctx.Err() == context.Canceled {
werr := p.CancelWaitForUpdates(context.Background())
return werr
}
return err
}
set := res.Returnval
if set == nil {
if req.Options != nil && req.Options.MaxWaitSeconds != nil {
return nil // WaitOptions.MaxWaitSeconds exceeded
}
// Retry if the result came back empty
continue
}
req.Version = set.Version
for _, fs := range set.FilterSet {
if f(fs.ObjectSet) {
return nil
}
}
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
govc/flags/network.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/network.go#L134-L147
|
go
|
train
|
// Change applies update backing and hardware address changes to the given network device.
|
func (flag *NetworkFlag) Change(device types.BaseVirtualDevice, update types.BaseVirtualDevice)
|
// Change applies update backing and hardware address changes to the given network device.
func (flag *NetworkFlag) Change(device types.BaseVirtualDevice, update types.BaseVirtualDevice)
|
{
current := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
changed := update.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
current.Backing = changed.Backing
if changed.MacAddress != "" {
current.MacAddress = changed.MacAddress
}
if changed.AddressType != "" {
current.AddressType = changed.AddressType
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/extension_manager.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/extension_manager.go#L34-L39
|
go
|
train
|
// GetExtensionManager wraps NewExtensionManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
|
func GetExtensionManager(c *vim25.Client) (*ExtensionManager, error)
|
// GetExtensionManager wraps NewExtensionManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetExtensionManager(c *vim25.Client) (*ExtensionManager, error)
|
{
if c.ServiceContent.ExtensionManager == nil {
return nil, ErrNotSupported
}
return NewExtensionManager(c), nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
simulator/datacenter.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/datacenter.go#L36-L50
|
go
|
train
|
// NewDatacenter creates a Datacenter and its child folders.
|
func NewDatacenter(f *Folder) *Datacenter
|
// NewDatacenter creates a Datacenter and its child folders.
func NewDatacenter(f *Folder) *Datacenter
|
{
dc := &Datacenter{
isESX: f.Self == esx.RootFolder.Self,
}
if dc.isESX {
dc.Datacenter = esx.Datacenter
}
f.putChild(dc)
dc.createFolders()
return dc
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
simulator/datacenter.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/datacenter.go#L56-L101
|
go
|
train
|
// Create Datacenter Folders.
// Every Datacenter has 4 inventory Folders: Vm, Host, Datastore and Network.
// The ESX folder child types are limited to 1 type.
// The VC folders have additional child types, including nested folders.
|
func (dc *Datacenter) createFolders()
|
// Create Datacenter Folders.
// Every Datacenter has 4 inventory Folders: Vm, Host, Datastore and Network.
// The ESX folder child types are limited to 1 type.
// The VC folders have additional child types, including nested folders.
func (dc *Datacenter) createFolders()
|
{
folders := []struct {
ref *types.ManagedObjectReference
name string
types []string
}{
{&dc.VmFolder, "vm", []string{"VirtualMachine", "VirtualApp", "Folder"}},
{&dc.HostFolder, "host", []string{"ComputeResource", "Folder"}},
{&dc.DatastoreFolder, "datastore", []string{"Datastore", "StoragePod", "Folder"}},
{&dc.NetworkFolder, "network", []string{"Network", "DistributedVirtualSwitch", "Folder"}},
}
for _, f := range folders {
folder := &Folder{}
folder.Name = f.name
if dc.isESX {
folder.ChildType = f.types[:1]
folder.Self = *f.ref
Map.PutEntity(dc, folder)
} else {
folder.ChildType = f.types
e := Map.PutEntity(dc, folder)
// propagate the generated morefs to Datacenter
ref := e.Reference()
f.ref.Type = ref.Type
f.ref.Value = ref.Value
}
}
net := Map.Get(dc.NetworkFolder).(*Folder)
for _, ref := range esx.Datacenter.Network {
// Add VM Network by default to each Datacenter
network := &mo.Network{}
network.Self = ref
network.Name = strings.Split(ref.Value, "-")[1]
network.Entity().Name = network.Name
if !dc.isESX {
network.Self.Value = "" // we want a different moid per-DC
}
net.putChild(network)
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L56-L66
|
go
|
train
|
// Patch merges updates from the given src.
|
func (t *Tag) Patch(src *Tag)
|
// Patch merges updates from the given src.
func (t *Tag) Patch(src *Tag)
|
{
if src.Name != "" {
t.Name = src.Name
}
if src.Description != "" {
t.Description = src.Description
}
if src.CategoryID != "" {
t.CategoryID = src.CategoryID
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L69-L96
|
go
|
train
|
// CreateTag creates a new tag with the given Name, Description and CategoryID.
|
func (c *Manager) CreateTag(ctx context.Context, tag *Tag) (string, error)
|
// CreateTag creates a new tag with the given Name, Description and CategoryID.
func (c *Manager) CreateTag(ctx context.Context, tag *Tag) (string, error)
|
{
// create avoids the annoyance of CreateTag requiring a "description" key 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"`
CategoryID string `json:"category_id"`
}
spec := struct {
Tag create `json:"create_spec"`
}{
Tag: create{
Name: tag.Name,
Description: tag.Description,
CategoryID: tag.CategoryID,
},
}
if isName(tag.CategoryID) {
cat, err := c.GetCategory(ctx, tag.CategoryID)
if err != nil {
return "", err
}
spec.Tag.CategoryID = cat.ID
}
url := internal.URL(c, internal.TagPath)
var res string
return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L99-L110
|
go
|
train
|
// UpdateTag can update one or both of the tag Description and Name fields.
|
func (c *Manager) UpdateTag(ctx context.Context, tag *Tag) error
|
// UpdateTag can update one or both of the tag Description and Name fields.
func (c *Manager) UpdateTag(ctx context.Context, tag *Tag) error
|
{
spec := struct {
Tag Tag `json:"update_spec"`
}{
Tag: Tag{
Name: tag.Name,
Description: tag.Description,
},
}
url := internal.URL(c, internal.TagPath).WithID(tag.ID)
return c.Do(ctx, url.Request(http.MethodPatch, spec), nil)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L113-L116
|
go
|
train
|
// DeleteTag deletes an existing tag.
|
func (c *Manager) DeleteTag(ctx context.Context, tag *Tag) error
|
// DeleteTag deletes an existing tag.
func (c *Manager) DeleteTag(ctx context.Context, tag *Tag) error
|
{
url := internal.URL(c, internal.TagPath).WithID(tag.ID)
return c.Do(ctx, url.Request(http.MethodDelete), nil)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L120-L138
|
go
|
train
|
// GetTag fetches the tag information for the given identifier.
// The id parameter can be a Tag ID or Tag Name.
|
func (c *Manager) GetTag(ctx context.Context, id string) (*Tag, error)
|
// GetTag fetches the tag information for the given identifier.
// The id parameter can be a Tag ID or Tag Name.
func (c *Manager) GetTag(ctx context.Context, id string) (*Tag, error)
|
{
if isName(id) {
tags, err := c.GetTags(ctx)
if err != nil {
return nil, err
}
for i := range tags {
if tags[i].Name == id {
return &tags[i], nil
}
}
}
url := internal.URL(c, internal.TagPath).WithID(id)
var res Tag
return &res, c.Do(ctx, url.Request(http.MethodGet), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L141-L162
|
go
|
train
|
// GetTagForCategory fetches the tag information for the given identifier in the given category.
|
func (c *Manager) GetTagForCategory(ctx context.Context, id, category string) (*Tag, error)
|
// GetTagForCategory fetches the tag information for the given identifier in the given category.
func (c *Manager) GetTagForCategory(ctx context.Context, id, category string) (*Tag, error)
|
{
if category == "" {
return c.GetTag(ctx, id)
}
ids, err := c.ListTagsForCategory(ctx, category)
if err != nil {
return nil, err
}
for _, tagid := range ids {
tag, err := c.GetTag(ctx, tagid)
if err != nil {
return nil, fmt.Errorf("get tag for category %s %s: %s", category, tagid, err)
}
if tag.ID == id || tag.Name == id {
return tag, nil
}
}
return nil, fmt.Errorf("tag %q not found in category %q", id, category)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L165-L169
|
go
|
train
|
// ListTags returns all tag IDs in the system.
|
func (c *Manager) ListTags(ctx context.Context) ([]string, error)
|
// ListTags returns all tag IDs in the system.
func (c *Manager) ListTags(ctx context.Context) ([]string, error)
|
{
url := internal.URL(c, internal.TagPath)
var res []string
return res, c.Do(ctx, url.Request(http.MethodGet), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L172-L189
|
go
|
train
|
// GetTags fetches an array of tag information in the system.
|
func (c *Manager) GetTags(ctx context.Context) ([]Tag, error)
|
// GetTags fetches an array of tag information in the system.
func (c *Manager) GetTags(ctx context.Context) ([]Tag, error)
|
{
ids, err := c.ListTags(ctx)
if err != nil {
return nil, fmt.Errorf("get tags failed for: %s", err)
}
var tags []Tag
for _, id := range ids {
tag, err := c.GetTag(ctx, id)
if err != nil {
return nil, fmt.Errorf("get category %s failed for %s", id, err)
}
tags = append(tags, *tag)
}
return tags, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L192-L207
|
go
|
train
|
// The id parameter can be a Category ID or Category Name.
|
func (c *Manager) ListTagsForCategory(ctx context.Context, id string) ([]string, error)
|
// The id parameter can be a Category ID or Category Name.
func (c *Manager) ListTagsForCategory(ctx context.Context, id string) ([]string, error)
|
{
if isName(id) {
cat, err := c.GetCategory(ctx, id)
if err != nil {
return nil, err
}
id = cat.ID
}
body := struct {
ID string `json:"category_id"`
}{id}
url := internal.URL(c, internal.TagPath).WithID(id).WithAction("list-tags-for-category")
var res []string
return res, c.Do(ctx, url.Request(http.MethodPost, body), &res)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vapi/tags/tags.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L210-L226
|
go
|
train
|
// The id parameter can be a Category ID or Category Name.
|
func (c *Manager) GetTagsForCategory(ctx context.Context, id string) ([]Tag, error)
|
// The id parameter can be a Category ID or Category Name.
func (c *Manager) GetTagsForCategory(ctx context.Context, id string) ([]Tag, error)
|
{
ids, err := c.ListTagsForCategory(ctx, id)
if err != nil {
return nil, err
}
var tags []Tag
for _, id := range ids {
tag, err := c.GetTag(ctx, id)
if err != nil {
return nil, fmt.Errorf("get tag %s: %s", id, err)
}
tags = append(tags, *tag)
}
return tags, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L92-L118
|
go
|
train
|
// ParseURL is wrapper around url.Parse, where Scheme defaults to "https" and Path defaults to "/sdk"
|
func ParseURL(s string) (*url.URL, error)
|
// ParseURL is wrapper around url.Parse, where Scheme defaults to "https" and Path defaults to "/sdk"
func ParseURL(s string) (*url.URL, error)
|
{
var err error
var u *url.URL
if s != "" {
// Default the scheme to https
if !schemeMatch.MatchString(s) {
s = "https://" + s
}
u, err = url.Parse(s)
if err != nil {
return nil, err
}
// Default the path to /sdk
if u.Path == "" {
u.Path = "/sdk"
}
if u.User == nil {
u.User = url.UserPassword("", "")
}
}
return u, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L159-L200
|
go
|
train
|
// NewServiceClient creates a NewClient with the given URL.Path and namespace.
|
func (c *Client) NewServiceClient(path string, namespace string) *Client
|
// NewServiceClient creates a NewClient with the given URL.Path and namespace.
func (c *Client) NewServiceClient(path string, namespace string) *Client
|
{
vc := c.URL()
u, err := url.Parse(path)
if err != nil {
log.Panicf("url.Parse(%q): %s", path, err)
}
if u.Host == "" {
u.Scheme = vc.Scheme
u.Host = vc.Host
}
client := NewClient(u, c.k)
client.Namespace = "urn:" + namespace
if cert := c.Certificate(); cert != nil {
client.SetCertificate(*cert)
}
// Copy the trusted thumbprints
c.hostsMu.Lock()
for k, v := range c.hosts {
client.hosts[k] = v
}
c.hostsMu.Unlock()
// Copy the cookies
client.Client.Jar.SetCookies(u, c.Client.Jar.Cookies(u))
// Set SOAP Header cookie
for _, cookie := range client.Jar.Cookies(u) {
if cookie.Name == SessionCookieName {
client.cookie = cookie.Value
break
}
}
// Copy any query params (e.g. GOVMOMI_TUNNEL_PROXY_PORT used in testing)
client.u.RawQuery = vc.RawQuery
client.UserAgent = c.UserAgent
return client
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L207-L226
|
go
|
train
|
// SetRootCAs defines the set of root certificate authorities
// that clients use when verifying server certificates.
// By default TLS uses the host's root CA set.
//
// See: http.Client.Transport.TLSClientConfig.RootCAs
|
func (c *Client) SetRootCAs(file string) error
|
// SetRootCAs defines the set of root certificate authorities
// that clients use when verifying server certificates.
// By default TLS uses the host's root CA set.
//
// See: http.Client.Transport.TLSClientConfig.RootCAs
func (c *Client) SetRootCAs(file string) error
|
{
pool := x509.NewCertPool()
for _, name := range filepath.SplitList(file) {
pem, err := ioutil.ReadFile(filepath.Clean(name))
if err != nil {
return err
}
if ok := pool.AppendCertsFromPEM(pem); !ok {
return errInvalidCACertificate{
File: name,
}
}
}
c.t.TLSClientConfig.RootCAs = pool
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L229-L235
|
go
|
train
|
// Add default https port if missing
|
func hostAddr(addr string) string
|
// Add default https port if missing
func hostAddr(addr string) string
|
{
_, port := splitHostPort(addr)
if port == "" {
return addr + ":443"
}
return addr
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L243-L253
|
go
|
train
|
// SetThumbprint sets the known certificate thumbprint for the given host.
// A custom DialTLS function is used to support thumbprint based verification.
// We first try tls.Dial with the default tls.Config, only falling back to thumbprint verification
// if it fails with an x509.UnknownAuthorityError or x509.HostnameError
//
// See: http.Client.Transport.DialTLS
|
func (c *Client) SetThumbprint(host string, thumbprint string)
|
// SetThumbprint sets the known certificate thumbprint for the given host.
// A custom DialTLS function is used to support thumbprint based verification.
// We first try tls.Dial with the default tls.Config, only falling back to thumbprint verification
// if it fails with an x509.UnknownAuthorityError or x509.HostnameError
//
// See: http.Client.Transport.DialTLS
func (c *Client) SetThumbprint(host string, thumbprint string)
|
{
host = hostAddr(host)
c.hostsMu.Lock()
if thumbprint == "" {
delete(c.hosts, host)
} else {
c.hosts[host] = thumbprint
}
c.hostsMu.Unlock()
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L256-L261
|
go
|
train
|
// Thumbprint returns the certificate thumbprint for the given host if known to this client.
|
func (c *Client) Thumbprint(host string) string
|
// Thumbprint returns the certificate thumbprint for the given host if known to this client.
func (c *Client) Thumbprint(host string) string
|
{
host = hostAddr(host)
c.hostsMu.Lock()
defer c.hostsMu.Unlock()
return c.hosts[host]
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L265-L278
|
go
|
train
|
// LoadThumbprints from file with the give name.
// If name is empty or name does not exist this function will return nil.
|
func (c *Client) LoadThumbprints(file string) error
|
// LoadThumbprints from file with the give name.
// If name is empty or name does not exist this function will return nil.
func (c *Client) LoadThumbprints(file string) error
|
{
if file == "" {
return nil
}
for _, name := range filepath.SplitList(file) {
err := c.loadThumbprints(name)
if err != nil {
return err
}
}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L308-L315
|
go
|
train
|
// ThumbprintSHA1 returns the thumbprint of the given cert in the same format used by the SDK and Client.SetThumbprint.
//
// See: SSLVerifyFault.Thumbprint, SessionManagerGenericServiceTicket.Thumbprint, HostConnectSpec.SslThumbprint
|
func ThumbprintSHA1(cert *x509.Certificate) string
|
// ThumbprintSHA1 returns the thumbprint of the given cert in the same format used by the SDK and Client.SetThumbprint.
//
// See: SSLVerifyFault.Thumbprint, SessionManagerGenericServiceTicket.Thumbprint, HostConnectSpec.SslThumbprint
func ThumbprintSHA1(cert *x509.Certificate) string
|
{
sum := sha1.Sum(cert.Raw)
hex := make([]string, len(sum))
for i, b := range sum {
hex[i] = fmt.Sprintf("%02X", b)
}
return strings.Join(hex, ":")
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L359-L370
|
go
|
train
|
// splitHostPort is similar to net.SplitHostPort,
// but rather than return error if there isn't a ':port',
// return an empty string for the port.
|
func splitHostPort(host string) (string, string)
|
// splitHostPort is similar to net.SplitHostPort,
// but rather than return error if there isn't a ':port',
// return an empty string for the port.
func splitHostPort(host string) (string, string)
|
{
ix := strings.LastIndex(host, ":")
if ix <= strings.LastIndex(host, "]") {
return host, ""
}
name := host[:ix]
port := host[ix+1:]
return name, port
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L392-L417
|
go
|
train
|
// Tunnel returns a Client configured to proxy requests through vCenter's http port 80,
// to the SDK tunnel virtual host. Use of the SDK tunnel is required by LoginExtensionByCertificate()
// and optional for other methods.
|
func (c *Client) Tunnel() *Client
|
// Tunnel returns a Client configured to proxy requests through vCenter's http port 80,
// to the SDK tunnel virtual host. Use of the SDK tunnel is required by LoginExtensionByCertificate()
// and optional for other methods.
func (c *Client) Tunnel() *Client
|
{
tunnel := c.NewServiceClient(c.u.Path, c.Namespace)
t := tunnel.Client.Transport.(*http.Transport)
// Proxy to vCenter host on port 80
host := tunnel.u.Hostname()
// Should be no reason to change the default port other than testing
key := "GOVMOMI_TUNNEL_PROXY_PORT"
port := tunnel.URL().Query().Get(key)
if port == "" {
port = os.Getenv(key)
}
if port != "" {
host += ":" + port
}
t.Proxy = http.ProxyURL(&url.URL{
Scheme: "http",
Host: host,
})
// Rewrite url Host to use the sdk tunnel, required for a certificate request.
tunnel.u.Host = sdkTunnel
return tunnel
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L511-L513
|
go
|
train
|
// WithHeader can be used to modify the outgoing request soap.Header fields.
|
func (c *Client) WithHeader(ctx context.Context, header Header) context.Context
|
// WithHeader can be used to modify the outgoing request soap.Header fields.
func (c *Client) WithHeader(ctx context.Context, header Header) context.Context
|
{
return context.WithValue(ctx, headerContext{}, header)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L595-L608
|
go
|
train
|
// ParseURL wraps url.Parse to rewrite the URL.Host field
// In the case of VM guest uploads or NFC lease URLs, a Host
// field with a value of "*" is rewritten to the Client's URL.Host.
|
func (c *Client) ParseURL(urlStr string) (*url.URL, error)
|
// ParseURL wraps url.Parse to rewrite the URL.Host field
// In the case of VM guest uploads or NFC lease URLs, a Host
// field with a value of "*" is rewritten to the Client's URL.Host.
func (c *Client) ParseURL(urlStr string) (*url.URL, error)
|
{
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
host, _ := splitHostPort(u.Host)
if host == "*" {
// Also use Client's port, to support port forwarding
u.Host = c.URL().Host
}
return u, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L625-L671
|
go
|
train
|
// Upload PUTs the local file to the given URL
|
func (c *Client) Upload(ctx context.Context, f io.Reader, u *url.URL, param *Upload) error
|
// Upload PUTs the local file to the given URL
func (c *Client) Upload(ctx context.Context, f io.Reader, u *url.URL, param *Upload) error
|
{
var err error
if param.Progress != nil {
pr := progress.NewReader(ctx, param.Progress, f, param.ContentLength)
f = pr
// Mark progress reader as done when returning from this function.
defer func() {
pr.Done(err)
}()
}
req, err := http.NewRequest(param.Method, u.String(), f)
if err != nil {
return err
}
req = req.WithContext(ctx)
req.ContentLength = param.ContentLength
req.Header.Set("Content-Type", param.Type)
for k, v := range param.Headers {
req.Header.Add(k, v)
}
if param.Ticket != nil {
req.AddCookie(param.Ticket)
}
res, err := c.Client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
switch res.StatusCode {
case http.StatusOK:
case http.StatusCreated:
default:
err = errors.New(res.Status)
}
return err
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L674-L694
|
go
|
train
|
// UploadFile PUTs the local file to the given URL
|
func (c *Client) UploadFile(ctx context.Context, file string, u *url.URL, param *Upload) error
|
// UploadFile PUTs the local file to the given URL
func (c *Client) UploadFile(ctx context.Context, file string, u *url.URL, param *Upload) error
|
{
if param == nil {
p := DefaultUpload // Copy since we set ContentLength
param = &p
}
s, err := os.Stat(file)
if err != nil {
return err
}
f, err := os.Open(filepath.Clean(file))
if err != nil {
return err
}
defer f.Close()
param.ContentLength = s.Size()
return c.Upload(ctx, f, u, param)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L709-L726
|
go
|
train
|
// DownloadRequest wraps http.Client.Do, returning the http.Response without checking its StatusCode
|
func (c *Client) DownloadRequest(ctx context.Context, u *url.URL, param *Download) (*http.Response, error)
|
// DownloadRequest wraps http.Client.Do, returning the http.Response without checking its StatusCode
func (c *Client) DownloadRequest(ctx context.Context, u *url.URL, param *Download) (*http.Response, error)
|
{
req, err := http.NewRequest(param.Method, u.String(), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
for k, v := range param.Headers {
req.Header.Add(k, v)
}
if param.Ticket != nil {
req.AddCookie(param.Ticket)
}
return c.Client.Do(req)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L729-L748
|
go
|
train
|
// Download GETs the remote file from the given URL
|
func (c *Client) Download(ctx context.Context, u *url.URL, param *Download) (io.ReadCloser, int64, error)
|
// Download GETs the remote file from the given URL
func (c *Client) Download(ctx context.Context, u *url.URL, param *Download) (io.ReadCloser, int64, error)
|
{
res, err := c.DownloadRequest(ctx, u, param)
if err != nil {
return nil, 0, err
}
switch res.StatusCode {
case http.StatusOK:
default:
err = errors.New(res.Status)
}
if err != nil {
return nil, 0, err
}
r := res.Body
return r, res.ContentLength, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/soap/client.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L788-L800
|
go
|
train
|
// DownloadFile GETs the given URL to a local file
|
func (c *Client) DownloadFile(ctx context.Context, file string, u *url.URL, param *Download) error
|
// DownloadFile GETs the given URL to a local file
func (c *Client) DownloadFile(ctx context.Context, file string, u *url.URL, param *Download) error
|
{
var err error
if param == nil {
param = &DefaultDownload
}
rc, contentLength, err := c.Download(ctx, u, param)
if err != nil {
return err
}
return c.WriteFile(ctx, file, rc, contentLength, param.Progress, param.Writer)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L110-L117
|
go
|
train
|
// WithIO enables toolbox Process IO without file system disk IO.
|
func (p *Process) WithIO() *Process
|
// WithIO enables toolbox Process IO without file system disk IO.
func (p *Process) WithIO() *Process
|
{
p.IO = &ProcessIO{
Out: new(bytes.Buffer),
Err: new(bytes.Buffer),
}
return p
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L221-L236
|
go
|
train
|
// NewProcessManager creates a new ProcessManager instance.
|
func NewProcessManager() *ProcessManager
|
// NewProcessManager creates a new ProcessManager instance.
func NewProcessManager() *ProcessManager
|
{
// We use pseudo PIDs that don't conflict with OS PIDs, so they can live in the same table.
// For the pseudo PIDs, we use a sync.Pool rather than a plain old counter to avoid the unlikely,
// but possible wrapping should such a counter exceed MaxInt64.
pid := int64(32768) // TODO: /proc/sys/kernel/pid_max
return &ProcessManager{
expire: time.Minute * 5,
entries: make(map[int64]*Process),
pids: sync.Pool{
New: func() interface{} {
return atomic.AddInt64(&pid, 1)
},
},
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L242-L303
|
go
|
train
|
// Start calls the Process.Start function, returning the pid on success or an error.
// A goroutine is started that calls the Process.Wait function. After Process.Wait has
// returned, the ProcessState EndTime and ExitCode fields are set. The process state can be
// queried via ListProcessesInGuest until it is removed, 5 minutes after Wait returns.
|
func (m *ProcessManager) Start(r *vix.StartProgramRequest, p *Process) (int64, error)
|
// Start calls the Process.Start function, returning the pid on success or an error.
// A goroutine is started that calls the Process.Wait function. After Process.Wait has
// returned, the ProcessState EndTime and ExitCode fields are set. The process state can be
// queried via ListProcessesInGuest until it is removed, 5 minutes after Wait returns.
func (m *ProcessManager) Start(r *vix.StartProgramRequest, p *Process) (int64, error)
|
{
p.Name = r.ProgramPath
p.Args = r.Arguments
// Owner is cosmetic, but useful for example with: govc guest.ps -U $uid
if p.Owner == "" {
p.Owner = defaultOwner
}
p.StartTime = time.Now().Unix()
p.ctx, p.Kill = context.WithCancel(context.Background())
pid, err := p.Start(p, r)
if err != nil {
return -1, err
}
if pid == 0 {
p.Pid = m.pids.Get().(int64) // pseudo pid for funcs
} else {
p.Pid = pid
}
m.mu.Lock()
m.entries[p.Pid] = p
m.mu.Unlock()
m.wg.Add(1)
go func() {
werr := p.Wait()
atomic.StoreInt64(&p.EndTime, time.Now().Unix())
if werr != nil {
rc := int32(1)
if xerr, ok := werr.(*ProcessError); ok {
rc = xerr.ExitCode
}
atomic.StoreInt32(&p.ExitCode, rc)
}
m.wg.Done()
p.Kill() // cancel context for those waiting on p.ctx.Done()
// See: http://pubs.vmware.com/vsphere-65/topic/com.vmware.wssdk.apiref.doc/vim.vm.guest.ProcessManager.ProcessInfo.html
// "If the process was started using StartProgramInGuest then the process completion time
// will be available if queried within 5 minutes after it completes."
<-time.After(m.expire)
m.mu.Lock()
delete(m.entries, p.Pid)
m.mu.Unlock()
if pid == 0 {
m.pids.Put(p.Pid) // pseudo pid can be reused now
}
}()
return p.Pid, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L307-L318
|
go
|
train
|
// Kill cancels the Process Context.
// Returns true if pid exists in the process table, false otherwise.
|
func (m *ProcessManager) Kill(pid int64) bool
|
// Kill cancels the Process Context.
// Returns true if pid exists in the process table, false otherwise.
func (m *ProcessManager) Kill(pid int64) bool
|
{
m.mu.Lock()
entry, ok := m.entries[pid]
m.mu.Unlock()
if ok {
entry.Kill()
return true
}
return false
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L323-L346
|
go
|
train
|
// ListProcesses marshals the ProcessState for the given pids.
// If no pids are specified, all current processes are included.
// The return value can be used for responding to a VixMsgListProcessesExRequest.
|
func (m *ProcessManager) ListProcesses(pids []int64) []byte
|
// ListProcesses marshals the ProcessState for the given pids.
// If no pids are specified, all current processes are included.
// The return value can be used for responding to a VixMsgListProcessesExRequest.
func (m *ProcessManager) ListProcesses(pids []int64) []byte
|
{
w := new(bytes.Buffer)
m.mu.Lock()
if len(pids) == 0 {
for _, p := range m.entries {
_, _ = w.WriteString(p.toXML())
}
} else {
for _, id := range pids {
p, ok := m.entries[id]
if !ok {
continue
}
_, _ = w.WriteString(p.toXML())
}
}
m.mu.Unlock()
return w.Bytes()
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L359-L424
|
go
|
train
|
// Stat implements hgfs.FileHandler.Stat
|
func (m *ProcessManager) Stat(u *url.URL) (os.FileInfo, error)
|
// Stat implements hgfs.FileHandler.Stat
func (m *ProcessManager) Stat(u *url.URL) (os.FileInfo, error)
|
{
name := path.Join("/proc", u.Path)
info, err := os.Stat(name)
if err == nil && info.Size() == 0 {
// This is a real /proc file
return &procFileInfo{info}, nil
}
dir, file := path.Split(u.Path)
pid, err := strconv.ParseInt(path.Base(dir), 10, 64)
if err != nil {
return nil, os.ErrNotExist
}
m.mu.Lock()
p := m.entries[pid]
m.mu.Unlock()
if p == nil || p.IO == nil {
return nil, os.ErrNotExist
}
pf := &ProcessFile{
name: name,
Closer: ioutil.NopCloser(nil), // via hgfs, nop for stdout and stderr
}
var r *bytes.Buffer
switch file {
case "stdin":
pf.Writer = p.IO.In.Writer
pf.Closer = p.IO.In.Closer
return pf, nil
case "stdout":
r = p.IO.Out
case "stderr":
r = p.IO.Err
default:
return nil, os.ErrNotExist
}
select {
case <-p.ctx.Done():
case <-time.After(time.Second):
// The vmx guest RPC calls are queue based, serialized on the vmx side.
// There are 5 seconds between "ping" RPC calls and after a few misses,
// the vmx considers tools as not running. In this case, the vmx would timeout
// a file transfer after 60 seconds.
//
// vix.FileAccessError is converted to a CannotAccessFile fault,
// so the client can choose to retry the transfer in this case.
// Would have preferred vix.ObjectIsBusy (EBUSY), but VC/ESX converts that
// to a general SystemErrorFault with nothing but a localized string message
// to check against: "<reason>vix error codes = (5, 0).</reason>"
// Is standard vmware-tools, EACCES is converted to a CannotAccessFile fault.
return nil, vix.Error(vix.FileAccessError)
}
pf.Reader = r
pf.size = r.Len()
return pf, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L427-L451
|
go
|
train
|
// Open implements hgfs.FileHandler.Open
|
func (m *ProcessManager) Open(u *url.URL, mode int32) (hgfs.File, error)
|
// Open implements hgfs.FileHandler.Open
func (m *ProcessManager) Open(u *url.URL, mode int32) (hgfs.File, error)
|
{
info, err := m.Stat(u)
if err != nil {
return nil, err
}
pinfo, ok := info.(*ProcessFile)
if !ok {
return nil, os.ErrNotExist // fall through to default os.Open
}
switch path.Base(u.Path) {
case "stdin":
if mode != hgfs.OpenModeWriteOnly {
return nil, vix.Error(vix.InvalidArg)
}
case "stdout", "stderr":
if mode != hgfs.OpenModeReadOnly {
return nil, vix.Error(vix.InvalidArg)
}
}
return pinfo, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L465-L472
|
go
|
train
|
// NewProcessFunc creates a new Process, where the Start function calls the given run function within a goroutine.
// The Wait function waits for the goroutine to finish and returns the error returned by run.
// The run ctx param may be used to return early via the ProcessManager.Kill method.
// The run args command is that of the VixMsgStartProgramRequest.Arguments field.
|
func NewProcessFunc(run func(ctx context.Context, args string) error) *Process
|
// NewProcessFunc creates a new Process, where the Start function calls the given run function within a goroutine.
// The Wait function waits for the goroutine to finish and returns the error returned by run.
// The run ctx param may be used to return early via the ProcessManager.Kill method.
// The run args command is that of the VixMsgStartProgramRequest.Arguments field.
func NewProcessFunc(run func(ctx context.Context, args string) error) *Process
|
{
f := &processFunc{run: run}
return &Process{
Start: f.start,
Wait: f.wait,
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L525-L532
|
go
|
train
|
// NewProcess creates a new Process, where the Start function use exec.CommandContext to create and start the process.
// The Wait function waits for the process to finish and returns the error returned by exec.Cmd.Wait().
// Prior to Wait returning, the exec.Cmd.Wait() error is used to set the ProcessState.ExitCode, if error is of type exec.ExitError.
// The ctx param may be used to kill the process via the ProcessManager.Kill method.
// The VixMsgStartProgramRequest param fields are mapped to the exec.Cmd counterpart fields.
// Processes are started within a sub-shell, allowing for i/o redirection, just as with the C version of vmware-tools.
|
func NewProcess() *Process
|
// NewProcess creates a new Process, where the Start function use exec.CommandContext to create and start the process.
// The Wait function waits for the process to finish and returns the error returned by exec.Cmd.Wait().
// Prior to Wait returning, the exec.Cmd.Wait() error is used to set the ProcessState.ExitCode, if error is of type exec.ExitError.
// The ctx param may be used to kill the process via the ProcessManager.Kill method.
// The VixMsgStartProgramRequest param fields are mapped to the exec.Cmd counterpart fields.
// Processes are started within a sub-shell, allowing for i/o redirection, just as with the C version of vmware-tools.
func NewProcess() *Process
|
{
c := new(processCmd)
return &Process{
Start: c.start,
Wait: c.wait,
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
toolbox/process.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L593-L631
|
go
|
train
|
// NewProcessRoundTrip starts a Go function to implement a toolbox backed http.RoundTripper
|
func NewProcessRoundTrip() *Process
|
// NewProcessRoundTrip starts a Go function to implement a toolbox backed http.RoundTripper
func NewProcessRoundTrip() *Process
|
{
return NewProcessFunc(func(ctx context.Context, host string) error {
p, _ := ctx.Value(ProcessFuncIO).(*ProcessIO)
closers := []io.Closer{p.In.Closer}
defer func() {
for _, c := range closers {
_ = c.Close()
}
}()
c, err := new(net.Dialer).DialContext(ctx, "tcp", host)
if err != nil {
return err
}
closers = append(closers, c)
go func() {
<-ctx.Done()
if ctx.Err() == context.DeadlineExceeded {
_ = c.Close()
}
}()
_, err = io.Copy(c, p.In.Reader)
if err != nil {
return err
}
_, err = io.Copy(p.Out, c)
if err != nil {
return err
}
return nil
}).WithIO()
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/progress/reader.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/reader.go#L101-L122
|
go
|
train
|
// Read calls the Read function on the underlying io.Reader. Additionally,
// every read causes a progress report to be sent to the progress reader's
// underlying channel.
|
func (r *reader) Read(b []byte) (int, error)
|
// Read calls the Read function on the underlying io.Reader. Additionally,
// every read causes a progress report to be sent to the progress reader's
// underlying channel.
func (r *reader) Read(b []byte) (int, error)
|
{
n, err := r.r.Read(b)
r.pos += int64(n)
if err != nil && err != io.EOF {
return n, err
}
q := readerReport{
t: time.Now(),
pos: r.pos,
size: r.size,
bps: &r.bps,
}
select {
case r.ch <- q:
case <-r.ctx.Done():
}
return n, err
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/progress/reader.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/reader.go#L126-L140
|
go
|
train
|
// Done marks the progress reader as done, optionally including an error in the
// progress report. After sending it, the underlying channel is closed.
|
func (r *reader) Done(err error)
|
// Done marks the progress reader as done, optionally including an error in the
// progress report. After sending it, the underlying channel is closed.
func (r *reader) Done(err error)
|
{
q := readerReport{
t: time.Now(),
pos: r.pos,
size: r.size,
bps: &r.bps,
err: err,
}
select {
case r.ch <- q:
close(r.ch)
case <-r.ctx.Done():
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/progress/reader.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/reader.go#L143-L151
|
go
|
train
|
// newBpsLoop returns a sink that monitors and stores throughput.
|
func newBpsLoop(dst *uint64) SinkFunc
|
// newBpsLoop returns a sink that monitors and stores throughput.
func newBpsLoop(dst *uint64) SinkFunc
|
{
fn := func() chan<- Report {
sink := make(chan Report)
go bpsLoop(sink, dst)
return sink
}
return fn
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vmdk/import.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vmdk/import.go#L61-L108
|
go
|
train
|
// stat looks at the vmdk header to make sure the format is streamOptimized and
// extracts the disk capacity required to properly generate the ovf descriptor.
|
func stat(name string) (*info, error)
|
// stat looks at the vmdk header to make sure the format is streamOptimized and
// extracts the disk capacity required to properly generate the ovf descriptor.
func stat(name string) (*info, error)
|
{
f, err := os.Open(filepath.Clean(name))
if err != nil {
return nil, err
}
var di info
var buf bytes.Buffer
_, err = io.CopyN(&buf, f, int64(binary.Size(di.Header)))
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
err = binary.Read(&buf, binary.LittleEndian, &di.Header)
if err != nil {
return nil, err
}
if di.Header.MagicNumber != 0x564d444b { // SPARSE_MAGICNUMBER
return nil, ErrInvalidFormat
}
if di.Header.Flags&(1<<16) == 0 { // SPARSEFLAG_COMPRESSED
// Needs to be converted, for example:
// vmware-vdiskmanager -r src.vmdk -t 5 dst.vmdk
// qemu-img convert -O vmdk -o subformat=streamOptimized src.vmdk dst.vmdk
return nil, ErrInvalidFormat
}
di.Capacity = di.Header.Capacity * 512 // VMDK_SECTOR_SIZE
di.Size = fi.Size()
di.Name = filepath.Base(name)
di.ImportName = strings.TrimSuffix(di.Name, ".vmdk")
return &di, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vmdk/import.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vmdk/import.go#L178-L192
|
go
|
train
|
// ovf returns an expanded descriptor template
|
func (di *info) ovf() (string, error)
|
// ovf returns an expanded descriptor template
func (di *info) ovf() (string, error)
|
{
var buf bytes.Buffer
tmpl, err := template.New("ovf").Parse(ovfenv)
if err != nil {
return "", err
}
err = tmpl.Execute(&buf, di)
if err != nil {
return "", err
}
return buf.String(), nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vmdk/import.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vmdk/import.go#L208-L342
|
go
|
train
|
// Import uploads a local vmdk file specified by name to the given datastore.
|
func Import(ctx context.Context, c *vim25.Client, name string, datastore *object.Datastore, p ImportParams) error
|
// Import uploads a local vmdk file specified by name to the given datastore.
func Import(ctx context.Context, c *vim25.Client, name string, datastore *object.Datastore, p ImportParams) error
|
{
m := ovf.NewManager(c)
fm := datastore.NewFileManager(p.Datacenter, p.Force)
disk, err := stat(name)
if err != nil {
return err
}
var rename string
p.Path = strings.TrimSuffix(p.Path, "/")
if p.Path != "" {
disk.ImportName = p.Path
rename = path.Join(disk.ImportName, disk.Name)
}
// "target" is the path that will be created by ImportVApp()
// ImportVApp uses the same name for the VM and the disk.
target := fmt.Sprintf("%s/%s.vmdk", disk.ImportName, disk.ImportName)
if _, err = datastore.Stat(ctx, target); err == nil {
if p.Force {
// If we don't delete, the nfc upload adds a file name suffix
if err = fm.Delete(ctx, target); err != nil {
return err
}
} else {
return fmt.Errorf("%s: %s", os.ErrExist, datastore.Path(target))
}
}
// If we need to rename at the end, check if the file exists early unless Force.
if !p.Force && rename != "" {
if _, err = datastore.Stat(ctx, rename); err == nil {
return fmt.Errorf("%s: %s", os.ErrExist, datastore.Path(rename))
}
}
// Expand the ovf template
descriptor, err := disk.ovf()
if err != nil {
return err
}
pool := p.Pool // TODO: use datastore to derive a default
folder := p.Folder // TODO: use datacenter to derive a default
kind := p.Type
if kind == "" {
kind = types.VirtualDiskTypeThin
}
params := types.OvfCreateImportSpecParams{
DiskProvisioning: string(kind),
EntityName: disk.ImportName,
}
spec, err := m.CreateImportSpec(ctx, descriptor, pool, datastore, params)
if err != nil {
return err
}
if spec.Error != nil {
return errors.New(spec.Error[0].LocalizedMessage)
}
lease, err := pool.ImportVApp(ctx, spec.ImportSpec, folder, p.Host)
if err != nil {
return err
}
info, err := lease.Wait(ctx, spec.FileItem)
if err != nil {
return err
}
f, err := os.Open(filepath.Clean(name))
if err != nil {
return err
}
opts := soap.Upload{
ContentLength: disk.Size,
Progress: p.Logger,
}
u := lease.StartUpdater(ctx, info)
defer u.Done()
item := info.Items[0] // we only have 1 disk to upload
err = lease.Upload(ctx, item, f, opts)
if err != nil {
return err
}
err = f.Close()
if err != nil {
return err
}
if err = lease.Complete(ctx); err != nil {
return err
}
// ImportVApp created a VM, here we detach the vmdk, then delete the VM.
vm := object.NewVirtualMachine(c, info.Entity)
device, err := vm.Device(ctx)
if err != nil {
return err
}
device = device.SelectByType((*types.VirtualDisk)(nil))
err = vm.RemoveDevice(ctx, true, device...)
if err != nil {
return err
}
task, err := vm.Destroy(ctx)
if err != nil {
return err
}
if err = task.Wait(ctx); err != nil {
return err
}
if rename == "" {
return nil
}
return fm.Move(ctx, target, rename)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
examples/examples.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/examples/examples.go#L33-L40
|
go
|
train
|
// getEnvString returns string from environment variable.
|
func getEnvString(v string, def string) string
|
// getEnvString returns string from environment variable.
func getEnvString(v string, def string) string
|
{
r := os.Getenv(v)
if r == "" {
return def
}
return r
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
examples/examples.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/examples/examples.go#L43-L55
|
go
|
train
|
// getEnvBool returns boolean from environment variable.
|
func getEnvBool(v string, def bool) bool
|
// getEnvBool returns boolean from environment variable.
func getEnvBool(v string, def bool) bool
|
{
r := os.Getenv(v)
if r == "" {
return def
}
switch strings.ToLower(r[0:1]) {
case "t", "y", "1":
return true
}
return false
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
examples/examples.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/examples/examples.go#L103-L117
|
go
|
train
|
// NewClient creates a govmomi.Client for use in the examples
|
func NewClient(ctx context.Context) (*govmomi.Client, error)
|
// NewClient creates a govmomi.Client for use in the examples
func NewClient(ctx context.Context) (*govmomi.Client, error)
|
{
flag.Parse()
// Parse URL from string
u, err := soap.ParseURL(*urlFlag)
if err != nil {
return nil, err
}
// Override username and/or password as required
processOverride(u)
// Connect and log in to ESX or vCenter
return govmomi.NewClient(ctx, u, *insecureFlag)
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
task/wait.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/task/wait.go#L117-L132
|
go
|
train
|
// Wait waits for a task to finish with either success or failure. It does so
// by waiting for the "info" property of task managed object to change. The
// function returns when it finds the task in the "success" or "error" state.
// In the former case, the return value is nil. In the latter case the return
// value is an instance of this package's Error struct.
//
// Any error returned while waiting for property changes causes the function to
// return immediately and propagate the error.
//
// If the progress.Sinker argument is specified, any progress updates for the
// task are sent here. The completion percentage is passed through directly.
// The detail for the progress update is set to an empty string. If the task
// finishes in the error state, the error instance is passed through as well.
// Note that this error is the same error that is returned by this function.
//
|
func Wait(ctx context.Context, ref types.ManagedObjectReference, pc *property.Collector, s progress.Sinker) (*types.TaskInfo, error)
|
// Wait waits for a task to finish with either success or failure. It does so
// by waiting for the "info" property of task managed object to change. The
// function returns when it finds the task in the "success" or "error" state.
// In the former case, the return value is nil. In the latter case the return
// value is an instance of this package's Error struct.
//
// Any error returned while waiting for property changes causes the function to
// return immediately and propagate the error.
//
// If the progress.Sinker argument is specified, any progress updates for the
// task are sent here. The completion percentage is passed through directly.
// The detail for the progress update is set to an empty string. If the task
// finishes in the error state, the error instance is passed through as well.
// Note that this error is the same error that is returned by this function.
//
func Wait(ctx context.Context, ref types.ManagedObjectReference, pc *property.Collector, s progress.Sinker) (*types.TaskInfo, error)
|
{
cb := &taskCallback{}
// Include progress sink if specified
if s != nil {
cb.ch = s.Sink()
defer close(cb.ch)
}
err := property.Wait(ctx, pc, ref, []string{"info"}, cb.fn)
if err != nil {
return nil, err
}
return cb.info, cb.err
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L49-L56
|
go
|
train
|
// Open opens the named file relative to the Datastore.
|
func (d Datastore) Open(ctx context.Context, name string) (*DatastoreFile, error)
|
// Open opens the named file relative to the Datastore.
func (d Datastore) Open(ctx context.Context, name string) (*DatastoreFile, error)
|
{
return &DatastoreFile{
d: d,
name: name,
length: -1,
ctx: ctx,
}, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L59-L87
|
go
|
train
|
// Read reads up to len(b) bytes from the DatastoreFile.
|
func (f *DatastoreFile) Read(b []byte) (int, error)
|
// Read reads up to len(b) bytes from the DatastoreFile.
func (f *DatastoreFile) Read(b []byte) (int, error)
|
{
if f.offset.read != f.offset.seek {
// A Seek() call changed the offset, we need to issue a new GET
_ = f.Close()
f.offset.read = f.offset.seek
} else if f.buf != nil {
// f.buf + f behaves like an io.MultiReader
n, err := f.buf.Read(b)
if err == io.EOF {
f.buf = nil // buffer has been drained
}
if n > 0 {
return n, nil
}
}
body, err := f.get()
if err != nil {
return 0, err
}
n, err := body.Read(b)
f.offset.read += int64(n)
f.offset.seek += int64(n)
return n, err
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L90-L101
|
go
|
train
|
// Close closes the DatastoreFile.
|
func (f *DatastoreFile) Close() error
|
// Close closes the DatastoreFile.
func (f *DatastoreFile) Close() error
|
{
var err error
if f.body != nil {
err = f.body.Close()
f.body = nil
}
f.buf = nil
return err
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L104-L129
|
go
|
train
|
// Seek sets the offset for the next Read on the DatastoreFile.
|
func (f *DatastoreFile) Seek(offset int64, whence int) (int64, error)
|
// Seek sets the offset for the next Read on the DatastoreFile.
func (f *DatastoreFile) Seek(offset int64, whence int) (int64, error)
|
{
switch whence {
case io.SeekStart:
case io.SeekCurrent:
offset += f.offset.seek
case io.SeekEnd:
if f.length < 0 {
_, err := f.Stat()
if err != nil {
return 0, err
}
}
offset += f.length
default:
return 0, errors.New("Seek: invalid whence")
}
// allow negative SeekStart for initial Range request
if offset < 0 {
return 0, errors.New("Seek: invalid offset")
}
f.offset.seek = offset
return offset, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L168-L187
|
go
|
train
|
// Stat returns the os.FileInfo interface describing file.
|
func (f *DatastoreFile) Stat() (os.FileInfo, error)
|
// Stat returns the os.FileInfo interface describing file.
func (f *DatastoreFile) Stat() (os.FileInfo, error)
|
{
// TODO: consider using Datastore.Stat() instead
u, p, err := f.d.downloadTicket(f.ctx, f.name, &soap.Download{Method: "HEAD"})
if err != nil {
return nil, err
}
res, err := f.d.Client().DownloadRequest(f.ctx, u, p)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, statusError(res)
}
f.length = res.ContentLength
return &fileStat{f, res.Header}, nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L260-L262
|
go
|
train
|
// Tail seeks to the position of the last N lines of the file.
|
func (f *DatastoreFile) Tail(n int) error
|
// Tail seeks to the position of the last N lines of the file.
func (f *DatastoreFile) Tail(n int) error
|
{
return f.TailFunc(n, func(line int, _ string) bool { return n > line })
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L266-L343
|
go
|
train
|
// TailFunc will seek backwards in the datastore file until it hits a line that does
// not satisfy the supplied `include` function.
|
func (f *DatastoreFile) TailFunc(lines int, include func(line int, message string) bool) error
|
// TailFunc will seek backwards in the datastore file until it hits a line that does
// not satisfy the supplied `include` function.
func (f *DatastoreFile) TailFunc(lines int, include func(line int, message string) bool) error
|
{
// Read the file in reverse using bsize chunks
const bsize = int64(1024 * 16)
fsize, err := f.Seek(0, io.SeekEnd)
if err != nil {
return err
}
if lines == 0 {
return nil
}
chunk := int64(-1)
buf := bytes.NewBuffer(make([]byte, 0, bsize))
line := 0
for {
var eof bool
var pos int64
nread := bsize
offset := chunk * bsize
remain := fsize + offset
if remain < 0 {
if pos, err = f.Seek(0, io.SeekStart); err != nil {
return err
}
nread = bsize + remain
eof = true
} else if pos, err = f.Seek(offset, io.SeekEnd); err != nil {
return err
}
if _, err = io.CopyN(buf, f, nread); err != nil {
if err != io.EOF {
return err
}
}
b := buf.Bytes()
idx, done := lastIndexLines(b, &line, include)
if done {
if chunk == -1 {
// We found all N lines in the last chunk of the file.
// The seek offset is also now at the current end of file.
// Save this buffer to avoid another GET request when Read() is called.
buf.Next(int(idx + 1))
f.buf = buf
return nil
}
if _, err = f.Seek(pos+idx+1, io.SeekStart); err != nil {
return err
}
break
}
if eof {
if remain < 0 {
// We found < N lines in the entire file, so seek to the start.
_, _ = f.Seek(0, io.SeekStart)
}
break
}
chunk--
buf.Reset()
}
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L354-L397
|
go
|
train
|
// Read reads up to len(b) bytes from the DatastoreFile being followed.
// This method will block until data is read, an error other than io.EOF is returned or Close() is called.
|
func (f *followDatastoreFile) Read(p []byte) (int, error)
|
// Read reads up to len(b) bytes from the DatastoreFile being followed.
// This method will block until data is read, an error other than io.EOF is returned or Close() is called.
func (f *followDatastoreFile) Read(p []byte) (int, error)
|
{
offset := f.r.offset.seek
stop := false
for {
n, err := f.r.Read(p)
if err != nil && err == io.EOF {
_ = f.r.Close() // GET request body has been drained.
if stop {
return n, err
}
err = nil
}
if n > 0 {
return n, err
}
select {
case <-f.c:
// Wake up and stop polling once the body has been drained
stop = true
case <-time.After(f.i):
}
info, serr := f.r.Stat()
if serr != nil {
// Return EOF rather than 404 if the file goes away
if serr == os.ErrNotExist {
_ = f.r.Close()
return 0, io.EOF
}
return 0, serr
}
if info.Size() < offset {
// assume file has be truncated
offset, err = f.r.Seek(0, io.SeekStart)
if err != nil {
return 0, err
}
}
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L400-L403
|
go
|
train
|
// Close will stop Follow polling and close the underlying DatastoreFile.
|
func (f *followDatastoreFile) Close() error
|
// Close will stop Follow polling and close the underlying DatastoreFile.
func (f *followDatastoreFile) Close() error
|
{
f.o.Do(func() { close(f.c) })
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/datastore_file.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L406-L412
|
go
|
train
|
// Follow returns an io.ReadCloser to stream the file contents as data is appended.
|
func (f *DatastoreFile) Follow(interval time.Duration) io.ReadCloser
|
// Follow returns an io.ReadCloser to stream the file contents as data is appended.
func (f *DatastoreFile) Follow(interval time.Duration) io.ReadCloser
|
{
return &followDatastoreFile{
r: f,
c: make(chan struct{}),
i: interval,
}
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/host_certificate_info.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L50-L75
|
go
|
train
|
// FromCertificate converts x509.Certificate to HostCertificateInfo
|
func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo
|
// FromCertificate converts x509.Certificate to HostCertificateInfo
func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo
|
{
info.Certificate = cert
info.subjectName = &cert.Subject
info.issuerName = &cert.Issuer
info.Issuer = info.fromName(info.issuerName)
info.NotBefore = &cert.NotBefore
info.NotAfter = &cert.NotAfter
info.Subject = info.fromName(info.subjectName)
info.ThumbprintSHA1 = soap.ThumbprintSHA1(cert)
// SHA-256 for info purposes only, API fields all use SHA-1
sum := sha256.Sum256(cert.Raw)
hex := make([]string, len(sum))
for i, b := range sum {
hex[i] = fmt.Sprintf("%02X", b)
}
info.ThumbprintSHA256 = strings.Join(hex, ":")
if info.Status == "" {
info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusUnknown)
}
return info
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/host_certificate_info.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L81-L111
|
go
|
train
|
// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState. If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
|
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error
|
// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState. If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error
|
{
addr := u.Host
if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
addr += ":443"
}
conn, err := tls.Dial("tcp", addr, config)
if err != nil {
switch err.(type) {
case x509.UnknownAuthorityError:
case x509.HostnameError:
default:
return err
}
info.Err = err
conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return err
}
} else {
info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
}
state := conn.ConnectionState()
_ = conn.Close()
info.FromCertificate(state.PeerCertificates[0])
return nil
}
|
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
object/host_certificate_info.go
|
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L187-L193
|
go
|
train
|
// SubjectName parses Subject into a pkix.Name
|
func (info *HostCertificateInfo) SubjectName() *pkix.Name
|
// SubjectName parses Subject into a pkix.Name
func (info *HostCertificateInfo) SubjectName() *pkix.Name
|
{
if info.subjectName != nil {
return info.subjectName
}
return info.toName(info.Subject)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.