Debian Codegraph @

rpcout/rpcout.go

raw
1 // Copyright 2016 VMware, Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package rpcout
16
17 import (
18 "errors"
19 "fmt"
20
21 "github.com/vmware/vmw-guestinfo/message"
22 )
23
24 // ErrRpciFormat represents an invalid result format
25 var ErrRpciFormat = errors.New("invalid format for RPCI command result")
26
27 const rpciProtocolNum uint32 = 0x49435052
28
29 // SendOne is a command-oriented wrapper for SendOneRaw
30 func SendOne(format string, a ...interface{}) (reply []byte, ok bool, err error) {
31 request := fmt.Sprintf(format, a...)
32 return SendOneRaw([]byte(request))
33 }
34
35 // SendOneRaw uses a throw-away RPCOut to send a request
36 func SendOneRaw(request []byte) (reply []byte, ok bool, err error) {
37 out := &RPCOut{}
38 if err = out.Start(); err != nil {
39 return
40 }
41 if reply, ok, err = out.Send(request); err != nil {
42 return
43 }
44 if err = out.Stop(); err != nil {
45 return
46 }
47 return
48 }
49
50 // RPCOut is an ougoing connection from the VM to the hypervisor
51 type RPCOut struct {
52 channel *message.Channel
53 }
54
55 // Start opens the connection
56 func (out *RPCOut) Start() error {
57 channel, err := message.NewChannel(rpciProtocolNum)
58 if err != nil {
59 return err
60 }
61 out.channel = channel
62 return nil
63 }
64
65 // Stop closes the connection
66 func (out *RPCOut) Stop() error {
67 err := out.channel.Close()
68 out.channel = nil
69 return err
70 }
71
72 // Send emits a request and receives a response
73 func (out *RPCOut) Send(request []byte) (reply []byte, ok bool, err error) {
74 if err = out.channel.Send(request); err != nil {
75 return
76 }
77
78 var resp []byte
79 if resp, err = out.channel.Receive(); err != nil {
80 return
81 }
82
83 switch string(resp[:2]) {
84 case "0 ":
85 reply = resp[2:]
86 case "1 ":
87 reply = resp[2:]
88 ok = true
89 default:
90 err = ErrRpciFormat
91 }
92 return
93 }