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 | vapi/tags/categories.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L96-L109 | go | train | // UpdateCategory can update one or more of the AssociableTypes, Cardinality, Description and Name fields. | func (c *Manager) UpdateCategory(ctx context.Context, category *Category) error | // UpdateCategory can update one or more of the AssociableTypes, Cardinality, Description and Name fields.
func (c *Manager) UpdateCategory(ctx context.Context, category *Category) error | {
spec := struct {
Category Category `json:"update_spec"`
}{
Category: Category{
AssociableTypes: category.AssociableTypes,
Cardinality: category.Cardinality,
Description: category.Description,
Name: category.Name,
},
}
url := internal.URL(c, internal.CategoryPath).WithID(category.ID)
return c.Do(ctx, url.Request(http.MethodPatch, spec), nil)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/tags/categories.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L112-L115 | go | train | // DeleteCategory deletes an existing category. | func (c *Manager) DeleteCategory(ctx context.Context, category *Category) error | // DeleteCategory deletes an existing category.
func (c *Manager) DeleteCategory(ctx context.Context, category *Category) error | {
url := internal.URL(c, internal.CategoryPath).WithID(category.ID)
return c.Do(ctx, url.Request(http.MethodDelete), nil)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/tags/categories.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L119-L135 | go | train | // GetCategory fetches the category information for the given identifier.
// The id parameter can be a Category ID or Category Name. | func (c *Manager) GetCategory(ctx context.Context, id string) (*Category, error) | // GetCategory fetches the category information for the given identifier.
// The id parameter can be a Category ID or Category Name.
func (c *Manager) GetCategory(ctx context.Context, id string) (*Category, error) | {
if isName(id) {
cat, err := c.GetCategories(ctx)
if err != nil {
return nil, err
}
for i := range cat {
if cat[i].Name == id {
return &cat[i], nil
}
}
}
url := internal.URL(c, internal.CategoryPath).WithID(id)
var res Category
return &res, c.Do(ctx, url.Request(http.MethodGet), &res)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/tags/categories.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L138-L142 | go | train | // ListCategories returns all category IDs in the system. | func (c *Manager) ListCategories(ctx context.Context) ([]string, error) | // ListCategories returns all category IDs in the system.
func (c *Manager) ListCategories(ctx context.Context) ([]string, error) | {
url := internal.URL(c, internal.CategoryPath)
var res []string
return res, c.Do(ctx, url.Request(http.MethodGet), &res)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/tags/categories.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/categories.go#L145-L162 | go | train | // GetCategories fetches an array of category information in the system. | func (c *Manager) GetCategories(ctx context.Context) ([]Category, error) | // GetCategories fetches an array of category information in the system.
func (c *Manager) GetCategories(ctx context.Context) ([]Category, error) | {
ids, err := c.ListCategories(ctx)
if err != nil {
return nil, fmt.Errorf("list categories: %s", err)
}
var categories []Category
for _, id := range ids {
category, err := c.GetCategory(ctx, id)
if err != nil {
return nil, fmt.Errorf("get category %s: %s", id, err)
}
categories = append(categories, *category)
}
return categories, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/mo/ancestors.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/ancestors.go#L29-L137 | go | train | // Ancestors returns the entire ancestry tree of a specified managed object.
// The return value includes the root node and the specified object itself. | func Ancestors(ctx context.Context, rt soap.RoundTripper, pc, obj types.ManagedObjectReference) ([]ManagedEntity, error) | // Ancestors returns the entire ancestry tree of a specified managed object.
// The return value includes the root node and the specified object itself.
func Ancestors(ctx context.Context, rt soap.RoundTripper, pc, obj types.ManagedObjectReference) ([]ManagedEntity, error) | {
ospec := types.ObjectSpec{
Obj: obj,
SelectSet: []types.BaseSelectionSpec{
&types.TraversalSpec{
SelectionSpec: types.SelectionSpec{Name: "traverseParent"},
Type: "ManagedEntity",
Path: "parent",
Skip: types.NewBool(false),
SelectSet: []types.BaseSelectionSpec{
&types.SelectionSpec{Name: "traverseParent"},
},
},
&types.TraversalSpec{
SelectionSpec: types.SelectionSpec{},
Type: "VirtualMachine",
Path: "parentVApp",
Skip: types.NewBool(false),
SelectSet: []types.BaseSelectionSpec{
&types.SelectionSpec{Name: "traverseParent"},
},
},
},
Skip: types.NewBool(false),
}
pspec := []types.PropertySpec{
{
Type: "ManagedEntity",
PathSet: []string{"name", "parent"},
},
{
Type: "VirtualMachine",
PathSet: []string{"parentVApp"},
},
}
req := types.RetrieveProperties{
This: pc,
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspec,
},
},
}
var ifaces []interface{}
err := RetrievePropertiesForRequest(ctx, rt, req, &ifaces)
if err != nil {
return nil, err
}
var out []ManagedEntity
// Build ancestry tree by iteratively finding a new child.
for len(out) < len(ifaces) {
var find types.ManagedObjectReference
if len(out) > 0 {
find = out[len(out)-1].Self
}
// Find entity we're looking for given the last entity in the current tree.
for _, iface := range ifaces {
me := iface.(IsManagedEntity).GetManagedEntity()
if me.Name == "" {
// The types below have their own 'Name' field, so ManagedEntity.Name (me.Name) is empty.
// We only hit this case when the 'obj' param is one of these types.
// In most cases, 'obj' is a Folder so Name isn't collected in this call.
switch x := iface.(type) {
case Network:
me.Name = x.Name
case DistributedVirtualSwitch:
me.Name = x.Name
case DistributedVirtualPortgroup:
me.Name = x.Name
case OpaqueNetwork:
me.Name = x.Name
default:
// ManagedEntity always has a Name, if we hit this point we missed a case above.
panic(fmt.Sprintf("%#v Name is empty", me.Reference()))
}
}
if me.Parent == nil {
// Special case for VirtualMachine within VirtualApp,
// unlikely to hit this other than via Finder.Element()
switch x := iface.(type) {
case VirtualMachine:
me.Parent = x.ParentVApp
}
}
if me.Parent == nil {
out = append(out, me)
break
}
if *me.Parent == find {
out = append(out, me)
break
}
}
}
return out, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L85-L140 | go | train | // New creates a vAPI simulator. | func New(u *url.URL, settings []vim.BaseOptionValue) (string, http.Handler) | // New creates a vAPI simulator.
func New(u *url.URL, settings []vim.BaseOptionValue) (string, http.Handler) | {
s := &handler{
ServeMux: http.NewServeMux(),
URL: *u,
Category: make(map[string]*tags.Category),
Tag: make(map[string]*tags.Tag),
Association: make(map[string]map[internal.AssociatedObject]bool),
Session: make(map[string]*session),
Library: make(map[string]content),
Update: make(map[string]update),
}
handlers := []struct {
p string
m http.HandlerFunc
}{
{internal.SessionPath, s.session},
{internal.CategoryPath, s.category},
{internal.CategoryPath + "/", s.categoryID},
{internal.TagPath, s.tag},
{internal.TagPath + "/", s.tagID},
{internal.AssociationPath, s.association},
{internal.AssociationPath + "/", s.associationID},
{internal.LibraryPath, s.library},
{internal.LocalLibraryPath, s.library},
{internal.LibraryPath + "/", s.libraryID},
{internal.LocalLibraryPath + "/", s.libraryID},
{internal.LibraryItemPath, s.libraryItem},
{internal.LibraryItemPath + "/", s.libraryItemID},
{internal.LibraryItemUpdateSession, s.libraryItemUpdateSession},
{internal.LibraryItemUpdateSession + "/", s.libraryItemUpdateSessionID},
{internal.LibraryItemUpdateSessionFile, s.libraryItemUpdateSessionFile},
{internal.LibraryItemUpdateSessionFile + "/", s.libraryItemUpdateSessionFileID},
{internal.LibraryItemAdd + "/", s.libraryItemAdd},
{internal.LibraryItemFilePath, s.libraryItemFile},
{internal.LibraryItemFilePath + "/", s.libraryItemFileID},
{internal.VCenterOVFLibraryItem + "/", s.libraryItemDeployID},
}
for i := range handlers {
h := handlers[i]
s.HandleFunc(internal.Path+h.p, func(w http.ResponseWriter, r *http.Request) {
s.Lock()
defer s.Unlock()
if !s.isAuthorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
h.m(w, r)
})
}
return internal.Path + "/", s
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L188-L198 | go | train | // AttachedObjects is meant for internal use via simulator.Registry.tagManager | func (s *handler) AttachedObjects(tag vim.VslmTagEntry) ([]vim.ManagedObjectReference, vim.BaseMethodFault) | // AttachedObjects is meant for internal use via simulator.Registry.tagManager
func (s *handler) AttachedObjects(tag vim.VslmTagEntry) ([]vim.ManagedObjectReference, vim.BaseMethodFault) | {
t := s.findTag(tag)
if t == nil {
return nil, new(vim.NotFound)
}
var ids []vim.ManagedObjectReference
for id := range s.Association[t.ID] {
ids = append(ids, vim.ManagedObjectReference(id))
}
return ids, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L201-L215 | go | train | // AttachedTags is meant for internal use via simulator.Registry.tagManager | func (s *handler) AttachedTags(ref vim.ManagedObjectReference) ([]vim.VslmTagEntry, vim.BaseMethodFault) | // AttachedTags is meant for internal use via simulator.Registry.tagManager
func (s *handler) AttachedTags(ref vim.ManagedObjectReference) ([]vim.VslmTagEntry, vim.BaseMethodFault) | {
oid := internal.AssociatedObject(ref)
var tags []vim.VslmTagEntry
for id, objs := range s.Association {
if objs[oid] {
tag := s.Tag[id]
cat := s.Category[tag.CategoryID]
tags = append(tags, vim.VslmTagEntry{
TagName: tag.Name,
ParentCategoryName: cat.Name,
})
}
}
return tags, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L218-L225 | go | train | // AttachTag is meant for internal use via simulator.Registry.tagManager | func (s *handler) AttachTag(ref vim.ManagedObjectReference, tag vim.VslmTagEntry) vim.BaseMethodFault | // AttachTag is meant for internal use via simulator.Registry.tagManager
func (s *handler) AttachTag(ref vim.ManagedObjectReference, tag vim.VslmTagEntry) vim.BaseMethodFault | {
t := s.findTag(tag)
if t == nil {
return new(vim.NotFound)
}
s.Association[t.ID][internal.AssociatedObject(ref)] = true
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L228-L235 | go | train | // DetachTag is meant for internal use via simulator.Registry.tagManager | func (s *handler) DetachTag(id vim.ManagedObjectReference, tag vim.VslmTagEntry) vim.BaseMethodFault | // DetachTag is meant for internal use via simulator.Registry.tagManager
func (s *handler) DetachTag(id vim.ManagedObjectReference, tag vim.VslmTagEntry) vim.BaseMethodFault | {
t := s.findTag(tag)
if t == nil {
return new(vim.NotFound)
}
delete(s.Association[t.ID], internal.AssociatedObject(id))
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L238-L254 | go | train | // ok responds with http.StatusOK and json encodes val if given. | func (s *handler) ok(w http.ResponseWriter, val ...interface{}) | // ok responds with http.StatusOK and json encodes val if given.
func (s *handler) ok(w http.ResponseWriter, val ...interface{}) | {
w.WriteHeader(http.StatusOK)
if len(val) == 0 {
return
}
err := json.NewEncoder(w).Encode(struct {
Value interface{} `json:"value,omitempty"`
}{
val[0],
})
if err != nil {
log.Panic(err)
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L279-L289 | go | train | // ServeHTTP handles vAPI requests. | func (s *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) | // ServeHTTP handles vAPI requests.
func (s *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) | {
switch r.Method {
case http.MethodPost, http.MethodDelete, http.MethodGet, http.MethodPatch, http.MethodPut:
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
h, _ := s.Handler(r)
h.ServeHTTP(w, r)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/simulator/simulator.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/simulator/simulator.go#L898-L903 | go | train | // libraryPath returns the local Datastore fs path for a Library or Item if id is specified. | func libraryPath(l *library.Library, id string) string | // libraryPath returns the local Datastore fs path for a Library or Item if id is specified.
func libraryPath(l *library.Library, id string) string | {
// DatastoreID (moref) format is "$local-path@$ds-folder-id",
// see simulator.HostDatastoreSystem.CreateLocalDatastore
ds := strings.SplitN(l.Storage[0].DatastoreID, "@", 2)[0]
return path.Join(append([]string{ds, "contentlib-" + l.ID}, id)...)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/library/finder/finder.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/finder/finder.go#L51-L66 | go | train | // Find finds one or more items that match the provided inventory path(s). | func (f *Finder) Find(
ctx context.Context, ipath ...string) ([]FindResult, error) | // Find finds one or more items that match the provided inventory path(s).
func (f *Finder) Find(
ctx context.Context, ipath ...string) ([]FindResult, error) | {
if len(ipath) == 0 {
ipath = []string{""}
}
var result []FindResult
for _, p := range ipath {
results, err := f.find(ctx, p)
if err != nil {
return nil, err
}
result = append(result, results...)
}
return result, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/library/ova.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/library/ova.go#L87-L94 | go | train | // NewOVAFile creates a new OVA file reader | func NewOVAFile(filename string) (*OVAFile, error) | // NewOVAFile creates a new OVA file reader
func NewOVAFile(filename string) (*OVAFile, error) | {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
tarFile := tar.NewReader(f)
return &OVAFile{filename: filename, file: f, tarFile: tarFile}, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/library/ova.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/library/ova.go#L97-L107 | go | train | // Find looks for a filename match in the OVA file | func (of *OVAFile) Find(filename string) (*tar.Header, error) | // Find looks for a filename match in the OVA file
func (of *OVAFile) Find(filename string) (*tar.Header, error) | {
for {
header, err := of.tarFile.Next()
if err == io.EOF {
return nil, err
}
if header.Name == filename {
return header, nil
}
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/library/ova.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/library/ova.go#L115-L120 | go | train | // Read reads from the current file in the OVA file | func (of *OVAFile) Read(b []byte) (int, error) | // Read reads from the current file in the OVA file
func (of *OVAFile) Read(b []byte) (int, error) | {
if of.tarFile == nil {
return 0, io.EOF
}
return of.tarFile.Read(b)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/library/ova.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/library/ova.go#L128-L147 | go | train | // getOVAFileInfo opens an OVA, finds the file entry, and returns both the size and md5 checksum | func getOVAFileInfo(ovafile string, filename string) (int64, string, error) | // getOVAFileInfo opens an OVA, finds the file entry, and returns both the size and md5 checksum
func getOVAFileInfo(ovafile string, filename string) (int64, string, error) | {
of, err := NewOVAFile(ovafile)
if err != nil {
return 0, "", err
}
hdr, err := of.Find(filename)
if err != nil {
return 0, "", err
}
hash := md5.New()
_, err = io.Copy(hash, of)
if err != nil {
return 0, "", err
}
md5String := hex.EncodeToString(hash.Sum(nil)[:16])
return hdr.Size, md5String, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/library/ova.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/library/ova.go#L150-L190 | go | train | // uploadFile will upload a single file from an OVA using the sessionID provided | func uploadFile(ctx context.Context, m *library.Manager, sessionID string, ovafile string, filename string) error | // uploadFile will upload a single file from an OVA using the sessionID provided
func uploadFile(ctx context.Context, m *library.Manager, sessionID string, ovafile string, filename string) error | {
var updateFileInfo library.UpdateFile
fmt.Printf("Uploading %s from %s\n", filename, ovafile)
size, md5String, _ := getOVAFileInfo(ovafile, filename)
// Get the URI for the file upload
updateFileInfo.Name = filename
updateFileInfo.Size = &size
updateFileInfo.SourceType = "PUSH"
updateFileInfo.Checksum = &library.Checksum{
Algorithm: "MD5",
Checksum: md5String,
}
addFileInfo, err := m.AddLibraryItemFile(ctx, sessionID, updateFileInfo)
if err != nil {
return err
}
of, err := NewOVAFile(ovafile)
if err != nil {
return err
}
defer of.Close()
// Setup to point to the OVA file to be transferred
_, err = of.Find(filename)
if err != nil {
return err
}
req, err := http.NewRequest("PUT", addFileInfo.UploadEndpoint.URI, of)
if err != nil {
return err
}
req.Header.Set("vmware-api-session-id", sessionID)
return m.Do(ctx, req, nil)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/folder.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/folder.go#L45-L65 | go | train | // update references when objects are added/removed from a Folder | func (f *Folder) update(o mo.Reference, u func(mo.Reference, *[]types.ManagedObjectReference, types.ManagedObjectReference)) | // update references when objects are added/removed from a Folder
func (f *Folder) update(o mo.Reference, u func(mo.Reference, *[]types.ManagedObjectReference, types.ManagedObjectReference)) | {
ref := o.Reference()
if f.Parent == nil {
return // this is the root folder
}
switch ref.Type {
case "Datacenter", "Folder":
return // nothing to update
}
dc := Map.getEntityDatacenter(f)
switch ref.Type {
case "Network", "DistributedVirtualSwitch", "DistributedVirtualPortgroup":
u(dc, &dc.Network, ref)
case "Datastore":
u(dc, &dc.Datastore, ref)
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/folder.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/folder.go#L260-L273 | go | train | // hostsWithDatastore returns hosts that have access to the given datastore path | func hostsWithDatastore(hosts []types.ManagedObjectReference, path string) []types.ManagedObjectReference | // hostsWithDatastore returns hosts that have access to the given datastore path
func hostsWithDatastore(hosts []types.ManagedObjectReference, path string) []types.ManagedObjectReference | {
attached := hosts[:0]
var p object.DatastorePath
p.FromString(path)
for _, host := range hosts {
h := Map.Get(host).(*HostSystem)
if Map.FindByName(p.Datastore, h.Datastore) != nil {
attached = append(attached, host)
}
}
return attached
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | ovf/env.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/env.go#L72-L79 | go | train | // Marshal marshals Env to xml by using xml.Marshal. | func (e Env) Marshal() (string, error) | // Marshal marshals Env to xml by using xml.Marshal.
func (e Env) Marshal() (string, error) | {
x, err := xml.Marshal(e)
if err != nil {
return "", err
}
return fmt.Sprintf("%s%s", xml.Header, x), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | ovf/env.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/env.go#L83-L99 | go | train | // MarshalManual manually marshals Env to xml suitable for a vApp guest.
// It exists to overcome the lack of expressiveness in Go's XML namespaces. | func (e Env) MarshalManual() string | // MarshalManual manually marshals Env to xml suitable for a vApp guest.
// It exists to overcome the lack of expressiveness in Go's XML namespaces.
func (e Env) MarshalManual() string | {
var buffer bytes.Buffer
buffer.WriteString(xml.Header)
buffer.WriteString(fmt.Sprintf(ovfEnvHeader, e.EsxID))
buffer.WriteString(fmt.Sprintf(ovfEnvPlatformSection, e.Platform.Kind, e.Platform.Version, e.Platform.Vendor, e.Platform.Locale))
buffer.WriteString(fmt.Sprint(ovfEnvPropertyHeader))
for _, p := range e.Property.Properties {
buffer.WriteString(fmt.Sprintf(ovfEnvPropertyEntry, p.Key, p.Value))
}
buffer.WriteString(fmt.Sprint(ovfEnvPropertyFooter))
buffer.WriteString(fmt.Sprint(ovfEnvFooter))
return buffer.String()
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L114-L116 | go | train | // BUG(rsc): Mapping between XML elements and data structures is inherently flawed:
// an XML element is an order-dependent collection of anonymous
// values, while a data structure is an order-independent collection
// of named values.
// See package json for a textual representation more suitable
// to data structures.
// Unmarshal parses the XML-encoded data and stores the result in
// the value pointed to by v, which must be an arbitrary struct,
// slice, or string. Well-formed data that does not fit into v is
// discarded.
//
// Because Unmarshal uses the reflect package, it can only assign
// to exported (upper case) fields. Unmarshal uses a case-sensitive
// comparison to match XML element names to tag values and struct
// field names.
//
// Unmarshal maps an XML element to a struct using the following rules.
// In the rules, the tag of a field refers to the value associated with the
// key 'xml' in the struct field's tag (see the example above).
//
// * If the struct has a field of type []byte or string with tag
// ",innerxml", Unmarshal accumulates the raw XML nested inside the
// element in that field. The rest of the rules still apply.
//
// * If the struct has a field named XMLName of type xml.Name,
// Unmarshal records the element name in that field.
//
// * If the XMLName field has an associated tag of the form
// "name" or "namespace-URL name", the XML element must have
// the given name (and, optionally, name space) or else Unmarshal
// returns an error.
//
// * If the XML element has an attribute whose name matches a
// struct field name with an associated tag containing ",attr" or
// the explicit name in a struct field tag of the form "name,attr",
// Unmarshal records the attribute value in that field.
//
// * If the XML element contains character data, that data is
// accumulated in the first struct field that has tag ",chardata".
// The struct field may have type []byte or string.
// If there is no such field, the character data is discarded.
//
// * If the XML element contains comments, they are accumulated in
// the first struct field that has tag ",comment". The struct
// field may have type []byte or string. If there is no such
// field, the comments are discarded.
//
// * If the XML element contains a sub-element whose name matches
// the prefix of a tag formatted as "a" or "a>b>c", unmarshal
// will descend into the XML structure looking for elements with the
// given names, and will map the innermost elements to that struct
// field. A tag starting with ">" is equivalent to one starting
// with the field name followed by ">".
//
// * If the XML element contains a sub-element whose name matches
// a struct field's XMLName tag and the struct field has no
// explicit name tag as per the previous rule, unmarshal maps
// the sub-element to that struct field.
//
// * If the XML element contains a sub-element whose name matches a
// field without any mode flags (",attr", ",chardata", etc), Unmarshal
// maps the sub-element to that struct field.
//
// * If the XML element contains a sub-element that hasn't matched any
// of the above rules and the struct has a field with tag ",any",
// unmarshal maps the sub-element to that struct field.
//
// * An anonymous struct field is handled as if the fields of its
// value were part of the outer struct.
//
// * A struct field with tag "-" is never unmarshalled into.
//
// Unmarshal maps an XML element to a string or []byte by saving the
// concatenation of that element's character data in the string or
// []byte. The saved []byte is never nil.
//
// Unmarshal maps an attribute value to a string or []byte by saving
// the value in the string or slice.
//
// Unmarshal maps an XML element to a slice by extending the length of
// the slice and mapping the element to the newly created value.
//
// Unmarshal maps an XML element or attribute value to a bool by
// setting it to the boolean value represented by the string.
//
// Unmarshal maps an XML element or attribute value to an integer or
// floating-point field by setting the field to the result of
// interpreting the string value in decimal. There is no check for
// overflow.
//
// Unmarshal maps an XML element to an xml.Name by recording the
// element name.
//
// Unmarshal maps an XML element to a pointer by setting the pointer
// to a freshly allocated value and then mapping the element to that value.
// | func Unmarshal(data []byte, v interface{}) error | // BUG(rsc): Mapping between XML elements and data structures is inherently flawed:
// an XML element is an order-dependent collection of anonymous
// values, while a data structure is an order-independent collection
// of named values.
// See package json for a textual representation more suitable
// to data structures.
// Unmarshal parses the XML-encoded data and stores the result in
// the value pointed to by v, which must be an arbitrary struct,
// slice, or string. Well-formed data that does not fit into v is
// discarded.
//
// Because Unmarshal uses the reflect package, it can only assign
// to exported (upper case) fields. Unmarshal uses a case-sensitive
// comparison to match XML element names to tag values and struct
// field names.
//
// Unmarshal maps an XML element to a struct using the following rules.
// In the rules, the tag of a field refers to the value associated with the
// key 'xml' in the struct field's tag (see the example above).
//
// * If the struct has a field of type []byte or string with tag
// ",innerxml", Unmarshal accumulates the raw XML nested inside the
// element in that field. The rest of the rules still apply.
//
// * If the struct has a field named XMLName of type xml.Name,
// Unmarshal records the element name in that field.
//
// * If the XMLName field has an associated tag of the form
// "name" or "namespace-URL name", the XML element must have
// the given name (and, optionally, name space) or else Unmarshal
// returns an error.
//
// * If the XML element has an attribute whose name matches a
// struct field name with an associated tag containing ",attr" or
// the explicit name in a struct field tag of the form "name,attr",
// Unmarshal records the attribute value in that field.
//
// * If the XML element contains character data, that data is
// accumulated in the first struct field that has tag ",chardata".
// The struct field may have type []byte or string.
// If there is no such field, the character data is discarded.
//
// * If the XML element contains comments, they are accumulated in
// the first struct field that has tag ",comment". The struct
// field may have type []byte or string. If there is no such
// field, the comments are discarded.
//
// * If the XML element contains a sub-element whose name matches
// the prefix of a tag formatted as "a" or "a>b>c", unmarshal
// will descend into the XML structure looking for elements with the
// given names, and will map the innermost elements to that struct
// field. A tag starting with ">" is equivalent to one starting
// with the field name followed by ">".
//
// * If the XML element contains a sub-element whose name matches
// a struct field's XMLName tag and the struct field has no
// explicit name tag as per the previous rule, unmarshal maps
// the sub-element to that struct field.
//
// * If the XML element contains a sub-element whose name matches a
// field without any mode flags (",attr", ",chardata", etc), Unmarshal
// maps the sub-element to that struct field.
//
// * If the XML element contains a sub-element that hasn't matched any
// of the above rules and the struct has a field with tag ",any",
// unmarshal maps the sub-element to that struct field.
//
// * An anonymous struct field is handled as if the fields of its
// value were part of the outer struct.
//
// * A struct field with tag "-" is never unmarshalled into.
//
// Unmarshal maps an XML element to a string or []byte by saving the
// concatenation of that element's character data in the string or
// []byte. The saved []byte is never nil.
//
// Unmarshal maps an attribute value to a string or []byte by saving
// the value in the string or slice.
//
// Unmarshal maps an XML element to a slice by extending the length of
// the slice and mapping the element to the newly created value.
//
// Unmarshal maps an XML element or attribute value to a bool by
// setting it to the boolean value represented by the string.
//
// Unmarshal maps an XML element or attribute value to an integer or
// floating-point field by setting the field to the result of
// interpreting the string value in decimal. There is no check for
// overflow.
//
// Unmarshal maps an XML element to an xml.Name by recording the
// element name.
//
// Unmarshal maps an XML element to a pointer by setting the pointer
// to a freshly allocated value and then mapping the element to that value.
//
func Unmarshal(data []byte, v interface{}) error | {
return NewDecoder(bytes.NewReader(data)).Decode(v)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L128-L134 | go | train | // DecodeElement works like xml.Unmarshal except that it takes
// a pointer to the start XML element to decode into v.
// It is useful when a client reads some raw XML tokens itself
// but also wants to defer to Unmarshal for some elements. | func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error | // DecodeElement works like xml.Unmarshal except that it takes
// a pointer to the start XML element to decode into v.
// It is useful when a client reads some raw XML tokens itself
// but also wants to defer to Unmarshal for some elements.
func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error | {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Ptr {
return errors.New("non-pointer passed to Unmarshal")
}
return d.unmarshal(val.Elem(), start)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L173-L179 | go | train | // receiverType returns the receiver type to use in an expression like "%s.MethodName". | func receiverType(val interface{}) string | // receiverType returns the receiver type to use in an expression like "%s.MethodName".
func receiverType(val interface{}) string | {
t := reflect.TypeOf(val)
if t.Name() != "" {
return t.String()
}
return "(" + t.String() + ")"
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L183-L200 | go | train | // unmarshalInterface unmarshals a single XML element into val.
// start is the opening tag of the element. | func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error | // unmarshalInterface unmarshals a single XML element into val.
// start is the opening tag of the element.
func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error | {
// Record that decoder must stop at end tag corresponding to start.
p.pushEOF()
p.unmarshalDepth++
err := val.UnmarshalXML(p, *start)
p.unmarshalDepth--
if err != nil {
p.popEOF()
return err
}
if !p.popEOF() {
return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L228-L263 | go | train | // unmarshalAttr unmarshals a single XML attribute into val. | func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error | // unmarshalAttr unmarshals a single XML attribute into val.
func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error | {
if val.Kind() == reflect.Ptr {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
// This is an unmarshaler with a non-pointer receiver,
// so it's likely to be incorrect, but we do what we're told.
return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
}
}
// Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
// This is an unmarshaler with a non-pointer receiver,
// so it's likely to be incorrect, but we do what we're told.
return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
}
}
copyValue(val, []byte(attr.Value))
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L272-L312 | go | train | // Find reflect.Type for an element's type attribute. | func (p *Decoder) typeForElement(val reflect.Value, start *StartElement) reflect.Type | // Find reflect.Type for an element's type attribute.
func (p *Decoder) typeForElement(val reflect.Value, start *StartElement) reflect.Type | {
t := ""
for i, a := range start.Attr {
if a.Name == xmlSchemaInstance || a.Name == xsiType {
t = a.Value
// HACK: ensure xsi:type is last in the list to avoid using that value for
// a "type" attribute, such as ManagedObjectReference.Type for example.
// Note that xsi:type is already the last attribute in VC/ESX responses.
// This is only an issue with govmomi simulator generated responses.
// Proper fix will require finding a few needles in this xml package haystack.
// Note: govmomi uses xmlSchemaInstance, other clients (e.g. rbvmomi) use xsiType.
// They are the same thing to XML parsers, but not to this hack here.
x := len(start.Attr) - 1
if i != x {
start.Attr[i] = start.Attr[x]
start.Attr[x] = a
}
break
}
}
if t == "" {
// No type attribute; fall back to looking up type by interface name.
t = val.Type().Name()
}
// Maybe the type is a basic xsd:* type.
typ := stringToType(t)
if typ != nil {
return typ
}
// Maybe the type is a custom type.
if p.TypeFunc != nil {
if typ, ok := p.TypeFunc(t); ok {
return typ
}
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L315-L621 | go | train | // Unmarshal a single XML element into val. | func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error | // Unmarshal a single XML element into val.
func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error | {
// Find start element if we need it.
if start == nil {
for {
tok, err := p.Token()
if err != nil {
return err
}
if t, ok := tok.(StartElement); ok {
start = &t
break
}
}
}
// Try to figure out type for empty interface values.
if val.Kind() == reflect.Interface && val.IsNil() {
typ := p.typeForElement(val, start)
if typ != nil {
pval := reflect.New(typ).Elem()
err := p.unmarshal(pval, start)
if err != nil {
return err
}
for i := 0; i < 2; i++ {
if typ.Implements(val.Type()) {
val.Set(pval)
return nil
}
typ = reflect.PtrTo(typ)
pval = pval.Addr()
}
val.Set(pval)
return nil
}
}
// Load value from interface, but only if the result will be
// usefully addressable.
if val.Kind() == reflect.Interface && !val.IsNil() {
e := val.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() {
val = e
}
}
if val.Kind() == reflect.Ptr {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
if val.CanInterface() && val.Type().Implements(unmarshalerType) {
// This is an unmarshaler with a non-pointer receiver,
// so it's likely to be incorrect, but we do what we're told.
return p.unmarshalInterface(val.Interface().(Unmarshaler), start)
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
return p.unmarshalInterface(pv.Interface().(Unmarshaler), start)
}
}
if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start)
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start)
}
}
var (
data []byte
saveData reflect.Value
comment []byte
saveComment reflect.Value
saveXML reflect.Value
saveXMLIndex int
saveXMLData []byte
saveAny reflect.Value
sv reflect.Value
tinfo *typeInfo
err error
)
switch v := val; v.Kind() {
default:
return errors.New("unknown type " + v.Type().String())
case reflect.Interface:
// TODO: For now, simply ignore the field. In the near
// future we may choose to unmarshal the start
// element on it, if not nil.
return p.Skip()
case reflect.Slice:
typ := v.Type()
if typ.Elem().Kind() == reflect.Uint8 {
// []byte
saveData = v
break
}
// Slice of element values.
// Grow slice.
n := v.Len()
if n >= v.Cap() {
ncap := 2 * n
if ncap < 4 {
ncap = 4
}
new := reflect.MakeSlice(typ, n, ncap)
reflect.Copy(new, v)
v.Set(new)
}
v.SetLen(n + 1)
// Recur to read element into slice.
if err := p.unmarshal(v.Index(n), start); err != nil {
v.SetLen(n)
return err
}
return nil
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String:
saveData = v
case reflect.Struct:
typ := v.Type()
if typ == nameType {
v.Set(reflect.ValueOf(start.Name))
break
}
sv = v
tinfo, err = getTypeInfo(typ)
if err != nil {
return err
}
// Validate and assign element name.
if tinfo.xmlname != nil {
finfo := tinfo.xmlname
if finfo.name != "" && finfo.name != start.Name.Local {
return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
}
if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
if start.Name.Space == "" {
e += "no name space"
} else {
e += start.Name.Space
}
return UnmarshalError(e)
}
fv := finfo.value(sv)
if _, ok := fv.Interface().(Name); ok {
fv.Set(reflect.ValueOf(start.Name))
}
}
// Assign attributes.
// Also, determine whether we need to save character data or comments.
for i := range tinfo.fields {
finfo := &tinfo.fields[i]
switch finfo.flags & fMode {
case fAttr:
strv := finfo.value(sv)
// Look for attribute.
for _, a := range start.Attr {
if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
if err := p.unmarshalAttr(strv, a); err != nil {
return err
}
break
}
}
case fCharData:
if !saveData.IsValid() {
saveData = finfo.value(sv)
}
case fComment:
if !saveComment.IsValid() {
saveComment = finfo.value(sv)
}
case fAny, fAny | fElement:
if !saveAny.IsValid() {
saveAny = finfo.value(sv)
}
case fInnerXml:
if !saveXML.IsValid() {
saveXML = finfo.value(sv)
if p.saved == nil {
saveXMLIndex = 0
p.saved = new(bytes.Buffer)
} else {
saveXMLIndex = p.savedOffset()
}
}
}
}
}
// Find end element.
// Process sub-elements along the way.
Loop:
for {
var savedOffset int
if saveXML.IsValid() {
savedOffset = p.savedOffset()
}
tok, err := p.Token()
if err != nil {
return err
}
switch t := tok.(type) {
case StartElement:
consumed := false
if sv.IsValid() {
consumed, err = p.unmarshalPath(tinfo, sv, nil, &t)
if err != nil {
return err
}
if !consumed && saveAny.IsValid() {
consumed = true
if err := p.unmarshal(saveAny, &t); err != nil {
return err
}
}
}
if !consumed {
if err := p.Skip(); err != nil {
return err
}
}
case EndElement:
if saveXML.IsValid() {
saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset]
if saveXMLIndex == 0 {
p.saved = nil
}
}
break Loop
case CharData:
if saveData.IsValid() {
data = append(data, t...)
}
case Comment:
if saveComment.IsValid() {
comment = append(comment, t...)
}
}
}
if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
return err
}
saveData = reflect.Value{}
}
if saveData.IsValid() && saveData.CanAddr() {
pv := saveData.Addr()
if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
return err
}
saveData = reflect.Value{}
}
}
if err := copyValue(saveData, data); err != nil {
return err
}
switch t := saveComment; t.Kind() {
case reflect.String:
t.SetString(string(comment))
case reflect.Slice:
t.Set(reflect.ValueOf(comment))
}
switch t := saveXML; t.Kind() {
case reflect.String:
t.SetString(string(saveXMLData))
case reflect.Slice:
t.Set(reflect.ValueOf(saveXMLData))
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L701-L758 | go | train | // unmarshalPath walks down an XML structure looking for wanted
// paths, and calls unmarshal on them.
// The consumed result tells whether XML elements have been consumed
// from the Decoder until start's matching end element, or if it's
// still untouched because start is uninteresting for sv's fields. | func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) | // unmarshalPath walks down an XML structure looking for wanted
// paths, and calls unmarshal on them.
// The consumed result tells whether XML elements have been consumed
// from the Decoder until start's matching end element, or if it's
// still untouched because start is uninteresting for sv's fields.
func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) | {
recurse := false
Loop:
for i := range tinfo.fields {
finfo := &tinfo.fields[i]
if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
continue
}
for j := range parents {
if parents[j] != finfo.parents[j] {
continue Loop
}
}
if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
// It's a perfect match, unmarshal the field.
return true, p.unmarshal(finfo.value(sv), start)
}
if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
// It's a prefix for the field. Break and recurse
// since it's not ok for one field path to be itself
// the prefix for another field path.
recurse = true
// We can reuse the same slice as long as we
// don't try to append to it.
parents = finfo.parents[:len(parents)+1]
break
}
}
if !recurse {
// We have no business with this element.
return false, nil
}
// The element is not a perfect match for any field, but one
// or more fields have the path to this element as a parent
// prefix. Recurse and attempt to match these.
for {
var tok Token
tok, err = p.Token()
if err != nil {
return true, err
}
switch t := tok.(type) {
case StartElement:
consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t)
if err != nil {
return true, err
}
if !consumed2 {
if err := p.Skip(); err != nil {
return true, err
}
}
case EndElement:
return true, nil
}
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vim25/xml/read.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/read.go#L766-L781 | go | train | // Skip reads tokens until it has consumed the end element
// matching the most recent start element already consumed.
// It recurs if it encounters a start element, so it can be used to
// skip nested structures.
// It returns nil if it finds an end element matching the start
// element; otherwise it returns an error describing the problem. | func (d *Decoder) Skip() error | // Skip reads tokens until it has consumed the end element
// matching the most recent start element already consumed.
// It recurs if it encounters a start element, so it can be used to
// skip nested structures.
// It returns nil if it finds an end element matching the start
// element; otherwise it returns an error describing the problem.
func (d *Decoder) Skip() error | {
for {
tok, err := d.Token()
if err != nil {
return err
}
switch tok.(type) {
case StartElement:
if err := d.Skip(); err != nil {
return err
}
case EndElement:
return nil
}
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/library/library_item_updatesession_file.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession_file.go#L59-L66 | go | train | // AddLibraryItemFile adds a file | func (c *Manager) AddLibraryItemFile(ctx context.Context, sessionID string, updateFile UpdateFile) (*UpdateFileInfo, error) | // AddLibraryItemFile adds a file
func (c *Manager) AddLibraryItemFile(ctx context.Context, sessionID string, updateFile UpdateFile) (*UpdateFileInfo, error) | {
url := internal.URL(c, internal.LibraryItemUpdateSessionFile).WithID(sessionID).WithAction("add")
spec := struct {
FileSpec UpdateFile `json:"file_spec"`
}{updateFile}
var res UpdateFileInfo
return &res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/library/library_item_updatesession_file.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession_file.go#L69-L92 | go | train | // AddLibraryItemFileFromURI adds a file from a remote URI. | func (c *Manager) AddLibraryItemFileFromURI(
ctx context.Context,
sessionID, fileName, uri string) (*UpdateFileInfo, error) | // AddLibraryItemFileFromURI adds a file from a remote URI.
func (c *Manager) AddLibraryItemFileFromURI(
ctx context.Context,
sessionID, fileName, uri string) (*UpdateFileInfo, error) | {
n, fingerprint, err := GetContentLengthAndFingerprint(ctx, uri)
if err != nil {
return nil, err
}
info, err := c.AddLibraryItemFile(ctx, sessionID, UpdateFile{
Name: fileName,
SourceType: "PULL",
Size: &n,
SourceEndpoint: &SourceEndpoint{
URI: uri,
SSLCertificateThumbprint: fingerprint,
},
})
if err != nil {
return nil, err
}
return info, c.CompleteLibraryItemUpdateSession(ctx, sessionID)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/library/library_item_updatesession_file.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession_file.go#L96-L103 | go | train | // GetLibraryItemUpdateSessionFile retrieves information about a specific file
// that is a part of an update session. | func (c *Manager) GetLibraryItemUpdateSessionFile(ctx context.Context, sessionID string, fileName string) (*UpdateFileInfo, error) | // GetLibraryItemUpdateSessionFile retrieves information about a specific file
// that is a part of an update session.
func (c *Manager) GetLibraryItemUpdateSessionFile(ctx context.Context, sessionID string, fileName string) (*UpdateFileInfo, error) | {
url := internal.URL(c, internal.LibraryItemUpdateSessionFile).WithID(sessionID).WithAction("get")
spec := struct {
Name string `json:"file_name"`
}{fileName}
var res UpdateFileInfo
return &res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | vapi/library/library_item_updatesession_file.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession_file.go#L108-L126 | go | train | // GetContentLengthAndFingerprint gets the number of bytes returned
// by the URI as well as the SHA1 fingerprint of the peer certificate
// if the URI's scheme is https. | func GetContentLengthAndFingerprint(
ctx context.Context, uri string) (int64, string, error) | // GetContentLengthAndFingerprint gets the number of bytes returned
// by the URI as well as the SHA1 fingerprint of the peer certificate
// if the URI's scheme is https.
func GetContentLengthAndFingerprint(
ctx context.Context, uri string) (int64, string, error) | {
resp, err := http.Head(uri)
if err != nil {
return 0, "", err
}
if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
return resp.ContentLength, "", nil
}
fingerprint := &bytes.Buffer{}
sum := sha1.Sum(resp.TLS.PeerCertificates[0].Raw)
for i, b := range sum {
fmt.Fprintf(fingerprint, "%X", b)
if i < len(sum)-1 {
fmt.Fprint(fingerprint, ":")
}
}
return resp.ContentLength, fingerprint.String(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L126-L152 | go | train | // formatMessage applies the EventDescriptionEventDetail.FullFormat template to the given event's FullFormattedMessage field. | func (m *EventManager) formatMessage(event types.BaseEvent) | // formatMessage applies the EventDescriptionEventDetail.FullFormat template to the given event's FullFormattedMessage field.
func (m *EventManager) formatMessage(event types.BaseEvent) | {
id := reflect.ValueOf(event).Elem().Type().Name()
e := event.GetEvent()
t, ok := m.templates[id]
if !ok {
for _, info := range m.Description.EventInfo {
if info.Key == id {
t = template.Must(template.New(id).Parse(info.FullFormat))
m.templates[id] = t
break
}
}
}
if t != nil {
var buf bytes.Buffer
if err := t.Execute(&buf, event); err != nil {
log.Print(err)
}
e.FullFormattedMessage = buf.String()
}
if logEvents {
log.Printf("[%s] %s", id, e.FullFormattedMessage)
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L191-L237 | go | train | // doEntityEventArgument calls f for each entity argument in the event.
// If f returns true, the iteration stops. | func doEntityEventArgument(event types.BaseEvent, f func(types.ManagedObjectReference, *types.EntityEventArgument) bool) bool | // doEntityEventArgument calls f for each entity argument in the event.
// If f returns true, the iteration stops.
func doEntityEventArgument(event types.BaseEvent, f func(types.ManagedObjectReference, *types.EntityEventArgument) bool) bool | {
e := event.GetEvent()
if arg := e.Vm; arg != nil {
if f(arg.Vm, &arg.EntityEventArgument) {
return true
}
}
if arg := e.Host; arg != nil {
if f(arg.Host, &arg.EntityEventArgument) {
return true
}
}
if arg := e.ComputeResource; arg != nil {
if f(arg.ComputeResource, &arg.EntityEventArgument) {
return true
}
}
if arg := e.Ds; arg != nil {
if f(arg.Datastore, &arg.EntityEventArgument) {
return true
}
}
if arg := e.Net; arg != nil {
if f(arg.Network, &arg.EntityEventArgument) {
return true
}
}
if arg := e.Dvs; arg != nil {
if f(arg.Dvs, &arg.EntityEventArgument) {
return true
}
}
if arg := e.Datacenter; arg != nil {
if f(arg.Datacenter, &arg.EntityEventArgument) {
return true
}
}
return false
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L240-L244 | go | train | // eventFilterSelf returns true if self is one of the entity arguments in the event. | func eventFilterSelf(event types.BaseEvent, self types.ManagedObjectReference) bool | // eventFilterSelf returns true if self is one of the entity arguments in the event.
func eventFilterSelf(event types.BaseEvent, self types.ManagedObjectReference) bool | {
return doEntityEventArgument(event, func(ref types.ManagedObjectReference, _ *types.EntityEventArgument) bool {
return self == ref
})
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L247-L266 | go | train | // eventFilterChildren returns true if a child of self is one of the entity arguments in the event. | func eventFilterChildren(event types.BaseEvent, self types.ManagedObjectReference) bool | // eventFilterChildren returns true if a child of self is one of the entity arguments in the event.
func eventFilterChildren(event types.BaseEvent, self types.ManagedObjectReference) bool | {
return doEntityEventArgument(event, func(ref types.ManagedObjectReference, _ *types.EntityEventArgument) bool {
seen := false
var match func(types.ManagedObjectReference)
match = func(child types.ManagedObjectReference) {
if child == self {
seen = true
return
}
walk(child, match)
}
walk(ref, match)
return seen
})
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L269-L290 | go | train | // entityMatches returns true if the spec Entity filter matches the event. | func (c *EventHistoryCollector) entityMatches(event types.BaseEvent, spec *types.EventFilterSpec) bool | // entityMatches returns true if the spec Entity filter matches the event.
func (c *EventHistoryCollector) entityMatches(event types.BaseEvent, spec *types.EventFilterSpec) bool | {
e := spec.Entity
if e == nil {
return true
}
isRootFolder := c.m.root == e.Entity
switch e.Recursion {
case types.EventFilterSpecRecursionOptionSelf:
return isRootFolder || eventFilterSelf(event, e.Entity)
case types.EventFilterSpecRecursionOptionChildren:
return eventFilterChildren(event, e.Entity)
case types.EventFilterSpecRecursionOptionAll:
if isRootFolder || eventFilterSelf(event, e.Entity) {
return true
}
return eventFilterChildren(event, e.Entity)
}
return false
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L293-L317 | go | train | // typeMatches returns true if one of the spec EventTypeId types matches the event. | func (c *EventHistoryCollector) typeMatches(event types.BaseEvent, spec *types.EventFilterSpec) bool | // typeMatches returns true if one of the spec EventTypeId types matches the event.
func (c *EventHistoryCollector) typeMatches(event types.BaseEvent, spec *types.EventFilterSpec) bool | {
if len(spec.EventTypeId) == 0 {
return true
}
matches := func(name string) bool {
for _, id := range spec.EventTypeId {
if id == name {
return true
}
}
return false
}
kind := reflect.ValueOf(event).Elem().Type()
if matches(kind.Name()) {
return true // concrete type
}
field, ok := kind.FieldByNameFunc(matches)
if ok {
return field.Anonymous // base type (embedded field)
}
return false
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L320-L330 | go | train | // eventMatches returns true one of the filters matches the event. | func (c *EventHistoryCollector) eventMatches(event types.BaseEvent) bool | // eventMatches returns true one of the filters matches the event.
func (c *EventHistoryCollector) eventMatches(event types.BaseEvent) bool | {
spec := c.Filter.(types.EventFilterSpec)
if !c.typeMatches(event, &spec) {
return false
}
// TODO: spec.Time, spec.UserName, etc
return c.entityMatches(event, &spec)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | simulator/event_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/event_manager.go#L333-L369 | go | train | // filePage copies the manager's latest events into the collector's page with Filter applied. | func (c *EventHistoryCollector) fillPage(size int) | // filePage copies the manager's latest events into the collector's page with Filter applied.
func (c *EventHistoryCollector) fillPage(size int) | {
c.pos = 0
l := c.page.Len()
delta := size - l
if delta < 0 {
// Shrink ring size
c.page = c.page.Unlink(-delta)
return
}
matches := 0
mpage := c.m.page
page := c.page
if delta != 0 {
// Grow ring size
c.page = c.page.Link(ring.New(delta))
}
for i := 0; i < maxPageSize; i++ {
event, ok := mpage.Value.(types.BaseEvent)
mpage = mpage.Prev()
if !ok {
continue
}
if c.eventMatches(event) {
page.Value = event
page = page.Prev()
matches++
if matches == size {
break
}
}
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | object/virtual_disk_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_disk_manager.go#L40-L70 | go | train | // CopyVirtualDisk copies a virtual disk, performing conversions as specified in the spec. | func (m VirtualDiskManager) CopyVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
destSpec *types.VirtualDiskSpec, force bool) (*Task, error) | // CopyVirtualDisk copies a virtual disk, performing conversions as specified in the spec.
func (m VirtualDiskManager) CopyVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
destSpec *types.VirtualDiskSpec, force bool) (*Task, error) | {
req := types.CopyVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
DestSpec: destSpec,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.CopyVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | object/virtual_disk_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_disk_manager.go#L73-L95 | go | train | // CreateVirtualDisk creates a new virtual disk. | func (m VirtualDiskManager) CreateVirtualDisk(
ctx context.Context,
name string, datacenter *Datacenter,
spec types.BaseVirtualDiskSpec) (*Task, error) | // CreateVirtualDisk creates a new virtual disk.
func (m VirtualDiskManager) CreateVirtualDisk(
ctx context.Context,
name string, datacenter *Datacenter,
spec types.BaseVirtualDiskSpec) (*Task, error) | {
req := types.CreateVirtualDisk_Task{
This: m.Reference(),
Name: name,
Spec: spec,
}
if datacenter != nil {
ref := datacenter.Reference()
req.Datacenter = &ref
}
res, err := methods.CreateVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | object/virtual_disk_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_disk_manager.go#L169-L187 | go | train | // ShrinkVirtualDisk shrinks a virtual disk. | func (m VirtualDiskManager) ShrinkVirtualDisk(ctx context.Context, name string, dc *Datacenter, copy *bool) (*Task, error) | // ShrinkVirtualDisk shrinks a virtual disk.
func (m VirtualDiskManager) ShrinkVirtualDisk(ctx context.Context, name string, dc *Datacenter, copy *bool) (*Task, error) | {
req := types.ShrinkVirtualDisk_Task{
This: m.Reference(),
Name: name,
Copy: copy,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.ShrinkVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | object/virtual_disk_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_disk_manager.go#L190-L211 | go | train | // Queries virtual disk uuid | func (m VirtualDiskManager) QueryVirtualDiskUuid(ctx context.Context, name string, dc *Datacenter) (string, error) | // Queries virtual disk uuid
func (m VirtualDiskManager) QueryVirtualDiskUuid(ctx context.Context, name string, dc *Datacenter) (string, error) | {
req := types.QueryVirtualDiskUuid{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.QueryVirtualDiskUuid(ctx, m.c, &req)
if err != nil {
return "", err
}
if res == nil {
return "", nil
}
return res.Returnval, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L75-L100 | go | train | // NewService initializes a Service instance | func NewService(rpcIn Channel, rpcOut Channel) *Service | // NewService initializes a Service instance
func NewService(rpcIn Channel, rpcOut Channel) *Service | {
s := &Service{
name: "toolbox", // Same name used by vmtoolsd
in: NewTraceChannel(rpcIn),
out: &ChannelOut{NewTraceChannel(rpcOut)},
handlers: make(map[string]Handler),
wg: new(sync.WaitGroup),
stop: make(chan struct{}),
PrimaryIP: DefaultIP,
}
s.RegisterHandler("reset", s.Reset)
s.RegisterHandler("ping", s.Ping)
s.RegisterHandler("Set_Option", s.SetOption)
s.RegisterHandler("Capabilities_Register", s.CapabilitiesRegister)
s.Command = registerCommandServer(s)
s.Command.FileServer = hgfs.NewServer()
s.Command.FileServer.RegisterFileHandler("proc", s.Command.ProcessManager)
s.Command.FileServer.RegisterFileHandler(hgfs.ArchiveScheme, hgfs.NewArchiveHandler())
s.Power = registerPowerCommandHandler(s)
return s
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L103-L116 | go | train | // backoff exponentially increases the RPC poll delay up to maxDelay | func (s *Service) backoff() | // backoff exponentially increases the RPC poll delay up to maxDelay
func (s *Service) backoff() | {
if s.delay < maxDelay {
if s.delay > 0 {
d := s.delay * 2
if d > s.delay && d < maxDelay {
s.delay = d
} else {
s.delay = maxDelay
}
} else {
s.delay = 1
}
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L147-L196 | go | train | // Start initializes the RPC channels and starts a goroutine to listen for incoming RPC requests | func (s *Service) Start() error | // Start initializes the RPC channels and starts a goroutine to listen for incoming RPC requests
func (s *Service) Start() error | {
err := s.startChannel()
if err != nil {
return err
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
// Same polling interval and backoff logic as vmtoolsd.
// Required in our case at startup at least, otherwise it is possible
// we miss the 1 Capabilities_Register call for example.
// Note we Send(response) even when nil, to let the VMX know we are here
var response []byte
for {
select {
case <-s.stop:
s.stopChannel()
return
case <-time.After(time.Millisecond * 10 * s.delay):
if err = s.checkReset(); err != nil {
continue
}
err = s.in.Send(response)
response = nil
if err != nil {
s.delay = resetDelay
s.rpcError = true
continue
}
request, _ := s.in.Receive()
if len(request) > 0 {
response = s.Dispatch(request)
s.delay = 0
} else {
s.backoff()
}
}
}
}()
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L212-L214 | go | train | // RegisterHandler for the given RPC name | func (s *Service) RegisterHandler(name string, handler Handler) | // RegisterHandler for the given RPC name
func (s *Service) RegisterHandler(name string, handler Handler) | {
s.handlers[name] = handler
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L217-L245 | go | train | // Dispatch an incoming RPC request to a Handler | func (s *Service) Dispatch(request []byte) []byte | // Dispatch an incoming RPC request to a Handler
func (s *Service) Dispatch(request []byte) []byte | {
msg := bytes.SplitN(request, []byte{' '}, 2)
name := msg[0]
// Trim NULL byte terminator
name = bytes.TrimRight(name, "\x00")
handler, ok := s.handlers[string(name)]
if !ok {
log.Printf("unknown command: %q\n", name)
return []byte("Unknown Command")
}
var args []byte
if len(msg) == 2 {
args = msg[1]
}
response, err := handler(args)
if err == nil {
response = append([]byte("OK "), response...)
} else {
log.Printf("error calling %s: %s\n", name, err)
response = append([]byte("ERR "), response...)
}
return response
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L248-L252 | go | train | // Reset is the default Handler for reset requests | func (s *Service) Reset([]byte) ([]byte, error) | // Reset is the default Handler for reset requests
func (s *Service) Reset([]byte) ([]byte, error) | {
s.SendGuestInfo() // Send the IP info ASAP
return []byte("ATR " + s.name), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L260-L290 | go | train | // SetOption is the default Handler for Set_Option requests | func (s *Service) SetOption(args []byte) ([]byte, error) | // SetOption is the default Handler for Set_Option requests
func (s *Service) SetOption(args []byte) ([]byte, error) | {
opts := bytes.SplitN(args, []byte{' '}, 2)
key := string(opts[0])
val := string(opts[1])
if Trace {
fmt.Fprintf(os.Stderr, "set option %q=%q\n", key, val)
}
switch key {
case "broadcastIP": // TODO: const-ify
if val == "1" {
ip := s.PrimaryIP()
if ip == "" {
log.Printf("failed to find primary IP")
return nil, nil
}
msg := fmt.Sprintf("info-set guestinfo.ip %s", ip)
_, err := s.out.Request([]byte(msg))
if err != nil {
return nil, err
}
s.SendGuestInfo()
}
default:
// TODO: handle other options...
}
return nil, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/service.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/service.go#L294-L307 | go | train | // DefaultIP is used by default when responding to a Set_Option broadcastIP request
// It can be overridden with the Service.PrimaryIP field | func DefaultIP() string | // DefaultIP is used by default when responding to a Set_Option broadcastIP request
// It can be overridden with the Service.PrimaryIP field
func DefaultIP() string | {
addrs, err := netInterfaceAddrs()
if err == nil {
for _, addr := range addrs {
if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() {
if ip.IP.To4() != nil {
return ip.IP.String()
}
}
}
}
return ""
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | object/namespace_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/namespace_manager.go#L41-L56 | go | train | // CreateDirectory creates a top-level directory on the given vsan datastore, using
// the given user display name hint and opaque storage policy. | func (nm DatastoreNamespaceManager) CreateDirectory(ctx context.Context, ds *Datastore, displayName string, policy string) (string, error) | // CreateDirectory creates a top-level directory on the given vsan datastore, using
// the given user display name hint and opaque storage policy.
func (nm DatastoreNamespaceManager) CreateDirectory(ctx context.Context, ds *Datastore, displayName string, policy string) (string, error) | {
req := &types.CreateDirectory{
This: nm.Reference(),
Datastore: ds.Reference(),
DisplayName: displayName,
Policy: policy,
}
resp, err := methods.CreateDirectory(ctx, nm.c, req)
if err != nil {
return "", err
}
return resp.Returnval, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | object/namespace_manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/namespace_manager.go#L59-L76 | go | train | // DeleteDirectory deletes the given top-level directory from a vsan datastore. | func (nm DatastoreNamespaceManager) DeleteDirectory(ctx context.Context, dc *Datacenter, datastorePath string) error | // DeleteDirectory deletes the given top-level directory from a vsan datastore.
func (nm DatastoreNamespaceManager) DeleteDirectory(ctx context.Context, dc *Datacenter, datastorePath string) error | {
req := &types.DeleteDirectory{
This: nm.Reference(),
DatastorePath: datastorePath,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
if _, err := methods.DeleteDirectory(ctx, nm.c, req); err != nil {
return err
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L58-L66 | go | train | // NewManager creates a new Manager instance. | func NewManager(client *vim25.Client) *Manager | // NewManager creates a new Manager instance.
func NewManager(client *vim25.Client) *Manager | {
m := Manager{
Common: object.NewCommon(client, *client.ServiceContent.PerfManager),
}
m.pm.PerformanceManager = new(mo.PerformanceManager)
return &m
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L72-L88 | go | train | // Enabled returns a map with Level as the key and enabled PerfInterval.Name(s) as the value. | func (l IntervalList) Enabled() map[int32][]string | // Enabled returns a map with Level as the key and enabled PerfInterval.Name(s) as the value.
func (l IntervalList) Enabled() map[int32][]string | {
enabled := make(map[int32][]string)
for level := int32(0); level <= 4; level++ {
var names []string
for _, interval := range l {
if interval.Enabled && interval.Level >= level {
names = append(names, interval.Name)
}
}
enabled[level] = names
}
return enabled
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L91-L100 | go | train | // HistoricalInterval gets the PerformanceManager.HistoricalInterval property and wraps as an IntervalList. | func (m *Manager) HistoricalInterval(ctx context.Context) (IntervalList, error) | // HistoricalInterval gets the PerformanceManager.HistoricalInterval property and wraps as an IntervalList.
func (m *Manager) HistoricalInterval(ctx context.Context) (IntervalList, error) | {
var pm mo.PerformanceManager
err := m.Properties(ctx, m.Reference(), []string{"historicalInterval"}, &pm)
if err != nil {
return nil, err
}
return IntervalList(pm.HistoricalInterval), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L104-L116 | go | train | // CounterInfo gets the PerformanceManager.PerfCounter property.
// The property value is only collected once, subsequent calls return the cached value. | func (m *Manager) CounterInfo(ctx context.Context) ([]types.PerfCounterInfo, error) | // CounterInfo gets the PerformanceManager.PerfCounter property.
// The property value is only collected once, subsequent calls return the cached value.
func (m *Manager) CounterInfo(ctx context.Context) ([]types.PerfCounterInfo, error) | {
m.pm.Lock()
defer m.pm.Unlock()
if len(m.pm.PerfCounter) == 0 {
err := m.Properties(ctx, m.Reference(), []string{"perfCounter"}, m.pm.PerformanceManager)
if err != nil {
return nil, err
}
}
return m.pm.PerfCounter, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L120-L142 | go | train | // CounterInfoByName converts the PerformanceManager.PerfCounter property to a map,
// where key is types.PerfCounterInfo.Name(). | func (m *Manager) CounterInfoByName(ctx context.Context) (map[string]*types.PerfCounterInfo, error) | // CounterInfoByName converts the PerformanceManager.PerfCounter property to a map,
// where key is types.PerfCounterInfo.Name().
func (m *Manager) CounterInfoByName(ctx context.Context) (map[string]*types.PerfCounterInfo, error) | {
m.infoByName.Lock()
defer m.infoByName.Unlock()
if m.infoByName.m != nil {
return m.infoByName.m, nil
}
info, err := m.CounterInfo(ctx)
if err != nil {
return nil, err
}
m.infoByName.m = make(map[string]*types.PerfCounterInfo)
for i := range info {
c := &info[i]
m.infoByName.m[c.Name()] = c
}
return m.infoByName.m, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L146-L168 | go | train | // CounterInfoByKey converts the PerformanceManager.PerfCounter property to a map,
// where key is types.PerfCounterInfo.Key. | func (m *Manager) CounterInfoByKey(ctx context.Context) (map[int32]*types.PerfCounterInfo, error) | // CounterInfoByKey converts the PerformanceManager.PerfCounter property to a map,
// where key is types.PerfCounterInfo.Key.
func (m *Manager) CounterInfoByKey(ctx context.Context) (map[int32]*types.PerfCounterInfo, error) | {
m.infoByKey.Lock()
defer m.infoByKey.Unlock()
if m.infoByKey.m != nil {
return m.infoByKey.m, nil
}
info, err := m.CounterInfo(ctx)
if err != nil {
return nil, err
}
m.infoByKey.m = make(map[int32]*types.PerfCounterInfo)
for i := range info {
c := &info[i]
m.infoByKey.m[c.Key] = c
}
return m.infoByKey.m, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L171-L183 | go | train | // ProviderSummary wraps the QueryPerfProviderSummary method, caching the value based on entity.Type. | func (m *Manager) ProviderSummary(ctx context.Context, entity types.ManagedObjectReference) (*types.PerfProviderSummary, error) | // ProviderSummary wraps the QueryPerfProviderSummary method, caching the value based on entity.Type.
func (m *Manager) ProviderSummary(ctx context.Context, entity types.ManagedObjectReference) (*types.PerfProviderSummary, error) | {
req := types.QueryPerfProviderSummary{
This: m.Reference(),
Entity: entity,
}
res, err := methods.QueryPerfProviderSummary(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L211-L220 | go | train | // ByKey converts MetricList to map, where key is types.PerfMetricId.CounterId / types.PerfCounterInfo.Key | func (l MetricList) ByKey() map[int32][]*types.PerfMetricId | // ByKey converts MetricList to map, where key is types.PerfMetricId.CounterId / types.PerfCounterInfo.Key
func (l MetricList) ByKey() map[int32][]*types.PerfMetricId | {
ids := make(map[int32][]*types.PerfMetricId, len(l))
for i := range l {
id := &l[i]
ids[id.CounterId] = append(ids[id.CounterId], id)
}
return ids
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L224-L246 | go | train | // AvailableMetric wraps the QueryAvailablePerfMetric method.
// The MetricList is sorted by PerfCounterInfo.GroupInfo.Key if Manager.Sort == true. | func (m *Manager) AvailableMetric(ctx context.Context, entity types.ManagedObjectReference, interval int32) (MetricList, error) | // AvailableMetric wraps the QueryAvailablePerfMetric method.
// The MetricList is sorted by PerfCounterInfo.GroupInfo.Key if Manager.Sort == true.
func (m *Manager) AvailableMetric(ctx context.Context, entity types.ManagedObjectReference, interval int32) (MetricList, error) | {
req := types.QueryAvailablePerfMetric{
This: m.Reference(),
Entity: entity.Reference(),
IntervalId: interval,
}
res, err := methods.QueryAvailablePerfMetric(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
if m.Sort {
info, err := m.CounterInfoByKey(ctx)
if err != nil {
return nil, err
}
sort.Sort(groupPerfCounterInfo{info, res.Returnval})
}
return MetricList(res.Returnval), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L249-L261 | go | train | // Query wraps the QueryPerf method. | func (m *Manager) Query(ctx context.Context, spec []types.PerfQuerySpec) ([]types.BasePerfEntityMetricBase, error) | // Query wraps the QueryPerf method.
func (m *Manager) Query(ctx context.Context, spec []types.PerfQuerySpec) ([]types.BasePerfEntityMetricBase, error) | {
req := types.QueryPerf{
This: m.Reference(),
QuerySpec: spec,
}
res, err := methods.QueryPerf(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L269-L321 | go | train | // SampleByName uses the spec param as a template, constructing a []types.PerfQuerySpec for the given metrics and entities
// and invoking the Query method.
// The spec template can specify instances using the MetricId.Instance field, by default all instances are collected.
// The spec template MaxSample defaults to 1.
// If the spec template IntervalId is a historical interval and StartTime is not specified,
// the StartTime is set to the current time - (IntervalId * MaxSample). | func (m *Manager) SampleByName(ctx context.Context, spec types.PerfQuerySpec, metrics []string, entity []types.ManagedObjectReference) ([]types.BasePerfEntityMetricBase, error) | // SampleByName uses the spec param as a template, constructing a []types.PerfQuerySpec for the given metrics and entities
// and invoking the Query method.
// The spec template can specify instances using the MetricId.Instance field, by default all instances are collected.
// The spec template MaxSample defaults to 1.
// If the spec template IntervalId is a historical interval and StartTime is not specified,
// the StartTime is set to the current time - (IntervalId * MaxSample).
func (m *Manager) SampleByName(ctx context.Context, spec types.PerfQuerySpec, metrics []string, entity []types.ManagedObjectReference) ([]types.BasePerfEntityMetricBase, error) | {
info, err := m.CounterInfoByName(ctx)
if err != nil {
return nil, err
}
var ids []types.PerfMetricId
instances := spec.MetricId
if len(instances) == 0 {
// Default to all instances
instances = []types.PerfMetricId{{Instance: "*"}}
}
for _, name := range metrics {
counter, ok := info[name]
if !ok {
return nil, fmt.Errorf("counter %q not found", name)
}
for _, i := range instances {
ids = append(ids, types.PerfMetricId{CounterId: counter.Key, Instance: i.Instance})
}
}
spec.MetricId = ids
if spec.MaxSample == 0 {
spec.MaxSample = 1
}
if spec.IntervalId >= 60 && spec.StartTime == nil {
// Need a StartTime to make use of history
now, err := methods.GetCurrentTime(ctx, m.Client())
if err != nil {
return nil, err
}
// Go back in time
x := spec.IntervalId * -1 * spec.MaxSample
t := now.Add(time.Duration(x) * time.Second)
spec.StartTime = &t
}
var query []types.PerfQuerySpec
for _, e := range entity {
spec.Entity = e.Reference()
query = append(query, spec)
}
return m.Query(ctx, query)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L341-L349 | go | train | // ValueCSV converts the Value field to a CSV string | func (s *MetricSeries) ValueCSV() string | // ValueCSV converts the Value field to a CSV string
func (s *MetricSeries) ValueCSV() string | {
vals := make([]string, len(s.Value))
for i := range s.Value {
vals[i] = s.Format(s.Value[i])
}
return strings.Join(vals, ",")
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L360-L373 | go | train | // SampleInfoCSV converts the SampleInfo field to a CSV string | func (m *EntityMetric) SampleInfoCSV() string | // SampleInfoCSV converts the SampleInfo field to a CSV string
func (m *EntityMetric) SampleInfoCSV() string | {
vals := make([]string, len(m.SampleInfo)*2)
i := 0
for _, s := range m.SampleInfo {
vals[i] = s.Timestamp.Format(time.RFC3339)
i++
vals[i] = strconv.Itoa(int(s.Interval))
i++
}
return strings.Join(vals, ",")
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | performance/manager.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/performance/manager.go#L376-L410 | go | train | // ToMetricSeries converts []BasePerfEntityMetricBase to []EntityMetric | func (m *Manager) ToMetricSeries(ctx context.Context, series []types.BasePerfEntityMetricBase) ([]EntityMetric, error) | // ToMetricSeries converts []BasePerfEntityMetricBase to []EntityMetric
func (m *Manager) ToMetricSeries(ctx context.Context, series []types.BasePerfEntityMetricBase) ([]EntityMetric, error) | {
counters, err := m.CounterInfoByKey(ctx)
if err != nil {
return nil, err
}
var result []EntityMetric
for i := range series {
var values []MetricSeries
s, ok := series[i].(*types.PerfEntityMetric)
if !ok {
panic(fmt.Errorf("expected type %T, got: %T", s, series[i]))
}
for j := range s.Value {
v := s.Value[j].(*types.PerfMetricIntSeries)
values = append(values, MetricSeries{
Name: counters[v.Id.CounterId].Name(),
unit: counters[v.Id.CounterId].UnitInfo.GetElementDescription().Key,
Instance: v.Id.Instance,
Value: v.Value,
})
}
result = append(result, EntityMetric{
Entity: s.Entity,
SampleInfo: s.SampleInfo,
Value: values,
})
}
return result, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/flags/host_connect.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/host_connect.go#L70-L85 | go | train | // Spec attempts to fill in SslThumbprint if empty.
// First checks GOVC_TLS_KNOWN_HOSTS, if not found and noverify=true then
// use object.HostCertificateInfo to get the thumbprint. | func (flag *HostConnectFlag) Spec(c *vim25.Client) types.HostConnectSpec | // Spec attempts to fill in SslThumbprint if empty.
// First checks GOVC_TLS_KNOWN_HOSTS, if not found and noverify=true then
// use object.HostCertificateInfo to get the thumbprint.
func (flag *HostConnectFlag) Spec(c *vim25.Client) types.HostConnectSpec | {
spec := flag.HostConnectSpec
if spec.SslThumbprint == "" {
spec.SslThumbprint = c.Thumbprint(spec.HostName)
if spec.SslThumbprint == "" && flag.noverify {
var info object.HostCertificateInfo
t := c.Transport.(*http.Transport)
_ = info.FromURL(&url.URL{Host: spec.HostName}, t.TLSClientConfig)
spec.SslThumbprint = info.ThumbprintSHA1
}
}
return spec
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/flags/host_connect.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/host_connect.go#L88-L101 | go | train | // Fault checks if error is SSLVerifyFault, including the thumbprint if so | func (flag *HostConnectFlag) Fault(err error) error | // Fault checks if error is SSLVerifyFault, including the thumbprint if so
func (flag *HostConnectFlag) Fault(err error) error | {
if err == nil {
return nil
}
if f, ok := err.(types.HasFault); ok {
switch fault := f.Fault().(type) {
case *types.SSLVerifyFault:
return fmt.Errorf("%s thumbprint=%s", err, fault.Thumbprint)
}
}
return err
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | guest/toolbox/client.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/guest/toolbox/client.go#L45-L65 | go | train | // procReader retries InitiateFileTransferFromGuest calls if toolbox is still running the process.
// See also: ProcessManager.Stat | func (c *Client) procReader(ctx context.Context, src string) (*types.FileTransferInformation, error) | // procReader retries InitiateFileTransferFromGuest calls if toolbox is still running the process.
// See also: ProcessManager.Stat
func (c *Client) procReader(ctx context.Context, src string) (*types.FileTransferInformation, error) | {
for {
info, err := c.FileManager.InitiateFileTransferFromGuest(ctx, c.Authentication, src)
if err != nil {
if soap.IsSoapFault(err) {
if _, ok := soap.ToSoapFault(err).VimFault().(types.CannotAccessFile); ok {
// We're not waiting in between retries since ProcessManager.Stat
// has already waited. In the case that this client was pointed at
// standard vmware-tools, the types.NotFound fault would have been
// returned since the file "/proc/$pid/stdout" does not exist - in
// which case, we won't retry at all.
continue
}
}
return nil, err
}
return info, err
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | guest/toolbox/client.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/guest/toolbox/client.go#L71-L138 | go | train | // RoundTrip implements http.RoundTripper over vmx guest RPC.
// This transport depends on govmomi/toolbox running in the VM guest and does not work with standard VMware tools.
// Using this transport makes it is possible to connect to HTTP endpoints that are bound to the VM's loopback address.
// Note that the toolbox's http.RoundTripper only supports the "http" scheme, "https" is not supported. | func (c *Client) RoundTrip(req *http.Request) (*http.Response, error) | // RoundTrip implements http.RoundTripper over vmx guest RPC.
// This transport depends on govmomi/toolbox running in the VM guest and does not work with standard VMware tools.
// Using this transport makes it is possible to connect to HTTP endpoints that are bound to the VM's loopback address.
// Note that the toolbox's http.RoundTripper only supports the "http" scheme, "https" is not supported.
func (c *Client) RoundTrip(req *http.Request) (*http.Response, error) | {
if req.URL.Scheme != "http" {
return nil, fmt.Errorf("%q scheme not supported", req.URL.Scheme)
}
ctx := req.Context()
req.Header.Set("Connection", "close") // we need the server to close the connection after 1 request
spec := types.GuestProgramSpec{
ProgramPath: "http.RoundTrip",
Arguments: req.URL.Host,
}
pid, err := c.ProcessManager.StartProgram(ctx, c.Authentication, &spec)
if err != nil {
return nil, err
}
dst := fmt.Sprintf("/proc/%d/stdin", pid)
src := fmt.Sprintf("/proc/%d/stdout", pid)
var buf bytes.Buffer
err = req.Write(&buf)
if err != nil {
return nil, err
}
attr := new(types.GuestPosixFileAttributes)
size := int64(buf.Len())
url, err := c.FileManager.InitiateFileTransferToGuest(ctx, c.Authentication, dst, attr, size, true)
if err != nil {
return nil, err
}
vc := c.ProcessManager.Client()
u, err := c.FileManager.TransferURL(ctx, url)
if err != nil {
return nil, err
}
p := soap.DefaultUpload
p.ContentLength = size
err = vc.Client.Upload(ctx, &buf, u, &p)
if err != nil {
return nil, err
}
info, err := c.procReader(ctx, src)
if err != nil {
return nil, err
}
u, err = c.FileManager.TransferURL(ctx, info.Url)
if err != nil {
return nil, err
}
f, _, err := vc.Client.Download(ctx, u, &soap.DefaultDownload)
if err != nil {
return nil, err
}
return http.ReadResponse(bufio.NewReader(f), req)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | guest/toolbox/client.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/guest/toolbox/client.go#L141-L230 | go | train | // Run implements exec.Cmd.Run over vmx guest RPC. | func (c *Client) Run(ctx context.Context, cmd *exec.Cmd) error | // Run implements exec.Cmd.Run over vmx guest RPC.
func (c *Client) Run(ctx context.Context, cmd *exec.Cmd) error | {
vc := c.ProcessManager.Client()
spec := types.GuestProgramSpec{
ProgramPath: cmd.Path,
Arguments: strings.Join(cmd.Args, " "),
EnvVariables: cmd.Env,
WorkingDirectory: cmd.Dir,
}
pid, serr := c.ProcessManager.StartProgram(ctx, c.Authentication, &spec)
if serr != nil {
return serr
}
if cmd.Stdin != nil {
dst := fmt.Sprintf("/proc/%d/stdin", pid)
var buf bytes.Buffer
size, err := io.Copy(&buf, cmd.Stdin)
if err != nil {
return err
}
attr := new(types.GuestPosixFileAttributes)
url, err := c.FileManager.InitiateFileTransferToGuest(ctx, c.Authentication, dst, attr, size, true)
if err != nil {
return err
}
u, err := c.FileManager.TransferURL(ctx, url)
if err != nil {
return err
}
p := soap.DefaultUpload
p.ContentLength = size
err = vc.Client.Upload(ctx, &buf, u, &p)
if err != nil {
return err
}
}
names := []string{"out", "err"}
for i, w := range []io.Writer{cmd.Stdout, cmd.Stderr} {
if w == nil {
continue
}
src := fmt.Sprintf("/proc/%d/std%s", pid, names[i])
info, err := c.procReader(ctx, src)
if err != nil {
return err
}
u, err := c.FileManager.TransferURL(ctx, info.Url)
if err != nil {
return err
}
f, _, err := vc.Client.Download(ctx, u, &soap.DefaultDownload)
if err != nil {
return err
}
_, err = io.Copy(w, f)
_ = f.Close()
if err != nil {
return err
}
}
procs, err := c.ProcessManager.ListProcesses(ctx, c.Authentication, []int64{pid})
if err != nil {
return err
}
if len(procs) == 1 {
rc := procs[0].ExitCode
if rc != 0 {
return fmt.Errorf("%s: exit %d", cmd.Path, rc)
}
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | guest/toolbox/client.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/guest/toolbox/client.go#L272-L297 | go | train | // Download initiates a file transfer from the guest | func (c *Client) Download(ctx context.Context, src string) (io.ReadCloser, int64, error) | // Download initiates a file transfer from the guest
func (c *Client) Download(ctx context.Context, src string) (io.ReadCloser, int64, error) | {
vc := c.ProcessManager.Client()
info, err := c.FileManager.InitiateFileTransferFromGuest(ctx, c.Authentication, src)
if err != nil {
return nil, 0, err
}
u, err := c.FileManager.TransferURL(ctx, info.Url)
if err != nil {
return nil, 0, err
}
p := soap.DefaultDownload
f, n, err := vc.Download(ctx, u, &p)
if err != nil {
return nil, n, err
}
if strings.HasPrefix(src, "/archive:/") || isDir(src) {
f = &archiveReader{ReadCloser: f} // look for the gzip trailer
}
return f, n, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | guest/toolbox/client.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/guest/toolbox/client.go#L300-L345 | go | train | // Upload transfers a file to the guest | func (c *Client) Upload(ctx context.Context, src io.Reader, dst string, p soap.Upload, attr types.BaseGuestFileAttributes, force bool) error | // Upload transfers a file to the guest
func (c *Client) Upload(ctx context.Context, src io.Reader, dst string, p soap.Upload, attr types.BaseGuestFileAttributes, force bool) error | {
vc := c.ProcessManager.Client()
var err error
if p.ContentLength == 0 { // Content-Length is required
switch r := src.(type) {
case *bytes.Buffer:
p.ContentLength = int64(r.Len())
case *bytes.Reader:
p.ContentLength = int64(r.Len())
case *strings.Reader:
p.ContentLength = int64(r.Len())
case *os.File:
info, serr := r.Stat()
if serr != nil {
return serr
}
p.ContentLength = info.Size()
}
if p.ContentLength == 0 { // os.File for example could be a device (stdin)
buf := new(bytes.Buffer)
p.ContentLength, err = io.Copy(buf, src)
if err != nil {
return err
}
src = buf
}
}
url, err := c.FileManager.InitiateFileTransferToGuest(ctx, c.Authentication, dst, attr, p.ContentLength, force)
if err != nil {
return err
}
u, err := c.FileManager.TransferURL(ctx, url)
if err != nil {
return err
}
return vc.Client.Upload(ctx, src, u, &p)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | lookup/simulator/registration_info.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/simulator/registration_info.go#L33-L133 | go | train | // registrationInfo returns a ServiceRegistration populated with vcsim's OptionManager settings.
// The complete list can be captured using: govc sso.service.ls -dump | func registrationInfo() []types.LookupServiceRegistrationInfo | // registrationInfo returns a ServiceRegistration populated with vcsim's OptionManager settings.
// The complete list can be captured using: govc sso.service.ls -dump
func registrationInfo() []types.LookupServiceRegistrationInfo | {
vc := simulator.Map.Get(vim25.ServiceInstance).(*simulator.ServiceInstance)
setting := simulator.Map.OptionManager().Setting
sm := simulator.Map.SessionManager()
opts := make(map[string]string, len(setting))
for _, o := range setting {
opt := o.GetOptionValue()
if val, ok := opt.Value.(string); ok {
opts[opt.Key] = val
}
}
trust := []string{""}
if sm.TLSCert != nil {
trust[0] = sm.TLSCert()
}
sdk := opts["vcsim.server.url"] + vim25.Path
admin := opts["config.vpxd.sso.default.admin"]
owner := opts["config.vpxd.sso.solutionUser.name"]
instance := opts["VirtualCenter.InstanceName"]
// Real PSC has 30+ services by default, we just provide a few that are useful for vmomi interaction..
return []types.LookupServiceRegistrationInfo{
{
LookupServiceRegistrationCommonServiceInfo: types.LookupServiceRegistrationCommonServiceInfo{
LookupServiceRegistrationMutableServiceInfo: types.LookupServiceRegistrationMutableServiceInfo{
ServiceVersion: lookup.Version,
ServiceEndpoints: []types.LookupServiceRegistrationEndpoint{
{
Url: opts["config.vpxd.sso.sts.uri"],
EndpointType: types.LookupServiceRegistrationEndpointType{
Protocol: "wsTrust",
Type: "com.vmware.cis.cs.identity.sso",
},
SslTrust: trust,
},
},
},
OwnerId: admin,
ServiceType: types.LookupServiceRegistrationServiceType{
Product: "com.vmware.cis",
Type: "sso:sts",
},
},
ServiceId: siteID + ":" + uuid.New().String(),
SiteId: siteID,
},
{
LookupServiceRegistrationCommonServiceInfo: types.LookupServiceRegistrationCommonServiceInfo{
LookupServiceRegistrationMutableServiceInfo: types.LookupServiceRegistrationMutableServiceInfo{
ServiceVersion: vim25.Version,
ServiceEndpoints: []types.LookupServiceRegistrationEndpoint{
{
Url: sdk,
EndpointType: types.LookupServiceRegistrationEndpointType{
Protocol: "vmomi",
Type: "com.vmware.vim",
},
SslTrust: trust,
EndpointAttributes: []types.LookupServiceRegistrationAttribute{
{
Key: "cis.common.ep.localurl",
Value: sdk,
},
},
},
},
ServiceAttributes: []types.LookupServiceRegistrationAttribute{
{
Key: "com.vmware.cis.cm.GroupInternalId",
Value: "com.vmware.vim.vcenter",
},
{
Key: "com.vmware.vim.vcenter.instanceName",
Value: instance,
},
{
Key: "com.vmware.cis.cm.ControlScript",
Value: "service-control-default-vmon",
},
{
Key: "com.vmware.cis.cm.HostId",
Value: uuid.New().String(),
},
},
ServiceNameResourceKey: "AboutInfo.vpx.name",
ServiceDescriptionResourceKey: "AboutInfo.vpx.name",
},
OwnerId: owner,
ServiceType: types.LookupServiceRegistrationServiceType{
Product: "com.vmware.cis",
Type: "vcenterserver",
},
NodeId: uuid.New().String(),
},
ServiceId: vc.Content.About.InstanceUuid,
SiteId: siteID,
},
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | govc/host/esxcli/guest_info.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/esxcli/guest_info.go#L85-L120 | go | train | // IpAddress attempts to find the guest IP address using esxcli.
// ESX hosts must be configured with the /Net/GuestIPHack enabled.
// For example:
// $ govc host.esxcli -- system settings advanced set -o /Net/GuestIPHack -i 1 | func (g *GuestInfo) IpAddress(vm *object.VirtualMachine) (string, error) | // IpAddress attempts to find the guest IP address using esxcli.
// ESX hosts must be configured with the /Net/GuestIPHack enabled.
// For example:
// $ govc host.esxcli -- system settings advanced set -o /Net/GuestIPHack -i 1
func (g *GuestInfo) IpAddress(vm *object.VirtualMachine) (string, error) | {
ctx := context.TODO()
const any = "0.0.0.0"
var mvm mo.VirtualMachine
pc := property.DefaultCollector(g.c)
err := pc.RetrieveOne(ctx, vm.Reference(), []string{"runtime.host", "config.uuid"}, &mvm)
if err != nil {
return "", err
}
h, err := g.hostInfo(mvm.Runtime.Host)
if err != nil {
return "", err
}
// Normalize uuid, esxcli and mo.VirtualMachine have different formats
uuid := strings.Replace(mvm.Config.Uuid, "-", "", -1)
if wid, ok := h.wids[uuid]; ok {
res, err := h.Run([]string{"network", "vm", "port", "list", "--world-id", wid})
if err != nil {
return "", err
}
for _, val := range res.Values {
if ip, ok := val["IPAddress"]; ok {
if ip[0] != any {
return ip[0], nil
}
}
}
}
return any, nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L100-L127 | go | train | // ErrorCode does its best to map the given error to a VIX error code.
// See also: Vix_TranslateErrno | func ErrorCode(err error) int | // ErrorCode does its best to map the given error to a VIX error code.
// See also: Vix_TranslateErrno
func ErrorCode(err error) int | {
switch t := err.(type) {
case Error:
return int(t)
case *os.PathError:
if errno, ok := t.Err.(syscall.Errno); ok {
switch errno {
case syscall.ENOTEMPTY:
return DirectoryNotEmpty
}
}
case *exec.Error:
if t.Err == exec.ErrNotFound {
return FileNotFound
}
}
switch {
case os.IsNotExist(err):
return FileNotFound
case os.IsExist(err):
return FileAlreadyExists
case os.IsPermission(err):
return FileAccessError
default:
return Fail
}
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L174-L213 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *StartProgramRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *StartProgramRequest) MarshalBinary() ([]byte, error) | {
var env bytes.Buffer
if n := len(r.EnvVars); n != 0 {
for _, e := range r.EnvVars {
_, _ = env.Write([]byte(e))
_ = env.WriteByte(0)
}
r.Body.NumEnvVars = uint32(n)
r.Body.EnvVarLength = uint32(env.Len())
}
var fields []string
add := func(s string, l *uint32) {
if n := len(s); n != 0 {
*l = uint32(n) + 1
fields = append(fields, s)
}
}
add(r.ProgramPath, &r.Body.ProgramPathLength)
add(r.Arguments, &r.Body.ArgumentsLength)
add(r.WorkingDir, &r.Body.WorkingDirLength)
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
for _, val := range fields {
_, _ = buf.Write([]byte(val))
_ = buf.WriteByte(0)
}
if r.Body.EnvVarLength != 0 {
_, _ = buf.Write(env.Bytes())
}
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L216-L253 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *StartProgramRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *StartProgramRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
fields := []struct {
len uint32
val *string
}{
{r.Body.ProgramPathLength, &r.ProgramPath},
{r.Body.ArgumentsLength, &r.Arguments},
{r.Body.WorkingDirLength, &r.WorkingDir},
}
for _, field := range fields {
if field.len == 0 {
continue
}
x := buf.Next(int(field.len))
*field.val = string(bytes.TrimRight(x, "\x00"))
}
for i := 0; i < int(r.Body.NumEnvVars); i++ {
env, rerr := buf.ReadString(0)
if rerr != nil {
return rerr
}
env = env[:len(env)-1] // discard NULL terminator
r.EnvVars = append(r.EnvVars, env)
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L265-L271 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *KillProcessRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *KillProcessRequest) MarshalBinary() ([]byte, error) | {
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L274-L278 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *KillProcessRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *KillProcessRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
return binary.Read(buf, binary.LittleEndian, &r.Body)
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L293-L305 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *ListProcessesRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *ListProcessesRequest) MarshalBinary() ([]byte, error) | {
r.Body.NumPids = uint32(len(r.Pids))
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
for _, pid := range r.Pids {
_ = binary.Write(buf, binary.LittleEndian, &pid)
}
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L308-L326 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *ListProcessesRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *ListProcessesRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
r.Pids = make([]int64, r.Body.NumPids)
for i := uint32(0); i < r.Body.NumPids; i++ {
err := binary.Read(buf, binary.LittleEndian, &r.Pids[i])
if err != nil {
return err
}
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L340-L361 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *ReadEnvironmentVariablesRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *ReadEnvironmentVariablesRequest) MarshalBinary() ([]byte, error) | {
var env bytes.Buffer
if n := len(r.Names); n != 0 {
for _, e := range r.Names {
_, _ = env.Write([]byte(e))
_ = env.WriteByte(0)
}
r.Body.NumNames = uint32(n)
r.Body.NamesLength = uint32(env.Len())
}
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
if r.Body.NamesLength != 0 {
_, _ = buf.Write(env.Bytes())
}
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L364-L383 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *ReadEnvironmentVariablesRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *ReadEnvironmentVariablesRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
for i := 0; i < int(r.Body.NumNames); i++ {
env, rerr := buf.ReadString(0)
if rerr != nil {
return rerr
}
env = env[:len(env)-1] // discard NULL terminator
r.Names = append(r.Names, env)
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L402-L424 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *CreateTempFileRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *CreateTempFileRequest) MarshalBinary() ([]byte, error) | {
var fields []string
add := func(s string, l *uint32) {
*l = uint32(len(s)) // NOTE: NULL byte is not included in the length fields on the wire
fields = append(fields, s)
}
add(r.FilePrefix, &r.Body.FilePrefixLength)
add(r.FileSuffix, &r.Body.FileSuffixLength)
add(r.DirectoryPath, &r.Body.DirectoryPathLength)
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
for _, val := range fields {
_, _ = buf.Write([]byte(val))
_ = buf.WriteByte(0)
}
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L427-L452 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *CreateTempFileRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *CreateTempFileRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
fields := []struct {
len uint32
val *string
}{
{r.Body.FilePrefixLength, &r.FilePrefix},
{r.Body.FileSuffixLength, &r.FileSuffix},
{r.Body.DirectoryPathLength, &r.DirectoryPath},
}
for _, field := range fields {
field.len++ // NOTE: NULL byte is not included in the length fields on the wire
x := buf.Next(int(field.len))
*field.val = string(bytes.TrimRight(x, "\x00"))
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L552-L573 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *RenameFileRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *RenameFileRequest) MarshalBinary() ([]byte, error) | {
var fields []string
add := func(s string, l *uint32) {
*l = uint32(len(s)) // NOTE: NULL byte is not included in the length fields on the wire
fields = append(fields, s)
}
add(r.OldPathName, &r.Body.OldPathNameLength)
add(r.NewPathName, &r.Body.NewPathNameLength)
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
for _, val := range fields {
_, _ = buf.Write([]byte(val))
_ = buf.WriteByte(0)
}
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L576-L600 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *RenameFileRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *RenameFileRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
fields := []struct {
len uint32
val *string
}{
{r.Body.OldPathNameLength, &r.OldPathName},
{r.Body.NewPathNameLength, &r.NewPathName},
}
for _, field := range fields {
field.len++ // NOTE: NULL byte is not included in the length fields on the wire
x := buf.Next(int(field.len))
*field.val = string(bytes.TrimRight(x, "\x00"))
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L619-L642 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *ListFilesRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *ListFilesRequest) MarshalBinary() ([]byte, error) | {
var fields []string
add := func(s string, l *uint32) {
if n := len(s); n != 0 {
*l = uint32(n) + 1
fields = append(fields, s)
}
}
add(r.GuestPathName, &r.Body.GuestPathNameLength)
add(r.Pattern, &r.Body.PatternLength)
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
for _, val := range fields {
_, _ = buf.Write([]byte(val))
_ = buf.WriteByte(0)
}
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L645-L671 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *ListFilesRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *ListFilesRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
fields := []struct {
len uint32
val *string
}{
{r.Body.GuestPathNameLength, &r.GuestPathName},
{r.Body.PatternLength, &r.Pattern},
}
for _, field := range fields {
if field.len == 0 {
continue
}
x := buf.Next(int(field.len))
*field.val = string(bytes.TrimRight(x, "\x00"))
}
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L692-L703 | go | train | // MarshalBinary implements the encoding.BinaryMarshaler interface | func (r *SetGuestFileAttributesRequest) MarshalBinary() ([]byte, error) | // MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *SetGuestFileAttributesRequest) MarshalBinary() ([]byte, error) | {
buf := new(bytes.Buffer)
r.Body.GuestPathNameLength = uint32(len(r.GuestPathName))
_ = binary.Write(buf, binary.LittleEndian, &r.Body)
_, _ = buf.WriteString(r.GuestPathName)
_ = buf.WriteByte(0)
return buf.Bytes(), nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L747-L758 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *CommandHgfsSendPacket) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *CommandHgfsSendPacket) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
r.Packet = buf.Next(int(r.Body.PacketSize))
return nil
} |
vmware/govmomi | fc3f0e9d2275df0e497a80917807a7c72d3c35bc | toolbox/vix/protocol.go | https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/vix/protocol.go#L787-L799 | go | train | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface | func (r *InitiateFileTransferToGuestRequest) UnmarshalBinary(data []byte) error | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *InitiateFileTransferToGuestRequest) UnmarshalBinary(data []byte) error | {
buf := bytes.NewBuffer(data)
err := binary.Read(buf, binary.LittleEndian, &r.Body)
if err != nil {
return err
}
name := buf.Next(int(r.Body.GuestPathNameLength))
r.GuestPathName = string(bytes.TrimRight(name, "\x00"))
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.