repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
vmware/govmomi
simulator/datacenter.go
NewDatacenter
func NewDatacenter(f *Folder) *Datacenter { dc := &Datacenter{ isESX: f.Self == esx.RootFolder.Self, } if dc.isESX { dc.Datacenter = esx.Datacenter } f.putChild(dc) dc.createFolders() return dc }
go
func NewDatacenter(f *Folder) *Datacenter { dc := &Datacenter{ isESX: f.Self == esx.RootFolder.Self, } if dc.isESX { dc.Datacenter = esx.Datacenter } f.putChild(dc) dc.createFolders() return dc }
[ "func", "NewDatacenter", "(", "f", "*", "Folder", ")", "*", "Datacenter", "{", "dc", ":=", "&", "Datacenter", "{", "isESX", ":", "f", ".", "Self", "==", "esx", ".", "RootFolder", ".", "Self", ",", "}", "\n\n", "if", "dc", ".", "isESX", "{", "dc", ".", "Datacenter", "=", "esx", ".", "Datacenter", "\n", "}", "\n\n", "f", ".", "putChild", "(", "dc", ")", "\n\n", "dc", ".", "createFolders", "(", ")", "\n\n", "return", "dc", "\n", "}" ]
// NewDatacenter creates a Datacenter and its child folders.
[ "NewDatacenter", "creates", "a", "Datacenter", "and", "its", "child", "folders", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/datacenter.go#L36-L50
train
vmware/govmomi
vapi/tags/tags.go
CreateTag
func (c *Manager) CreateTag(ctx context.Context, tag *Tag) (string, error) { // create avoids the annoyance of CreateTag requiring a "description" key to be included in the request, // even though the field value can be empty. type create struct { Name string `json:"name"` Description string `json:"description"` CategoryID string `json:"category_id"` } spec := struct { Tag create `json:"create_spec"` }{ Tag: create{ Name: tag.Name, Description: tag.Description, CategoryID: tag.CategoryID, }, } if isName(tag.CategoryID) { cat, err := c.GetCategory(ctx, tag.CategoryID) if err != nil { return "", err } spec.Tag.CategoryID = cat.ID } url := internal.URL(c, internal.TagPath) var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
go
func (c *Manager) CreateTag(ctx context.Context, tag *Tag) (string, error) { // create avoids the annoyance of CreateTag requiring a "description" key to be included in the request, // even though the field value can be empty. type create struct { Name string `json:"name"` Description string `json:"description"` CategoryID string `json:"category_id"` } spec := struct { Tag create `json:"create_spec"` }{ Tag: create{ Name: tag.Name, Description: tag.Description, CategoryID: tag.CategoryID, }, } if isName(tag.CategoryID) { cat, err := c.GetCategory(ctx, tag.CategoryID) if err != nil { return "", err } spec.Tag.CategoryID = cat.ID } url := internal.URL(c, internal.TagPath) var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
[ "func", "(", "c", "*", "Manager", ")", "CreateTag", "(", "ctx", "context", ".", "Context", ",", "tag", "*", "Tag", ")", "(", "string", ",", "error", ")", "{", "// create avoids the annoyance of CreateTag requiring a \"description\" key to be included in the request,", "// even though the field value can be empty.", "type", "create", "struct", "{", "Name", "string", "`json:\"name\"`", "\n", "Description", "string", "`json:\"description\"`", "\n", "CategoryID", "string", "`json:\"category_id\"`", "\n", "}", "\n", "spec", ":=", "struct", "{", "Tag", "create", "`json:\"create_spec\"`", "\n", "}", "{", "Tag", ":", "create", "{", "Name", ":", "tag", ".", "Name", ",", "Description", ":", "tag", ".", "Description", ",", "CategoryID", ":", "tag", ".", "CategoryID", ",", "}", ",", "}", "\n", "if", "isName", "(", "tag", ".", "CategoryID", ")", "{", "cat", ",", "err", ":=", "c", ".", "GetCategory", "(", "ctx", ",", "tag", ".", "CategoryID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "spec", ".", "Tag", ".", "CategoryID", "=", "cat", ".", "ID", "\n", "}", "\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "TagPath", ")", "\n", "var", "res", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "spec", ")", ",", "&", "res", ")", "\n", "}" ]
// CreateTag creates a new tag with the given Name, Description and CategoryID.
[ "CreateTag", "creates", "a", "new", "tag", "with", "the", "given", "Name", "Description", "and", "CategoryID", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L69-L96
train
vmware/govmomi
vapi/tags/tags.go
UpdateTag
func (c *Manager) UpdateTag(ctx context.Context, tag *Tag) error { spec := struct { Tag Tag `json:"update_spec"` }{ Tag: Tag{ Name: tag.Name, Description: tag.Description, }, } url := internal.URL(c, internal.TagPath).WithID(tag.ID) return c.Do(ctx, url.Request(http.MethodPatch, spec), nil) }
go
func (c *Manager) UpdateTag(ctx context.Context, tag *Tag) error { spec := struct { Tag Tag `json:"update_spec"` }{ Tag: Tag{ Name: tag.Name, Description: tag.Description, }, } url := internal.URL(c, internal.TagPath).WithID(tag.ID) return c.Do(ctx, url.Request(http.MethodPatch, spec), nil) }
[ "func", "(", "c", "*", "Manager", ")", "UpdateTag", "(", "ctx", "context", ".", "Context", ",", "tag", "*", "Tag", ")", "error", "{", "spec", ":=", "struct", "{", "Tag", "Tag", "`json:\"update_spec\"`", "\n", "}", "{", "Tag", ":", "Tag", "{", "Name", ":", "tag", ".", "Name", ",", "Description", ":", "tag", ".", "Description", ",", "}", ",", "}", "\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "TagPath", ")", ".", "WithID", "(", "tag", ".", "ID", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPatch", ",", "spec", ")", ",", "nil", ")", "\n", "}" ]
// UpdateTag can update one or both of the tag Description and Name fields.
[ "UpdateTag", "can", "update", "one", "or", "both", "of", "the", "tag", "Description", "and", "Name", "fields", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L99-L110
train
vmware/govmomi
vapi/tags/tags.go
DeleteTag
func (c *Manager) DeleteTag(ctx context.Context, tag *Tag) error { url := internal.URL(c, internal.TagPath).WithID(tag.ID) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
go
func (c *Manager) DeleteTag(ctx context.Context, tag *Tag) error { url := internal.URL(c, internal.TagPath).WithID(tag.ID) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
[ "func", "(", "c", "*", "Manager", ")", "DeleteTag", "(", "ctx", "context", ".", "Context", ",", "tag", "*", "Tag", ")", "error", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "TagPath", ")", ".", "WithID", "(", "tag", ".", "ID", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodDelete", ")", ",", "nil", ")", "\n", "}" ]
// DeleteTag deletes an existing tag.
[ "DeleteTag", "deletes", "an", "existing", "tag", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L113-L116
train
vmware/govmomi
vapi/tags/tags.go
GetTag
func (c *Manager) GetTag(ctx context.Context, id string) (*Tag, error) { if isName(id) { tags, err := c.GetTags(ctx) if err != nil { return nil, err } for i := range tags { if tags[i].Name == id { return &tags[i], nil } } } url := internal.URL(c, internal.TagPath).WithID(id) var res Tag return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
go
func (c *Manager) GetTag(ctx context.Context, id string) (*Tag, error) { if isName(id) { tags, err := c.GetTags(ctx) if err != nil { return nil, err } for i := range tags { if tags[i].Name == id { return &tags[i], nil } } } url := internal.URL(c, internal.TagPath).WithID(id) var res Tag return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
[ "func", "(", "c", "*", "Manager", ")", "GetTag", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "*", "Tag", ",", "error", ")", "{", "if", "isName", "(", "id", ")", "{", "tags", ",", "err", ":=", "c", ".", "GetTags", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "i", ":=", "range", "tags", "{", "if", "tags", "[", "i", "]", ".", "Name", "==", "id", "{", "return", "&", "tags", "[", "i", "]", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "TagPath", ")", ".", "WithID", "(", "id", ")", "\n", "var", "res", "Tag", "\n", "return", "&", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodGet", ")", ",", "&", "res", ")", "\n\n", "}" ]
// GetTag fetches the tag information for the given identifier. // The id parameter can be a Tag ID or Tag Name.
[ "GetTag", "fetches", "the", "tag", "information", "for", "the", "given", "identifier", ".", "The", "id", "parameter", "can", "be", "a", "Tag", "ID", "or", "Tag", "Name", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L120-L138
train
vmware/govmomi
vapi/tags/tags.go
GetTagForCategory
func (c *Manager) GetTagForCategory(ctx context.Context, id, category string) (*Tag, error) { if category == "" { return c.GetTag(ctx, id) } ids, err := c.ListTagsForCategory(ctx, category) if err != nil { return nil, err } for _, tagid := range ids { tag, err := c.GetTag(ctx, tagid) if err != nil { return nil, fmt.Errorf("get tag for category %s %s: %s", category, tagid, err) } if tag.ID == id || tag.Name == id { return tag, nil } } return nil, fmt.Errorf("tag %q not found in category %q", id, category) }
go
func (c *Manager) GetTagForCategory(ctx context.Context, id, category string) (*Tag, error) { if category == "" { return c.GetTag(ctx, id) } ids, err := c.ListTagsForCategory(ctx, category) if err != nil { return nil, err } for _, tagid := range ids { tag, err := c.GetTag(ctx, tagid) if err != nil { return nil, fmt.Errorf("get tag for category %s %s: %s", category, tagid, err) } if tag.ID == id || tag.Name == id { return tag, nil } } return nil, fmt.Errorf("tag %q not found in category %q", id, category) }
[ "func", "(", "c", "*", "Manager", ")", "GetTagForCategory", "(", "ctx", "context", ".", "Context", ",", "id", ",", "category", "string", ")", "(", "*", "Tag", ",", "error", ")", "{", "if", "category", "==", "\"", "\"", "{", "return", "c", ".", "GetTag", "(", "ctx", ",", "id", ")", "\n", "}", "\n\n", "ids", ",", "err", ":=", "c", ".", "ListTagsForCategory", "(", "ctx", ",", "category", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "tagid", ":=", "range", "ids", "{", "tag", ",", "err", ":=", "c", ".", "GetTag", "(", "ctx", ",", "tagid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "category", ",", "tagid", ",", "err", ")", "\n", "}", "\n", "if", "tag", ".", "ID", "==", "id", "||", "tag", ".", "Name", "==", "id", "{", "return", "tag", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "category", ")", "\n", "}" ]
// GetTagForCategory fetches the tag information for the given identifier in the given category.
[ "GetTagForCategory", "fetches", "the", "tag", "information", "for", "the", "given", "identifier", "in", "the", "given", "category", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L141-L162
train
vmware/govmomi
vapi/tags/tags.go
ListTags
func (c *Manager) ListTags(ctx context.Context) ([]string, error) { url := internal.URL(c, internal.TagPath) var res []string return res, c.Do(ctx, url.Request(http.MethodGet), &res) }
go
func (c *Manager) ListTags(ctx context.Context) ([]string, error) { url := internal.URL(c, internal.TagPath) var res []string return res, c.Do(ctx, url.Request(http.MethodGet), &res) }
[ "func", "(", "c", "*", "Manager", ")", "ListTags", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "TagPath", ")", "\n", "var", "res", "[", "]", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodGet", ")", ",", "&", "res", ")", "\n", "}" ]
// ListTags returns all tag IDs in the system.
[ "ListTags", "returns", "all", "tag", "IDs", "in", "the", "system", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L165-L169
train
vmware/govmomi
vapi/tags/tags.go
GetTags
func (c *Manager) GetTags(ctx context.Context) ([]Tag, error) { ids, err := c.ListTags(ctx) if err != nil { return nil, fmt.Errorf("get tags failed for: %s", err) } var tags []Tag for _, id := range ids { tag, err := c.GetTag(ctx, id) if err != nil { return nil, fmt.Errorf("get category %s failed for %s", id, err) } tags = append(tags, *tag) } return tags, nil }
go
func (c *Manager) GetTags(ctx context.Context) ([]Tag, error) { ids, err := c.ListTags(ctx) if err != nil { return nil, fmt.Errorf("get tags failed for: %s", err) } var tags []Tag for _, id := range ids { tag, err := c.GetTag(ctx, id) if err != nil { return nil, fmt.Errorf("get category %s failed for %s", id, err) } tags = append(tags, *tag) } return tags, nil }
[ "func", "(", "c", "*", "Manager", ")", "GetTags", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "Tag", ",", "error", ")", "{", "ids", ",", "err", ":=", "c", ".", "ListTags", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "tags", "[", "]", "Tag", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "tag", ",", "err", ":=", "c", ".", "GetTag", "(", "ctx", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "err", ")", "\n", "}", "\n\n", "tags", "=", "append", "(", "tags", ",", "*", "tag", ")", "\n\n", "}", "\n", "return", "tags", ",", "nil", "\n", "}" ]
// GetTags fetches an array of tag information in the system.
[ "GetTags", "fetches", "an", "array", "of", "tag", "information", "in", "the", "system", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tags.go#L172-L189
train
vmware/govmomi
vim25/soap/client.go
NewServiceClient
func (c *Client) NewServiceClient(path string, namespace string) *Client { vc := c.URL() u, err := url.Parse(path) if err != nil { log.Panicf("url.Parse(%q): %s", path, err) } if u.Host == "" { u.Scheme = vc.Scheme u.Host = vc.Host } client := NewClient(u, c.k) client.Namespace = "urn:" + namespace if cert := c.Certificate(); cert != nil { client.SetCertificate(*cert) } // Copy the trusted thumbprints c.hostsMu.Lock() for k, v := range c.hosts { client.hosts[k] = v } c.hostsMu.Unlock() // Copy the cookies client.Client.Jar.SetCookies(u, c.Client.Jar.Cookies(u)) // Set SOAP Header cookie for _, cookie := range client.Jar.Cookies(u) { if cookie.Name == SessionCookieName { client.cookie = cookie.Value break } } // Copy any query params (e.g. GOVMOMI_TUNNEL_PROXY_PORT used in testing) client.u.RawQuery = vc.RawQuery client.UserAgent = c.UserAgent return client }
go
func (c *Client) NewServiceClient(path string, namespace string) *Client { vc := c.URL() u, err := url.Parse(path) if err != nil { log.Panicf("url.Parse(%q): %s", path, err) } if u.Host == "" { u.Scheme = vc.Scheme u.Host = vc.Host } client := NewClient(u, c.k) client.Namespace = "urn:" + namespace if cert := c.Certificate(); cert != nil { client.SetCertificate(*cert) } // Copy the trusted thumbprints c.hostsMu.Lock() for k, v := range c.hosts { client.hosts[k] = v } c.hostsMu.Unlock() // Copy the cookies client.Client.Jar.SetCookies(u, c.Client.Jar.Cookies(u)) // Set SOAP Header cookie for _, cookie := range client.Jar.Cookies(u) { if cookie.Name == SessionCookieName { client.cookie = cookie.Value break } } // Copy any query params (e.g. GOVMOMI_TUNNEL_PROXY_PORT used in testing) client.u.RawQuery = vc.RawQuery client.UserAgent = c.UserAgent return client }
[ "func", "(", "c", "*", "Client", ")", "NewServiceClient", "(", "path", "string", ",", "namespace", "string", ")", "*", "Client", "{", "vc", ":=", "c", ".", "URL", "(", ")", "\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Panicf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "if", "u", ".", "Host", "==", "\"", "\"", "{", "u", ".", "Scheme", "=", "vc", ".", "Scheme", "\n", "u", ".", "Host", "=", "vc", ".", "Host", "\n", "}", "\n\n", "client", ":=", "NewClient", "(", "u", ",", "c", ".", "k", ")", "\n", "client", ".", "Namespace", "=", "\"", "\"", "+", "namespace", "\n", "if", "cert", ":=", "c", ".", "Certificate", "(", ")", ";", "cert", "!=", "nil", "{", "client", ".", "SetCertificate", "(", "*", "cert", ")", "\n", "}", "\n\n", "// Copy the trusted thumbprints", "c", ".", "hostsMu", ".", "Lock", "(", ")", "\n", "for", "k", ",", "v", ":=", "range", "c", ".", "hosts", "{", "client", ".", "hosts", "[", "k", "]", "=", "v", "\n", "}", "\n", "c", ".", "hostsMu", ".", "Unlock", "(", ")", "\n\n", "// Copy the cookies", "client", ".", "Client", ".", "Jar", ".", "SetCookies", "(", "u", ",", "c", ".", "Client", ".", "Jar", ".", "Cookies", "(", "u", ")", ")", "\n\n", "// Set SOAP Header cookie", "for", "_", ",", "cookie", ":=", "range", "client", ".", "Jar", ".", "Cookies", "(", "u", ")", "{", "if", "cookie", ".", "Name", "==", "SessionCookieName", "{", "client", ".", "cookie", "=", "cookie", ".", "Value", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// Copy any query params (e.g. GOVMOMI_TUNNEL_PROXY_PORT used in testing)", "client", ".", "u", ".", "RawQuery", "=", "vc", ".", "RawQuery", "\n\n", "client", ".", "UserAgent", "=", "c", ".", "UserAgent", "\n\n", "return", "client", "\n", "}" ]
// NewServiceClient creates a NewClient with the given URL.Path and namespace.
[ "NewServiceClient", "creates", "a", "NewClient", "with", "the", "given", "URL", ".", "Path", "and", "namespace", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L159-L200
train
vmware/govmomi
vim25/soap/client.go
hostAddr
func hostAddr(addr string) string { _, port := splitHostPort(addr) if port == "" { return addr + ":443" } return addr }
go
func hostAddr(addr string) string { _, port := splitHostPort(addr) if port == "" { return addr + ":443" } return addr }
[ "func", "hostAddr", "(", "addr", "string", ")", "string", "{", "_", ",", "port", ":=", "splitHostPort", "(", "addr", ")", "\n", "if", "port", "==", "\"", "\"", "{", "return", "addr", "+", "\"", "\"", "\n", "}", "\n", "return", "addr", "\n", "}" ]
// Add default https port if missing
[ "Add", "default", "https", "port", "if", "missing" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L229-L235
train
vmware/govmomi
vim25/soap/client.go
Thumbprint
func (c *Client) Thumbprint(host string) string { host = hostAddr(host) c.hostsMu.Lock() defer c.hostsMu.Unlock() return c.hosts[host] }
go
func (c *Client) Thumbprint(host string) string { host = hostAddr(host) c.hostsMu.Lock() defer c.hostsMu.Unlock() return c.hosts[host] }
[ "func", "(", "c", "*", "Client", ")", "Thumbprint", "(", "host", "string", ")", "string", "{", "host", "=", "hostAddr", "(", "host", ")", "\n", "c", ".", "hostsMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "hostsMu", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "hosts", "[", "host", "]", "\n", "}" ]
// Thumbprint returns the certificate thumbprint for the given host if known to this client.
[ "Thumbprint", "returns", "the", "certificate", "thumbprint", "for", "the", "given", "host", "if", "known", "to", "this", "client", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L256-L261
train
vmware/govmomi
vim25/soap/client.go
LoadThumbprints
func (c *Client) LoadThumbprints(file string) error { if file == "" { return nil } for _, name := range filepath.SplitList(file) { err := c.loadThumbprints(name) if err != nil { return err } } return nil }
go
func (c *Client) LoadThumbprints(file string) error { if file == "" { return nil } for _, name := range filepath.SplitList(file) { err := c.loadThumbprints(name) if err != nil { return err } } return nil }
[ "func", "(", "c", "*", "Client", ")", "LoadThumbprints", "(", "file", "string", ")", "error", "{", "if", "file", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "for", "_", ",", "name", ":=", "range", "filepath", ".", "SplitList", "(", "file", ")", "{", "err", ":=", "c", ".", "loadThumbprints", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// LoadThumbprints from file with the give name. // If name is empty or name does not exist this function will return nil.
[ "LoadThumbprints", "from", "file", "with", "the", "give", "name", ".", "If", "name", "is", "empty", "or", "name", "does", "not", "exist", "this", "function", "will", "return", "nil", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L265-L278
train
vmware/govmomi
vim25/soap/client.go
WithHeader
func (c *Client) WithHeader(ctx context.Context, header Header) context.Context { return context.WithValue(ctx, headerContext{}, header) }
go
func (c *Client) WithHeader(ctx context.Context, header Header) context.Context { return context.WithValue(ctx, headerContext{}, header) }
[ "func", "(", "c", "*", "Client", ")", "WithHeader", "(", "ctx", "context", ".", "Context", ",", "header", "Header", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "headerContext", "{", "}", ",", "header", ")", "\n", "}" ]
// WithHeader can be used to modify the outgoing request soap.Header fields.
[ "WithHeader", "can", "be", "used", "to", "modify", "the", "outgoing", "request", "soap", ".", "Header", "fields", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L511-L513
train
vmware/govmomi
vim25/soap/client.go
Upload
func (c *Client) Upload(ctx context.Context, f io.Reader, u *url.URL, param *Upload) error { var err error if param.Progress != nil { pr := progress.NewReader(ctx, param.Progress, f, param.ContentLength) f = pr // Mark progress reader as done when returning from this function. defer func() { pr.Done(err) }() } req, err := http.NewRequest(param.Method, u.String(), f) if err != nil { return err } req = req.WithContext(ctx) req.ContentLength = param.ContentLength req.Header.Set("Content-Type", param.Type) for k, v := range param.Headers { req.Header.Add(k, v) } if param.Ticket != nil { req.AddCookie(param.Ticket) } res, err := c.Client.Do(req) if err != nil { return err } defer res.Body.Close() switch res.StatusCode { case http.StatusOK: case http.StatusCreated: default: err = errors.New(res.Status) } return err }
go
func (c *Client) Upload(ctx context.Context, f io.Reader, u *url.URL, param *Upload) error { var err error if param.Progress != nil { pr := progress.NewReader(ctx, param.Progress, f, param.ContentLength) f = pr // Mark progress reader as done when returning from this function. defer func() { pr.Done(err) }() } req, err := http.NewRequest(param.Method, u.String(), f) if err != nil { return err } req = req.WithContext(ctx) req.ContentLength = param.ContentLength req.Header.Set("Content-Type", param.Type) for k, v := range param.Headers { req.Header.Add(k, v) } if param.Ticket != nil { req.AddCookie(param.Ticket) } res, err := c.Client.Do(req) if err != nil { return err } defer res.Body.Close() switch res.StatusCode { case http.StatusOK: case http.StatusCreated: default: err = errors.New(res.Status) } return err }
[ "func", "(", "c", "*", "Client", ")", "Upload", "(", "ctx", "context", ".", "Context", ",", "f", "io", ".", "Reader", ",", "u", "*", "url", ".", "URL", ",", "param", "*", "Upload", ")", "error", "{", "var", "err", "error", "\n\n", "if", "param", ".", "Progress", "!=", "nil", "{", "pr", ":=", "progress", ".", "NewReader", "(", "ctx", ",", "param", ".", "Progress", ",", "f", ",", "param", ".", "ContentLength", ")", "\n", "f", "=", "pr", "\n\n", "// Mark progress reader as done when returning from this function.", "defer", "func", "(", ")", "{", "pr", ".", "Done", "(", "err", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "param", ".", "Method", ",", "u", ".", "String", "(", ")", ",", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "req", "=", "req", ".", "WithContext", "(", "ctx", ")", "\n\n", "req", ".", "ContentLength", "=", "param", ".", "ContentLength", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "param", ".", "Type", ")", "\n\n", "for", "k", ",", "v", ":=", "range", "param", ".", "Headers", "{", "req", ".", "Header", ".", "Add", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "if", "param", ".", "Ticket", "!=", "nil", "{", "req", ".", "AddCookie", "(", "param", ".", "Ticket", ")", "\n", "}", "\n\n", "res", ",", "err", ":=", "c", ".", "Client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "case", "http", ".", "StatusCreated", ":", "default", ":", "err", "=", "errors", ".", "New", "(", "res", ".", "Status", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// Upload PUTs the local file to the given URL
[ "Upload", "PUTs", "the", "local", "file", "to", "the", "given", "URL" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L625-L671
train
vmware/govmomi
vim25/soap/client.go
UploadFile
func (c *Client) UploadFile(ctx context.Context, file string, u *url.URL, param *Upload) error { if param == nil { p := DefaultUpload // Copy since we set ContentLength param = &p } s, err := os.Stat(file) if err != nil { return err } f, err := os.Open(filepath.Clean(file)) if err != nil { return err } defer f.Close() param.ContentLength = s.Size() return c.Upload(ctx, f, u, param) }
go
func (c *Client) UploadFile(ctx context.Context, file string, u *url.URL, param *Upload) error { if param == nil { p := DefaultUpload // Copy since we set ContentLength param = &p } s, err := os.Stat(file) if err != nil { return err } f, err := os.Open(filepath.Clean(file)) if err != nil { return err } defer f.Close() param.ContentLength = s.Size() return c.Upload(ctx, f, u, param) }
[ "func", "(", "c", "*", "Client", ")", "UploadFile", "(", "ctx", "context", ".", "Context", ",", "file", "string", ",", "u", "*", "url", ".", "URL", ",", "param", "*", "Upload", ")", "error", "{", "if", "param", "==", "nil", "{", "p", ":=", "DefaultUpload", "// Copy since we set ContentLength", "\n", "param", "=", "&", "p", "\n", "}", "\n\n", "s", ",", "err", ":=", "os", ".", "Stat", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Clean", "(", "file", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "param", ".", "ContentLength", "=", "s", ".", "Size", "(", ")", "\n\n", "return", "c", ".", "Upload", "(", "ctx", ",", "f", ",", "u", ",", "param", ")", "\n", "}" ]
// UploadFile PUTs the local file to the given URL
[ "UploadFile", "PUTs", "the", "local", "file", "to", "the", "given", "URL" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L674-L694
train
vmware/govmomi
vim25/soap/client.go
DownloadRequest
func (c *Client) DownloadRequest(ctx context.Context, u *url.URL, param *Download) (*http.Response, error) { req, err := http.NewRequest(param.Method, u.String(), nil) if err != nil { return nil, err } req = req.WithContext(ctx) for k, v := range param.Headers { req.Header.Add(k, v) } if param.Ticket != nil { req.AddCookie(param.Ticket) } return c.Client.Do(req) }
go
func (c *Client) DownloadRequest(ctx context.Context, u *url.URL, param *Download) (*http.Response, error) { req, err := http.NewRequest(param.Method, u.String(), nil) if err != nil { return nil, err } req = req.WithContext(ctx) for k, v := range param.Headers { req.Header.Add(k, v) } if param.Ticket != nil { req.AddCookie(param.Ticket) } return c.Client.Do(req) }
[ "func", "(", "c", "*", "Client", ")", "DownloadRequest", "(", "ctx", "context", ".", "Context", ",", "u", "*", "url", ".", "URL", ",", "param", "*", "Download", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "param", ".", "Method", ",", "u", ".", "String", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "req", "=", "req", ".", "WithContext", "(", "ctx", ")", "\n\n", "for", "k", ",", "v", ":=", "range", "param", ".", "Headers", "{", "req", ".", "Header", ".", "Add", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "if", "param", ".", "Ticket", "!=", "nil", "{", "req", ".", "AddCookie", "(", "param", ".", "Ticket", ")", "\n", "}", "\n\n", "return", "c", ".", "Client", ".", "Do", "(", "req", ")", "\n", "}" ]
// DownloadRequest wraps http.Client.Do, returning the http.Response without checking its StatusCode
[ "DownloadRequest", "wraps", "http", ".", "Client", ".", "Do", "returning", "the", "http", ".", "Response", "without", "checking", "its", "StatusCode" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L709-L726
train
vmware/govmomi
vim25/soap/client.go
Download
func (c *Client) Download(ctx context.Context, u *url.URL, param *Download) (io.ReadCloser, int64, error) { res, err := c.DownloadRequest(ctx, u, param) if err != nil { return nil, 0, err } switch res.StatusCode { case http.StatusOK: default: err = errors.New(res.Status) } if err != nil { return nil, 0, err } r := res.Body return r, res.ContentLength, nil }
go
func (c *Client) Download(ctx context.Context, u *url.URL, param *Download) (io.ReadCloser, int64, error) { res, err := c.DownloadRequest(ctx, u, param) if err != nil { return nil, 0, err } switch res.StatusCode { case http.StatusOK: default: err = errors.New(res.Status) } if err != nil { return nil, 0, err } r := res.Body return r, res.ContentLength, nil }
[ "func", "(", "c", "*", "Client", ")", "Download", "(", "ctx", "context", ".", "Context", ",", "u", "*", "url", ".", "URL", ",", "param", "*", "Download", ")", "(", "io", ".", "ReadCloser", ",", "int64", ",", "error", ")", "{", "res", ",", "err", ":=", "c", ".", "DownloadRequest", "(", "ctx", ",", "u", ",", "param", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "default", ":", "err", "=", "errors", ".", "New", "(", "res", ".", "Status", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "r", ":=", "res", ".", "Body", "\n\n", "return", "r", ",", "res", ".", "ContentLength", ",", "nil", "\n", "}" ]
// Download GETs the remote file from the given URL
[ "Download", "GETs", "the", "remote", "file", "from", "the", "given", "URL" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L729-L748
train
vmware/govmomi
vim25/soap/client.go
DownloadFile
func (c *Client) DownloadFile(ctx context.Context, file string, u *url.URL, param *Download) error { var err error if param == nil { param = &DefaultDownload } rc, contentLength, err := c.Download(ctx, u, param) if err != nil { return err } return c.WriteFile(ctx, file, rc, contentLength, param.Progress, param.Writer) }
go
func (c *Client) DownloadFile(ctx context.Context, file string, u *url.URL, param *Download) error { var err error if param == nil { param = &DefaultDownload } rc, contentLength, err := c.Download(ctx, u, param) if err != nil { return err } return c.WriteFile(ctx, file, rc, contentLength, param.Progress, param.Writer) }
[ "func", "(", "c", "*", "Client", ")", "DownloadFile", "(", "ctx", "context", ".", "Context", ",", "file", "string", ",", "u", "*", "url", ".", "URL", ",", "param", "*", "Download", ")", "error", "{", "var", "err", "error", "\n", "if", "param", "==", "nil", "{", "param", "=", "&", "DefaultDownload", "\n", "}", "\n\n", "rc", ",", "contentLength", ",", "err", ":=", "c", ".", "Download", "(", "ctx", ",", "u", ",", "param", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "c", ".", "WriteFile", "(", "ctx", ",", "file", ",", "rc", ",", "contentLength", ",", "param", ".", "Progress", ",", "param", ".", "Writer", ")", "\n", "}" ]
// DownloadFile GETs the given URL to a local file
[ "DownloadFile", "GETs", "the", "given", "URL", "to", "a", "local", "file" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/soap/client.go#L788-L800
train
vmware/govmomi
toolbox/process.go
WithIO
func (p *Process) WithIO() *Process { p.IO = &ProcessIO{ Out: new(bytes.Buffer), Err: new(bytes.Buffer), } return p }
go
func (p *Process) WithIO() *Process { p.IO = &ProcessIO{ Out: new(bytes.Buffer), Err: new(bytes.Buffer), } return p }
[ "func", "(", "p", "*", "Process", ")", "WithIO", "(", ")", "*", "Process", "{", "p", ".", "IO", "=", "&", "ProcessIO", "{", "Out", ":", "new", "(", "bytes", ".", "Buffer", ")", ",", "Err", ":", "new", "(", "bytes", ".", "Buffer", ")", ",", "}", "\n\n", "return", "p", "\n", "}" ]
// WithIO enables toolbox Process IO without file system disk IO.
[ "WithIO", "enables", "toolbox", "Process", "IO", "without", "file", "system", "disk", "IO", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L110-L117
train
vmware/govmomi
toolbox/process.go
NewProcessManager
func NewProcessManager() *ProcessManager { // We use pseudo PIDs that don't conflict with OS PIDs, so they can live in the same table. // For the pseudo PIDs, we use a sync.Pool rather than a plain old counter to avoid the unlikely, // but possible wrapping should such a counter exceed MaxInt64. pid := int64(32768) // TODO: /proc/sys/kernel/pid_max return &ProcessManager{ expire: time.Minute * 5, entries: make(map[int64]*Process), pids: sync.Pool{ New: func() interface{} { return atomic.AddInt64(&pid, 1) }, }, } }
go
func NewProcessManager() *ProcessManager { // We use pseudo PIDs that don't conflict with OS PIDs, so they can live in the same table. // For the pseudo PIDs, we use a sync.Pool rather than a plain old counter to avoid the unlikely, // but possible wrapping should such a counter exceed MaxInt64. pid := int64(32768) // TODO: /proc/sys/kernel/pid_max return &ProcessManager{ expire: time.Minute * 5, entries: make(map[int64]*Process), pids: sync.Pool{ New: func() interface{} { return atomic.AddInt64(&pid, 1) }, }, } }
[ "func", "NewProcessManager", "(", ")", "*", "ProcessManager", "{", "// We use pseudo PIDs that don't conflict with OS PIDs, so they can live in the same table.", "// For the pseudo PIDs, we use a sync.Pool rather than a plain old counter to avoid the unlikely,", "// but possible wrapping should such a counter exceed MaxInt64.", "pid", ":=", "int64", "(", "32768", ")", "// TODO: /proc/sys/kernel/pid_max", "\n\n", "return", "&", "ProcessManager", "{", "expire", ":", "time", ".", "Minute", "*", "5", ",", "entries", ":", "make", "(", "map", "[", "int64", "]", "*", "Process", ")", ",", "pids", ":", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "atomic", ".", "AddInt64", "(", "&", "pid", ",", "1", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// NewProcessManager creates a new ProcessManager instance.
[ "NewProcessManager", "creates", "a", "new", "ProcessManager", "instance", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L221-L236
train
vmware/govmomi
toolbox/process.go
Start
func (m *ProcessManager) Start(r *vix.StartProgramRequest, p *Process) (int64, error) { p.Name = r.ProgramPath p.Args = r.Arguments // Owner is cosmetic, but useful for example with: govc guest.ps -U $uid if p.Owner == "" { p.Owner = defaultOwner } p.StartTime = time.Now().Unix() p.ctx, p.Kill = context.WithCancel(context.Background()) pid, err := p.Start(p, r) if err != nil { return -1, err } if pid == 0 { p.Pid = m.pids.Get().(int64) // pseudo pid for funcs } else { p.Pid = pid } m.mu.Lock() m.entries[p.Pid] = p m.mu.Unlock() m.wg.Add(1) go func() { werr := p.Wait() atomic.StoreInt64(&p.EndTime, time.Now().Unix()) if werr != nil { rc := int32(1) if xerr, ok := werr.(*ProcessError); ok { rc = xerr.ExitCode } atomic.StoreInt32(&p.ExitCode, rc) } m.wg.Done() p.Kill() // cancel context for those waiting on p.ctx.Done() // See: http://pubs.vmware.com/vsphere-65/topic/com.vmware.wssdk.apiref.doc/vim.vm.guest.ProcessManager.ProcessInfo.html // "If the process was started using StartProgramInGuest then the process completion time // will be available if queried within 5 minutes after it completes." <-time.After(m.expire) m.mu.Lock() delete(m.entries, p.Pid) m.mu.Unlock() if pid == 0 { m.pids.Put(p.Pid) // pseudo pid can be reused now } }() return p.Pid, nil }
go
func (m *ProcessManager) Start(r *vix.StartProgramRequest, p *Process) (int64, error) { p.Name = r.ProgramPath p.Args = r.Arguments // Owner is cosmetic, but useful for example with: govc guest.ps -U $uid if p.Owner == "" { p.Owner = defaultOwner } p.StartTime = time.Now().Unix() p.ctx, p.Kill = context.WithCancel(context.Background()) pid, err := p.Start(p, r) if err != nil { return -1, err } if pid == 0 { p.Pid = m.pids.Get().(int64) // pseudo pid for funcs } else { p.Pid = pid } m.mu.Lock() m.entries[p.Pid] = p m.mu.Unlock() m.wg.Add(1) go func() { werr := p.Wait() atomic.StoreInt64(&p.EndTime, time.Now().Unix()) if werr != nil { rc := int32(1) if xerr, ok := werr.(*ProcessError); ok { rc = xerr.ExitCode } atomic.StoreInt32(&p.ExitCode, rc) } m.wg.Done() p.Kill() // cancel context for those waiting on p.ctx.Done() // See: http://pubs.vmware.com/vsphere-65/topic/com.vmware.wssdk.apiref.doc/vim.vm.guest.ProcessManager.ProcessInfo.html // "If the process was started using StartProgramInGuest then the process completion time // will be available if queried within 5 minutes after it completes." <-time.After(m.expire) m.mu.Lock() delete(m.entries, p.Pid) m.mu.Unlock() if pid == 0 { m.pids.Put(p.Pid) // pseudo pid can be reused now } }() return p.Pid, nil }
[ "func", "(", "m", "*", "ProcessManager", ")", "Start", "(", "r", "*", "vix", ".", "StartProgramRequest", ",", "p", "*", "Process", ")", "(", "int64", ",", "error", ")", "{", "p", ".", "Name", "=", "r", ".", "ProgramPath", "\n", "p", ".", "Args", "=", "r", ".", "Arguments", "\n\n", "// Owner is cosmetic, but useful for example with: govc guest.ps -U $uid", "if", "p", ".", "Owner", "==", "\"", "\"", "{", "p", ".", "Owner", "=", "defaultOwner", "\n", "}", "\n\n", "p", ".", "StartTime", "=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n\n", "p", ".", "ctx", ",", "p", ".", "Kill", "=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n\n", "pid", ",", "err", ":=", "p", ".", "Start", "(", "p", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "if", "pid", "==", "0", "{", "p", ".", "Pid", "=", "m", ".", "pids", ".", "Get", "(", ")", ".", "(", "int64", ")", "// pseudo pid for funcs", "\n", "}", "else", "{", "p", ".", "Pid", "=", "pid", "\n", "}", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "m", ".", "entries", "[", "p", ".", "Pid", "]", "=", "p", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "m", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "werr", ":=", "p", ".", "Wait", "(", ")", "\n\n", "atomic", ".", "StoreInt64", "(", "&", "p", ".", "EndTime", ",", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n\n", "if", "werr", "!=", "nil", "{", "rc", ":=", "int32", "(", "1", ")", "\n", "if", "xerr", ",", "ok", ":=", "werr", ".", "(", "*", "ProcessError", ")", ";", "ok", "{", "rc", "=", "xerr", ".", "ExitCode", "\n", "}", "\n\n", "atomic", ".", "StoreInt32", "(", "&", "p", ".", "ExitCode", ",", "rc", ")", "\n", "}", "\n\n", "m", ".", "wg", ".", "Done", "(", ")", "\n", "p", ".", "Kill", "(", ")", "// cancel context for those waiting on p.ctx.Done()", "\n\n", "// See: http://pubs.vmware.com/vsphere-65/topic/com.vmware.wssdk.apiref.doc/vim.vm.guest.ProcessManager.ProcessInfo.html", "// \"If the process was started using StartProgramInGuest then the process completion time", "// will be available if queried within 5 minutes after it completes.\"", "<-", "time", ".", "After", "(", "m", ".", "expire", ")", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "delete", "(", "m", ".", "entries", ",", "p", ".", "Pid", ")", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "pid", "==", "0", "{", "m", ".", "pids", ".", "Put", "(", "p", ".", "Pid", ")", "// pseudo pid can be reused now", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "p", ".", "Pid", ",", "nil", "\n", "}" ]
// Start calls the Process.Start function, returning the pid on success or an error. // A goroutine is started that calls the Process.Wait function. After Process.Wait has // returned, the ProcessState EndTime and ExitCode fields are set. The process state can be // queried via ListProcessesInGuest until it is removed, 5 minutes after Wait returns.
[ "Start", "calls", "the", "Process", ".", "Start", "function", "returning", "the", "pid", "on", "success", "or", "an", "error", ".", "A", "goroutine", "is", "started", "that", "calls", "the", "Process", ".", "Wait", "function", ".", "After", "Process", ".", "Wait", "has", "returned", "the", "ProcessState", "EndTime", "and", "ExitCode", "fields", "are", "set", ".", "The", "process", "state", "can", "be", "queried", "via", "ListProcessesInGuest", "until", "it", "is", "removed", "5", "minutes", "after", "Wait", "returns", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L242-L303
train
vmware/govmomi
toolbox/process.go
Kill
func (m *ProcessManager) Kill(pid int64) bool { m.mu.Lock() entry, ok := m.entries[pid] m.mu.Unlock() if ok { entry.Kill() return true } return false }
go
func (m *ProcessManager) Kill(pid int64) bool { m.mu.Lock() entry, ok := m.entries[pid] m.mu.Unlock() if ok { entry.Kill() return true } return false }
[ "func", "(", "m", "*", "ProcessManager", ")", "Kill", "(", "pid", "int64", ")", "bool", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "entry", ",", "ok", ":=", "m", ".", "entries", "[", "pid", "]", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "ok", "{", "entry", ".", "Kill", "(", ")", "\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Kill cancels the Process Context. // Returns true if pid exists in the process table, false otherwise.
[ "Kill", "cancels", "the", "Process", "Context", ".", "Returns", "true", "if", "pid", "exists", "in", "the", "process", "table", "false", "otherwise", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L307-L318
train
vmware/govmomi
toolbox/process.go
ListProcesses
func (m *ProcessManager) ListProcesses(pids []int64) []byte { w := new(bytes.Buffer) m.mu.Lock() if len(pids) == 0 { for _, p := range m.entries { _, _ = w.WriteString(p.toXML()) } } else { for _, id := range pids { p, ok := m.entries[id] if !ok { continue } _, _ = w.WriteString(p.toXML()) } } m.mu.Unlock() return w.Bytes() }
go
func (m *ProcessManager) ListProcesses(pids []int64) []byte { w := new(bytes.Buffer) m.mu.Lock() if len(pids) == 0 { for _, p := range m.entries { _, _ = w.WriteString(p.toXML()) } } else { for _, id := range pids { p, ok := m.entries[id] if !ok { continue } _, _ = w.WriteString(p.toXML()) } } m.mu.Unlock() return w.Bytes() }
[ "func", "(", "m", "*", "ProcessManager", ")", "ListProcesses", "(", "pids", "[", "]", "int64", ")", "[", "]", "byte", "{", "w", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n\n", "if", "len", "(", "pids", ")", "==", "0", "{", "for", "_", ",", "p", ":=", "range", "m", ".", "entries", "{", "_", ",", "_", "=", "w", ".", "WriteString", "(", "p", ".", "toXML", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "id", ":=", "range", "pids", "{", "p", ",", "ok", ":=", "m", ".", "entries", "[", "id", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "_", ",", "_", "=", "w", ".", "WriteString", "(", "p", ".", "toXML", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "w", ".", "Bytes", "(", ")", "\n", "}" ]
// ListProcesses marshals the ProcessState for the given pids. // If no pids are specified, all current processes are included. // The return value can be used for responding to a VixMsgListProcessesExRequest.
[ "ListProcesses", "marshals", "the", "ProcessState", "for", "the", "given", "pids", ".", "If", "no", "pids", "are", "specified", "all", "current", "processes", "are", "included", ".", "The", "return", "value", "can", "be", "used", "for", "responding", "to", "a", "VixMsgListProcessesExRequest", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L323-L346
train
vmware/govmomi
toolbox/process.go
Stat
func (m *ProcessManager) Stat(u *url.URL) (os.FileInfo, error) { name := path.Join("/proc", u.Path) info, err := os.Stat(name) if err == nil && info.Size() == 0 { // This is a real /proc file return &procFileInfo{info}, nil } dir, file := path.Split(u.Path) pid, err := strconv.ParseInt(path.Base(dir), 10, 64) if err != nil { return nil, os.ErrNotExist } m.mu.Lock() p := m.entries[pid] m.mu.Unlock() if p == nil || p.IO == nil { return nil, os.ErrNotExist } pf := &ProcessFile{ name: name, Closer: ioutil.NopCloser(nil), // via hgfs, nop for stdout and stderr } var r *bytes.Buffer switch file { case "stdin": pf.Writer = p.IO.In.Writer pf.Closer = p.IO.In.Closer return pf, nil case "stdout": r = p.IO.Out case "stderr": r = p.IO.Err default: return nil, os.ErrNotExist } select { case <-p.ctx.Done(): case <-time.After(time.Second): // The vmx guest RPC calls are queue based, serialized on the vmx side. // There are 5 seconds between "ping" RPC calls and after a few misses, // the vmx considers tools as not running. In this case, the vmx would timeout // a file transfer after 60 seconds. // // vix.FileAccessError is converted to a CannotAccessFile fault, // so the client can choose to retry the transfer in this case. // Would have preferred vix.ObjectIsBusy (EBUSY), but VC/ESX converts that // to a general SystemErrorFault with nothing but a localized string message // to check against: "<reason>vix error codes = (5, 0).</reason>" // Is standard vmware-tools, EACCES is converted to a CannotAccessFile fault. return nil, vix.Error(vix.FileAccessError) } pf.Reader = r pf.size = r.Len() return pf, nil }
go
func (m *ProcessManager) Stat(u *url.URL) (os.FileInfo, error) { name := path.Join("/proc", u.Path) info, err := os.Stat(name) if err == nil && info.Size() == 0 { // This is a real /proc file return &procFileInfo{info}, nil } dir, file := path.Split(u.Path) pid, err := strconv.ParseInt(path.Base(dir), 10, 64) if err != nil { return nil, os.ErrNotExist } m.mu.Lock() p := m.entries[pid] m.mu.Unlock() if p == nil || p.IO == nil { return nil, os.ErrNotExist } pf := &ProcessFile{ name: name, Closer: ioutil.NopCloser(nil), // via hgfs, nop for stdout and stderr } var r *bytes.Buffer switch file { case "stdin": pf.Writer = p.IO.In.Writer pf.Closer = p.IO.In.Closer return pf, nil case "stdout": r = p.IO.Out case "stderr": r = p.IO.Err default: return nil, os.ErrNotExist } select { case <-p.ctx.Done(): case <-time.After(time.Second): // The vmx guest RPC calls are queue based, serialized on the vmx side. // There are 5 seconds between "ping" RPC calls and after a few misses, // the vmx considers tools as not running. In this case, the vmx would timeout // a file transfer after 60 seconds. // // vix.FileAccessError is converted to a CannotAccessFile fault, // so the client can choose to retry the transfer in this case. // Would have preferred vix.ObjectIsBusy (EBUSY), but VC/ESX converts that // to a general SystemErrorFault with nothing but a localized string message // to check against: "<reason>vix error codes = (5, 0).</reason>" // Is standard vmware-tools, EACCES is converted to a CannotAccessFile fault. return nil, vix.Error(vix.FileAccessError) } pf.Reader = r pf.size = r.Len() return pf, nil }
[ "func", "(", "m", "*", "ProcessManager", ")", "Stat", "(", "u", "*", "url", ".", "URL", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "name", ":=", "path", ".", "Join", "(", "\"", "\"", ",", "u", ".", "Path", ")", "\n\n", "info", ",", "err", ":=", "os", ".", "Stat", "(", "name", ")", "\n", "if", "err", "==", "nil", "&&", "info", ".", "Size", "(", ")", "==", "0", "{", "// This is a real /proc file", "return", "&", "procFileInfo", "{", "info", "}", ",", "nil", "\n", "}", "\n\n", "dir", ",", "file", ":=", "path", ".", "Split", "(", "u", ".", "Path", ")", "\n\n", "pid", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "path", ".", "Base", "(", "dir", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "p", ":=", "m", ".", "entries", "[", "pid", "]", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "p", "==", "nil", "||", "p", ".", "IO", "==", "nil", "{", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n\n", "pf", ":=", "&", "ProcessFile", "{", "name", ":", "name", ",", "Closer", ":", "ioutil", ".", "NopCloser", "(", "nil", ")", ",", "// via hgfs, nop for stdout and stderr", "}", "\n\n", "var", "r", "*", "bytes", ".", "Buffer", "\n\n", "switch", "file", "{", "case", "\"", "\"", ":", "pf", ".", "Writer", "=", "p", ".", "IO", ".", "In", ".", "Writer", "\n", "pf", ".", "Closer", "=", "p", ".", "IO", ".", "In", ".", "Closer", "\n", "return", "pf", ",", "nil", "\n", "case", "\"", "\"", ":", "r", "=", "p", ".", "IO", ".", "Out", "\n", "case", "\"", "\"", ":", "r", "=", "p", ".", "IO", ".", "Err", "\n", "default", ":", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n\n", "select", "{", "case", "<-", "p", ".", "ctx", ".", "Done", "(", ")", ":", "case", "<-", "time", ".", "After", "(", "time", ".", "Second", ")", ":", "// The vmx guest RPC calls are queue based, serialized on the vmx side.", "// There are 5 seconds between \"ping\" RPC calls and after a few misses,", "// the vmx considers tools as not running. In this case, the vmx would timeout", "// a file transfer after 60 seconds.", "//", "// vix.FileAccessError is converted to a CannotAccessFile fault,", "// so the client can choose to retry the transfer in this case.", "// Would have preferred vix.ObjectIsBusy (EBUSY), but VC/ESX converts that", "// to a general SystemErrorFault with nothing but a localized string message", "// to check against: \"<reason>vix error codes = (5, 0).</reason>\"", "// Is standard vmware-tools, EACCES is converted to a CannotAccessFile fault.", "return", "nil", ",", "vix", ".", "Error", "(", "vix", ".", "FileAccessError", ")", "\n", "}", "\n\n", "pf", ".", "Reader", "=", "r", "\n", "pf", ".", "size", "=", "r", ".", "Len", "(", ")", "\n\n", "return", "pf", ",", "nil", "\n", "}" ]
// Stat implements hgfs.FileHandler.Stat
[ "Stat", "implements", "hgfs", ".", "FileHandler", ".", "Stat" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L359-L424
train
vmware/govmomi
toolbox/process.go
Open
func (m *ProcessManager) Open(u *url.URL, mode int32) (hgfs.File, error) { info, err := m.Stat(u) if err != nil { return nil, err } pinfo, ok := info.(*ProcessFile) if !ok { return nil, os.ErrNotExist // fall through to default os.Open } switch path.Base(u.Path) { case "stdin": if mode != hgfs.OpenModeWriteOnly { return nil, vix.Error(vix.InvalidArg) } case "stdout", "stderr": if mode != hgfs.OpenModeReadOnly { return nil, vix.Error(vix.InvalidArg) } } return pinfo, nil }
go
func (m *ProcessManager) Open(u *url.URL, mode int32) (hgfs.File, error) { info, err := m.Stat(u) if err != nil { return nil, err } pinfo, ok := info.(*ProcessFile) if !ok { return nil, os.ErrNotExist // fall through to default os.Open } switch path.Base(u.Path) { case "stdin": if mode != hgfs.OpenModeWriteOnly { return nil, vix.Error(vix.InvalidArg) } case "stdout", "stderr": if mode != hgfs.OpenModeReadOnly { return nil, vix.Error(vix.InvalidArg) } } return pinfo, nil }
[ "func", "(", "m", "*", "ProcessManager", ")", "Open", "(", "u", "*", "url", ".", "URL", ",", "mode", "int32", ")", "(", "hgfs", ".", "File", ",", "error", ")", "{", "info", ",", "err", ":=", "m", ".", "Stat", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pinfo", ",", "ok", ":=", "info", ".", "(", "*", "ProcessFile", ")", "\n\n", "if", "!", "ok", "{", "return", "nil", ",", "os", ".", "ErrNotExist", "// fall through to default os.Open", "\n", "}", "\n\n", "switch", "path", ".", "Base", "(", "u", ".", "Path", ")", "{", "case", "\"", "\"", ":", "if", "mode", "!=", "hgfs", ".", "OpenModeWriteOnly", "{", "return", "nil", ",", "vix", ".", "Error", "(", "vix", ".", "InvalidArg", ")", "\n", "}", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "if", "mode", "!=", "hgfs", ".", "OpenModeReadOnly", "{", "return", "nil", ",", "vix", ".", "Error", "(", "vix", ".", "InvalidArg", ")", "\n", "}", "\n", "}", "\n\n", "return", "pinfo", ",", "nil", "\n", "}" ]
// Open implements hgfs.FileHandler.Open
[ "Open", "implements", "hgfs", ".", "FileHandler", ".", "Open" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L427-L451
train
vmware/govmomi
toolbox/process.go
NewProcessFunc
func NewProcessFunc(run func(ctx context.Context, args string) error) *Process { f := &processFunc{run: run} return &Process{ Start: f.start, Wait: f.wait, } }
go
func NewProcessFunc(run func(ctx context.Context, args string) error) *Process { f := &processFunc{run: run} return &Process{ Start: f.start, Wait: f.wait, } }
[ "func", "NewProcessFunc", "(", "run", "func", "(", "ctx", "context", ".", "Context", ",", "args", "string", ")", "error", ")", "*", "Process", "{", "f", ":=", "&", "processFunc", "{", "run", ":", "run", "}", "\n\n", "return", "&", "Process", "{", "Start", ":", "f", ".", "start", ",", "Wait", ":", "f", ".", "wait", ",", "}", "\n", "}" ]
// NewProcessFunc creates a new Process, where the Start function calls the given run function within a goroutine. // The Wait function waits for the goroutine to finish and returns the error returned by run. // The run ctx param may be used to return early via the ProcessManager.Kill method. // The run args command is that of the VixMsgStartProgramRequest.Arguments field.
[ "NewProcessFunc", "creates", "a", "new", "Process", "where", "the", "Start", "function", "calls", "the", "given", "run", "function", "within", "a", "goroutine", ".", "The", "Wait", "function", "waits", "for", "the", "goroutine", "to", "finish", "and", "returns", "the", "error", "returned", "by", "run", ".", "The", "run", "ctx", "param", "may", "be", "used", "to", "return", "early", "via", "the", "ProcessManager", ".", "Kill", "method", ".", "The", "run", "args", "command", "is", "that", "of", "the", "VixMsgStartProgramRequest", ".", "Arguments", "field", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L465-L472
train
vmware/govmomi
toolbox/process.go
NewProcessRoundTrip
func NewProcessRoundTrip() *Process { return NewProcessFunc(func(ctx context.Context, host string) error { p, _ := ctx.Value(ProcessFuncIO).(*ProcessIO) closers := []io.Closer{p.In.Closer} defer func() { for _, c := range closers { _ = c.Close() } }() c, err := new(net.Dialer).DialContext(ctx, "tcp", host) if err != nil { return err } closers = append(closers, c) go func() { <-ctx.Done() if ctx.Err() == context.DeadlineExceeded { _ = c.Close() } }() _, err = io.Copy(c, p.In.Reader) if err != nil { return err } _, err = io.Copy(p.Out, c) if err != nil { return err } return nil }).WithIO() }
go
func NewProcessRoundTrip() *Process { return NewProcessFunc(func(ctx context.Context, host string) error { p, _ := ctx.Value(ProcessFuncIO).(*ProcessIO) closers := []io.Closer{p.In.Closer} defer func() { for _, c := range closers { _ = c.Close() } }() c, err := new(net.Dialer).DialContext(ctx, "tcp", host) if err != nil { return err } closers = append(closers, c) go func() { <-ctx.Done() if ctx.Err() == context.DeadlineExceeded { _ = c.Close() } }() _, err = io.Copy(c, p.In.Reader) if err != nil { return err } _, err = io.Copy(p.Out, c) if err != nil { return err } return nil }).WithIO() }
[ "func", "NewProcessRoundTrip", "(", ")", "*", "Process", "{", "return", "NewProcessFunc", "(", "func", "(", "ctx", "context", ".", "Context", ",", "host", "string", ")", "error", "{", "p", ",", "_", ":=", "ctx", ".", "Value", "(", "ProcessFuncIO", ")", ".", "(", "*", "ProcessIO", ")", "\n\n", "closers", ":=", "[", "]", "io", ".", "Closer", "{", "p", ".", "In", ".", "Closer", "}", "\n\n", "defer", "func", "(", ")", "{", "for", "_", ",", "c", ":=", "range", "closers", "{", "_", "=", "c", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "c", ",", "err", ":=", "new", "(", "net", ".", "Dialer", ")", ".", "DialContext", "(", "ctx", ",", "\"", "\"", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "closers", "=", "append", "(", "closers", ",", "c", ")", "\n\n", "go", "func", "(", ")", "{", "<-", "ctx", ".", "Done", "(", ")", "\n", "if", "ctx", ".", "Err", "(", ")", "==", "context", ".", "DeadlineExceeded", "{", "_", "=", "c", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "c", ",", "p", ".", "In", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "p", ".", "Out", ",", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", ".", "WithIO", "(", ")", "\n", "}" ]
// NewProcessRoundTrip starts a Go function to implement a toolbox backed http.RoundTripper
[ "NewProcessRoundTrip", "starts", "a", "Go", "function", "to", "implement", "a", "toolbox", "backed", "http", ".", "RoundTripper" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/process.go#L593-L631
train
vmware/govmomi
vim25/progress/reader.go
Read
func (r *reader) Read(b []byte) (int, error) { n, err := r.r.Read(b) r.pos += int64(n) if err != nil && err != io.EOF { return n, err } q := readerReport{ t: time.Now(), pos: r.pos, size: r.size, bps: &r.bps, } select { case r.ch <- q: case <-r.ctx.Done(): } return n, err }
go
func (r *reader) Read(b []byte) (int, error) { n, err := r.r.Read(b) r.pos += int64(n) if err != nil && err != io.EOF { return n, err } q := readerReport{ t: time.Now(), pos: r.pos, size: r.size, bps: &r.bps, } select { case r.ch <- q: case <-r.ctx.Done(): } return n, err }
[ "func", "(", "r", "*", "reader", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "r", ".", "r", ".", "Read", "(", "b", ")", "\n", "r", ".", "pos", "+=", "int64", "(", "n", ")", "\n\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "n", ",", "err", "\n", "}", "\n\n", "q", ":=", "readerReport", "{", "t", ":", "time", ".", "Now", "(", ")", ",", "pos", ":", "r", ".", "pos", ",", "size", ":", "r", ".", "size", ",", "bps", ":", "&", "r", ".", "bps", ",", "}", "\n\n", "select", "{", "case", "r", ".", "ch", "<-", "q", ":", "case", "<-", "r", ".", "ctx", ".", "Done", "(", ")", ":", "}", "\n\n", "return", "n", ",", "err", "\n", "}" ]
// Read calls the Read function on the underlying io.Reader. Additionally, // every read causes a progress report to be sent to the progress reader's // underlying channel.
[ "Read", "calls", "the", "Read", "function", "on", "the", "underlying", "io", ".", "Reader", ".", "Additionally", "every", "read", "causes", "a", "progress", "report", "to", "be", "sent", "to", "the", "progress", "reader", "s", "underlying", "channel", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/reader.go#L101-L122
train
vmware/govmomi
vim25/progress/reader.go
Done
func (r *reader) Done(err error) { q := readerReport{ t: time.Now(), pos: r.pos, size: r.size, bps: &r.bps, err: err, } select { case r.ch <- q: close(r.ch) case <-r.ctx.Done(): } }
go
func (r *reader) Done(err error) { q := readerReport{ t: time.Now(), pos: r.pos, size: r.size, bps: &r.bps, err: err, } select { case r.ch <- q: close(r.ch) case <-r.ctx.Done(): } }
[ "func", "(", "r", "*", "reader", ")", "Done", "(", "err", "error", ")", "{", "q", ":=", "readerReport", "{", "t", ":", "time", ".", "Now", "(", ")", ",", "pos", ":", "r", ".", "pos", ",", "size", ":", "r", ".", "size", ",", "bps", ":", "&", "r", ".", "bps", ",", "err", ":", "err", ",", "}", "\n\n", "select", "{", "case", "r", ".", "ch", "<-", "q", ":", "close", "(", "r", ".", "ch", ")", "\n", "case", "<-", "r", ".", "ctx", ".", "Done", "(", ")", ":", "}", "\n", "}" ]
// Done marks the progress reader as done, optionally including an error in the // progress report. After sending it, the underlying channel is closed.
[ "Done", "marks", "the", "progress", "reader", "as", "done", "optionally", "including", "an", "error", "in", "the", "progress", "report", ".", "After", "sending", "it", "the", "underlying", "channel", "is", "closed", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/reader.go#L126-L140
train
vmware/govmomi
vim25/progress/reader.go
newBpsLoop
func newBpsLoop(dst *uint64) SinkFunc { fn := func() chan<- Report { sink := make(chan Report) go bpsLoop(sink, dst) return sink } return fn }
go
func newBpsLoop(dst *uint64) SinkFunc { fn := func() chan<- Report { sink := make(chan Report) go bpsLoop(sink, dst) return sink } return fn }
[ "func", "newBpsLoop", "(", "dst", "*", "uint64", ")", "SinkFunc", "{", "fn", ":=", "func", "(", ")", "chan", "<-", "Report", "{", "sink", ":=", "make", "(", "chan", "Report", ")", "\n", "go", "bpsLoop", "(", "sink", ",", "dst", ")", "\n", "return", "sink", "\n", "}", "\n\n", "return", "fn", "\n", "}" ]
// newBpsLoop returns a sink that monitors and stores throughput.
[ "newBpsLoop", "returns", "a", "sink", "that", "monitors", "and", "stores", "throughput", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/reader.go#L143-L151
train
vmware/govmomi
vmdk/import.go
stat
func stat(name string) (*info, error) { f, err := os.Open(filepath.Clean(name)) if err != nil { return nil, err } var di info var buf bytes.Buffer _, err = io.CopyN(&buf, f, int64(binary.Size(di.Header))) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { return nil, err } err = f.Close() if err != nil { return nil, err } err = binary.Read(&buf, binary.LittleEndian, &di.Header) if err != nil { return nil, err } if di.Header.MagicNumber != 0x564d444b { // SPARSE_MAGICNUMBER return nil, ErrInvalidFormat } if di.Header.Flags&(1<<16) == 0 { // SPARSEFLAG_COMPRESSED // Needs to be converted, for example: // vmware-vdiskmanager -r src.vmdk -t 5 dst.vmdk // qemu-img convert -O vmdk -o subformat=streamOptimized src.vmdk dst.vmdk return nil, ErrInvalidFormat } di.Capacity = di.Header.Capacity * 512 // VMDK_SECTOR_SIZE di.Size = fi.Size() di.Name = filepath.Base(name) di.ImportName = strings.TrimSuffix(di.Name, ".vmdk") return &di, nil }
go
func stat(name string) (*info, error) { f, err := os.Open(filepath.Clean(name)) if err != nil { return nil, err } var di info var buf bytes.Buffer _, err = io.CopyN(&buf, f, int64(binary.Size(di.Header))) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { return nil, err } err = f.Close() if err != nil { return nil, err } err = binary.Read(&buf, binary.LittleEndian, &di.Header) if err != nil { return nil, err } if di.Header.MagicNumber != 0x564d444b { // SPARSE_MAGICNUMBER return nil, ErrInvalidFormat } if di.Header.Flags&(1<<16) == 0 { // SPARSEFLAG_COMPRESSED // Needs to be converted, for example: // vmware-vdiskmanager -r src.vmdk -t 5 dst.vmdk // qemu-img convert -O vmdk -o subformat=streamOptimized src.vmdk dst.vmdk return nil, ErrInvalidFormat } di.Capacity = di.Header.Capacity * 512 // VMDK_SECTOR_SIZE di.Size = fi.Size() di.Name = filepath.Base(name) di.ImportName = strings.TrimSuffix(di.Name, ".vmdk") return &di, nil }
[ "func", "stat", "(", "name", "string", ")", "(", "*", "info", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "di", "info", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n\n", "_", ",", "err", "=", "io", ".", "CopyN", "(", "&", "buf", ",", "f", ",", "int64", "(", "binary", ".", "Size", "(", "di", ".", "Header", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fi", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "f", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "binary", ".", "Read", "(", "&", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "di", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "di", ".", "Header", ".", "MagicNumber", "!=", "0x564d444b", "{", "// SPARSE_MAGICNUMBER", "return", "nil", ",", "ErrInvalidFormat", "\n", "}", "\n\n", "if", "di", ".", "Header", ".", "Flags", "&", "(", "1", "<<", "16", ")", "==", "0", "{", "// SPARSEFLAG_COMPRESSED", "// Needs to be converted, for example:", "// vmware-vdiskmanager -r src.vmdk -t 5 dst.vmdk", "// qemu-img convert -O vmdk -o subformat=streamOptimized src.vmdk dst.vmdk", "return", "nil", ",", "ErrInvalidFormat", "\n", "}", "\n\n", "di", ".", "Capacity", "=", "di", ".", "Header", ".", "Capacity", "*", "512", "// VMDK_SECTOR_SIZE", "\n", "di", ".", "Size", "=", "fi", ".", "Size", "(", ")", "\n", "di", ".", "Name", "=", "filepath", ".", "Base", "(", "name", ")", "\n", "di", ".", "ImportName", "=", "strings", ".", "TrimSuffix", "(", "di", ".", "Name", ",", "\"", "\"", ")", "\n\n", "return", "&", "di", ",", "nil", "\n", "}" ]
// stat looks at the vmdk header to make sure the format is streamOptimized and // extracts the disk capacity required to properly generate the ovf descriptor.
[ "stat", "looks", "at", "the", "vmdk", "header", "to", "make", "sure", "the", "format", "is", "streamOptimized", "and", "extracts", "the", "disk", "capacity", "required", "to", "properly", "generate", "the", "ovf", "descriptor", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vmdk/import.go#L61-L108
train
vmware/govmomi
vmdk/import.go
ovf
func (di *info) ovf() (string, error) { var buf bytes.Buffer tmpl, err := template.New("ovf").Parse(ovfenv) if err != nil { return "", err } err = tmpl.Execute(&buf, di) if err != nil { return "", err } return buf.String(), nil }
go
func (di *info) ovf() (string, error) { var buf bytes.Buffer tmpl, err := template.New("ovf").Parse(ovfenv) if err != nil { return "", err } err = tmpl.Execute(&buf, di) if err != nil { return "", err } return buf.String(), nil }
[ "func", "(", "di", "*", "info", ")", "ovf", "(", ")", "(", "string", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "ovfenv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "err", "=", "tmpl", ".", "Execute", "(", "&", "buf", ",", "di", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "buf", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// ovf returns an expanded descriptor template
[ "ovf", "returns", "an", "expanded", "descriptor", "template" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vmdk/import.go#L178-L192
train
vmware/govmomi
examples/examples.go
getEnvString
func getEnvString(v string, def string) string { r := os.Getenv(v) if r == "" { return def } return r }
go
func getEnvString(v string, def string) string { r := os.Getenv(v) if r == "" { return def } return r }
[ "func", "getEnvString", "(", "v", "string", ",", "def", "string", ")", "string", "{", "r", ":=", "os", ".", "Getenv", "(", "v", ")", "\n", "if", "r", "==", "\"", "\"", "{", "return", "def", "\n", "}", "\n\n", "return", "r", "\n", "}" ]
// getEnvString returns string from environment variable.
[ "getEnvString", "returns", "string", "from", "environment", "variable", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/examples/examples.go#L33-L40
train
vmware/govmomi
examples/examples.go
getEnvBool
func getEnvBool(v string, def bool) bool { r := os.Getenv(v) if r == "" { return def } switch strings.ToLower(r[0:1]) { case "t", "y", "1": return true } return false }
go
func getEnvBool(v string, def bool) bool { r := os.Getenv(v) if r == "" { return def } switch strings.ToLower(r[0:1]) { case "t", "y", "1": return true } return false }
[ "func", "getEnvBool", "(", "v", "string", ",", "def", "bool", ")", "bool", "{", "r", ":=", "os", ".", "Getenv", "(", "v", ")", "\n", "if", "r", "==", "\"", "\"", "{", "return", "def", "\n", "}", "\n\n", "switch", "strings", ".", "ToLower", "(", "r", "[", "0", ":", "1", "]", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// getEnvBool returns boolean from environment variable.
[ "getEnvBool", "returns", "boolean", "from", "environment", "variable", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/examples/examples.go#L43-L55
train
vmware/govmomi
examples/examples.go
NewClient
func NewClient(ctx context.Context) (*govmomi.Client, error) { flag.Parse() // Parse URL from string u, err := soap.ParseURL(*urlFlag) if err != nil { return nil, err } // Override username and/or password as required processOverride(u) // Connect and log in to ESX or vCenter return govmomi.NewClient(ctx, u, *insecureFlag) }
go
func NewClient(ctx context.Context) (*govmomi.Client, error) { flag.Parse() // Parse URL from string u, err := soap.ParseURL(*urlFlag) if err != nil { return nil, err } // Override username and/or password as required processOverride(u) // Connect and log in to ESX or vCenter return govmomi.NewClient(ctx, u, *insecureFlag) }
[ "func", "NewClient", "(", "ctx", "context", ".", "Context", ")", "(", "*", "govmomi", ".", "Client", ",", "error", ")", "{", "flag", ".", "Parse", "(", ")", "\n\n", "// Parse URL from string", "u", ",", "err", ":=", "soap", ".", "ParseURL", "(", "*", "urlFlag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Override username and/or password as required", "processOverride", "(", "u", ")", "\n\n", "// Connect and log in to ESX or vCenter", "return", "govmomi", ".", "NewClient", "(", "ctx", ",", "u", ",", "*", "insecureFlag", ")", "\n", "}" ]
// NewClient creates a govmomi.Client for use in the examples
[ "NewClient", "creates", "a", "govmomi", ".", "Client", "for", "use", "in", "the", "examples" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/examples/examples.go#L103-L117
train
vmware/govmomi
task/wait.go
Wait
func Wait(ctx context.Context, ref types.ManagedObjectReference, pc *property.Collector, s progress.Sinker) (*types.TaskInfo, error) { cb := &taskCallback{} // Include progress sink if specified if s != nil { cb.ch = s.Sink() defer close(cb.ch) } err := property.Wait(ctx, pc, ref, []string{"info"}, cb.fn) if err != nil { return nil, err } return cb.info, cb.err }
go
func Wait(ctx context.Context, ref types.ManagedObjectReference, pc *property.Collector, s progress.Sinker) (*types.TaskInfo, error) { cb := &taskCallback{} // Include progress sink if specified if s != nil { cb.ch = s.Sink() defer close(cb.ch) } err := property.Wait(ctx, pc, ref, []string{"info"}, cb.fn) if err != nil { return nil, err } return cb.info, cb.err }
[ "func", "Wait", "(", "ctx", "context", ".", "Context", ",", "ref", "types", ".", "ManagedObjectReference", ",", "pc", "*", "property", ".", "Collector", ",", "s", "progress", ".", "Sinker", ")", "(", "*", "types", ".", "TaskInfo", ",", "error", ")", "{", "cb", ":=", "&", "taskCallback", "{", "}", "\n\n", "// Include progress sink if specified", "if", "s", "!=", "nil", "{", "cb", ".", "ch", "=", "s", ".", "Sink", "(", ")", "\n", "defer", "close", "(", "cb", ".", "ch", ")", "\n", "}", "\n\n", "err", ":=", "property", ".", "Wait", "(", "ctx", ",", "pc", ",", "ref", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "cb", ".", "fn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "cb", ".", "info", ",", "cb", ".", "err", "\n", "}" ]
// Wait waits for a task to finish with either success or failure. It does so // by waiting for the "info" property of task managed object to change. The // function returns when it finds the task in the "success" or "error" state. // In the former case, the return value is nil. In the latter case the return // value is an instance of this package's Error struct. // // Any error returned while waiting for property changes causes the function to // return immediately and propagate the error. // // If the progress.Sinker argument is specified, any progress updates for the // task are sent here. The completion percentage is passed through directly. // The detail for the progress update is set to an empty string. If the task // finishes in the error state, the error instance is passed through as well. // Note that this error is the same error that is returned by this function. //
[ "Wait", "waits", "for", "a", "task", "to", "finish", "with", "either", "success", "or", "failure", ".", "It", "does", "so", "by", "waiting", "for", "the", "info", "property", "of", "task", "managed", "object", "to", "change", ".", "The", "function", "returns", "when", "it", "finds", "the", "task", "in", "the", "success", "or", "error", "state", ".", "In", "the", "former", "case", "the", "return", "value", "is", "nil", ".", "In", "the", "latter", "case", "the", "return", "value", "is", "an", "instance", "of", "this", "package", "s", "Error", "struct", ".", "Any", "error", "returned", "while", "waiting", "for", "property", "changes", "causes", "the", "function", "to", "return", "immediately", "and", "propagate", "the", "error", ".", "If", "the", "progress", ".", "Sinker", "argument", "is", "specified", "any", "progress", "updates", "for", "the", "task", "are", "sent", "here", ".", "The", "completion", "percentage", "is", "passed", "through", "directly", ".", "The", "detail", "for", "the", "progress", "update", "is", "set", "to", "an", "empty", "string", ".", "If", "the", "task", "finishes", "in", "the", "error", "state", "the", "error", "instance", "is", "passed", "through", "as", "well", ".", "Note", "that", "this", "error", "is", "the", "same", "error", "that", "is", "returned", "by", "this", "function", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/task/wait.go#L117-L132
train
vmware/govmomi
object/datastore_file.go
Open
func (d Datastore) Open(ctx context.Context, name string) (*DatastoreFile, error) { return &DatastoreFile{ d: d, name: name, length: -1, ctx: ctx, }, nil }
go
func (d Datastore) Open(ctx context.Context, name string) (*DatastoreFile, error) { return &DatastoreFile{ d: d, name: name, length: -1, ctx: ctx, }, nil }
[ "func", "(", "d", "Datastore", ")", "Open", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "(", "*", "DatastoreFile", ",", "error", ")", "{", "return", "&", "DatastoreFile", "{", "d", ":", "d", ",", "name", ":", "name", ",", "length", ":", "-", "1", ",", "ctx", ":", "ctx", ",", "}", ",", "nil", "\n", "}" ]
// Open opens the named file relative to the Datastore.
[ "Open", "opens", "the", "named", "file", "relative", "to", "the", "Datastore", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L49-L56
train
vmware/govmomi
object/datastore_file.go
Close
func (f *DatastoreFile) Close() error { var err error if f.body != nil { err = f.body.Close() f.body = nil } f.buf = nil return err }
go
func (f *DatastoreFile) Close() error { var err error if f.body != nil { err = f.body.Close() f.body = nil } f.buf = nil return err }
[ "func", "(", "f", "*", "DatastoreFile", ")", "Close", "(", ")", "error", "{", "var", "err", "error", "\n\n", "if", "f", ".", "body", "!=", "nil", "{", "err", "=", "f", ".", "body", ".", "Close", "(", ")", "\n", "f", ".", "body", "=", "nil", "\n", "}", "\n\n", "f", ".", "buf", "=", "nil", "\n\n", "return", "err", "\n", "}" ]
// Close closes the DatastoreFile.
[ "Close", "closes", "the", "DatastoreFile", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L90-L101
train
vmware/govmomi
object/datastore_file.go
Seek
func (f *DatastoreFile) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: case io.SeekCurrent: offset += f.offset.seek case io.SeekEnd: if f.length < 0 { _, err := f.Stat() if err != nil { return 0, err } } offset += f.length default: return 0, errors.New("Seek: invalid whence") } // allow negative SeekStart for initial Range request if offset < 0 { return 0, errors.New("Seek: invalid offset") } f.offset.seek = offset return offset, nil }
go
func (f *DatastoreFile) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: case io.SeekCurrent: offset += f.offset.seek case io.SeekEnd: if f.length < 0 { _, err := f.Stat() if err != nil { return 0, err } } offset += f.length default: return 0, errors.New("Seek: invalid whence") } // allow negative SeekStart for initial Range request if offset < 0 { return 0, errors.New("Seek: invalid offset") } f.offset.seek = offset return offset, nil }
[ "func", "(", "f", "*", "DatastoreFile", ")", "Seek", "(", "offset", "int64", ",", "whence", "int", ")", "(", "int64", ",", "error", ")", "{", "switch", "whence", "{", "case", "io", ".", "SeekStart", ":", "case", "io", ".", "SeekCurrent", ":", "offset", "+=", "f", ".", "offset", ".", "seek", "\n", "case", "io", ".", "SeekEnd", ":", "if", "f", ".", "length", "<", "0", "{", "_", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "offset", "+=", "f", ".", "length", "\n", "default", ":", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// allow negative SeekStart for initial Range request", "if", "offset", "<", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "f", ".", "offset", ".", "seek", "=", "offset", "\n\n", "return", "offset", ",", "nil", "\n", "}" ]
// Seek sets the offset for the next Read on the DatastoreFile.
[ "Seek", "sets", "the", "offset", "for", "the", "next", "Read", "on", "the", "DatastoreFile", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L104-L129
train
vmware/govmomi
object/datastore_file.go
Stat
func (f *DatastoreFile) Stat() (os.FileInfo, error) { // TODO: consider using Datastore.Stat() instead u, p, err := f.d.downloadTicket(f.ctx, f.name, &soap.Download{Method: "HEAD"}) if err != nil { return nil, err } res, err := f.d.Client().DownloadRequest(f.ctx, u, p) if err != nil { return nil, err } if res.StatusCode != http.StatusOK { return nil, statusError(res) } f.length = res.ContentLength return &fileStat{f, res.Header}, nil }
go
func (f *DatastoreFile) Stat() (os.FileInfo, error) { // TODO: consider using Datastore.Stat() instead u, p, err := f.d.downloadTicket(f.ctx, f.name, &soap.Download{Method: "HEAD"}) if err != nil { return nil, err } res, err := f.d.Client().DownloadRequest(f.ctx, u, p) if err != nil { return nil, err } if res.StatusCode != http.StatusOK { return nil, statusError(res) } f.length = res.ContentLength return &fileStat{f, res.Header}, nil }
[ "func", "(", "f", "*", "DatastoreFile", ")", "Stat", "(", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "// TODO: consider using Datastore.Stat() instead", "u", ",", "p", ",", "err", ":=", "f", ".", "d", ".", "downloadTicket", "(", "f", ".", "ctx", ",", "f", ".", "name", ",", "&", "soap", ".", "Download", "{", "Method", ":", "\"", "\"", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "f", ".", "d", ".", "Client", "(", ")", ".", "DownloadRequest", "(", "f", ".", "ctx", ",", "u", ",", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "statusError", "(", "res", ")", "\n", "}", "\n\n", "f", ".", "length", "=", "res", ".", "ContentLength", "\n\n", "return", "&", "fileStat", "{", "f", ",", "res", ".", "Header", "}", ",", "nil", "\n", "}" ]
// Stat returns the os.FileInfo interface describing file.
[ "Stat", "returns", "the", "os", ".", "FileInfo", "interface", "describing", "file", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L168-L187
train
vmware/govmomi
object/datastore_file.go
Tail
func (f *DatastoreFile) Tail(n int) error { return f.TailFunc(n, func(line int, _ string) bool { return n > line }) }
go
func (f *DatastoreFile) Tail(n int) error { return f.TailFunc(n, func(line int, _ string) bool { return n > line }) }
[ "func", "(", "f", "*", "DatastoreFile", ")", "Tail", "(", "n", "int", ")", "error", "{", "return", "f", ".", "TailFunc", "(", "n", ",", "func", "(", "line", "int", ",", "_", "string", ")", "bool", "{", "return", "n", ">", "line", "}", ")", "\n", "}" ]
// Tail seeks to the position of the last N lines of the file.
[ "Tail", "seeks", "to", "the", "position", "of", "the", "last", "N", "lines", "of", "the", "file", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L260-L262
train
vmware/govmomi
object/datastore_file.go
TailFunc
func (f *DatastoreFile) TailFunc(lines int, include func(line int, message string) bool) error { // Read the file in reverse using bsize chunks const bsize = int64(1024 * 16) fsize, err := f.Seek(0, io.SeekEnd) if err != nil { return err } if lines == 0 { return nil } chunk := int64(-1) buf := bytes.NewBuffer(make([]byte, 0, bsize)) line := 0 for { var eof bool var pos int64 nread := bsize offset := chunk * bsize remain := fsize + offset if remain < 0 { if pos, err = f.Seek(0, io.SeekStart); err != nil { return err } nread = bsize + remain eof = true } else if pos, err = f.Seek(offset, io.SeekEnd); err != nil { return err } if _, err = io.CopyN(buf, f, nread); err != nil { if err != io.EOF { return err } } b := buf.Bytes() idx, done := lastIndexLines(b, &line, include) if done { if chunk == -1 { // We found all N lines in the last chunk of the file. // The seek offset is also now at the current end of file. // Save this buffer to avoid another GET request when Read() is called. buf.Next(int(idx + 1)) f.buf = buf return nil } if _, err = f.Seek(pos+idx+1, io.SeekStart); err != nil { return err } break } if eof { if remain < 0 { // We found < N lines in the entire file, so seek to the start. _, _ = f.Seek(0, io.SeekStart) } break } chunk-- buf.Reset() } return nil }
go
func (f *DatastoreFile) TailFunc(lines int, include func(line int, message string) bool) error { // Read the file in reverse using bsize chunks const bsize = int64(1024 * 16) fsize, err := f.Seek(0, io.SeekEnd) if err != nil { return err } if lines == 0 { return nil } chunk := int64(-1) buf := bytes.NewBuffer(make([]byte, 0, bsize)) line := 0 for { var eof bool var pos int64 nread := bsize offset := chunk * bsize remain := fsize + offset if remain < 0 { if pos, err = f.Seek(0, io.SeekStart); err != nil { return err } nread = bsize + remain eof = true } else if pos, err = f.Seek(offset, io.SeekEnd); err != nil { return err } if _, err = io.CopyN(buf, f, nread); err != nil { if err != io.EOF { return err } } b := buf.Bytes() idx, done := lastIndexLines(b, &line, include) if done { if chunk == -1 { // We found all N lines in the last chunk of the file. // The seek offset is also now at the current end of file. // Save this buffer to avoid another GET request when Read() is called. buf.Next(int(idx + 1)) f.buf = buf return nil } if _, err = f.Seek(pos+idx+1, io.SeekStart); err != nil { return err } break } if eof { if remain < 0 { // We found < N lines in the entire file, so seek to the start. _, _ = f.Seek(0, io.SeekStart) } break } chunk-- buf.Reset() } return nil }
[ "func", "(", "f", "*", "DatastoreFile", ")", "TailFunc", "(", "lines", "int", ",", "include", "func", "(", "line", "int", ",", "message", "string", ")", "bool", ")", "error", "{", "// Read the file in reverse using bsize chunks", "const", "bsize", "=", "int64", "(", "1024", "*", "16", ")", "\n\n", "fsize", ",", "err", ":=", "f", ".", "Seek", "(", "0", ",", "io", ".", "SeekEnd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "lines", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "chunk", ":=", "int64", "(", "-", "1", ")", "\n\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "bsize", ")", ")", "\n", "line", ":=", "0", "\n\n", "for", "{", "var", "eof", "bool", "\n", "var", "pos", "int64", "\n\n", "nread", ":=", "bsize", "\n\n", "offset", ":=", "chunk", "*", "bsize", "\n", "remain", ":=", "fsize", "+", "offset", "\n\n", "if", "remain", "<", "0", "{", "if", "pos", ",", "err", "=", "f", ".", "Seek", "(", "0", ",", "io", ".", "SeekStart", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "nread", "=", "bsize", "+", "remain", "\n", "eof", "=", "true", "\n", "}", "else", "if", "pos", ",", "err", "=", "f", ".", "Seek", "(", "offset", ",", "io", ".", "SeekEnd", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "_", ",", "err", "=", "io", ".", "CopyN", "(", "buf", ",", "f", ",", "nread", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "b", ":=", "buf", ".", "Bytes", "(", ")", "\n", "idx", ",", "done", ":=", "lastIndexLines", "(", "b", ",", "&", "line", ",", "include", ")", "\n\n", "if", "done", "{", "if", "chunk", "==", "-", "1", "{", "// We found all N lines in the last chunk of the file.", "// The seek offset is also now at the current end of file.", "// Save this buffer to avoid another GET request when Read() is called.", "buf", ".", "Next", "(", "int", "(", "idx", "+", "1", ")", ")", "\n", "f", ".", "buf", "=", "buf", "\n", "return", "nil", "\n", "}", "\n\n", "if", "_", ",", "err", "=", "f", ".", "Seek", "(", "pos", "+", "idx", "+", "1", ",", "io", ".", "SeekStart", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "break", "\n", "}", "\n\n", "if", "eof", "{", "if", "remain", "<", "0", "{", "// We found < N lines in the entire file, so seek to the start.", "_", ",", "_", "=", "f", ".", "Seek", "(", "0", ",", "io", ".", "SeekStart", ")", "\n", "}", "\n", "break", "\n", "}", "\n\n", "chunk", "--", "\n", "buf", ".", "Reset", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// TailFunc will seek backwards in the datastore file until it hits a line that does // not satisfy the supplied `include` function.
[ "TailFunc", "will", "seek", "backwards", "in", "the", "datastore", "file", "until", "it", "hits", "a", "line", "that", "does", "not", "satisfy", "the", "supplied", "include", "function", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L266-L343
train
vmware/govmomi
object/datastore_file.go
Close
func (f *followDatastoreFile) Close() error { f.o.Do(func() { close(f.c) }) return nil }
go
func (f *followDatastoreFile) Close() error { f.o.Do(func() { close(f.c) }) return nil }
[ "func", "(", "f", "*", "followDatastoreFile", ")", "Close", "(", ")", "error", "{", "f", ".", "o", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "f", ".", "c", ")", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Close will stop Follow polling and close the underlying DatastoreFile.
[ "Close", "will", "stop", "Follow", "polling", "and", "close", "the", "underlying", "DatastoreFile", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L400-L403
train
vmware/govmomi
object/datastore_file.go
Follow
func (f *DatastoreFile) Follow(interval time.Duration) io.ReadCloser { return &followDatastoreFile{ r: f, c: make(chan struct{}), i: interval, } }
go
func (f *DatastoreFile) Follow(interval time.Duration) io.ReadCloser { return &followDatastoreFile{ r: f, c: make(chan struct{}), i: interval, } }
[ "func", "(", "f", "*", "DatastoreFile", ")", "Follow", "(", "interval", "time", ".", "Duration", ")", "io", ".", "ReadCloser", "{", "return", "&", "followDatastoreFile", "{", "r", ":", "f", ",", "c", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "i", ":", "interval", ",", "}", "\n", "}" ]
// Follow returns an io.ReadCloser to stream the file contents as data is appended.
[ "Follow", "returns", "an", "io", ".", "ReadCloser", "to", "stream", "the", "file", "contents", "as", "data", "is", "appended", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/datastore_file.go#L406-L412
train
vmware/govmomi
object/host_certificate_info.go
FromCertificate
func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo { info.Certificate = cert info.subjectName = &cert.Subject info.issuerName = &cert.Issuer info.Issuer = info.fromName(info.issuerName) info.NotBefore = &cert.NotBefore info.NotAfter = &cert.NotAfter info.Subject = info.fromName(info.subjectName) info.ThumbprintSHA1 = soap.ThumbprintSHA1(cert) // SHA-256 for info purposes only, API fields all use SHA-1 sum := sha256.Sum256(cert.Raw) hex := make([]string, len(sum)) for i, b := range sum { hex[i] = fmt.Sprintf("%02X", b) } info.ThumbprintSHA256 = strings.Join(hex, ":") if info.Status == "" { info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusUnknown) } return info }
go
func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo { info.Certificate = cert info.subjectName = &cert.Subject info.issuerName = &cert.Issuer info.Issuer = info.fromName(info.issuerName) info.NotBefore = &cert.NotBefore info.NotAfter = &cert.NotAfter info.Subject = info.fromName(info.subjectName) info.ThumbprintSHA1 = soap.ThumbprintSHA1(cert) // SHA-256 for info purposes only, API fields all use SHA-1 sum := sha256.Sum256(cert.Raw) hex := make([]string, len(sum)) for i, b := range sum { hex[i] = fmt.Sprintf("%02X", b) } info.ThumbprintSHA256 = strings.Join(hex, ":") if info.Status == "" { info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusUnknown) } return info }
[ "func", "(", "info", "*", "HostCertificateInfo", ")", "FromCertificate", "(", "cert", "*", "x509", ".", "Certificate", ")", "*", "HostCertificateInfo", "{", "info", ".", "Certificate", "=", "cert", "\n", "info", ".", "subjectName", "=", "&", "cert", ".", "Subject", "\n", "info", ".", "issuerName", "=", "&", "cert", ".", "Issuer", "\n\n", "info", ".", "Issuer", "=", "info", ".", "fromName", "(", "info", ".", "issuerName", ")", "\n", "info", ".", "NotBefore", "=", "&", "cert", ".", "NotBefore", "\n", "info", ".", "NotAfter", "=", "&", "cert", ".", "NotAfter", "\n", "info", ".", "Subject", "=", "info", ".", "fromName", "(", "info", ".", "subjectName", ")", "\n\n", "info", ".", "ThumbprintSHA1", "=", "soap", ".", "ThumbprintSHA1", "(", "cert", ")", "\n\n", "// SHA-256 for info purposes only, API fields all use SHA-1", "sum", ":=", "sha256", ".", "Sum256", "(", "cert", ".", "Raw", ")", "\n", "hex", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "sum", ")", ")", "\n", "for", "i", ",", "b", ":=", "range", "sum", "{", "hex", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ")", "\n", "}", "\n", "info", ".", "ThumbprintSHA256", "=", "strings", ".", "Join", "(", "hex", ",", "\"", "\"", ")", "\n\n", "if", "info", ".", "Status", "==", "\"", "\"", "{", "info", ".", "Status", "=", "string", "(", "types", ".", "HostCertificateManagerCertificateInfoCertificateStatusUnknown", ")", "\n", "}", "\n\n", "return", "info", "\n", "}" ]
// FromCertificate converts x509.Certificate to HostCertificateInfo
[ "FromCertificate", "converts", "x509", ".", "Certificate", "to", "HostCertificateInfo" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L50-L75
train
vmware/govmomi
object/host_certificate_info.go
FromURL
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error { addr := u.Host if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) { addr += ":443" } conn, err := tls.Dial("tcp", addr, config) if err != nil { switch err.(type) { case x509.UnknownAuthorityError: case x509.HostnameError: default: return err } info.Err = err conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true}) if err != nil { return err } } else { info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood) } state := conn.ConnectionState() _ = conn.Close() info.FromCertificate(state.PeerCertificates[0]) return nil }
go
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error { addr := u.Host if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) { addr += ":443" } conn, err := tls.Dial("tcp", addr, config) if err != nil { switch err.(type) { case x509.UnknownAuthorityError: case x509.HostnameError: default: return err } info.Err = err conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true}) if err != nil { return err } } else { info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood) } state := conn.ConnectionState() _ = conn.Close() info.FromCertificate(state.PeerCertificates[0]) return nil }
[ "func", "(", "info", "*", "HostCertificateInfo", ")", "FromURL", "(", "u", "*", "url", ".", "URL", ",", "config", "*", "tls", ".", "Config", ")", "error", "{", "addr", ":=", "u", ".", "Host", "\n", "if", "!", "(", "strings", ".", "LastIndex", "(", "addr", ",", "\"", "\"", ")", ">", "strings", ".", "LastIndex", "(", "addr", ",", "\"", "\"", ")", ")", "{", "addr", "+=", "\"", "\"", "\n", "}", "\n\n", "conn", ",", "err", ":=", "tls", ".", "Dial", "(", "\"", "\"", ",", "addr", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "(", "type", ")", "{", "case", "x509", ".", "UnknownAuthorityError", ":", "case", "x509", ".", "HostnameError", ":", "default", ":", "return", "err", "\n", "}", "\n\n", "info", ".", "Err", "=", "err", "\n\n", "conn", ",", "err", "=", "tls", ".", "Dial", "(", "\"", "\"", ",", "addr", ",", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "info", ".", "Status", "=", "string", "(", "types", ".", "HostCertificateManagerCertificateInfoCertificateStatusGood", ")", "\n", "}", "\n\n", "state", ":=", "conn", ".", "ConnectionState", "(", ")", "\n", "_", "=", "conn", ".", "Close", "(", ")", "\n", "info", ".", "FromCertificate", "(", "state", ".", "PeerCertificates", "[", "0", "]", ")", "\n\n", "return", "nil", "\n", "}" ]
// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo // via tls.ConnectionState. If the certificate was verified with the given tls.Config, the Err field will be nil. // Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError. // If tls.Dial returns an error of any other type, that error is returned.
[ "FromURL", "connects", "to", "the", "given", "URL", ".", "Host", "via", "tls", ".", "Dial", "with", "the", "given", "tls", ".", "Config", "and", "populates", "the", "HostCertificateInfo", "via", "tls", ".", "ConnectionState", ".", "If", "the", "certificate", "was", "verified", "with", "the", "given", "tls", ".", "Config", "the", "Err", "field", "will", "be", "nil", ".", "Otherwise", "Err", "will", "be", "set", "to", "the", "x509", ".", "UnknownAuthorityError", "or", "x509", ".", "HostnameError", ".", "If", "tls", ".", "Dial", "returns", "an", "error", "of", "any", "other", "type", "that", "error", "is", "returned", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L81-L111
train
vmware/govmomi
object/host_certificate_info.go
SubjectName
func (info *HostCertificateInfo) SubjectName() *pkix.Name { if info.subjectName != nil { return info.subjectName } return info.toName(info.Subject) }
go
func (info *HostCertificateInfo) SubjectName() *pkix.Name { if info.subjectName != nil { return info.subjectName } return info.toName(info.Subject) }
[ "func", "(", "info", "*", "HostCertificateInfo", ")", "SubjectName", "(", ")", "*", "pkix", ".", "Name", "{", "if", "info", ".", "subjectName", "!=", "nil", "{", "return", "info", ".", "subjectName", "\n", "}", "\n\n", "return", "info", ".", "toName", "(", "info", ".", "Subject", ")", "\n", "}" ]
// SubjectName parses Subject into a pkix.Name
[ "SubjectName", "parses", "Subject", "into", "a", "pkix", ".", "Name" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L187-L193
train
vmware/govmomi
object/host_certificate_info.go
IssuerName
func (info *HostCertificateInfo) IssuerName() *pkix.Name { if info.issuerName != nil { return info.issuerName } return info.toName(info.Issuer) }
go
func (info *HostCertificateInfo) IssuerName() *pkix.Name { if info.issuerName != nil { return info.issuerName } return info.toName(info.Issuer) }
[ "func", "(", "info", "*", "HostCertificateInfo", ")", "IssuerName", "(", ")", "*", "pkix", ".", "Name", "{", "if", "info", ".", "issuerName", "!=", "nil", "{", "return", "info", ".", "issuerName", "\n", "}", "\n\n", "return", "info", ".", "toName", "(", "info", ".", "Issuer", ")", "\n", "}" ]
// IssuerName parses Issuer into a pkix.Name
[ "IssuerName", "parses", "Issuer", "into", "a", "pkix", ".", "Name" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L196-L202
train
vmware/govmomi
object/host_certificate_info.go
Write
func (info *HostCertificateInfo) Write(w io.Writer) error { tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0) s := func(val string) string { if val != "" { return val } return "<Not Part Of Certificate>" } ss := func(val []string) string { return s(strings.Join(val, ",")) } name := func(n *pkix.Name) { fmt.Fprintf(tw, " Common Name (CN):\t%s\n", s(n.CommonName)) fmt.Fprintf(tw, " Organization (O):\t%s\n", ss(n.Organization)) fmt.Fprintf(tw, " Organizational Unit (OU):\t%s\n", ss(n.OrganizationalUnit)) } status := info.Status if info.Err != nil { status = fmt.Sprintf("ERROR %s", info.Err) } fmt.Fprintf(tw, "Certificate Status:\t%s\n", status) fmt.Fprintln(tw, "Issued To:\t") name(info.SubjectName()) fmt.Fprintln(tw, "Issued By:\t") name(info.IssuerName()) fmt.Fprintln(tw, "Validity Period:\t") fmt.Fprintf(tw, " Issued On:\t%s\n", info.NotBefore) fmt.Fprintf(tw, " Expires On:\t%s\n", info.NotAfter) if info.ThumbprintSHA1 != "" { fmt.Fprintln(tw, "Thumbprints:\t") if info.ThumbprintSHA256 != "" { fmt.Fprintf(tw, " SHA-256 Thumbprint:\t%s\n", info.ThumbprintSHA256) } fmt.Fprintf(tw, " SHA-1 Thumbprint:\t%s\n", info.ThumbprintSHA1) } return tw.Flush() }
go
func (info *HostCertificateInfo) Write(w io.Writer) error { tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0) s := func(val string) string { if val != "" { return val } return "<Not Part Of Certificate>" } ss := func(val []string) string { return s(strings.Join(val, ",")) } name := func(n *pkix.Name) { fmt.Fprintf(tw, " Common Name (CN):\t%s\n", s(n.CommonName)) fmt.Fprintf(tw, " Organization (O):\t%s\n", ss(n.Organization)) fmt.Fprintf(tw, " Organizational Unit (OU):\t%s\n", ss(n.OrganizationalUnit)) } status := info.Status if info.Err != nil { status = fmt.Sprintf("ERROR %s", info.Err) } fmt.Fprintf(tw, "Certificate Status:\t%s\n", status) fmt.Fprintln(tw, "Issued To:\t") name(info.SubjectName()) fmt.Fprintln(tw, "Issued By:\t") name(info.IssuerName()) fmt.Fprintln(tw, "Validity Period:\t") fmt.Fprintf(tw, " Issued On:\t%s\n", info.NotBefore) fmt.Fprintf(tw, " Expires On:\t%s\n", info.NotAfter) if info.ThumbprintSHA1 != "" { fmt.Fprintln(tw, "Thumbprints:\t") if info.ThumbprintSHA256 != "" { fmt.Fprintf(tw, " SHA-256 Thumbprint:\t%s\n", info.ThumbprintSHA256) } fmt.Fprintf(tw, " SHA-1 Thumbprint:\t%s\n", info.ThumbprintSHA1) } return tw.Flush() }
[ "func", "(", "info", "*", "HostCertificateInfo", ")", "Write", "(", "w", "io", ".", "Writer", ")", "error", "{", "tw", ":=", "tabwriter", ".", "NewWriter", "(", "w", ",", "2", ",", "0", ",", "2", ",", "' '", ",", "0", ")", "\n\n", "s", ":=", "func", "(", "val", "string", ")", "string", "{", "if", "val", "!=", "\"", "\"", "{", "return", "val", "\n", "}", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "ss", ":=", "func", "(", "val", "[", "]", "string", ")", "string", "{", "return", "s", "(", "strings", ".", "Join", "(", "val", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "name", ":=", "func", "(", "n", "*", "pkix", ".", "Name", ")", "{", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "s", "(", "n", ".", "CommonName", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "ss", "(", "n", ".", "Organization", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "ss", "(", "n", ".", "OrganizationalUnit", ")", ")", "\n", "}", "\n\n", "status", ":=", "info", ".", "Status", "\n", "if", "info", ".", "Err", "!=", "nil", "{", "status", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "info", ".", "Err", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "status", ")", "\n\n", "fmt", ".", "Fprintln", "(", "tw", ",", "\"", "\\t", "\"", ")", "\n", "name", "(", "info", ".", "SubjectName", "(", ")", ")", "\n\n", "fmt", ".", "Fprintln", "(", "tw", ",", "\"", "\\t", "\"", ")", "\n", "name", "(", "info", ".", "IssuerName", "(", ")", ")", "\n\n", "fmt", ".", "Fprintln", "(", "tw", ",", "\"", "\\t", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "info", ".", "NotBefore", ")", "\n", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "info", ".", "NotAfter", ")", "\n\n", "if", "info", ".", "ThumbprintSHA1", "!=", "\"", "\"", "{", "fmt", ".", "Fprintln", "(", "tw", ",", "\"", "\\t", "\"", ")", "\n", "if", "info", ".", "ThumbprintSHA256", "!=", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "info", ".", "ThumbprintSHA256", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "info", ".", "ThumbprintSHA1", ")", "\n", "}", "\n\n", "return", "tw", ".", "Flush", "(", ")", "\n", "}" ]
// Write outputs info similar to the Chrome Certificate Viewer.
[ "Write", "outputs", "info", "similar", "to", "the", "Chrome", "Certificate", "Viewer", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_info.go#L205-L250
train
vmware/govmomi
toolbox/hgfs/encoding.go
MarshalBinary
func MarshalBinary(fields ...interface{}) ([]byte, error) { buf := new(bytes.Buffer) for _, p := range fields { switch m := p.(type) { case encoding.BinaryMarshaler: data, err := m.MarshalBinary() if err != nil { return nil, ProtocolError(err) } _, _ = buf.Write(data) case []byte: _, _ = buf.Write(m) case string: _, _ = buf.WriteString(m) default: err := binary.Write(buf, binary.LittleEndian, p) if err != nil { return nil, ProtocolError(err) } } } return buf.Bytes(), nil }
go
func MarshalBinary(fields ...interface{}) ([]byte, error) { buf := new(bytes.Buffer) for _, p := range fields { switch m := p.(type) { case encoding.BinaryMarshaler: data, err := m.MarshalBinary() if err != nil { return nil, ProtocolError(err) } _, _ = buf.Write(data) case []byte: _, _ = buf.Write(m) case string: _, _ = buf.WriteString(m) default: err := binary.Write(buf, binary.LittleEndian, p) if err != nil { return nil, ProtocolError(err) } } } return buf.Bytes(), nil }
[ "func", "MarshalBinary", "(", "fields", "...", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "for", "_", ",", "p", ":=", "range", "fields", "{", "switch", "m", ":=", "p", ".", "(", "type", ")", "{", "case", "encoding", ".", "BinaryMarshaler", ":", "data", ",", "err", ":=", "m", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ProtocolError", "(", "err", ")", "\n", "}", "\n\n", "_", ",", "_", "=", "buf", ".", "Write", "(", "data", ")", "\n", "case", "[", "]", "byte", ":", "_", ",", "_", "=", "buf", ".", "Write", "(", "m", ")", "\n", "case", "string", ":", "_", ",", "_", "=", "buf", ".", "WriteString", "(", "m", ")", "\n", "default", ":", "err", ":=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ProtocolError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalBinary is a wrapper around binary.Write
[ "MarshalBinary", "is", "a", "wrapper", "around", "binary", ".", "Write" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/encoding.go#L26-L51
train
vmware/govmomi
toolbox/hgfs/encoding.go
UnmarshalBinary
func UnmarshalBinary(data []byte, fields ...interface{}) error { buf := bytes.NewBuffer(data) for _, p := range fields { switch m := p.(type) { case encoding.BinaryUnmarshaler: return m.UnmarshalBinary(buf.Bytes()) case *[]byte: *m = buf.Bytes() return nil default: err := binary.Read(buf, binary.LittleEndian, p) if err != nil { return ProtocolError(err) } } } return nil }
go
func UnmarshalBinary(data []byte, fields ...interface{}) error { buf := bytes.NewBuffer(data) for _, p := range fields { switch m := p.(type) { case encoding.BinaryUnmarshaler: return m.UnmarshalBinary(buf.Bytes()) case *[]byte: *m = buf.Bytes() return nil default: err := binary.Read(buf, binary.LittleEndian, p) if err != nil { return ProtocolError(err) } } } return nil }
[ "func", "UnmarshalBinary", "(", "data", "[", "]", "byte", ",", "fields", "...", "interface", "{", "}", ")", "error", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n\n", "for", "_", ",", "p", ":=", "range", "fields", "{", "switch", "m", ":=", "p", ".", "(", "type", ")", "{", "case", "encoding", ".", "BinaryUnmarshaler", ":", "return", "m", ".", "UnmarshalBinary", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "case", "*", "[", "]", "byte", ":", "*", "m", "=", "buf", ".", "Bytes", "(", ")", "\n", "return", "nil", "\n", "default", ":", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ProtocolError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary is a wrapper around binary.Read
[ "UnmarshalBinary", "is", "a", "wrapper", "around", "binary", ".", "Read" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/encoding.go#L54-L73
train
vmware/govmomi
ssoadmin/methods/role.go
C14N
func (b *LoginBody) C14N() string { req, err := xml.Marshal(b.Req) if err != nil { panic(err) } return string(req) }
go
func (b *LoginBody) C14N() string { req, err := xml.Marshal(b.Req) if err != nil { panic(err) } return string(req) }
[ "func", "(", "b", "*", "LoginBody", ")", "C14N", "(", ")", "string", "{", "req", ",", "err", ":=", "xml", ".", "Marshal", "(", "b", ".", "Req", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "req", ")", "\n", "}" ]
// C14N returns the canonicalized form of LoginBody.Req, for use by sts.Signer
[ "C14N", "returns", "the", "canonicalized", "form", "of", "LoginBody", ".", "Req", "for", "use", "by", "sts", ".", "Signer" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ssoadmin/methods/role.go#L70-L76
train
vmware/govmomi
simulator/model.go
ESX
func ESX() *Model { return &Model{ ServiceContent: esx.ServiceContent, RootFolder: esx.RootFolder, Autostart: true, Datastore: 1, Machine: 2, DelayConfig: DelayConfig{ Delay: 0, DelayJitter: 0, MethodDelay: nil, }, } }
go
func ESX() *Model { return &Model{ ServiceContent: esx.ServiceContent, RootFolder: esx.RootFolder, Autostart: true, Datastore: 1, Machine: 2, DelayConfig: DelayConfig{ Delay: 0, DelayJitter: 0, MethodDelay: nil, }, } }
[ "func", "ESX", "(", ")", "*", "Model", "{", "return", "&", "Model", "{", "ServiceContent", ":", "esx", ".", "ServiceContent", ",", "RootFolder", ":", "esx", ".", "RootFolder", ",", "Autostart", ":", "true", ",", "Datastore", ":", "1", ",", "Machine", ":", "2", ",", "DelayConfig", ":", "DelayConfig", "{", "Delay", ":", "0", ",", "DelayJitter", ":", "0", ",", "MethodDelay", ":", "nil", ",", "}", ",", "}", "\n", "}" ]
// ESX is the default Model for a standalone ESX instance
[ "ESX", "is", "the", "default", "Model", "for", "a", "standalone", "ESX", "instance" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L107-L120
train
vmware/govmomi
simulator/model.go
VPX
func VPX() *Model { return &Model{ ServiceContent: vpx.ServiceContent, RootFolder: vpx.RootFolder, Autostart: true, Datacenter: 1, Portgroup: 1, Host: 1, Cluster: 1, ClusterHost: 3, Datastore: 1, Machine: 2, DelayConfig: DelayConfig{ Delay: 0, DelayJitter: 0, MethodDelay: nil, }, } }
go
func VPX() *Model { return &Model{ ServiceContent: vpx.ServiceContent, RootFolder: vpx.RootFolder, Autostart: true, Datacenter: 1, Portgroup: 1, Host: 1, Cluster: 1, ClusterHost: 3, Datastore: 1, Machine: 2, DelayConfig: DelayConfig{ Delay: 0, DelayJitter: 0, MethodDelay: nil, }, } }
[ "func", "VPX", "(", ")", "*", "Model", "{", "return", "&", "Model", "{", "ServiceContent", ":", "vpx", ".", "ServiceContent", ",", "RootFolder", ":", "vpx", ".", "RootFolder", ",", "Autostart", ":", "true", ",", "Datacenter", ":", "1", ",", "Portgroup", ":", "1", ",", "Host", ":", "1", ",", "Cluster", ":", "1", ",", "ClusterHost", ":", "3", ",", "Datastore", ":", "1", ",", "Machine", ":", "2", ",", "DelayConfig", ":", "DelayConfig", "{", "Delay", ":", "0", ",", "DelayJitter", ":", "0", ",", "MethodDelay", ":", "nil", ",", "}", ",", "}", "\n", "}" ]
// VPX is the default Model for a vCenter instance
[ "VPX", "is", "the", "default", "Model", "for", "a", "vCenter", "instance" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L123-L141
train
vmware/govmomi
simulator/model.go
Count
func (m *Model) Count() Model { count := Model{} for ref, obj := range Map.objects { if _, ok := obj.(mo.Entity); !ok { continue } count.total++ switch ref.Type { case "Datacenter": count.Datacenter++ case "DistributedVirtualPortgroup": count.Portgroup++ case "ClusterComputeResource": count.Cluster++ case "Datastore": count.Datastore++ case "HostSystem": count.Host++ case "VirtualMachine": count.Machine++ case "ResourcePool": count.Pool++ case "VirtualApp": count.App++ case "Folder": count.Folder++ case "StoragePod": count.Pod++ } } return count }
go
func (m *Model) Count() Model { count := Model{} for ref, obj := range Map.objects { if _, ok := obj.(mo.Entity); !ok { continue } count.total++ switch ref.Type { case "Datacenter": count.Datacenter++ case "DistributedVirtualPortgroup": count.Portgroup++ case "ClusterComputeResource": count.Cluster++ case "Datastore": count.Datastore++ case "HostSystem": count.Host++ case "VirtualMachine": count.Machine++ case "ResourcePool": count.Pool++ case "VirtualApp": count.App++ case "Folder": count.Folder++ case "StoragePod": count.Pod++ } } return count }
[ "func", "(", "m", "*", "Model", ")", "Count", "(", ")", "Model", "{", "count", ":=", "Model", "{", "}", "\n\n", "for", "ref", ",", "obj", ":=", "range", "Map", ".", "objects", "{", "if", "_", ",", "ok", ":=", "obj", ".", "(", "mo", ".", "Entity", ")", ";", "!", "ok", "{", "continue", "\n", "}", "\n\n", "count", ".", "total", "++", "\n\n", "switch", "ref", ".", "Type", "{", "case", "\"", "\"", ":", "count", ".", "Datacenter", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Portgroup", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Cluster", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Datastore", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Host", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Machine", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Pool", "++", "\n", "case", "\"", "\"", ":", "count", ".", "App", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Folder", "++", "\n", "case", "\"", "\"", ":", "count", ".", "Pod", "++", "\n", "}", "\n", "}", "\n\n", "return", "count", "\n", "}" ]
// Count returns a Model with total number of each existing type
[ "Count", "returns", "a", "Model", "with", "total", "number", "of", "each", "existing", "type" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L144-L179
train
vmware/govmomi
simulator/model.go
Remove
func (m *Model) Remove() { for _, dir := range m.dirs { _ = os.RemoveAll(dir) } }
go
func (m *Model) Remove() { for _, dir := range m.dirs { _ = os.RemoveAll(dir) } }
[ "func", "(", "m", "*", "Model", ")", "Remove", "(", ")", "{", "for", "_", ",", "dir", ":=", "range", "m", ".", "dirs", "{", "_", "=", "os", ".", "RemoveAll", "(", "dir", ")", "\n", "}", "\n", "}" ]
// Remove cleans up items created by the Model, such as local datastore directories
[ "Remove", "cleans", "up", "items", "created", "by", "the", "Model", "such", "as", "local", "datastore", "directories" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/model.go#L516-L520
train
vmware/govmomi
govc/host/autostart/autostart.go
VirtualMachines
func (f *AutostartFlag) VirtualMachines(args []string) ([]*object.VirtualMachine, error) { ctx := context.TODO() if len(args) == 0 { return nil, errors.New("no argument") } finder, err := f.Finder() if err != nil { return nil, err } var out []*object.VirtualMachine for _, arg := range args { vms, err := finder.VirtualMachineList(ctx, arg) if err != nil { return nil, err } out = append(out, vms...) } return out, nil }
go
func (f *AutostartFlag) VirtualMachines(args []string) ([]*object.VirtualMachine, error) { ctx := context.TODO() if len(args) == 0 { return nil, errors.New("no argument") } finder, err := f.Finder() if err != nil { return nil, err } var out []*object.VirtualMachine for _, arg := range args { vms, err := finder.VirtualMachineList(ctx, arg) if err != nil { return nil, err } out = append(out, vms...) } return out, nil }
[ "func", "(", "f", "*", "AutostartFlag", ")", "VirtualMachines", "(", "args", "[", "]", "string", ")", "(", "[", "]", "*", "object", ".", "VirtualMachine", ",", "error", ")", "{", "ctx", ":=", "context", ".", "TODO", "(", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "finder", ",", "err", ":=", "f", ".", "Finder", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "out", "[", "]", "*", "object", ".", "VirtualMachine", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "vms", ",", "err", ":=", "finder", ".", "VirtualMachineList", "(", "ctx", ",", "arg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "out", "=", "append", "(", "out", ",", "vms", "...", ")", "\n", "}", "\n\n", "return", "out", ",", "nil", "\n", "}" ]
// VirtualMachines returns list of virtual machine objects based on the // arguments specified on the command line. This helper is defined in // flags.SearchFlag as well, but that pulls in other virtual machine flags that // are not relevant here.
[ "VirtualMachines", "returns", "list", "of", "virtual", "machine", "objects", "based", "on", "the", "arguments", "specified", "on", "the", "command", "line", ".", "This", "helper", "is", "defined", "in", "flags", ".", "SearchFlag", "as", "well", "but", "that", "pulls", "in", "other", "virtual", "machine", "flags", "that", "are", "not", "relevant", "here", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/autostart/autostart.go#L68-L90
train
vmware/govmomi
vim25/retry.go
Retry
func Retry(roundTripper soap.RoundTripper, fn RetryFunc) soap.RoundTripper { r := &retry{ roundTripper: roundTripper, fn: fn, } return r }
go
func Retry(roundTripper soap.RoundTripper, fn RetryFunc) soap.RoundTripper { r := &retry{ roundTripper: roundTripper, fn: fn, } return r }
[ "func", "Retry", "(", "roundTripper", "soap", ".", "RoundTripper", ",", "fn", "RetryFunc", ")", "soap", ".", "RoundTripper", "{", "r", ":=", "&", "retry", "{", "roundTripper", ":", "roundTripper", ",", "fn", ":", "fn", ",", "}", "\n\n", "return", "r", "\n", "}" ]
// Retry wraps the specified soap.RoundTripper and invokes the // specified RetryFunc. The RetryFunc returns whether or not to // retry the call, and if so, how long to wait before retrying. If // the result of this function is to not retry, the original error // is returned from the RoundTrip function.
[ "Retry", "wraps", "the", "specified", "soap", ".", "RoundTripper", "and", "invokes", "the", "specified", "RetryFunc", ".", "The", "RetryFunc", "returns", "whether", "or", "not", "to", "retry", "the", "call", "and", "if", "so", "how", "long", "to", "wait", "before", "retrying", ".", "If", "the", "result", "of", "this", "function", "is", "to", "not", "retry", "the", "original", "error", "is", "returned", "from", "the", "RoundTrip", "function", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/retry.go#L77-L84
train
vmware/govmomi
object/custom_fields_manager.go
GetCustomFieldsManager
func GetCustomFieldsManager(c *vim25.Client) (*CustomFieldsManager, error) { if c.ServiceContent.CustomFieldsManager == nil { return nil, ErrNotSupported } return NewCustomFieldsManager(c), nil }
go
func GetCustomFieldsManager(c *vim25.Client) (*CustomFieldsManager, error) { if c.ServiceContent.CustomFieldsManager == nil { return nil, ErrNotSupported } return NewCustomFieldsManager(c), nil }
[ "func", "GetCustomFieldsManager", "(", "c", "*", "vim25", ".", "Client", ")", "(", "*", "CustomFieldsManager", ",", "error", ")", "{", "if", "c", ".", "ServiceContent", ".", "CustomFieldsManager", "==", "nil", "{", "return", "nil", ",", "ErrNotSupported", "\n", "}", "\n", "return", "NewCustomFieldsManager", "(", "c", ")", ",", "nil", "\n", "}" ]
// GetCustomFieldsManager wraps NewCustomFieldsManager, returning ErrNotSupported // when the client is not connected to a vCenter instance.
[ "GetCustomFieldsManager", "wraps", "NewCustomFieldsManager", "returning", "ErrNotSupported", "when", "the", "client", "is", "not", "connected", "to", "a", "vCenter", "instance", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/custom_fields_manager.go#L40-L45
train
vmware/govmomi
object/diagnostic_log.go
Seek
func (l *DiagnosticLog) Seek(ctx context.Context, nlines int32) error { h, err := l.m.BrowseLog(ctx, l.Host, l.Key, math.MaxInt32, 0) if err != nil { return err } l.Start = h.LineEnd - nlines return nil }
go
func (l *DiagnosticLog) Seek(ctx context.Context, nlines int32) error { h, err := l.m.BrowseLog(ctx, l.Host, l.Key, math.MaxInt32, 0) if err != nil { return err } l.Start = h.LineEnd - nlines return nil }
[ "func", "(", "l", "*", "DiagnosticLog", ")", "Seek", "(", "ctx", "context", ".", "Context", ",", "nlines", "int32", ")", "error", "{", "h", ",", "err", ":=", "l", ".", "m", ".", "BrowseLog", "(", "ctx", ",", "l", ".", "Host", ",", "l", ".", "Key", ",", "math", ".", "MaxInt32", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "l", ".", "Start", "=", "h", ".", "LineEnd", "-", "nlines", "\n\n", "return", "nil", "\n", "}" ]
// Seek to log position starting at the last nlines of the log
[ "Seek", "to", "log", "position", "starting", "at", "the", "last", "nlines", "of", "the", "log" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/diagnostic_log.go#L37-L46
train
vmware/govmomi
object/diagnostic_log.go
Copy
func (l *DiagnosticLog) Copy(ctx context.Context, w io.Writer) (int, error) { const max = 500 // VC max == 500, ESX max == 1000 written := 0 for { h, err := l.m.BrowseLog(ctx, l.Host, l.Key, l.Start, max) if err != nil { return 0, err } for _, line := range h.LineText { n, err := fmt.Fprintln(w, line) written += n if err != nil { return written, err } } l.Start += int32(len(h.LineText)) if l.Start >= h.LineEnd { break } } return written, nil }
go
func (l *DiagnosticLog) Copy(ctx context.Context, w io.Writer) (int, error) { const max = 500 // VC max == 500, ESX max == 1000 written := 0 for { h, err := l.m.BrowseLog(ctx, l.Host, l.Key, l.Start, max) if err != nil { return 0, err } for _, line := range h.LineText { n, err := fmt.Fprintln(w, line) written += n if err != nil { return written, err } } l.Start += int32(len(h.LineText)) if l.Start >= h.LineEnd { break } } return written, nil }
[ "func", "(", "l", "*", "DiagnosticLog", ")", "Copy", "(", "ctx", "context", ".", "Context", ",", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "const", "max", "=", "500", "// VC max == 500, ESX max == 1000", "\n", "written", ":=", "0", "\n\n", "for", "{", "h", ",", "err", ":=", "l", ".", "m", ".", "BrowseLog", "(", "ctx", ",", "l", ".", "Host", ",", "l", ".", "Key", ",", "l", ".", "Start", ",", "max", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "line", ":=", "range", "h", ".", "LineText", "{", "n", ",", "err", ":=", "fmt", ".", "Fprintln", "(", "w", ",", "line", ")", "\n", "written", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "written", ",", "err", "\n", "}", "\n", "}", "\n\n", "l", ".", "Start", "+=", "int32", "(", "len", "(", "h", ".", "LineText", ")", ")", "\n\n", "if", "l", ".", "Start", ">=", "h", ".", "LineEnd", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "written", ",", "nil", "\n", "}" ]
// Copy log starting from l.Start to the given io.Writer // Returns on error or when end of log is reached.
[ "Copy", "log", "starting", "from", "l", ".", "Start", "to", "the", "given", "io", ".", "Writer", "Returns", "on", "error", "or", "when", "end", "of", "log", "is", "reached", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/diagnostic_log.go#L50-L76
train
vmware/govmomi
object/search_index.go
FindByDatastorePath
func (s SearchIndex) FindByDatastorePath(ctx context.Context, dc *Datacenter, path string) (Reference, error) { req := types.FindByDatastorePath{ This: s.Reference(), Datacenter: dc.Reference(), Path: path, } res, err := methods.FindByDatastorePath(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
go
func (s SearchIndex) FindByDatastorePath(ctx context.Context, dc *Datacenter, path string) (Reference, error) { req := types.FindByDatastorePath{ This: s.Reference(), Datacenter: dc.Reference(), Path: path, } res, err := methods.FindByDatastorePath(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
[ "func", "(", "s", "SearchIndex", ")", "FindByDatastorePath", "(", "ctx", "context", ".", "Context", ",", "dc", "*", "Datacenter", ",", "path", "string", ")", "(", "Reference", ",", "error", ")", "{", "req", ":=", "types", ".", "FindByDatastorePath", "{", "This", ":", "s", ".", "Reference", "(", ")", ",", "Datacenter", ":", "dc", ".", "Reference", "(", ")", ",", "Path", ":", "path", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "FindByDatastorePath", "(", "ctx", ",", "s", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "Returnval", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "NewReference", "(", "s", ".", "c", ",", "*", "res", ".", "Returnval", ")", ",", "nil", "\n", "}" ]
// FindByDatastorePath finds a virtual machine by its location on a datastore.
[ "FindByDatastorePath", "finds", "a", "virtual", "machine", "by", "its", "location", "on", "a", "datastore", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L40-L56
train
vmware/govmomi
object/search_index.go
FindByDnsName
func (s SearchIndex) FindByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) (Reference, error) { req := types.FindByDnsName{ This: s.Reference(), DnsName: dnsName, VmSearch: vmSearch, } if dc != nil { ref := dc.Reference() req.Datacenter = &ref } res, err := methods.FindByDnsName(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
go
func (s SearchIndex) FindByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) (Reference, error) { req := types.FindByDnsName{ This: s.Reference(), DnsName: dnsName, VmSearch: vmSearch, } if dc != nil { ref := dc.Reference() req.Datacenter = &ref } res, err := methods.FindByDnsName(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
[ "func", "(", "s", "SearchIndex", ")", "FindByDnsName", "(", "ctx", "context", ".", "Context", ",", "dc", "*", "Datacenter", ",", "dnsName", "string", ",", "vmSearch", "bool", ")", "(", "Reference", ",", "error", ")", "{", "req", ":=", "types", ".", "FindByDnsName", "{", "This", ":", "s", ".", "Reference", "(", ")", ",", "DnsName", ":", "dnsName", ",", "VmSearch", ":", "vmSearch", ",", "}", "\n", "if", "dc", "!=", "nil", "{", "ref", ":=", "dc", ".", "Reference", "(", ")", "\n", "req", ".", "Datacenter", "=", "&", "ref", "\n", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "FindByDnsName", "(", "ctx", ",", "s", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "Returnval", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "NewReference", "(", "s", ".", "c", ",", "*", "res", ".", "Returnval", ")", ",", "nil", "\n", "}" ]
// FindByDnsName finds a virtual machine or host by DNS name.
[ "FindByDnsName", "finds", "a", "virtual", "machine", "or", "host", "by", "DNS", "name", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L59-L79
train
vmware/govmomi
object/search_index.go
FindByInventoryPath
func (s SearchIndex) FindByInventoryPath(ctx context.Context, path string) (Reference, error) { req := types.FindByInventoryPath{ This: s.Reference(), InventoryPath: path, } res, err := methods.FindByInventoryPath(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
go
func (s SearchIndex) FindByInventoryPath(ctx context.Context, path string) (Reference, error) { req := types.FindByInventoryPath{ This: s.Reference(), InventoryPath: path, } res, err := methods.FindByInventoryPath(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
[ "func", "(", "s", "SearchIndex", ")", "FindByInventoryPath", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "Reference", ",", "error", ")", "{", "req", ":=", "types", ".", "FindByInventoryPath", "{", "This", ":", "s", ".", "Reference", "(", ")", ",", "InventoryPath", ":", "path", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "FindByInventoryPath", "(", "ctx", ",", "s", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "Returnval", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "NewReference", "(", "s", ".", "c", ",", "*", "res", ".", "Returnval", ")", ",", "nil", "\n", "}" ]
// FindByInventoryPath finds a managed entity based on its location in the inventory.
[ "FindByInventoryPath", "finds", "a", "managed", "entity", "based", "on", "its", "location", "in", "the", "inventory", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L82-L97
train
vmware/govmomi
object/search_index.go
FindByUuid
func (s SearchIndex) FindByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) (Reference, error) { req := types.FindByUuid{ This: s.Reference(), Uuid: uuid, VmSearch: vmSearch, InstanceUuid: instanceUuid, } if dc != nil { ref := dc.Reference() req.Datacenter = &ref } res, err := methods.FindByUuid(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
go
func (s SearchIndex) FindByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) (Reference, error) { req := types.FindByUuid{ This: s.Reference(), Uuid: uuid, VmSearch: vmSearch, InstanceUuid: instanceUuid, } if dc != nil { ref := dc.Reference() req.Datacenter = &ref } res, err := methods.FindByUuid(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
[ "func", "(", "s", "SearchIndex", ")", "FindByUuid", "(", "ctx", "context", ".", "Context", ",", "dc", "*", "Datacenter", ",", "uuid", "string", ",", "vmSearch", "bool", ",", "instanceUuid", "*", "bool", ")", "(", "Reference", ",", "error", ")", "{", "req", ":=", "types", ".", "FindByUuid", "{", "This", ":", "s", ".", "Reference", "(", ")", ",", "Uuid", ":", "uuid", ",", "VmSearch", ":", "vmSearch", ",", "InstanceUuid", ":", "instanceUuid", ",", "}", "\n", "if", "dc", "!=", "nil", "{", "ref", ":=", "dc", ".", "Reference", "(", ")", "\n", "req", ".", "Datacenter", "=", "&", "ref", "\n", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "FindByUuid", "(", "ctx", ",", "s", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "Returnval", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "NewReference", "(", "s", ".", "c", ",", "*", "res", ".", "Returnval", ")", ",", "nil", "\n", "}" ]
// FindByUuid finds a virtual machine or host by UUID.
[ "FindByUuid", "finds", "a", "virtual", "machine", "or", "host", "by", "UUID", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L123-L144
train
vmware/govmomi
object/search_index.go
FindChild
func (s SearchIndex) FindChild(ctx context.Context, entity Reference, name string) (Reference, error) { req := types.FindChild{ This: s.Reference(), Entity: entity.Reference(), Name: name, } res, err := methods.FindChild(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
go
func (s SearchIndex) FindChild(ctx context.Context, entity Reference, name string) (Reference, error) { req := types.FindChild{ This: s.Reference(), Entity: entity.Reference(), Name: name, } res, err := methods.FindChild(ctx, s.c, &req) if err != nil { return nil, err } if res.Returnval == nil { return nil, nil } return NewReference(s.c, *res.Returnval), nil }
[ "func", "(", "s", "SearchIndex", ")", "FindChild", "(", "ctx", "context", ".", "Context", ",", "entity", "Reference", ",", "name", "string", ")", "(", "Reference", ",", "error", ")", "{", "req", ":=", "types", ".", "FindChild", "{", "This", ":", "s", ".", "Reference", "(", ")", ",", "Entity", ":", "entity", ".", "Reference", "(", ")", ",", "Name", ":", "name", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "FindChild", "(", "ctx", ",", "s", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "Returnval", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "NewReference", "(", "s", ".", "c", ",", "*", "res", ".", "Returnval", ")", ",", "nil", "\n", "}" ]
// FindChild finds a particular child based on a managed entity name.
[ "FindChild", "finds", "a", "particular", "child", "based", "on", "a", "managed", "entity", "name", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/search_index.go#L147-L163
train
vmware/govmomi
toolbox/toolbox/main.go
main
func main() { flag.Parse() in := toolbox.NewBackdoorChannelIn() out := toolbox.NewBackdoorChannelOut() service := toolbox.NewService(in, out) if os.Getuid() == 0 { service.Power.Halt.Handler = toolbox.Halt service.Power.Reboot.Handler = toolbox.Reboot } err := service.Start() if err != nil { log.Fatal(err) } // handle the signals and gracefully shutdown the service sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) go func() { log.Printf("signal %s received", <-sig) service.Stop() }() service.Wait() }
go
func main() { flag.Parse() in := toolbox.NewBackdoorChannelIn() out := toolbox.NewBackdoorChannelOut() service := toolbox.NewService(in, out) if os.Getuid() == 0 { service.Power.Halt.Handler = toolbox.Halt service.Power.Reboot.Handler = toolbox.Reboot } err := service.Start() if err != nil { log.Fatal(err) } // handle the signals and gracefully shutdown the service sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) go func() { log.Printf("signal %s received", <-sig) service.Stop() }() service.Wait() }
[ "func", "main", "(", ")", "{", "flag", ".", "Parse", "(", ")", "\n\n", "in", ":=", "toolbox", ".", "NewBackdoorChannelIn", "(", ")", "\n", "out", ":=", "toolbox", ".", "NewBackdoorChannelOut", "(", ")", "\n\n", "service", ":=", "toolbox", ".", "NewService", "(", "in", ",", "out", ")", "\n\n", "if", "os", ".", "Getuid", "(", ")", "==", "0", "{", "service", ".", "Power", ".", "Halt", ".", "Handler", "=", "toolbox", ".", "Halt", "\n", "service", ".", "Power", ".", "Reboot", ".", "Handler", "=", "toolbox", ".", "Reboot", "\n", "}", "\n\n", "err", ":=", "service", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "// handle the signals and gracefully shutdown the service", "sig", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sig", ",", "syscall", ".", "SIGINT", ",", "syscall", ".", "SIGTERM", ")", "\n\n", "go", "func", "(", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "<-", "sig", ")", "\n", "service", ".", "Stop", "(", ")", "\n", "}", "(", ")", "\n\n", "service", ".", "Wait", "(", ")", "\n", "}" ]
// This example can be run on a VM hosted by ESX, Fusion or Workstation
[ "This", "example", "can", "be", "run", "on", "a", "VM", "hosted", "by", "ESX", "Fusion", "or", "Workstation" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/toolbox/main.go#L43-L71
train
vmware/govmomi
govc/flags/client.go
configure
func (flag *ClientFlag) configure(sc *soap.Client) (soap.RoundTripper, error) { if flag.cert != "" { cert, err := tls.LoadX509KeyPair(flag.cert, flag.key) if err != nil { return nil, err } sc.SetCertificate(cert) } // Set namespace and version sc.Namespace = "urn:" + flag.vimNamespace sc.Version = flag.vimVersion sc.UserAgent = fmt.Sprintf("govc/%s", Version) if err := flag.SetRootCAs(sc); err != nil { return nil, err } if err := sc.LoadThumbprints(flag.tlsKnownHosts); err != nil { return nil, err } if t, ok := sc.Transport.(*http.Transport); ok { var err error value := os.Getenv("GOVC_TLS_HANDSHAKE_TIMEOUT") if value != "" { t.TLSHandshakeTimeout, err = time.ParseDuration(value) if err != nil { return nil, err } } } // Retry twice when a temporary I/O error occurs. // This means a maximum of 3 attempts. return vim25.Retry(sc, vim25.TemporaryNetworkError(3)), nil }
go
func (flag *ClientFlag) configure(sc *soap.Client) (soap.RoundTripper, error) { if flag.cert != "" { cert, err := tls.LoadX509KeyPair(flag.cert, flag.key) if err != nil { return nil, err } sc.SetCertificate(cert) } // Set namespace and version sc.Namespace = "urn:" + flag.vimNamespace sc.Version = flag.vimVersion sc.UserAgent = fmt.Sprintf("govc/%s", Version) if err := flag.SetRootCAs(sc); err != nil { return nil, err } if err := sc.LoadThumbprints(flag.tlsKnownHosts); err != nil { return nil, err } if t, ok := sc.Transport.(*http.Transport); ok { var err error value := os.Getenv("GOVC_TLS_HANDSHAKE_TIMEOUT") if value != "" { t.TLSHandshakeTimeout, err = time.ParseDuration(value) if err != nil { return nil, err } } } // Retry twice when a temporary I/O error occurs. // This means a maximum of 3 attempts. return vim25.Retry(sc, vim25.TemporaryNetworkError(3)), nil }
[ "func", "(", "flag", "*", "ClientFlag", ")", "configure", "(", "sc", "*", "soap", ".", "Client", ")", "(", "soap", ".", "RoundTripper", ",", "error", ")", "{", "if", "flag", ".", "cert", "!=", "\"", "\"", "{", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "flag", ".", "cert", ",", "flag", ".", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sc", ".", "SetCertificate", "(", "cert", ")", "\n", "}", "\n\n", "// Set namespace and version", "sc", ".", "Namespace", "=", "\"", "\"", "+", "flag", ".", "vimNamespace", "\n", "sc", ".", "Version", "=", "flag", ".", "vimVersion", "\n\n", "sc", ".", "UserAgent", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "Version", ")", "\n\n", "if", "err", ":=", "flag", ".", "SetRootCAs", "(", "sc", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "sc", ".", "LoadThumbprints", "(", "flag", ".", "tlsKnownHosts", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "t", ",", "ok", ":=", "sc", ".", "Transport", ".", "(", "*", "http", ".", "Transport", ")", ";", "ok", "{", "var", "err", "error", "\n\n", "value", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "value", "!=", "\"", "\"", "{", "t", ".", "TLSHandshakeTimeout", ",", "err", "=", "time", ".", "ParseDuration", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Retry twice when a temporary I/O error occurs.", "// This means a maximum of 3 attempts.", "return", "vim25", ".", "Retry", "(", "sc", ",", "vim25", ".", "TemporaryNetworkError", "(", "3", ")", ")", ",", "nil", "\n", "}" ]
// configure TLS and retry settings before making any connections
[ "configure", "TLS", "and", "retry", "settings", "before", "making", "any", "connections" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L277-L316
train
vmware/govmomi
govc/flags/client.go
apiVersionValid
func apiVersionValid(c *vim25.Client, minVersionString string) error { if minVersionString == "-" { // Disable version check return nil } apiVersion := c.ServiceContent.About.ApiVersion if isDevelopmentVersion(apiVersion) { return nil } realVersion, err := ParseVersion(apiVersion) if err != nil { return fmt.Errorf("error parsing API version %q: %s", apiVersion, err) } minVersion, err := ParseVersion(minVersionString) if err != nil { return fmt.Errorf("error parsing %s=%q: %s", envMinAPIVersion, minVersionString, err) } if !minVersion.Lte(realVersion) { err = fmt.Errorf("require API version %q, connected to API version %q (set %s to override)", minVersionString, c.ServiceContent.About.ApiVersion, envMinAPIVersion) return err } return nil }
go
func apiVersionValid(c *vim25.Client, minVersionString string) error { if minVersionString == "-" { // Disable version check return nil } apiVersion := c.ServiceContent.About.ApiVersion if isDevelopmentVersion(apiVersion) { return nil } realVersion, err := ParseVersion(apiVersion) if err != nil { return fmt.Errorf("error parsing API version %q: %s", apiVersion, err) } minVersion, err := ParseVersion(minVersionString) if err != nil { return fmt.Errorf("error parsing %s=%q: %s", envMinAPIVersion, minVersionString, err) } if !minVersion.Lte(realVersion) { err = fmt.Errorf("require API version %q, connected to API version %q (set %s to override)", minVersionString, c.ServiceContent.About.ApiVersion, envMinAPIVersion) return err } return nil }
[ "func", "apiVersionValid", "(", "c", "*", "vim25", ".", "Client", ",", "minVersionString", "string", ")", "error", "{", "if", "minVersionString", "==", "\"", "\"", "{", "// Disable version check", "return", "nil", "\n", "}", "\n\n", "apiVersion", ":=", "c", ".", "ServiceContent", ".", "About", ".", "ApiVersion", "\n", "if", "isDevelopmentVersion", "(", "apiVersion", ")", "{", "return", "nil", "\n", "}", "\n\n", "realVersion", ",", "err", ":=", "ParseVersion", "(", "apiVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "apiVersion", ",", "err", ")", "\n", "}", "\n\n", "minVersion", ",", "err", ":=", "ParseVersion", "(", "minVersionString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "envMinAPIVersion", ",", "minVersionString", ",", "err", ")", "\n", "}", "\n\n", "if", "!", "minVersion", ".", "Lte", "(", "realVersion", ")", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "minVersionString", ",", "c", ".", "ServiceContent", ".", "About", ".", "ApiVersion", ",", "envMinAPIVersion", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// apiVersionValid returns whether or not the API version supported by the // server the client is connected to is not recent enough.
[ "apiVersionValid", "returns", "whether", "or", "not", "the", "API", "version", "supported", "by", "the", "server", "the", "client", "is", "connected", "to", "is", "not", "recent", "enough", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L494-L524
train
vmware/govmomi
govc/flags/client.go
Environ
func (flag *ClientFlag) Environ(extra bool) []string { var env []string add := func(k, v string) { env = append(env, fmt.Sprintf("%s=%s", k, v)) } u := *flag.url if u.User != nil { add(envUsername, u.User.Username()) if p, ok := u.User.Password(); ok { add(envPassword, p) } u.User = nil } if u.Path == vim25.Path { u.Path = "" } u.Fragment = "" u.RawQuery = "" add(envURL, strings.TrimPrefix(u.String(), "https://")) keys := []string{ envCertificate, envPrivateKey, envInsecure, envPersist, envMinAPIVersion, envVimNamespace, envVimVersion, } for _, k := range keys { if v := os.Getenv(k); v != "" { add(k, v) } } if extra { add("GOVC_URL_SCHEME", flag.url.Scheme) v := strings.SplitN(u.Host, ":", 2) add("GOVC_URL_HOST", v[0]) if len(v) == 2 { add("GOVC_URL_PORT", v[1]) } add("GOVC_URL_PATH", flag.url.Path) if f := flag.url.Fragment; f != "" { add("GOVC_URL_FRAGMENT", f) } if q := flag.url.RawQuery; q != "" { add("GOVC_URL_QUERY", q) } } return env }
go
func (flag *ClientFlag) Environ(extra bool) []string { var env []string add := func(k, v string) { env = append(env, fmt.Sprintf("%s=%s", k, v)) } u := *flag.url if u.User != nil { add(envUsername, u.User.Username()) if p, ok := u.User.Password(); ok { add(envPassword, p) } u.User = nil } if u.Path == vim25.Path { u.Path = "" } u.Fragment = "" u.RawQuery = "" add(envURL, strings.TrimPrefix(u.String(), "https://")) keys := []string{ envCertificate, envPrivateKey, envInsecure, envPersist, envMinAPIVersion, envVimNamespace, envVimVersion, } for _, k := range keys { if v := os.Getenv(k); v != "" { add(k, v) } } if extra { add("GOVC_URL_SCHEME", flag.url.Scheme) v := strings.SplitN(u.Host, ":", 2) add("GOVC_URL_HOST", v[0]) if len(v) == 2 { add("GOVC_URL_PORT", v[1]) } add("GOVC_URL_PATH", flag.url.Path) if f := flag.url.Fragment; f != "" { add("GOVC_URL_FRAGMENT", f) } if q := flag.url.RawQuery; q != "" { add("GOVC_URL_QUERY", q) } } return env }
[ "func", "(", "flag", "*", "ClientFlag", ")", "Environ", "(", "extra", "bool", ")", "[", "]", "string", "{", "var", "env", "[", "]", "string", "\n", "add", ":=", "func", "(", "k", ",", "v", "string", ")", "{", "env", "=", "append", "(", "env", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n\n", "u", ":=", "*", "flag", ".", "url", "\n", "if", "u", ".", "User", "!=", "nil", "{", "add", "(", "envUsername", ",", "u", ".", "User", ".", "Username", "(", ")", ")", "\n\n", "if", "p", ",", "ok", ":=", "u", ".", "User", ".", "Password", "(", ")", ";", "ok", "{", "add", "(", "envPassword", ",", "p", ")", "\n", "}", "\n\n", "u", ".", "User", "=", "nil", "\n", "}", "\n\n", "if", "u", ".", "Path", "==", "vim25", ".", "Path", "{", "u", ".", "Path", "=", "\"", "\"", "\n", "}", "\n", "u", ".", "Fragment", "=", "\"", "\"", "\n", "u", ".", "RawQuery", "=", "\"", "\"", "\n\n", "add", "(", "envURL", ",", "strings", ".", "TrimPrefix", "(", "u", ".", "String", "(", ")", ",", "\"", "\"", ")", ")", "\n\n", "keys", ":=", "[", "]", "string", "{", "envCertificate", ",", "envPrivateKey", ",", "envInsecure", ",", "envPersist", ",", "envMinAPIVersion", ",", "envVimNamespace", ",", "envVimVersion", ",", "}", "\n\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "if", "v", ":=", "os", ".", "Getenv", "(", "k", ")", ";", "v", "!=", "\"", "\"", "{", "add", "(", "k", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "if", "extra", "{", "add", "(", "\"", "\"", ",", "flag", ".", "url", ".", "Scheme", ")", "\n\n", "v", ":=", "strings", ".", "SplitN", "(", "u", ".", "Host", ",", "\"", "\"", ",", "2", ")", "\n", "add", "(", "\"", "\"", ",", "v", "[", "0", "]", ")", "\n", "if", "len", "(", "v", ")", "==", "2", "{", "add", "(", "\"", "\"", ",", "v", "[", "1", "]", ")", "\n", "}", "\n\n", "add", "(", "\"", "\"", ",", "flag", ".", "url", ".", "Path", ")", "\n\n", "if", "f", ":=", "flag", ".", "url", ".", "Fragment", ";", "f", "!=", "\"", "\"", "{", "add", "(", "\"", "\"", ",", "f", ")", "\n", "}", "\n\n", "if", "q", ":=", "flag", ".", "url", ".", "RawQuery", ";", "q", "!=", "\"", "\"", "{", "add", "(", "\"", "\"", ",", "q", ")", "\n", "}", "\n", "}", "\n\n", "return", "env", "\n", "}" ]
// Environ returns the govc environment variables for this connection
[ "Environ", "returns", "the", "govc", "environment", "variables", "for", "this", "connection" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L606-L668
train
vmware/govmomi
govc/flags/client.go
WithCancel
func (flag *ClientFlag) WithCancel(ctx context.Context, f func(context.Context) error) error { sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT) wctx, cancel := context.WithCancel(ctx) defer cancel() done := make(chan bool) var werr error go func() { defer close(done) werr = f(wctx) }() select { case <-sig: cancel() <-done // Wait for f() to complete case <-done: } return werr }
go
func (flag *ClientFlag) WithCancel(ctx context.Context, f func(context.Context) error) error { sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT) wctx, cancel := context.WithCancel(ctx) defer cancel() done := make(chan bool) var werr error go func() { defer close(done) werr = f(wctx) }() select { case <-sig: cancel() <-done // Wait for f() to complete case <-done: } return werr }
[ "func", "(", "flag", "*", "ClientFlag", ")", "WithCancel", "(", "ctx", "context", ".", "Context", ",", "f", "func", "(", "context", ".", "Context", ")", "error", ")", "error", "{", "sig", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sig", ",", "syscall", ".", "SIGINT", ")", "\n\n", "wctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "done", ":=", "make", "(", "chan", "bool", ")", "\n", "var", "werr", "error", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "done", ")", "\n", "werr", "=", "f", "(", "wctx", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "sig", ":", "cancel", "(", ")", "\n", "<-", "done", "// Wait for f() to complete", "\n", "case", "<-", "done", ":", "}", "\n\n", "return", "werr", "\n", "}" ]
// WithCancel calls the given function, returning when complete or canceled via SIGINT.
[ "WithCancel", "calls", "the", "given", "function", "returning", "when", "complete", "or", "canceled", "via", "SIGINT", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/client.go#L671-L694
train
vmware/govmomi
vim25/progress/tee.go
Tee
func Tee(s1, s2 Sinker) Sinker { fn := func() chan<- Report { d1 := s1.Sink() d2 := s2.Sink() u := make(chan Report) go tee(u, d1, d2) return u } return SinkFunc(fn) }
go
func Tee(s1, s2 Sinker) Sinker { fn := func() chan<- Report { d1 := s1.Sink() d2 := s2.Sink() u := make(chan Report) go tee(u, d1, d2) return u } return SinkFunc(fn) }
[ "func", "Tee", "(", "s1", ",", "s2", "Sinker", ")", "Sinker", "{", "fn", ":=", "func", "(", ")", "chan", "<-", "Report", "{", "d1", ":=", "s1", ".", "Sink", "(", ")", "\n", "d2", ":=", "s2", ".", "Sink", "(", ")", "\n", "u", ":=", "make", "(", "chan", "Report", ")", "\n", "go", "tee", "(", "u", ",", "d1", ",", "d2", ")", "\n", "return", "u", "\n", "}", "\n\n", "return", "SinkFunc", "(", "fn", ")", "\n", "}" ]
// Tee works like Unix tee; it forwards all progress reports it receives to the // specified sinks
[ "Tee", "works", "like", "Unix", "tee", ";", "it", "forwards", "all", "progress", "reports", "it", "receives", "to", "the", "specified", "sinks" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/progress/tee.go#L21-L31
train
vmware/govmomi
simulator/host_system.go
CreateStandaloneHost
func CreateStandaloneHost(f *Folder, spec types.HostConnectSpec) (*HostSystem, types.BaseMethodFault) { if spec.HostName == "" { return nil, &types.NoHost{} } pool := NewResourcePool() host := NewHostSystem(esx.HostSystem) host.Summary.Config.Name = spec.HostName host.Name = host.Summary.Config.Name host.Runtime.ConnectionState = types.HostSystemConnectionStateDisconnected summary := new(types.ComputeResourceSummary) addComputeResource(summary, host) cr := &mo.ComputeResource{ ConfigurationEx: &types.ComputeResourceConfigInfo{ VmSwapPlacement: string(types.VirtualMachineConfigInfoSwapPlacementTypeVmDirectory), }, Summary: summary, EnvironmentBrowser: newEnvironmentBrowser(), } Map.PutEntity(cr, Map.NewEntity(host)) host.Summary.Host = &host.Self Map.PutEntity(cr, Map.NewEntity(pool)) cr.Name = host.Name cr.Network = Map.getEntityDatacenter(f).defaultNetwork() cr.Host = append(cr.Host, host.Reference()) cr.ResourcePool = &pool.Self f.putChild(cr) pool.Owner = cr.Self host.Network = cr.Network return host, nil }
go
func CreateStandaloneHost(f *Folder, spec types.HostConnectSpec) (*HostSystem, types.BaseMethodFault) { if spec.HostName == "" { return nil, &types.NoHost{} } pool := NewResourcePool() host := NewHostSystem(esx.HostSystem) host.Summary.Config.Name = spec.HostName host.Name = host.Summary.Config.Name host.Runtime.ConnectionState = types.HostSystemConnectionStateDisconnected summary := new(types.ComputeResourceSummary) addComputeResource(summary, host) cr := &mo.ComputeResource{ ConfigurationEx: &types.ComputeResourceConfigInfo{ VmSwapPlacement: string(types.VirtualMachineConfigInfoSwapPlacementTypeVmDirectory), }, Summary: summary, EnvironmentBrowser: newEnvironmentBrowser(), } Map.PutEntity(cr, Map.NewEntity(host)) host.Summary.Host = &host.Self Map.PutEntity(cr, Map.NewEntity(pool)) cr.Name = host.Name cr.Network = Map.getEntityDatacenter(f).defaultNetwork() cr.Host = append(cr.Host, host.Reference()) cr.ResourcePool = &pool.Self f.putChild(cr) pool.Owner = cr.Self host.Network = cr.Network return host, nil }
[ "func", "CreateStandaloneHost", "(", "f", "*", "Folder", ",", "spec", "types", ".", "HostConnectSpec", ")", "(", "*", "HostSystem", ",", "types", ".", "BaseMethodFault", ")", "{", "if", "spec", ".", "HostName", "==", "\"", "\"", "{", "return", "nil", ",", "&", "types", ".", "NoHost", "{", "}", "\n", "}", "\n\n", "pool", ":=", "NewResourcePool", "(", ")", "\n", "host", ":=", "NewHostSystem", "(", "esx", ".", "HostSystem", ")", "\n\n", "host", ".", "Summary", ".", "Config", ".", "Name", "=", "spec", ".", "HostName", "\n", "host", ".", "Name", "=", "host", ".", "Summary", ".", "Config", ".", "Name", "\n", "host", ".", "Runtime", ".", "ConnectionState", "=", "types", ".", "HostSystemConnectionStateDisconnected", "\n\n", "summary", ":=", "new", "(", "types", ".", "ComputeResourceSummary", ")", "\n", "addComputeResource", "(", "summary", ",", "host", ")", "\n\n", "cr", ":=", "&", "mo", ".", "ComputeResource", "{", "ConfigurationEx", ":", "&", "types", ".", "ComputeResourceConfigInfo", "{", "VmSwapPlacement", ":", "string", "(", "types", ".", "VirtualMachineConfigInfoSwapPlacementTypeVmDirectory", ")", ",", "}", ",", "Summary", ":", "summary", ",", "EnvironmentBrowser", ":", "newEnvironmentBrowser", "(", ")", ",", "}", "\n\n", "Map", ".", "PutEntity", "(", "cr", ",", "Map", ".", "NewEntity", "(", "host", ")", ")", "\n", "host", ".", "Summary", ".", "Host", "=", "&", "host", ".", "Self", "\n\n", "Map", ".", "PutEntity", "(", "cr", ",", "Map", ".", "NewEntity", "(", "pool", ")", ")", "\n\n", "cr", ".", "Name", "=", "host", ".", "Name", "\n", "cr", ".", "Network", "=", "Map", ".", "getEntityDatacenter", "(", "f", ")", ".", "defaultNetwork", "(", ")", "\n", "cr", ".", "Host", "=", "append", "(", "cr", ".", "Host", ",", "host", ".", "Reference", "(", ")", ")", "\n", "cr", ".", "ResourcePool", "=", "&", "pool", ".", "Self", "\n\n", "f", ".", "putChild", "(", "cr", ")", "\n", "pool", ".", "Owner", "=", "cr", ".", "Self", "\n", "host", ".", "Network", "=", "cr", ".", "Network", "\n\n", "return", "host", ",", "nil", "\n", "}" ]
// CreateStandaloneHost uses esx.HostSystem as a template, applying the given spec // and creating the ComputeResource parent and ResourcePool sibling.
[ "CreateStandaloneHost", "uses", "esx", ".", "HostSystem", "as", "a", "template", "applying", "the", "given", "spec", "and", "creating", "the", "ComputeResource", "parent", "and", "ResourcePool", "sibling", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/host_system.go#L165-L203
train
vmware/govmomi
vapi/library/library_item_updatesession.go
CreateLibraryItemUpdateSession
func (c *Manager) CreateLibraryItemUpdateSession(ctx context.Context, session UpdateSession) (string, error) { url := internal.URL(c, internal.LibraryItemUpdateSession) spec := struct { CreateSpec UpdateSession `json:"create_spec"` }{session} var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
go
func (c *Manager) CreateLibraryItemUpdateSession(ctx context.Context, session UpdateSession) (string, error) { url := internal.URL(c, internal.LibraryItemUpdateSession) spec := struct { CreateSpec UpdateSession `json:"create_spec"` }{session} var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
[ "func", "(", "c", "*", "Manager", ")", "CreateLibraryItemUpdateSession", "(", "ctx", "context", ".", "Context", ",", "session", "UpdateSession", ")", "(", "string", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemUpdateSession", ")", "\n", "spec", ":=", "struct", "{", "CreateSpec", "UpdateSession", "`json:\"create_spec\"`", "\n", "}", "{", "session", "}", "\n", "var", "res", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "spec", ")", ",", "&", "res", ")", "\n", "}" ]
// CreateLibraryItemUpdateSession creates a new library item
[ "CreateLibraryItemUpdateSession", "creates", "a", "new", "library", "item" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L43-L50
train
vmware/govmomi
vapi/library/library_item_updatesession.go
GetLibraryItemUpdateSession
func (c *Manager) GetLibraryItemUpdateSession(ctx context.Context, id string) (*UpdateSession, error) { url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id) var res UpdateSession return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
go
func (c *Manager) GetLibraryItemUpdateSession(ctx context.Context, id string) (*UpdateSession, error) { url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id) var res UpdateSession return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
[ "func", "(", "c", "*", "Manager", ")", "GetLibraryItemUpdateSession", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "*", "UpdateSession", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemUpdateSession", ")", ".", "WithID", "(", "id", ")", "\n", "var", "res", "UpdateSession", "\n", "return", "&", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodGet", ")", ",", "&", "res", ")", "\n", "}" ]
// GetLibraryItemUpdateSession gets the update session information with status
[ "GetLibraryItemUpdateSession", "gets", "the", "update", "session", "information", "with", "status" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L53-L57
train
vmware/govmomi
vapi/library/library_item_updatesession.go
ListLibraryItemUpdateSession
func (c *Manager) ListLibraryItemUpdateSession(ctx context.Context) (*[]string, error) { url := internal.URL(c, internal.LibraryItemUpdateSession) var res []string return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
go
func (c *Manager) ListLibraryItemUpdateSession(ctx context.Context) (*[]string, error) { url := internal.URL(c, internal.LibraryItemUpdateSession) var res []string return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
[ "func", "(", "c", "*", "Manager", ")", "ListLibraryItemUpdateSession", "(", "ctx", "context", ".", "Context", ")", "(", "*", "[", "]", "string", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemUpdateSession", ")", "\n", "var", "res", "[", "]", "string", "\n", "return", "&", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodGet", ")", ",", "&", "res", ")", "\n", "}" ]
// ListLibraryItemUpdateSession gets the list of update sessions
[ "ListLibraryItemUpdateSession", "gets", "the", "list", "of", "update", "sessions" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L60-L64
train
vmware/govmomi
vapi/library/library_item_updatesession.go
DeleteLibraryItemUpdateSession
func (c *Manager) DeleteLibraryItemUpdateSession(ctx context.Context, id string) error { url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
go
func (c *Manager) DeleteLibraryItemUpdateSession(ctx context.Context, id string) error { url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
[ "func", "(", "c", "*", "Manager", ")", "DeleteLibraryItemUpdateSession", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemUpdateSession", ")", ".", "WithID", "(", "id", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodDelete", ")", ",", "nil", ")", "\n", "}" ]
// DeleteLibraryItemUpdateSession deletes an update session
[ "DeleteLibraryItemUpdateSession", "deletes", "an", "update", "session" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L79-L82
train
vmware/govmomi
vapi/library/library_item_updatesession.go
FailLibraryItemUpdateSession
func (c *Manager) FailLibraryItemUpdateSession(ctx context.Context, id string) error { url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id).WithAction("fail") return c.Do(ctx, url.Request(http.MethodPost), nil) }
go
func (c *Manager) FailLibraryItemUpdateSession(ctx context.Context, id string) error { url := internal.URL(c, internal.LibraryItemUpdateSession).WithID(id).WithAction("fail") return c.Do(ctx, url.Request(http.MethodPost), nil) }
[ "func", "(", "c", "*", "Manager", ")", "FailLibraryItemUpdateSession", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemUpdateSession", ")", ".", "WithID", "(", "id", ")", ".", "WithAction", "(", "\"", "\"", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ")", ",", "nil", ")", "\n", "}" ]
// FailLibraryItemUpdateSession fails an update session
[ "FailLibraryItemUpdateSession", "fails", "an", "update", "session" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L85-L88
train
vmware/govmomi
vapi/library/library_item_updatesession.go
WaitOnLibraryItemUpdateSession
func (c *Manager) WaitOnLibraryItemUpdateSession( ctx context.Context, sessionID string, interval time.Duration, intervalCallback func()) error { // Wait until the upload operation is complete to return. for { session, err := c.GetLibraryItemUpdateSession(ctx, sessionID) if err != nil { return err } if session.State != "ACTIVE" { return nil } time.Sleep(interval) if intervalCallback != nil { intervalCallback() } } }
go
func (c *Manager) WaitOnLibraryItemUpdateSession( ctx context.Context, sessionID string, interval time.Duration, intervalCallback func()) error { // Wait until the upload operation is complete to return. for { session, err := c.GetLibraryItemUpdateSession(ctx, sessionID) if err != nil { return err } if session.State != "ACTIVE" { return nil } time.Sleep(interval) if intervalCallback != nil { intervalCallback() } } }
[ "func", "(", "c", "*", "Manager", ")", "WaitOnLibraryItemUpdateSession", "(", "ctx", "context", ".", "Context", ",", "sessionID", "string", ",", "interval", "time", ".", "Duration", ",", "intervalCallback", "func", "(", ")", ")", "error", "{", "// Wait until the upload operation is complete to return.", "for", "{", "session", ",", "err", ":=", "c", ".", "GetLibraryItemUpdateSession", "(", "ctx", ",", "sessionID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "session", ".", "State", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "time", ".", "Sleep", "(", "interval", ")", "\n", "if", "intervalCallback", "!=", "nil", "{", "intervalCallback", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// WaitOnLibraryItemUpdateSession blocks until the update session is no longer // in the ACTIVE state.
[ "WaitOnLibraryItemUpdateSession", "blocks", "until", "the", "update", "session", "is", "no", "longer", "in", "the", "ACTIVE", "state", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item_updatesession.go#L98-L116
train
vmware/govmomi
sts/internal/types.go
toString
func (r *RequestSecurityToken) toString(c14n bool) string { actas := "" if r.ActAs != nil { token := r.ActAs.Token if c14n { var a Assertion err := Unmarshal([]byte(r.ActAs.Token), &a) if err != nil { log.Printf("decode ActAs: %s", err) } token = a.C14N() } actas = fmt.Sprintf(`<wst:ActAs xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200802">%s</wst:ActAs>`, token) } body := []string{ fmt.Sprintf(`<RequestSecurityToken xmlns="http://docs.oasis-open.org/ws-sx/ws-trust/200512">`), fmt.Sprintf(`<TokenType>%s</TokenType>`, r.TokenType), fmt.Sprintf(`<RequestType>%s</RequestType>`, r.RequestType), r.Lifetime.C14N(), } if r.RenewTarget == nil { body = append(body, fmt.Sprintf(`<Renewing Allow="%t" OK="%t"></Renewing>`, r.Renewing.Allow, r.Renewing.OK), fmt.Sprintf(`<Delegatable>%t</Delegatable>`, r.Delegatable), actas, fmt.Sprintf(`<KeyType>%s</KeyType>`, r.KeyType), fmt.Sprintf(`<SignatureAlgorithm>%s</SignatureAlgorithm>`, r.SignatureAlgorithm), fmt.Sprintf(`<UseKey Sig="%s"></UseKey>`, r.UseKey.Sig)) } else { token := r.RenewTarget.Token if c14n { var a Assertion err := Unmarshal([]byte(r.RenewTarget.Token), &a) if err != nil { log.Printf("decode Renew: %s", err) } token = a.C14N() } body = append(body, fmt.Sprintf(`<UseKey Sig="%s"></UseKey>`, r.UseKey.Sig), fmt.Sprintf(`<RenewTarget>%s</RenewTarget>`, token)) } return strings.Join(append(body, `</RequestSecurityToken>`), "") }
go
func (r *RequestSecurityToken) toString(c14n bool) string { actas := "" if r.ActAs != nil { token := r.ActAs.Token if c14n { var a Assertion err := Unmarshal([]byte(r.ActAs.Token), &a) if err != nil { log.Printf("decode ActAs: %s", err) } token = a.C14N() } actas = fmt.Sprintf(`<wst:ActAs xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200802">%s</wst:ActAs>`, token) } body := []string{ fmt.Sprintf(`<RequestSecurityToken xmlns="http://docs.oasis-open.org/ws-sx/ws-trust/200512">`), fmt.Sprintf(`<TokenType>%s</TokenType>`, r.TokenType), fmt.Sprintf(`<RequestType>%s</RequestType>`, r.RequestType), r.Lifetime.C14N(), } if r.RenewTarget == nil { body = append(body, fmt.Sprintf(`<Renewing Allow="%t" OK="%t"></Renewing>`, r.Renewing.Allow, r.Renewing.OK), fmt.Sprintf(`<Delegatable>%t</Delegatable>`, r.Delegatable), actas, fmt.Sprintf(`<KeyType>%s</KeyType>`, r.KeyType), fmt.Sprintf(`<SignatureAlgorithm>%s</SignatureAlgorithm>`, r.SignatureAlgorithm), fmt.Sprintf(`<UseKey Sig="%s"></UseKey>`, r.UseKey.Sig)) } else { token := r.RenewTarget.Token if c14n { var a Assertion err := Unmarshal([]byte(r.RenewTarget.Token), &a) if err != nil { log.Printf("decode Renew: %s", err) } token = a.C14N() } body = append(body, fmt.Sprintf(`<UseKey Sig="%s"></UseKey>`, r.UseKey.Sig), fmt.Sprintf(`<RenewTarget>%s</RenewTarget>`, token)) } return strings.Join(append(body, `</RequestSecurityToken>`), "") }
[ "func", "(", "r", "*", "RequestSecurityToken", ")", "toString", "(", "c14n", "bool", ")", "string", "{", "actas", ":=", "\"", "\"", "\n", "if", "r", ".", "ActAs", "!=", "nil", "{", "token", ":=", "r", ".", "ActAs", ".", "Token", "\n", "if", "c14n", "{", "var", "a", "Assertion", "\n", "err", ":=", "Unmarshal", "(", "[", "]", "byte", "(", "r", ".", "ActAs", ".", "Token", ")", ",", "&", "a", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "token", "=", "a", ".", "C14N", "(", ")", "\n", "}", "\n\n", "actas", "=", "fmt", ".", "Sprintf", "(", "`<wst:ActAs xmlns:wst=\"http://docs.oasis-open.org/ws-sx/ws-trust/200802\">%s</wst:ActAs>`", ",", "token", ")", "\n", "}", "\n\n", "body", ":=", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "`<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">`", ")", ",", "fmt", ".", "Sprintf", "(", "`<TokenType>%s</TokenType>`", ",", "r", ".", "TokenType", ")", ",", "fmt", ".", "Sprintf", "(", "`<RequestType>%s</RequestType>`", ",", "r", ".", "RequestType", ")", ",", "r", ".", "Lifetime", ".", "C14N", "(", ")", ",", "}", "\n\n", "if", "r", ".", "RenewTarget", "==", "nil", "{", "body", "=", "append", "(", "body", ",", "fmt", ".", "Sprintf", "(", "`<Renewing Allow=\"%t\" OK=\"%t\"></Renewing>`", ",", "r", ".", "Renewing", ".", "Allow", ",", "r", ".", "Renewing", ".", "OK", ")", ",", "fmt", ".", "Sprintf", "(", "`<Delegatable>%t</Delegatable>`", ",", "r", ".", "Delegatable", ")", ",", "actas", ",", "fmt", ".", "Sprintf", "(", "`<KeyType>%s</KeyType>`", ",", "r", ".", "KeyType", ")", ",", "fmt", ".", "Sprintf", "(", "`<SignatureAlgorithm>%s</SignatureAlgorithm>`", ",", "r", ".", "SignatureAlgorithm", ")", ",", "fmt", ".", "Sprintf", "(", "`<UseKey Sig=\"%s\"></UseKey>`", ",", "r", ".", "UseKey", ".", "Sig", ")", ")", "\n", "}", "else", "{", "token", ":=", "r", ".", "RenewTarget", ".", "Token", "\n", "if", "c14n", "{", "var", "a", "Assertion", "\n", "err", ":=", "Unmarshal", "(", "[", "]", "byte", "(", "r", ".", "RenewTarget", ".", "Token", ")", ",", "&", "a", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "token", "=", "a", ".", "C14N", "(", ")", "\n", "}", "\n\n", "body", "=", "append", "(", "body", ",", "fmt", ".", "Sprintf", "(", "`<UseKey Sig=\"%s\"></UseKey>`", ",", "r", ".", "UseKey", ".", "Sig", ")", ",", "fmt", ".", "Sprintf", "(", "`<RenewTarget>%s</RenewTarget>`", ",", "token", ")", ")", "\n", "}", "\n\n", "return", "strings", ".", "Join", "(", "append", "(", "body", ",", "`</RequestSecurityToken>`", ")", ",", "\"", "\"", ")", "\n", "}" ]
// toString returns an XML encoded RequestSecurityToken. // When c14n is true, returns the canonicalized ActAs.Assertion which is required to sign the Issue request. // When c14n is false, returns the original content of the ActAs.Assertion. // The original content must be used within the request Body, as it has its own signature.
[ "toString", "returns", "an", "XML", "encoded", "RequestSecurityToken", ".", "When", "c14n", "is", "true", "returns", "the", "canonicalized", "ActAs", ".", "Assertion", "which", "is", "required", "to", "sign", "the", "Issue", "request", ".", "When", "c14n", "is", "false", "returns", "the", "original", "content", "of", "the", "ActAs", ".", "Assertion", ".", "The", "original", "content", "must", "be", "used", "within", "the", "request", "Body", "as", "it", "has", "its", "own", "signature", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/internal/types.go#L552-L600
train
vmware/govmomi
sts/internal/types.go
Marshal
func Marshal(val interface{}) string { b, err := xml.Marshal(val) if err != nil { panic(err) } return string(b) }
go
func Marshal(val interface{}) string { b, err := xml.Marshal(val) if err != nil { panic(err) } return string(b) }
[ "func", "Marshal", "(", "val", "interface", "{", "}", ")", "string", "{", "b", ",", "err", ":=", "xml", ".", "Marshal", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "b", ")", "\n", "}" ]
// Marshal panics if xml.Marshal returns an error
[ "Marshal", "panics", "if", "xml", ".", "Marshal", "returns", "an", "error" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/internal/types.go#L673-L679
train
vmware/govmomi
sts/internal/types.go
mkns
func mkns(ns string, obj interface{}, name ...*xml.Name) string { ns += ":" for i := range name { name[i].Space = "" if !strings.HasPrefix(name[i].Local, ns) { name[i].Local = ns + name[i].Local } } return Marshal(obj) }
go
func mkns(ns string, obj interface{}, name ...*xml.Name) string { ns += ":" for i := range name { name[i].Space = "" if !strings.HasPrefix(name[i].Local, ns) { name[i].Local = ns + name[i].Local } } return Marshal(obj) }
[ "func", "mkns", "(", "ns", "string", ",", "obj", "interface", "{", "}", ",", "name", "...", "*", "xml", ".", "Name", ")", "string", "{", "ns", "+=", "\"", "\"", "\n", "for", "i", ":=", "range", "name", "{", "name", "[", "i", "]", ".", "Space", "=", "\"", "\"", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "name", "[", "i", "]", ".", "Local", ",", "ns", ")", "{", "name", "[", "i", "]", ".", "Local", "=", "ns", "+", "name", "[", "i", "]", ".", "Local", "\n", "}", "\n", "}", "\n\n", "return", "Marshal", "(", "obj", ")", "\n", "}" ]
// mkns prepends the given namespace to xml.Name.Local and returns obj encoded as xml. // Note that the namespace is required when encoding, but the namespace prefix must not be // present when decoding as Go's decoding does not handle namespace prefix.
[ "mkns", "prepends", "the", "given", "namespace", "to", "xml", ".", "Name", ".", "Local", "and", "returns", "obj", "encoded", "as", "xml", ".", "Note", "that", "the", "namespace", "is", "required", "when", "encoding", "but", "the", "namespace", "prefix", "must", "not", "be", "present", "when", "decoding", "as", "Go", "s", "decoding", "does", "not", "handle", "namespace", "prefix", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/internal/types.go#L684-L694
train
vmware/govmomi
view/container_view.go
Retrieve
func (v ContainerView) Retrieve(ctx context.Context, kind []string, ps []string, dst interface{}) error { pc := property.DefaultCollector(v.Client()) ospec := types.ObjectSpec{ Obj: v.Reference(), Skip: types.NewBool(true), SelectSet: []types.BaseSelectionSpec{ &types.TraversalSpec{ Type: v.Reference().Type, Path: "view", }, }, } var pspec []types.PropertySpec if len(kind) == 0 { kind = []string{"ManagedEntity"} } for _, t := range kind { spec := types.PropertySpec{ Type: t, } if len(ps) == 0 { spec.All = types.NewBool(true) } else { spec.PathSet = ps } pspec = append(pspec, spec) } req := types.RetrieveProperties{ SpecSet: []types.PropertyFilterSpec{ { ObjectSet: []types.ObjectSpec{ospec}, PropSet: pspec, }, }, } res, err := pc.RetrieveProperties(ctx, req) if err != nil { return err } if d, ok := dst.(*[]types.ObjectContent); ok { *d = res.Returnval return nil } return mo.LoadRetrievePropertiesResponse(res, dst) }
go
func (v ContainerView) Retrieve(ctx context.Context, kind []string, ps []string, dst interface{}) error { pc := property.DefaultCollector(v.Client()) ospec := types.ObjectSpec{ Obj: v.Reference(), Skip: types.NewBool(true), SelectSet: []types.BaseSelectionSpec{ &types.TraversalSpec{ Type: v.Reference().Type, Path: "view", }, }, } var pspec []types.PropertySpec if len(kind) == 0 { kind = []string{"ManagedEntity"} } for _, t := range kind { spec := types.PropertySpec{ Type: t, } if len(ps) == 0 { spec.All = types.NewBool(true) } else { spec.PathSet = ps } pspec = append(pspec, spec) } req := types.RetrieveProperties{ SpecSet: []types.PropertyFilterSpec{ { ObjectSet: []types.ObjectSpec{ospec}, PropSet: pspec, }, }, } res, err := pc.RetrieveProperties(ctx, req) if err != nil { return err } if d, ok := dst.(*[]types.ObjectContent); ok { *d = res.Returnval return nil } return mo.LoadRetrievePropertiesResponse(res, dst) }
[ "func", "(", "v", "ContainerView", ")", "Retrieve", "(", "ctx", "context", ".", "Context", ",", "kind", "[", "]", "string", ",", "ps", "[", "]", "string", ",", "dst", "interface", "{", "}", ")", "error", "{", "pc", ":=", "property", ".", "DefaultCollector", "(", "v", ".", "Client", "(", ")", ")", "\n\n", "ospec", ":=", "types", ".", "ObjectSpec", "{", "Obj", ":", "v", ".", "Reference", "(", ")", ",", "Skip", ":", "types", ".", "NewBool", "(", "true", ")", ",", "SelectSet", ":", "[", "]", "types", ".", "BaseSelectionSpec", "{", "&", "types", ".", "TraversalSpec", "{", "Type", ":", "v", ".", "Reference", "(", ")", ".", "Type", ",", "Path", ":", "\"", "\"", ",", "}", ",", "}", ",", "}", "\n\n", "var", "pspec", "[", "]", "types", ".", "PropertySpec", "\n\n", "if", "len", "(", "kind", ")", "==", "0", "{", "kind", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n\n", "for", "_", ",", "t", ":=", "range", "kind", "{", "spec", ":=", "types", ".", "PropertySpec", "{", "Type", ":", "t", ",", "}", "\n\n", "if", "len", "(", "ps", ")", "==", "0", "{", "spec", ".", "All", "=", "types", ".", "NewBool", "(", "true", ")", "\n", "}", "else", "{", "spec", ".", "PathSet", "=", "ps", "\n", "}", "\n\n", "pspec", "=", "append", "(", "pspec", ",", "spec", ")", "\n", "}", "\n\n", "req", ":=", "types", ".", "RetrieveProperties", "{", "SpecSet", ":", "[", "]", "types", ".", "PropertyFilterSpec", "{", "{", "ObjectSet", ":", "[", "]", "types", ".", "ObjectSpec", "{", "ospec", "}", ",", "PropSet", ":", "pspec", ",", "}", ",", "}", ",", "}", "\n\n", "res", ",", "err", ":=", "pc", ".", "RetrieveProperties", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "d", ",", "ok", ":=", "dst", ".", "(", "*", "[", "]", "types", ".", "ObjectContent", ")", ";", "ok", "{", "*", "d", "=", "res", ".", "Returnval", "\n", "return", "nil", "\n", "}", "\n\n", "return", "mo", ".", "LoadRetrievePropertiesResponse", "(", "res", ",", "dst", ")", "\n", "}" ]
// Retrieve populates dst as property.Collector.Retrieve does, for all entities in the view of types specified by kind.
[ "Retrieve", "populates", "dst", "as", "property", ".", "Collector", ".", "Retrieve", "does", "for", "all", "entities", "in", "the", "view", "of", "types", "specified", "by", "kind", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/container_view.go#L39-L93
train
vmware/govmomi
view/container_view.go
Find
func (v ContainerView) Find(ctx context.Context, kind []string, filter property.Filter) ([]types.ManagedObjectReference, error) { if len(filter) == 0 { // Ensure we have at least 1 filter to avoid retrieving all properties. filter = property.Filter{"name": "*"} } var content []types.ObjectContent err := v.Retrieve(ctx, kind, filter.Keys(), &content) if err != nil { return nil, err } return filter.MatchObjectContent(content), nil }
go
func (v ContainerView) Find(ctx context.Context, kind []string, filter property.Filter) ([]types.ManagedObjectReference, error) { if len(filter) == 0 { // Ensure we have at least 1 filter to avoid retrieving all properties. filter = property.Filter{"name": "*"} } var content []types.ObjectContent err := v.Retrieve(ctx, kind, filter.Keys(), &content) if err != nil { return nil, err } return filter.MatchObjectContent(content), nil }
[ "func", "(", "v", "ContainerView", ")", "Find", "(", "ctx", "context", ".", "Context", ",", "kind", "[", "]", "string", ",", "filter", "property", ".", "Filter", ")", "(", "[", "]", "types", ".", "ManagedObjectReference", ",", "error", ")", "{", "if", "len", "(", "filter", ")", "==", "0", "{", "// Ensure we have at least 1 filter to avoid retrieving all properties.", "filter", "=", "property", ".", "Filter", "{", "\"", "\"", ":", "\"", "\"", "}", "\n", "}", "\n\n", "var", "content", "[", "]", "types", ".", "ObjectContent", "\n\n", "err", ":=", "v", ".", "Retrieve", "(", "ctx", ",", "kind", ",", "filter", ".", "Keys", "(", ")", ",", "&", "content", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "filter", ".", "MatchObjectContent", "(", "content", ")", ",", "nil", "\n", "}" ]
// Find returns object references for entities of type kind, matching the given filter.
[ "Find", "returns", "object", "references", "for", "entities", "of", "type", "kind", "matching", "the", "given", "filter", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/container_view.go#L116-L130
train
vmware/govmomi
simulator/virtual_machine.go
updateDiskLayouts
func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault { var disksLayout []types.VirtualMachineFileLayoutDiskLayout var disksLayoutEx []types.VirtualMachineFileLayoutExDiskLayout disks := object.VirtualDeviceList(vm.Config.Hardware.Device).SelectByType((*types.VirtualDisk)(nil)) for _, disk := range disks { disk := disk.(*types.VirtualDisk) diskBacking := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo) diskLayout := &types.VirtualMachineFileLayoutDiskLayout{Key: disk.Key} diskLayoutEx := &types.VirtualMachineFileLayoutExDiskLayout{Key: disk.Key} // Iterate through disk and its parents for { dFileName := diskBacking.GetVirtualDeviceFileBackingInfo().FileName var fileKeys []int32 dm := Map.VirtualDiskManager() // Add disk descriptor and extent files for _, diskName := range dm.names(dFileName) { // get full path including datastore location p, fault := parseDatastorePath(diskName) if fault != nil { return fault } datastore := vm.useDatastore(p.Datastore) dFilePath := path.Join(datastore.Info.GetDatastoreInfo().Url, p.Path) var fileSize int64 // If file can not be opened - fileSize will be 0 if dFileInfo, err := os.Stat(dFilePath); err == nil { fileSize = dFileInfo.Size() } diskKey := vm.addFileLayoutEx(*p, fileSize) fileKeys = append(fileKeys, diskKey) } diskLayout.DiskFile = append(diskLayout.DiskFile, dFileName) diskLayoutEx.Chain = append(diskLayoutEx.Chain, types.VirtualMachineFileLayoutExDiskUnit{ FileKey: fileKeys, }) if parent := diskBacking.Parent; parent != nil { diskBacking = parent } else { break } } disksLayout = append(disksLayout, *diskLayout) disksLayoutEx = append(disksLayoutEx, *diskLayoutEx) } vm.Layout.Disk = disksLayout vm.LayoutEx.Disk = disksLayoutEx vm.LayoutEx.Timestamp = time.Now() vm.updateStorage() return nil }
go
func (vm *VirtualMachine) updateDiskLayouts() types.BaseMethodFault { var disksLayout []types.VirtualMachineFileLayoutDiskLayout var disksLayoutEx []types.VirtualMachineFileLayoutExDiskLayout disks := object.VirtualDeviceList(vm.Config.Hardware.Device).SelectByType((*types.VirtualDisk)(nil)) for _, disk := range disks { disk := disk.(*types.VirtualDisk) diskBacking := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo) diskLayout := &types.VirtualMachineFileLayoutDiskLayout{Key: disk.Key} diskLayoutEx := &types.VirtualMachineFileLayoutExDiskLayout{Key: disk.Key} // Iterate through disk and its parents for { dFileName := diskBacking.GetVirtualDeviceFileBackingInfo().FileName var fileKeys []int32 dm := Map.VirtualDiskManager() // Add disk descriptor and extent files for _, diskName := range dm.names(dFileName) { // get full path including datastore location p, fault := parseDatastorePath(diskName) if fault != nil { return fault } datastore := vm.useDatastore(p.Datastore) dFilePath := path.Join(datastore.Info.GetDatastoreInfo().Url, p.Path) var fileSize int64 // If file can not be opened - fileSize will be 0 if dFileInfo, err := os.Stat(dFilePath); err == nil { fileSize = dFileInfo.Size() } diskKey := vm.addFileLayoutEx(*p, fileSize) fileKeys = append(fileKeys, diskKey) } diskLayout.DiskFile = append(diskLayout.DiskFile, dFileName) diskLayoutEx.Chain = append(diskLayoutEx.Chain, types.VirtualMachineFileLayoutExDiskUnit{ FileKey: fileKeys, }) if parent := diskBacking.Parent; parent != nil { diskBacking = parent } else { break } } disksLayout = append(disksLayout, *diskLayout) disksLayoutEx = append(disksLayoutEx, *diskLayoutEx) } vm.Layout.Disk = disksLayout vm.LayoutEx.Disk = disksLayoutEx vm.LayoutEx.Timestamp = time.Now() vm.updateStorage() return nil }
[ "func", "(", "vm", "*", "VirtualMachine", ")", "updateDiskLayouts", "(", ")", "types", ".", "BaseMethodFault", "{", "var", "disksLayout", "[", "]", "types", ".", "VirtualMachineFileLayoutDiskLayout", "\n", "var", "disksLayoutEx", "[", "]", "types", ".", "VirtualMachineFileLayoutExDiskLayout", "\n\n", "disks", ":=", "object", ".", "VirtualDeviceList", "(", "vm", ".", "Config", ".", "Hardware", ".", "Device", ")", ".", "SelectByType", "(", "(", "*", "types", ".", "VirtualDisk", ")", "(", "nil", ")", ")", "\n", "for", "_", ",", "disk", ":=", "range", "disks", "{", "disk", ":=", "disk", ".", "(", "*", "types", ".", "VirtualDisk", ")", "\n", "diskBacking", ":=", "disk", ".", "Backing", ".", "(", "*", "types", ".", "VirtualDiskFlatVer2BackingInfo", ")", "\n\n", "diskLayout", ":=", "&", "types", ".", "VirtualMachineFileLayoutDiskLayout", "{", "Key", ":", "disk", ".", "Key", "}", "\n", "diskLayoutEx", ":=", "&", "types", ".", "VirtualMachineFileLayoutExDiskLayout", "{", "Key", ":", "disk", ".", "Key", "}", "\n\n", "// Iterate through disk and its parents", "for", "{", "dFileName", ":=", "diskBacking", ".", "GetVirtualDeviceFileBackingInfo", "(", ")", ".", "FileName", "\n\n", "var", "fileKeys", "[", "]", "int32", "\n\n", "dm", ":=", "Map", ".", "VirtualDiskManager", "(", ")", "\n", "// Add disk descriptor and extent files", "for", "_", ",", "diskName", ":=", "range", "dm", ".", "names", "(", "dFileName", ")", "{", "// get full path including datastore location", "p", ",", "fault", ":=", "parseDatastorePath", "(", "diskName", ")", "\n", "if", "fault", "!=", "nil", "{", "return", "fault", "\n", "}", "\n\n", "datastore", ":=", "vm", ".", "useDatastore", "(", "p", ".", "Datastore", ")", "\n", "dFilePath", ":=", "path", ".", "Join", "(", "datastore", ".", "Info", ".", "GetDatastoreInfo", "(", ")", ".", "Url", ",", "p", ".", "Path", ")", "\n\n", "var", "fileSize", "int64", "\n", "// If file can not be opened - fileSize will be 0", "if", "dFileInfo", ",", "err", ":=", "os", ".", "Stat", "(", "dFilePath", ")", ";", "err", "==", "nil", "{", "fileSize", "=", "dFileInfo", ".", "Size", "(", ")", "\n", "}", "\n\n", "diskKey", ":=", "vm", ".", "addFileLayoutEx", "(", "*", "p", ",", "fileSize", ")", "\n", "fileKeys", "=", "append", "(", "fileKeys", ",", "diskKey", ")", "\n", "}", "\n\n", "diskLayout", ".", "DiskFile", "=", "append", "(", "diskLayout", ".", "DiskFile", ",", "dFileName", ")", "\n", "diskLayoutEx", ".", "Chain", "=", "append", "(", "diskLayoutEx", ".", "Chain", ",", "types", ".", "VirtualMachineFileLayoutExDiskUnit", "{", "FileKey", ":", "fileKeys", ",", "}", ")", "\n\n", "if", "parent", ":=", "diskBacking", ".", "Parent", ";", "parent", "!=", "nil", "{", "diskBacking", "=", "parent", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n\n", "disksLayout", "=", "append", "(", "disksLayout", ",", "*", "diskLayout", ")", "\n", "disksLayoutEx", "=", "append", "(", "disksLayoutEx", ",", "*", "diskLayoutEx", ")", "\n", "}", "\n\n", "vm", ".", "Layout", ".", "Disk", "=", "disksLayout", "\n\n", "vm", ".", "LayoutEx", ".", "Disk", "=", "disksLayoutEx", "\n", "vm", ".", "LayoutEx", ".", "Timestamp", "=", "time", ".", "Now", "(", ")", "\n\n", "vm", ".", "updateStorage", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Updates both vm.Layout.Disk and vm.LayoutEx.Disk
[ "Updates", "both", "vm", ".", "Layout", ".", "Disk", "and", "vm", ".", "LayoutEx", ".", "Disk" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/virtual_machine.go#L519-L583
train
vmware/govmomi
govc/flags/output.go
Log
func (flag *OutputFlag) Log(s string) (int, error) { if len(s) > 0 && s[0] == '\r' { flag.Write([]byte{'\r', 033, '[', 'K'}) s = s[1:] } return flag.WriteString(time.Now().Format("[02-01-06 15:04:05] ") + s) }
go
func (flag *OutputFlag) Log(s string) (int, error) { if len(s) > 0 && s[0] == '\r' { flag.Write([]byte{'\r', 033, '[', 'K'}) s = s[1:] } return flag.WriteString(time.Now().Format("[02-01-06 15:04:05] ") + s) }
[ "func", "(", "flag", "*", "OutputFlag", ")", "Log", "(", "s", "string", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "s", ")", ">", "0", "&&", "s", "[", "0", "]", "==", "'\\r'", "{", "flag", ".", "Write", "(", "[", "]", "byte", "{", "'\\r'", ",", "033", ",", "'['", ",", "'K'", "}", ")", "\n", "s", "=", "s", "[", "1", ":", "]", "\n", "}", "\n\n", "return", "flag", ".", "WriteString", "(", "time", ".", "Now", "(", ")", ".", "Format", "(", "\"", "\"", ")", "+", "s", ")", "\n", "}" ]
// Log outputs the specified string, prefixed with the current time. // A newline is not automatically added. If the specified string // starts with a '\r', the current line is cleared first.
[ "Log", "outputs", "the", "specified", "string", "prefixed", "with", "the", "current", "time", ".", "A", "newline", "is", "not", "automatically", "added", ".", "If", "the", "specified", "string", "starts", "with", "a", "\\", "r", "the", "current", "line", "is", "cleared", "first", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/flags/output.go#L80-L87
train
vmware/govmomi
vim25/mo/retrieve.go
ObjectContentToType
func ObjectContentToType(o types.ObjectContent) (interface{}, error) { // Expect no properties in the missing set for _, p := range o.MissingSet { if ignoreMissingProperty(o.Obj, p) { continue } return nil, soap.WrapVimFault(p.Fault.Fault) } ti := typeInfoForType(o.Obj.Type) v, err := ti.LoadFromObjectContent(o) if err != nil { return nil, err } return v.Elem().Interface(), nil }
go
func ObjectContentToType(o types.ObjectContent) (interface{}, error) { // Expect no properties in the missing set for _, p := range o.MissingSet { if ignoreMissingProperty(o.Obj, p) { continue } return nil, soap.WrapVimFault(p.Fault.Fault) } ti := typeInfoForType(o.Obj.Type) v, err := ti.LoadFromObjectContent(o) if err != nil { return nil, err } return v.Elem().Interface(), nil }
[ "func", "ObjectContentToType", "(", "o", "types", ".", "ObjectContent", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Expect no properties in the missing set", "for", "_", ",", "p", ":=", "range", "o", ".", "MissingSet", "{", "if", "ignoreMissingProperty", "(", "o", ".", "Obj", ",", "p", ")", "{", "continue", "\n", "}", "\n\n", "return", "nil", ",", "soap", ".", "WrapVimFault", "(", "p", ".", "Fault", ".", "Fault", ")", "\n", "}", "\n\n", "ti", ":=", "typeInfoForType", "(", "o", ".", "Obj", ".", "Type", ")", "\n", "v", ",", "err", ":=", "ti", ".", "LoadFromObjectContent", "(", "o", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "v", ".", "Elem", "(", ")", ".", "Interface", "(", ")", ",", "nil", "\n", "}" ]
// ObjectContentToType loads an ObjectContent value into the value it // represents. If the ObjectContent value has a non-empty 'MissingSet' field, // it returns the first fault it finds there as error. If the 'MissingSet' // field is empty, it returns a pointer to a reflect.Value. It handles contain // nested properties, such as 'guest.ipAddress' or 'config.hardware'.
[ "ObjectContentToType", "loads", "an", "ObjectContent", "value", "into", "the", "value", "it", "represents", ".", "If", "the", "ObjectContent", "value", "has", "a", "non", "-", "empty", "MissingSet", "field", "it", "returns", "the", "first", "fault", "it", "finds", "there", "as", "error", ".", "If", "the", "MissingSet", "field", "is", "empty", "it", "returns", "a", "pointer", "to", "a", "reflect", ".", "Value", ".", "It", "handles", "contain", "nested", "properties", "such", "as", "guest", ".", "ipAddress", "or", "config", ".", "hardware", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L49-L66
train
vmware/govmomi
vim25/mo/retrieve.go
ApplyPropertyChange
func ApplyPropertyChange(obj Reference, changes []types.PropertyChange) { t := typeInfoForType(obj.Reference().Type) v := reflect.ValueOf(obj) for _, p := range changes { rv, ok := t.props[p.Name] if !ok { continue } assignValue(v, rv, reflect.ValueOf(p.Val)) } }
go
func ApplyPropertyChange(obj Reference, changes []types.PropertyChange) { t := typeInfoForType(obj.Reference().Type) v := reflect.ValueOf(obj) for _, p := range changes { rv, ok := t.props[p.Name] if !ok { continue } assignValue(v, rv, reflect.ValueOf(p.Val)) } }
[ "func", "ApplyPropertyChange", "(", "obj", "Reference", ",", "changes", "[", "]", "types", ".", "PropertyChange", ")", "{", "t", ":=", "typeInfoForType", "(", "obj", ".", "Reference", "(", ")", ".", "Type", ")", "\n", "v", ":=", "reflect", ".", "ValueOf", "(", "obj", ")", "\n\n", "for", "_", ",", "p", ":=", "range", "changes", "{", "rv", ",", "ok", ":=", "t", ".", "props", "[", "p", ".", "Name", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "assignValue", "(", "v", ",", "rv", ",", "reflect", ".", "ValueOf", "(", "p", ".", "Val", ")", ")", "\n", "}", "\n", "}" ]
// ApplyPropertyChange converts the response of a call to WaitForUpdates // and applies it to the given managed object.
[ "ApplyPropertyChange", "converts", "the", "response", "of", "a", "call", "to", "WaitForUpdates", "and", "applies", "it", "to", "the", "given", "managed", "object", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L70-L82
train
vmware/govmomi
vim25/mo/retrieve.go
LoadRetrievePropertiesResponse
func LoadRetrievePropertiesResponse(res *types.RetrievePropertiesResponse, dst interface{}) error { rt := reflect.TypeOf(dst) if rt == nil || rt.Kind() != reflect.Ptr { panic("need pointer") } rv := reflect.ValueOf(dst).Elem() if !rv.CanSet() { panic("cannot set dst") } isSlice := false switch rt.Elem().Kind() { case reflect.Struct: case reflect.Slice: isSlice = true default: panic("unexpected type") } if isSlice { for _, p := range res.Returnval { v, err := ObjectContentToType(p) if err != nil { return err } vt := reflect.TypeOf(v) if !rv.Type().AssignableTo(vt) { // For example: dst is []ManagedEntity, res is []HostSystem if field, ok := vt.FieldByName(rt.Elem().Elem().Name()); ok && field.Anonymous { rv.Set(reflect.Append(rv, reflect.ValueOf(v).FieldByIndex(field.Index))) continue } } rv.Set(reflect.Append(rv, reflect.ValueOf(v))) } } else { switch len(res.Returnval) { case 0: case 1: v, err := ObjectContentToType(res.Returnval[0]) if err != nil { return err } vt := reflect.TypeOf(v) if !rv.Type().AssignableTo(vt) { // For example: dst is ComputeResource, res is ClusterComputeResource if field, ok := vt.FieldByName(rt.Elem().Name()); ok && field.Anonymous { rv.Set(reflect.ValueOf(v).FieldByIndex(field.Index)) return nil } } rv.Set(reflect.ValueOf(v)) default: // If dst is not a slice, expect to receive 0 or 1 results panic("more than 1 result") } } return nil }
go
func LoadRetrievePropertiesResponse(res *types.RetrievePropertiesResponse, dst interface{}) error { rt := reflect.TypeOf(dst) if rt == nil || rt.Kind() != reflect.Ptr { panic("need pointer") } rv := reflect.ValueOf(dst).Elem() if !rv.CanSet() { panic("cannot set dst") } isSlice := false switch rt.Elem().Kind() { case reflect.Struct: case reflect.Slice: isSlice = true default: panic("unexpected type") } if isSlice { for _, p := range res.Returnval { v, err := ObjectContentToType(p) if err != nil { return err } vt := reflect.TypeOf(v) if !rv.Type().AssignableTo(vt) { // For example: dst is []ManagedEntity, res is []HostSystem if field, ok := vt.FieldByName(rt.Elem().Elem().Name()); ok && field.Anonymous { rv.Set(reflect.Append(rv, reflect.ValueOf(v).FieldByIndex(field.Index))) continue } } rv.Set(reflect.Append(rv, reflect.ValueOf(v))) } } else { switch len(res.Returnval) { case 0: case 1: v, err := ObjectContentToType(res.Returnval[0]) if err != nil { return err } vt := reflect.TypeOf(v) if !rv.Type().AssignableTo(vt) { // For example: dst is ComputeResource, res is ClusterComputeResource if field, ok := vt.FieldByName(rt.Elem().Name()); ok && field.Anonymous { rv.Set(reflect.ValueOf(v).FieldByIndex(field.Index)) return nil } } rv.Set(reflect.ValueOf(v)) default: // If dst is not a slice, expect to receive 0 or 1 results panic("more than 1 result") } } return nil }
[ "func", "LoadRetrievePropertiesResponse", "(", "res", "*", "types", ".", "RetrievePropertiesResponse", ",", "dst", "interface", "{", "}", ")", "error", "{", "rt", ":=", "reflect", ".", "TypeOf", "(", "dst", ")", "\n", "if", "rt", "==", "nil", "||", "rt", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "rv", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", ".", "Elem", "(", ")", "\n", "if", "!", "rv", ".", "CanSet", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "isSlice", ":=", "false", "\n", "switch", "rt", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "case", "reflect", ".", "Slice", ":", "isSlice", "=", "true", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "isSlice", "{", "for", "_", ",", "p", ":=", "range", "res", ".", "Returnval", "{", "v", ",", "err", ":=", "ObjectContentToType", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "vt", ":=", "reflect", ".", "TypeOf", "(", "v", ")", "\n\n", "if", "!", "rv", ".", "Type", "(", ")", ".", "AssignableTo", "(", "vt", ")", "{", "// For example: dst is []ManagedEntity, res is []HostSystem", "if", "field", ",", "ok", ":=", "vt", ".", "FieldByName", "(", "rt", ".", "Elem", "(", ")", ".", "Elem", "(", ")", ".", "Name", "(", ")", ")", ";", "ok", "&&", "field", ".", "Anonymous", "{", "rv", ".", "Set", "(", "reflect", ".", "Append", "(", "rv", ",", "reflect", ".", "ValueOf", "(", "v", ")", ".", "FieldByIndex", "(", "field", ".", "Index", ")", ")", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "rv", ".", "Set", "(", "reflect", ".", "Append", "(", "rv", ",", "reflect", ".", "ValueOf", "(", "v", ")", ")", ")", "\n", "}", "\n", "}", "else", "{", "switch", "len", "(", "res", ".", "Returnval", ")", "{", "case", "0", ":", "case", "1", ":", "v", ",", "err", ":=", "ObjectContentToType", "(", "res", ".", "Returnval", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "vt", ":=", "reflect", ".", "TypeOf", "(", "v", ")", "\n\n", "if", "!", "rv", ".", "Type", "(", ")", ".", "AssignableTo", "(", "vt", ")", "{", "// For example: dst is ComputeResource, res is ClusterComputeResource", "if", "field", ",", "ok", ":=", "vt", ".", "FieldByName", "(", "rt", ".", "Elem", "(", ")", ".", "Name", "(", ")", ")", ";", "ok", "&&", "field", ".", "Anonymous", "{", "rv", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "v", ")", ".", "FieldByIndex", "(", "field", ".", "Index", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "rv", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "v", ")", ")", "\n", "default", ":", "// If dst is not a slice, expect to receive 0 or 1 results", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// LoadRetrievePropertiesResponse converts the response of a call to // RetrieveProperties to one or more managed objects.
[ "LoadRetrievePropertiesResponse", "converts", "the", "response", "of", "a", "call", "to", "RetrieveProperties", "to", "one", "or", "more", "managed", "objects", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L86-L152
train
vmware/govmomi
vim25/mo/retrieve.go
RetrievePropertiesForRequest
func RetrievePropertiesForRequest(ctx context.Context, r soap.RoundTripper, req types.RetrieveProperties, dst interface{}) error { res, err := methods.RetrieveProperties(ctx, r, &req) if err != nil { return err } return LoadRetrievePropertiesResponse(res, dst) }
go
func RetrievePropertiesForRequest(ctx context.Context, r soap.RoundTripper, req types.RetrieveProperties, dst interface{}) error { res, err := methods.RetrieveProperties(ctx, r, &req) if err != nil { return err } return LoadRetrievePropertiesResponse(res, dst) }
[ "func", "RetrievePropertiesForRequest", "(", "ctx", "context", ".", "Context", ",", "r", "soap", ".", "RoundTripper", ",", "req", "types", ".", "RetrieveProperties", ",", "dst", "interface", "{", "}", ")", "error", "{", "res", ",", "err", ":=", "methods", ".", "RetrieveProperties", "(", "ctx", ",", "r", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "LoadRetrievePropertiesResponse", "(", "res", ",", "dst", ")", "\n", "}" ]
// RetrievePropertiesForRequest calls the RetrieveProperties method with the // specified request and decodes the response struct into the value pointed to // by dst.
[ "RetrievePropertiesForRequest", "calls", "the", "RetrieveProperties", "method", "with", "the", "specified", "request", "and", "decodes", "the", "response", "struct", "into", "the", "value", "pointed", "to", "by", "dst", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L157-L164
train
vmware/govmomi
vim25/mo/retrieve.go
RetrieveProperties
func RetrieveProperties(ctx context.Context, r soap.RoundTripper, pc, obj types.ManagedObjectReference, dst interface{}) error { req := types.RetrieveProperties{ This: pc, SpecSet: []types.PropertyFilterSpec{ { ObjectSet: []types.ObjectSpec{ { Obj: obj, Skip: types.NewBool(false), }, }, PropSet: []types.PropertySpec{ { All: types.NewBool(true), Type: obj.Type, }, }, }, }, } return RetrievePropertiesForRequest(ctx, r, req, dst) }
go
func RetrieveProperties(ctx context.Context, r soap.RoundTripper, pc, obj types.ManagedObjectReference, dst interface{}) error { req := types.RetrieveProperties{ This: pc, SpecSet: []types.PropertyFilterSpec{ { ObjectSet: []types.ObjectSpec{ { Obj: obj, Skip: types.NewBool(false), }, }, PropSet: []types.PropertySpec{ { All: types.NewBool(true), Type: obj.Type, }, }, }, }, } return RetrievePropertiesForRequest(ctx, r, req, dst) }
[ "func", "RetrieveProperties", "(", "ctx", "context", ".", "Context", ",", "r", "soap", ".", "RoundTripper", ",", "pc", ",", "obj", "types", ".", "ManagedObjectReference", ",", "dst", "interface", "{", "}", ")", "error", "{", "req", ":=", "types", ".", "RetrieveProperties", "{", "This", ":", "pc", ",", "SpecSet", ":", "[", "]", "types", ".", "PropertyFilterSpec", "{", "{", "ObjectSet", ":", "[", "]", "types", ".", "ObjectSpec", "{", "{", "Obj", ":", "obj", ",", "Skip", ":", "types", ".", "NewBool", "(", "false", ")", ",", "}", ",", "}", ",", "PropSet", ":", "[", "]", "types", ".", "PropertySpec", "{", "{", "All", ":", "types", ".", "NewBool", "(", "true", ")", ",", "Type", ":", "obj", ".", "Type", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n\n", "return", "RetrievePropertiesForRequest", "(", "ctx", ",", "r", ",", "req", ",", "dst", ")", "\n", "}" ]
// RetrieveProperties retrieves the properties of the managed object specified // as obj and decodes the response struct into the value pointed to by dst.
[ "RetrieveProperties", "retrieves", "the", "properties", "of", "the", "managed", "object", "specified", "as", "obj", "and", "decodes", "the", "response", "struct", "into", "the", "value", "pointed", "to", "by", "dst", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/retrieve.go#L168-L190
train
vmware/govmomi
toolbox/hgfs/server.go
NewServer
func NewServer() *Server { if f := flag.Lookup("toolbox.trace"); f != nil { Trace, _ = strconv.ParseBool(f.Value.String()) } s := &Server{ sessions: make(map[uint64]*session), schemes: make(map[string]FileHandler), chmod: os.Chmod, chown: os.Chown, } s.handlers = map[int32]func(*Packet) (interface{}, error){ OpCreateSessionV4: s.CreateSessionV4, OpDestroySessionV4: s.DestroySessionV4, OpGetattrV2: s.GetattrV2, OpSetattrV2: s.SetattrV2, OpOpen: s.Open, OpClose: s.Close, OpOpenV3: s.OpenV3, OpReadV3: s.ReadV3, OpWriteV3: s.WriteV3, } for op := range s.handlers { s.Capabilities = append(s.Capabilities, Capability{Op: op, Flags: 0x1}) } return s }
go
func NewServer() *Server { if f := flag.Lookup("toolbox.trace"); f != nil { Trace, _ = strconv.ParseBool(f.Value.String()) } s := &Server{ sessions: make(map[uint64]*session), schemes: make(map[string]FileHandler), chmod: os.Chmod, chown: os.Chown, } s.handlers = map[int32]func(*Packet) (interface{}, error){ OpCreateSessionV4: s.CreateSessionV4, OpDestroySessionV4: s.DestroySessionV4, OpGetattrV2: s.GetattrV2, OpSetattrV2: s.SetattrV2, OpOpen: s.Open, OpClose: s.Close, OpOpenV3: s.OpenV3, OpReadV3: s.ReadV3, OpWriteV3: s.WriteV3, } for op := range s.handlers { s.Capabilities = append(s.Capabilities, Capability{Op: op, Flags: 0x1}) } return s }
[ "func", "NewServer", "(", ")", "*", "Server", "{", "if", "f", ":=", "flag", ".", "Lookup", "(", "\"", "\"", ")", ";", "f", "!=", "nil", "{", "Trace", ",", "_", "=", "strconv", ".", "ParseBool", "(", "f", ".", "Value", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "s", ":=", "&", "Server", "{", "sessions", ":", "make", "(", "map", "[", "uint64", "]", "*", "session", ")", ",", "schemes", ":", "make", "(", "map", "[", "string", "]", "FileHandler", ")", ",", "chmod", ":", "os", ".", "Chmod", ",", "chown", ":", "os", ".", "Chown", ",", "}", "\n\n", "s", ".", "handlers", "=", "map", "[", "int32", "]", "func", "(", "*", "Packet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "OpCreateSessionV4", ":", "s", ".", "CreateSessionV4", ",", "OpDestroySessionV4", ":", "s", ".", "DestroySessionV4", ",", "OpGetattrV2", ":", "s", ".", "GetattrV2", ",", "OpSetattrV2", ":", "s", ".", "SetattrV2", ",", "OpOpen", ":", "s", ".", "Open", ",", "OpClose", ":", "s", ".", "Close", ",", "OpOpenV3", ":", "s", ".", "OpenV3", ",", "OpReadV3", ":", "s", ".", "ReadV3", ",", "OpWriteV3", ":", "s", ".", "WriteV3", ",", "}", "\n\n", "for", "op", ":=", "range", "s", ".", "handlers", "{", "s", ".", "Capabilities", "=", "append", "(", "s", ".", "Capabilities", ",", "Capability", "{", "Op", ":", "op", ",", "Flags", ":", "0x1", "}", ")", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// NewServer creates a new Server instance with the default handlers
[ "NewServer", "creates", "a", "new", "Server", "instance", "with", "the", "default", "handlers" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L57-L86
train
vmware/govmomi
toolbox/hgfs/server.go
RegisterFileHandler
func (s *Server) RegisterFileHandler(scheme string, handler FileHandler) { if handler == nil { delete(s.schemes, scheme) return } s.schemes[scheme] = handler }
go
func (s *Server) RegisterFileHandler(scheme string, handler FileHandler) { if handler == nil { delete(s.schemes, scheme) return } s.schemes[scheme] = handler }
[ "func", "(", "s", "*", "Server", ")", "RegisterFileHandler", "(", "scheme", "string", ",", "handler", "FileHandler", ")", "{", "if", "handler", "==", "nil", "{", "delete", "(", "s", ".", "schemes", ",", "scheme", ")", "\n", "return", "\n", "}", "\n", "s", ".", "schemes", "[", "scheme", "]", "=", "handler", "\n", "}" ]
// RegisterFileHandler enables dispatch to handler for the given scheme.
[ "RegisterFileHandler", "enables", "dispatch", "to", "handler", "for", "the", "given", "scheme", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L89-L95
train
vmware/govmomi
toolbox/hgfs/server.go
Dispatch
func (s *Server) Dispatch(packet []byte) ([]byte, error) { req := &Packet{} err := req.UnmarshalBinary(packet) if err != nil { return nil, err } if Trace { fmt.Fprintf(os.Stderr, "[hgfs] request %#v\n", req.Header) } var res interface{} handler, ok := s.handlers[req.Op] if ok { res, err = handler(req) } else { err = &Status{ Code: StatusOperationNotSupported, Err: fmt.Errorf("unsupported Op(%d)", req.Op), } } return req.Reply(res, err) }
go
func (s *Server) Dispatch(packet []byte) ([]byte, error) { req := &Packet{} err := req.UnmarshalBinary(packet) if err != nil { return nil, err } if Trace { fmt.Fprintf(os.Stderr, "[hgfs] request %#v\n", req.Header) } var res interface{} handler, ok := s.handlers[req.Op] if ok { res, err = handler(req) } else { err = &Status{ Code: StatusOperationNotSupported, Err: fmt.Errorf("unsupported Op(%d)", req.Op), } } return req.Reply(res, err) }
[ "func", "(", "s", "*", "Server", ")", "Dispatch", "(", "packet", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "req", ":=", "&", "Packet", "{", "}", "\n\n", "err", ":=", "req", ".", "UnmarshalBinary", "(", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "Trace", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "req", ".", "Header", ")", "\n", "}", "\n\n", "var", "res", "interface", "{", "}", "\n\n", "handler", ",", "ok", ":=", "s", ".", "handlers", "[", "req", ".", "Op", "]", "\n", "if", "ok", "{", "res", ",", "err", "=", "handler", "(", "req", ")", "\n", "}", "else", "{", "err", "=", "&", "Status", "{", "Code", ":", "StatusOperationNotSupported", ",", "Err", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Op", ")", ",", "}", "\n", "}", "\n\n", "return", "req", ".", "Reply", "(", "res", ",", "err", ")", "\n", "}" ]
// Dispatch unpacks the given request packet and dispatches to the appropriate handler
[ "Dispatch", "unpacks", "the", "given", "request", "packet", "and", "dispatches", "to", "the", "appropriate", "handler" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L98-L123
train
vmware/govmomi
toolbox/hgfs/server.go
urlParse
func urlParse(name string) *url.URL { var info os.FileInfo u, err := url.Parse(name) if err == nil && u.Scheme == "" { info, err = os.Stat(u.Path) if err == nil && info.IsDir() { u.Scheme = ArchiveScheme // special case for IsDir() return u } } u, err = url.Parse(strings.TrimPrefix(name, "/")) // must appear to be an absolute path or hgfs errors if err != nil { u = &url.URL{Path: name} } if u.Scheme == "" { ix := strings.Index(u.Path, "/") if ix > 0 { u.Scheme = u.Path[:ix] u.Path = u.Path[ix:] } } return u }
go
func urlParse(name string) *url.URL { var info os.FileInfo u, err := url.Parse(name) if err == nil && u.Scheme == "" { info, err = os.Stat(u.Path) if err == nil && info.IsDir() { u.Scheme = ArchiveScheme // special case for IsDir() return u } } u, err = url.Parse(strings.TrimPrefix(name, "/")) // must appear to be an absolute path or hgfs errors if err != nil { u = &url.URL{Path: name} } if u.Scheme == "" { ix := strings.Index(u.Path, "/") if ix > 0 { u.Scheme = u.Path[:ix] u.Path = u.Path[ix:] } } return u }
[ "func", "urlParse", "(", "name", "string", ")", "*", "url", ".", "URL", "{", "var", "info", "os", ".", "FileInfo", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "name", ")", "\n", "if", "err", "==", "nil", "&&", "u", ".", "Scheme", "==", "\"", "\"", "{", "info", ",", "err", "=", "os", ".", "Stat", "(", "u", ".", "Path", ")", "\n", "if", "err", "==", "nil", "&&", "info", ".", "IsDir", "(", ")", "{", "u", ".", "Scheme", "=", "ArchiveScheme", "// special case for IsDir()", "\n", "return", "u", "\n", "}", "\n", "}", "\n\n", "u", ",", "err", "=", "url", ".", "Parse", "(", "strings", ".", "TrimPrefix", "(", "name", ",", "\"", "\"", ")", ")", "// must appear to be an absolute path or hgfs errors", "\n", "if", "err", "!=", "nil", "{", "u", "=", "&", "url", ".", "URL", "{", "Path", ":", "name", "}", "\n", "}", "\n\n", "if", "u", ".", "Scheme", "==", "\"", "\"", "{", "ix", ":=", "strings", ".", "Index", "(", "u", ".", "Path", ",", "\"", "\"", ")", "\n", "if", "ix", ">", "0", "{", "u", ".", "Scheme", "=", "u", ".", "Path", "[", ":", "ix", "]", "\n", "u", ".", "Path", "=", "u", ".", "Path", "[", "ix", ":", "]", "\n", "}", "\n", "}", "\n\n", "return", "u", "\n", "}" ]
// urlParse attempts to convert the given name to a URL with scheme for use as FileHandler dispatch.
[ "urlParse", "attempts", "to", "convert", "the", "given", "name", "to", "a", "URL", "with", "scheme", "for", "use", "as", "FileHandler", "dispatch", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L142-L168
train
vmware/govmomi
toolbox/hgfs/server.go
OpenFile
func (s *Server) OpenFile(name string, mode int32) (File, error) { u := urlParse(name) if h, ok := s.schemes[u.Scheme]; ok { f, serr := h.Open(u, mode) if serr != os.ErrNotExist { return f, serr } } switch mode { case OpenModeReadOnly: return os.Open(filepath.Clean(name)) case OpenModeWriteOnly: flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC return os.OpenFile(name, flag, 0600) default: return nil, &Status{ Err: fmt.Errorf("open mode(%d) not supported for file %q", mode, name), Code: StatusAccessDenied, } } }
go
func (s *Server) OpenFile(name string, mode int32) (File, error) { u := urlParse(name) if h, ok := s.schemes[u.Scheme]; ok { f, serr := h.Open(u, mode) if serr != os.ErrNotExist { return f, serr } } switch mode { case OpenModeReadOnly: return os.Open(filepath.Clean(name)) case OpenModeWriteOnly: flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC return os.OpenFile(name, flag, 0600) default: return nil, &Status{ Err: fmt.Errorf("open mode(%d) not supported for file %q", mode, name), Code: StatusAccessDenied, } } }
[ "func", "(", "s", "*", "Server", ")", "OpenFile", "(", "name", "string", ",", "mode", "int32", ")", "(", "File", ",", "error", ")", "{", "u", ":=", "urlParse", "(", "name", ")", "\n\n", "if", "h", ",", "ok", ":=", "s", ".", "schemes", "[", "u", ".", "Scheme", "]", ";", "ok", "{", "f", ",", "serr", ":=", "h", ".", "Open", "(", "u", ",", "mode", ")", "\n", "if", "serr", "!=", "os", ".", "ErrNotExist", "{", "return", "f", ",", "serr", "\n", "}", "\n", "}", "\n\n", "switch", "mode", "{", "case", "OpenModeReadOnly", ":", "return", "os", ".", "Open", "(", "filepath", ".", "Clean", "(", "name", ")", ")", "\n", "case", "OpenModeWriteOnly", ":", "flag", ":=", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", "\n", "return", "os", ".", "OpenFile", "(", "name", ",", "flag", ",", "0600", ")", "\n", "default", ":", "return", "nil", ",", "&", "Status", "{", "Err", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mode", ",", "name", ")", ",", "Code", ":", "StatusAccessDenied", ",", "}", "\n", "}", "\n", "}" ]
// OpenFile selects the File implementation based on file type and mode.
[ "OpenFile", "selects", "the", "File", "implementation", "based", "on", "file", "type", "and", "mode", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L171-L193
train
vmware/govmomi
toolbox/hgfs/server.go
CreateSessionV4
func (s *Server) CreateSessionV4(p *Packet) (interface{}, error) { const SessionMaxPacketSizeValid = 0x1 req := new(RequestCreateSessionV4) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } res := &ReplyCreateSessionV4{ SessionID: uint64(rand.Int63()), NumCapabilities: uint32(len(s.Capabilities)), MaxPacketSize: LargePacketMax, Flags: SessionMaxPacketSizeValid, Capabilities: s.Capabilities, } s.mu.Lock() defer s.mu.Unlock() if len(s.sessions) > maxSessions { return nil, &Status{Code: StatusTooManySessions} } s.sessions[res.SessionID] = newSession() return res, nil }
go
func (s *Server) CreateSessionV4(p *Packet) (interface{}, error) { const SessionMaxPacketSizeValid = 0x1 req := new(RequestCreateSessionV4) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } res := &ReplyCreateSessionV4{ SessionID: uint64(rand.Int63()), NumCapabilities: uint32(len(s.Capabilities)), MaxPacketSize: LargePacketMax, Flags: SessionMaxPacketSizeValid, Capabilities: s.Capabilities, } s.mu.Lock() defer s.mu.Unlock() if len(s.sessions) > maxSessions { return nil, &Status{Code: StatusTooManySessions} } s.sessions[res.SessionID] = newSession() return res, nil }
[ "func", "(", "s", "*", "Server", ")", "CreateSessionV4", "(", "p", "*", "Packet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "const", "SessionMaxPacketSizeValid", "=", "0x1", "\n\n", "req", ":=", "new", "(", "RequestCreateSessionV4", ")", "\n", "err", ":=", "UnmarshalBinary", "(", "p", ".", "Payload", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ":=", "&", "ReplyCreateSessionV4", "{", "SessionID", ":", "uint64", "(", "rand", ".", "Int63", "(", ")", ")", ",", "NumCapabilities", ":", "uint32", "(", "len", "(", "s", ".", "Capabilities", ")", ")", ",", "MaxPacketSize", ":", "LargePacketMax", ",", "Flags", ":", "SessionMaxPacketSizeValid", ",", "Capabilities", ":", "s", ".", "Capabilities", ",", "}", "\n\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "s", ".", "sessions", ")", ">", "maxSessions", "{", "return", "nil", ",", "&", "Status", "{", "Code", ":", "StatusTooManySessions", "}", "\n", "}", "\n\n", "s", ".", "sessions", "[", "res", ".", "SessionID", "]", "=", "newSession", "(", ")", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// CreateSessionV4 handls OpCreateSessionV4 requests
[ "CreateSessionV4", "handls", "OpCreateSessionV4", "requests" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L271-L297
train
vmware/govmomi
toolbox/hgfs/server.go
DestroySessionV4
func (s *Server) DestroySessionV4(p *Packet) (interface{}, error) { if s.removeSession(p.SessionID) { return &ReplyDestroySessionV4{}, nil } return nil, &Status{Code: StatusStaleSession} }
go
func (s *Server) DestroySessionV4(p *Packet) (interface{}, error) { if s.removeSession(p.SessionID) { return &ReplyDestroySessionV4{}, nil } return nil, &Status{Code: StatusStaleSession} }
[ "func", "(", "s", "*", "Server", ")", "DestroySessionV4", "(", "p", "*", "Packet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "s", ".", "removeSession", "(", "p", ".", "SessionID", ")", "{", "return", "&", "ReplyDestroySessionV4", "{", "}", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "&", "Status", "{", "Code", ":", "StatusStaleSession", "}", "\n", "}" ]
// DestroySessionV4 handls OpDestroySessionV4 requests
[ "DestroySessionV4", "handls", "OpDestroySessionV4", "requests" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L300-L306
train
vmware/govmomi
toolbox/hgfs/server.go
Stat
func (a *AttrV2) Stat(info os.FileInfo) { switch { case info.IsDir(): a.Type = FileTypeDirectory case info.Mode()&os.ModeSymlink == os.ModeSymlink: a.Type = FileTypeSymlink default: a.Type = FileTypeRegular } a.Size = uint64(info.Size()) a.Mask = AttrValidType | AttrValidSize a.sysStat(info) }
go
func (a *AttrV2) Stat(info os.FileInfo) { switch { case info.IsDir(): a.Type = FileTypeDirectory case info.Mode()&os.ModeSymlink == os.ModeSymlink: a.Type = FileTypeSymlink default: a.Type = FileTypeRegular } a.Size = uint64(info.Size()) a.Mask = AttrValidType | AttrValidSize a.sysStat(info) }
[ "func", "(", "a", "*", "AttrV2", ")", "Stat", "(", "info", "os", ".", "FileInfo", ")", "{", "switch", "{", "case", "info", ".", "IsDir", "(", ")", ":", "a", ".", "Type", "=", "FileTypeDirectory", "\n", "case", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "==", "os", ".", "ModeSymlink", ":", "a", ".", "Type", "=", "FileTypeSymlink", "\n", "default", ":", "a", ".", "Type", "=", "FileTypeRegular", "\n", "}", "\n\n", "a", ".", "Size", "=", "uint64", "(", "info", ".", "Size", "(", ")", ")", "\n\n", "a", ".", "Mask", "=", "AttrValidType", "|", "AttrValidSize", "\n\n", "a", ".", "sysStat", "(", "info", ")", "\n", "}" ]
// Stat maps os.FileInfo to AttrV2
[ "Stat", "maps", "os", ".", "FileInfo", "to", "AttrV2" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L309-L324
train
vmware/govmomi
toolbox/hgfs/server.go
GetattrV2
func (s *Server) GetattrV2(p *Packet) (interface{}, error) { res := &ReplyGetattrV2{} req := new(RequestGetattrV2) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } name := req.FileName.Path() info, err := s.Stat(name) if err != nil { return nil, err } res.Attr.Stat(info) return res, nil }
go
func (s *Server) GetattrV2(p *Packet) (interface{}, error) { res := &ReplyGetattrV2{} req := new(RequestGetattrV2) err := UnmarshalBinary(p.Payload, req) if err != nil { return nil, err } name := req.FileName.Path() info, err := s.Stat(name) if err != nil { return nil, err } res.Attr.Stat(info) return res, nil }
[ "func", "(", "s", "*", "Server", ")", "GetattrV2", "(", "p", "*", "Packet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "res", ":=", "&", "ReplyGetattrV2", "{", "}", "\n\n", "req", ":=", "new", "(", "RequestGetattrV2", ")", "\n", "err", ":=", "UnmarshalBinary", "(", "p", ".", "Payload", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "name", ":=", "req", ".", "FileName", ".", "Path", "(", ")", "\n", "info", ",", "err", ":=", "s", ".", "Stat", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ".", "Attr", ".", "Stat", "(", "info", ")", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// GetattrV2 handles OpGetattrV2 requests
[ "GetattrV2", "handles", "OpGetattrV2", "requests" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/server.go#L327-L345
train