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

     1  /*
     2  Copyright (c) 2017 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package toolbox
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  )
    23  
    24  // Channel abstracts the guest<->vmx RPC transport
    25  type Channel interface {
    26  	Start() error
    27  	Stop() error
    28  	Send([]byte) error
    29  	Receive() ([]byte, error)
    30  }
    31  
    32  var (
    33  	rpciOK  = []byte{'1', ' '}
    34  	rpciERR = []byte{'0', ' '}
    35  )
    36  
    37  // ChannelOut extends Channel to provide RPCI protocol helpers
    38  type ChannelOut struct {
    39  	Channel
    40  }
    41  
    42  // Request sends an RPC command to the vmx and checks the return code for success or error
    43  func (c *ChannelOut) Request(request []byte) ([]byte, error) {
    44  	if err := c.Send(request); err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	reply, err := c.Receive()
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	if bytes.HasPrefix(reply, rpciOK) {
    54  		return reply[2:], nil
    55  	}
    56  
    57  	return nil, fmt.Errorf("request %q: %q", request, reply)
    58  }