id
int32
0
167k
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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
21,600
vmware/govmomi
vapi/rest/client.go
Do
func (c *Client) Do(ctx context.Context, req *http.Request, resBody interface{}) error { switch req.Method { case http.MethodPost, http.MethodPatch: req.Header.Set("Content-Type", "application/json") } req.Header.Set("Accept", "application/json") if s, ok := ctx.Value(signerContext{}).(Signer); ok { if err := s.SignRequest(req); err != nil { return err } } return c.Client.Do(ctx, req, func(res *http.Response) error { switch res.StatusCode { case http.StatusOK: case http.StatusBadRequest: // TODO: structured error types detail, err := ioutil.ReadAll(res.Body) if err != nil { return err } return fmt.Errorf("%s: %s", res.Status, bytes.TrimSpace(detail)) default: return fmt.Errorf("%s %s: %s", req.Method, req.URL, res.Status) } if resBody == nil { return nil } switch b := resBody.(type) { case io.Writer: _, err := io.Copy(b, res.Body) return err default: val := struct { Value interface{} `json:"value,omitempty"` }{ resBody, } return json.NewDecoder(res.Body).Decode(&val) } }) }
go
func (c *Client) Do(ctx context.Context, req *http.Request, resBody interface{}) error { switch req.Method { case http.MethodPost, http.MethodPatch: req.Header.Set("Content-Type", "application/json") } req.Header.Set("Accept", "application/json") if s, ok := ctx.Value(signerContext{}).(Signer); ok { if err := s.SignRequest(req); err != nil { return err } } return c.Client.Do(ctx, req, func(res *http.Response) error { switch res.StatusCode { case http.StatusOK: case http.StatusBadRequest: // TODO: structured error types detail, err := ioutil.ReadAll(res.Body) if err != nil { return err } return fmt.Errorf("%s: %s", res.Status, bytes.TrimSpace(detail)) default: return fmt.Errorf("%s %s: %s", req.Method, req.URL, res.Status) } if resBody == nil { return nil } switch b := resBody.(type) { case io.Writer: _, err := io.Copy(b, res.Body) return err default: val := struct { Value interface{} `json:"value,omitempty"` }{ resBody, } return json.NewDecoder(res.Body).Decode(&val) } }) }
[ "func", "(", "c", "*", "Client", ")", "Do", "(", "ctx", "context", ".", "Context", ",", "req", "*", "http", ".", "Request", ",", "resBody", "interface", "{", "}", ")", "error", "{", "switch", "req", ".", "Method", "{", "case", "http", ".", "MethodPost", ",", "http", ".", "MethodPatch", ":", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "s", ",", "ok", ":=", "ctx", ".", "Value", "(", "signerContext", "{", "}", ")", ".", "(", "Signer", ")", ";", "ok", "{", "if", "err", ":=", "s", ".", "SignRequest", "(", "req", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "c", ".", "Client", ".", "Do", "(", "ctx", ",", "req", ",", "func", "(", "res", "*", "http", ".", "Response", ")", "error", "{", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "case", "http", ".", "StatusBadRequest", ":", "// TODO: structured error types", "detail", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Status", ",", "bytes", ".", "TrimSpace", "(", "detail", ")", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ",", "res", ".", "Status", ")", "\n", "}", "\n\n", "if", "resBody", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "switch", "b", ":=", "resBody", ".", "(", "type", ")", "{", "case", "io", ".", "Writer", ":", "_", ",", "err", ":=", "io", ".", "Copy", "(", "b", ",", "res", ".", "Body", ")", "\n", "return", "err", "\n", "default", ":", "val", ":=", "struct", "{", "Value", "interface", "{", "}", "`json:\"value,omitempty\"`", "\n", "}", "{", "resBody", ",", "}", "\n", "return", "json", ".", "NewDecoder", "(", "res", ".", "Body", ")", ".", "Decode", "(", "&", "val", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Do sends the http.Request, decoding resBody if provided.
[ "Do", "sends", "the", "http", ".", "Request", "decoding", "resBody", "if", "provided", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L57-L102
21,601
vmware/govmomi
vapi/rest/client.go
Login
func (c *Client) Login(ctx context.Context, user *url.Userinfo) error { req := internal.URL(c, internal.SessionPath).Request(http.MethodPost) if user != nil { if password, ok := user.Password(); ok { req.SetBasicAuth(user.Username(), password) } } return c.Do(ctx, req, nil) }
go
func (c *Client) Login(ctx context.Context, user *url.Userinfo) error { req := internal.URL(c, internal.SessionPath).Request(http.MethodPost) if user != nil { if password, ok := user.Password(); ok { req.SetBasicAuth(user.Username(), password) } } return c.Do(ctx, req, nil) }
[ "func", "(", "c", "*", "Client", ")", "Login", "(", "ctx", "context", ".", "Context", ",", "user", "*", "url", ".", "Userinfo", ")", "error", "{", "req", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "SessionPath", ")", ".", "Request", "(", "http", ".", "MethodPost", ")", "\n\n", "if", "user", "!=", "nil", "{", "if", "password", ",", "ok", ":=", "user", ".", "Password", "(", ")", ";", "ok", "{", "req", ".", "SetBasicAuth", "(", "user", ".", "Username", "(", ")", ",", "password", ")", "\n", "}", "\n", "}", "\n\n", "return", "c", ".", "Do", "(", "ctx", ",", "req", ",", "nil", ")", "\n", "}" ]
// Login creates a new session via Basic Authentication with the given url.Userinfo.
[ "Login", "creates", "a", "new", "session", "via", "Basic", "Authentication", "with", "the", "given", "url", ".", "Userinfo", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L105-L115
21,602
vmware/govmomi
vapi/rest/client.go
Logout
func (c *Client) Logout(ctx context.Context) error { req := internal.URL(c, internal.SessionPath).Request(http.MethodDelete) return c.Do(ctx, req, nil) }
go
func (c *Client) Logout(ctx context.Context) error { req := internal.URL(c, internal.SessionPath).Request(http.MethodDelete) return c.Do(ctx, req, nil) }
[ "func", "(", "c", "*", "Client", ")", "Logout", "(", "ctx", "context", ".", "Context", ")", "error", "{", "req", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "SessionPath", ")", ".", "Request", "(", "http", ".", "MethodDelete", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "req", ",", "nil", ")", "\n", "}" ]
// Logout deletes the current session.
[ "Logout", "deletes", "the", "current", "session", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L122-L125
21,603
vmware/govmomi
lookup/client.go
NewClient
func NewClient(ctx context.Context, c *vim25.Client) (*Client, error) { sc := c.Client.NewServiceClient(Path, Namespace) sc.Version = Version req := types.RetrieveServiceContent{ This: ServiceInstance, } res, err := methods.RetrieveServiceContent(ctx, sc, &req) if err != nil { return nil, err } return &Client{sc, res.Returnval}, nil }
go
func NewClient(ctx context.Context, c *vim25.Client) (*Client, error) { sc := c.Client.NewServiceClient(Path, Namespace) sc.Version = Version req := types.RetrieveServiceContent{ This: ServiceInstance, } res, err := methods.RetrieveServiceContent(ctx, sc, &req) if err != nil { return nil, err } return &Client{sc, res.Returnval}, nil }
[ "func", "NewClient", "(", "ctx", "context", ".", "Context", ",", "c", "*", "vim25", ".", "Client", ")", "(", "*", "Client", ",", "error", ")", "{", "sc", ":=", "c", ".", "Client", ".", "NewServiceClient", "(", "Path", ",", "Namespace", ")", "\n", "sc", ".", "Version", "=", "Version", "\n\n", "req", ":=", "types", ".", "RetrieveServiceContent", "{", "This", ":", "ServiceInstance", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "RetrieveServiceContent", "(", "ctx", ",", "sc", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Client", "{", "sc", ",", "res", ".", "Returnval", "}", ",", "nil", "\n", "}" ]
// NewClient returns a client targeting the SSO Lookup Service API endpoint.
[ "NewClient", "returns", "a", "client", "targeting", "the", "SSO", "Lookup", "Service", "API", "endpoint", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/client.go#L54-L68
21,604
vmware/govmomi
lookup/client.go
EndpointURL
func EndpointURL(ctx context.Context, c *vim25.Client, path string, filter *types.LookupServiceRegistrationFilter) string { if lu, err := NewClient(ctx, c); err == nil { info, _ := lu.List(ctx, filter) if len(info) != 0 && len(info[0].ServiceEndpoints) != 0 { endpoint := &info[0].ServiceEndpoints[0] path = endpoint.Url if u, err := url.Parse(path); err == nil { if c.Thumbprint(u.Host) == "" { c.SetThumbprint(u.Host, endpointThumbprint(endpoint)) } } } } return path }
go
func EndpointURL(ctx context.Context, c *vim25.Client, path string, filter *types.LookupServiceRegistrationFilter) string { if lu, err := NewClient(ctx, c); err == nil { info, _ := lu.List(ctx, filter) if len(info) != 0 && len(info[0].ServiceEndpoints) != 0 { endpoint := &info[0].ServiceEndpoints[0] path = endpoint.Url if u, err := url.Parse(path); err == nil { if c.Thumbprint(u.Host) == "" { c.SetThumbprint(u.Host, endpointThumbprint(endpoint)) } } } } return path }
[ "func", "EndpointURL", "(", "ctx", "context", ".", "Context", ",", "c", "*", "vim25", ".", "Client", ",", "path", "string", ",", "filter", "*", "types", ".", "LookupServiceRegistrationFilter", ")", "string", "{", "if", "lu", ",", "err", ":=", "NewClient", "(", "ctx", ",", "c", ")", ";", "err", "==", "nil", "{", "info", ",", "_", ":=", "lu", ".", "List", "(", "ctx", ",", "filter", ")", "\n", "if", "len", "(", "info", ")", "!=", "0", "&&", "len", "(", "info", "[", "0", "]", ".", "ServiceEndpoints", ")", "!=", "0", "{", "endpoint", ":=", "&", "info", "[", "0", "]", ".", "ServiceEndpoints", "[", "0", "]", "\n", "path", "=", "endpoint", ".", "Url", "\n\n", "if", "u", ",", "err", ":=", "url", ".", "Parse", "(", "path", ")", ";", "err", "==", "nil", "{", "if", "c", ".", "Thumbprint", "(", "u", ".", "Host", ")", "==", "\"", "\"", "{", "c", ".", "SetThumbprint", "(", "u", ".", "Host", ",", "endpointThumbprint", "(", "endpoint", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "path", "\n", "}" ]
// EndpointURL uses the Lookup Service to find the endpoint URL and thumbprint for the given filter. // If the endpoint is found, its TLS certificate is also added to the vim25.Client's trusted host thumbprints. // If the Lookup Service is not available, the given path is returned as the default.
[ "EndpointURL", "uses", "the", "Lookup", "Service", "to", "find", "the", "endpoint", "URL", "and", "thumbprint", "for", "the", "given", "filter", ".", "If", "the", "endpoint", "is", "found", "its", "TLS", "certificate", "is", "also", "added", "to", "the", "vim25", ".", "Client", "s", "trusted", "host", "thumbprints", ".", "If", "the", "Lookup", "Service", "is", "not", "available", "the", "given", "path", "is", "returned", "as", "the", "default", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/client.go#L98-L113
21,605
vmware/govmomi
lookup/client.go
endpointThumbprint
func endpointThumbprint(endpoint *types.LookupServiceRegistrationEndpoint) string { if len(endpoint.SslTrust) == 0 { return "" } enc := endpoint.SslTrust[0] b, err := base64.StdEncoding.DecodeString(enc) if err != nil { log.Printf("base64.Decode(%q): %s", enc, err) return "" } cert, err := x509.ParseCertificate(b) if err != nil { log.Printf("x509.ParseCertificate(%q): %s", enc, err) return "" } return soap.ThumbprintSHA1(cert) }
go
func endpointThumbprint(endpoint *types.LookupServiceRegistrationEndpoint) string { if len(endpoint.SslTrust) == 0 { return "" } enc := endpoint.SslTrust[0] b, err := base64.StdEncoding.DecodeString(enc) if err != nil { log.Printf("base64.Decode(%q): %s", enc, err) return "" } cert, err := x509.ParseCertificate(b) if err != nil { log.Printf("x509.ParseCertificate(%q): %s", enc, err) return "" } return soap.ThumbprintSHA1(cert) }
[ "func", "endpointThumbprint", "(", "endpoint", "*", "types", ".", "LookupServiceRegistrationEndpoint", ")", "string", "{", "if", "len", "(", "endpoint", ".", "SslTrust", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "enc", ":=", "endpoint", ".", "SslTrust", "[", "0", "]", "\n\n", "b", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "enc", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "enc", ",", "err", ")", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "enc", ",", "err", ")", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "return", "soap", ".", "ThumbprintSHA1", "(", "cert", ")", "\n", "}" ]
// endpointThumbprint converts the base64 encoded endpoint certificate to a SHA1 thumbprint.
[ "endpointThumbprint", "converts", "the", "base64", "encoded", "endpoint", "certificate", "to", "a", "SHA1", "thumbprint", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/client.go#L116-L135
21,606
vmware/govmomi
ovf/manager.go
CreateDescriptor
func (m *Manager) CreateDescriptor(ctx context.Context, obj mo.Reference, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error) { req := types.CreateDescriptor{ This: m.Reference(), Obj: obj.Reference(), Cdp: cdp, } res, err := methods.CreateDescriptor(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
go
func (m *Manager) CreateDescriptor(ctx context.Context, obj mo.Reference, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error) { req := types.CreateDescriptor{ This: m.Reference(), Obj: obj.Reference(), Cdp: cdp, } res, err := methods.CreateDescriptor(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
[ "func", "(", "m", "*", "Manager", ")", "CreateDescriptor", "(", "ctx", "context", ".", "Context", ",", "obj", "mo", ".", "Reference", ",", "cdp", "types", ".", "OvfCreateDescriptorParams", ")", "(", "*", "types", ".", "OvfCreateDescriptorResult", ",", "error", ")", "{", "req", ":=", "types", ".", "CreateDescriptor", "{", "This", ":", "m", ".", "Reference", "(", ")", ",", "Obj", ":", "obj", ".", "Reference", "(", ")", ",", "Cdp", ":", "cdp", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "CreateDescriptor", "(", "ctx", ",", "m", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "res", ".", "Returnval", ",", "nil", "\n", "}" ]
// CreateDescriptor wraps methods.CreateDescriptor
[ "CreateDescriptor", "wraps", "methods", ".", "CreateDescriptor" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L39-L52
21,607
vmware/govmomi
ovf/manager.go
CreateImportSpec
func (m *Manager) CreateImportSpec(ctx context.Context, ovfDescriptor string, resourcePool mo.Reference, datastore mo.Reference, cisp types.OvfCreateImportSpecParams) (*types.OvfCreateImportSpecResult, error) { req := types.CreateImportSpec{ This: m.Reference(), OvfDescriptor: ovfDescriptor, ResourcePool: resourcePool.Reference(), Datastore: datastore.Reference(), Cisp: cisp, } res, err := methods.CreateImportSpec(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
go
func (m *Manager) CreateImportSpec(ctx context.Context, ovfDescriptor string, resourcePool mo.Reference, datastore mo.Reference, cisp types.OvfCreateImportSpecParams) (*types.OvfCreateImportSpecResult, error) { req := types.CreateImportSpec{ This: m.Reference(), OvfDescriptor: ovfDescriptor, ResourcePool: resourcePool.Reference(), Datastore: datastore.Reference(), Cisp: cisp, } res, err := methods.CreateImportSpec(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
[ "func", "(", "m", "*", "Manager", ")", "CreateImportSpec", "(", "ctx", "context", ".", "Context", ",", "ovfDescriptor", "string", ",", "resourcePool", "mo", ".", "Reference", ",", "datastore", "mo", ".", "Reference", ",", "cisp", "types", ".", "OvfCreateImportSpecParams", ")", "(", "*", "types", ".", "OvfCreateImportSpecResult", ",", "error", ")", "{", "req", ":=", "types", ".", "CreateImportSpec", "{", "This", ":", "m", ".", "Reference", "(", ")", ",", "OvfDescriptor", ":", "ovfDescriptor", ",", "ResourcePool", ":", "resourcePool", ".", "Reference", "(", ")", ",", "Datastore", ":", "datastore", ".", "Reference", "(", ")", ",", "Cisp", ":", "cisp", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "CreateImportSpec", "(", "ctx", ",", "m", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "res", ".", "Returnval", ",", "nil", "\n", "}" ]
// CreateImportSpec wraps methods.CreateImportSpec
[ "CreateImportSpec", "wraps", "methods", ".", "CreateImportSpec" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L55-L70
21,608
vmware/govmomi
ovf/manager.go
ParseDescriptor
func (m *Manager) ParseDescriptor(ctx context.Context, ovfDescriptor string, pdp types.OvfParseDescriptorParams) (*types.OvfParseDescriptorResult, error) { req := types.ParseDescriptor{ This: m.Reference(), OvfDescriptor: ovfDescriptor, Pdp: pdp, } res, err := methods.ParseDescriptor(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
go
func (m *Manager) ParseDescriptor(ctx context.Context, ovfDescriptor string, pdp types.OvfParseDescriptorParams) (*types.OvfParseDescriptorResult, error) { req := types.ParseDescriptor{ This: m.Reference(), OvfDescriptor: ovfDescriptor, Pdp: pdp, } res, err := methods.ParseDescriptor(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
[ "func", "(", "m", "*", "Manager", ")", "ParseDescriptor", "(", "ctx", "context", ".", "Context", ",", "ovfDescriptor", "string", ",", "pdp", "types", ".", "OvfParseDescriptorParams", ")", "(", "*", "types", ".", "OvfParseDescriptorResult", ",", "error", ")", "{", "req", ":=", "types", ".", "ParseDescriptor", "{", "This", ":", "m", ".", "Reference", "(", ")", ",", "OvfDescriptor", ":", "ovfDescriptor", ",", "Pdp", ":", "pdp", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "ParseDescriptor", "(", "ctx", ",", "m", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "res", ".", "Returnval", ",", "nil", "\n", "}" ]
// ParseDescriptor wraps methods.ParseDescriptor
[ "ParseDescriptor", "wraps", "methods", ".", "ParseDescriptor" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L73-L86
21,609
vmware/govmomi
ovf/manager.go
ValidateHost
func (m *Manager) ValidateHost(ctx context.Context, ovfDescriptor string, host mo.Reference, vhp types.OvfValidateHostParams) (*types.OvfValidateHostResult, error) { req := types.ValidateHost{ This: m.Reference(), OvfDescriptor: ovfDescriptor, Host: host.Reference(), Vhp: vhp, } res, err := methods.ValidateHost(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
go
func (m *Manager) ValidateHost(ctx context.Context, ovfDescriptor string, host mo.Reference, vhp types.OvfValidateHostParams) (*types.OvfValidateHostResult, error) { req := types.ValidateHost{ This: m.Reference(), OvfDescriptor: ovfDescriptor, Host: host.Reference(), Vhp: vhp, } res, err := methods.ValidateHost(ctx, m.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
[ "func", "(", "m", "*", "Manager", ")", "ValidateHost", "(", "ctx", "context", ".", "Context", ",", "ovfDescriptor", "string", ",", "host", "mo", ".", "Reference", ",", "vhp", "types", ".", "OvfValidateHostParams", ")", "(", "*", "types", ".", "OvfValidateHostResult", ",", "error", ")", "{", "req", ":=", "types", ".", "ValidateHost", "{", "This", ":", "m", ".", "Reference", "(", ")", ",", "OvfDescriptor", ":", "ovfDescriptor", ",", "Host", ":", "host", ".", "Reference", "(", ")", ",", "Vhp", ":", "vhp", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "ValidateHost", "(", "ctx", ",", "m", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "res", ".", "Returnval", ",", "nil", "\n", "}" ]
// ValidateHost wraps methods.ValidateHost
[ "ValidateHost", "wraps", "methods", ".", "ValidateHost" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L89-L103
21,610
vmware/govmomi
vapi/library/library_item.go
CreateLibraryItem
func (c *Manager) CreateLibraryItem(ctx context.Context, item Item) (string, error) { type createItemSpec struct { Name string `json:"name"` Description string `json:"description"` LibraryID string `json:"library_id,omitempty"` Type string `json:"type"` } spec := struct { Item createItemSpec `json:"create_spec"` }{ Item: createItemSpec{ Name: item.Name, Description: item.Description, LibraryID: item.LibraryID, Type: item.Type, }, } url := internal.URL(c, internal.LibraryItemPath) var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
go
func (c *Manager) CreateLibraryItem(ctx context.Context, item Item) (string, error) { type createItemSpec struct { Name string `json:"name"` Description string `json:"description"` LibraryID string `json:"library_id,omitempty"` Type string `json:"type"` } spec := struct { Item createItemSpec `json:"create_spec"` }{ Item: createItemSpec{ Name: item.Name, Description: item.Description, LibraryID: item.LibraryID, Type: item.Type, }, } url := internal.URL(c, internal.LibraryItemPath) var res string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
[ "func", "(", "c", "*", "Manager", ")", "CreateLibraryItem", "(", "ctx", "context", ".", "Context", ",", "item", "Item", ")", "(", "string", ",", "error", ")", "{", "type", "createItemSpec", "struct", "{", "Name", "string", "`json:\"name\"`", "\n", "Description", "string", "`json:\"description\"`", "\n", "LibraryID", "string", "`json:\"library_id,omitempty\"`", "\n", "Type", "string", "`json:\"type\"`", "\n", "}", "\n", "spec", ":=", "struct", "{", "Item", "createItemSpec", "`json:\"create_spec\"`", "\n", "}", "{", "Item", ":", "createItemSpec", "{", "Name", ":", "item", ".", "Name", ",", "Description", ":", "item", ".", "Description", ",", "LibraryID", ":", "item", ".", "LibraryID", ",", "Type", ":", "item", ".", "Type", ",", "}", ",", "}", "\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemPath", ")", "\n", "var", "res", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "spec", ")", ",", "&", "res", ")", "\n", "}" ]
// CreateLibraryItem creates a new library item
[ "CreateLibraryItem", "creates", "a", "new", "library", "item" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L62-L82
21,611
vmware/govmomi
vapi/library/library_item.go
DeleteLibraryItem
func (c *Manager) DeleteLibraryItem(ctx context.Context, item *Item) error { url := internal.URL(c, internal.LibraryItemPath).WithID(item.ID) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
go
func (c *Manager) DeleteLibraryItem(ctx context.Context, item *Item) error { url := internal.URL(c, internal.LibraryItemPath).WithID(item.ID) return c.Do(ctx, url.Request(http.MethodDelete), nil) }
[ "func", "(", "c", "*", "Manager", ")", "DeleteLibraryItem", "(", "ctx", "context", ".", "Context", ",", "item", "*", "Item", ")", "error", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemPath", ")", ".", "WithID", "(", "item", ".", "ID", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodDelete", ")", ",", "nil", ")", "\n", "}" ]
// DeleteLibraryItem deletes an existing library item.
[ "DeleteLibraryItem", "deletes", "an", "existing", "library", "item", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L85-L88
21,612
vmware/govmomi
vapi/library/library_item.go
ListLibraryItems
func (c *Manager) ListLibraryItems(ctx context.Context, id string) ([]string, error) { url := internal.URL(c, internal.LibraryItemPath).WithParameter("library_id", id) var res []string return res, c.Do(ctx, url.Request(http.MethodGet), &res) }
go
func (c *Manager) ListLibraryItems(ctx context.Context, id string) ([]string, error) { url := internal.URL(c, internal.LibraryItemPath).WithParameter("library_id", id) var res []string return res, c.Do(ctx, url.Request(http.MethodGet), &res) }
[ "func", "(", "c", "*", "Manager", ")", "ListLibraryItems", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemPath", ")", ".", "WithParameter", "(", "\"", "\"", ",", "id", ")", "\n", "var", "res", "[", "]", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodGet", ")", ",", "&", "res", ")", "\n", "}" ]
// ListLibraryItems returns a list of all items in a content library.
[ "ListLibraryItems", "returns", "a", "list", "of", "all", "items", "in", "a", "content", "library", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L91-L95
21,613
vmware/govmomi
vapi/library/library_item.go
GetLibraryItem
func (c *Manager) GetLibraryItem(ctx context.Context, id string) (*Item, error) { url := internal.URL(c, internal.LibraryItemPath).WithID(id) var res Item return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
go
func (c *Manager) GetLibraryItem(ctx context.Context, id string) (*Item, error) { url := internal.URL(c, internal.LibraryItemPath).WithID(id) var res Item return &res, c.Do(ctx, url.Request(http.MethodGet), &res) }
[ "func", "(", "c", "*", "Manager", ")", "GetLibraryItem", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "*", "Item", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemPath", ")", ".", "WithID", "(", "id", ")", "\n", "var", "res", "Item", "\n", "return", "&", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodGet", ")", ",", "&", "res", ")", "\n", "}" ]
// GetLibraryItem returns information on a library item for the given ID.
[ "GetLibraryItem", "returns", "information", "on", "a", "library", "item", "for", "the", "given", "ID", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L98-L102
21,614
vmware/govmomi
vapi/library/library_item.go
GetLibraryItems
func (c *Manager) GetLibraryItems(ctx context.Context, libraryID string) ([]Item, error) { ids, err := c.ListLibraryItems(ctx, libraryID) if err != nil { return nil, fmt.Errorf("get library items failed for: %s", err) } var items []Item for _, id := range ids { item, err := c.GetLibraryItem(ctx, id) if err != nil { return nil, fmt.Errorf("get library item for %s failed for %s", id, err) } items = append(items, *item) } return items, nil }
go
func (c *Manager) GetLibraryItems(ctx context.Context, libraryID string) ([]Item, error) { ids, err := c.ListLibraryItems(ctx, libraryID) if err != nil { return nil, fmt.Errorf("get library items failed for: %s", err) } var items []Item for _, id := range ids { item, err := c.GetLibraryItem(ctx, id) if err != nil { return nil, fmt.Errorf("get library item for %s failed for %s", id, err) } items = append(items, *item) } return items, nil }
[ "func", "(", "c", "*", "Manager", ")", "GetLibraryItems", "(", "ctx", "context", ".", "Context", ",", "libraryID", "string", ")", "(", "[", "]", "Item", ",", "error", ")", "{", "ids", ",", "err", ":=", "c", ".", "ListLibraryItems", "(", "ctx", ",", "libraryID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "var", "items", "[", "]", "Item", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "item", ",", "err", ":=", "c", ".", "GetLibraryItem", "(", "ctx", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "err", ")", "\n", "}", "\n", "items", "=", "append", "(", "items", ",", "*", "item", ")", "\n", "}", "\n", "return", "items", ",", "nil", "\n", "}" ]
// GetLibraryItems returns a list of all the library items for the specified library.
[ "GetLibraryItems", "returns", "a", "list", "of", "all", "the", "library", "items", "for", "the", "specified", "library", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L105-L119
21,615
vmware/govmomi
vapi/library/library_item.go
FindLibraryItems
func (c *Manager) FindLibraryItems( ctx context.Context, search FindItem) ([]string, error) { url := internal.URL(c, internal.LibraryItemPath).WithAction("find") spec := struct { Spec FindItem `json:"spec"` }{search} var res []string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
go
func (c *Manager) FindLibraryItems( ctx context.Context, search FindItem) ([]string, error) { url := internal.URL(c, internal.LibraryItemPath).WithAction("find") spec := struct { Spec FindItem `json:"spec"` }{search} var res []string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
[ "func", "(", "c", "*", "Manager", ")", "FindLibraryItems", "(", "ctx", "context", ".", "Context", ",", "search", "FindItem", ")", "(", "[", "]", "string", ",", "error", ")", "{", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "LibraryItemPath", ")", ".", "WithAction", "(", "\"", "\"", ")", "\n", "spec", ":=", "struct", "{", "Spec", "FindItem", "`json:\"spec\"`", "\n", "}", "{", "search", "}", "\n", "var", "res", "[", "]", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "spec", ")", ",", "&", "res", ")", "\n", "}" ]
// FindLibraryItems returns the IDs of all the library items that match the // search criteria.
[ "FindLibraryItems", "returns", "the", "IDs", "of", "all", "the", "library", "items", "that", "match", "the", "search", "criteria", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L132-L141
21,616
vmware/govmomi
govc/host/esxcli/firewall_info.go
GetFirewallInfo
func GetFirewallInfo(s *object.HostSystem) (*FirewallInfo, error) { x, err := NewExecutor(s.Client(), s) if err != nil { return nil, err } res, err := x.Run([]string{"network", "firewall", "get"}) if err != nil { return nil, err } info := &FirewallInfo{ Loaded: res.Values[0]["Loaded"][0] == "true", Enabled: res.Values[0]["Enabled"][0] == "true", DefaultAction: res.Values[0]["DefaultAction"][0], } return info, nil }
go
func GetFirewallInfo(s *object.HostSystem) (*FirewallInfo, error) { x, err := NewExecutor(s.Client(), s) if err != nil { return nil, err } res, err := x.Run([]string{"network", "firewall", "get"}) if err != nil { return nil, err } info := &FirewallInfo{ Loaded: res.Values[0]["Loaded"][0] == "true", Enabled: res.Values[0]["Enabled"][0] == "true", DefaultAction: res.Values[0]["DefaultAction"][0], } return info, nil }
[ "func", "GetFirewallInfo", "(", "s", "*", "object", ".", "HostSystem", ")", "(", "*", "FirewallInfo", ",", "error", ")", "{", "x", ",", "err", ":=", "NewExecutor", "(", "s", ".", "Client", "(", ")", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "x", ".", "Run", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "info", ":=", "&", "FirewallInfo", "{", "Loaded", ":", "res", ".", "Values", "[", "0", "]", "[", "\"", "\"", "]", "[", "0", "]", "==", "\"", "\"", ",", "Enabled", ":", "res", ".", "Values", "[", "0", "]", "[", "\"", "\"", "]", "[", "0", "]", "==", "\"", "\"", ",", "DefaultAction", ":", "res", ".", "Values", "[", "0", "]", "[", "\"", "\"", "]", "[", "0", "]", ",", "}", "\n\n", "return", "info", ",", "nil", "\n", "}" ]
// GetFirewallInfo via 'esxcli network firewall get' // The HostFirewallSystem type does not expose this data. // This helper can be useful in particular to determine if the firewall is enabled or disabled.
[ "GetFirewallInfo", "via", "esxcli", "network", "firewall", "get", "The", "HostFirewallSystem", "type", "does", "not", "expose", "this", "data", ".", "This", "helper", "can", "be", "useful", "in", "particular", "to", "determine", "if", "the", "firewall", "is", "enabled", "or", "disabled", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/esxcli/firewall_info.go#L30-L48
21,617
vmware/govmomi
session/keep_alive.go
KeepAlive
func KeepAlive(roundTripper soap.RoundTripper, idleTime time.Duration) soap.RoundTripper { return KeepAliveHandler(roundTripper, idleTime, defaultKeepAlive) }
go
func KeepAlive(roundTripper soap.RoundTripper, idleTime time.Duration) soap.RoundTripper { return KeepAliveHandler(roundTripper, idleTime, defaultKeepAlive) }
[ "func", "KeepAlive", "(", "roundTripper", "soap", ".", "RoundTripper", ",", "idleTime", "time", ".", "Duration", ")", "soap", ".", "RoundTripper", "{", "return", "KeepAliveHandler", "(", "roundTripper", ",", "idleTime", ",", "defaultKeepAlive", ")", "\n", "}" ]
// KeepAlive wraps the specified soap.RoundTripper and executes a meaningless // API request in the background after the RoundTripper has been idle for the // specified amount of idle time. The keep alive process only starts once a // user logs in and runs until the user logs out again.
[ "KeepAlive", "wraps", "the", "specified", "soap", ".", "RoundTripper", "and", "executes", "a", "meaningless", "API", "request", "in", "the", "background", "after", "the", "RoundTripper", "has", "been", "idle", "for", "the", "specified", "amount", "of", "idle", "time", ".", "The", "keep", "alive", "process", "only", "starts", "once", "a", "user", "logs", "in", "and", "runs", "until", "the", "user", "logs", "out", "again", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/session/keep_alive.go#L51-L53
21,618
vmware/govmomi
vapi/tags/tag_association.go
AttachTag
func (c *Manager) AttachTag(ctx context.Context, tagID string, ref mo.Reference) error { id, err := c.tagID(ctx, tagID) if err != nil { return err } spec := internal.NewAssociation(ref) url := internal.URL(c, internal.AssociationPath).WithID(id).WithAction("attach") return c.Do(ctx, url.Request(http.MethodPost, spec), nil) }
go
func (c *Manager) AttachTag(ctx context.Context, tagID string, ref mo.Reference) error { id, err := c.tagID(ctx, tagID) if err != nil { return err } spec := internal.NewAssociation(ref) url := internal.URL(c, internal.AssociationPath).WithID(id).WithAction("attach") return c.Do(ctx, url.Request(http.MethodPost, spec), nil) }
[ "func", "(", "c", "*", "Manager", ")", "AttachTag", "(", "ctx", "context", ".", "Context", ",", "tagID", "string", ",", "ref", "mo", ".", "Reference", ")", "error", "{", "id", ",", "err", ":=", "c", ".", "tagID", "(", "ctx", ",", "tagID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "spec", ":=", "internal", ".", "NewAssociation", "(", "ref", ")", "\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "AssociationPath", ")", ".", "WithID", "(", "id", ")", ".", "WithAction", "(", "\"", "\"", ")", "\n", "return", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "spec", ")", ",", "nil", ")", "\n", "}" ]
// AttachTag attaches a tag ID to a managed object.
[ "AttachTag", "attaches", "a", "tag", "ID", "to", "a", "managed", "object", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L40-L48
21,619
vmware/govmomi
vapi/tags/tag_association.go
ListAttachedTags
func (c *Manager) ListAttachedTags(ctx context.Context, ref mo.Reference) ([]string, error) { spec := internal.NewAssociation(ref) url := internal.URL(c, internal.AssociationPath).WithAction("list-attached-tags") var res []string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
go
func (c *Manager) ListAttachedTags(ctx context.Context, ref mo.Reference) ([]string, error) { spec := internal.NewAssociation(ref) url := internal.URL(c, internal.AssociationPath).WithAction("list-attached-tags") var res []string return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res) }
[ "func", "(", "c", "*", "Manager", ")", "ListAttachedTags", "(", "ctx", "context", ".", "Context", ",", "ref", "mo", ".", "Reference", ")", "(", "[", "]", "string", ",", "error", ")", "{", "spec", ":=", "internal", ".", "NewAssociation", "(", "ref", ")", "\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "AssociationPath", ")", ".", "WithAction", "(", "\"", "\"", ")", "\n", "var", "res", "[", "]", "string", "\n", "return", "res", ",", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "spec", ")", ",", "&", "res", ")", "\n", "}" ]
// ListAttachedTags fetches the array of tag IDs attached to the given object.
[ "ListAttachedTags", "fetches", "the", "array", "of", "tag", "IDs", "attached", "to", "the", "given", "object", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L63-L68
21,620
vmware/govmomi
vapi/tags/tag_association.go
GetAttachedTags
func (c *Manager) GetAttachedTags(ctx context.Context, ref mo.Reference) ([]Tag, error) { ids, err := c.ListAttachedTags(ctx, ref) if err != nil { return nil, fmt.Errorf("get attached tags %s: %s", ref, err) } var info []Tag for _, id := range ids { tag, err := c.GetTag(ctx, id) if err != nil { return nil, fmt.Errorf("get tag %s: %s", id, err) } info = append(info, *tag) } return info, nil }
go
func (c *Manager) GetAttachedTags(ctx context.Context, ref mo.Reference) ([]Tag, error) { ids, err := c.ListAttachedTags(ctx, ref) if err != nil { return nil, fmt.Errorf("get attached tags %s: %s", ref, err) } var info []Tag for _, id := range ids { tag, err := c.GetTag(ctx, id) if err != nil { return nil, fmt.Errorf("get tag %s: %s", id, err) } info = append(info, *tag) } return info, nil }
[ "func", "(", "c", "*", "Manager", ")", "GetAttachedTags", "(", "ctx", "context", ".", "Context", ",", "ref", "mo", ".", "Reference", ")", "(", "[", "]", "Tag", ",", "error", ")", "{", "ids", ",", "err", ":=", "c", ".", "ListAttachedTags", "(", "ctx", ",", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ref", ",", "err", ")", "\n", "}", "\n\n", "var", "info", "[", "]", "Tag", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "tag", ",", "err", ":=", "c", ".", "GetTag", "(", "ctx", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "err", ")", "\n", "}", "\n", "info", "=", "append", "(", "info", ",", "*", "tag", ")", "\n", "}", "\n", "return", "info", ",", "nil", "\n", "}" ]
// GetAttachedTags fetches the array of tags attached to the given object.
[ "GetAttachedTags", "fetches", "the", "array", "of", "tags", "attached", "to", "the", "given", "object", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L71-L86
21,621
vmware/govmomi
vapi/tags/tag_association.go
ListAttachedObjects
func (c *Manager) ListAttachedObjects(ctx context.Context, tagID string) ([]mo.Reference, error) { id, err := c.tagID(ctx, tagID) if err != nil { return nil, err } url := internal.URL(c, internal.AssociationPath).WithID(id).WithAction("list-attached-objects") var res []internal.AssociatedObject if err := c.Do(ctx, url.Request(http.MethodPost, nil), &res); err != nil { return nil, err } refs := make([]mo.Reference, len(res)) for i := range res { refs[i] = res[i] } return refs, nil }
go
func (c *Manager) ListAttachedObjects(ctx context.Context, tagID string) ([]mo.Reference, error) { id, err := c.tagID(ctx, tagID) if err != nil { return nil, err } url := internal.URL(c, internal.AssociationPath).WithID(id).WithAction("list-attached-objects") var res []internal.AssociatedObject if err := c.Do(ctx, url.Request(http.MethodPost, nil), &res); err != nil { return nil, err } refs := make([]mo.Reference, len(res)) for i := range res { refs[i] = res[i] } return refs, nil }
[ "func", "(", "c", "*", "Manager", ")", "ListAttachedObjects", "(", "ctx", "context", ".", "Context", ",", "tagID", "string", ")", "(", "[", "]", "mo", ".", "Reference", ",", "error", ")", "{", "id", ",", "err", ":=", "c", ".", "tagID", "(", "ctx", ",", "tagID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "url", ":=", "internal", ".", "URL", "(", "c", ",", "internal", ".", "AssociationPath", ")", ".", "WithID", "(", "id", ")", ".", "WithAction", "(", "\"", "\"", ")", "\n", "var", "res", "[", "]", "internal", ".", "AssociatedObject", "\n", "if", "err", ":=", "c", ".", "Do", "(", "ctx", ",", "url", ".", "Request", "(", "http", ".", "MethodPost", ",", "nil", ")", ",", "&", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "refs", ":=", "make", "(", "[", "]", "mo", ".", "Reference", ",", "len", "(", "res", ")", ")", "\n", "for", "i", ":=", "range", "res", "{", "refs", "[", "i", "]", "=", "res", "[", "i", "]", "\n", "}", "\n", "return", "refs", ",", "nil", "\n", "}" ]
// ListAttachedObjects fetches the array of attached objects for the given tag ID.
[ "ListAttachedObjects", "fetches", "the", "array", "of", "attached", "objects", "for", "the", "given", "tag", "ID", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L89-L105
21,622
vmware/govmomi
toolbox/channel.go
Request
func (c *ChannelOut) Request(request []byte) ([]byte, error) { if err := c.Send(request); err != nil { return nil, err } reply, err := c.Receive() if err != nil { return nil, err } if bytes.HasPrefix(reply, rpciOK) { return reply[2:], nil } return nil, fmt.Errorf("request %q: %q", request, reply) }
go
func (c *ChannelOut) Request(request []byte) ([]byte, error) { if err := c.Send(request); err != nil { return nil, err } reply, err := c.Receive() if err != nil { return nil, err } if bytes.HasPrefix(reply, rpciOK) { return reply[2:], nil } return nil, fmt.Errorf("request %q: %q", request, reply) }
[ "func", "(", "c", "*", "ChannelOut", ")", "Request", "(", "request", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "Send", "(", "request", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "reply", ",", "err", ":=", "c", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "bytes", ".", "HasPrefix", "(", "reply", ",", "rpciOK", ")", "{", "return", "reply", "[", "2", ":", "]", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "request", ",", "reply", ")", "\n", "}" ]
// Request sends an RPC command to the vmx and checks the return code for success or error
[ "Request", "sends", "an", "RPC", "command", "to", "the", "vmx", "and", "checks", "the", "return", "code", "for", "success", "or", "error" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/channel.go#L43-L58
21,623
vmware/govmomi
find/finder.go
datacenterPath
func (f *Finder) datacenterPath(ctx context.Context, ref types.ManagedObjectReference) (string, error) { mes, err := mo.Ancestors(ctx, f.client, f.client.ServiceContent.PropertyCollector, ref) if err != nil { return "", err } // Chop leaves under the Datacenter for i := len(mes) - 1; i > 0; i-- { if mes[i].Self.Type == "Datacenter" { break } mes = mes[:i] } var p string for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } p = p + "/" + me.Name } return p, nil }
go
func (f *Finder) datacenterPath(ctx context.Context, ref types.ManagedObjectReference) (string, error) { mes, err := mo.Ancestors(ctx, f.client, f.client.ServiceContent.PropertyCollector, ref) if err != nil { return "", err } // Chop leaves under the Datacenter for i := len(mes) - 1; i > 0; i-- { if mes[i].Self.Type == "Datacenter" { break } mes = mes[:i] } var p string for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } p = p + "/" + me.Name } return p, nil }
[ "func", "(", "f", "*", "Finder", ")", "datacenterPath", "(", "ctx", "context", ".", "Context", ",", "ref", "types", ".", "ManagedObjectReference", ")", "(", "string", ",", "error", ")", "{", "mes", ",", "err", ":=", "mo", ".", "Ancestors", "(", "ctx", ",", "f", ".", "client", ",", "f", ".", "client", ".", "ServiceContent", ".", "PropertyCollector", ",", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Chop leaves under the Datacenter", "for", "i", ":=", "len", "(", "mes", ")", "-", "1", ";", "i", ">", "0", ";", "i", "--", "{", "if", "mes", "[", "i", "]", ".", "Self", ".", "Type", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "mes", "=", "mes", "[", ":", "i", "]", "\n", "}", "\n\n", "var", "p", "string", "\n\n", "for", "_", ",", "me", ":=", "range", "mes", "{", "// Skip root entity in building inventory path.", "if", "me", ".", "Parent", "==", "nil", "{", "continue", "\n", "}", "\n\n", "p", "=", "p", "+", "\"", "\"", "+", "me", ".", "Name", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// datacenterPath returns the absolute path to the Datacenter containing the given ref
[ "datacenterPath", "returns", "the", "absolute", "path", "to", "the", "Datacenter", "containing", "the", "given", "ref" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L152-L178
21,624
vmware/govmomi
find/finder.go
Element
func (f *Finder) Element(ctx context.Context, ref types.ManagedObjectReference) (*list.Element, error) { rl := func(_ context.Context) (object.Reference, error) { return ref, nil } s := &spec{ Relative: rl, } e, err := f.find(ctx, "./", s) if err != nil { return nil, err } if len(e) == 0 { return nil, &NotFoundError{ref.Type, ref.Value} } if len(e) > 1 { panic("ManagedObjectReference must be unique") } return &e[0], nil }
go
func (f *Finder) Element(ctx context.Context, ref types.ManagedObjectReference) (*list.Element, error) { rl := func(_ context.Context) (object.Reference, error) { return ref, nil } s := &spec{ Relative: rl, } e, err := f.find(ctx, "./", s) if err != nil { return nil, err } if len(e) == 0 { return nil, &NotFoundError{ref.Type, ref.Value} } if len(e) > 1 { panic("ManagedObjectReference must be unique") } return &e[0], nil }
[ "func", "(", "f", "*", "Finder", ")", "Element", "(", "ctx", "context", ".", "Context", ",", "ref", "types", ".", "ManagedObjectReference", ")", "(", "*", "list", ".", "Element", ",", "error", ")", "{", "rl", ":=", "func", "(", "_", "context", ".", "Context", ")", "(", "object", ".", "Reference", ",", "error", ")", "{", "return", "ref", ",", "nil", "\n", "}", "\n\n", "s", ":=", "&", "spec", "{", "Relative", ":", "rl", ",", "}", "\n\n", "e", ",", "err", ":=", "f", ".", "find", "(", "ctx", ",", "\"", "\"", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "e", ")", "==", "0", "{", "return", "nil", ",", "&", "NotFoundError", "{", "ref", ".", "Type", ",", "ref", ".", "Value", "}", "\n", "}", "\n\n", "if", "len", "(", "e", ")", ">", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "e", "[", "0", "]", ",", "nil", "\n", "}" ]
// Element returns an Element for the given ManagedObjectReference // This method is only useful for looking up the InventoryPath of a ManagedObjectReference.
[ "Element", "returns", "an", "Element", "for", "the", "given", "ManagedObjectReference", "This", "method", "is", "only", "useful", "for", "looking", "up", "the", "InventoryPath", "of", "a", "ManagedObjectReference", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L276-L299
21,625
vmware/govmomi
find/finder.go
ObjectReference
func (f *Finder) ObjectReference(ctx context.Context, ref types.ManagedObjectReference) (object.Reference, error) { e, err := f.Element(ctx, ref) if err != nil { return nil, err } r := object.NewReference(f.client, ref) type common interface { SetInventoryPath(string) } r.(common).SetInventoryPath(e.Path) if f.dc != nil { if ds, ok := r.(*object.Datastore); ok { ds.DatacenterPath = f.dc.InventoryPath } } return r, nil }
go
func (f *Finder) ObjectReference(ctx context.Context, ref types.ManagedObjectReference) (object.Reference, error) { e, err := f.Element(ctx, ref) if err != nil { return nil, err } r := object.NewReference(f.client, ref) type common interface { SetInventoryPath(string) } r.(common).SetInventoryPath(e.Path) if f.dc != nil { if ds, ok := r.(*object.Datastore); ok { ds.DatacenterPath = f.dc.InventoryPath } } return r, nil }
[ "func", "(", "f", "*", "Finder", ")", "ObjectReference", "(", "ctx", "context", ".", "Context", ",", "ref", "types", ".", "ManagedObjectReference", ")", "(", "object", ".", "Reference", ",", "error", ")", "{", "e", ",", "err", ":=", "f", ".", "Element", "(", "ctx", ",", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "r", ":=", "object", ".", "NewReference", "(", "f", ".", "client", ",", "ref", ")", "\n\n", "type", "common", "interface", "{", "SetInventoryPath", "(", "string", ")", "\n", "}", "\n\n", "r", ".", "(", "common", ")", ".", "SetInventoryPath", "(", "e", ".", "Path", ")", "\n\n", "if", "f", ".", "dc", "!=", "nil", "{", "if", "ds", ",", "ok", ":=", "r", ".", "(", "*", "object", ".", "Datastore", ")", ";", "ok", "{", "ds", ".", "DatacenterPath", "=", "f", ".", "dc", ".", "InventoryPath", "\n", "}", "\n", "}", "\n\n", "return", "r", ",", "nil", "\n", "}" ]
// ObjectReference converts the given ManagedObjectReference to a type from the object package via object.NewReference // with the object.Common.InventoryPath field set.
[ "ObjectReference", "converts", "the", "given", "ManagedObjectReference", "to", "a", "type", "from", "the", "object", "package", "via", "object", ".", "NewReference", "with", "the", "object", ".", "Common", ".", "InventoryPath", "field", "set", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L303-L324
21,626
vmware/govmomi
find/finder.go
ResourcePoolListAll
func (f *Finder) ResourcePoolListAll(ctx context.Context, path string) ([]*object.ResourcePool, error) { pools, err := f.ResourcePoolList(ctx, path) if err != nil { if _, ok := err.(*NotFoundError); !ok { return nil, err } vapps, _ := f.VirtualAppList(ctx, path) if len(vapps) == 0 { return nil, err } for _, vapp := range vapps { pools = append(pools, vapp.ResourcePool) } } return pools, nil }
go
func (f *Finder) ResourcePoolListAll(ctx context.Context, path string) ([]*object.ResourcePool, error) { pools, err := f.ResourcePoolList(ctx, path) if err != nil { if _, ok := err.(*NotFoundError); !ok { return nil, err } vapps, _ := f.VirtualAppList(ctx, path) if len(vapps) == 0 { return nil, err } for _, vapp := range vapps { pools = append(pools, vapp.ResourcePool) } } return pools, nil }
[ "func", "(", "f", "*", "Finder", ")", "ResourcePoolListAll", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "[", "]", "*", "object", ".", "ResourcePool", ",", "error", ")", "{", "pools", ",", "err", ":=", "f", ".", "ResourcePoolList", "(", "ctx", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "NotFoundError", ")", ";", "!", "ok", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "vapps", ",", "_", ":=", "f", ".", "VirtualAppList", "(", "ctx", ",", "path", ")", "\n\n", "if", "len", "(", "vapps", ")", "==", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "vapp", ":=", "range", "vapps", "{", "pools", "=", "append", "(", "pools", ",", "vapp", ".", "ResourcePool", ")", "\n", "}", "\n", "}", "\n\n", "return", "pools", ",", "nil", "\n", "}" ]
// ResourcePoolListAll combines ResourcePoolList and VirtualAppList // VirtualAppList is only called if ResourcePoolList does not find any pools with the given path.
[ "ResourcePoolListAll", "combines", "ResourcePoolList", "and", "VirtualAppList", "VirtualAppList", "is", "only", "called", "if", "ResourcePoolList", "does", "not", "find", "any", "pools", "with", "the", "given", "path", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L881-L900
21,627
vmware/govmomi
vim25/xml/marshal.go
MarshalIndent
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { var b bytes.Buffer enc := NewEncoder(&b) enc.Indent(prefix, indent) if err := enc.Encode(v); err != nil { return nil, err } return b.Bytes(), nil }
go
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { var b bytes.Buffer enc := NewEncoder(&b) enc.Indent(prefix, indent) if err := enc.Encode(v); err != nil { return nil, err } return b.Bytes(), nil }
[ "func", "MarshalIndent", "(", "v", "interface", "{", "}", ",", "prefix", ",", "indent", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "b", "bytes", ".", "Buffer", "\n", "enc", ":=", "NewEncoder", "(", "&", "b", ")", "\n", "enc", ".", "Indent", "(", "prefix", ",", "indent", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "b", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalIndent works like Marshal, but each XML element begins on a new // indented line that starts with prefix and is followed by one or more // copies of indent according to the nesting depth.
[ "MarshalIndent", "works", "like", "Marshal", "but", "each", "XML", "element", "begins", "on", "a", "new", "indented", "line", "that", "starts", "with", "prefix", "and", "is", "followed", "by", "one", "or", "more", "copies", "of", "indent", "according", "to", "the", "nesting", "depth", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L116-L124
21,628
vmware/govmomi
vim25/xml/marshal.go
Indent
func (enc *Encoder) Indent(prefix, indent string) { enc.p.prefix = prefix enc.p.indent = indent }
go
func (enc *Encoder) Indent(prefix, indent string) { enc.p.prefix = prefix enc.p.indent = indent }
[ "func", "(", "enc", "*", "Encoder", ")", "Indent", "(", "prefix", ",", "indent", "string", ")", "{", "enc", ".", "p", ".", "prefix", "=", "prefix", "\n", "enc", ".", "p", ".", "indent", "=", "indent", "\n", "}" ]
// Indent sets the encoder to generate XML in which each element // begins on a new indented line that starts with prefix and is followed by // one or more copies of indent according to the nesting depth.
[ "Indent", "sets", "the", "encoder", "to", "generate", "XML", "in", "which", "each", "element", "begins", "on", "a", "new", "indented", "line", "that", "starts", "with", "prefix", "and", "is", "followed", "by", "one", "or", "more", "copies", "of", "indent", "according", "to", "the", "nesting", "depth", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L141-L144
21,629
vmware/govmomi
vim25/xml/marshal.go
Encode
func (enc *Encoder) Encode(v interface{}) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) if err != nil { return err } return enc.p.Flush() }
go
func (enc *Encoder) Encode(v interface{}) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) if err != nil { return err } return enc.p.Flush() }
[ "func", "(", "enc", "*", "Encoder", ")", "Encode", "(", "v", "interface", "{", "}", ")", "error", "{", "err", ":=", "enc", ".", "p", ".", "marshalValue", "(", "reflect", ".", "ValueOf", "(", "v", ")", ",", "nil", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "enc", ".", "p", ".", "Flush", "(", ")", "\n", "}" ]
// Encode writes the XML encoding of v to the stream. // // See the documentation for Marshal for details about the conversion // of Go values to XML. // // Encode calls Flush before returning.
[ "Encode", "writes", "the", "XML", "encoding", "of", "v", "to", "the", "stream", ".", "See", "the", "documentation", "for", "Marshal", "for", "details", "about", "the", "conversion", "of", "Go", "values", "to", "XML", ".", "Encode", "calls", "Flush", "before", "returning", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L152-L158
21,630
vmware/govmomi
vim25/xml/marshal.go
EncodeElement
func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) if err != nil { return err } return enc.p.Flush() }
go
func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) if err != nil { return err } return enc.p.Flush() }
[ "func", "(", "enc", "*", "Encoder", ")", "EncodeElement", "(", "v", "interface", "{", "}", ",", "start", "StartElement", ")", "error", "{", "err", ":=", "enc", ".", "p", ".", "marshalValue", "(", "reflect", ".", "ValueOf", "(", "v", ")", ",", "nil", ",", "&", "start", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "enc", ".", "p", ".", "Flush", "(", ")", "\n", "}" ]
// EncodeElement writes the XML encoding of v to the stream, // using start as the outermost tag in the encoding. // // See the documentation for Marshal for details about the conversion // of Go values to XML. // // EncodeElement calls Flush before returning.
[ "EncodeElement", "writes", "the", "XML", "encoding", "of", "v", "to", "the", "stream", "using", "start", "as", "the", "outermost", "tag", "in", "the", "encoding", ".", "See", "the", "documentation", "for", "Marshal", "for", "details", "about", "the", "conversion", "of", "Go", "values", "to", "XML", ".", "EncodeElement", "calls", "Flush", "before", "returning", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L167-L173
21,631
vmware/govmomi
vim25/xml/marshal.go
deleteAttrPrefix
func (p *printer) deleteAttrPrefix(prefix string) { delete(p.attrPrefix, p.attrNS[prefix]) delete(p.attrNS, prefix) }
go
func (p *printer) deleteAttrPrefix(prefix string) { delete(p.attrPrefix, p.attrNS[prefix]) delete(p.attrNS, prefix) }
[ "func", "(", "p", "*", "printer", ")", "deleteAttrPrefix", "(", "prefix", "string", ")", "{", "delete", "(", "p", ".", "attrPrefix", ",", "p", ".", "attrNS", "[", "prefix", "]", ")", "\n", "delete", "(", "p", ".", "attrNS", ",", "prefix", ")", "\n", "}" ]
// deleteAttrPrefix removes an attribute name space prefix.
[ "deleteAttrPrefix", "removes", "an", "attribute", "name", "space", "prefix", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L324-L327
21,632
vmware/govmomi
vim25/xml/marshal.go
defaultStart
func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement { var start StartElement // Precedence for the XML element name is as above, // except that we do not look inside structs for the first field. if startTemplate != nil { start.Name = startTemplate.Name start.Attr = append(start.Attr, startTemplate.Attr...) } else if finfo != nil && finfo.name != "" { start.Name.Local = finfo.name start.Name.Space = finfo.xmlns } else if typ.Name() != "" { start.Name.Local = typ.Name() } else { // Must be a pointer to a named type, // since it has the Marshaler methods. start.Name.Local = typ.Elem().Name() } // Add type attribute if necessary if finfo != nil && finfo.flags&fTypeAttr != 0 { start.Attr = append(start.Attr, Attr{xmlSchemaInstance, typeToString(typ)}) } return start }
go
func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement { var start StartElement // Precedence for the XML element name is as above, // except that we do not look inside structs for the first field. if startTemplate != nil { start.Name = startTemplate.Name start.Attr = append(start.Attr, startTemplate.Attr...) } else if finfo != nil && finfo.name != "" { start.Name.Local = finfo.name start.Name.Space = finfo.xmlns } else if typ.Name() != "" { start.Name.Local = typ.Name() } else { // Must be a pointer to a named type, // since it has the Marshaler methods. start.Name.Local = typ.Elem().Name() } // Add type attribute if necessary if finfo != nil && finfo.flags&fTypeAttr != 0 { start.Attr = append(start.Attr, Attr{xmlSchemaInstance, typeToString(typ)}) } return start }
[ "func", "defaultStart", "(", "typ", "reflect", ".", "Type", ",", "finfo", "*", "fieldInfo", ",", "startTemplate", "*", "StartElement", ")", "StartElement", "{", "var", "start", "StartElement", "\n", "// Precedence for the XML element name is as above,", "// except that we do not look inside structs for the first field.", "if", "startTemplate", "!=", "nil", "{", "start", ".", "Name", "=", "startTemplate", ".", "Name", "\n", "start", ".", "Attr", "=", "append", "(", "start", ".", "Attr", ",", "startTemplate", ".", "Attr", "...", ")", "\n", "}", "else", "if", "finfo", "!=", "nil", "&&", "finfo", ".", "name", "!=", "\"", "\"", "{", "start", ".", "Name", ".", "Local", "=", "finfo", ".", "name", "\n", "start", ".", "Name", ".", "Space", "=", "finfo", ".", "xmlns", "\n", "}", "else", "if", "typ", ".", "Name", "(", ")", "!=", "\"", "\"", "{", "start", ".", "Name", ".", "Local", "=", "typ", ".", "Name", "(", ")", "\n", "}", "else", "{", "// Must be a pointer to a named type,", "// since it has the Marshaler methods.", "start", ".", "Name", ".", "Local", "=", "typ", ".", "Elem", "(", ")", ".", "Name", "(", ")", "\n", "}", "\n\n", "// Add type attribute if necessary", "if", "finfo", "!=", "nil", "&&", "finfo", ".", "flags", "&", "fTypeAttr", "!=", "0", "{", "start", ".", "Attr", "=", "append", "(", "start", ".", "Attr", ",", "Attr", "{", "xmlSchemaInstance", ",", "typeToString", "(", "typ", ")", "}", ")", "\n", "}", "\n\n", "return", "start", "\n", "}" ]
// defaultStart returns the default start element to use, // given the reflect type, field info, and start template.
[ "defaultStart", "returns", "the", "default", "start", "element", "to", "use", "given", "the", "reflect", "type", "field", "info", "and", "start", "template", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L560-L584
21,633
vmware/govmomi
vim25/xml/marshal.go
marshalInterface
func (p *printer) marshalInterface(val Marshaler, start StartElement) error { // Push a marker onto the tag stack so that MarshalXML // cannot close the XML tags that it did not open. p.tags = append(p.tags, Name{}) n := len(p.tags) err := val.MarshalXML(p.encoder, start) if err != nil { return err } // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark. if len(p.tags) > n { return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local) } p.tags = p.tags[:n-1] return nil }
go
func (p *printer) marshalInterface(val Marshaler, start StartElement) error { // Push a marker onto the tag stack so that MarshalXML // cannot close the XML tags that it did not open. p.tags = append(p.tags, Name{}) n := len(p.tags) err := val.MarshalXML(p.encoder, start) if err != nil { return err } // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark. if len(p.tags) > n { return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local) } p.tags = p.tags[:n-1] return nil }
[ "func", "(", "p", "*", "printer", ")", "marshalInterface", "(", "val", "Marshaler", ",", "start", "StartElement", ")", "error", "{", "// Push a marker onto the tag stack so that MarshalXML", "// cannot close the XML tags that it did not open.", "p", ".", "tags", "=", "append", "(", "p", ".", "tags", ",", "Name", "{", "}", ")", "\n", "n", ":=", "len", "(", "p", ".", "tags", ")", "\n\n", "err", ":=", "val", ".", "MarshalXML", "(", "p", ".", "encoder", ",", "start", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.", "if", "len", "(", "p", ".", "tags", ")", ">", "n", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "receiverType", "(", "val", ")", ",", "p", ".", "tags", "[", "len", "(", "p", ".", "tags", ")", "-", "1", "]", ".", "Local", ")", "\n", "}", "\n", "p", ".", "tags", "=", "p", ".", "tags", "[", ":", "n", "-", "1", "]", "\n", "return", "nil", "\n", "}" ]
// marshalInterface marshals a Marshaler interface value.
[ "marshalInterface", "marshals", "a", "Marshaler", "interface", "value", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L587-L604
21,634
vmware/govmomi
vim25/xml/marshal.go
marshalTextInterface
func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error { if err := p.writeStart(&start); err != nil { return err } text, err := val.MarshalText() if err != nil { return err } EscapeText(p, text) return p.writeEnd(start.Name) }
go
func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error { if err := p.writeStart(&start); err != nil { return err } text, err := val.MarshalText() if err != nil { return err } EscapeText(p, text) return p.writeEnd(start.Name) }
[ "func", "(", "p", "*", "printer", ")", "marshalTextInterface", "(", "val", "encoding", ".", "TextMarshaler", ",", "start", "StartElement", ")", "error", "{", "if", "err", ":=", "p", ".", "writeStart", "(", "&", "start", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "text", ",", "err", ":=", "val", ".", "MarshalText", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "EscapeText", "(", "p", ",", "text", ")", "\n", "return", "p", ".", "writeEnd", "(", "start", ".", "Name", ")", "\n", "}" ]
// marshalTextInterface marshals a TextMarshaler interface value.
[ "marshalTextInterface", "marshals", "a", "TextMarshaler", "interface", "value", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L607-L617
21,635
vmware/govmomi
vim25/xml/marshal.go
writeStart
func (p *printer) writeStart(start *StartElement) error { if start.Name.Local == "" { return fmt.Errorf("xml: start tag with no name") } p.tags = append(p.tags, start.Name) p.markPrefix() p.writeIndent(1) p.WriteByte('<') p.WriteString(start.Name.Local) if start.Name.Space != "" { p.WriteString(` xmlns="`) p.EscapeString(start.Name.Space) p.WriteByte('"') } // Attributes for _, attr := range start.Attr { name := attr.Name if name.Local == "" { continue } p.WriteByte(' ') if name.Space != "" { p.WriteString(p.createAttrPrefix(name.Space)) p.WriteByte(':') } p.WriteString(name.Local) p.WriteString(`="`) p.EscapeString(attr.Value) p.WriteByte('"') } p.WriteByte('>') return nil }
go
func (p *printer) writeStart(start *StartElement) error { if start.Name.Local == "" { return fmt.Errorf("xml: start tag with no name") } p.tags = append(p.tags, start.Name) p.markPrefix() p.writeIndent(1) p.WriteByte('<') p.WriteString(start.Name.Local) if start.Name.Space != "" { p.WriteString(` xmlns="`) p.EscapeString(start.Name.Space) p.WriteByte('"') } // Attributes for _, attr := range start.Attr { name := attr.Name if name.Local == "" { continue } p.WriteByte(' ') if name.Space != "" { p.WriteString(p.createAttrPrefix(name.Space)) p.WriteByte(':') } p.WriteString(name.Local) p.WriteString(`="`) p.EscapeString(attr.Value) p.WriteByte('"') } p.WriteByte('>') return nil }
[ "func", "(", "p", "*", "printer", ")", "writeStart", "(", "start", "*", "StartElement", ")", "error", "{", "if", "start", ".", "Name", ".", "Local", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ".", "tags", "=", "append", "(", "p", ".", "tags", ",", "start", ".", "Name", ")", "\n", "p", ".", "markPrefix", "(", ")", "\n\n", "p", ".", "writeIndent", "(", "1", ")", "\n", "p", ".", "WriteByte", "(", "'<'", ")", "\n", "p", ".", "WriteString", "(", "start", ".", "Name", ".", "Local", ")", "\n\n", "if", "start", ".", "Name", ".", "Space", "!=", "\"", "\"", "{", "p", ".", "WriteString", "(", "` xmlns=\"`", ")", "\n", "p", ".", "EscapeString", "(", "start", ".", "Name", ".", "Space", ")", "\n", "p", ".", "WriteByte", "(", "'\"'", ")", "\n", "}", "\n\n", "// Attributes", "for", "_", ",", "attr", ":=", "range", "start", ".", "Attr", "{", "name", ":=", "attr", ".", "Name", "\n", "if", "name", ".", "Local", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "p", ".", "WriteByte", "(", "' '", ")", "\n", "if", "name", ".", "Space", "!=", "\"", "\"", "{", "p", ".", "WriteString", "(", "p", ".", "createAttrPrefix", "(", "name", ".", "Space", ")", ")", "\n", "p", ".", "WriteByte", "(", "':'", ")", "\n", "}", "\n", "p", ".", "WriteString", "(", "name", ".", "Local", ")", "\n", "p", ".", "WriteString", "(", "`=\"`", ")", "\n", "p", ".", "EscapeString", "(", "attr", ".", "Value", ")", "\n", "p", ".", "WriteByte", "(", "'\"'", ")", "\n", "}", "\n", "p", ".", "WriteByte", "(", "'>'", ")", "\n", "return", "nil", "\n", "}" ]
// writeStart writes the given start element.
[ "writeStart", "writes", "the", "given", "start", "element", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L620-L656
21,636
vmware/govmomi
vim25/xml/marshal.go
cachedWriteError
func (p *printer) cachedWriteError() error { _, err := p.Write(nil) return err }
go
func (p *printer) cachedWriteError() error { _, err := p.Write(nil) return err }
[ "func", "(", "p", "*", "printer", ")", "cachedWriteError", "(", ")", "error", "{", "_", ",", "err", ":=", "p", ".", "Write", "(", "nil", ")", "\n", "return", "err", "\n", "}" ]
// return the bufio Writer's cached write error
[ "return", "the", "bufio", "Writer", "s", "cached", "write", "error" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L852-L855
21,637
vmware/govmomi
vim25/xml/marshal.go
trim
func (s *parentStack) trim(parents []string) error { split := 0 for ; split < len(parents) && split < len(s.stack); split++ { if parents[split] != s.stack[split] { break } } for i := len(s.stack) - 1; i >= split; i-- { if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil { return err } } s.stack = parents[:split] return nil }
go
func (s *parentStack) trim(parents []string) error { split := 0 for ; split < len(parents) && split < len(s.stack); split++ { if parents[split] != s.stack[split] { break } } for i := len(s.stack) - 1; i >= split; i-- { if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil { return err } } s.stack = parents[:split] return nil }
[ "func", "(", "s", "*", "parentStack", ")", "trim", "(", "parents", "[", "]", "string", ")", "error", "{", "split", ":=", "0", "\n", "for", ";", "split", "<", "len", "(", "parents", ")", "&&", "split", "<", "len", "(", "s", ".", "stack", ")", ";", "split", "++", "{", "if", "parents", "[", "split", "]", "!=", "s", ".", "stack", "[", "split", "]", "{", "break", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "len", "(", "s", ".", "stack", ")", "-", "1", ";", "i", ">=", "split", ";", "i", "--", "{", "if", "err", ":=", "s", ".", "p", ".", "writeEnd", "(", "Name", "{", "Local", ":", "s", ".", "stack", "[", "i", "]", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "s", ".", "stack", "=", "parents", "[", ":", "split", "]", "\n", "return", "nil", "\n", "}" ]
// trim updates the XML context to match the longest common prefix of the stack // and the given parents. A closing tag will be written for every parent // popped. Passing a zero slice or nil will close all the elements.
[ "trim", "updates", "the", "XML", "context", "to", "match", "the", "longest", "common", "prefix", "of", "the", "stack", "and", "the", "given", "parents", ".", "A", "closing", "tag", "will", "be", "written", "for", "every", "parent", "popped", ".", "Passing", "a", "zero", "slice", "or", "nil", "will", "close", "all", "the", "elements", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L896-L910
21,638
vmware/govmomi
vim25/xml/marshal.go
push
func (s *parentStack) push(parents []string) error { for i := 0; i < len(parents); i++ { if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil { return err } } s.stack = append(s.stack, parents...) return nil }
go
func (s *parentStack) push(parents []string) error { for i := 0; i < len(parents); i++ { if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil { return err } } s.stack = append(s.stack, parents...) return nil }
[ "func", "(", "s", "*", "parentStack", ")", "push", "(", "parents", "[", "]", "string", ")", "error", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "parents", ")", ";", "i", "++", "{", "if", "err", ":=", "s", ".", "p", ".", "writeStart", "(", "&", "StartElement", "{", "Name", ":", "Name", "{", "Local", ":", "parents", "[", "i", "]", "}", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "s", ".", "stack", "=", "append", "(", "s", ".", "stack", ",", "parents", "...", ")", "\n", "return", "nil", "\n", "}" ]
// push adds parent elements to the stack and writes open tags.
[ "push", "adds", "parent", "elements", "to", "the", "stack", "and", "writes", "open", "tags", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L913-L921
21,639
vmware/govmomi
govc/object/find.go
rootMatch
func (cmd *find) rootMatch(ctx context.Context, root object.Reference, client *vim25.Client, filter property.Filter) bool { ref := root.Reference() if !cmd.kind.wanted(ref.Type) { return false } if len(filter) == 1 && filter["name"] == "*" { return true } var content []types.ObjectContent pc := property.DefaultCollector(client) _ = pc.RetrieveWithFilter(ctx, []types.ManagedObjectReference{ref}, filter.Keys(), &content, filter) return content != nil }
go
func (cmd *find) rootMatch(ctx context.Context, root object.Reference, client *vim25.Client, filter property.Filter) bool { ref := root.Reference() if !cmd.kind.wanted(ref.Type) { return false } if len(filter) == 1 && filter["name"] == "*" { return true } var content []types.ObjectContent pc := property.DefaultCollector(client) _ = pc.RetrieveWithFilter(ctx, []types.ManagedObjectReference{ref}, filter.Keys(), &content, filter) return content != nil }
[ "func", "(", "cmd", "*", "find", ")", "rootMatch", "(", "ctx", "context", ".", "Context", ",", "root", "object", ".", "Reference", ",", "client", "*", "vim25", ".", "Client", ",", "filter", "property", ".", "Filter", ")", "bool", "{", "ref", ":=", "root", ".", "Reference", "(", ")", "\n\n", "if", "!", "cmd", ".", "kind", ".", "wanted", "(", "ref", ".", "Type", ")", "{", "return", "false", "\n", "}", "\n\n", "if", "len", "(", "filter", ")", "==", "1", "&&", "filter", "[", "\"", "\"", "]", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n\n", "var", "content", "[", "]", "types", ".", "ObjectContent", "\n\n", "pc", ":=", "property", ".", "DefaultCollector", "(", "client", ")", "\n", "_", "=", "pc", ".", "RetrieveWithFilter", "(", "ctx", ",", "[", "]", "types", ".", "ManagedObjectReference", "{", "ref", "}", ",", "filter", ".", "Keys", "(", ")", ",", "&", "content", ",", "filter", ")", "\n\n", "return", "content", "!=", "nil", "\n", "}" ]
// rootMatch returns true if the root object path should be printed
[ "rootMatch", "returns", "true", "if", "the", "root", "object", "path", "should", "be", "printed" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/object/find.go#L157-L174
21,640
vmware/govmomi
vslm/object_manager.go
NewObjectManager
func NewObjectManager(client *vim25.Client, ref ...types.ManagedObjectReference) *ObjectManager { mref := *client.ServiceContent.VStorageObjectManager if len(ref) == 1 { mref = ref[0] } m := ObjectManager{ ManagedObjectReference: mref, c: client, isVC: mref.Type == "VcenterVStorageObjectManager", } return &m }
go
func NewObjectManager(client *vim25.Client, ref ...types.ManagedObjectReference) *ObjectManager { mref := *client.ServiceContent.VStorageObjectManager if len(ref) == 1 { mref = ref[0] } m := ObjectManager{ ManagedObjectReference: mref, c: client, isVC: mref.Type == "VcenterVStorageObjectManager", } return &m }
[ "func", "NewObjectManager", "(", "client", "*", "vim25", ".", "Client", ",", "ref", "...", "types", ".", "ManagedObjectReference", ")", "*", "ObjectManager", "{", "mref", ":=", "*", "client", ".", "ServiceContent", ".", "VStorageObjectManager", "\n\n", "if", "len", "(", "ref", ")", "==", "1", "{", "mref", "=", "ref", "[", "0", "]", "\n", "}", "\n\n", "m", ":=", "ObjectManager", "{", "ManagedObjectReference", ":", "mref", ",", "c", ":", "client", ",", "isVC", ":", "mref", ".", "Type", "==", "\"", "\"", ",", "}", "\n\n", "return", "&", "m", "\n", "}" ]
// NewObjectManager returns an ObjectManager referencing the VcenterVStorageObjectManager singleton when connected to vCenter or // the HostVStorageObjectManager singleton when connected to an ESX host. The optional ref param can be used to specify a ESX // host instead, when connected to vCenter.
[ "NewObjectManager", "returns", "an", "ObjectManager", "referencing", "the", "VcenterVStorageObjectManager", "singleton", "when", "connected", "to", "vCenter", "or", "the", "HostVStorageObjectManager", "singleton", "when", "connected", "to", "an", "ESX", "host", ".", "The", "optional", "ref", "param", "can", "be", "used", "to", "specify", "a", "ESX", "host", "instead", "when", "connected", "to", "vCenter", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vslm/object_manager.go#L40-L54
21,641
vmware/govmomi
vslm/object_manager.go
PlaceDisk
func (m ObjectManager) PlaceDisk(ctx context.Context, spec *types.VslmCreateSpec, pool types.ManagedObjectReference) error { backing := spec.BackingSpec.GetVslmCreateSpecBackingSpec() if backing.Datastore.Type != "StoragePod" { return nil } device := &types.VirtualDisk{ VirtualDevice: types.VirtualDevice{ Key: 0, Backing: &types.VirtualDiskFlatVer2BackingInfo{ DiskMode: string(types.VirtualDiskModePersistent), ThinProvisioned: types.NewBool(true), }, UnitNumber: types.NewInt32(0), }, CapacityInKB: spec.CapacityInMB * 1024, } storage := types.StoragePlacementSpec{ Type: string(types.StoragePlacementSpecPlacementTypeCreate), ResourcePool: &pool, PodSelectionSpec: types.StorageDrsPodSelectionSpec{ StoragePod: &backing.Datastore, InitialVmConfig: []types.VmPodConfigForPlacement{ { StoragePod: backing.Datastore, Disk: []types.PodDiskLocator{ { DiskId: device.Key, DiskBackingInfo: device.Backing, }, }, }, }, }, ConfigSpec: &types.VirtualMachineConfigSpec{ Name: spec.Name, DeviceChange: []types.BaseVirtualDeviceConfigSpec{ &types.VirtualDeviceConfigSpec{ Operation: types.VirtualDeviceConfigSpecOperationAdd, FileOperation: types.VirtualDeviceConfigSpecFileOperationCreate, Device: device, }, }, }, } req := types.RecommendDatastores{ This: *m.c.ServiceContent.StorageResourceManager, StorageSpec: storage, } res, err := methods.RecommendDatastores(ctx, m.c, &req) if err != nil { return err } r := res.Returnval.Recommendations if len(r) == 0 { return errors.New("no storage placement recommendations") } backing.Datastore = r[0].Action[0].(*types.StoragePlacementAction).Destination return nil }
go
func (m ObjectManager) PlaceDisk(ctx context.Context, spec *types.VslmCreateSpec, pool types.ManagedObjectReference) error { backing := spec.BackingSpec.GetVslmCreateSpecBackingSpec() if backing.Datastore.Type != "StoragePod" { return nil } device := &types.VirtualDisk{ VirtualDevice: types.VirtualDevice{ Key: 0, Backing: &types.VirtualDiskFlatVer2BackingInfo{ DiskMode: string(types.VirtualDiskModePersistent), ThinProvisioned: types.NewBool(true), }, UnitNumber: types.NewInt32(0), }, CapacityInKB: spec.CapacityInMB * 1024, } storage := types.StoragePlacementSpec{ Type: string(types.StoragePlacementSpecPlacementTypeCreate), ResourcePool: &pool, PodSelectionSpec: types.StorageDrsPodSelectionSpec{ StoragePod: &backing.Datastore, InitialVmConfig: []types.VmPodConfigForPlacement{ { StoragePod: backing.Datastore, Disk: []types.PodDiskLocator{ { DiskId: device.Key, DiskBackingInfo: device.Backing, }, }, }, }, }, ConfigSpec: &types.VirtualMachineConfigSpec{ Name: spec.Name, DeviceChange: []types.BaseVirtualDeviceConfigSpec{ &types.VirtualDeviceConfigSpec{ Operation: types.VirtualDeviceConfigSpecOperationAdd, FileOperation: types.VirtualDeviceConfigSpecFileOperationCreate, Device: device, }, }, }, } req := types.RecommendDatastores{ This: *m.c.ServiceContent.StorageResourceManager, StorageSpec: storage, } res, err := methods.RecommendDatastores(ctx, m.c, &req) if err != nil { return err } r := res.Returnval.Recommendations if len(r) == 0 { return errors.New("no storage placement recommendations") } backing.Datastore = r[0].Action[0].(*types.StoragePlacementAction).Destination return nil }
[ "func", "(", "m", "ObjectManager", ")", "PlaceDisk", "(", "ctx", "context", ".", "Context", ",", "spec", "*", "types", ".", "VslmCreateSpec", ",", "pool", "types", ".", "ManagedObjectReference", ")", "error", "{", "backing", ":=", "spec", ".", "BackingSpec", ".", "GetVslmCreateSpecBackingSpec", "(", ")", "\n", "if", "backing", ".", "Datastore", ".", "Type", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "device", ":=", "&", "types", ".", "VirtualDisk", "{", "VirtualDevice", ":", "types", ".", "VirtualDevice", "{", "Key", ":", "0", ",", "Backing", ":", "&", "types", ".", "VirtualDiskFlatVer2BackingInfo", "{", "DiskMode", ":", "string", "(", "types", ".", "VirtualDiskModePersistent", ")", ",", "ThinProvisioned", ":", "types", ".", "NewBool", "(", "true", ")", ",", "}", ",", "UnitNumber", ":", "types", ".", "NewInt32", "(", "0", ")", ",", "}", ",", "CapacityInKB", ":", "spec", ".", "CapacityInMB", "*", "1024", ",", "}", "\n\n", "storage", ":=", "types", ".", "StoragePlacementSpec", "{", "Type", ":", "string", "(", "types", ".", "StoragePlacementSpecPlacementTypeCreate", ")", ",", "ResourcePool", ":", "&", "pool", ",", "PodSelectionSpec", ":", "types", ".", "StorageDrsPodSelectionSpec", "{", "StoragePod", ":", "&", "backing", ".", "Datastore", ",", "InitialVmConfig", ":", "[", "]", "types", ".", "VmPodConfigForPlacement", "{", "{", "StoragePod", ":", "backing", ".", "Datastore", ",", "Disk", ":", "[", "]", "types", ".", "PodDiskLocator", "{", "{", "DiskId", ":", "device", ".", "Key", ",", "DiskBackingInfo", ":", "device", ".", "Backing", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "ConfigSpec", ":", "&", "types", ".", "VirtualMachineConfigSpec", "{", "Name", ":", "spec", ".", "Name", ",", "DeviceChange", ":", "[", "]", "types", ".", "BaseVirtualDeviceConfigSpec", "{", "&", "types", ".", "VirtualDeviceConfigSpec", "{", "Operation", ":", "types", ".", "VirtualDeviceConfigSpecOperationAdd", ",", "FileOperation", ":", "types", ".", "VirtualDeviceConfigSpecFileOperationCreate", ",", "Device", ":", "device", ",", "}", ",", "}", ",", "}", ",", "}", "\n\n", "req", ":=", "types", ".", "RecommendDatastores", "{", "This", ":", "*", "m", ".", "c", ".", "ServiceContent", ".", "StorageResourceManager", ",", "StorageSpec", ":", "storage", ",", "}", "\n\n", "res", ",", "err", ":=", "methods", ".", "RecommendDatastores", "(", "ctx", ",", "m", ".", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "r", ":=", "res", ".", "Returnval", ".", "Recommendations", "\n", "if", "len", "(", "r", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "backing", ".", "Datastore", "=", "r", "[", "0", "]", ".", "Action", "[", "0", "]", ".", "(", "*", "types", ".", "StoragePlacementAction", ")", ".", "Destination", "\n\n", "return", "nil", "\n", "}" ]
// PlaceDisk uses StorageResourceManager datastore placement recommendations to choose a Datastore from a Datastore cluster. // If the given spec backing Datastore field is not that of type StoragePod, the spec is unmodifed. // Otherwise, the backing Datastore field is replaced with a Datastore suggestion.
[ "PlaceDisk", "uses", "StorageResourceManager", "datastore", "placement", "recommendations", "to", "choose", "a", "Datastore", "from", "a", "Datastore", "cluster", ".", "If", "the", "given", "spec", "backing", "Datastore", "field", "is", "not", "that", "of", "type", "StoragePod", "the", "spec", "is", "unmodifed", ".", "Otherwise", "the", "backing", "Datastore", "field", "is", "replaced", "with", "a", "Datastore", "suggestion", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vslm/object_manager.go#L59-L124
21,642
vmware/govmomi
simulator/registry.go
NewRegistry
func NewRegistry() *Registry { r := &Registry{ objects: make(map[types.ManagedObjectReference]mo.Reference), handlers: make(map[types.ManagedObjectReference]RegisterObject), locks: make(map[types.ManagedObjectReference]sync.Locker), Namespace: vim25.Namespace, Path: vim25.Path, } return r }
go
func NewRegistry() *Registry { r := &Registry{ objects: make(map[types.ManagedObjectReference]mo.Reference), handlers: make(map[types.ManagedObjectReference]RegisterObject), locks: make(map[types.ManagedObjectReference]sync.Locker), Namespace: vim25.Namespace, Path: vim25.Path, } return r }
[ "func", "NewRegistry", "(", ")", "*", "Registry", "{", "r", ":=", "&", "Registry", "{", "objects", ":", "make", "(", "map", "[", "types", ".", "ManagedObjectReference", "]", "mo", ".", "Reference", ")", ",", "handlers", ":", "make", "(", "map", "[", "types", ".", "ManagedObjectReference", "]", "RegisterObject", ")", ",", "locks", ":", "make", "(", "map", "[", "types", ".", "ManagedObjectReference", "]", "sync", ".", "Locker", ")", ",", "Namespace", ":", "vim25", ".", "Namespace", ",", "Path", ":", "vim25", ".", "Path", ",", "}", "\n\n", "return", "r", "\n", "}" ]
// NewRegistry creates a new instances of Registry
[ "NewRegistry", "creates", "a", "new", "instances", "of", "Registry" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L81-L92
21,643
vmware/govmomi
simulator/registry.go
typeName
func typeName(item mo.Reference) string { return reflect.TypeOf(item).Elem().Name() }
go
func typeName(item mo.Reference) string { return reflect.TypeOf(item).Elem().Name() }
[ "func", "typeName", "(", "item", "mo", ".", "Reference", ")", "string", "{", "return", "reflect", ".", "TypeOf", "(", "item", ")", ".", "Elem", "(", ")", ".", "Name", "(", ")", "\n", "}" ]
// typeName returns the type of the given object.
[ "typeName", "returns", "the", "type", "of", "the", "given", "object", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L104-L106
21,644
vmware/govmomi
simulator/registry.go
valuePrefix
func valuePrefix(typeName string) string { if v, ok := refValueMap[typeName]; ok { return v } return strings.ToLower(typeName) }
go
func valuePrefix(typeName string) string { if v, ok := refValueMap[typeName]; ok { return v } return strings.ToLower(typeName) }
[ "func", "valuePrefix", "(", "typeName", "string", ")", "string", "{", "if", "v", ",", "ok", ":=", "refValueMap", "[", "typeName", "]", ";", "ok", "{", "return", "v", "\n", "}", "\n\n", "return", "strings", ".", "ToLower", "(", "typeName", ")", "\n", "}" ]
// valuePrefix returns the value name prefix of a given object
[ "valuePrefix", "returns", "the", "value", "name", "prefix", "of", "a", "given", "object" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L109-L115
21,645
vmware/govmomi
simulator/registry.go
newReference
func (r *Registry) newReference(item mo.Reference) types.ManagedObjectReference { ref := item.Reference() if ref.Type == "" { ref.Type = typeName(item) } if ref.Value == "" { n := atomic.AddInt64(&r.counter, 1) ref.Value = fmt.Sprintf("%s-%d", valuePrefix(ref.Type), n) } return ref }
go
func (r *Registry) newReference(item mo.Reference) types.ManagedObjectReference { ref := item.Reference() if ref.Type == "" { ref.Type = typeName(item) } if ref.Value == "" { n := atomic.AddInt64(&r.counter, 1) ref.Value = fmt.Sprintf("%s-%d", valuePrefix(ref.Type), n) } return ref }
[ "func", "(", "r", "*", "Registry", ")", "newReference", "(", "item", "mo", ".", "Reference", ")", "types", ".", "ManagedObjectReference", "{", "ref", ":=", "item", ".", "Reference", "(", ")", "\n\n", "if", "ref", ".", "Type", "==", "\"", "\"", "{", "ref", ".", "Type", "=", "typeName", "(", "item", ")", "\n", "}", "\n\n", "if", "ref", ".", "Value", "==", "\"", "\"", "{", "n", ":=", "atomic", ".", "AddInt64", "(", "&", "r", ".", "counter", ",", "1", ")", "\n", "ref", ".", "Value", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "valuePrefix", "(", "ref", ".", "Type", ")", ",", "n", ")", "\n", "}", "\n\n", "return", "ref", "\n", "}" ]
// newReference returns a new MOR, where Type defaults to type of the given item // and Value defaults to a unique id for the given type.
[ "newReference", "returns", "a", "new", "MOR", "where", "Type", "defaults", "to", "type", "of", "the", "given", "item", "and", "Value", "defaults", "to", "a", "unique", "id", "for", "the", "given", "type", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L119-L132
21,646
vmware/govmomi
simulator/registry.go
AddHandler
func (r *Registry) AddHandler(h RegisterObject) { r.m.Lock() r.handlers[h.Reference()] = h r.m.Unlock() }
go
func (r *Registry) AddHandler(h RegisterObject) { r.m.Lock() r.handlers[h.Reference()] = h r.m.Unlock() }
[ "func", "(", "r", "*", "Registry", ")", "AddHandler", "(", "h", "RegisterObject", ")", "{", "r", ".", "m", ".", "Lock", "(", ")", "\n", "r", ".", "handlers", "[", "h", ".", "Reference", "(", ")", "]", "=", "h", "\n", "r", ".", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// AddHandler adds a RegisterObject handler to the Registry.
[ "AddHandler", "adds", "a", "RegisterObject", "handler", "to", "the", "Registry", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L140-L144
21,647
vmware/govmomi
simulator/registry.go
PutEntity
func (r *Registry) PutEntity(parent mo.Entity, item mo.Entity) mo.Entity { e := item.Entity() if parent != nil { e.Parent = &parent.Entity().Self } r.Put(item) return item }
go
func (r *Registry) PutEntity(parent mo.Entity, item mo.Entity) mo.Entity { e := item.Entity() if parent != nil { e.Parent = &parent.Entity().Self } r.Put(item) return item }
[ "func", "(", "r", "*", "Registry", ")", "PutEntity", "(", "parent", "mo", ".", "Entity", ",", "item", "mo", ".", "Entity", ")", "mo", ".", "Entity", "{", "e", ":=", "item", ".", "Entity", "(", ")", "\n\n", "if", "parent", "!=", "nil", "{", "e", ".", "Parent", "=", "&", "parent", ".", "Entity", "(", ")", ".", "Self", "\n", "}", "\n\n", "r", ".", "Put", "(", "item", ")", "\n\n", "return", "item", "\n", "}" ]
// PutEntity sets item.Parent to that of parent.Self before adding item to the Registry.
[ "PutEntity", "sets", "item", ".", "Parent", "to", "that", "of", "parent", ".", "Self", "before", "adding", "item", "to", "the", "Registry", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L156-L166
21,648
vmware/govmomi
simulator/registry.go
Get
func (r *Registry) Get(ref types.ManagedObjectReference) mo.Reference { r.m.Lock() defer r.m.Unlock() return r.objects[ref] }
go
func (r *Registry) Get(ref types.ManagedObjectReference) mo.Reference { r.m.Lock() defer r.m.Unlock() return r.objects[ref] }
[ "func", "(", "r", "*", "Registry", ")", "Get", "(", "ref", "types", ".", "ManagedObjectReference", ")", "mo", ".", "Reference", "{", "r", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "m", ".", "Unlock", "(", ")", "\n\n", "return", "r", ".", "objects", "[", "ref", "]", "\n", "}" ]
// Get returns the object for the given reference.
[ "Get", "returns", "the", "object", "for", "the", "given", "reference", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L169-L174
21,649
vmware/govmomi
simulator/registry.go
Any
func (r *Registry) Any(kind string) mo.Entity { r.m.Lock() defer r.m.Unlock() for ref, val := range r.objects { if ref.Type == kind { return val.(mo.Entity) } } return nil }
go
func (r *Registry) Any(kind string) mo.Entity { r.m.Lock() defer r.m.Unlock() for ref, val := range r.objects { if ref.Type == kind { return val.(mo.Entity) } } return nil }
[ "func", "(", "r", "*", "Registry", ")", "Any", "(", "kind", "string", ")", "mo", ".", "Entity", "{", "r", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "m", ".", "Unlock", "(", ")", "\n\n", "for", "ref", ",", "val", ":=", "range", "r", ".", "objects", "{", "if", "ref", ".", "Type", "==", "kind", "{", "return", "val", ".", "(", "mo", ".", "Entity", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Any returns the first instance of entity type specified by kind.
[ "Any", "returns", "the", "first", "instance", "of", "entity", "type", "specified", "by", "kind", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L177-L188
21,650
vmware/govmomi
simulator/registry.go
All
func (r *Registry) All(kind string) []mo.Entity { r.m.Lock() defer r.m.Unlock() var entities []mo.Entity for ref, val := range r.objects { if kind == "" || ref.Type == kind { if e, ok := val.(mo.Entity); ok { entities = append(entities, e) } } } return entities }
go
func (r *Registry) All(kind string) []mo.Entity { r.m.Lock() defer r.m.Unlock() var entities []mo.Entity for ref, val := range r.objects { if kind == "" || ref.Type == kind { if e, ok := val.(mo.Entity); ok { entities = append(entities, e) } } } return entities }
[ "func", "(", "r", "*", "Registry", ")", "All", "(", "kind", "string", ")", "[", "]", "mo", ".", "Entity", "{", "r", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "m", ".", "Unlock", "(", ")", "\n\n", "var", "entities", "[", "]", "mo", ".", "Entity", "\n", "for", "ref", ",", "val", ":=", "range", "r", ".", "objects", "{", "if", "kind", "==", "\"", "\"", "||", "ref", ".", "Type", "==", "kind", "{", "if", "e", ",", "ok", ":=", "val", ".", "(", "mo", ".", "Entity", ")", ";", "ok", "{", "entities", "=", "append", "(", "entities", ",", "e", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "entities", "\n", "}" ]
// All returns all entities of type specified by kind. // If kind is empty - all entities will be returned.
[ "All", "returns", "all", "entities", "of", "type", "specified", "by", "kind", ".", "If", "kind", "is", "empty", "-", "all", "entities", "will", "be", "returned", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L192-L206
21,651
vmware/govmomi
simulator/registry.go
applyHandlers
func (r *Registry) applyHandlers(f func(o RegisterObject)) { r.m.Lock() handlers := make([]RegisterObject, 0, len(r.handlers)) for _, handler := range r.handlers { handlers = append(handlers, handler) } r.m.Unlock() for i := range handlers { f(handlers[i]) } }
go
func (r *Registry) applyHandlers(f func(o RegisterObject)) { r.m.Lock() handlers := make([]RegisterObject, 0, len(r.handlers)) for _, handler := range r.handlers { handlers = append(handlers, handler) } r.m.Unlock() for i := range handlers { f(handlers[i]) } }
[ "func", "(", "r", "*", "Registry", ")", "applyHandlers", "(", "f", "func", "(", "o", "RegisterObject", ")", ")", "{", "r", ".", "m", ".", "Lock", "(", ")", "\n", "handlers", ":=", "make", "(", "[", "]", "RegisterObject", ",", "0", ",", "len", "(", "r", ".", "handlers", ")", ")", "\n", "for", "_", ",", "handler", ":=", "range", "r", ".", "handlers", "{", "handlers", "=", "append", "(", "handlers", ",", "handler", ")", "\n", "}", "\n", "r", ".", "m", ".", "Unlock", "(", ")", "\n\n", "for", "i", ":=", "range", "handlers", "{", "f", "(", "handlers", "[", "i", "]", ")", "\n", "}", "\n", "}" ]
// applyHandlers calls the given func for each r.handlers
[ "applyHandlers", "calls", "the", "given", "func", "for", "each", "r", ".", "handlers" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L209-L220
21,652
vmware/govmomi
simulator/registry.go
Put
func (r *Registry) Put(item mo.Reference) mo.Reference { r.m.Lock() ref := item.Reference() if ref.Type == "" || ref.Value == "" { ref = r.newReference(item) r.setReference(item, ref) } if me, ok := item.(mo.Entity); ok { me.Entity().ConfigStatus = types.ManagedEntityStatusGreen me.Entity().OverallStatus = types.ManagedEntityStatusGreen me.Entity().EffectiveRole = []int32{-1} // Admin } r.objects[ref] = item r.m.Unlock() r.applyHandlers(func(o RegisterObject) { o.PutObject(item) }) return item }
go
func (r *Registry) Put(item mo.Reference) mo.Reference { r.m.Lock() ref := item.Reference() if ref.Type == "" || ref.Value == "" { ref = r.newReference(item) r.setReference(item, ref) } if me, ok := item.(mo.Entity); ok { me.Entity().ConfigStatus = types.ManagedEntityStatusGreen me.Entity().OverallStatus = types.ManagedEntityStatusGreen me.Entity().EffectiveRole = []int32{-1} // Admin } r.objects[ref] = item r.m.Unlock() r.applyHandlers(func(o RegisterObject) { o.PutObject(item) }) return item }
[ "func", "(", "r", "*", "Registry", ")", "Put", "(", "item", "mo", ".", "Reference", ")", "mo", ".", "Reference", "{", "r", ".", "m", ".", "Lock", "(", ")", "\n\n", "ref", ":=", "item", ".", "Reference", "(", ")", "\n", "if", "ref", ".", "Type", "==", "\"", "\"", "||", "ref", ".", "Value", "==", "\"", "\"", "{", "ref", "=", "r", ".", "newReference", "(", "item", ")", "\n", "r", ".", "setReference", "(", "item", ",", "ref", ")", "\n", "}", "\n\n", "if", "me", ",", "ok", ":=", "item", ".", "(", "mo", ".", "Entity", ")", ";", "ok", "{", "me", ".", "Entity", "(", ")", ".", "ConfigStatus", "=", "types", ".", "ManagedEntityStatusGreen", "\n", "me", ".", "Entity", "(", ")", ".", "OverallStatus", "=", "types", ".", "ManagedEntityStatusGreen", "\n", "me", ".", "Entity", "(", ")", ".", "EffectiveRole", "=", "[", "]", "int32", "{", "-", "1", "}", "// Admin", "\n", "}", "\n\n", "r", ".", "objects", "[", "ref", "]", "=", "item", "\n\n", "r", ".", "m", ".", "Unlock", "(", ")", "\n\n", "r", ".", "applyHandlers", "(", "func", "(", "o", "RegisterObject", ")", "{", "o", ".", "PutObject", "(", "item", ")", "\n", "}", ")", "\n\n", "return", "item", "\n", "}" ]
// Put adds a new object to Registry, generating a ManagedObjectReference if not already set.
[ "Put", "adds", "a", "new", "object", "to", "Registry", "generating", "a", "ManagedObjectReference", "if", "not", "already", "set", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L223-L247
21,653
vmware/govmomi
simulator/registry.go
Remove
func (r *Registry) Remove(item types.ManagedObjectReference) { r.applyHandlers(func(o RegisterObject) { o.RemoveObject(item) }) r.m.Lock() delete(r.objects, item) delete(r.handlers, item) delete(r.locks, item) r.m.Unlock() }
go
func (r *Registry) Remove(item types.ManagedObjectReference) { r.applyHandlers(func(o RegisterObject) { o.RemoveObject(item) }) r.m.Lock() delete(r.objects, item) delete(r.handlers, item) delete(r.locks, item) r.m.Unlock() }
[ "func", "(", "r", "*", "Registry", ")", "Remove", "(", "item", "types", ".", "ManagedObjectReference", ")", "{", "r", ".", "applyHandlers", "(", "func", "(", "o", "RegisterObject", ")", "{", "o", ".", "RemoveObject", "(", "item", ")", "\n", "}", ")", "\n\n", "r", ".", "m", ".", "Lock", "(", ")", "\n", "delete", "(", "r", ".", "objects", ",", "item", ")", "\n", "delete", "(", "r", ".", "handlers", ",", "item", ")", "\n", "delete", "(", "r", ".", "locks", ",", "item", ")", "\n", "r", ".", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove removes an object from the Registry.
[ "Remove", "removes", "an", "object", "from", "the", "Registry", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L250-L260
21,654
vmware/govmomi
simulator/registry.go
Update
func (r *Registry) Update(obj mo.Reference, changes []types.PropertyChange) { for i := range changes { if changes[i].Op == "" { changes[i].Op = types.PropertyChangeOpAssign } if changes[i].Val != nil { rval := reflect.ValueOf(changes[i].Val) changes[i].Val = wrapValue(rval, rval.Type()) } } val := getManagedObject(obj).Addr().Interface().(mo.Reference) mo.ApplyPropertyChange(val, changes) r.applyHandlers(func(o RegisterObject) { o.UpdateObject(val, changes) }) }
go
func (r *Registry) Update(obj mo.Reference, changes []types.PropertyChange) { for i := range changes { if changes[i].Op == "" { changes[i].Op = types.PropertyChangeOpAssign } if changes[i].Val != nil { rval := reflect.ValueOf(changes[i].Val) changes[i].Val = wrapValue(rval, rval.Type()) } } val := getManagedObject(obj).Addr().Interface().(mo.Reference) mo.ApplyPropertyChange(val, changes) r.applyHandlers(func(o RegisterObject) { o.UpdateObject(val, changes) }) }
[ "func", "(", "r", "*", "Registry", ")", "Update", "(", "obj", "mo", ".", "Reference", ",", "changes", "[", "]", "types", ".", "PropertyChange", ")", "{", "for", "i", ":=", "range", "changes", "{", "if", "changes", "[", "i", "]", ".", "Op", "==", "\"", "\"", "{", "changes", "[", "i", "]", ".", "Op", "=", "types", ".", "PropertyChangeOpAssign", "\n", "}", "\n", "if", "changes", "[", "i", "]", ".", "Val", "!=", "nil", "{", "rval", ":=", "reflect", ".", "ValueOf", "(", "changes", "[", "i", "]", ".", "Val", ")", "\n", "changes", "[", "i", "]", ".", "Val", "=", "wrapValue", "(", "rval", ",", "rval", ".", "Type", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "val", ":=", "getManagedObject", "(", "obj", ")", ".", "Addr", "(", ")", ".", "Interface", "(", ")", ".", "(", "mo", ".", "Reference", ")", "\n\n", "mo", ".", "ApplyPropertyChange", "(", "val", ",", "changes", ")", "\n\n", "r", ".", "applyHandlers", "(", "func", "(", "o", "RegisterObject", ")", "{", "o", ".", "UpdateObject", "(", "val", ",", "changes", ")", "\n", "}", ")", "\n", "}" ]
// Update dispatches object property changes to RegisterObject handlers, // such as any PropertyCollector instances with in-progress WaitForUpdates calls. // The changes are also applied to the given object via mo.ApplyPropertyChange, // so there is no need to set object fields directly.
[ "Update", "dispatches", "object", "property", "changes", "to", "RegisterObject", "handlers", "such", "as", "any", "PropertyCollector", "instances", "with", "in", "-", "progress", "WaitForUpdates", "calls", ".", "The", "changes", "are", "also", "applied", "to", "the", "given", "object", "via", "mo", ".", "ApplyPropertyChange", "so", "there", "is", "no", "need", "to", "set", "object", "fields", "directly", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L266-L284
21,655
vmware/govmomi
simulator/registry.go
getEntityParent
func (r *Registry) getEntityParent(item mo.Entity, kind string) mo.Entity { for { parent := item.Entity().Parent item = r.Get(*parent).(mo.Entity) if item.Reference().Type == kind { return item } } }
go
func (r *Registry) getEntityParent(item mo.Entity, kind string) mo.Entity { for { parent := item.Entity().Parent item = r.Get(*parent).(mo.Entity) if item.Reference().Type == kind { return item } } }
[ "func", "(", "r", "*", "Registry", ")", "getEntityParent", "(", "item", "mo", ".", "Entity", ",", "kind", "string", ")", "mo", ".", "Entity", "{", "for", "{", "parent", ":=", "item", ".", "Entity", "(", ")", ".", "Parent", "\n\n", "item", "=", "r", ".", "Get", "(", "*", "parent", ")", ".", "(", "mo", ".", "Entity", ")", "\n\n", "if", "item", ".", "Reference", "(", ")", ".", "Type", "==", "kind", "{", "return", "item", "\n", "}", "\n", "}", "\n", "}" ]
// getEntityParent traverses up the inventory and returns the first object of type kind. // If no object of type kind is found, the method will panic when it reaches the // inventory root Folder where the Parent field is nil.
[ "getEntityParent", "traverses", "up", "the", "inventory", "and", "returns", "the", "first", "object", "of", "type", "kind", ".", "If", "no", "object", "of", "type", "kind", "is", "found", "the", "method", "will", "panic", "when", "it", "reaches", "the", "inventory", "root", "Folder", "where", "the", "Parent", "field", "is", "nil", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L289-L299
21,656
vmware/govmomi
simulator/registry.go
getEntityDatacenter
func (r *Registry) getEntityDatacenter(item mo.Entity) *Datacenter { return r.getEntityParent(item, "Datacenter").(*Datacenter) }
go
func (r *Registry) getEntityDatacenter(item mo.Entity) *Datacenter { return r.getEntityParent(item, "Datacenter").(*Datacenter) }
[ "func", "(", "r", "*", "Registry", ")", "getEntityDatacenter", "(", "item", "mo", ".", "Entity", ")", "*", "Datacenter", "{", "return", "r", ".", "getEntityParent", "(", "item", ",", "\"", "\"", ")", ".", "(", "*", "Datacenter", ")", "\n", "}" ]
// getEntityDatacenter returns the Datacenter containing the given item
[ "getEntityDatacenter", "returns", "the", "Datacenter", "containing", "the", "given", "item" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L302-L304
21,657
vmware/govmomi
simulator/registry.go
getEntityComputeResource
func (r *Registry) getEntityComputeResource(item mo.Entity) mo.Entity { for { parent := item.Entity().Parent item = r.Get(*parent).(mo.Entity) switch item.Reference().Type { case "ComputeResource": return item case "ClusterComputeResource": return item } } }
go
func (r *Registry) getEntityComputeResource(item mo.Entity) mo.Entity { for { parent := item.Entity().Parent item = r.Get(*parent).(mo.Entity) switch item.Reference().Type { case "ComputeResource": return item case "ClusterComputeResource": return item } } }
[ "func", "(", "r", "*", "Registry", ")", "getEntityComputeResource", "(", "item", "mo", ".", "Entity", ")", "mo", ".", "Entity", "{", "for", "{", "parent", ":=", "item", ".", "Entity", "(", ")", ".", "Parent", "\n\n", "item", "=", "r", ".", "Get", "(", "*", "parent", ")", ".", "(", "mo", ".", "Entity", ")", "\n\n", "switch", "item", ".", "Reference", "(", ")", ".", "Type", "{", "case", "\"", "\"", ":", "return", "item", "\n", "case", "\"", "\"", ":", "return", "item", "\n", "}", "\n", "}", "\n", "}" ]
// getEntityComputeResource returns the ComputeResource parent for the given item. // A ResourcePool for example may have N Parents of type ResourcePool, but the top // most Parent pool is always a ComputeResource child.
[ "getEntityComputeResource", "returns", "the", "ComputeResource", "parent", "for", "the", "given", "item", ".", "A", "ResourcePool", "for", "example", "may", "have", "N", "Parents", "of", "type", "ResourcePool", "but", "the", "top", "most", "Parent", "pool", "is", "always", "a", "ComputeResource", "child", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L332-L345
21,658
vmware/govmomi
simulator/registry.go
FindByName
func (r *Registry) FindByName(name string, refs []types.ManagedObjectReference) mo.Entity { for _, ref := range refs { if e, ok := r.Get(ref).(mo.Entity); ok { if name == e.Entity().Name { return e } } } return nil }
go
func (r *Registry) FindByName(name string, refs []types.ManagedObjectReference) mo.Entity { for _, ref := range refs { if e, ok := r.Get(ref).(mo.Entity); ok { if name == e.Entity().Name { return e } } } return nil }
[ "func", "(", "r", "*", "Registry", ")", "FindByName", "(", "name", "string", ",", "refs", "[", "]", "types", ".", "ManagedObjectReference", ")", "mo", ".", "Entity", "{", "for", "_", ",", "ref", ":=", "range", "refs", "{", "if", "e", ",", "ok", ":=", "r", ".", "Get", "(", "ref", ")", ".", "(", "mo", ".", "Entity", ")", ";", "ok", "{", "if", "name", "==", "e", ".", "Entity", "(", ")", ".", "Name", "{", "return", "e", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// FindByName returns the first mo.Entity of the given refs whose Name field is equal to the given name. // If there is no match, nil is returned. // This method is useful for cases where objects are required to have a unique name, such as Datastore with // a HostStorageSystem or HostSystem within a ClusterComputeResource.
[ "FindByName", "returns", "the", "first", "mo", ".", "Entity", "of", "the", "given", "refs", "whose", "Name", "field", "is", "equal", "to", "the", "given", "name", ".", "If", "there", "is", "no", "match", "nil", "is", "returned", ".", "This", "method", "is", "useful", "for", "cases", "where", "objects", "are", "required", "to", "have", "a", "unique", "name", "such", "as", "Datastore", "with", "a", "HostStorageSystem", "or", "HostSystem", "within", "a", "ClusterComputeResource", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L351-L361
21,659
vmware/govmomi
simulator/registry.go
FindReference
func FindReference(refs []types.ManagedObjectReference, match ...types.ManagedObjectReference) *types.ManagedObjectReference { for _, ref := range refs { for _, m := range match { if ref == m { return &ref } } } return nil }
go
func FindReference(refs []types.ManagedObjectReference, match ...types.ManagedObjectReference) *types.ManagedObjectReference { for _, ref := range refs { for _, m := range match { if ref == m { return &ref } } } return nil }
[ "func", "FindReference", "(", "refs", "[", "]", "types", ".", "ManagedObjectReference", ",", "match", "...", "types", ".", "ManagedObjectReference", ")", "*", "types", ".", "ManagedObjectReference", "{", "for", "_", ",", "ref", ":=", "range", "refs", "{", "for", "_", ",", "m", ":=", "range", "match", "{", "if", "ref", "==", "m", "{", "return", "&", "ref", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// FindReference returns the 1st match found in refs, or nil if not found.
[ "FindReference", "returns", "the", "1st", "match", "found", "in", "refs", "or", "nil", "if", "not", "found", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L364-L374
21,660
vmware/govmomi
simulator/registry.go
AppendReference
func (r *Registry) AppendReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref ...types.ManagedObjectReference) { r.WithLock(obj, func() { *field = append(*field, ref...) }) }
go
func (r *Registry) AppendReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref ...types.ManagedObjectReference) { r.WithLock(obj, func() { *field = append(*field, ref...) }) }
[ "func", "(", "r", "*", "Registry", ")", "AppendReference", "(", "obj", "mo", ".", "Reference", ",", "field", "*", "[", "]", "types", ".", "ManagedObjectReference", ",", "ref", "...", "types", ".", "ManagedObjectReference", ")", "{", "r", ".", "WithLock", "(", "obj", ",", "func", "(", ")", "{", "*", "field", "=", "append", "(", "*", "field", ",", "ref", "...", ")", "\n", "}", ")", "\n", "}" ]
// AppendReference appends the given refs to field.
[ "AppendReference", "appends", "the", "given", "refs", "to", "field", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L377-L381
21,661
vmware/govmomi
simulator/registry.go
AddReference
func (r *Registry) AddReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref types.ManagedObjectReference) { r.WithLock(obj, func() { if FindReference(*field, ref) == nil { *field = append(*field, ref) } }) }
go
func (r *Registry) AddReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref types.ManagedObjectReference) { r.WithLock(obj, func() { if FindReference(*field, ref) == nil { *field = append(*field, ref) } }) }
[ "func", "(", "r", "*", "Registry", ")", "AddReference", "(", "obj", "mo", ".", "Reference", ",", "field", "*", "[", "]", "types", ".", "ManagedObjectReference", ",", "ref", "types", ".", "ManagedObjectReference", ")", "{", "r", ".", "WithLock", "(", "obj", ",", "func", "(", ")", "{", "if", "FindReference", "(", "*", "field", ",", "ref", ")", "==", "nil", "{", "*", "field", "=", "append", "(", "*", "field", ",", "ref", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// AddReference appends ref to field if not already in the given field.
[ "AddReference", "appends", "ref", "to", "field", "if", "not", "already", "in", "the", "given", "field", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L384-L390
21,662
vmware/govmomi
simulator/registry.go
SearchIndex
func (r *Registry) SearchIndex() *SearchIndex { return r.Get(r.content().SearchIndex.Reference()).(*SearchIndex) }
go
func (r *Registry) SearchIndex() *SearchIndex { return r.Get(r.content().SearchIndex.Reference()).(*SearchIndex) }
[ "func", "(", "r", "*", "Registry", ")", "SearchIndex", "(", ")", "*", "SearchIndex", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "SearchIndex", ".", "Reference", "(", ")", ")", ".", "(", "*", "SearchIndex", ")", "\n", "}" ]
// SearchIndex returns the SearchIndex singleton
[ "SearchIndex", "returns", "the", "SearchIndex", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L435-L437
21,663
vmware/govmomi
simulator/registry.go
EventManager
func (r *Registry) EventManager() *EventManager { return r.Get(r.content().EventManager.Reference()).(*EventManager) }
go
func (r *Registry) EventManager() *EventManager { return r.Get(r.content().EventManager.Reference()).(*EventManager) }
[ "func", "(", "r", "*", "Registry", ")", "EventManager", "(", ")", "*", "EventManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "EventManager", ".", "Reference", "(", ")", ")", ".", "(", "*", "EventManager", ")", "\n", "}" ]
// EventManager returns the EventManager singleton
[ "EventManager", "returns", "the", "EventManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L440-L442
21,664
vmware/govmomi
simulator/registry.go
FileManager
func (r *Registry) FileManager() *FileManager { return r.Get(r.content().FileManager.Reference()).(*FileManager) }
go
func (r *Registry) FileManager() *FileManager { return r.Get(r.content().FileManager.Reference()).(*FileManager) }
[ "func", "(", "r", "*", "Registry", ")", "FileManager", "(", ")", "*", "FileManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "FileManager", ".", "Reference", "(", ")", ")", ".", "(", "*", "FileManager", ")", "\n", "}" ]
// FileManager returns the FileManager singleton
[ "FileManager", "returns", "the", "FileManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L445-L447
21,665
vmware/govmomi
simulator/registry.go
VirtualDiskManager
func (r *Registry) VirtualDiskManager() *VirtualDiskManager { return r.Get(r.content().VirtualDiskManager.Reference()).(*VirtualDiskManager) }
go
func (r *Registry) VirtualDiskManager() *VirtualDiskManager { return r.Get(r.content().VirtualDiskManager.Reference()).(*VirtualDiskManager) }
[ "func", "(", "r", "*", "Registry", ")", "VirtualDiskManager", "(", ")", "*", "VirtualDiskManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "VirtualDiskManager", ".", "Reference", "(", ")", ")", ".", "(", "*", "VirtualDiskManager", ")", "\n", "}" ]
// VirtualDiskManager returns the VirtualDiskManager singleton
[ "VirtualDiskManager", "returns", "the", "VirtualDiskManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L450-L452
21,666
vmware/govmomi
simulator/registry.go
ViewManager
func (r *Registry) ViewManager() *ViewManager { return r.Get(r.content().ViewManager.Reference()).(*ViewManager) }
go
func (r *Registry) ViewManager() *ViewManager { return r.Get(r.content().ViewManager.Reference()).(*ViewManager) }
[ "func", "(", "r", "*", "Registry", ")", "ViewManager", "(", ")", "*", "ViewManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "ViewManager", ".", "Reference", "(", ")", ")", ".", "(", "*", "ViewManager", ")", "\n", "}" ]
// ViewManager returns the ViewManager singleton
[ "ViewManager", "returns", "the", "ViewManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L455-L457
21,667
vmware/govmomi
simulator/registry.go
UserDirectory
func (r *Registry) UserDirectory() *UserDirectory { return r.Get(r.content().UserDirectory.Reference()).(*UserDirectory) }
go
func (r *Registry) UserDirectory() *UserDirectory { return r.Get(r.content().UserDirectory.Reference()).(*UserDirectory) }
[ "func", "(", "r", "*", "Registry", ")", "UserDirectory", "(", ")", "*", "UserDirectory", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "UserDirectory", ".", "Reference", "(", ")", ")", ".", "(", "*", "UserDirectory", ")", "\n", "}" ]
// UserDirectory returns the UserDirectory singleton
[ "UserDirectory", "returns", "the", "UserDirectory", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L460-L462
21,668
vmware/govmomi
simulator/registry.go
SessionManager
func (r *Registry) SessionManager() *SessionManager { return r.Get(r.content().SessionManager.Reference()).(*SessionManager) }
go
func (r *Registry) SessionManager() *SessionManager { return r.Get(r.content().SessionManager.Reference()).(*SessionManager) }
[ "func", "(", "r", "*", "Registry", ")", "SessionManager", "(", ")", "*", "SessionManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "SessionManager", ".", "Reference", "(", ")", ")", ".", "(", "*", "SessionManager", ")", "\n", "}" ]
// SessionManager returns the SessionManager singleton
[ "SessionManager", "returns", "the", "SessionManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L465-L467
21,669
vmware/govmomi
simulator/registry.go
OptionManager
func (r *Registry) OptionManager() *OptionManager { return r.Get(r.content().Setting.Reference()).(*OptionManager) }
go
func (r *Registry) OptionManager() *OptionManager { return r.Get(r.content().Setting.Reference()).(*OptionManager) }
[ "func", "(", "r", "*", "Registry", ")", "OptionManager", "(", ")", "*", "OptionManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "Setting", ".", "Reference", "(", ")", ")", ".", "(", "*", "OptionManager", ")", "\n", "}" ]
// OptionManager returns the OptionManager singleton
[ "OptionManager", "returns", "the", "OptionManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L470-L472
21,670
vmware/govmomi
simulator/registry.go
CustomFieldsManager
func (r *Registry) CustomFieldsManager() *CustomFieldsManager { return r.Get(r.content().CustomFieldsManager.Reference()).(*CustomFieldsManager) }
go
func (r *Registry) CustomFieldsManager() *CustomFieldsManager { return r.Get(r.content().CustomFieldsManager.Reference()).(*CustomFieldsManager) }
[ "func", "(", "r", "*", "Registry", ")", "CustomFieldsManager", "(", ")", "*", "CustomFieldsManager", "{", "return", "r", ".", "Get", "(", "r", ".", "content", "(", ")", ".", "CustomFieldsManager", ".", "Reference", "(", ")", ")", ".", "(", "*", "CustomFieldsManager", ")", "\n", "}" ]
// CustomFieldsManager returns CustomFieldsManager singleton
[ "CustomFieldsManager", "returns", "CustomFieldsManager", "singleton" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L475-L477
21,671
vmware/govmomi
vim25/mo/type_info.go
LoadFromObjectContent
func (t *typeInfo) LoadFromObjectContent(o types.ObjectContent) (reflect.Value, error) { v := reflect.New(t.typ) assignValue(v, t.self, reflect.ValueOf(o.Obj)) for _, p := range o.PropSet { rv, ok := t.props[p.Name] if !ok { continue } assignValue(v, rv, reflect.ValueOf(p.Val)) } return v, nil }
go
func (t *typeInfo) LoadFromObjectContent(o types.ObjectContent) (reflect.Value, error) { v := reflect.New(t.typ) assignValue(v, t.self, reflect.ValueOf(o.Obj)) for _, p := range o.PropSet { rv, ok := t.props[p.Name] if !ok { continue } assignValue(v, rv, reflect.ValueOf(p.Val)) } return v, nil }
[ "func", "(", "t", "*", "typeInfo", ")", "LoadFromObjectContent", "(", "o", "types", ".", "ObjectContent", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "v", ":=", "reflect", ".", "New", "(", "t", ".", "typ", ")", "\n", "assignValue", "(", "v", ",", "t", ".", "self", ",", "reflect", ".", "ValueOf", "(", "o", ".", "Obj", ")", ")", "\n\n", "for", "_", ",", "p", ":=", "range", "o", ".", "PropSet", "{", "rv", ",", "ok", ":=", "t", ".", "props", "[", "p", ".", "Name", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "assignValue", "(", "v", ",", "rv", ",", "reflect", ".", "ValueOf", "(", "p", ".", "Val", ")", ")", "\n", "}", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// LoadObjectFromContent loads properties from the 'PropSet' field in the // specified ObjectContent value into the value it represents, which is // returned as a reflect.Value.
[ "LoadObjectFromContent", "loads", "properties", "from", "the", "PropSet", "field", "in", "the", "specified", "ObjectContent", "value", "into", "the", "value", "it", "represents", "which", "is", "returned", "as", "a", "reflect", ".", "Value", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/type_info.go#L245-L258
21,672
vmware/govmomi
simulator/simulator.go
New
func New(instance *ServiceInstance) *Service { s := &Service{ readAll: ioutil.ReadAll, sm: Map.SessionManager(), sdk: make(map[string]*Registry), } s.client, _ = vim25.NewClient(context.Background(), s) return s }
go
func New(instance *ServiceInstance) *Service { s := &Service{ readAll: ioutil.ReadAll, sm: Map.SessionManager(), sdk: make(map[string]*Registry), } s.client, _ = vim25.NewClient(context.Background(), s) return s }
[ "func", "New", "(", "instance", "*", "ServiceInstance", ")", "*", "Service", "{", "s", ":=", "&", "Service", "{", "readAll", ":", "ioutil", ".", "ReadAll", ",", "sm", ":", "Map", ".", "SessionManager", "(", ")", ",", "sdk", ":", "make", "(", "map", "[", "string", "]", "*", "Registry", ")", ",", "}", "\n\n", "s", ".", "client", ",", "_", "=", "vim25", ".", "NewClient", "(", "context", ".", "Background", "(", ")", ",", "s", ")", "\n\n", "return", "s", "\n", "}" ]
// New returns an initialized simulator Service instance
[ "New", "returns", "an", "initialized", "simulator", "Service", "instance" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L88-L98
21,673
vmware/govmomi
simulator/simulator.go
Fault
func Fault(msg string, fault types.BaseMethodFault) *soap.Fault { f := &soap.Fault{ Code: "ServerFaultCode", String: msg, } f.Detail.Fault = fault return f }
go
func Fault(msg string, fault types.BaseMethodFault) *soap.Fault { f := &soap.Fault{ Code: "ServerFaultCode", String: msg, } f.Detail.Fault = fault return f }
[ "func", "Fault", "(", "msg", "string", ",", "fault", "types", ".", "BaseMethodFault", ")", "*", "soap", ".", "Fault", "{", "f", ":=", "&", "soap", ".", "Fault", "{", "Code", ":", "\"", "\"", ",", "String", ":", "msg", ",", "}", "\n\n", "f", ".", "Detail", ".", "Fault", "=", "fault", "\n\n", "return", "f", "\n", "}" ]
// Fault wraps the given message and fault in a soap.Fault
[ "Fault", "wraps", "the", "given", "message", "and", "fault", "in", "a", "soap", ".", "Fault" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L111-L120
21,674
vmware/govmomi
simulator/simulator.go
About
func (s *Service) About(w http.ResponseWriter, r *http.Request) { var about struct { Methods []string Types []string } seen := make(map[string]bool) f := reflect.TypeOf((*soap.HasFault)(nil)).Elem() for _, obj := range Map.objects { kind := obj.Reference().Type if seen[kind] { continue } seen[kind] = true about.Types = append(about.Types, kind) t := reflect.TypeOf(obj) for i := 0; i < t.NumMethod(); i++ { m := t.Method(i) if seen[m.Name] { continue } seen[m.Name] = true in := m.Type.NumIn() if in < 2 || in > 3 { // at least 2 params (receiver and request), optionally a 3rd param (context) continue } if m.Type.NumOut() != 1 || m.Type.Out(0) != f { // all methods return soap.HasFault continue } about.Methods = append(about.Methods, strings.Replace(m.Name, "Task", "_Task", 1)) } } sort.Strings(about.Methods) sort.Strings(about.Types) w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) enc.SetIndent("", " ") _ = enc.Encode(&about) }
go
func (s *Service) About(w http.ResponseWriter, r *http.Request) { var about struct { Methods []string Types []string } seen := make(map[string]bool) f := reflect.TypeOf((*soap.HasFault)(nil)).Elem() for _, obj := range Map.objects { kind := obj.Reference().Type if seen[kind] { continue } seen[kind] = true about.Types = append(about.Types, kind) t := reflect.TypeOf(obj) for i := 0; i < t.NumMethod(); i++ { m := t.Method(i) if seen[m.Name] { continue } seen[m.Name] = true in := m.Type.NumIn() if in < 2 || in > 3 { // at least 2 params (receiver and request), optionally a 3rd param (context) continue } if m.Type.NumOut() != 1 || m.Type.Out(0) != f { // all methods return soap.HasFault continue } about.Methods = append(about.Methods, strings.Replace(m.Name, "Task", "_Task", 1)) } } sort.Strings(about.Methods) sort.Strings(about.Types) w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) enc.SetIndent("", " ") _ = enc.Encode(&about) }
[ "func", "(", "s", "*", "Service", ")", "About", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "about", "struct", "{", "Methods", "[", "]", "string", "\n", "Types", "[", "]", "string", "\n", "}", "\n\n", "seen", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "f", ":=", "reflect", ".", "TypeOf", "(", "(", "*", "soap", ".", "HasFault", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n\n", "for", "_", ",", "obj", ":=", "range", "Map", ".", "objects", "{", "kind", ":=", "obj", ".", "Reference", "(", ")", ".", "Type", "\n", "if", "seen", "[", "kind", "]", "{", "continue", "\n", "}", "\n", "seen", "[", "kind", "]", "=", "true", "\n\n", "about", ".", "Types", "=", "append", "(", "about", ".", "Types", ",", "kind", ")", "\n\n", "t", ":=", "reflect", ".", "TypeOf", "(", "obj", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumMethod", "(", ")", ";", "i", "++", "{", "m", ":=", "t", ".", "Method", "(", "i", ")", "\n", "if", "seen", "[", "m", ".", "Name", "]", "{", "continue", "\n", "}", "\n", "seen", "[", "m", ".", "Name", "]", "=", "true", "\n\n", "in", ":=", "m", ".", "Type", ".", "NumIn", "(", ")", "\n", "if", "in", "<", "2", "||", "in", ">", "3", "{", "// at least 2 params (receiver and request), optionally a 3rd param (context)", "continue", "\n", "}", "\n", "if", "m", ".", "Type", ".", "NumOut", "(", ")", "!=", "1", "||", "m", ".", "Type", ".", "Out", "(", "0", ")", "!=", "f", "{", "// all methods return soap.HasFault", "continue", "\n", "}", "\n\n", "about", ".", "Methods", "=", "append", "(", "about", ".", "Methods", ",", "strings", ".", "Replace", "(", "m", ".", "Name", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", ")", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "about", ".", "Methods", ")", "\n", "sort", ".", "Strings", "(", "about", ".", "Types", ")", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "enc", ":=", "json", ".", "NewEncoder", "(", "w", ")", "\n", "enc", ".", "SetIndent", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "_", "=", "enc", ".", "Encode", "(", "&", "about", ")", "\n", "}" ]
// About generates some info about the simulator.
[ "About", "generates", "some", "info", "about", "the", "simulator", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L317-L363
21,675
vmware/govmomi
simulator/simulator.go
Handle
func (s *Service) Handle(pattern string, handler http.Handler) { s.ServeMux.Handle(pattern, handler) // Not ideal, but avoids having to add yet another registration mechanism // so we can optionally use vapi/simulator internally. if m, ok := handler.(tagManager); ok { s.sdk[vim25.Path].tagManager = m } }
go
func (s *Service) Handle(pattern string, handler http.Handler) { s.ServeMux.Handle(pattern, handler) // Not ideal, but avoids having to add yet another registration mechanism // so we can optionally use vapi/simulator internally. if m, ok := handler.(tagManager); ok { s.sdk[vim25.Path].tagManager = m } }
[ "func", "(", "s", "*", "Service", ")", "Handle", "(", "pattern", "string", ",", "handler", "http", ".", "Handler", ")", "{", "s", ".", "ServeMux", ".", "Handle", "(", "pattern", ",", "handler", ")", "\n", "// Not ideal, but avoids having to add yet another registration mechanism", "// so we can optionally use vapi/simulator internally.", "if", "m", ",", "ok", ":=", "handler", ".", "(", "tagManager", ")", ";", "ok", "{", "s", ".", "sdk", "[", "vim25", ".", "Path", "]", ".", "tagManager", "=", "m", "\n", "}", "\n", "}" ]
// Handle registers the handler for the given pattern with Service.ServeMux.
[ "Handle", "registers", "the", "handler", "for", "the", "given", "pattern", "with", "Service", ".", "ServeMux", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L366-L373
21,676
vmware/govmomi
simulator/simulator.go
RegisterSDK
func (s *Service) RegisterSDK(r *Registry) { if s.ServeMux == nil { s.ServeMux = http.NewServeMux() } s.sdk[r.Path] = r s.ServeMux.HandleFunc(r.Path, s.ServeSDK) }
go
func (s *Service) RegisterSDK(r *Registry) { if s.ServeMux == nil { s.ServeMux = http.NewServeMux() } s.sdk[r.Path] = r s.ServeMux.HandleFunc(r.Path, s.ServeSDK) }
[ "func", "(", "s", "*", "Service", ")", "RegisterSDK", "(", "r", "*", "Registry", ")", "{", "if", "s", ".", "ServeMux", "==", "nil", "{", "s", ".", "ServeMux", "=", "http", ".", "NewServeMux", "(", ")", "\n", "}", "\n\n", "s", ".", "sdk", "[", "r", ".", "Path", "]", "=", "r", "\n", "s", ".", "ServeMux", ".", "HandleFunc", "(", "r", ".", "Path", ",", "s", ".", "ServeSDK", ")", "\n", "}" ]
// RegisterSDK adds an HTTP handler for the Registry's Path and Namespace.
[ "RegisterSDK", "adds", "an", "HTTP", "handler", "for", "the", "Registry", "s", "Path", "and", "Namespace", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L376-L383
21,677
vmware/govmomi
simulator/simulator.go
ServeSDK
func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } body, err := s.readAll(r.Body) _ = r.Body.Close() if err != nil { log.Printf("error reading body: %s", err) w.WriteHeader(http.StatusBadRequest) return } if Trace { fmt.Fprintf(os.Stderr, "Request: %s\n", string(body)) } ctx := &Context{ req: r, res: w, svc: s, Map: s.sdk[r.URL.Path], Context: context.Background(), } ctx.Map.WithLock(s.sm, ctx.mapSession) var res soap.HasFault var soapBody interface{} method, err := UnmarshalBody(ctx.Map.typeFunc, body) if err != nil { res = serverFault(err.Error()) } else { ctx.Header = method.Header if method.Name == "Fetch" { // Redirect any Fetch method calls to the PropertyCollector singleton method.This = ctx.Map.content().PropertyCollector } res = s.call(ctx, method) } if f := res.Fault(); f != nil { w.WriteHeader(http.StatusInternalServerError) // the generated method/*Body structs use the '*soap.Fault' type, // so we need our own Body type to use the modified '*soapFault' type. soapBody = struct { Fault *soapFault }{ &soapFault{ Code: f.Code, String: f.String, Detail: struct { Fault *faultDetail }{&faultDetail{f.Detail.Fault}}, }, } } else { w.WriteHeader(http.StatusOK) soapBody = &response{ctx.Map.Namespace, res} } var out bytes.Buffer fmt.Fprint(&out, xml.Header) e := xml.NewEncoder(&out) err = e.Encode(&soapEnvelope{ Enc: "http://schemas.xmlsoap.org/soap/encoding/", Env: "http://schemas.xmlsoap.org/soap/envelope/", XSD: "http://www.w3.org/2001/XMLSchema", XSI: "http://www.w3.org/2001/XMLSchema-instance", Body: soapBody, }) if err == nil { err = e.Flush() } if err != nil { log.Printf("error encoding %s response: %s", method.Name, err) return } if Trace { fmt.Fprintf(os.Stderr, "Response: %s\n", out.String()) } _, _ = w.Write(out.Bytes()) }
go
func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } body, err := s.readAll(r.Body) _ = r.Body.Close() if err != nil { log.Printf("error reading body: %s", err) w.WriteHeader(http.StatusBadRequest) return } if Trace { fmt.Fprintf(os.Stderr, "Request: %s\n", string(body)) } ctx := &Context{ req: r, res: w, svc: s, Map: s.sdk[r.URL.Path], Context: context.Background(), } ctx.Map.WithLock(s.sm, ctx.mapSession) var res soap.HasFault var soapBody interface{} method, err := UnmarshalBody(ctx.Map.typeFunc, body) if err != nil { res = serverFault(err.Error()) } else { ctx.Header = method.Header if method.Name == "Fetch" { // Redirect any Fetch method calls to the PropertyCollector singleton method.This = ctx.Map.content().PropertyCollector } res = s.call(ctx, method) } if f := res.Fault(); f != nil { w.WriteHeader(http.StatusInternalServerError) // the generated method/*Body structs use the '*soap.Fault' type, // so we need our own Body type to use the modified '*soapFault' type. soapBody = struct { Fault *soapFault }{ &soapFault{ Code: f.Code, String: f.String, Detail: struct { Fault *faultDetail }{&faultDetail{f.Detail.Fault}}, }, } } else { w.WriteHeader(http.StatusOK) soapBody = &response{ctx.Map.Namespace, res} } var out bytes.Buffer fmt.Fprint(&out, xml.Header) e := xml.NewEncoder(&out) err = e.Encode(&soapEnvelope{ Enc: "http://schemas.xmlsoap.org/soap/encoding/", Env: "http://schemas.xmlsoap.org/soap/envelope/", XSD: "http://www.w3.org/2001/XMLSchema", XSI: "http://www.w3.org/2001/XMLSchema-instance", Body: soapBody, }) if err == nil { err = e.Flush() } if err != nil { log.Printf("error encoding %s response: %s", method.Name, err) return } if Trace { fmt.Fprintf(os.Stderr, "Response: %s\n", out.String()) } _, _ = w.Write(out.Bytes()) }
[ "func", "(", "s", "*", "Service", ")", "ServeSDK", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "!=", "http", ".", "MethodPost", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusMethodNotAllowed", ")", "\n", "return", "\n", "}", "\n\n", "body", ",", "err", ":=", "s", ".", "readAll", "(", "r", ".", "Body", ")", "\n", "_", "=", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n\n", "if", "Trace", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "string", "(", "body", ")", ")", "\n", "}", "\n\n", "ctx", ":=", "&", "Context", "{", "req", ":", "r", ",", "res", ":", "w", ",", "svc", ":", "s", ",", "Map", ":", "s", ".", "sdk", "[", "r", ".", "URL", ".", "Path", "]", ",", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", "\n", "ctx", ".", "Map", ".", "WithLock", "(", "s", ".", "sm", ",", "ctx", ".", "mapSession", ")", "\n\n", "var", "res", "soap", ".", "HasFault", "\n", "var", "soapBody", "interface", "{", "}", "\n\n", "method", ",", "err", ":=", "UnmarshalBody", "(", "ctx", ".", "Map", ".", "typeFunc", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "serverFault", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "ctx", ".", "Header", "=", "method", ".", "Header", "\n", "if", "method", ".", "Name", "==", "\"", "\"", "{", "// Redirect any Fetch method calls to the PropertyCollector singleton", "method", ".", "This", "=", "ctx", ".", "Map", ".", "content", "(", ")", ".", "PropertyCollector", "\n", "}", "\n", "res", "=", "s", ".", "call", "(", "ctx", ",", "method", ")", "\n", "}", "\n\n", "if", "f", ":=", "res", ".", "Fault", "(", ")", ";", "f", "!=", "nil", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n\n", "// the generated method/*Body structs use the '*soap.Fault' type,", "// so we need our own Body type to use the modified '*soapFault' type.", "soapBody", "=", "struct", "{", "Fault", "*", "soapFault", "\n", "}", "{", "&", "soapFault", "{", "Code", ":", "f", ".", "Code", ",", "String", ":", "f", ".", "String", ",", "Detail", ":", "struct", "{", "Fault", "*", "faultDetail", "\n", "}", "{", "&", "faultDetail", "{", "f", ".", "Detail", ".", "Fault", "}", "}", ",", "}", ",", "}", "\n", "}", "else", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n\n", "soapBody", "=", "&", "response", "{", "ctx", ".", "Map", ".", "Namespace", ",", "res", "}", "\n", "}", "\n\n", "var", "out", "bytes", ".", "Buffer", "\n\n", "fmt", ".", "Fprint", "(", "&", "out", ",", "xml", ".", "Header", ")", "\n", "e", ":=", "xml", ".", "NewEncoder", "(", "&", "out", ")", "\n", "err", "=", "e", ".", "Encode", "(", "&", "soapEnvelope", "{", "Enc", ":", "\"", "\"", ",", "Env", ":", "\"", "\"", ",", "XSD", ":", "\"", "\"", ",", "XSI", ":", "\"", "\"", ",", "Body", ":", "soapBody", ",", "}", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "e", ".", "Flush", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "method", ".", "Name", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "Trace", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "out", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "_", ",", "_", "=", "w", ".", "Write", "(", "out", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// ServeSDK implements the http.Handler interface
[ "ServeSDK", "implements", "the", "http", ".", "Handler", "interface" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L386-L476
21,678
vmware/govmomi
simulator/simulator.go
defaultIP
func defaultIP(addr *net.TCPAddr) string { if !addr.IP.IsUnspecified() { return addr.IP.String() } nics, err := net.Interfaces() if err != nil { return addr.IP.String() } for _, nic := range nics { if nic.Name == "docker0" || strings.HasPrefix(nic.Name, "vmnet") { continue } addrs, aerr := nic.Addrs() if aerr != nil { continue } for _, addr := range addrs { if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() { if ip.IP.To4() != nil { return ip.IP.String() } } } } return addr.IP.String() }
go
func defaultIP(addr *net.TCPAddr) string { if !addr.IP.IsUnspecified() { return addr.IP.String() } nics, err := net.Interfaces() if err != nil { return addr.IP.String() } for _, nic := range nics { if nic.Name == "docker0" || strings.HasPrefix(nic.Name, "vmnet") { continue } addrs, aerr := nic.Addrs() if aerr != nil { continue } for _, addr := range addrs { if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() { if ip.IP.To4() != nil { return ip.IP.String() } } } } return addr.IP.String() }
[ "func", "defaultIP", "(", "addr", "*", "net", ".", "TCPAddr", ")", "string", "{", "if", "!", "addr", ".", "IP", ".", "IsUnspecified", "(", ")", "{", "return", "addr", ".", "IP", ".", "String", "(", ")", "\n", "}", "\n\n", "nics", ",", "err", ":=", "net", ".", "Interfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "addr", ".", "IP", ".", "String", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "nic", ":=", "range", "nics", "{", "if", "nic", ".", "Name", "==", "\"", "\"", "||", "strings", ".", "HasPrefix", "(", "nic", ".", "Name", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "addrs", ",", "aerr", ":=", "nic", ".", "Addrs", "(", ")", "\n", "if", "aerr", "!=", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "if", "ip", ",", "ok", ":=", "addr", ".", "(", "*", "net", ".", "IPNet", ")", ";", "ok", "&&", "!", "ip", ".", "IP", ".", "IsLoopback", "(", ")", "{", "if", "ip", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "return", "ip", ".", "IP", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "addr", ".", "IP", ".", "String", "(", ")", "\n", "}" ]
// defaultIP returns addr.IP if specified, otherwise attempts to find a non-loopback ipv4 IP
[ "defaultIP", "returns", "addr", ".", "IP", "if", "specified", "otherwise", "attempts", "to", "find", "a", "non", "-", "loopback", "ipv4", "IP" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L561-L589
21,679
vmware/govmomi
simulator/simulator.go
NewServer
func (s *Service) NewServer() *Server { s.RegisterSDK(Map) mux := s.ServeMux vim := Map.Path + "/vimService" s.sdk[vim] = s.sdk[vim25.Path] mux.HandleFunc(vim, s.ServeSDK) mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) mux.HandleFunc(folderPrefix, s.ServeDatastore) mux.HandleFunc(nfcPrefix, ServeNFC) mux.HandleFunc("/about", s.About) ts := internal.NewUnstartedServer(mux, s.Listen) addr := ts.Listener.Addr().(*net.TCPAddr) port := strconv.Itoa(addr.Port) u := &url.URL{ Scheme: "http", Host: net.JoinHostPort(defaultIP(addr), port), Path: Map.Path, } if s.TLS != nil { u.Scheme += "s" } // Redirect clients to this http server, rather than HostSystem.Name Map.SessionManager().ServiceHostName = u.Host // Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example) m := Map.OptionManager() m.Setting = append(m.Setting, &types.OptionValue{ Key: "vcsim.server.url", Value: u.String(), }, ) u.User = url.UserPassword("user", "pass") if s.TLS != nil { ts.TLS = s.TLS ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate Map.SessionManager().TLSCert = func() string { return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0]) } ts.StartTLS() } else { ts.Start() } return &Server{ Server: ts, URL: u, } }
go
func (s *Service) NewServer() *Server { s.RegisterSDK(Map) mux := s.ServeMux vim := Map.Path + "/vimService" s.sdk[vim] = s.sdk[vim25.Path] mux.HandleFunc(vim, s.ServeSDK) mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) mux.HandleFunc(folderPrefix, s.ServeDatastore) mux.HandleFunc(nfcPrefix, ServeNFC) mux.HandleFunc("/about", s.About) ts := internal.NewUnstartedServer(mux, s.Listen) addr := ts.Listener.Addr().(*net.TCPAddr) port := strconv.Itoa(addr.Port) u := &url.URL{ Scheme: "http", Host: net.JoinHostPort(defaultIP(addr), port), Path: Map.Path, } if s.TLS != nil { u.Scheme += "s" } // Redirect clients to this http server, rather than HostSystem.Name Map.SessionManager().ServiceHostName = u.Host // Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example) m := Map.OptionManager() m.Setting = append(m.Setting, &types.OptionValue{ Key: "vcsim.server.url", Value: u.String(), }, ) u.User = url.UserPassword("user", "pass") if s.TLS != nil { ts.TLS = s.TLS ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate Map.SessionManager().TLSCert = func() string { return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0]) } ts.StartTLS() } else { ts.Start() } return &Server{ Server: ts, URL: u, } }
[ "func", "(", "s", "*", "Service", ")", "NewServer", "(", ")", "*", "Server", "{", "s", ".", "RegisterSDK", "(", "Map", ")", "\n\n", "mux", ":=", "s", ".", "ServeMux", "\n", "vim", ":=", "Map", ".", "Path", "+", "\"", "\"", "\n", "s", ".", "sdk", "[", "vim", "]", "=", "s", ".", "sdk", "[", "vim25", ".", "Path", "]", "\n", "mux", ".", "HandleFunc", "(", "vim", ",", "s", ".", "ServeSDK", ")", "\n", "mux", ".", "HandleFunc", "(", "Map", ".", "Path", "+", "\"", "\"", ",", "s", ".", "ServiceVersions", ")", "\n", "mux", ".", "HandleFunc", "(", "folderPrefix", ",", "s", ".", "ServeDatastore", ")", "\n", "mux", ".", "HandleFunc", "(", "nfcPrefix", ",", "ServeNFC", ")", "\n", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "s", ".", "About", ")", "\n\n", "ts", ":=", "internal", ".", "NewUnstartedServer", "(", "mux", ",", "s", ".", "Listen", ")", "\n", "addr", ":=", "ts", ".", "Listener", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "port", ":=", "strconv", ".", "Itoa", "(", "addr", ".", "Port", ")", "\n", "u", ":=", "&", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "net", ".", "JoinHostPort", "(", "defaultIP", "(", "addr", ")", ",", "port", ")", ",", "Path", ":", "Map", ".", "Path", ",", "}", "\n", "if", "s", ".", "TLS", "!=", "nil", "{", "u", ".", "Scheme", "+=", "\"", "\"", "\n", "}", "\n\n", "// Redirect clients to this http server, rather than HostSystem.Name", "Map", ".", "SessionManager", "(", ")", ".", "ServiceHostName", "=", "u", ".", "Host", "\n\n", "// Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example)", "m", ":=", "Map", ".", "OptionManager", "(", ")", "\n", "m", ".", "Setting", "=", "append", "(", "m", ".", "Setting", ",", "&", "types", ".", "OptionValue", "{", "Key", ":", "\"", "\"", ",", "Value", ":", "u", ".", "String", "(", ")", ",", "}", ",", ")", "\n\n", "u", ".", "User", "=", "url", ".", "UserPassword", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "s", ".", "TLS", "!=", "nil", "{", "ts", ".", "TLS", "=", "s", ".", "TLS", "\n", "ts", ".", "TLS", ".", "ClientAuth", "=", "tls", ".", "RequestClientCert", "// Used by SessionManager.LoginExtensionByCertificate", "\n", "Map", ".", "SessionManager", "(", ")", ".", "TLSCert", "=", "func", "(", ")", "string", "{", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "ts", ".", "TLS", ".", "Certificates", "[", "0", "]", ".", "Certificate", "[", "0", "]", ")", "\n", "}", "\n", "ts", ".", "StartTLS", "(", ")", "\n", "}", "else", "{", "ts", ".", "Start", "(", ")", "\n", "}", "\n\n", "return", "&", "Server", "{", "Server", ":", "ts", ",", "URL", ":", "u", ",", "}", "\n", "}" ]
// NewServer returns an http Server instance for the given service
[ "NewServer", "returns", "an", "http", "Server", "instance", "for", "the", "given", "service" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L592-L645
21,680
vmware/govmomi
simulator/simulator.go
Certificate
func (s *Server) Certificate() *x509.Certificate { // By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here: cert, _ := x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0]) return cert }
go
func (s *Server) Certificate() *x509.Certificate { // By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here: cert, _ := x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0]) return cert }
[ "func", "(", "s", "*", "Server", ")", "Certificate", "(", ")", "*", "x509", ".", "Certificate", "{", "// By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here:", "cert", ",", "_", ":=", "x509", ".", "ParseCertificate", "(", "s", ".", "TLS", ".", "Certificates", "[", "0", "]", ".", "Certificate", "[", "0", "]", ")", "\n", "return", "cert", "\n", "}" ]
// Certificate returns the TLS certificate for the Server if started with TLS enabled. // This method will panic if TLS is not enabled for the server.
[ "Certificate", "returns", "the", "TLS", "certificate", "for", "the", "Server", "if", "started", "with", "TLS", "enabled", ".", "This", "method", "will", "panic", "if", "TLS", "is", "not", "enabled", "for", "the", "server", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L649-L653
21,681
vmware/govmomi
simulator/simulator.go
proxy
func (s *Server) proxy(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodConnect { http.Error(w, "", http.StatusMethodNotAllowed) return } dst, err := net.Dial("tcp", s.URL.Host) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.WriteHeader(http.StatusOK) src, _, err := w.(http.Hijacker).Hijack() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } go io.Copy(src, dst) go func() { _, _ = io.Copy(dst, src) _ = dst.Close() _ = src.Close() }() }
go
func (s *Server) proxy(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodConnect { http.Error(w, "", http.StatusMethodNotAllowed) return } dst, err := net.Dial("tcp", s.URL.Host) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.WriteHeader(http.StatusOK) src, _, err := w.(http.Hijacker).Hijack() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } go io.Copy(src, dst) go func() { _, _ = io.Copy(dst, src) _ = dst.Close() _ = src.Close() }() }
[ "func", "(", "s", "*", "Server", ")", "proxy", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "!=", "http", ".", "MethodConnect", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusMethodNotAllowed", ")", "\n", "return", "\n", "}", "\n\n", "dst", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "s", ".", "URL", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadGateway", ")", "\n", "return", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n\n", "src", ",", "_", ",", "err", ":=", "w", ".", "(", "http", ".", "Hijacker", ")", ".", "Hijack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n\n", "go", "io", ".", "Copy", "(", "src", ",", "dst", ")", "\n", "go", "func", "(", ")", "{", "_", ",", "_", "=", "io", ".", "Copy", "(", "dst", ",", "src", ")", "\n", "_", "=", "dst", ".", "Close", "(", ")", "\n", "_", "=", "src", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// proxy tunnels SDK requests
[ "proxy", "tunnels", "SDK", "requests" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L681-L706
21,682
vmware/govmomi
simulator/simulator.go
StartTunnel
func (s *Server) StartTunnel() error { tunnel := &http.Server{ Addr: fmt.Sprintf("%s:%d", s.URL.Hostname(), s.Tunnel), Handler: http.HandlerFunc(s.proxy), } l, err := net.Listen("tcp", tunnel.Addr) if err != nil { return err } if s.Tunnel == 0 { s.Tunnel = l.Addr().(*net.TCPAddr).Port } // Set client proxy port (defaults to vCenter host port 80 in real life) q := s.URL.Query() q.Set("GOVMOMI_TUNNEL_PROXY_PORT", strconv.Itoa(s.Tunnel)) s.URL.RawQuery = q.Encode() go tunnel.Serve(l) return nil }
go
func (s *Server) StartTunnel() error { tunnel := &http.Server{ Addr: fmt.Sprintf("%s:%d", s.URL.Hostname(), s.Tunnel), Handler: http.HandlerFunc(s.proxy), } l, err := net.Listen("tcp", tunnel.Addr) if err != nil { return err } if s.Tunnel == 0 { s.Tunnel = l.Addr().(*net.TCPAddr).Port } // Set client proxy port (defaults to vCenter host port 80 in real life) q := s.URL.Query() q.Set("GOVMOMI_TUNNEL_PROXY_PORT", strconv.Itoa(s.Tunnel)) s.URL.RawQuery = q.Encode() go tunnel.Serve(l) return nil }
[ "func", "(", "s", "*", "Server", ")", "StartTunnel", "(", ")", "error", "{", "tunnel", ":=", "&", "http", ".", "Server", "{", "Addr", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "URL", ".", "Hostname", "(", ")", ",", "s", ".", "Tunnel", ")", ",", "Handler", ":", "http", ".", "HandlerFunc", "(", "s", ".", "proxy", ")", ",", "}", "\n\n", "l", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "tunnel", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "s", ".", "Tunnel", "==", "0", "{", "s", ".", "Tunnel", "=", "l", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", ".", "Port", "\n", "}", "\n\n", "// Set client proxy port (defaults to vCenter host port 80 in real life)", "q", ":=", "s", ".", "URL", ".", "Query", "(", ")", "\n", "q", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "s", ".", "Tunnel", ")", ")", "\n", "s", ".", "URL", ".", "RawQuery", "=", "q", ".", "Encode", "(", ")", "\n\n", "go", "tunnel", ".", "Serve", "(", "l", ")", "\n\n", "return", "nil", "\n", "}" ]
// StartTunnel runs an HTTP proxy for tunneling SDK requests that require TLS client certificate authentication.
[ "StartTunnel", "runs", "an", "HTTP", "proxy", "for", "tunneling", "SDK", "requests", "that", "require", "TLS", "client", "certificate", "authentication", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L709-L732
21,683
vmware/govmomi
simulator/simulator.go
UnmarshalBody
func UnmarshalBody(typeFunc func(string) (reflect.Type, bool), data []byte) (*Method, error) { body := &Element{typeFunc: typeFunc} req := soap.Envelope{ Header: &soap.Header{ Security: new(Element), }, Body: body, } err := xml.Unmarshal(data, &req) if err != nil { return nil, fmt.Errorf("xml.Unmarshal: %s", err) } var start xml.StartElement var ok bool decoder := body.decoder() for { tok, derr := decoder.Token() if derr != nil { return nil, fmt.Errorf("decoding: %s", derr) } if start, ok = tok.(xml.StartElement); ok { break } } if !ok { return nil, fmt.Errorf("decoding: method token not found") } kind := start.Name.Local rtype, ok := typeFunc(kind) if !ok { return nil, fmt.Errorf("no vmomi type defined for '%s'", kind) } val := reflect.New(rtype).Interface() err = decoder.DecodeElement(val, &start) if err != nil { return nil, fmt.Errorf("decoding %s: %s", kind, err) } method := &Method{Name: kind, Header: *req.Header, Body: val} field := reflect.ValueOf(val).Elem().FieldByName("This") method.This = field.Interface().(types.ManagedObjectReference) return method, nil }
go
func UnmarshalBody(typeFunc func(string) (reflect.Type, bool), data []byte) (*Method, error) { body := &Element{typeFunc: typeFunc} req := soap.Envelope{ Header: &soap.Header{ Security: new(Element), }, Body: body, } err := xml.Unmarshal(data, &req) if err != nil { return nil, fmt.Errorf("xml.Unmarshal: %s", err) } var start xml.StartElement var ok bool decoder := body.decoder() for { tok, derr := decoder.Token() if derr != nil { return nil, fmt.Errorf("decoding: %s", derr) } if start, ok = tok.(xml.StartElement); ok { break } } if !ok { return nil, fmt.Errorf("decoding: method token not found") } kind := start.Name.Local rtype, ok := typeFunc(kind) if !ok { return nil, fmt.Errorf("no vmomi type defined for '%s'", kind) } val := reflect.New(rtype).Interface() err = decoder.DecodeElement(val, &start) if err != nil { return nil, fmt.Errorf("decoding %s: %s", kind, err) } method := &Method{Name: kind, Header: *req.Header, Body: val} field := reflect.ValueOf(val).Elem().FieldByName("This") method.This = field.Interface().(types.ManagedObjectReference) return method, nil }
[ "func", "UnmarshalBody", "(", "typeFunc", "func", "(", "string", ")", "(", "reflect", ".", "Type", ",", "bool", ")", ",", "data", "[", "]", "byte", ")", "(", "*", "Method", ",", "error", ")", "{", "body", ":=", "&", "Element", "{", "typeFunc", ":", "typeFunc", "}", "\n", "req", ":=", "soap", ".", "Envelope", "{", "Header", ":", "&", "soap", ".", "Header", "{", "Security", ":", "new", "(", "Element", ")", ",", "}", ",", "Body", ":", "body", ",", "}", "\n\n", "err", ":=", "xml", ".", "Unmarshal", "(", "data", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "start", "xml", ".", "StartElement", "\n", "var", "ok", "bool", "\n", "decoder", ":=", "body", ".", "decoder", "(", ")", "\n\n", "for", "{", "tok", ",", "derr", ":=", "decoder", ".", "Token", "(", ")", "\n", "if", "derr", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "derr", ")", "\n", "}", "\n", "if", "start", ",", "ok", "=", "tok", ".", "(", "xml", ".", "StartElement", ")", ";", "ok", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "kind", ":=", "start", ".", "Name", ".", "Local", "\n", "rtype", ",", "ok", ":=", "typeFunc", "(", "kind", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "kind", ")", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "New", "(", "rtype", ")", ".", "Interface", "(", ")", "\n\n", "err", "=", "decoder", ".", "DecodeElement", "(", "val", ",", "&", "start", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "kind", ",", "err", ")", "\n", "}", "\n\n", "method", ":=", "&", "Method", "{", "Name", ":", "kind", ",", "Header", ":", "*", "req", ".", "Header", ",", "Body", ":", "val", "}", "\n\n", "field", ":=", "reflect", ".", "ValueOf", "(", "val", ")", ".", "Elem", "(", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n\n", "method", ".", "This", "=", "field", ".", "Interface", "(", ")", ".", "(", "types", ".", "ManagedObjectReference", ")", "\n\n", "return", "method", ",", "nil", "\n", "}" ]
// UnmarshalBody extracts the Body from a soap.Envelope and unmarshals to the corresponding govmomi type
[ "UnmarshalBody", "extracts", "the", "Body", "from", "a", "soap", ".", "Envelope", "and", "unmarshals", "to", "the", "corresponding", "govmomi", "type" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L786-L838
21,684
vmware/govmomi
govc/host/autostart/info.go
vmPaths
func (r *infoResult) vmPaths() (map[string]string, error) { ctx := context.TODO() paths := make(map[string]string) for _, info := range r.mhas.Config.PowerInfo { mes, err := mo.Ancestors(ctx, r.client, r.client.ServiceContent.PropertyCollector, info.Key) if err != nil { return nil, err } path := "" for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } path += "/" + me.Name } paths[info.Key.Value] = path } return paths, nil }
go
func (r *infoResult) vmPaths() (map[string]string, error) { ctx := context.TODO() paths := make(map[string]string) for _, info := range r.mhas.Config.PowerInfo { mes, err := mo.Ancestors(ctx, r.client, r.client.ServiceContent.PropertyCollector, info.Key) if err != nil { return nil, err } path := "" for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } path += "/" + me.Name } paths[info.Key.Value] = path } return paths, nil }
[ "func", "(", "r", "*", "infoResult", ")", "vmPaths", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "ctx", ":=", "context", ".", "TODO", "(", ")", "\n", "paths", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "info", ":=", "range", "r", ".", "mhas", ".", "Config", ".", "PowerInfo", "{", "mes", ",", "err", ":=", "mo", ".", "Ancestors", "(", "ctx", ",", "r", ".", "client", ",", "r", ".", "client", ".", "ServiceContent", ".", "PropertyCollector", ",", "info", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "path", ":=", "\"", "\"", "\n", "for", "_", ",", "me", ":=", "range", "mes", "{", "// Skip root entity in building inventory path.", "if", "me", ".", "Parent", "==", "nil", "{", "continue", "\n", "}", "\n", "path", "+=", "\"", "\"", "+", "me", ".", "Name", "\n", "}", "\n\n", "paths", "[", "info", ".", "Key", ".", "Value", "]", "=", "path", "\n", "}", "\n\n", "return", "paths", ",", "nil", "\n", "}" ]
// vmPaths resolves the paths for the VMs in the result.
[ "vmPaths", "resolves", "the", "paths", "for", "the", "VMs", "in", "the", "result", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/autostart/info.go#L86-L108
21,685
vmware/govmomi
simulator/custom_fields_manager.go
entitiesFieldRemove
func entitiesFieldRemove(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { entity.AvailableField = append(aFields[:i], aFields[i+1:]...) break } } values := e.Entity().Value for i, value := range values { if value.(*types.CustomFieldStringValue).Key == field.Key { entity.Value = append(values[:i], values[i+1:]...) break } } cValues := e.Entity().CustomValue for i, cValue := range cValues { if cValue.(*types.CustomFieldStringValue).Key == field.Key { entity.CustomValue = append(cValues[:i], cValues[i+1:]...) break } } }) } }
go
func entitiesFieldRemove(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { entity.AvailableField = append(aFields[:i], aFields[i+1:]...) break } } values := e.Entity().Value for i, value := range values { if value.(*types.CustomFieldStringValue).Key == field.Key { entity.Value = append(values[:i], values[i+1:]...) break } } cValues := e.Entity().CustomValue for i, cValue := range cValues { if cValue.(*types.CustomFieldStringValue).Key == field.Key { entity.CustomValue = append(cValues[:i], cValues[i+1:]...) break } } }) } }
[ "func", "entitiesFieldRemove", "(", "field", "types", ".", "CustomFieldDef", ")", "{", "entities", ":=", "Map", ".", "All", "(", "field", ".", "ManagedObjectType", ")", "\n", "for", "_", ",", "e", ":=", "range", "entities", "{", "entity", ":=", "e", ".", "Entity", "(", ")", "\n", "Map", ".", "WithLock", "(", "entity", ",", "func", "(", ")", "{", "aFields", ":=", "entity", ".", "AvailableField", "\n", "for", "i", ",", "aField", ":=", "range", "aFields", "{", "if", "aField", ".", "Key", "==", "field", ".", "Key", "{", "entity", ".", "AvailableField", "=", "append", "(", "aFields", "[", ":", "i", "]", ",", "aFields", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "values", ":=", "e", ".", "Entity", "(", ")", ".", "Value", "\n", "for", "i", ",", "value", ":=", "range", "values", "{", "if", "value", ".", "(", "*", "types", ".", "CustomFieldStringValue", ")", ".", "Key", "==", "field", ".", "Key", "{", "entity", ".", "Value", "=", "append", "(", "values", "[", ":", "i", "]", ",", "values", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "cValues", ":=", "e", ".", "Entity", "(", ")", ".", "CustomValue", "\n", "for", "i", ",", "cValue", ":=", "range", "cValues", "{", "if", "cValue", ".", "(", "*", "types", ".", "CustomFieldStringValue", ")", ".", "Key", "==", "field", ".", "Key", "{", "entity", ".", "CustomValue", "=", "append", "(", "cValues", "[", ":", "i", "]", ",", "cValues", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Iterates through all entities of passed field type; // Removes found field from their custom field properties.
[ "Iterates", "through", "all", "entities", "of", "passed", "field", "type", ";", "Removes", "found", "field", "from", "their", "custom", "field", "properties", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/custom_fields_manager.go#L41-L71
21,686
vmware/govmomi
simulator/custom_fields_manager.go
entitiesFieldRename
func entitiesFieldRename(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { aFields[i].Name = field.Name break } } }) } }
go
func entitiesFieldRename(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { aFields[i].Name = field.Name break } } }) } }
[ "func", "entitiesFieldRename", "(", "field", "types", ".", "CustomFieldDef", ")", "{", "entities", ":=", "Map", ".", "All", "(", "field", ".", "ManagedObjectType", ")", "\n", "for", "_", ",", "e", ":=", "range", "entities", "{", "entity", ":=", "e", ".", "Entity", "(", ")", "\n", "Map", ".", "WithLock", "(", "entity", ",", "func", "(", ")", "{", "aFields", ":=", "entity", ".", "AvailableField", "\n", "for", "i", ",", "aField", ":=", "range", "aFields", "{", "if", "aField", ".", "Key", "==", "field", ".", "Key", "{", "aFields", "[", "i", "]", ".", "Name", "=", "field", ".", "Name", "\n", "break", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Iterates through all entities of passed field type; // Renames found field in entity's AvailableField property.
[ "Iterates", "through", "all", "entities", "of", "passed", "field", "type", ";", "Renames", "found", "field", "in", "entity", "s", "AvailableField", "property", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/custom_fields_manager.go#L75-L89
21,687
vmware/govmomi
toolbox/hgfs/archive.go
Stat
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error) { switch u.Query().Get("format") { case "", "tar", "tgz": // ok default: log.Printf("unknown archive format: %q", u) return nil, vix.Error(vix.InvalidArg) } return &archive{ name: u.Path, size: math.MaxInt64, }, nil }
go
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error) { switch u.Query().Get("format") { case "", "tar", "tgz": // ok default: log.Printf("unknown archive format: %q", u) return nil, vix.Error(vix.InvalidArg) } return &archive{ name: u.Path, size: math.MaxInt64, }, nil }
[ "func", "(", "*", "ArchiveHandler", ")", "Stat", "(", "u", "*", "url", ".", "URL", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "switch", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "// ok", "default", ":", "log", ".", "Printf", "(", "\"", "\"", ",", "u", ")", "\n", "return", "nil", ",", "vix", ".", "Error", "(", "vix", ".", "InvalidArg", ")", "\n", "}", "\n\n", "return", "&", "archive", "{", "name", ":", "u", ".", "Path", ",", "size", ":", "math", ".", "MaxInt64", ",", "}", ",", "nil", "\n", "}" ]
// Stat implements FileHandler.Stat
[ "Stat", "implements", "FileHandler", ".", "Stat" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L56-L69
21,688
vmware/govmomi
toolbox/hgfs/archive.go
Open
func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error) { switch mode { case OpenModeReadOnly: return h.newArchiveFromGuest(u) case OpenModeWriteOnly: return h.newArchiveToGuest(u) default: return nil, os.ErrNotExist } }
go
func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error) { switch mode { case OpenModeReadOnly: return h.newArchiveFromGuest(u) case OpenModeWriteOnly: return h.newArchiveToGuest(u) default: return nil, os.ErrNotExist } }
[ "func", "(", "h", "*", "ArchiveHandler", ")", "Open", "(", "u", "*", "url", ".", "URL", ",", "mode", "int32", ")", "(", "File", ",", "error", ")", "{", "switch", "mode", "{", "case", "OpenModeReadOnly", ":", "return", "h", ".", "newArchiveFromGuest", "(", "u", ")", "\n", "case", "OpenModeWriteOnly", ":", "return", "h", ".", "newArchiveToGuest", "(", "u", ")", "\n", "default", ":", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n", "}" ]
// Open implements FileHandler.Open
[ "Open", "implements", "FileHandler", ".", "Open" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L72-L81
21,689
vmware/govmomi
toolbox/hgfs/archive.go
newArchiveFromGuest
func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error) { r, w := io.Pipe() a := &archive{ name: u.Path, done: r.Close, Reader: r, Writer: w, } var z io.Writer = w var c io.Closer = ioutil.NopCloser(nil) switch u.Query().Get("format") { case "tgz": gz := gzip.NewWriter(w) z = gz c = gz } tw := tar.NewWriter(z) go func() { err := h.Write(u, tw) _ = tw.Close() _ = c.Close() if gzipTrailer { _, _ = w.Write(gzipHeader) } _ = w.CloseWithError(err) }() return a, nil }
go
func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error) { r, w := io.Pipe() a := &archive{ name: u.Path, done: r.Close, Reader: r, Writer: w, } var z io.Writer = w var c io.Closer = ioutil.NopCloser(nil) switch u.Query().Get("format") { case "tgz": gz := gzip.NewWriter(w) z = gz c = gz } tw := tar.NewWriter(z) go func() { err := h.Write(u, tw) _ = tw.Close() _ = c.Close() if gzipTrailer { _, _ = w.Write(gzipHeader) } _ = w.CloseWithError(err) }() return a, nil }
[ "func", "(", "h", "*", "ArchiveHandler", ")", "newArchiveFromGuest", "(", "u", "*", "url", ".", "URL", ")", "(", "File", ",", "error", ")", "{", "r", ",", "w", ":=", "io", ".", "Pipe", "(", ")", "\n\n", "a", ":=", "&", "archive", "{", "name", ":", "u", ".", "Path", ",", "done", ":", "r", ".", "Close", ",", "Reader", ":", "r", ",", "Writer", ":", "w", ",", "}", "\n\n", "var", "z", "io", ".", "Writer", "=", "w", "\n", "var", "c", "io", ".", "Closer", "=", "ioutil", ".", "NopCloser", "(", "nil", ")", "\n\n", "switch", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ":", "gz", ":=", "gzip", ".", "NewWriter", "(", "w", ")", "\n", "z", "=", "gz", "\n", "c", "=", "gz", "\n", "}", "\n\n", "tw", ":=", "tar", ".", "NewWriter", "(", "z", ")", "\n\n", "go", "func", "(", ")", "{", "err", ":=", "h", ".", "Write", "(", "u", ",", "tw", ")", "\n\n", "_", "=", "tw", ".", "Close", "(", ")", "\n", "_", "=", "c", ".", "Close", "(", ")", "\n", "if", "gzipTrailer", "{", "_", ",", "_", "=", "w", ".", "Write", "(", "gzipHeader", ")", "\n", "}", "\n", "_", "=", "w", ".", "CloseWithError", "(", "err", ")", "\n", "}", "(", ")", "\n\n", "return", "a", ",", "nil", "\n", "}" ]
// newArchiveFromGuest returns an hgfs.File implementation to read a directory as a gzip'd tar.
[ "newArchiveFromGuest", "returns", "an", "hgfs", ".", "File", "implementation", "to", "read", "a", "directory", "as", "a", "gzip", "d", "tar", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L131-L165
21,690
vmware/govmomi
toolbox/hgfs/archive.go
newArchiveToGuest
func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error) { r, w := io.Pipe() buf := bufio.NewReader(r) a := &archive{ name: u.Path, Reader: buf, Writer: w, } var cerr error var wg sync.WaitGroup a.done = func() error { _ = w.Close() // We need to wait for unpack to finish to complete its work // and to propagate the error if any to Close. wg.Wait() return cerr } wg.Add(1) go func() { defer wg.Done() c := func() error { // Drain the pipe of tar trailer data (two null blocks) if cerr == nil { _, _ = io.Copy(ioutil.Discard, a.Reader) } return nil } header, _ := buf.Peek(len(gzipHeader)) if bytes.Equal(header, gzipHeader) { gz, err := gzip.NewReader(a.Reader) if err != nil { _ = r.CloseWithError(err) cerr = err return } c = gz.Close a.Reader = gz } tr := tar.NewReader(a.Reader) cerr = h.Read(u, tr) _ = c() _ = r.CloseWithError(cerr) }() return a, nil }
go
func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error) { r, w := io.Pipe() buf := bufio.NewReader(r) a := &archive{ name: u.Path, Reader: buf, Writer: w, } var cerr error var wg sync.WaitGroup a.done = func() error { _ = w.Close() // We need to wait for unpack to finish to complete its work // and to propagate the error if any to Close. wg.Wait() return cerr } wg.Add(1) go func() { defer wg.Done() c := func() error { // Drain the pipe of tar trailer data (two null blocks) if cerr == nil { _, _ = io.Copy(ioutil.Discard, a.Reader) } return nil } header, _ := buf.Peek(len(gzipHeader)) if bytes.Equal(header, gzipHeader) { gz, err := gzip.NewReader(a.Reader) if err != nil { _ = r.CloseWithError(err) cerr = err return } c = gz.Close a.Reader = gz } tr := tar.NewReader(a.Reader) cerr = h.Read(u, tr) _ = c() _ = r.CloseWithError(cerr) }() return a, nil }
[ "func", "(", "h", "*", "ArchiveHandler", ")", "newArchiveToGuest", "(", "u", "*", "url", ".", "URL", ")", "(", "File", ",", "error", ")", "{", "r", ",", "w", ":=", "io", ".", "Pipe", "(", ")", "\n\n", "buf", ":=", "bufio", ".", "NewReader", "(", "r", ")", "\n\n", "a", ":=", "&", "archive", "{", "name", ":", "u", ".", "Path", ",", "Reader", ":", "buf", ",", "Writer", ":", "w", ",", "}", "\n\n", "var", "cerr", "error", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n\n", "a", ".", "done", "=", "func", "(", ")", "error", "{", "_", "=", "w", ".", "Close", "(", ")", "\n", "// We need to wait for unpack to finish to complete its work", "// and to propagate the error if any to Close.", "wg", ".", "Wait", "(", ")", "\n", "return", "cerr", "\n", "}", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "c", ":=", "func", "(", ")", "error", "{", "// Drain the pipe of tar trailer data (two null blocks)", "if", "cerr", "==", "nil", "{", "_", ",", "_", "=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "a", ".", "Reader", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "header", ",", "_", ":=", "buf", ".", "Peek", "(", "len", "(", "gzipHeader", ")", ")", "\n\n", "if", "bytes", ".", "Equal", "(", "header", ",", "gzipHeader", ")", "{", "gz", ",", "err", ":=", "gzip", ".", "NewReader", "(", "a", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "_", "=", "r", ".", "CloseWithError", "(", "err", ")", "\n", "cerr", "=", "err", "\n", "return", "\n", "}", "\n\n", "c", "=", "gz", ".", "Close", "\n", "a", ".", "Reader", "=", "gz", "\n", "}", "\n\n", "tr", ":=", "tar", ".", "NewReader", "(", "a", ".", "Reader", ")", "\n\n", "cerr", "=", "h", ".", "Read", "(", "u", ",", "tr", ")", "\n\n", "_", "=", "c", "(", ")", "\n", "_", "=", "r", ".", "CloseWithError", "(", "cerr", ")", "\n", "}", "(", ")", "\n\n", "return", "a", ",", "nil", "\n", "}" ]
// newArchiveToGuest returns an hgfs.File implementation to expand a gzip'd tar into a directory.
[ "newArchiveToGuest", "returns", "an", "hgfs", ".", "File", "implementation", "to", "expand", "a", "gzip", "d", "tar", "into", "a", "directory", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L168-L225
21,691
vmware/govmomi
toolbox/hgfs/archive.go
archiveRead
func archiveRead(u *url.URL, tr *tar.Reader) error { for { header, err := tr.Next() if err != nil { if err == io.EOF { return nil } return err } name := filepath.Join(u.Path, header.Name) mode := os.FileMode(header.Mode) switch header.Typeflag { case tar.TypeDir: err = os.MkdirAll(name, mode) case tar.TypeReg: _ = os.MkdirAll(filepath.Dir(name), 0750) var f *os.File f, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode) if err == nil { _, cerr := io.Copy(f, tr) err = f.Close() if cerr != nil { err = cerr } } case tar.TypeSymlink: err = os.Symlink(header.Linkname, name) } // TODO: Uid/Gid may not be meaningful here without some mapping. // The other option to consider would be making use of the guest auth user ID. // os.Lchown(name, header.Uid, header.Gid) if err != nil { return err } } }
go
func archiveRead(u *url.URL, tr *tar.Reader) error { for { header, err := tr.Next() if err != nil { if err == io.EOF { return nil } return err } name := filepath.Join(u.Path, header.Name) mode := os.FileMode(header.Mode) switch header.Typeflag { case tar.TypeDir: err = os.MkdirAll(name, mode) case tar.TypeReg: _ = os.MkdirAll(filepath.Dir(name), 0750) var f *os.File f, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode) if err == nil { _, cerr := io.Copy(f, tr) err = f.Close() if cerr != nil { err = cerr } } case tar.TypeSymlink: err = os.Symlink(header.Linkname, name) } // TODO: Uid/Gid may not be meaningful here without some mapping. // The other option to consider would be making use of the guest auth user ID. // os.Lchown(name, header.Uid, header.Gid) if err != nil { return err } } }
[ "func", "archiveRead", "(", "u", "*", "url", ".", "URL", ",", "tr", "*", "tar", ".", "Reader", ")", "error", "{", "for", "{", "header", ",", "err", ":=", "tr", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "name", ":=", "filepath", ".", "Join", "(", "u", ".", "Path", ",", "header", ".", "Name", ")", "\n", "mode", ":=", "os", ".", "FileMode", "(", "header", ".", "Mode", ")", "\n\n", "switch", "header", ".", "Typeflag", "{", "case", "tar", ".", "TypeDir", ":", "err", "=", "os", ".", "MkdirAll", "(", "name", ",", "mode", ")", "\n", "case", "tar", ".", "TypeReg", ":", "_", "=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "name", ")", ",", "0750", ")", "\n\n", "var", "f", "*", "os", ".", "File", "\n\n", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", ",", "mode", ")", "\n", "if", "err", "==", "nil", "{", "_", ",", "cerr", ":=", "io", ".", "Copy", "(", "f", ",", "tr", ")", "\n", "err", "=", "f", ".", "Close", "(", ")", "\n", "if", "cerr", "!=", "nil", "{", "err", "=", "cerr", "\n", "}", "\n", "}", "\n", "case", "tar", ".", "TypeSymlink", ":", "err", "=", "os", ".", "Symlink", "(", "header", ".", "Linkname", ",", "name", ")", "\n", "}", "\n\n", "// TODO: Uid/Gid may not be meaningful here without some mapping.", "// The other option to consider would be making use of the guest auth user ID.", "// os.Lchown(name, header.Uid, header.Gid)", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// archiveRead writes the contents of the given tar.Reader to the given directory.
[ "archiveRead", "writes", "the", "contents", "of", "the", "given", "tar", ".", "Reader", "to", "the", "given", "directory", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L232-L273
21,692
vmware/govmomi
toolbox/hgfs/archive.go
archiveWrite
func archiveWrite(u *url.URL, tw *tar.Writer) error { info, err := os.Stat(u.Path) if err != nil { return err } // Note that the VMX will trim any trailing slash. For example: // "/foo/bar/?prefix=bar/" will end up here as "/foo/bar/?prefix=bar" // Escape to avoid this: "/for/bar/?prefix=bar%2F" prefix := u.Query().Get("prefix") dir := u.Path f := func(file string, fi os.FileInfo, err error) error { if err != nil { return filepath.SkipDir } name := strings.TrimPrefix(file, dir) name = strings.TrimPrefix(name, "/") if name == "" { return nil // this is u.Path itself (which may or may not have a trailing "/") } if prefix != "" { name = prefix + name } header, _ := tar.FileInfoHeader(fi, name) header.Name = name if header.Typeflag == tar.TypeDir { header.Name += "/" } var f *os.File if header.Typeflag == tar.TypeReg && fi.Size() != 0 { f, err = os.Open(filepath.Clean(file)) if err != nil { if os.IsPermission(err) { return nil } return err } } _ = tw.WriteHeader(header) if f != nil { _, err = io.Copy(tw, f) _ = f.Close() } return err } if info.IsDir() { return filepath.Walk(u.Path, f) } dir = filepath.Dir(dir) return f(u.Path, info, nil) }
go
func archiveWrite(u *url.URL, tw *tar.Writer) error { info, err := os.Stat(u.Path) if err != nil { return err } // Note that the VMX will trim any trailing slash. For example: // "/foo/bar/?prefix=bar/" will end up here as "/foo/bar/?prefix=bar" // Escape to avoid this: "/for/bar/?prefix=bar%2F" prefix := u.Query().Get("prefix") dir := u.Path f := func(file string, fi os.FileInfo, err error) error { if err != nil { return filepath.SkipDir } name := strings.TrimPrefix(file, dir) name = strings.TrimPrefix(name, "/") if name == "" { return nil // this is u.Path itself (which may or may not have a trailing "/") } if prefix != "" { name = prefix + name } header, _ := tar.FileInfoHeader(fi, name) header.Name = name if header.Typeflag == tar.TypeDir { header.Name += "/" } var f *os.File if header.Typeflag == tar.TypeReg && fi.Size() != 0 { f, err = os.Open(filepath.Clean(file)) if err != nil { if os.IsPermission(err) { return nil } return err } } _ = tw.WriteHeader(header) if f != nil { _, err = io.Copy(tw, f) _ = f.Close() } return err } if info.IsDir() { return filepath.Walk(u.Path, f) } dir = filepath.Dir(dir) return f(u.Path, info, nil) }
[ "func", "archiveWrite", "(", "u", "*", "url", ".", "URL", ",", "tw", "*", "tar", ".", "Writer", ")", "error", "{", "info", ",", "err", ":=", "os", ".", "Stat", "(", "u", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Note that the VMX will trim any trailing slash. For example:", "// \"/foo/bar/?prefix=bar/\" will end up here as \"/foo/bar/?prefix=bar\"", "// Escape to avoid this: \"/for/bar/?prefix=bar%2F\"", "prefix", ":=", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n\n", "dir", ":=", "u", ".", "Path", "\n\n", "f", ":=", "func", "(", "file", "string", ",", "fi", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n\n", "name", ":=", "strings", ".", "TrimPrefix", "(", "file", ",", "dir", ")", "\n", "name", "=", "strings", ".", "TrimPrefix", "(", "name", ",", "\"", "\"", ")", "\n\n", "if", "name", "==", "\"", "\"", "{", "return", "nil", "// this is u.Path itself (which may or may not have a trailing \"/\")", "\n", "}", "\n\n", "if", "prefix", "!=", "\"", "\"", "{", "name", "=", "prefix", "+", "name", "\n", "}", "\n\n", "header", ",", "_", ":=", "tar", ".", "FileInfoHeader", "(", "fi", ",", "name", ")", "\n\n", "header", ".", "Name", "=", "name", "\n\n", "if", "header", ".", "Typeflag", "==", "tar", ".", "TypeDir", "{", "header", ".", "Name", "+=", "\"", "\"", "\n", "}", "\n\n", "var", "f", "*", "os", ".", "File", "\n\n", "if", "header", ".", "Typeflag", "==", "tar", ".", "TypeReg", "&&", "fi", ".", "Size", "(", ")", "!=", "0", "{", "f", ",", "err", "=", "os", ".", "Open", "(", "filepath", ".", "Clean", "(", "file", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsPermission", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "_", "=", "tw", ".", "WriteHeader", "(", "header", ")", "\n\n", "if", "f", "!=", "nil", "{", "_", ",", "err", "=", "io", ".", "Copy", "(", "tw", ",", "f", ")", "\n", "_", "=", "f", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "filepath", ".", "Walk", "(", "u", ".", "Path", ",", "f", ")", "\n", "}", "\n\n", "dir", "=", "filepath", ".", "Dir", "(", "dir", ")", "\n\n", "return", "f", "(", "u", ".", "Path", ",", "info", ",", "nil", ")", "\n", "}" ]
// archiveWrite writes the contents of the given source directory to the given tar.Writer.
[ "archiveWrite", "writes", "the", "contents", "of", "the", "given", "source", "directory", "to", "the", "given", "tar", ".", "Writer", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L276-L342
21,693
vmware/govmomi
property/filter.go
MatchProperty
func (f Filter) MatchProperty(prop types.DynamicProperty) bool { match, ok := f[prop.Name] if !ok { return false } if match == prop.Val { return true } ptype := reflect.TypeOf(prop.Val) if strings.HasPrefix(ptype.Name(), "ArrayOf") { pval := reflect.ValueOf(prop.Val).Field(0) for i := 0; i < pval.Len(); i++ { prop.Val = pval.Index(i).Interface() if f.MatchProperty(prop) { return true } } return false } if reflect.TypeOf(match) != ptype { s, ok := match.(string) if !ok { return false } // convert if we can switch prop.Val.(type) { case bool: match, _ = strconv.ParseBool(s) case int16: x, _ := strconv.ParseInt(s, 10, 16) match = int16(x) case int32: x, _ := strconv.ParseInt(s, 10, 32) match = int32(x) case int64: match, _ = strconv.ParseInt(s, 10, 64) case float32: x, _ := strconv.ParseFloat(s, 32) match = float32(x) case float64: match, _ = strconv.ParseFloat(s, 64) case fmt.Stringer: prop.Val = prop.Val.(fmt.Stringer).String() default: if ptype.Kind() != reflect.String { return false } // An enum type we can convert to a string type prop.Val = reflect.ValueOf(prop.Val).String() } } switch pval := prop.Val.(type) { case string: s := match.(string) if s == "*" { return true // TODO: path.Match fails if s contains a '/' } m, _ := path.Match(s, pval) return m default: return reflect.DeepEqual(match, pval) } }
go
func (f Filter) MatchProperty(prop types.DynamicProperty) bool { match, ok := f[prop.Name] if !ok { return false } if match == prop.Val { return true } ptype := reflect.TypeOf(prop.Val) if strings.HasPrefix(ptype.Name(), "ArrayOf") { pval := reflect.ValueOf(prop.Val).Field(0) for i := 0; i < pval.Len(); i++ { prop.Val = pval.Index(i).Interface() if f.MatchProperty(prop) { return true } } return false } if reflect.TypeOf(match) != ptype { s, ok := match.(string) if !ok { return false } // convert if we can switch prop.Val.(type) { case bool: match, _ = strconv.ParseBool(s) case int16: x, _ := strconv.ParseInt(s, 10, 16) match = int16(x) case int32: x, _ := strconv.ParseInt(s, 10, 32) match = int32(x) case int64: match, _ = strconv.ParseInt(s, 10, 64) case float32: x, _ := strconv.ParseFloat(s, 32) match = float32(x) case float64: match, _ = strconv.ParseFloat(s, 64) case fmt.Stringer: prop.Val = prop.Val.(fmt.Stringer).String() default: if ptype.Kind() != reflect.String { return false } // An enum type we can convert to a string type prop.Val = reflect.ValueOf(prop.Val).String() } } switch pval := prop.Val.(type) { case string: s := match.(string) if s == "*" { return true // TODO: path.Match fails if s contains a '/' } m, _ := path.Match(s, pval) return m default: return reflect.DeepEqual(match, pval) } }
[ "func", "(", "f", "Filter", ")", "MatchProperty", "(", "prop", "types", ".", "DynamicProperty", ")", "bool", "{", "match", ",", "ok", ":=", "f", "[", "prop", ".", "Name", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "if", "match", "==", "prop", ".", "Val", "{", "return", "true", "\n", "}", "\n\n", "ptype", ":=", "reflect", ".", "TypeOf", "(", "prop", ".", "Val", ")", "\n\n", "if", "strings", ".", "HasPrefix", "(", "ptype", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "pval", ":=", "reflect", ".", "ValueOf", "(", "prop", ".", "Val", ")", ".", "Field", "(", "0", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "pval", ".", "Len", "(", ")", ";", "i", "++", "{", "prop", ".", "Val", "=", "pval", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", "\n\n", "if", "f", ".", "MatchProperty", "(", "prop", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}", "\n\n", "if", "reflect", ".", "TypeOf", "(", "match", ")", "!=", "ptype", "{", "s", ",", "ok", ":=", "match", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// convert if we can", "switch", "prop", ".", "Val", ".", "(", "type", ")", "{", "case", "bool", ":", "match", ",", "_", "=", "strconv", ".", "ParseBool", "(", "s", ")", "\n", "case", "int16", ":", "x", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "16", ")", "\n", "match", "=", "int16", "(", "x", ")", "\n", "case", "int32", ":", "x", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "32", ")", "\n", "match", "=", "int32", "(", "x", ")", "\n", "case", "int64", ":", "match", ",", "_", "=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "64", ")", "\n", "case", "float32", ":", "x", ",", "_", ":=", "strconv", ".", "ParseFloat", "(", "s", ",", "32", ")", "\n", "match", "=", "float32", "(", "x", ")", "\n", "case", "float64", ":", "match", ",", "_", "=", "strconv", ".", "ParseFloat", "(", "s", ",", "64", ")", "\n", "case", "fmt", ".", "Stringer", ":", "prop", ".", "Val", "=", "prop", ".", "Val", ".", "(", "fmt", ".", "Stringer", ")", ".", "String", "(", ")", "\n", "default", ":", "if", "ptype", ".", "Kind", "(", ")", "!=", "reflect", ".", "String", "{", "return", "false", "\n", "}", "\n", "// An enum type we can convert to a string type", "prop", ".", "Val", "=", "reflect", ".", "ValueOf", "(", "prop", ".", "Val", ")", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n\n", "switch", "pval", ":=", "prop", ".", "Val", ".", "(", "type", ")", "{", "case", "string", ":", "s", ":=", "match", ".", "(", "string", ")", "\n", "if", "s", "==", "\"", "\"", "{", "return", "true", "// TODO: path.Match fails if s contains a '/'", "\n", "}", "\n", "m", ",", "_", ":=", "path", ".", "Match", "(", "s", ",", "pval", ")", "\n", "return", "m", "\n", "default", ":", "return", "reflect", ".", "DeepEqual", "(", "match", ",", "pval", ")", "\n", "}", "\n", "}" ]
// MatchProperty returns true if a Filter entry matches the given prop.
[ "MatchProperty", "returns", "true", "if", "a", "Filter", "entry", "matches", "the", "given", "prop", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L44-L115
21,694
vmware/govmomi
property/filter.go
MatchPropertyList
func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool { for _, p := range props { if !f.MatchProperty(p) { return false } } return len(f) == len(props) // false if a property such as VM "guest" is unset }
go
func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool { for _, p := range props { if !f.MatchProperty(p) { return false } } return len(f) == len(props) // false if a property such as VM "guest" is unset }
[ "func", "(", "f", "Filter", ")", "MatchPropertyList", "(", "props", "[", "]", "types", ".", "DynamicProperty", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "props", "{", "if", "!", "f", ".", "MatchProperty", "(", "p", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "len", "(", "f", ")", "==", "len", "(", "props", ")", "// false if a property such as VM \"guest\" is unset", "\n", "}" ]
// MatchPropertyList returns true if all given props match the Filter.
[ "MatchPropertyList", "returns", "true", "if", "all", "given", "props", "match", "the", "Filter", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L118-L126
21,695
vmware/govmomi
property/filter.go
MatchObjectContent
func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference { var refs []types.ManagedObjectReference for _, o := range objects { if f.MatchPropertyList(o.PropSet) { refs = append(refs, o.Obj) } } return refs }
go
func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference { var refs []types.ManagedObjectReference for _, o := range objects { if f.MatchPropertyList(o.PropSet) { refs = append(refs, o.Obj) } } return refs }
[ "func", "(", "f", "Filter", ")", "MatchObjectContent", "(", "objects", "[", "]", "types", ".", "ObjectContent", ")", "[", "]", "types", ".", "ManagedObjectReference", "{", "var", "refs", "[", "]", "types", ".", "ManagedObjectReference", "\n\n", "for", "_", ",", "o", ":=", "range", "objects", "{", "if", "f", ".", "MatchPropertyList", "(", "o", ".", "PropSet", ")", "{", "refs", "=", "append", "(", "refs", ",", "o", ".", "Obj", ")", "\n", "}", "\n", "}", "\n\n", "return", "refs", "\n", "}" ]
// MatchObjectContent returns a list of ObjectContent.Obj where the ObjectContent.PropSet matches the Filter.
[ "MatchObjectContent", "returns", "a", "list", "of", "ObjectContent", ".", "Obj", "where", "the", "ObjectContent", ".", "PropSet", "matches", "the", "Filter", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L129-L139
21,696
golang/lint
lint.go
Lint
func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) { return l.LintFiles(map[string][]byte{filename: src}) }
go
func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) { return l.LintFiles(map[string][]byte{filename: src}) }
[ "func", "(", "l", "*", "Linter", ")", "Lint", "(", "filename", "string", ",", "src", "[", "]", "byte", ")", "(", "[", "]", "Problem", ",", "error", ")", "{", "return", "l", ".", "LintFiles", "(", "map", "[", "string", "]", "[", "]", "byte", "{", "filename", ":", "src", "}", ")", "\n", "}" ]
// Lint lints src.
[ "Lint", "lints", "src", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L79-L81
21,697
golang/lint
lint.go
LintFiles
func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) { pkg := &pkg{ fset: token.NewFileSet(), files: make(map[string]*file), } var pkgName string for filename, src := range files { if isGenerated(src) { continue // See issue #239 } f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) if err != nil { return nil, err } if pkgName == "" { pkgName = f.Name.Name } else if f.Name.Name != pkgName { return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) } pkg.files[filename] = &file{ pkg: pkg, f: f, fset: pkg.fset, src: src, filename: filename, } } if len(pkg.files) == 0 { return nil, nil } return pkg.lint(), nil }
go
func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) { pkg := &pkg{ fset: token.NewFileSet(), files: make(map[string]*file), } var pkgName string for filename, src := range files { if isGenerated(src) { continue // See issue #239 } f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) if err != nil { return nil, err } if pkgName == "" { pkgName = f.Name.Name } else if f.Name.Name != pkgName { return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) } pkg.files[filename] = &file{ pkg: pkg, f: f, fset: pkg.fset, src: src, filename: filename, } } if len(pkg.files) == 0 { return nil, nil } return pkg.lint(), nil }
[ "func", "(", "l", "*", "Linter", ")", "LintFiles", "(", "files", "map", "[", "string", "]", "[", "]", "byte", ")", "(", "[", "]", "Problem", ",", "error", ")", "{", "pkg", ":=", "&", "pkg", "{", "fset", ":", "token", ".", "NewFileSet", "(", ")", ",", "files", ":", "make", "(", "map", "[", "string", "]", "*", "file", ")", ",", "}", "\n", "var", "pkgName", "string", "\n", "for", "filename", ",", "src", ":=", "range", "files", "{", "if", "isGenerated", "(", "src", ")", "{", "continue", "// See issue #239", "\n", "}", "\n", "f", ",", "err", ":=", "parser", ".", "ParseFile", "(", "pkg", ".", "fset", ",", "filename", ",", "src", ",", "parser", ".", "ParseComments", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pkgName", "==", "\"", "\"", "{", "pkgName", "=", "f", ".", "Name", ".", "Name", "\n", "}", "else", "if", "f", ".", "Name", ".", "Name", "!=", "pkgName", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filename", ",", "f", ".", "Name", ".", "Name", ",", "pkgName", ")", "\n", "}", "\n", "pkg", ".", "files", "[", "filename", "]", "=", "&", "file", "{", "pkg", ":", "pkg", ",", "f", ":", "f", ",", "fset", ":", "pkg", ".", "fset", ",", "src", ":", "src", ",", "filename", ":", "filename", ",", "}", "\n", "}", "\n", "if", "len", "(", "pkg", ".", "files", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "pkg", ".", "lint", "(", ")", ",", "nil", "\n", "}" ]
// LintFiles lints a set of files of a single package. // The argument is a map of filename to source.
[ "LintFiles", "lints", "a", "set", "of", "files", "of", "a", "single", "package", ".", "The", "argument", "is", "a", "map", "of", "filename", "to", "source", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L85-L116
21,698
golang/lint
lint.go
errorf
func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem { pos := f.fset.Position(n.Pos()) if pos.Filename == "" { pos.Filename = f.filename } return f.pkg.errorfAt(pos, confidence, args...) }
go
func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem { pos := f.fset.Position(n.Pos()) if pos.Filename == "" { pos.Filename = f.filename } return f.pkg.errorfAt(pos, confidence, args...) }
[ "func", "(", "f", "*", "file", ")", "errorf", "(", "n", "ast", ".", "Node", ",", "confidence", "float64", ",", "args", "...", "interface", "{", "}", ")", "*", "Problem", "{", "pos", ":=", "f", ".", "fset", ".", "Position", "(", "n", ".", "Pos", "(", ")", ")", "\n", "if", "pos", ".", "Filename", "==", "\"", "\"", "{", "pos", ".", "Filename", "=", "f", ".", "filename", "\n", "}", "\n", "return", "f", ".", "pkg", ".", "errorfAt", "(", "pos", ",", "confidence", ",", "args", "...", ")", "\n", "}" ]
// The variadic arguments may start with link and category types, // and must end with a format string and any arguments. // It returns the new Problem.
[ "The", "variadic", "arguments", "may", "start", "with", "link", "and", "category", "types", "and", "must", "end", "with", "a", "format", "string", "and", "any", "arguments", ".", "It", "returns", "the", "new", "Problem", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L222-L228
21,699
golang/lint
lint.go
scopeOf
func (p *pkg) scopeOf(id *ast.Ident) *types.Scope { var scope *types.Scope if obj := p.typesInfo.ObjectOf(id); obj != nil { scope = obj.Parent() } if scope == p.typesPkg.Scope() { // We were given a top-level identifier. // Use the file-level scope instead of the package-level scope. pos := id.Pos() for _, f := range p.files { if f.f.Pos() <= pos && pos < f.f.End() { scope = p.typesInfo.Scopes[f.f] break } } } return scope }
go
func (p *pkg) scopeOf(id *ast.Ident) *types.Scope { var scope *types.Scope if obj := p.typesInfo.ObjectOf(id); obj != nil { scope = obj.Parent() } if scope == p.typesPkg.Scope() { // We were given a top-level identifier. // Use the file-level scope instead of the package-level scope. pos := id.Pos() for _, f := range p.files { if f.f.Pos() <= pos && pos < f.f.End() { scope = p.typesInfo.Scopes[f.f] break } } } return scope }
[ "func", "(", "p", "*", "pkg", ")", "scopeOf", "(", "id", "*", "ast", ".", "Ident", ")", "*", "types", ".", "Scope", "{", "var", "scope", "*", "types", ".", "Scope", "\n", "if", "obj", ":=", "p", ".", "typesInfo", ".", "ObjectOf", "(", "id", ")", ";", "obj", "!=", "nil", "{", "scope", "=", "obj", ".", "Parent", "(", ")", "\n", "}", "\n", "if", "scope", "==", "p", ".", "typesPkg", ".", "Scope", "(", ")", "{", "// We were given a top-level identifier.", "// Use the file-level scope instead of the package-level scope.", "pos", ":=", "id", ".", "Pos", "(", ")", "\n", "for", "_", ",", "f", ":=", "range", "p", ".", "files", "{", "if", "f", ".", "f", ".", "Pos", "(", ")", "<=", "pos", "&&", "pos", "<", "f", ".", "f", ".", "End", "(", ")", "{", "scope", "=", "p", ".", "typesInfo", ".", "Scopes", "[", "f", ".", "f", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "scope", "\n", "}" ]
// scopeOf returns the tightest scope encompassing id.
[ "scopeOf", "returns", "the", "tightest", "scope", "encompassing", "id", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L308-L325