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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
|
/*
Copyright (c) 2014-2015 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 vm
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type intRange struct {
low, high int
}
var intRangeRegexp = regexp.MustCompile("^([0-9]+)-([0-9]+)$")
func (i *intRange) Set(s string) error {
m := intRangeRegexp.FindStringSubmatch(s)
if m == nil {
return fmt.Errorf("invalid range: %s", s)
}
low, err := strconv.Atoi(m[1])
if err != nil {
return fmt.Errorf("couldn't convert to integer: %v", err)
}
high, err := strconv.Atoi(m[2])
if err != nil {
return fmt.Errorf("couldn't convert to integer: %v", err)
}
if low > high {
return fmt.Errorf("invalid range: low > high")
}
i.low = low
i.high = high
return nil
}
func (i *intRange) String() string {
return fmt.Sprintf("%d-%d", i.low, i.high)
}
type vnc struct {
*flags.SearchFlag
Enable bool
Disable bool
Port int
PortRange intRange
Password string
}
func init() {
cmd := &vnc{}
err := cmd.PortRange.Set("5900-5999")
if err != nil {
fmt.Printf("Error setting port range %v", err)
}
cli.Register("vm.vnc", cmd)
}
func (cmd *vnc) Register(ctx context.Context, f *flag.FlagSet) {
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
f.BoolVar(&cmd.Enable, "enable", false, "Enable VNC")
f.BoolVar(&cmd.Disable, "disable", false, "Disable VNC")
f.IntVar(&cmd.Port, "port", -1, "VNC port (-1 for auto-select)")
f.Var(&cmd.PortRange, "port-range", "VNC port auto-select range")
f.StringVar(&cmd.Password, "password", "", "VNC password")
}
func (cmd *vnc) Process(ctx context.Context) error {
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
// Either may be true or none may be true.
if cmd.Enable && cmd.Disable {
return flag.ErrHelp
}
return nil
}
func (cmd *vnc) Usage() string {
return "VM..."
}
func (cmd *vnc) Description() string {
return `Enable or disable VNC for VM.
Port numbers are automatically chosen if not specified.
If neither -enable or -disable is specified, the current state is returned.
Examples:
govc vm.vnc -enable -password 1234 $vm | awk '{print $2}' | xargs open`
}
func (cmd *vnc) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.loadVMs(f.Args())
if err != nil {
return err
}
// Actuate settings in VMs
for _, vm := range vms {
switch {
case cmd.Enable:
err = vm.enable(cmd.Port, cmd.Password)
if err != nil {
return err
}
case cmd.Disable:
err = vm.disable()
if err != nil {
return err
}
}
}
// Reconfigure VMs to reflect updates
for _, vm := range vms {
err = vm.reconfigure()
if err != nil {
return err
}
}
return cmd.WriteResult(vncResult(vms))
}
func (cmd *vnc) loadVMs(args []string) ([]*vncVM, error) {
c, err := cmd.Client()
if err != nil {
return nil, err
}
vms, err := cmd.VirtualMachines(args)
if err != nil {
return nil, err
}
var vncVMs []*vncVM
for _, vm := range vms {
v, err := newVNCVM(c, vm)
if err != nil {
return nil, err
}
vncVMs = append(vncVMs, v)
}
// Assign vncHosts to vncVMs
hosts := make(map[string]*vncHost)
for _, vm := range vncVMs {
if h, ok := hosts[vm.hostReference().Value]; ok {
vm.host = h
continue
}
hs := object.NewHostSystem(c, vm.hostReference())
h, err := newVNCHost(c, hs, cmd.PortRange.low, cmd.PortRange.high)
if err != nil {
return nil, err
}
hosts[vm.hostReference().Value] = h
vm.host = h
}
return vncVMs, nil
}
type vncVM struct {
c *vim25.Client
vm *object.VirtualMachine
mvm mo.VirtualMachine
host *vncHost
curOptions vncOptions
newOptions vncOptions
}
func newVNCVM(c *vim25.Client, vm *object.VirtualMachine) (*vncVM, error) {
v := &vncVM{
c: c,
vm: vm,
}
virtualMachineProperties := []string{
"name",
"config.extraConfig",
"runtime.host",
}
pc := property.DefaultCollector(c)
ctx := context.TODO()
err := pc.RetrieveOne(ctx, vm.Reference(), virtualMachineProperties, &v.mvm)
if err != nil {
return nil, err
}
v.curOptions = vncOptionsFromExtraConfig(v.mvm.Config.ExtraConfig)
v.newOptions = vncOptionsFromExtraConfig(v.mvm.Config.ExtraConfig)
return v, nil
}
func (v *vncVM) hostReference() types.ManagedObjectReference {
return *v.mvm.Runtime.Host
}
func (v *vncVM) enable(port int, password string) error {
v.newOptions["enabled"] = "true"
v.newOptions["port"] = fmt.Sprintf("%d", port)
v.newOptions["password"] = password
// Find port if auto-select
if port == -1 {
// Reuse port if If VM already has a port, reuse it.
// Otherwise, find unused VNC port on host.
if p, ok := v.curOptions["port"]; ok && p != "" {
v.newOptions["port"] = p
} else {
port, err := v.host.popUnusedPort()
if err != nil {
return err
}
v.newOptions["port"] = fmt.Sprintf("%d", port)
}
}
return nil
}
func (v *vncVM) disable() error {
v.newOptions["enabled"] = "false"
v.newOptions["port"] = ""
v.newOptions["password"] = ""
return nil
}
func (v *vncVM) reconfigure() error {
if reflect.DeepEqual(v.curOptions, v.newOptions) {
// No changes to settings
return nil
}
spec := types.VirtualMachineConfigSpec{
ExtraConfig: v.newOptions.ToExtraConfig(),
}
ctx := context.TODO()
task, err := v.vm.Reconfigure(ctx, spec)
if err != nil {
return err
}
return task.Wait(ctx)
}
func (v *vncVM) uri() (string, error) {
ip, err := v.host.managementIP()
if err != nil {
return "", err
}
uri := fmt.Sprintf("vnc://:%s@%s:%s",
v.newOptions["password"],
ip,
v.newOptions["port"])
return uri, nil
}
func (v *vncVM) write(w io.Writer) error {
if strings.EqualFold(v.newOptions["enabled"], "true") {
uri, err := v.uri()
if err != nil {
return err
}
fmt.Printf("%s: %s\n", v.mvm.Name, uri)
} else {
fmt.Printf("%s: disabled\n", v.mvm.Name)
}
return nil
}
type vncHost struct {
c *vim25.Client
host *object.HostSystem
ports map[int]struct{}
ip string // This field is populated by `managementIP`
}
func newVNCHost(c *vim25.Client, host *object.HostSystem, low, high int) (*vncHost, error) {
ports := make(map[int]struct{})
for i := low; i <= high; i++ {
ports[i] = struct{}{}
}
used, err := loadUsedPorts(c, host.Reference())
if err != nil {
return nil, err
}
// Remove used ports from range
for _, u := range used {
delete(ports, u)
}
h := &vncHost{
c: c,
host: host,
ports: ports,
}
return h, nil
}
func loadUsedPorts(c *vim25.Client, host types.ManagedObjectReference) ([]int, error) {
ctx := context.TODO()
ospec := types.ObjectSpec{
Obj: host,
SelectSet: []types.BaseSelectionSpec{
&types.TraversalSpec{
Type: "HostSystem",
Path: "vm",
Skip: types.NewBool(false),
},
},
Skip: types.NewBool(false),
}
pspec := types.PropertySpec{
Type: "VirtualMachine",
PathSet: []string{"config.extraConfig"},
}
req := types.RetrieveProperties{
This: c.ServiceContent.PropertyCollector,
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: []types.PropertySpec{pspec},
},
},
}
var vms []mo.VirtualMachine
err := mo.RetrievePropertiesForRequest(ctx, c, req, &vms)
if err != nil {
return nil, err
}
var ports []int
for _, vm := range vms {
if vm.Config == nil || vm.Config.ExtraConfig == nil {
continue
}
options := vncOptionsFromExtraConfig(vm.Config.ExtraConfig)
if ps, ok := options["port"]; ok && ps != "" {
pi, err := strconv.Atoi(ps)
if err == nil {
ports = append(ports, pi)
}
}
}
return ports, nil
}
func (h *vncHost) popUnusedPort() (int, error) {
if len(h.ports) == 0 {
return 0, fmt.Errorf("no unused ports in range")
}
// Return first port we get when iterating
var port int
for port = range h.ports {
break
}
delete(h.ports, port)
return port, nil
}
func (h *vncHost) managementIP() (string, error) {
ctx := context.TODO()
if h.ip != "" {
return h.ip, nil
}
ips, err := h.host.ManagementIPs(ctx)
if err != nil {
return "", err
}
if len(ips) > 0 {
h.ip = ips[0].String()
} else {
h.ip = "<unknown>"
}
return h.ip, nil
}
type vncResult []*vncVM
func (vms vncResult) MarshalJSON() ([]byte, error) {
out := make(map[string]string)
for _, vm := range vms {
uri, err := vm.uri()
if err != nil {
return nil, err
}
out[vm.mvm.Name] = uri
}
return json.Marshal(out)
}
func (vms vncResult) Write(w io.Writer) error {
for _, vm := range vms {
err := vm.write(w)
if err != nil {
return err
}
}
return nil
}
type vncOptions map[string]string
var vncPrefix = "RemoteDisplay.vnc."
func vncOptionsFromExtraConfig(ov []types.BaseOptionValue) vncOptions {
vo := make(vncOptions)
for _, b := range ov {
o := b.GetOptionValue()
if strings.HasPrefix(o.Key, vncPrefix) {
key := o.Key[len(vncPrefix):]
if key != "key" {
vo[key] = o.Value.(string)
}
}
}
return vo
}
func (vo vncOptions) ToExtraConfig() []types.BaseOptionValue {
ov := make([]types.BaseOptionValue, 0)
for k, v := range vo {
key := vncPrefix + k
value := v
o := types.OptionValue{
Key: key,
Value: &value, // Pass pointer to avoid omitempty
}
ov = append(ov, &o)
}
// Don't know how to deal with the key option, set it to be empty...
o := types.OptionValue{
Key: vncPrefix + "key",
Value: new(string), // Pass pointer to avoid omitempty
}
ov = append(ov, &o)
return ov
}
|