forked from vmware/govmomi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
336 lines (271 loc) · 7.32 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
Copyright (c) 2017 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package toolbox
import (
"bytes"
"fmt"
"log"
"net"
"os"
"sync"
"time"
"github.com/vmware/govmomi/toolbox/hgfs"
)
const (
// TOOLS_VERSION_UNMANAGED as defined in open-vm-tools/lib/include/vm_tools_version.h
toolsVersionUnmanaged = 0x7fffffff
// RPCIN_MAX_DELAY as defined in rpcChannelInt.h:
maxDelay = 10
)
var (
capabilities = []string{
// Without tools.set.version, the UI reports Tools are "running", but "not installed"
fmt.Sprintf("tools.set.version %d", toolsVersionUnmanaged),
// Required to invoke guest power operations (shutdown, reboot)
"tools.capability.statechange",
"tools.capability.hgfs_server toolbox 1",
}
netInterfaceAddrs = net.InterfaceAddrs
// If we have an RPCI send error, the channels will be reset.
// open-vm-tools/lib/rpcChannel/rpcChannel.c:RpcChannelCheckReset also backs off in this case
resetDelay = time.Duration(500) // 500 * 10ms == 5s
)
// Service receives and dispatches incoming RPC requests from the vmx
type Service struct {
name string
in Channel
out *ChannelOut
handlers map[string]Handler
stop chan struct{}
wg *sync.WaitGroup
delay time.Duration
rpcError bool
Command *CommandServer
Power *PowerCommandHandler
PrimaryIP func() string
}
// NewService initializes a Service instance
func NewService(rpcIn Channel, rpcOut Channel) *Service {
s := &Service{
name: "toolbox", // Same name used by vmtoolsd
in: NewTraceChannel(rpcIn),
out: &ChannelOut{NewTraceChannel(rpcOut)},
handlers: make(map[string]Handler),
wg: new(sync.WaitGroup),
stop: make(chan struct{}),
PrimaryIP: DefaultIP,
}
s.RegisterHandler("reset", s.Reset)
s.RegisterHandler("ping", s.Ping)
s.RegisterHandler("Set_Option", s.SetOption)
s.RegisterHandler("Capabilities_Register", s.CapabilitiesRegister)
s.Command = registerCommandServer(s)
s.Command.FileServer = hgfs.NewServer()
s.Command.FileServer.RegisterFileHandler("proc", s.Command.ProcessManager)
s.Command.FileServer.RegisterFileHandler(hgfs.ArchiveScheme, hgfs.NewArchiveHandler())
s.Power = registerPowerCommandHandler(s)
return s
}
// backoff exponentially increases the RPC poll delay up to maxDelay
func (s *Service) backoff() {
if s.delay < maxDelay {
if s.delay > 0 {
d := s.delay * 2
if d > s.delay && d < maxDelay {
s.delay = d
} else {
s.delay = maxDelay
}
} else {
s.delay = 1
}
}
}
func (s *Service) stopChannel() {
_ = s.in.Stop()
_ = s.out.Stop()
}
func (s *Service) startChannel() error {
err := s.in.Start()
if err != nil {
return err
}
return s.out.Start()
}
func (s *Service) checkReset() error {
if s.rpcError {
s.stopChannel()
err := s.startChannel()
if err != nil {
s.delay = resetDelay
return err
}
s.rpcError = false
}
return nil
}
// Start initializes the RPC channels and starts a goroutine to listen for incoming RPC requests
func (s *Service) Start() error {
err := s.startChannel()
if err != nil {
return err
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
// Same polling interval and backoff logic as vmtoolsd.
// Required in our case at startup at least, otherwise it is possible
// we miss the 1 Capabilities_Register call for example.
// Note we Send(response) even when nil, to let the VMX know we are here
var response []byte
for {
select {
case <-s.stop:
s.stopChannel()
return
case <-time.After(time.Millisecond * 10 * s.delay):
if err = s.checkReset(); err != nil {
continue
}
err = s.in.Send(response)
response = nil
if err != nil {
s.delay = resetDelay
s.rpcError = true
continue
}
request, _ := s.in.Receive()
if len(request) > 0 {
response = s.Dispatch(request)
s.delay = 0
} else {
s.backoff()
}
}
}
}()
return nil
}
// Stop cancels the RPC listener routine created via Start
func (s *Service) Stop() {
close(s.stop)
}
// Wait blocks until Start returns, allowing any current RPC in progress to complete.
func (s *Service) Wait() {
s.wg.Wait()
}
// Handler is given the raw argument portion of an RPC request and returns a response
type Handler func([]byte) ([]byte, error)
// RegisterHandler for the given RPC name
func (s *Service) RegisterHandler(name string, handler Handler) {
s.handlers[name] = handler
}
// Dispatch an incoming RPC request to a Handler
func (s *Service) Dispatch(request []byte) []byte {
msg := bytes.SplitN(request, []byte{' '}, 2)
name := msg[0]
// Trim NULL byte terminator
name = bytes.TrimRight(name, "\x00")
handler, ok := s.handlers[string(name)]
if !ok {
log.Printf("unknown command: %q\n", name)
return []byte("Unknown Command")
}
var args []byte
if len(msg) == 2 {
args = msg[1]
}
response, err := handler(args)
if err == nil {
response = append([]byte("OK "), response...)
} else {
log.Printf("error calling %s: %s\n", name, err)
response = append([]byte("ERR "), response...)
}
return response
}
// Reset is the default Handler for reset requests
func (s *Service) Reset([]byte) ([]byte, error) {
s.SendGuestInfo() // Send the IP info ASAP
return []byte("ATR " + s.name), nil
}
// Ping is the default Handler for ping requests
func (s *Service) Ping([]byte) ([]byte, error) {
return nil, nil
}
// SetOption is the default Handler for Set_Option requests
func (s *Service) SetOption(args []byte) ([]byte, error) {
opts := bytes.SplitN(args, []byte{' '}, 2)
key := string(opts[0])
val := string(opts[1])
if Trace {
fmt.Fprintf(os.Stderr, "set option %q=%q\n", key, val)
}
switch key {
case "broadcastIP": // TODO: const-ify
if val == "1" {
ip := s.PrimaryIP()
if ip == "" {
log.Printf("failed to find primary IP")
return nil, nil
}
msg := fmt.Sprintf("info-set guestinfo.ip %s", ip)
_, err := s.out.Request([]byte(msg))
if err != nil {
return nil, err
}
s.SendGuestInfo()
}
default:
// TODO: handle other options...
}
return nil, nil
}
// DefaultIP is used by default when responding to a Set_Option broadcastIP request
// It can be overridden with the Service.PrimaryIP field
func DefaultIP() string {
addrs, err := netInterfaceAddrs()
if err == nil {
for _, addr := range addrs {
if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() {
if ip.IP.To4() != nil {
return ip.IP.String()
}
}
}
}
return ""
}
func (s *Service) CapabilitiesRegister([]byte) ([]byte, error) {
for _, cap := range capabilities {
_, err := s.out.Request([]byte(cap))
if err != nil {
log.Printf("send %q: %s", cap, err)
}
}
return nil, nil
}
func (s *Service) SendGuestInfo() {
info := []func() ([]byte, error){
GuestInfoNicInfoRequest,
}
for i, r := range info {
b, err := r()
if err == nil {
_, err = s.out.Request(b)
}
if err != nil {
log.Printf("SendGuestInfo %d: %s", i, err)
}
}
}