repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_firewall_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_firewall_system.go#L85-L105
go
train
// ByRule returns a HostFirewallRulesetList where Direction, PortType and Protocol are equal and Port is within range
func (l HostFirewallRulesetList) ByRule(rule types.HostFirewallRule) HostFirewallRulesetList
// ByRule returns a HostFirewallRulesetList where Direction, PortType and Protocol are equal and Port is within range func (l HostFirewallRulesetList) ByRule(rule types.HostFirewallRule) HostFirewallRulesetList
{ var matches HostFirewallRulesetList for _, rs := range l { for _, r := range rs.Rule { if r.PortType != rule.PortType || r.Protocol != rule.Protocol || r.Direction != rule.Direction { continue } if r.EndPort == 0 && rule.Port == r.Port || rule.Port >= r.Port && rule.Port <= r.EndPort { matches = append(matches, rs) break } } } return matches }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_firewall_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_firewall_system.go#L110-L144
go
train
// EnabledByRule returns a HostFirewallRulesetList with Match(rule) applied and filtered via Enabled() // if enabled param is true, otherwise filtered via Disabled(). // An error is returned if the resulting list is empty.
func (l HostFirewallRulesetList) EnabledByRule(rule types.HostFirewallRule, enabled bool) (HostFirewallRulesetList, error)
// EnabledByRule returns a HostFirewallRulesetList with Match(rule) applied and filtered via Enabled() // if enabled param is true, otherwise filtered via Disabled(). // An error is returned if the resulting list is empty. func (l HostFirewallRulesetList) EnabledByRule(rule types.HostFirewallRule, enabled bool) (HostFirewallRulesetList, error)
{ var matched, skipped HostFirewallRulesetList var matchedKind, skippedKind string l = l.ByRule(rule) if enabled { matched = l.Enabled() matchedKind = "enabled" skipped = l.Disabled() skippedKind = "disabled" } else { matched = l.Disabled() matchedKind = "disabled" skipped = l.Enabled() skippedKind = "enabled" } if len(matched) == 0 { msg := fmt.Sprintf("%d %s firewall rulesets match %s %s %s %d, %d %s rulesets match", len(matched), matchedKind, rule.Direction, rule.Protocol, rule.PortType, rule.Port, len(skipped), skippedKind) if len(skipped) != 0 { msg += fmt.Sprintf(": %s", strings.Join(skipped.Keys(), ", ")) } return nil, errors.New(msg) } return matched, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_firewall_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_firewall_system.go#L147-L157
go
train
// Enabled returns a HostFirewallRulesetList with enabled rules
func (l HostFirewallRulesetList) Enabled() HostFirewallRulesetList
// Enabled returns a HostFirewallRulesetList with enabled rules func (l HostFirewallRulesetList) Enabled() HostFirewallRulesetList
{ var matches HostFirewallRulesetList for _, rs := range l { if rs.Enabled { matches = append(matches, rs) } } return matches }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_firewall_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_firewall_system.go#L173-L181
go
train
// Keys returns the HostFirewallRuleset.Key for each ruleset in the list
func (l HostFirewallRulesetList) Keys() []string
// Keys returns the HostFirewallRuleset.Key for each ruleset in the list func (l HostFirewallRulesetList) Keys() []string
{ var keys []string for _, rs := range l { keys = append(keys, rs.Key) } return keys }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L118-L132
go
train
// CopyToken returns a copy of a Token.
func CopyToken(t Token) Token
// CopyToken returns a copy of a Token. func CopyToken(t Token) Token
{ switch v := t.(type) { case CharData: return v.Copy() case Comment: return v.Copy() case Directive: return v.Copy() case ProcInst: return v.Copy() case StartElement: return v.Copy() } return t }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L209-L218
go
train
// NewDecoder creates a new XML parser reading from r. // If r does not implement io.ByteReader, NewDecoder will // do its own buffering.
func NewDecoder(r io.Reader) *Decoder
// NewDecoder creates a new XML parser reading from r. // If r does not implement io.ByteReader, NewDecoder will // do its own buffering. func NewDecoder(r io.Reader) *Decoder
{ d := &Decoder{ ns: make(map[string]string), nextByte: -1, line: 1, Strict: true, } d.switchToReader(r) return d }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L242-L295
go
train
// Token returns the next XML token in the input stream. // At the end of the input stream, Token returns nil, io.EOF. // // Slices of bytes in the returned token data refer to the // parser's internal buffer and remain valid only until the next // call to Token. To acquire a copy of the bytes, call CopyToken // or the token's Copy method. // // Token expands self-closing elements such as <br/> // into separate start and end elements returned by successive calls. // // Token guarantees that the StartElement and EndElement // tokens it returns are properly nested and matched: // if Token encounters an unexpected end element, // it will return an error. // // Token implements XML name spaces as described by // http://www.w3.org/TR/REC-xml-names/. Each of the // Name structures contained in the Token has the Space // set to the URL identifying its name space when known. // If Token encounters an unrecognized name space prefix, // it uses the prefix as the Space rather than report an error.
func (d *Decoder) Token() (t Token, err error)
// Token returns the next XML token in the input stream. // At the end of the input stream, Token returns nil, io.EOF. // // Slices of bytes in the returned token data refer to the // parser's internal buffer and remain valid only until the next // call to Token. To acquire a copy of the bytes, call CopyToken // or the token's Copy method. // // Token expands self-closing elements such as <br/> // into separate start and end elements returned by successive calls. // // Token guarantees that the StartElement and EndElement // tokens it returns are properly nested and matched: // if Token encounters an unexpected end element, // it will return an error. // // Token implements XML name spaces as described by // http://www.w3.org/TR/REC-xml-names/. Each of the // Name structures contained in the Token has the Space // set to the URL identifying its name space when known. // If Token encounters an unrecognized name space prefix, // it uses the prefix as the Space rather than report an error. func (d *Decoder) Token() (t Token, err error)
{ if d.stk != nil && d.stk.kind == stkEOF { err = io.EOF return } if d.nextToken != nil { t = d.nextToken d.nextToken = nil } else if t, err = d.rawToken(); err != nil { return } if !d.Strict { if t1, ok := d.autoClose(t); ok { d.nextToken = t t = t1 } } switch t1 := t.(type) { case StartElement: // In XML name spaces, the translations listed in the // attributes apply to the element name and // to the other attribute names, so process // the translations first. for _, a := range t1.Attr { if a.Name.Space == "xmlns" { v, ok := d.ns[a.Name.Local] d.pushNs(a.Name.Local, v, ok) d.ns[a.Name.Local] = a.Value } if a.Name.Space == "" && a.Name.Local == "xmlns" { // Default space for untagged names v, ok := d.ns[""] d.pushNs("", v, ok) d.ns[""] = a.Value } } d.translate(&t1.Name, true) for i := range t1.Attr { d.translate(&t1.Attr[i].Name, false) } d.pushElement(t1.Name) t = t1 case EndElement: d.translate(&t1.Name, true) if !d.popElement(&t1) { return nil, d.err } t = t1 } return }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L375-L397
go
train
// Record that after the current element is finished // (that element is already pushed on the stack) // Token should return EOF until popEOF is called.
func (d *Decoder) pushEOF()
// Record that after the current element is finished // (that element is already pushed on the stack) // Token should return EOF until popEOF is called. func (d *Decoder) pushEOF()
{ // Walk down stack to find Start. // It might not be the top, because there might be stkNs // entries above it. start := d.stk for start.kind != stkStart { start = start.next } // The stkNs entries below a start are associated with that // element too; skip over them. for start.next != nil && start.next.kind == stkNs { start = start.next } s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.kind = stkEOF s.next = start.next start.next = s }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L401-L407
go
train
// Undo a pushEOF. // The element must have been finished, so the EOF should be at the top of the stack.
func (d *Decoder) popEOF() bool
// Undo a pushEOF. // The element must have been finished, so the EOF should be at the top of the stack. func (d *Decoder) popEOF() bool
{ if d.stk == nil || d.stk.kind != stkEOF { return false } d.pop() return true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L410-L413
go
train
// Record that we are starting an element with the given name.
func (d *Decoder) pushElement(name Name)
// Record that we are starting an element with the given name. func (d *Decoder) pushElement(name Name)
{ s := d.push(stkStart) s.name = name }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L417-L422
go
train
// Record that we are changing the value of ns[local]. // The old value is url, ok.
func (d *Decoder) pushNs(local string, url string, ok bool)
// Record that we are changing the value of ns[local]. // The old value is url, ok. func (d *Decoder) pushNs(local string, url string, ok bool)
{ s := d.push(stkNs) s.name.Local = local s.name.Space = url s.ok = ok }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L425-L427
go
train
// Creates a SyntaxError with the current line number.
func (d *Decoder) syntaxError(msg string) error
// Creates a SyntaxError with the current line number. func (d *Decoder) syntaxError(msg string) error
{ return &SyntaxError{Msg: msg, Line: d.line} }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L435-L469
go
train
// Record that we are ending an element with the given name. // The name must match the record at the top of the stack, // which must be a pushElement record. // After popping the element, apply any undo records from // the stack to restore the name translations that existed // before we saw this element.
func (d *Decoder) popElement(t *EndElement) bool
// Record that we are ending an element with the given name. // The name must match the record at the top of the stack, // which must be a pushElement record. // After popping the element, apply any undo records from // the stack to restore the name translations that existed // before we saw this element. func (d *Decoder) popElement(t *EndElement) bool
{ s := d.pop() name := t.Name switch { case s == nil || s.kind != stkStart: d.err = d.syntaxError("unexpected end element </" + name.Local + ">") return false case s.name.Local != name.Local: if !d.Strict { d.needClose = true d.toClose = t.Name t.Name = s.name return true } d.err = d.syntaxError("element <" + s.name.Local + "> closed by </" + name.Local + ">") return false case s.name.Space != name.Space: d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space + "closed by </" + name.Local + "> in space " + name.Space) return false } // Pop stack until a Start or EOF is on the top, undoing the // translations that were associated with the element we just closed. for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF { s := d.pop() if s.ok { d.ns[s.name.Local] = s.name.Space } else { delete(d.ns, s.name.Local) } } return true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L473-L489
go
train
// If the top element on the stack is autoclosing and // t is not the end tag, invent the end tag.
func (d *Decoder) autoClose(t Token) (Token, bool)
// If the top element on the stack is autoclosing and // t is not the end tag, invent the end tag. func (d *Decoder) autoClose(t Token) (Token, bool)
{ if d.stk == nil || d.stk.kind != stkStart { return nil, false } name := strings.ToLower(d.stk.name.Local) for _, s := range d.AutoClose { if strings.ToLower(s) == name { // This one should be auto closed if t doesn't close it. et, ok := t.(EndElement) if !ok || et.Name.Local != name { return EndElement{d.stk.name}, true } break } } return nil, false }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L496-L501
go
train
// RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs.
func (d *Decoder) RawToken() (Token, error)
// RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs. func (d *Decoder) RawToken() (Token, error)
{ if d.unmarshalDepth > 0 { return nil, errRawToken } return d.rawToken() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L828-L841
go
train
// Skip spaces if any
func (d *Decoder) space()
// Skip spaces if any func (d *Decoder) space()
{ for { b, ok := d.getc() if !ok { return } switch b { case ' ', '\r', '\n', '\t': default: d.ungetc(b) return } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L847-L867
go
train
// Read a single byte. // If there is no byte to read, return ok==false // and leave the error in d.err. // Maintain line number.
func (d *Decoder) getc() (b byte, ok bool)
// Read a single byte. // If there is no byte to read, return ok==false // and leave the error in d.err. // Maintain line number. func (d *Decoder) getc() (b byte, ok bool)
{ if d.err != nil { return 0, false } if d.nextByte >= 0 { b = byte(d.nextByte) d.nextByte = -1 } else { b, d.err = d.r.ReadByte() if d.err != nil { return 0, false } if d.saved != nil { d.saved.WriteByte(b) } } if b == '\n' { d.line++ } return b, true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L871-L877
go
train
// Return saved offset. // If we did ungetc (nextByte >= 0), have to back up one.
func (d *Decoder) savedOffset() int
// Return saved offset. // If we did ungetc (nextByte >= 0), have to back up one. func (d *Decoder) savedOffset() int
{ n := d.saved.Len() if d.nextByte >= 0 { n-- } return n }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L883-L890
go
train
// Must read a single byte. // If there is no byte to read, // set d.err to SyntaxError("unexpected EOF") // and return ok==false
func (d *Decoder) mustgetc() (b byte, ok bool)
// Must read a single byte. // If there is no byte to read, // set d.err to SyntaxError("unexpected EOF") // and return ok==false func (d *Decoder) mustgetc() (b byte, ok bool)
{ if b, ok = d.getc(); !ok { if d.err == io.EOF { d.err = d.syntaxError("unexpected EOF") } } return }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L1080-L1087
go
train
// Decide whether the given rune is in the XML Character Range, per // the Char production of http://www.xml.com/axml/testaxml.htm, // Section 2.2 Characters.
func isInCharacterRange(r rune) (inrange bool)
// Decide whether the given rune is in the XML Character Range, per // the Char production of http://www.xml.com/axml/testaxml.htm, // Section 2.2 Characters. func isInCharacterRange(r rune) (inrange bool)
{ return r == 0x09 || r == 0x0A || r == 0x0D || r >= 0x20 && r <= 0xDF77 || r >= 0xE000 && r <= 0xFFFD || r >= 0x10000 && r <= 0x10FFFF }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L1091-L1104
go
train
// Get name space name: name with a : stuck in the middle. // The part before the : is the name space identifier.
func (d *Decoder) nsname() (name Name, ok bool)
// Get name space name: name with a : stuck in the middle. // The part before the : is the name space identifier. func (d *Decoder) nsname() (name Name, ok bool)
{ s, ok := d.name() if !ok { return } i := strings.Index(s, ":") if i < 0 { name.Local = s } else { name.Space = s[0:i] name.Local = s[i+1:] } return name, true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L1109-L1122
go
train
// Get name: /first(first|second)*/ // Do not set d.err if the name is missing (unless unexpected EOF is received): // let the caller provide better context.
func (d *Decoder) name() (s string, ok bool)
// Get name: /first(first|second)*/ // Do not set d.err if the name is missing (unless unexpected EOF is received): // let the caller provide better context. func (d *Decoder) name() (s string, ok bool)
{ d.buf.Reset() if !d.readName() { return "", false } // Now we check the characters. s = d.buf.String() if !isName([]byte(s)) { d.err = d.syntaxError("invalid XML name: " + s) return "", false } return s, true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L1127-L1149
go
train
// Read a name and append its bytes to d.buf. // The name is delimited by any single-byte character not valid in names. // All multi-byte characters are accepted; the caller must check their validity.
func (d *Decoder) readName() (ok bool)
// Read a name and append its bytes to d.buf. // The name is delimited by any single-byte character not valid in names. // All multi-byte characters are accepted; the caller must check their validity. func (d *Decoder) readName() (ok bool)
{ var b byte if b, ok = d.mustgetc(); !ok { return } if b < utf8.RuneSelf && !isNameByte(b) { d.ungetc(b) return false } d.buf.WriteByte(b) for { if b, ok = d.mustgetc(); !ok { return } if b < utf8.RuneSelf && !isNameByte(b) { d.ungetc(b) break } d.buf.WriteByte(b) } return true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L1874-L1909
go
train
// EscapeString writes to p the properly escaped XML equivalent // of the plain text data s.
func (p *printer) EscapeString(s string)
// EscapeString writes to p the properly escaped XML equivalent // of the plain text data s. func (p *printer) EscapeString(s string)
{ var esc []byte last := 0 for i := 0; i < len(s); { r, width := utf8.DecodeRuneInString(s[i:]) i += width switch r { case '"': esc = esc_quot case '\'': esc = esc_apos case '&': esc = esc_amp case '<': esc = esc_lt case '>': esc = esc_gt case '\t': esc = esc_tab case '\n': esc = esc_nl case '\r': esc = esc_cr default: if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { esc = esc_fffd break } continue } p.WriteString(s[last : i-width]) p.Write(esc) last = i } p.WriteString(s[last:]) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/xml.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/xml.go#L1920-L1939
go
train
// procInstEncoding parses the `encoding="..."` or `encoding='...'` // value out of the provided string, returning "" if not found.
func procInstEncoding(s string) string
// procInstEncoding parses the `encoding="..."` or `encoding='...'` // value out of the provided string, returning "" if not found. func procInstEncoding(s string) string
{ // TODO: this parsing is somewhat lame and not exact. // It works for all actual cases, though. idx := strings.Index(s, "encoding=") if idx == -1 { return "" } v := s[idx+len("encoding="):] if v == "" { return "" } if v[0] != '\'' && v[0] != '"' { return "" } idx = strings.IndexRune(v[1:], rune(v[0])) if idx == -1 { return "" } return v[1 : idx+1] }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/distributed_virtual_portgroup.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/distributed_virtual_portgroup.go#L40-L66
go
train
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this DistributedVirtualPortgroup
func (p DistributedVirtualPortgroup) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this DistributedVirtualPortgroup func (p DistributedVirtualPortgroup) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
{ var dvp mo.DistributedVirtualPortgroup var dvs mo.DistributedVirtualSwitch prop := "config.distributedVirtualSwitch" if err := p.Properties(ctx, p.Reference(), []string{"key", prop}, &dvp); err != nil { return nil, err } // "This property should always be set unless the user's setting does not have System.Read privilege on the object referred to by this property." if dvp.Config.DistributedVirtualSwitch == nil { return nil, fmt.Errorf("no System.Read privilege on: %s.%s", p.Reference(), prop) } if err := p.Properties(ctx, *dvp.Config.DistributedVirtualSwitch, []string{"uuid"}, &dvs); err != nil { return nil, err } backing := &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{ Port: types.DistributedVirtualSwitchPortConnection{ PortgroupKey: dvp.Key, SwitchUuid: dvs.Uuid, }, } return backing, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L38-L50
go
train
// AddPortGroup wraps methods.AddPortGroup
func (o HostNetworkSystem) AddPortGroup(ctx context.Context, portgrp types.HostPortGroupSpec) error
// AddPortGroup wraps methods.AddPortGroup func (o HostNetworkSystem) AddPortGroup(ctx context.Context, portgrp types.HostPortGroupSpec) error
{ req := types.AddPortGroup{ This: o.Reference(), Portgrp: portgrp, } _, err := methods.AddPortGroup(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L53-L66
go
train
// AddServiceConsoleVirtualNic wraps methods.AddServiceConsoleVirtualNic
func (o HostNetworkSystem) AddServiceConsoleVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error)
// AddServiceConsoleVirtualNic wraps methods.AddServiceConsoleVirtualNic func (o HostNetworkSystem) AddServiceConsoleVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error)
{ req := types.AddServiceConsoleVirtualNic{ This: o.Reference(), Portgroup: portgroup, Nic: nic, } res, err := methods.AddServiceConsoleVirtualNic(ctx, o.c, &req) if err != nil { return "", err } return res.Returnval, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L85-L98
go
train
// AddVirtualSwitch wraps methods.AddVirtualSwitch
func (o HostNetworkSystem) AddVirtualSwitch(ctx context.Context, vswitchName string, spec *types.HostVirtualSwitchSpec) error
// AddVirtualSwitch wraps methods.AddVirtualSwitch func (o HostNetworkSystem) AddVirtualSwitch(ctx context.Context, vswitchName string, spec *types.HostVirtualSwitchSpec) error
{ req := types.AddVirtualSwitch{ This: o.Reference(), VswitchName: vswitchName, Spec: spec, } _, err := methods.AddVirtualSwitch(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L101-L113
go
train
// QueryNetworkHint wraps methods.QueryNetworkHint
func (o HostNetworkSystem) QueryNetworkHint(ctx context.Context, device []string) error
// QueryNetworkHint wraps methods.QueryNetworkHint func (o HostNetworkSystem) QueryNetworkHint(ctx context.Context, device []string) error
{ req := types.QueryNetworkHint{ This: o.Reference(), Device: device, } _, err := methods.QueryNetworkHint(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L116-L127
go
train
// RefreshNetworkSystem wraps methods.RefreshNetworkSystem
func (o HostNetworkSystem) RefreshNetworkSystem(ctx context.Context) error
// RefreshNetworkSystem wraps methods.RefreshNetworkSystem func (o HostNetworkSystem) RefreshNetworkSystem(ctx context.Context) error
{ req := types.RefreshNetworkSystem{ This: o.Reference(), } _, err := methods.RefreshNetworkSystem(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L130-L142
go
train
// RemovePortGroup wraps methods.RemovePortGroup
func (o HostNetworkSystem) RemovePortGroup(ctx context.Context, pgName string) error
// RemovePortGroup wraps methods.RemovePortGroup func (o HostNetworkSystem) RemovePortGroup(ctx context.Context, pgName string) error
{ req := types.RemovePortGroup{ This: o.Reference(), PgName: pgName, } _, err := methods.RemovePortGroup(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L175-L187
go
train
// RemoveVirtualSwitch wraps methods.RemoveVirtualSwitch
func (o HostNetworkSystem) RemoveVirtualSwitch(ctx context.Context, vswitchName string) error
// RemoveVirtualSwitch wraps methods.RemoveVirtualSwitch func (o HostNetworkSystem) RemoveVirtualSwitch(ctx context.Context, vswitchName string) error
{ req := types.RemoveVirtualSwitch{ This: o.Reference(), VswitchName: vswitchName, } _, err := methods.RemoveVirtualSwitch(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L205-L217
go
train
// UpdateConsoleIpRouteConfig wraps methods.UpdateConsoleIpRouteConfig
func (o HostNetworkSystem) UpdateConsoleIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error
// UpdateConsoleIpRouteConfig wraps methods.UpdateConsoleIpRouteConfig func (o HostNetworkSystem) UpdateConsoleIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error
{ req := types.UpdateConsoleIpRouteConfig{ This: o.Reference(), Config: config, } _, err := methods.UpdateConsoleIpRouteConfig(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L265-L278
go
train
// UpdateNetworkConfig wraps methods.UpdateNetworkConfig
func (o HostNetworkSystem) UpdateNetworkConfig(ctx context.Context, config types.HostNetworkConfig, changeMode string) (*types.HostNetworkConfigResult, error)
// UpdateNetworkConfig wraps methods.UpdateNetworkConfig func (o HostNetworkSystem) UpdateNetworkConfig(ctx context.Context, config types.HostNetworkConfig, changeMode string) (*types.HostNetworkConfigResult, error)
{ req := types.UpdateNetworkConfig{ This: o.Reference(), Config: config, ChangeMode: changeMode, } res, err := methods.UpdateNetworkConfig(ctx, o.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L281-L294
go
train
// UpdatePhysicalNicLinkSpeed wraps methods.UpdatePhysicalNicLinkSpeed
func (o HostNetworkSystem) UpdatePhysicalNicLinkSpeed(ctx context.Context, device string, linkSpeed *types.PhysicalNicLinkInfo) error
// UpdatePhysicalNicLinkSpeed wraps methods.UpdatePhysicalNicLinkSpeed func (o HostNetworkSystem) UpdatePhysicalNicLinkSpeed(ctx context.Context, device string, linkSpeed *types.PhysicalNicLinkInfo) error
{ req := types.UpdatePhysicalNicLinkSpeed{ This: o.Reference(), Device: device, LinkSpeed: linkSpeed, } _, err := methods.UpdatePhysicalNicLinkSpeed(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L297-L310
go
train
// UpdatePortGroup wraps methods.UpdatePortGroup
func (o HostNetworkSystem) UpdatePortGroup(ctx context.Context, pgName string, portgrp types.HostPortGroupSpec) error
// UpdatePortGroup wraps methods.UpdatePortGroup func (o HostNetworkSystem) UpdatePortGroup(ctx context.Context, pgName string, portgrp types.HostPortGroupSpec) error
{ req := types.UpdatePortGroup{ This: o.Reference(), PgName: pgName, Portgrp: portgrp, } _, err := methods.UpdatePortGroup(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_network_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_network_system.go#L329-L342
go
train
// UpdateVirtualNic wraps methods.UpdateVirtualNic
func (o HostNetworkSystem) UpdateVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error
// UpdateVirtualNic wraps methods.UpdateVirtualNic func (o HostNetworkSystem) UpdateVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error
{ req := types.UpdateVirtualNic{ This: o.Reference(), Device: device, Nic: nic, } _, err := methods.UpdateVirtualNic(ctx, o.c, &req) if err != nil { return err } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/host/esxcli/command.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/esxcli/command.go#L95-L122
go
train
// Parse generates a flag.FlagSet based on the given []CommandInfoParam and // returns arguments for use with methods.ExecuteSoap
func (c *Command) Parse(params []CommandInfoParam) ([]internal.ReflectManagedMethodExecuterSoapArgument, error)
// Parse generates a flag.FlagSet based on the given []CommandInfoParam and // returns arguments for use with methods.ExecuteSoap func (c *Command) Parse(params []CommandInfoParam) ([]internal.ReflectManagedMethodExecuterSoapArgument, error)
{ flags := flag.NewFlagSet(strings.Join(c.name, " "), flag.ExitOnError) vals := make([]string, len(params)) for i, p := range params { v := &vals[i] for _, a := range p.Aliases { a = strings.TrimPrefix(a[1:], "-") flags.StringVar(v, a, "", p.Help) } } err := flags.Parse(c.args) if err != nil { return nil, err } args := []internal.ReflectManagedMethodExecuterSoapArgument{} for i, p := range params { if vals[i] == "" { continue } args = append(args, c.Argument(p.Name, vals[i])) } return args, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
view/task_view.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/task_view.go#L36-L48
go
train
// CreateTaskView creates a new ListView that optionally watches for a ManagedEntity's recentTask updates.
func (m Manager) CreateTaskView(ctx context.Context, watch *types.ManagedObjectReference) (*TaskView, error)
// CreateTaskView creates a new ListView that optionally watches for a ManagedEntity's recentTask updates. func (m Manager) CreateTaskView(ctx context.Context, watch *types.ManagedObjectReference) (*TaskView, error)
{ l, err := m.CreateListView(ctx, nil) if err != nil { return nil, err } tv := &TaskView{ ListView: l, Watch: watch, } return tv, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
view/task_view.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/view/task_view.go#L51-L125
go
train
// Collect calls function f for each Task update.
func (v TaskView) Collect(ctx context.Context, f func([]types.TaskInfo)) error
// Collect calls function f for each Task update. func (v TaskView) Collect(ctx context.Context, f func([]types.TaskInfo)) error
{ // Using TaskHistoryCollector would be less clunky, but it isn't supported on ESX at all. ref := v.Reference() filter := new(property.WaitFilter).Add(ref, "Task", []string{"info"}, v.TraversalSpec()) if v.Watch != nil { filter.Add(*v.Watch, v.Watch.Type, []string{"recentTask"}) } pc := property.DefaultCollector(v.Client()) completed := make(map[string]bool) return property.WaitForUpdates(ctx, pc, filter, func(updates []types.ObjectUpdate) bool { var infos []types.TaskInfo var prune []types.ManagedObjectReference var tasks []types.ManagedObjectReference var reset func() for _, update := range updates { for _, change := range update.ChangeSet { if change.Name == "recentTask" { tasks = change.Val.(types.ArrayOfManagedObjectReference).ManagedObjectReference if len(tasks) != 0 { reset = func() { _ = v.Reset(ctx, tasks) // Remember any tasks we've reported as complete already, // to avoid reporting multiple times when Reset is triggered. rtasks := make(map[string]bool) for i := range tasks { if _, ok := completed[tasks[i].Value]; ok { rtasks[tasks[i].Value] = true } } completed = rtasks } } continue } info, ok := change.Val.(types.TaskInfo) if !ok { continue } if !completed[info.Task.Value] { infos = append(infos, info) } if v.Follow && info.CompleteTime != nil { prune = append(prune, info.Task) completed[info.Task.Value] = true } } } if len(infos) != 0 { f(infos) } if reset != nil { reset() } else if len(prune) != 0 { _ = v.Remove(ctx, prune) } if len(tasks) != 0 && len(infos) == 0 { return false } return !v.Follow }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/vcenter/vcenter_ovf.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/vcenter/vcenter_ovf.go#L93-L105
go
train
// Error implements the error interface
func (e *DeploymentError) Error() string
// Error implements the error interface func (e *DeploymentError) Error() string
{ msg := "" if len(e.Errors) != 0 { err := e.Errors[0] if err.Error != nil && len(err.Error.Messages) != 0 { msg = err.Error.Messages[0].DefaultMessage } } if msg == "" { msg = fmt.Sprintf("%+v", e) } return "deploy error: " + msg }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/vcenter/vcenter_ovf.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/vcenter/vcenter_ovf.go#L141-L145
go
train
// DeployLibraryItem deploys a library OVF
func (c *Manager) DeployLibraryItem(ctx context.Context, libraryItemID string, deploy Deploy) (Deployment, error)
// DeployLibraryItem deploys a library OVF func (c *Manager) DeployLibraryItem(ctx context.Context, libraryItemID string, deploy Deploy) (Deployment, error)
{ url := internal.URL(c, internal.VCenterOVFLibraryItem).WithID(libraryItemID).WithAction("deploy") var res Deployment return res, c.Do(ctx, url.Request(http.MethodPost, deploy), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/vcenter/vcenter_ovf.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/vcenter/vcenter_ovf.go#L148-L152
go
train
// FilterLibraryItem deploys a library OVF
func (c *Manager) FilterLibraryItem(ctx context.Context, libraryItemID string, filter FilterRequest) (FilterResponse, error)
// FilterLibraryItem deploys a library OVF func (c *Manager) FilterLibraryItem(ctx context.Context, libraryItemID string, filter FilterRequest) (FilterResponse, error)
{ url := internal.URL(c, internal.VCenterOVFLibraryItem).WithID(libraryItemID).WithAction("filter") var res FilterResponse return res, c.Do(ctx, url.Request(http.MethodPost, filter), &res) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/rest/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L40-L44
go
train
// NewClient creates a new Client instance.
func NewClient(c *vim25.Client) *Client
// NewClient creates a new Client instance. func NewClient(c *vim25.Client) *Client
{ sc := c.Client.NewServiceClient(internal.Path, "") return &Client{sc} }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/rest/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L57-L102
go
train
// Do sends the http.Request, decoding resBody if provided.
func (c *Client) Do(ctx context.Context, req *http.Request, resBody interface{}) error
// Do sends the http.Request, decoding resBody if provided. 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) } }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/rest/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L105-L115
go
train
// Login creates a new session via Basic Authentication with the given url.Userinfo.
func (c *Client) Login(ctx context.Context, user *url.Userinfo) error
// Login creates a new session via Basic Authentication with the given url.Userinfo. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/rest/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/rest/client.go#L122-L125
go
train
// Logout deletes the current session.
func (c *Client) Logout(ctx context.Context) error
// Logout deletes the current session. func (c *Client) Logout(ctx context.Context) error
{ req := internal.URL(c, internal.SessionPath).Request(http.MethodDelete) return c.Do(ctx, req, nil) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
lookup/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/client.go#L54-L68
go
train
// NewClient returns a client targeting the SSO Lookup Service API endpoint.
func NewClient(ctx context.Context, c *vim25.Client) (*Client, error)
// NewClient returns a client targeting the SSO Lookup Service API endpoint. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
lookup/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/client.go#L98-L113
go
train
// 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.
func EndpointURL(ctx context.Context, c *vim25.Client, path string, filter *types.LookupServiceRegistrationFilter) string
// 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. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
lookup/client.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/lookup/client.go#L116-L135
go
train
// endpointThumbprint converts the base64 encoded endpoint certificate to a SHA1 thumbprint.
func endpointThumbprint(endpoint *types.LookupServiceRegistrationEndpoint) string
// endpointThumbprint converts the base64 encoded endpoint certificate to a SHA1 thumbprint. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_vsan_system.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_vsan_system.go#L53-L88
go
train
// updateVnic in support of the HostVirtualNicManager.{SelectVnic,DeselectVnic} methods
func (s HostVsanSystem) updateVnic(ctx context.Context, device string, enable bool) error
// updateVnic in support of the HostVirtualNicManager.{SelectVnic,DeselectVnic} methods func (s HostVsanSystem) updateVnic(ctx context.Context, device string, enable bool) error
{ var vsan mo.HostVsanSystem err := s.Properties(ctx, s.Reference(), []string{"config.networkInfo.port"}, &vsan) if err != nil { return err } info := vsan.Config var port []types.VsanHostConfigInfoNetworkInfoPortConfig for _, p := range info.NetworkInfo.Port { if p.Device == device { continue } port = append(port, p) } if enable { port = append(port, types.VsanHostConfigInfoNetworkInfoPortConfig{ Device: device, }) } info.NetworkInfo.Port = port task, err := s.Update(ctx, info) if err != nil { return err } _, err = task.WaitForResult(ctx, nil) return err }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
ovf/manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L39-L52
go
train
// CreateDescriptor wraps methods.CreateDescriptor
func (m *Manager) CreateDescriptor(ctx context.Context, obj mo.Reference, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error)
// CreateDescriptor wraps methods.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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
ovf/manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L55-L70
go
train
// CreateImportSpec wraps methods.CreateImportSpec
func (m *Manager) CreateImportSpec(ctx context.Context, ovfDescriptor string, resourcePool mo.Reference, datastore mo.Reference, cisp types.OvfCreateImportSpecParams) (*types.OvfCreateImportSpecResult, error)
// CreateImportSpec wraps methods.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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
ovf/manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L73-L86
go
train
// ParseDescriptor wraps methods.ParseDescriptor
func (m *Manager) ParseDescriptor(ctx context.Context, ovfDescriptor string, pdp types.OvfParseDescriptorParams) (*types.OvfParseDescriptorResult, error)
// ParseDescriptor wraps methods.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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
ovf/manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/ovf/manager.go#L89-L103
go
train
// ValidateHost wraps methods.ValidateHost
func (m *Manager) ValidateHost(ctx context.Context, ovfDescriptor string, host mo.Reference, vhp types.OvfValidateHostParams) (*types.OvfValidateHostResult, error)
// ValidateHost wraps methods.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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L46-L59
go
train
// Patch merges updates from the given src.
func (i *Item) Patch(src *Item)
// Patch merges updates from the given src. func (i *Item) Patch(src *Item)
{ if src.Name != "" { i.Name = src.Name } if src.Description != "" { i.Description = src.Description } if src.Type != "" { i.Type = src.Type } if src.Version != "" { i.Version = src.Version } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L62-L82
go
train
// CreateLibraryItem creates a new library item
func (c *Manager) CreateLibraryItem(ctx context.Context, item Item) (string, error)
// CreateLibraryItem creates a new library item 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L85-L88
go
train
// DeleteLibraryItem deletes an existing library item.
func (c *Manager) DeleteLibraryItem(ctx context.Context, item *Item) error
// DeleteLibraryItem deletes an existing library item. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L91-L95
go
train
// ListLibraryItems returns a list of all items in a content library.
func (c *Manager) ListLibraryItems(ctx context.Context, id string) ([]string, error)
// ListLibraryItems returns a list of all items in a content library. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L98-L102
go
train
// GetLibraryItem returns information on a library item for the given ID.
func (c *Manager) GetLibraryItem(ctx context.Context, id string) (*Item, error)
// GetLibraryItem returns information on a library item for the given ID. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L105-L119
go
train
// GetLibraryItems returns a list of all the library items for the specified library.
func (c *Manager) GetLibraryItems(ctx context.Context, libraryID string) ([]Item, error)
// GetLibraryItems returns a list of all the library items for the specified library. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/library/library_item.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/library/library_item.go#L132-L141
go
train
// FindLibraryItems returns the IDs of all the library items that match the // search criteria.
func (c *Manager) FindLibraryItems( ctx context.Context, search FindItem) ([]string, error)
// FindLibraryItems returns the IDs of all the library items that match the // search criteria. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/host/esxcli/firewall_info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/esxcli/firewall_info.go#L30-L48
go
train
// 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.
func GetFirewallInfo(s *object.HostSystem) (*FirewallInfo, error)
// 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. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
session/keep_alive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/session/keep_alive.go#L51-L53
go
train
// 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.
func KeepAlive(roundTripper soap.RoundTripper, idleTime time.Duration) soap.RoundTripper
// 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. func KeepAlive(roundTripper soap.RoundTripper, idleTime time.Duration) soap.RoundTripper
{ return KeepAliveHandler(roundTripper, idleTime, defaultKeepAlive) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
session/keep_alive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/session/keep_alive.go#L58-L68
go
train
// KeepAliveHandler works as KeepAlive() does, but the handler param can decide how to handle errors. // For example, if connectivity to ESX/VC is down long enough for a session to expire, a handler can choose to // Login() on a types.NotAuthenticated error. If handler returns non-nil, the keep alive go routine will be stopped.
func KeepAliveHandler(roundTripper soap.RoundTripper, idleTime time.Duration, handler func(soap.RoundTripper) error) soap.RoundTripper
// KeepAliveHandler works as KeepAlive() does, but the handler param can decide how to handle errors. // For example, if connectivity to ESX/VC is down long enough for a session to expire, a handler can choose to // Login() on a types.NotAuthenticated error. If handler returns non-nil, the keep alive go routine will be stopped. func KeepAliveHandler(roundTripper soap.RoundTripper, idleTime time.Duration, handler func(soap.RoundTripper) error) soap.RoundTripper
{ k := &keepAlive{ roundTripper: roundTripper, idleTime: idleTime, notifyRequest: make(chan struct{}), } k.keepAlive = handler return k }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
pbm/pbm_util.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/pbm/pbm_util.go#L131-L137
go
train
// Verify if the capability value is of type integer.
func verifyPropertyValueIsInt(propertyValue string, dataType string) (int32, error)
// Verify if the capability value is of type integer. func verifyPropertyValueIsInt(propertyValue string, dataType string) (int32, error)
{ val, err := strconv.ParseInt(propertyValue, 10, 32) if err != nil { return -1, err } return int32(val), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
pbm/pbm_util.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/pbm/pbm_util.go#L140-L146
go
train
// Verify if the capability value is of type integer.
func verifyPropertyValueIsBoolean(propertyValue string, dataType string) (bool, error)
// Verify if the capability value is of type integer. func verifyPropertyValueIsBoolean(propertyValue string, dataType string) (bool, error)
{ val, err := strconv.ParseBool(propertyValue) if err != nil { return false, err } return val, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/tags/tag_association.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L40-L48
go
train
// AttachTag attaches a tag ID to a managed object.
func (c *Manager) AttachTag(ctx context.Context, tagID string, ref mo.Reference) error
// AttachTag attaches a tag ID to a managed object. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/tags/tag_association.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L63-L68
go
train
// ListAttachedTags fetches the array of tag IDs attached to the given object.
func (c *Manager) ListAttachedTags(ctx context.Context, ref mo.Reference) ([]string, error)
// ListAttachedTags fetches the array of tag IDs attached to the given object. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/tags/tag_association.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L71-L86
go
train
// GetAttachedTags fetches the array of tags attached to the given object.
func (c *Manager) GetAttachedTags(ctx context.Context, ref mo.Reference) ([]Tag, error)
// GetAttachedTags fetches the array of tags attached to the given object. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vapi/tags/tag_association.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vapi/tags/tag_association.go#L89-L105
go
train
// ListAttachedObjects fetches the array of attached objects for the given tag ID.
func (c *Manager) ListAttachedObjects(ctx context.Context, tagID string) ([]mo.Reference, error)
// ListAttachedObjects fetches the array of attached objects for the given tag ID. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/channel.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/channel.go#L43-L58
go
train
// Request sends an RPC command to the vmx and checks the return code for success or error
func (c *ChannelOut) Request(request []byte) ([]byte, error)
// Request sends an RPC command to the vmx and checks the return code for success or error 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
sts/signer.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/signer.go#L92-L227
go
train
// Sign is a soap.Signer implementation which can be used to sign RequestSecurityToken and LoginByTokenBody requests.
func (s *Signer) Sign(env soap.Envelope) ([]byte, error)
// Sign is a soap.Signer implementation which can be used to sign RequestSecurityToken and LoginByTokenBody requests. func (s *Signer) Sign(env soap.Envelope) ([]byte, error)
{ var key *rsa.PrivateKey hasKey := false if s.Certificate != nil { key, hasKey = s.Certificate.PrivateKey.(*rsa.PrivateKey) if !hasKey { return nil, errors.New("sts: rsa.PrivateKey is required") } } created := time.Now().UTC() header := &internal.Security{ WSU: internal.WSU, WSSE: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", Timestamp: internal.Timestamp{ NS: internal.WSU, ID: newID(), Created: created.Format(internal.Time), Expires: created.Add(time.Minute).Format(internal.Time), // If STS receives this request after this, it is assumed to have expired. }, } env.Header.Security = header info := internal.KeyInfo{XMLName: xml.Name{Local: "ds:KeyInfo"}} var c14n, body string type requestToken interface { RequestSecurityToken() *internal.RequestSecurityToken } switch x := env.Body.(type) { case requestToken: if hasKey { // We need c14n for all requests, as its digest is included in the signature and must match on the server side. // We need the body in original form when using an ActAs or RenewTarget token, where the token and its signature are embedded in the body. req := x.RequestSecurityToken() c14n = req.C14N() body = req.String() id := newID() info.SecurityTokenReference = &internal.SecurityTokenReference{ Reference: &internal.SecurityReference{ URI: "#" + id, ValueType: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3", }, } header.BinarySecurityToken = &internal.BinarySecurityToken{ EncodingType: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary", ValueType: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3", ID: id, Value: base64.StdEncoding.EncodeToString(s.Certificate.Certificate[0]), } } else { header.UsernameToken = &internal.UsernameToken{ Username: s.user.Username(), } header.UsernameToken.Password, _ = s.user.Password() } case *methods.LoginByTokenBody: header.Assertion = s.Token if hasKey { if err := s.setTokenReference(&info); err != nil { return nil, err } c14n = internal.Marshal(x.Req) } default: // We can end up here via ssoadmin.SessionManager.Login(). // No other known cases where a signed request is needed. header.Assertion = s.Token if hasKey { if err := s.setTokenReference(&info); err != nil { return nil, err } type Req interface { C14N() string } c14n = env.Body.(Req).C14N() } } if !hasKey { return xml.Marshal(env) // Bearer token without key to sign } id := newID() tmpl := `<soap:Body xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="%s" wsu:Id="%s">%s</soap:Body>` c14n = fmt.Sprintf(tmpl, internal.WSU, id, c14n) if body == "" { body = c14n } else { body = fmt.Sprintf(tmpl, internal.WSU, id, body) } header.Signature = &internal.Signature{ XMLName: xml.Name{Local: "ds:Signature"}, NS: internal.DSIG, ID: s.keyID, KeyInfo: info, SignedInfo: internal.SignedInfo{ XMLName: xml.Name{Local: "ds:SignedInfo"}, NS: internal.DSIG, CanonicalizationMethod: internal.Method{ XMLName: xml.Name{Local: "ds:CanonicalizationMethod"}, Algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#", }, SignatureMethod: internal.Method{ XMLName: xml.Name{Local: "ds:SignatureMethod"}, Algorithm: internal.SHA256, }, Reference: []internal.Reference{ internal.NewReference(header.Timestamp.ID, header.Timestamp.C14N()), internal.NewReference(id, c14n), }, }, } sum := sha256.Sum256([]byte(header.Signature.SignedInfo.C14N())) sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:]) if err != nil { return nil, err } header.Signature.SignatureValue = internal.Value{ XMLName: xml.Name{Local: "ds:SignatureValue"}, Value: base64.StdEncoding.EncodeToString(sig), } return xml.Marshal(signedEnvelope{ NS: "http://schemas.xmlsoap.org/soap/envelope/", Header: *env.Header, Body: body, }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
sts/signer.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/sts/signer.go#L230-L316
go
train
// SignRequest is a rest.Signer implementation which can be used to sign rest.Client.LoginByTokenBody requests.
func (s *Signer) SignRequest(req *http.Request) error
// SignRequest is a rest.Signer implementation which can be used to sign rest.Client.LoginByTokenBody requests. func (s *Signer) SignRequest(req *http.Request) error
{ type param struct { key, val string } var params []string add := func(p param) { params = append(params, fmt.Sprintf(`%s="%s"`, p.key, p.val)) } var buf bytes.Buffer gz := gzip.NewWriter(&buf) if _, err := io.WriteString(gz, s.Token); err != nil { return fmt.Errorf("zip token: %s", err) } if err := gz.Close(); err != nil { return fmt.Errorf("zip token: %s", err) } add(param{ key: "token", val: base64.StdEncoding.EncodeToString(buf.Bytes()), }) if s.Certificate != nil { nonce := fmt.Sprintf("%d:%d", time.Now().UnixNano()/1e6, mrand.Int()) var body []byte if req.GetBody != nil { r, rerr := req.GetBody() if rerr != nil { return fmt.Errorf("sts: getting http.Request body: %s", rerr) } defer r.Close() body, rerr = ioutil.ReadAll(r) if rerr != nil { return fmt.Errorf("sts: reading http.Request body: %s", rerr) } } bhash := sha256.New().Sum(body) // Port in the signature must be that of the reverse proxy port, vCenter's default is port 80 port := "80" // TODO: get from lookup service var buf bytes.Buffer msg := []string{ nonce, req.Method, req.URL.Path, strings.ToLower(req.URL.Hostname()), port, } for i := range msg { buf.WriteString(msg[i]) buf.WriteByte('\n') } buf.Write(bhash) buf.WriteByte('\n') sum := sha256.Sum256(buf.Bytes()) key, ok := s.Certificate.PrivateKey.(*rsa.PrivateKey) if !ok { return errors.New("sts: rsa.PrivateKey is required to sign http.Request") } sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:]) if err != nil { return err } add(param{ key: "signature_alg", val: "RSA-SHA256", }) add(param{ key: "signature", val: base64.StdEncoding.EncodeToString(sig), }) add(param{ key: "nonce", val: nonce, }) add(param{ key: "bodyhash", val: base64.StdEncoding.EncodeToString(bhash), }) } req.Header.Set("Authorization", fmt.Sprintf("SIGN %s", strings.Join(params, ", "))) return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
find/finder.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L62-L90
go
train
// findRoot makes it possible to use "find" mode with a different root path. // Example: ResourcePoolList("/dc1/host/cluster1/...")
func (f *Finder) findRoot(ctx context.Context, root *list.Element, parts []string) bool
// findRoot makes it possible to use "find" mode with a different root path. // Example: ResourcePoolList("/dc1/host/cluster1/...") func (f *Finder) findRoot(ctx context.Context, root *list.Element, parts []string) bool
{ if len(parts) == 0 { return false } ix := len(parts) - 1 if parts[ix] != "..." { return false } if ix == 0 { return true // We already have the Object for root.Path } // Lookup the Object for the new root.Path rootPath := path.Join(root.Path, path.Join(parts[:ix]...)) ref, err := f.si.FindByInventoryPath(ctx, rootPath) if err != nil || ref == nil { // If we get an error or fail to match, fall through to find() with the original root and path return false } root.Path = rootPath root.Object = ref return true }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
find/finder.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L152-L178
go
train
// datacenterPath returns the absolute path to the Datacenter containing the given ref
func (f *Finder) datacenterPath(ctx context.Context, ref types.ManagedObjectReference) (string, error)
// datacenterPath returns the absolute path to the Datacenter containing the given ref 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
find/finder.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L276-L299
go
train
// Element returns an Element for the given ManagedObjectReference // This method is only useful for looking up the InventoryPath of a ManagedObjectReference.
func (f *Finder) Element(ctx context.Context, ref types.ManagedObjectReference) (*list.Element, error)
// Element returns an Element for the given ManagedObjectReference // This method is only useful for looking up the InventoryPath of a ManagedObjectReference. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
find/finder.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L303-L324
go
train
// ObjectReference converts the given ManagedObjectReference to a type from the object package via object.NewReference // with the object.Common.InventoryPath field set.
func (f *Finder) ObjectReference(ctx context.Context, ref types.ManagedObjectReference) (object.Reference, error)
// ObjectReference converts the given ManagedObjectReference to a type from the object package via object.NewReference // with the object.Common.InventoryPath field set. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
find/finder.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/find/finder.go#L881-L900
go
train
// ResourcePoolListAll combines ResourcePoolList and VirtualAppList // VirtualAppList is only called if ResourcePoolList does not find any pools with the given path.
func (f *Finder) ResourcePoolListAll(ctx context.Context, path string) ([]*object.ResourcePool, error)
// ResourcePoolListAll combines ResourcePoolList and VirtualAppList // VirtualAppList is only called if ResourcePoolList does not find any pools with the given path. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L116-L124
go
train
// 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.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
// 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. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L132-L136
go
train
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder
// NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder
{ e := &Encoder{printer{Writer: bufio.NewWriter(w)}} e.p.encoder = e return e }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L141-L144
go
train
// 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.
func (enc *Encoder) Indent(prefix, indent string)
// 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. func (enc *Encoder) Indent(prefix, indent string)
{ enc.p.prefix = prefix enc.p.indent = indent }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L152-L158
go
train
// 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.
func (enc *Encoder) Encode(v interface{}) error
// 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. 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() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L167-L173
go
train
// 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.
func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error
// 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. 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() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L324-L327
go
train
// deleteAttrPrefix removes an attribute name space prefix.
func (p *printer) deleteAttrPrefix(prefix string)
// deleteAttrPrefix removes an attribute name space prefix. func (p *printer) deleteAttrPrefix(prefix string)
{ delete(p.attrPrefix, p.attrNS[prefix]) delete(p.attrNS, prefix) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L352-L556
go
train
// marshalValue writes one or more XML elements representing val. // If val was obtained from a struct field, finfo must have its details.
func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error
// marshalValue writes one or more XML elements representing val. // If val was obtained from a struct field, finfo must have its details. func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error
{ if startTemplate != nil && startTemplate.Name.Local == "" { return fmt.Errorf("xml: EncodeElement of StartElement with missing name") } if !val.IsValid() { return nil } if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) { return nil } // Drill into interfaces and pointers. // This can turn into an infinite loop given a cyclic chain, // but it matches the Go 1 behavior. for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { if val.IsNil() { return nil } val = val.Elem() } kind := val.Kind() typ := val.Type() // Check for marshaler. if val.CanInterface() && typ.Implements(marshalerType) { return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(marshalerType) { return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate)) } } // Check for text marshaler. if val.CanInterface() && typ.Implements(textMarshalerType) { return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate)) } } // Slices and arrays iterate over the elements. They do not have an enclosing tag. if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 { for i, n := 0, val.Len(); i < n; i++ { if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil { return err } } return nil } tinfo, err := getTypeInfo(typ) if err != nil { return err } // Create start element. // Precedence for the XML element name is: // 0. startTemplate // 1. XMLName field in underlying struct; // 2. field name/tag in the struct field; and // 3. type name var start StartElement if startTemplate != nil { start.Name = startTemplate.Name start.Attr = append(start.Attr, startTemplate.Attr...) } else if tinfo.xmlname != nil { xmlname := tinfo.xmlname if xmlname.name != "" { start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name } else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" { start.Name = v } } if start.Name.Local == "" && finfo != nil { start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name } if start.Name.Local == "" { name := typ.Name() if name == "" { return &UnsupportedTypeError{typ} } start.Name.Local = name } // Add type attribute if necessary if finfo != nil && finfo.flags&fTypeAttr != 0 { start.Attr = append(start.Attr, Attr{xmlSchemaInstance, typeToString(typ)}) } // Attributes for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fAttr == 0 { continue } fv := finfo.value(val) name := Name{Space: finfo.xmlns, Local: finfo.name} if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) { continue } if fv.Kind() == reflect.Interface && fv.IsNil() { continue } if fv.CanInterface() && fv.Type().Implements(marshalerAttrType) { attr, err := fv.Interface().(MarshalerAttr).MarshalXMLAttr(name) if err != nil { return err } if attr.Name.Local != "" { start.Attr = append(start.Attr, attr) } continue } if fv.CanAddr() { pv := fv.Addr() if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) { attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name) if err != nil { return err } if attr.Name.Local != "" { start.Attr = append(start.Attr, attr) } continue } } if fv.CanInterface() && fv.Type().Implements(textMarshalerType) { text, err := fv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } start.Attr = append(start.Attr, Attr{name, string(text)}) continue } if fv.CanAddr() { pv := fv.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { text, err := pv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } start.Attr = append(start.Attr, Attr{name, string(text)}) continue } } // Dereference or skip nil pointer, interface values. switch fv.Kind() { case reflect.Ptr, reflect.Interface: if fv.IsNil() { continue } fv = fv.Elem() } s, b, err := p.marshalSimple(fv.Type(), fv) if err != nil { return err } if b != nil { s = string(b) } start.Attr = append(start.Attr, Attr{name, s}) } if err := p.writeStart(&start); err != nil { return err } if val.Kind() == reflect.Struct { err = p.marshalStruct(tinfo, val) } else { s, b, err1 := p.marshalSimple(typ, val) if err1 != nil { err = err1 } else if b != nil { EscapeText(p, b) } else { p.EscapeString(s) } } if err != nil { return err } if err := p.writeEnd(start.Name); err != nil { return err } return p.cachedWriteError() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L560-L584
go
train
// defaultStart returns the default start element to use, // given the reflect type, field info, and start template.
func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement
// defaultStart returns the default start element to use, // given the reflect type, field info, and start template. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L587-L604
go
train
// marshalInterface marshals a Marshaler interface value.
func (p *printer) marshalInterface(val Marshaler, start StartElement) error
// marshalInterface marshals a Marshaler interface value. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L607-L617
go
train
// marshalTextInterface marshals a TextMarshaler interface value.
func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error
// marshalTextInterface marshals a TextMarshaler interface value. 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) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L620-L656
go
train
// writeStart writes the given start element.
func (p *printer) writeStart(start *StartElement) error
// writeStart writes the given start element. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L852-L855
go
train
// return the bufio Writer's cached write error
func (p *printer) cachedWriteError() error
// return the bufio Writer's cached write error func (p *printer) cachedWriteError() error
{ _, err := p.Write(nil) return err }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L896-L910
go
train
// 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.
func (s *parentStack) trim(parents []string) error
// 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. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/xml/marshal.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/marshal.go#L913-L921
go
train
// push adds parent elements to the stack and writes open tags.
func (s *parentStack) push(parents []string) error
// push adds parent elements to the stack and writes open tags. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/object/find.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/object/find.go#L157-L174
go
train
// rootMatch returns true if the root object path should be printed
func (cmd *find) rootMatch(ctx context.Context, root object.Reference, client *vim25.Client, filter property.Filter) bool
// rootMatch returns true if the root object path should be printed 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vslm/object_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vslm/object_manager.go#L40-L54
go
train
// 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.
func NewObjectManager(client *vim25.Client, ref ...types.ManagedObjectReference) *ObjectManager
// 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. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vslm/object_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vslm/object_manager.go#L59-L124
go
train
// 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.
func (m ObjectManager) PlaceDisk(ctx context.Context, spec *types.VslmCreateSpec, pool types.ManagedObjectReference) error
// 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. 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 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/vstorage_object_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/vstorage_object_manager.go#L95-L115
go
train
// statDatastoreBacking checks if object(s) backing file exists on the given datastore ref.
func (m *VcenterVStorageObjectManager) statDatastoreBacking(ctx *Context, ref types.ManagedObjectReference, id *types.ID) map[types.ID]error
// statDatastoreBacking checks if object(s) backing file exists on the given datastore ref. func (m *VcenterVStorageObjectManager) statDatastoreBacking(ctx *Context, ref types.ManagedObjectReference, id *types.ID) map[types.ID]error
{ objs := m.objects[ref] // default to checking all objects if id != nil { // check for a specific object objs = map[types.ID]*VStorageObject{ *id: objs[*id], } } res := make(map[types.ID]error, len(objs)) ds := ctx.Map.Get(ref).(*Datastore) dc := ctx.Map.getEntityDatacenter(ds) fm := ctx.Map.FileManager() for _, obj := range objs { backing := obj.Config.Backing.(*types.BaseConfigInfoDiskFileBackingInfo) file, _ := fm.resolve(&dc.Self, backing.FilePath) _, res[obj.Config.Id] = os.Stat(file) } return res }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/vm/info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/vm/info.go#L182-L275
go
train
// collectReferences builds a unique set of MORs to the set of VirtualMachines, // so we can collect properties in a single call for each reference type {host,datastore,network}.
func (r *infoResult) collectReferences(pc *property.Collector, ctx context.Context) error
// collectReferences builds a unique set of MORs to the set of VirtualMachines, // so we can collect properties in a single call for each reference type {host,datastore,network}. func (r *infoResult) collectReferences(pc *property.Collector, ctx context.Context) error
{ // MOR -> Name map r.entities = make(map[types.ManagedObjectReference]string) var host []mo.HostSystem var network []mo.Network var opaque []mo.OpaqueNetwork var dvp []mo.DistributedVirtualPortgroup var datastore []mo.Datastore // Table to drive inflating refs to their mo.* counterparts (dest) // and save() the Name to r.entities w/o using reflection here. // Note that we cannot use a []mo.ManagedEntity here, since mo.Network has its own 'Name' field, // the mo.Network.ManagedEntity.Name field will not be set. vrefs := map[string]*struct { dest interface{} refs []types.ManagedObjectReference save func() }{ "HostSystem": { &host, nil, func() { for _, e := range host { r.entities[e.Reference()] = e.Name } }, }, "Network": { &network, nil, func() { for _, e := range network { r.entities[e.Reference()] = e.Name } }, }, "OpaqueNetwork": { &opaque, nil, func() { for _, e := range opaque { r.entities[e.Reference()] = e.Name } }, }, "DistributedVirtualPortgroup": { &dvp, nil, func() { for _, e := range dvp { r.entities[e.Reference()] = e.Name } }, }, "Datastore": { &datastore, nil, func() { for _, e := range datastore { r.entities[e.Reference()] = e.Name } }, }, } xrefs := make(map[types.ManagedObjectReference]bool) // Add MOR to vrefs[kind].refs avoiding any duplicates. addRef := func(refs ...types.ManagedObjectReference) { for _, ref := range refs { if _, exists := xrefs[ref]; exists { return } xrefs[ref] = true vref := vrefs[ref.Type] vref.refs = append(vref.refs, ref) } } for _, vm := range r.VirtualMachines { if r.cmd.General { if ref := vm.Summary.Runtime.Host; ref != nil { addRef(*ref) } } if r.cmd.Resources { addRef(vm.Datastore...) addRef(vm.Network...) } } for _, vref := range vrefs { if vref.refs == nil { continue } err := pc.Retrieve(ctx, vref.refs, []string{"name"}, vref.dest) if err != nil { return err } vref.save() } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L81-L92
go
train
// NewRegistry creates a new instances of Registry
func NewRegistry() *Registry
// NewRegistry creates a new instances of Registry 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 }