github.com/vmware/govmomi@v0.51.0/toolbox/channel.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package toolbox
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  )
    11  
    12  // Channel abstracts the guest<->vmx RPC transport
    13  type Channel interface {
    14  	Start() error
    15  	Stop() error
    16  	Send([]byte) error
    17  	Receive() ([]byte, error)
    18  }
    19  
    20  var (
    21  	rpciOK  = []byte{'1', ' '}
    22  	rpciERR = []byte{'0', ' '}
    23  )
    24  
    25  // ChannelOut extends Channel to provide RPCI protocol helpers
    26  type ChannelOut struct {
    27  	Channel
    28  }
    29  
    30  // Request sends an RPC command to the vmx and checks the return code for success or error
    31  func (c *ChannelOut) Request(request []byte) ([]byte, error) {
    32  	if err := c.Send(request); err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	reply, err := c.Receive()
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	if bytes.HasPrefix(reply, rpciOK) {
    42  		return reply[2:], nil
    43  	}
    44  
    45  	return nil, fmt.Errorf("request %q: %q", request, reply)
    46  }