1
0
mirror of https://github.com/Oxalide/vsphere-influxdb-go.git synced 2023-10-10 11:36:51 +00:00

add vendoring with go dep

This commit is contained in:
Adrian Todorov
2017-10-25 20:52:40 +00:00
parent 704f4d20d1
commit a59409f16b
1627 changed files with 489673 additions and 0 deletions

110
vendor/github.com/vmware/govmomi/govc/vm/change.go generated vendored Normal file
View File

@@ -0,0 +1,110 @@
/*
Copyright (c) 2015-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 vm
import (
"context"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type extraConfig []types.BaseOptionValue
func (e *extraConfig) String() string {
return fmt.Sprintf("%v", *e)
}
func (e *extraConfig) Set(v string) error {
r := strings.SplitN(v, "=", 2)
if len(r) < 2 {
return fmt.Errorf("failed to parse extraConfig: %s", v)
}
*e = append(*e, &types.OptionValue{Key: r[0], Value: r[1]})
return nil
}
type change struct {
*flags.VirtualMachineFlag
types.VirtualMachineConfigSpec
extraConfig extraConfig
}
func init() {
cli.Register("vm.change", &change{})
}
func (cmd *change) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.Int64Var(&cmd.MemoryMB, "m", 0, "Size in MB of memory")
f.Var(flags.NewInt32(&cmd.NumCPUs), "c", "Number of CPUs")
f.StringVar(&cmd.GuestId, "g", "", "Guest OS")
f.StringVar(&cmd.Name, "name", "", "Display name")
f.Var(&cmd.extraConfig, "e", "ExtraConfig. <key>=<value>")
f.Var(flags.NewOptionalBool(&cmd.NestedHVEnabled), "nested-hv-enabled", "Enable nested hardware-assisted virtualization")
cmd.Tools = &types.ToolsConfigInfo{}
f.Var(flags.NewOptionalBool(&cmd.Tools.SyncTimeWithHost), "sync-time-with-host", "Enable SyncTimeWithHost")
}
func (cmd *change) Description() string {
return `Change VM configuration.
To add ExtraConfig variables that can read within the guest, use the 'guestinfo.' prefix.
Examples:
govc vm.change -vm $vm -e smc.present=TRUE -e ich7m.present=TRUE
govc vm.change -vm $vm -e guestinfo.vmname $vm
# Read the variable set above inside the guest:
vmware-rpctool "info-get guestinfo.vmname"`
}
func (cmd *change) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *change) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
if len(cmd.extraConfig) > 0 {
cmd.VirtualMachineConfigSpec.ExtraConfig = cmd.extraConfig
}
task, err := vm.Reconfigure(ctx, cmd.VirtualMachineConfigSpec)
if err != nil {
return err
}
return task.Wait(ctx)
}

410
vendor/github.com/vmware/govmomi/govc/vm/clone.go generated vendored Normal file
View File

@@ -0,0 +1,410 @@
/*
Copyright (c) 2014-2016 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"
"flag"
"fmt"
"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 clone struct {
*flags.ClientFlag
*flags.DatacenterFlag
*flags.DatastoreFlag
*flags.StoragePodFlag
*flags.ResourcePoolFlag
*flags.HostSystemFlag
*flags.NetworkFlag
*flags.FolderFlag
*flags.VirtualMachineFlag
name string
memory int
cpus int
on bool
force bool
template bool
customization string
waitForIP bool
annotation string
Client *vim25.Client
Datacenter *object.Datacenter
Datastore *object.Datastore
StoragePod *object.StoragePod
ResourcePool *object.ResourcePool
HostSystem *object.HostSystem
Folder *object.Folder
VirtualMachine *object.VirtualMachine
}
func init() {
cli.Register("vm.clone", &clone{})
}
func (cmd *clone) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
cmd.StoragePodFlag, ctx = flags.NewStoragePodFlag(ctx)
cmd.StoragePodFlag.Register(ctx, f)
cmd.ResourcePoolFlag, ctx = flags.NewResourcePoolFlag(ctx)
cmd.ResourcePoolFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.NetworkFlag, ctx = flags.NewNetworkFlag(ctx)
cmd.NetworkFlag.Register(ctx, f)
cmd.FolderFlag, ctx = flags.NewFolderFlag(ctx)
cmd.FolderFlag.Register(ctx, f)
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.IntVar(&cmd.memory, "m", 0, "Size in MB of memory")
f.IntVar(&cmd.cpus, "c", 0, "Number of CPUs")
f.BoolVar(&cmd.on, "on", true, "Power on VM")
f.BoolVar(&cmd.force, "force", false, "Create VM if vmx already exists")
f.BoolVar(&cmd.template, "template", false, "Create a Template")
f.StringVar(&cmd.customization, "customization", "", "Customization Specification Name")
f.BoolVar(&cmd.waitForIP, "waitip", false, "Wait for VM to acquire IP address")
f.StringVar(&cmd.annotation, "annotation", "", "VM description")
}
func (cmd *clone) Usage() string {
return "NAME"
}
func (cmd *clone) Description() string {
return `Clone VM to NAME.
Examples:
govc vm.clone -vm template-vm new-vm`
}
func (cmd *clone) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
if err := cmd.StoragePodFlag.Process(ctx); err != nil {
return err
}
if err := cmd.ResourcePoolFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.NetworkFlag.Process(ctx); err != nil {
return err
}
if err := cmd.FolderFlag.Process(ctx); err != nil {
return err
}
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *clone) Run(ctx context.Context, f *flag.FlagSet) error {
var err error
if len(f.Args()) != 1 {
return flag.ErrHelp
}
cmd.name = f.Arg(0)
if cmd.name == "" {
return flag.ErrHelp
}
cmd.Client, err = cmd.ClientFlag.Client()
if err != nil {
return err
}
cmd.Datacenter, err = cmd.DatacenterFlag.Datacenter()
if err != nil {
return err
}
if cmd.StoragePodFlag.Isset() {
cmd.StoragePod, err = cmd.StoragePodFlag.StoragePod()
if err != nil {
return err
}
} else {
cmd.Datastore, err = cmd.DatastoreFlag.Datastore()
if err != nil {
return err
}
}
cmd.HostSystem, err = cmd.HostSystemFlag.HostSystemIfSpecified()
if err != nil {
return err
}
if cmd.HostSystem != nil {
if cmd.ResourcePool, err = cmd.HostSystem.ResourcePool(ctx); err != nil {
return err
}
} else {
// -host is optional
if cmd.ResourcePool, err = cmd.ResourcePoolFlag.ResourcePool(); err != nil {
return err
}
}
if cmd.Folder, err = cmd.FolderFlag.Folder(); err != nil {
return err
}
if cmd.VirtualMachine, err = cmd.VirtualMachineFlag.VirtualMachine(); err != nil {
return err
}
if cmd.VirtualMachine == nil {
return flag.ErrHelp
}
task, err := cmd.cloneVM(ctx)
if err != nil {
return err
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
return err
}
vm := object.NewVirtualMachine(cmd.Client, info.Result.(types.ManagedObjectReference))
if cmd.cpus > 0 || cmd.memory > 0 {
vmConfigSpec := types.VirtualMachineConfigSpec{}
if cmd.cpus > 0 {
vmConfigSpec.NumCPUs = int32(cmd.cpus)
}
if cmd.memory > 0 {
vmConfigSpec.MemoryMB = int64(cmd.memory)
}
vmConfigSpec.Annotation = cmd.annotation
task, err := vm.Reconfigure(ctx, vmConfigSpec)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
}
if cmd.on {
task, err := vm.PowerOn(ctx)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
if cmd.waitForIP {
_, err = vm.WaitForIP(ctx)
if err != nil {
return err
}
}
}
return nil
}
func (cmd *clone) cloneVM(ctx context.Context) (*object.Task, error) {
// search for the first network card of the source
devices, err := cmd.VirtualMachine.Device(ctx)
if err != nil {
return nil, err
}
var card *types.VirtualEthernetCard
for _, device := range devices {
if c, ok := device.(types.BaseVirtualEthernetCard); ok {
card = c.GetVirtualEthernetCard()
break
}
}
if card == nil {
return nil, fmt.Errorf("No network device found.")
}
// get the new backing information
dev, err := cmd.NetworkFlag.Device()
if err != nil {
return nil, err
}
//set backing info
card.Backing = dev.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard().Backing
// prepare virtual device config spec for network card
configSpecs := []types.BaseVirtualDeviceConfigSpec{
&types.VirtualDeviceConfigSpec{
Operation: types.VirtualDeviceConfigSpecOperationEdit,
Device: card,
},
}
folderref := cmd.Folder.Reference()
poolref := cmd.ResourcePool.Reference()
relocateSpec := types.VirtualMachineRelocateSpec{
DeviceChange: configSpecs,
Folder: &folderref,
Pool: &poolref,
}
if cmd.HostSystem != nil {
hostref := cmd.HostSystem.Reference()
relocateSpec.Host = &hostref
}
cloneSpec := &types.VirtualMachineCloneSpec{
Location: relocateSpec,
PowerOn: false,
Template: cmd.template,
}
// clone to storage pod
datastoreref := types.ManagedObjectReference{}
if cmd.StoragePod != nil && cmd.Datastore == nil {
storagePod := cmd.StoragePod.Reference()
// Build pod selection spec from config spec
podSelectionSpec := types.StorageDrsPodSelectionSpec{
StoragePod: &storagePod,
}
// Get the virtual machine reference
vmref := cmd.VirtualMachine.Reference()
// Build the placement spec
storagePlacementSpec := types.StoragePlacementSpec{
Folder: &folderref,
Vm: &vmref,
CloneName: cmd.name,
CloneSpec: cloneSpec,
PodSelectionSpec: podSelectionSpec,
Type: string(types.StoragePlacementSpecPlacementTypeClone),
}
// Get the storage placement result
storageResourceManager := object.NewStorageResourceManager(cmd.Client)
result, err := storageResourceManager.RecommendDatastores(ctx, storagePlacementSpec)
if err != nil {
return nil, err
}
// Get the recommendations
recommendations := result.Recommendations
if len(recommendations) == 0 {
return nil, fmt.Errorf("no recommendations")
}
// Get the first recommendation
datastoreref = recommendations[0].Action[0].(*types.StoragePlacementAction).Destination
} else if cmd.StoragePod == nil && cmd.Datastore != nil {
datastoreref = cmd.Datastore.Reference()
} else {
return nil, fmt.Errorf("Please provide either a datastore or a storagepod")
}
// Set the destination datastore
cloneSpec.Location.Datastore = &datastoreref
// Check if vmx already exists
if !cmd.force {
vmxPath := fmt.Sprintf("%s/%s.vmx", cmd.name, cmd.name)
var mds mo.Datastore
err = property.DefaultCollector(cmd.Client).RetrieveOne(ctx, datastoreref, []string{"name"}, &mds)
if err != nil {
return nil, err
}
datastore := object.NewDatastore(cmd.Client, datastoreref)
datastore.InventoryPath = mds.Name
_, err := datastore.Stat(ctx, vmxPath)
if err == nil {
dsPath := cmd.Datastore.Path(vmxPath)
return nil, fmt.Errorf("File %s already exists", dsPath)
}
}
// check if customization specification requested
if len(cmd.customization) > 0 {
// get the customization spec manager
customizationSpecManager := object.NewCustomizationSpecManager(cmd.Client)
// check if customization specification exists
exists, err := customizationSpecManager.DoesCustomizationSpecExist(ctx, cmd.customization)
if err != nil {
return nil, err
}
if exists == false {
return nil, fmt.Errorf("Customization specification %s does not exists.", cmd.customization)
}
// get the customization specification
customSpecItem, err := customizationSpecManager.GetCustomizationSpec(ctx, cmd.customization)
if err != nil {
return nil, err
}
customSpec := customSpecItem.Spec
// set the customization
cloneSpec.Customization = &customSpec
}
// clone virtualmachine
return cmd.VirtualMachine.Clone(ctx, cmd.Folder, cmd.name, *cloneSpec)
}

507
vendor/github.com/vmware/govmomi/govc/vm/create.go generated vendored Normal file
View File

@@ -0,0 +1,507 @@
/*
Copyright (c) 2014-2016 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"
"flag"
"fmt"
"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/units"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type create struct {
*flags.ClientFlag
*flags.DatacenterFlag
*flags.DatastoreFlag
*flags.StoragePodFlag
*flags.ResourcePoolFlag
*flags.HostSystemFlag
*flags.NetworkFlag
*flags.FolderFlag
name string
memory int
cpus int
guestID string
link bool
on bool
force bool
controller string
annotation string
iso string
isoDatastoreFlag *flags.DatastoreFlag
isoDatastore *object.Datastore
disk string
diskDatastoreFlag *flags.DatastoreFlag
diskDatastore *object.Datastore
// Only set if the disk argument is a byte size, which means the disk
// doesn't exist yet and should be created
diskByteSize int64
Client *vim25.Client
Datacenter *object.Datacenter
Datastore *object.Datastore
StoragePod *object.StoragePod
ResourcePool *object.ResourcePool
HostSystem *object.HostSystem
Folder *object.Folder
}
func init() {
cli.Register("vm.create", &create{})
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
cmd.StoragePodFlag, ctx = flags.NewStoragePodFlag(ctx)
cmd.StoragePodFlag.Register(ctx, f)
cmd.ResourcePoolFlag, ctx = flags.NewResourcePoolFlag(ctx)
cmd.ResourcePoolFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.NetworkFlag, ctx = flags.NewNetworkFlag(ctx)
cmd.NetworkFlag.Register(ctx, f)
cmd.FolderFlag, ctx = flags.NewFolderFlag(ctx)
cmd.FolderFlag.Register(ctx, f)
f.IntVar(&cmd.memory, "m", 1024, "Size in MB of memory")
f.IntVar(&cmd.cpus, "c", 1, "Number of CPUs")
f.StringVar(&cmd.guestID, "g", "otherGuest", "Guest OS")
f.BoolVar(&cmd.link, "link", true, "Link specified disk")
f.BoolVar(&cmd.on, "on", true, "Power on VM. Default is true if -disk argument is given.")
f.BoolVar(&cmd.force, "force", false, "Create VM if vmx already exists")
f.StringVar(&cmd.controller, "disk.controller", "scsi", "Disk controller type")
f.StringVar(&cmd.annotation, "annotation", "", "VM description")
f.StringVar(&cmd.iso, "iso", "", "ISO path")
cmd.isoDatastoreFlag, ctx = flags.NewCustomDatastoreFlag(ctx)
f.StringVar(&cmd.isoDatastoreFlag.Name, "iso-datastore", "", "Datastore for ISO file")
f.StringVar(&cmd.disk, "disk", "", "Disk path (to use existing) OR size (to create new, e.g. 20GB)")
cmd.diskDatastoreFlag, _ = flags.NewCustomDatastoreFlag(ctx)
f.StringVar(&cmd.diskDatastoreFlag.Name, "disk-datastore", "", "Datastore for disk file")
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
if err := cmd.StoragePodFlag.Process(ctx); err != nil {
return err
}
if err := cmd.ResourcePoolFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.NetworkFlag.Process(ctx); err != nil {
return err
}
if err := cmd.FolderFlag.Process(ctx); err != nil {
return err
}
// Default iso/disk datastores to the VM's datastore
if cmd.isoDatastoreFlag.Name == "" {
cmd.isoDatastoreFlag = cmd.DatastoreFlag
}
if cmd.diskDatastoreFlag.Name == "" {
cmd.diskDatastoreFlag = cmd.DatastoreFlag
}
return nil
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
var err error
if len(f.Args()) != 1 {
return flag.ErrHelp
}
cmd.name = f.Arg(0)
if cmd.name == "" {
return flag.ErrHelp
}
cmd.Client, err = cmd.ClientFlag.Client()
if err != nil {
return err
}
cmd.Datacenter, err = cmd.DatacenterFlag.Datacenter()
if err != nil {
return err
}
if cmd.StoragePodFlag.Isset() {
cmd.StoragePod, err = cmd.StoragePodFlag.StoragePod()
if err != nil {
return err
}
} else {
cmd.Datastore, err = cmd.DatastoreFlag.Datastore()
if err != nil {
return err
}
}
cmd.HostSystem, err = cmd.HostSystemFlag.HostSystemIfSpecified()
if err != nil {
return err
}
if cmd.HostSystem != nil {
if cmd.ResourcePool, err = cmd.HostSystem.ResourcePool(ctx); err != nil {
return err
}
} else {
// -host is optional
if cmd.ResourcePool, err = cmd.ResourcePoolFlag.ResourcePool(); err != nil {
return err
}
}
if cmd.Folder, err = cmd.FolderFlag.Folder(); err != nil {
return err
}
// Verify ISO exists
if cmd.iso != "" {
_, err = cmd.isoDatastoreFlag.Stat(ctx, cmd.iso)
if err != nil {
return err
}
cmd.isoDatastore, err = cmd.isoDatastoreFlag.Datastore()
if err != nil {
return err
}
}
// Verify disk exists
if cmd.disk != "" {
var b units.ByteSize
// If disk can be parsed as byte units, don't stat
err = b.Set(cmd.disk)
if err == nil {
cmd.diskByteSize = int64(b)
} else {
_, err = cmd.diskDatastoreFlag.Stat(ctx, cmd.disk)
if err != nil {
return err
}
cmd.diskDatastore, err = cmd.diskDatastoreFlag.Datastore()
if err != nil {
return err
}
}
}
task, err := cmd.createVM(ctx)
if err != nil {
return err
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
return err
}
vm := object.NewVirtualMachine(cmd.Client, info.Result.(types.ManagedObjectReference))
if cmd.on {
task, err := vm.PowerOn(ctx)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
}
return nil
}
func (cmd *create) createVM(ctx context.Context) (*object.Task, error) {
var devices object.VirtualDeviceList
var err error
spec := &types.VirtualMachineConfigSpec{
Name: cmd.name,
GuestId: cmd.guestID,
NumCPUs: int32(cmd.cpus),
MemoryMB: int64(cmd.memory),
Annotation: cmd.annotation,
}
devices, err = cmd.addStorage(nil)
if err != nil {
return nil, err
}
devices, err = cmd.addNetwork(devices)
if err != nil {
return nil, err
}
deviceChange, err := devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd)
if err != nil {
return nil, err
}
spec.DeviceChange = deviceChange
var datastore *object.Datastore
// If storage pod is specified, collect placement recommendations
if cmd.StoragePod != nil {
datastore, err = cmd.recommendDatastore(ctx, spec)
if err != nil {
return nil, err
}
} else {
datastore = cmd.Datastore
}
if !cmd.force {
vmxPath := fmt.Sprintf("%s/%s.vmx", cmd.name, cmd.name)
_, err := datastore.Stat(ctx, vmxPath)
if err == nil {
dsPath := cmd.Datastore.Path(vmxPath)
return nil, fmt.Errorf("File %s already exists", dsPath)
}
}
folder := cmd.Folder
spec.Files = &types.VirtualMachineFileInfo{
VmPathName: fmt.Sprintf("[%s]", datastore.Name()),
}
return folder.CreateVM(ctx, *spec, cmd.ResourcePool, cmd.HostSystem)
}
func (cmd *create) addStorage(devices object.VirtualDeviceList) (object.VirtualDeviceList, error) {
if cmd.controller != "ide" {
if cmd.controller == "nvme" {
nvme, err := devices.CreateNVMEController()
if err != nil {
return nil, err
}
devices = append(devices, nvme)
cmd.controller = devices.Name(nvme)
} else {
scsi, err := devices.CreateSCSIController(cmd.controller)
if err != nil {
return nil, err
}
devices = append(devices, scsi)
cmd.controller = devices.Name(scsi)
}
}
// If controller is specified to be IDE or if an ISO is specified, add IDE controller.
if cmd.controller == "ide" || cmd.iso != "" {
ide, err := devices.CreateIDEController()
if err != nil {
return nil, err
}
devices = append(devices, ide)
}
if cmd.diskByteSize != 0 {
controller, err := devices.FindDiskController(cmd.controller)
if err != nil {
return nil, err
}
disk := &types.VirtualDisk{
VirtualDevice: types.VirtualDevice{
Key: devices.NewKey(),
Backing: &types.VirtualDiskFlatVer2BackingInfo{
DiskMode: string(types.VirtualDiskModePersistent),
ThinProvisioned: types.NewBool(true),
},
},
CapacityInKB: cmd.diskByteSize / 1024,
}
devices.AssignController(disk, controller)
devices = append(devices, disk)
} else if cmd.disk != "" {
controller, err := devices.FindDiskController(cmd.controller)
if err != nil {
return nil, err
}
ds := cmd.diskDatastore.Reference()
path := cmd.diskDatastore.Path(cmd.disk)
disk := devices.CreateDisk(controller, ds, path)
if cmd.link {
disk = devices.ChildDisk(disk)
}
devices = append(devices, disk)
}
if cmd.iso != "" {
ide, err := devices.FindIDEController("")
if err != nil {
return nil, err
}
cdrom, err := devices.CreateCdrom(ide)
if err != nil {
return nil, err
}
cdrom = devices.InsertIso(cdrom, cmd.isoDatastore.Path(cmd.iso))
devices = append(devices, cdrom)
}
return devices, nil
}
func (cmd *create) addNetwork(devices object.VirtualDeviceList) (object.VirtualDeviceList, error) {
netdev, err := cmd.NetworkFlag.Device()
if err != nil {
return nil, err
}
devices = append(devices, netdev)
return devices, nil
}
func (cmd *create) recommendDatastore(ctx context.Context, spec *types.VirtualMachineConfigSpec) (*object.Datastore, error) {
sp := cmd.StoragePod.Reference()
// Build pod selection spec from config spec
podSelectionSpec := types.StorageDrsPodSelectionSpec{
StoragePod: &sp,
}
// Keep list of disks that need to be placed
var disks []*types.VirtualDisk
// Collect disks eligible for placement
for _, deviceConfigSpec := range spec.DeviceChange {
s := deviceConfigSpec.GetVirtualDeviceConfigSpec()
if s.Operation != types.VirtualDeviceConfigSpecOperationAdd {
continue
}
if s.FileOperation != types.VirtualDeviceConfigSpecFileOperationCreate {
continue
}
d, ok := s.Device.(*types.VirtualDisk)
if !ok {
continue
}
podConfigForPlacement := types.VmPodConfigForPlacement{
StoragePod: sp,
Disk: []types.PodDiskLocator{
{
DiskId: d.Key,
DiskBackingInfo: d.Backing,
},
},
}
podSelectionSpec.InitialVmConfig = append(podSelectionSpec.InitialVmConfig, podConfigForPlacement)
disks = append(disks, d)
}
sps := types.StoragePlacementSpec{
Type: string(types.StoragePlacementSpecPlacementTypeCreate),
ResourcePool: types.NewReference(cmd.ResourcePool.Reference()),
PodSelectionSpec: podSelectionSpec,
ConfigSpec: spec,
}
srm := object.NewStorageResourceManager(cmd.Client)
result, err := srm.RecommendDatastores(ctx, sps)
if err != nil {
return nil, err
}
// Use result to pin disks to recommended datastores
recs := result.Recommendations
if len(recs) == 0 {
return nil, fmt.Errorf("no recommendations")
}
ds := recs[0].Action[0].(*types.StoragePlacementAction).Destination
var mds mo.Datastore
err = property.DefaultCollector(cmd.Client).RetrieveOne(ctx, ds, []string{"name"}, &mds)
if err != nil {
return nil, err
}
datastore := object.NewDatastore(cmd.Client, ds)
datastore.InventoryPath = mds.Name
// Apply recommendation to eligible disks
for _, disk := range disks {
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
backing.Datastore = &ds
}
return datastore, nil
}

82
vendor/github.com/vmware/govmomi/govc/vm/destroy.go generated vendored Normal file
View File

@@ -0,0 +1,82 @@
/*
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"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type destroy struct {
*flags.ClientFlag
*flags.SearchFlag
}
func init() {
cli.Register("vm.destroy", &destroy{})
}
func (cmd *destroy) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
}
func (cmd *destroy) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
for _, vm := range vms {
task, err := vm.PowerOff(ctx)
if err != nil {
return err
}
// Ignore error since the VM may already been in powered off state.
// vm.Destroy will fail if the VM is still powered on.
_ = task.Wait(ctx)
task, err = vm.Destroy(ctx)
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return err
}
}
return nil
}

110
vendor/github.com/vmware/govmomi/govc/vm/disk/attach.go generated vendored Normal file
View File

@@ -0,0 +1,110 @@
/*
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 disk
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type attach struct {
*flags.DatastoreFlag
*flags.VirtualMachineFlag
persist bool
link bool
disk string
controller string
}
func init() {
cli.Register("vm.disk.attach", &attach{})
}
func (cmd *attach) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.BoolVar(&cmd.persist, "persist", true, "Persist attached disk")
f.BoolVar(&cmd.link, "link", true, "Link specified disk")
f.StringVar(&cmd.controller, "controller", "", "Disk controller")
f.StringVar(&cmd.disk, "disk", "", "Disk path name")
}
func (cmd *attach) Process(ctx context.Context) error {
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *attach) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
ds, err := cmd.Datastore()
if err != nil {
return err
}
devices, err := vm.Device(ctx)
if err != nil {
return err
}
controller, err := devices.FindDiskController(cmd.controller)
if err != nil {
return err
}
disk := devices.CreateDisk(controller, ds.Reference(), ds.Path(cmd.disk))
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
if cmd.link {
if cmd.persist {
backing.DiskMode = string(types.VirtualDiskModeIndependent_persistent)
} else {
backing.DiskMode = string(types.VirtualDiskModeIndependent_nonpersistent)
}
disk = devices.ChildDisk(disk)
return vm.AddDevice(ctx, disk)
}
if cmd.persist {
backing.DiskMode = string(types.VirtualDiskModePersistent)
} else {
backing.DiskMode = string(types.VirtualDiskModeNonpersistent)
}
return vm.AddDevice(ctx, disk)
}

174
vendor/github.com/vmware/govmomi/govc/vm/disk/change.go generated vendored Normal file
View File

@@ -0,0 +1,174 @@
/*
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 disk
import (
"context"
"errors"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/units"
"github.com/vmware/govmomi/vim25/types"
)
type change struct {
*flags.VirtualMachineFlag
name string
key int
label string
filePath string
bytes units.ByteSize
mode string
}
func init() {
cli.Register("vm.disk.change", &change{})
}
func (cmd *change) Description() string {
return `Change some properties of a VM's DISK
In particular, you can change the DISK mode, and the size (as long as it is bigger)
Examples:
govc vm.disk.change -vm VM -disk.key 2001 -size 10G
govc vm.disk.change -vm VM -disk.label "BDD disk" -size 10G
govc vm.disk.change -vm VM -disk.name "hard-1000-0" -size 12G
govc vm.disk.change -vm VM -disk.filePath "[DS] VM/VM-1.vmdk" -mode nonpersistent`
}
func (cmd *change) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
err := (&cmd.bytes).Set("0G")
if err != nil {
panic(err)
}
f.Var(&cmd.bytes, "size", "New disk size")
f.StringVar(&cmd.name, "disk.name", "", "Disk name")
f.StringVar(&cmd.label, "disk.label", "", "Disk label")
f.StringVar(&cmd.filePath, "disk.filePath", "", "Disk file name")
f.IntVar(&cmd.key, "disk.key", 0, "Disk unique key")
f.StringVar(&cmd.mode, "mode", "", fmt.Sprintf("Disk mode (%s)", strings.Join(vdmTypes, "|")))
}
func (cmd *change) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *change) FindDisk(ctx context.Context, list object.VirtualDeviceList) (*types.VirtualDisk, error) {
var disks []*types.VirtualDisk
for _, device := range list {
switch md := device.(type) {
case *types.VirtualDisk:
if cmd.CheckDiskProperties(ctx, list.Name(device), md) {
disks = append(disks, md)
}
default:
continue
}
}
switch len(disks) {
case 0:
return nil, errors.New("No disk found using the given values")
case 1:
return disks[0], nil
}
return nil, errors.New("The given disk values match multiple disks")
}
func (cmd *change) CheckDiskProperties(ctx context.Context, name string, disk *types.VirtualDisk) bool {
switch {
case cmd.key != 0 && disk.Key != int32(cmd.key):
fallthrough
case cmd.name != "" && name != cmd.name:
fallthrough
case cmd.label != "" && disk.DeviceInfo.GetDescription().Label != cmd.label:
return false
case cmd.filePath != "":
if b, ok := disk.Backing.(types.BaseVirtualDeviceFileBackingInfo); ok {
if b.GetVirtualDeviceFileBackingInfo().FileName != cmd.filePath {
return false
}
}
}
return true
}
func (cmd *change) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
devices, err := vm.Device(ctx)
if err != nil {
return err
}
editdisk, err := cmd.FindDisk(ctx, devices)
if err != nil {
return err
}
if int64(cmd.bytes) != 0 {
editdisk.CapacityInKB = int64(cmd.bytes) / 1024
}
backing := editdisk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
if len(cmd.mode) != 0 {
backing.DiskMode = cmd.mode
}
spec := types.VirtualMachineConfigSpec{}
config := &types.VirtualDeviceConfigSpec{
Device: editdisk,
Operation: types.VirtualDeviceConfigSpecOperationEdit,
}
config.FileOperation = ""
spec.DeviceChange = append(spec.DeviceChange, config)
task, err := vm.Reconfigure(ctx, spec)
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return fmt.Errorf("Error resizing main disk\nLogged Item: %s", err)
}
return nil
}

159
vendor/github.com/vmware/govmomi/govc/vm/disk/create.go generated vendored Normal file
View File

@@ -0,0 +1,159 @@
/*
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 disk
import (
"context"
"errors"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/units"
"github.com/vmware/govmomi/vim25/types"
)
type create struct {
*flags.DatastoreFlag
*flags.OutputFlag
*flags.VirtualMachineFlag
controller string
Name string
Bytes units.ByteSize
Thick bool
Eager bool
DiskMode string
}
var vdmTypes = []string{
string(types.VirtualDiskModePersistent),
string(types.VirtualDiskModeNonpersistent),
string(types.VirtualDiskModeUndoable),
string(types.VirtualDiskModeIndependent_persistent),
string(types.VirtualDiskModeIndependent_nonpersistent),
string(types.VirtualDiskModeAppend),
}
func init() {
cli.Register("vm.disk.create", &create{})
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
err := (&cmd.Bytes).Set("10G")
if err != nil {
panic(err)
}
f.StringVar(&cmd.controller, "controller", "", "Disk controller")
f.StringVar(&cmd.Name, "name", "", "Name for new disk")
f.Var(&cmd.Bytes, "size", "Size of new disk")
f.BoolVar(&cmd.Thick, "thick", false, "Thick provision new disk")
f.BoolVar(&cmd.Eager, "eager", false, "Eagerly scrub new disk")
f.StringVar(&cmd.DiskMode, "mode", "persistent", fmt.Sprintf("Disk mode (%s)", strings.Join(vdmTypes, "|")))
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *create) Description() string {
return `Create disk and attach to VM.
Examples:
govc vm.disk.create -vm $name -name $name/disk1 -size 10G`
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
if len(cmd.Name) == 0 {
return errors.New("please specify a disk name")
}
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return errors.New("please specify a vm")
}
ds, err := cmd.Datastore()
if err != nil {
return err
}
devices, err := vm.Device(ctx)
if err != nil {
return err
}
controller, err := devices.FindDiskController(cmd.controller)
if err != nil {
return err
}
vdmMatch := false
for _, vdm := range vdmTypes {
if cmd.DiskMode == vdm {
vdmMatch = true
}
}
if vdmMatch == false {
return errors.New("please specify a valid disk mode")
}
disk := devices.CreateDisk(controller, ds.Reference(), ds.Path(cmd.Name))
existing := devices.SelectByBackingInfo(disk.Backing)
if len(existing) > 0 {
cmd.Log("Disk already present\n")
return nil
}
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
if cmd.Thick {
backing.ThinProvisioned = types.NewBool(false)
backing.EagerlyScrub = types.NewBool(cmd.Eager)
}
backing.DiskMode = cmd.DiskMode
cmd.Log("Creating disk\n")
disk.CapacityInKB = int64(cmd.Bytes) / 1024
return vm.AddDevice(ctx, disk)
}

67
vendor/github.com/vmware/govmomi/govc/vm/guest/auth.go generated vendored Normal file
View File

@@ -0,0 +1,67 @@
/*
Copyright (c) 2014-2016 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 guest
import (
"context"
"flag"
"fmt"
"os"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
type AuthFlag struct {
auth types.NamePasswordAuthentication
}
func newAuthFlag(ctx context.Context) (*AuthFlag, context.Context) {
return &AuthFlag{}, ctx
}
func (flag *AuthFlag) String() string {
return fmt.Sprintf("%s:%s", flag.auth.Username, strings.Repeat("x", len(flag.auth.Password)))
}
func (flag *AuthFlag) Set(s string) error {
c := strings.Split(s, ":")
if len(c) > 0 {
flag.auth.Username = c[0]
if len(c) > 1 {
flag.auth.Password = c[1]
}
}
return nil
}
func (flag *AuthFlag) Register(ctx context.Context, f *flag.FlagSet) {
env := "GOVC_GUEST_LOGIN"
value := os.Getenv(env)
flag.Set(value)
usage := fmt.Sprintf("Guest VM credentials [%s]", env)
f.Var(flag, "l", usage)
}
func (flag *AuthFlag) Process(ctx context.Context) error {
return nil
}
func (flag *AuthFlag) Auth() types.BaseGuestAuthentication {
return &flag.auth
}

View File

@@ -0,0 +1,77 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"strconv"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/types"
)
type chmod struct {
*GuestFlag
}
func init() {
cli.Register("guest.chmod", &chmod{})
}
func (cmd *chmod) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
}
func (cmd *chmod) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *chmod) Usage() string {
return "MODE FILE"
}
func (cmd *chmod) Description() string {
return `Change FILE MODE on VM.
Examples:
govc guest.chmod -vm $name 0644 /var/log/foo.log`
}
func (cmd *chmod) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 2 {
return flag.ErrHelp
}
m, err := cmd.FileManager()
if err != nil {
return err
}
var attr types.GuestPosixFileAttributes
attr.Permissions, err = strconv.ParseInt(f.Arg(0), 0, 64)
if err != nil {
return err
}
return m.ChangeFileAttributes(ctx, cmd.Auth(), f.Arg(1), &attr)
}

View File

@@ -0,0 +1,96 @@
/*
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 guest
import (
"context"
"flag"
"strconv"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/types"
)
type chown struct {
*GuestFlag
}
func init() {
cli.Register("guest.chown", &chown{})
}
func (cmd *chown) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
}
func (cmd *chown) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *chown) Usage() string {
return "UID[:GID] FILE"
}
func (cmd *chown) Description() string {
return `Change FILE UID and GID on VM.
Examples:
govc guest.chown -vm $name UID[:GID] /var/log/foo.log`
}
func (cmd *chown) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 2 {
return flag.ErrHelp
}
m, err := cmd.FileManager()
if err != nil {
return err
}
var attr types.GuestPosixFileAttributes
ids := strings.SplitN(f.Arg(0), ":", 2)
if len(ids) == 0 {
return flag.ErrHelp
}
id, err := strconv.Atoi(ids[0])
if err != nil {
return err
}
attr.OwnerId = new(int32)
*attr.OwnerId = int32(id)
if len(ids) == 2 {
id, err = strconv.Atoi(ids[1])
if err != nil {
return err
}
attr.GroupId = new(int32)
*attr.GroupId = int32(id)
}
return m.ChangeFileAttributes(ctx, cmd.Auth(), f.Arg(1), &attr)
}

View File

@@ -0,0 +1,119 @@
/*
Copyright (c) 2014-2016 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 guest
import (
"flag"
"io"
"context"
"os"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/soap"
)
type download struct {
*GuestFlag
overwrite bool
}
func init() {
cli.Register("guest.download", &download{})
}
func (cmd *download) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.overwrite, "f", false, "If set, the local destination file is clobbered")
}
func (cmd *download) Usage() string {
return "SOURCE DEST"
}
func (cmd *download) Description() string {
return `Copy SOURCE from the guest VM to DEST on the local system.
If DEST name is "-", source is written to stdout.
Examples:
govc guest.download -l user:pass -vm=my-vm /var/log/my.log ./local.log
govc guest.download -l user:pass -vm=my-vm /etc/motd -`
}
func (cmd *download) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *download) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 2 {
return flag.ErrHelp
}
m, err := cmd.FileManager()
if err != nil {
return err
}
src := f.Arg(0)
dst := f.Arg(1)
_, err = os.Stat(dst)
if err == nil && !cmd.overwrite {
return os.ErrExist
}
info, err := m.InitiateFileTransferFromGuest(ctx, cmd.Auth(), src)
if err != nil {
return err
}
u, err := cmd.ParseURL(info.Url)
if err != nil {
return err
}
c, err := cmd.Client()
if err != nil {
return nil
}
p := soap.DefaultDownload
if dst == "-" {
f, _, err := c.Client.Download(u, &p)
if err != nil {
return err
}
_, err = io.Copy(os.Stdout, f)
return err
}
if cmd.OutputFlag.TTY {
logger := cmd.ProgressLogger("Downloading... ")
p.Progress = logger
defer logger.Wait()
}
return c.Client.DownloadFile(dst, u, &p)
}

View File

@@ -0,0 +1,47 @@
/*
Copyright (c) 2014-2016 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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type FileAttrFlag struct {
types.GuestPosixFileAttributes
}
func newFileAttrFlag(ctx context.Context) (*FileAttrFlag, context.Context) {
return &FileAttrFlag{}, ctx
}
func (flag *FileAttrFlag) Register(ctx context.Context, f *flag.FlagSet) {
f.Var(flags.NewOptionalInt32(&flag.OwnerId), "uid", "User ID")
f.Var(flags.NewOptionalInt32(&flag.GroupId), "gid", "Group ID")
f.Int64Var(&flag.Permissions, "perm", 0, "File permissions")
}
func (flag *FileAttrFlag) Process(ctx context.Context) error {
return nil
}
func (flag *FileAttrFlag) Attr() types.BaseGuestFileAttributes {
return &flag.GuestPosixFileAttributes
}

View File

@@ -0,0 +1,75 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
)
type getenv struct {
*GuestFlag
}
func init() {
cli.Register("guest.getenv", &getenv{})
}
func (cmd *getenv) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
}
func (cmd *getenv) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *getenv) Usage() string {
return "[NAME]..."
}
func (cmd *getenv) Description() string {
return `Read NAME environment variables from VM.
Examples:
govc guest.getenv -vm $name
govc guest.getenv -vm $name HOME`
}
func (cmd *getenv) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.ProcessManager()
if err != nil {
return err
}
vars, err := m.ReadEnvironmentVariable(ctx, cmd.Auth(), f.Args())
if err != nil {
return err
}
for _, v := range vars {
fmt.Printf("%s\n", v)
}
return nil
}

115
vendor/github.com/vmware/govmomi/govc/vm/guest/guest.go generated vendored Normal file
View File

@@ -0,0 +1,115 @@
/*
Copyright (c) 2014-2016 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 guest
import (
"errors"
"flag"
"context"
"net/url"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/guest"
"github.com/vmware/govmomi/object"
)
type GuestFlag struct {
*flags.ClientFlag
*flags.VirtualMachineFlag
*AuthFlag
}
func newGuestFlag(ctx context.Context) (*GuestFlag, context.Context) {
f := &GuestFlag{}
f.ClientFlag, ctx = flags.NewClientFlag(ctx)
f.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
f.AuthFlag, ctx = newAuthFlag(ctx)
return f, ctx
}
func (flag *GuestFlag) Register(ctx context.Context, f *flag.FlagSet) {
flag.ClientFlag.Register(ctx, f)
flag.VirtualMachineFlag.Register(ctx, f)
flag.AuthFlag.Register(ctx, f)
}
func (flag *GuestFlag) Process(ctx context.Context) error {
if err := flag.ClientFlag.Process(ctx); err != nil {
return err
}
if err := flag.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
if err := flag.AuthFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (flag *GuestFlag) FileManager() (*guest.FileManager, error) {
ctx := context.TODO()
c, err := flag.Client()
if err != nil {
return nil, err
}
vm, err := flag.VirtualMachine()
if err != nil {
return nil, err
}
o := guest.NewOperationsManager(c, vm.Reference())
return o.FileManager(ctx)
}
func (flag *GuestFlag) ProcessManager() (*guest.ProcessManager, error) {
ctx := context.TODO()
c, err := flag.Client()
if err != nil {
return nil, err
}
vm, err := flag.VirtualMachine()
if err != nil {
return nil, err
}
o := guest.NewOperationsManager(c, vm.Reference())
return o.ProcessManager(ctx)
}
func (flag *GuestFlag) ParseURL(urlStr string) (*url.URL, error) {
c, err := flag.Client()
if err != nil {
return nil, err
}
return c.Client.ParseURL(urlStr)
}
func (flag *GuestFlag) VirtualMachine() (*object.VirtualMachine, error) {
vm, err := flag.VirtualMachineFlag.VirtualMachine()
if err != nil {
return nil, err
}
if vm == nil {
return nil, errors.New("no vm specified")
}
return vm, nil
}

70
vendor/github.com/vmware/govmomi/govc/vm/guest/kill.go generated vendored Normal file
View File

@@ -0,0 +1,70 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
)
type kill struct {
*GuestFlag
pids pidSelector
}
func init() {
cli.Register("guest.kill", &kill{})
}
func (cmd *kill) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.Var(&cmd.pids, "p", "Process ID")
}
func (cmd *kill) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *kill) Description() string {
return `Kill process ID on VM.
Examples:
govc guest.kill -vm $name -p 12345`
}
func (cmd *kill) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.ProcessManager()
if err != nil {
return err
}
for _, pid := range cmd.pids {
if err := m.TerminateProcess(ctx, cmd.Auth(), pid); err != nil {
return err
}
}
return nil
}

121
vendor/github.com/vmware/govmomi/govc/vm/guest/ls.go generated vendored Normal file
View File

@@ -0,0 +1,121 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"fmt"
"os"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/units"
"github.com/vmware/govmomi/vim25/types"
)
type ls struct {
*GuestFlag
simple bool
}
func init() {
cli.Register("guest.ls", &ls{})
}
func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.simple, "s", false, "Simple path only listing") // sadly we used '-l' for guest login
}
func (cmd *ls) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *ls) Usage() string {
return "PATH"
}
func (cmd *ls) Description() string {
return `List PATH files in VM.
Examples:
govc guest.ls -vm $name /tmp`
}
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.FileManager()
if err != nil {
return err
}
var offset int32
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
for {
info, err := m.ListFiles(ctx, cmd.Auth(), f.Arg(0), offset, 0, f.Arg(1))
if err != nil {
return err
}
for _, f := range info.Files {
if cmd.simple {
fmt.Fprintln(tw, f.Path)
continue
}
var kind byte
switch types.GuestFileType(f.Type) {
case types.GuestFileTypeDirectory:
kind = 'd'
if f.Size == 0 {
f.Size = 4092
}
case types.GuestFileTypeSymlink:
kind = 'l'
case types.GuestFileTypeFile:
kind = '-'
}
switch x := f.Attributes.(type) {
case *types.GuestPosixFileAttributes:
perm := os.FileMode(x.Permissions).Perm().String()[1:]
fmt.Fprintf(tw, "%c%s\t%d\t%d\t", kind, perm, *x.OwnerId, *x.GroupId)
}
attr := f.Attributes.GetGuestFileAttributes()
fmt.Fprintf(tw, "%s\t%s\t%s\n", units.FileSize(f.Size), attr.ModificationTime.Format("Jan 2 15:04 2006"), f.Path)
}
_ = tw.Flush()
if info.Remaining == 0 {
break
}
offset += int32(len(info.Files))
}
return nil
}

View File

@@ -0,0 +1,83 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type mkdir struct {
*GuestFlag
createParents bool
}
func init() {
cli.Register("guest.mkdir", &mkdir{})
}
func (cmd *mkdir) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.createParents, "p", false, "Create intermediate directories as needed")
}
func (cmd *mkdir) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mkdir) Usage() string {
return "PATH"
}
func (cmd *mkdir) Description() string {
return `Create directory PATH in VM.
Examples:
govc guest.mkdir -vm $name /tmp/logs
govc guest.mkdir -vm $name -p /tmp/logs/foo/bar`
}
func (cmd *mkdir) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.FileManager()
if err != nil {
return err
}
err = m.MakeDirectory(ctx, cmd.Auth(), f.Arg(0), cmd.createParents)
// ignore EEXIST if -p flag is given
if err != nil && cmd.createParents {
if soap.IsSoapFault(err) {
soapFault := soap.ToSoapFault(err)
if _, ok := soapFault.VimFault().(types.FileAlreadyExists); ok {
return nil
}
}
}
return err
}

View File

@@ -0,0 +1,86 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
)
type mktemp struct {
*GuestFlag
dir bool
path string
prefix string
suffix string
}
func init() {
cli.Register("guest.mktemp", &mktemp{})
}
func (cmd *mktemp) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.dir, "d", false, "Make a directory instead of a file")
f.StringVar(&cmd.path, "p", "", "If specified, create relative to this directory")
f.StringVar(&cmd.prefix, "t", "", "Prefix")
f.StringVar(&cmd.suffix, "s", "", "Suffix")
}
func (cmd *mktemp) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mktemp) Description() string {
return `Create a temporary file or directory in VM.
Examples:
govc guest.mktemp -vm $name
govc guest.mktemp -vm $name -d
govc guest.mktemp -vm $name -t myprefix
govc guest.mktemp -vm $name -p /var/tmp/$USER`
}
func (cmd *mktemp) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.FileManager()
if err != nil {
return err
}
mk := m.CreateTemporaryFile
if cmd.dir {
mk = m.CreateTemporaryDirectory
}
name, err := mk(ctx, cmd.Auth(), cmd.prefix, cmd.suffix, cmd.path)
if err != nil {
return err
}
fmt.Println(name)
return nil
}

85
vendor/github.com/vmware/govmomi/govc/vm/guest/mv.go generated vendored Normal file
View File

@@ -0,0 +1,85 @@
/*
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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type mv struct {
*GuestFlag
noclobber bool
}
func init() {
cli.Register("guest.mv", &mv{})
}
func (cmd *mv) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.noclobber, "n", false, "Do not overwrite an existing file")
}
func (cmd *mv) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mv) Usage() string {
return "SOURCE DEST"
}
func (cmd *mv) Description() string {
return `Move (rename) files in VM.
Examples:
govc guest.mv -vm $name /tmp/foo.sh /tmp/bar.sh
govc guest.mv -vm $name -n /tmp/baz.sh /tmp/bar.sh`
}
func (cmd *mv) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.FileManager()
if err != nil {
return err
}
src := f.Arg(0)
dst := f.Arg(1)
err = m.MoveFile(ctx, cmd.Auth(), src, dst, !cmd.noclobber)
if err != nil {
if soap.IsSoapFault(err) {
soapFault := soap.ToSoapFault(err)
if _, ok := soapFault.VimFault().(types.NotAFile); ok {
err = m.MoveDirectory(ctx, cmd.Auth(), src, dst)
}
}
}
return err
}

199
vendor/github.com/vmware/govmomi/govc/vm/guest/ps.go generated vendored Normal file
View File

@@ -0,0 +1,199 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"fmt"
"io"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type ps struct {
*flags.OutputFlag
*GuestFlag
every bool
exit bool
wait bool
pids pidSelector
uids uidSelector
}
type pidSelector []int64
func (s *pidSelector) String() string {
return fmt.Sprint(*s)
}
func (s *pidSelector) Set(value string) error {
v, err := strconv.ParseInt(value, 0, 64)
if err != nil {
return err
}
*s = append(*s, v)
return nil
}
type uidSelector map[string]bool
func (s uidSelector) String() string {
return ""
}
func (s uidSelector) Set(value string) error {
s[value] = true
return nil
}
func init() {
cli.Register("guest.ps", &ps{})
}
func (cmd *ps) Register(ctx context.Context, f *flag.FlagSet) {
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
cmd.uids = make(map[string]bool)
f.BoolVar(&cmd.every, "e", false, "Select all processes")
f.BoolVar(&cmd.exit, "x", false, "Output exit time and code")
f.BoolVar(&cmd.wait, "X", false, "Wait for process to exit")
f.Var(&cmd.pids, "p", "Select by process ID")
f.Var(&cmd.uids, "U", "Select by process UID")
}
func (cmd *ps) Process(ctx context.Context) error {
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *ps) Description() string {
return `List processes in VM.
By default, unless the '-e', '-p' or '-U' flag is specified, only processes owned
by the '-l' flag user are displayed.
The '-x' and '-X' flags only apply to processes started by vmware-tools,
such as those started with the govc guest.start command.
Examples:
govc guest.ps -vm $name
govc guest.ps -vm $name -e
govc guest.ps -vm $name -p 12345
govc guest.ps -vm $name -U root`
}
func running(procs []types.GuestProcessInfo) bool {
for _, p := range procs {
if p.EndTime == nil {
return true
}
}
return false
}
func (cmd *ps) list(ctx context.Context) ([]types.GuestProcessInfo, error) {
m, err := cmd.ProcessManager()
if err != nil {
return nil, err
}
auth := cmd.Auth()
for {
procs, err := m.ListProcesses(ctx, auth, cmd.pids)
if err != nil {
return nil, err
}
if cmd.wait && running(procs) {
<-time.After(time.Millisecond * 250)
continue
}
return procs, nil
}
}
func (cmd *ps) Run(ctx context.Context, f *flag.FlagSet) error {
procs, err := cmd.list(ctx)
if err != nil {
return err
}
r := &psResult{cmd, procs}
return cmd.WriteResult(r)
}
type psResult struct {
cmd *ps
ProcessInfo []types.GuestProcessInfo
}
func (r *psResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "%s\t%s\t%s", "UID", "PID", "STIME")
if r.cmd.exit {
fmt.Fprintf(tw, "\t%s\t%s", "XTIME", "XCODE")
}
fmt.Fprint(tw, "\tCMD\n")
if len(r.cmd.pids) != 0 {
r.cmd.every = true
}
if !r.cmd.every && len(r.cmd.uids) == 0 {
r.cmd.uids[r.cmd.auth.Username] = true
}
for _, p := range r.ProcessInfo {
if r.cmd.every || r.cmd.uids[p.Owner] {
fmt.Fprintf(tw, "%s\t%d\t%s", p.Owner, p.Pid, p.StartTime.Format("15:04"))
if r.cmd.exit {
etime := "-"
ecode := "-"
if p.EndTime != nil {
etime = p.EndTime.Format("15:04")
ecode = strconv.Itoa(int(p.ExitCode))
}
fmt.Fprintf(tw, "\t%s\t%s", etime, ecode)
}
fmt.Fprintf(tw, "\t%s\n", strings.TrimSpace(p.CmdLine))
}
}
return tw.Flush()
}

64
vendor/github.com/vmware/govmomi/govc/vm/guest/rm.go generated vendored Normal file
View File

@@ -0,0 +1,64 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
)
type rm struct {
*GuestFlag
}
func init() {
cli.Register("guest.rm", &rm{})
}
func (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
}
func (cmd *rm) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *rm) Usage() string {
return "PATH"
}
func (cmd *rm) Description() string {
return `Remove file PATH in VM.
Examples:
govc guest.rm -vm $name /tmp/foo.log`
}
func (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.FileManager()
if err != nil {
return err
}
return m.DeleteFile(ctx, cmd.Auth(), f.Arg(0))
}

View File

@@ -0,0 +1,69 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
)
type rmdir struct {
*GuestFlag
recursive bool
}
func init() {
cli.Register("guest.rmdir", &rmdir{})
}
func (cmd *rmdir) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.recursive, "r", false, "Recursive removal")
}
func (cmd *rmdir) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *rmdir) Usage() string {
return "PATH"
}
func (cmd *rmdir) Description() string {
return `Remove directory PATH in VM.
Examples:
govc guest.rmdir -vm $name /tmp/empty-dir
govc guest.rmdir -vm $name -r /tmp/non-empty-dir`
}
func (cmd *rmdir) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.FileManager()
if err != nil {
return err
}
return m.DeleteDirectory(ctx, cmd.Auth(), f.Arg(0), cmd.recursive)
}

103
vendor/github.com/vmware/govmomi/govc/vm/guest/start.go generated vendored Normal file
View File

@@ -0,0 +1,103 @@
/*
Copyright (c) 2014-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 guest
import (
"context"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/types"
)
type start struct {
*GuestFlag
dir string
vars env
}
type env []string
func (e *env) String() string {
return fmt.Sprint(*e)
}
func (e *env) Set(value string) error {
*e = append(*e, value)
return nil
}
func init() {
cli.Register("guest.start", &start{})
}
func (cmd *start) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.StringVar(&cmd.dir, "C", "", "The absolute path of the working directory for the program to start")
f.Var(&cmd.vars, "e", "Set environment variable (key=val)")
}
func (cmd *start) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *start) Usage() string {
return "PATH [ARG]..."
}
func (cmd *start) Description() string {
return `Start program in VM.
The process can have its status queried with govc guest.ps.
When the process completes, its exit code and end time will be available for 5 minutes after completion.
Examples:
govc guest.start -vm $name /bin/mount /dev/hdb1 /data
pid=$(govc guest.start -vm $name /bin/long-running-thing)
govc guest.ps -vm $name -p $pid -X`
}
func (cmd *start) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.ProcessManager()
if err != nil {
return err
}
spec := types.GuestProgramSpec{
ProgramPath: f.Arg(0),
Arguments: strings.Join(f.Args()[1:], " "),
WorkingDirectory: cmd.dir,
EnvVariables: cmd.vars,
}
pid, err := m.StartProgram(ctx, cmd.Auth(), &spec)
if err != nil {
return err
}
fmt.Printf("%d\n", pid)
return nil
}

116
vendor/github.com/vmware/govmomi/govc/vm/guest/tools.go generated vendored Normal file
View File

@@ -0,0 +1,116 @@
/*
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 guest
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
)
type tools struct {
*flags.ClientFlag
*flags.SearchFlag
mount bool
upgrade bool
options string
unmount bool
}
func init() {
cli.Register("vm.guest.tools", &tools{})
}
func (cmd *tools) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
f.BoolVar(&cmd.mount, "mount", false, "Mount tools CD installer in the guest")
f.BoolVar(&cmd.upgrade, "upgrade", false, "Upgrade tools in the guest")
f.StringVar(&cmd.options, "options", "", "Installer options")
f.BoolVar(&cmd.unmount, "unmount", false, "Unmount tools CD installer in the guest")
}
func (cmd *tools) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *tools) Usage() string {
return "VM..."
}
func (cmd *tools) Description() string {
return `Manage guest tools in VM.
Examples:
govc vm.guest.tools -mount VM
govc vm.guest.tools -unmount VM
govc vm.guest.tools -upgrade -options "opt1 opt2" VM`
}
func (cmd *tools) Upgrade(ctx context.Context, vm *object.VirtualMachine) error {
task, err := vm.UpgradeTools(ctx, cmd.options)
if err != nil {
return err
}
return task.Wait(ctx)
}
func (cmd *tools) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
for _, vm := range vms {
switch {
case cmd.mount:
err = vm.MountToolsInstaller(ctx)
if err != nil {
return err
}
case cmd.upgrade:
err = cmd.Upgrade(ctx, vm)
if err != nil {
return err
}
case cmd.unmount:
err = vm.UnmountToolsInstaller(ctx)
if err != nil {
return err
}
default:
return flag.ErrHelp
}
}
return nil
}

126
vendor/github.com/vmware/govmomi/govc/vm/guest/touch.go generated vendored Normal file
View File

@@ -0,0 +1,126 @@
/*
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 guest
import (
"bytes"
"context"
"flag"
"time"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type touch struct {
*GuestFlag
nocreate bool
atime bool
date string
}
func init() {
cli.Register("guest.touch", &touch{})
}
func (cmd *touch) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
f.BoolVar(&cmd.atime, "a", false, "Change only the access time")
f.BoolVar(&cmd.nocreate, "c", false, "Do not create any files")
f.StringVar(&cmd.date, "d", "", "Use DATE instead of current time")
}
func (cmd *touch) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *touch) Usage() string {
return "FILE"
}
func (cmd *touch) Description() string {
return `Change FILE times on VM.
Examples:
govc guest.touch -vm $name /var/log/foo.log
govc guest.touch -vm $name -d "$(date -d '1 day ago')" /var/log/foo.log`
}
func (cmd *touch) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return flag.ErrHelp
}
m, err := cmd.FileManager()
if err != nil {
return err
}
name := f.Arg(0)
var attr types.GuestFileAttributes
now := time.Now()
if cmd.date != "" {
now, err = time.Parse(time.UnixDate, cmd.date)
if err != nil {
return err
}
}
if cmd.atime {
attr.AccessTime = &now
} else {
attr.ModificationTime = &now
}
err = m.ChangeFileAttributes(ctx, cmd.Auth(), name, &attr)
if err != nil && !cmd.nocreate && soap.IsSoapFault(err) {
fault := soap.ToSoapFault(err)
if _, ok := fault.VimFault().(types.FileNotFound); ok {
// create a new empty file
url, cerr := m.InitiateFileTransferToGuest(ctx, cmd.Auth(), name, &attr, 0, false)
if cerr != nil {
return cerr
}
u, cerr := cmd.ParseURL(url)
if cerr != nil {
return cerr
}
c, cerr := cmd.Client()
if cerr != nil {
return cerr
}
err = c.Client.Upload(new(bytes.Buffer), u, &soap.DefaultUpload)
if err == nil && cmd.date != "" {
err = m.ChangeFileAttributes(ctx, cmd.Auth(), name, &attr)
}
}
}
return err
}

View File

@@ -0,0 +1,133 @@
/*
Copyright (c) 2014-2016 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 guest
import (
"bytes"
"context"
"flag"
"io"
"os"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/soap"
)
type upload struct {
*GuestFlag
*FileAttrFlag
overwrite bool
}
func init() {
cli.Register("guest.upload", &upload{})
}
func (cmd *upload) Register(ctx context.Context, f *flag.FlagSet) {
cmd.GuestFlag, ctx = newGuestFlag(ctx)
cmd.GuestFlag.Register(ctx, f)
cmd.FileAttrFlag, ctx = newFileAttrFlag(ctx)
cmd.FileAttrFlag.Register(ctx, f)
f.BoolVar(&cmd.overwrite, "f", false, "If set, the guest destination file is clobbered")
}
func (cmd *upload) Usage() string {
return "SOURCE DEST"
}
func (cmd *upload) Description() string {
return `Copy SOURCE from the local system to DEST in the guest VM.
If SOURCE name is "-", read source from stdin.
Examples:
govc guest.upload -l user:pass -vm=my-vm ~/.ssh/id_rsa.pub /home/$USER/.ssh/authorized_keys
cowsay "have a great day" | govc guest.upload -l user:pass -vm=my-vm - /etc/motd`
}
func (cmd *upload) Process(ctx context.Context) error {
if err := cmd.GuestFlag.Process(ctx); err != nil {
return err
}
if err := cmd.FileAttrFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *upload) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 2 {
return flag.ErrHelp
}
m, err := cmd.FileManager()
if err != nil {
return err
}
src := f.Arg(0)
dst := f.Arg(1)
var size int64
var buf *bytes.Buffer
if src == "-" {
buf = new(bytes.Buffer)
size, err = io.Copy(buf, os.Stdin)
if err != nil {
return err
}
} else {
s, err := os.Stat(src)
if err != nil {
return err
}
size = s.Size()
}
url, err := m.InitiateFileTransferToGuest(ctx, cmd.Auth(), dst, cmd.Attr(), size, cmd.overwrite)
if err != nil {
return err
}
u, err := cmd.ParseURL(url)
if err != nil {
return err
}
c, err := cmd.Client()
if err != nil {
return nil
}
p := soap.DefaultUpload
if buf != nil {
p.ContentLength = size
return c.Client.Upload(buf, u, &p)
}
if cmd.OutputFlag.TTY {
logger := cmd.ProgressLogger("Uploading... ")
p.Progress = logger
defer logger.Wait()
}
return c.Client.UploadFile(src, u, nil)
}

345
vendor/github.com/vmware/govmomi/govc/vm/info.go generated vendored Normal file
View File

@@ -0,0 +1,345 @@
/*
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 (
"flag"
"fmt"
"io"
"os"
"strings"
"text/tabwriter"
"context"
"github.com/vmware/govmomi/find"
"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/units"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type info struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.SearchFlag
WaitForIP bool
General bool
ExtraConfig bool
Resources bool
ToolsConfigInfo bool
}
func init() {
cli.Register("vm.info", &info{})
}
func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
f.BoolVar(&cmd.WaitForIP, "waitip", false, "Wait for VM to acquire IP address")
f.BoolVar(&cmd.General, "g", true, "Show general summary")
f.BoolVar(&cmd.ExtraConfig, "e", false, "Show ExtraConfig")
f.BoolVar(&cmd.Resources, "r", false, "Show resource summary")
f.BoolVar(&cmd.ToolsConfigInfo, "t", false, "Show ToolsConfigInfo")
}
func (cmd *info) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return err
}
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
if _, ok := err.(*find.NotFoundError); ok {
// Continue with empty VM slice
} else {
return err
}
}
refs := make([]types.ManagedObjectReference, 0, len(vms))
for _, vm := range vms {
refs = append(refs, vm.Reference())
}
var res infoResult
var props []string
if cmd.OutputFlag.JSON {
props = nil // Load everything
} else {
props = []string{"summary"} // Load summary
if cmd.General {
props = append(props, "guest.ipAddress")
}
if cmd.ExtraConfig {
props = append(props, "config.extraConfig")
}
if cmd.Resources {
props = append(props, "datastore", "network")
}
if cmd.ToolsConfigInfo {
props = append(props, "config.tools")
}
}
pc := property.DefaultCollector(c)
if len(refs) != 0 {
err = pc.Retrieve(ctx, refs, props, &res.VirtualMachines)
if err != nil {
return err
}
}
if cmd.WaitForIP {
for i, vm := range res.VirtualMachines {
if vm.Guest == nil || vm.Guest.IpAddress == "" {
_, err = vms[i].WaitForIP(ctx)
if err != nil {
return err
}
// Reload virtual machine object
err = pc.RetrieveOne(ctx, vms[i].Reference(), props, &res.VirtualMachines[i])
if err != nil {
return err
}
}
}
}
if !cmd.OutputFlag.JSON {
res.objects = vms
res.cmd = cmd
if err = res.collectReferences(pc, ctx); err != nil {
return err
}
}
return cmd.WriteResult(&res)
}
type infoResult struct {
VirtualMachines []mo.VirtualMachine
objects []*object.VirtualMachine
entities map[types.ManagedObjectReference]string
cmd *info
}
// collectReferences builds a unique set of MORs to the set of VirtualMachines,
// so we can collect properties in a single call for each reference type {host,datastore,network}.
func (r *infoResult) collectReferences(pc *property.Collector, ctx context.Context) error {
r.entities = make(map[types.ManagedObjectReference]string) // MOR -> Name map
var host []mo.HostSystem
var network []mo.Network
var opaque []mo.OpaqueNetwork
var dvp []mo.DistributedVirtualPortgroup
var datastore []mo.Datastore
// Table to drive inflating refs to their mo.* counterparts (dest)
// and save() the Name to r.entities w/o using reflection here.
// Note that we cannot use a []mo.ManagedEntity here, since mo.Network has its own 'Name' field,
// the mo.Network.ManagedEntity.Name field will not be set.
vrefs := map[string]*struct {
dest interface{}
refs []types.ManagedObjectReference
save func()
}{
"HostSystem": {
&host, nil, func() {
for _, e := range host {
r.entities[e.Reference()] = e.Name
}
},
},
"Network": {
&network, nil, func() {
for _, e := range network {
r.entities[e.Reference()] = e.Name
}
},
},
"OpaqueNetwork": {
&opaque, nil, func() {
for _, e := range opaque {
r.entities[e.Reference()] = e.Name
}
},
},
"DistributedVirtualPortgroup": {
&dvp, nil, func() {
for _, e := range dvp {
r.entities[e.Reference()] = e.Name
}
},
},
"Datastore": {
&datastore, nil, func() {
for _, e := range datastore {
r.entities[e.Reference()] = e.Name
}
},
},
}
xrefs := make(map[types.ManagedObjectReference]bool)
// Add MOR to vrefs[kind].refs avoiding any duplicates.
addRef := func(refs ...types.ManagedObjectReference) {
for _, ref := range refs {
if _, exists := xrefs[ref]; exists {
return
}
xrefs[ref] = true
vref := vrefs[ref.Type]
vref.refs = append(vref.refs, ref)
}
}
for _, vm := range r.VirtualMachines {
if r.cmd.General {
if ref := vm.Summary.Runtime.Host; ref != nil {
addRef(*ref)
}
}
if r.cmd.Resources {
addRef(vm.Datastore...)
addRef(vm.Network...)
}
}
for _, vref := range vrefs {
if vref.refs == nil {
continue
}
err := pc.Retrieve(ctx, vref.refs, []string{"name"}, vref.dest)
if err != nil {
return err
}
vref.save()
}
return nil
}
func (r *infoResult) entityNames(refs []types.ManagedObjectReference) string {
var names []string
for _, ref := range refs {
names = append(names, r.entities[ref])
}
return strings.Join(names, ", ")
}
func (r *infoResult) Write(w io.Writer) error {
// Maintain order via r.objects as Property collector does not always return results in order.
objects := make(map[types.ManagedObjectReference]mo.VirtualMachine, len(r.VirtualMachines))
for _, o := range r.VirtualMachines {
objects[o.Reference()] = o
}
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
for _, o := range r.objects {
vm := objects[o.Reference()]
s := vm.Summary
fmt.Fprintf(tw, "Name:\t%s\n", s.Config.Name)
if r.cmd.General {
hostName := "<unavailable>"
if href := vm.Summary.Runtime.Host; href != nil {
if name, ok := r.entities[*href]; ok {
hostName = name
}
}
fmt.Fprintf(tw, " Path:\t%s\n", o.InventoryPath)
fmt.Fprintf(tw, " UUID:\t%s\n", s.Config.Uuid)
fmt.Fprintf(tw, " Guest name:\t%s\n", s.Config.GuestFullName)
fmt.Fprintf(tw, " Memory:\t%dMB\n", s.Config.MemorySizeMB)
fmt.Fprintf(tw, " CPU:\t%d vCPU(s)\n", s.Config.NumCpu)
fmt.Fprintf(tw, " Power state:\t%s\n", s.Runtime.PowerState)
fmt.Fprintf(tw, " Boot time:\t%s\n", s.Runtime.BootTime)
fmt.Fprintf(tw, " IP address:\t%s\n", s.Guest.IpAddress)
fmt.Fprintf(tw, " Host:\t%s\n", hostName)
}
if r.cmd.Resources {
if s.Storage == nil {
s.Storage = new(types.VirtualMachineStorageSummary)
}
fmt.Fprintf(tw, " CPU usage:\t%dMHz\n", s.QuickStats.OverallCpuUsage)
fmt.Fprintf(tw, " Host memory usage:\t%dMB\n", s.QuickStats.HostMemoryUsage)
fmt.Fprintf(tw, " Guest memory usage:\t%dMB\n", s.QuickStats.GuestMemoryUsage)
fmt.Fprintf(tw, " Storage uncommitted:\t%s\n", units.ByteSize(s.Storage.Uncommitted))
fmt.Fprintf(tw, " Storage committed:\t%s\n", units.ByteSize(s.Storage.Committed))
fmt.Fprintf(tw, " Storage unshared:\t%s\n", units.ByteSize(s.Storage.Unshared))
fmt.Fprintf(tw, " Storage:\t%s\n", r.entityNames(vm.Datastore))
fmt.Fprintf(tw, " Network:\t%s\n", r.entityNames(vm.Network))
}
if r.cmd.ExtraConfig {
fmt.Fprintf(tw, " ExtraConfig:\n")
for _, v := range vm.Config.ExtraConfig {
fmt.Fprintf(tw, " %s:\t%s\n", v.GetOptionValue().Key, v.GetOptionValue().Value)
}
}
if r.cmd.ToolsConfigInfo {
t := vm.Config.Tools
fmt.Fprintf(tw, " ToolsConfigInfo:\n")
fmt.Fprintf(tw, " ToolsVersion:\t%d\n", t.ToolsVersion)
fmt.Fprintf(tw, " AfterPowerOn:\t%s\n", flags.NewOptionalBool(&t.AfterPowerOn).String())
fmt.Fprintf(tw, " AfterResume:\t%s\n", flags.NewOptionalBool(&t.AfterResume).String())
fmt.Fprintf(tw, " BeforeGuestStandby:\t%s\n", flags.NewOptionalBool(&t.BeforeGuestStandby).String())
fmt.Fprintf(tw, " BeforeGuestShutdown:\t%s\n", flags.NewOptionalBool(&t.BeforeGuestShutdown).String())
fmt.Fprintf(tw, " BeforeGuestReboot:\t%s\n", flags.NewOptionalBool(&t.BeforeGuestReboot).String())
fmt.Fprintf(tw, " ToolsUpgradePolicy:\t%s\n", t.ToolsUpgradePolicy)
fmt.Fprintf(tw, " PendingCustomization:\t%s\n", t.PendingCustomization)
fmt.Fprintf(tw, " SyncTimeWithHost:\t%s\n", flags.NewOptionalBool(&t.SyncTimeWithHost).String())
}
}
return tw.Flush()
}

194
vendor/github.com/vmware/govmomi/govc/vm/ip.go generated vendored Normal file
View File

@@ -0,0 +1,194 @@
/*
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"
"flag"
"fmt"
"strings"
"time"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/govc/host/esxcli"
"github.com/vmware/govmomi/object"
)
type ip struct {
*flags.OutputFlag
*flags.SearchFlag
esx bool
all bool
v4 bool
wait time.Duration
nic string
}
func init() {
cli.Register("vm.ip", &ip{})
}
func (cmd *ip) Register(ctx context.Context, f *flag.FlagSet) {
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
f.BoolVar(&cmd.esx, "esxcli", false, "Use esxcli instead of guest tools")
f.BoolVar(&cmd.all, "a", false, "Wait for an IP address on all NICs")
f.StringVar(&cmd.nic, "n", "", "Wait for IP address on NIC, specified by device name or MAC")
f.BoolVar(&cmd.v4, "v4", false, "Only report IPv4 addresses")
f.DurationVar(&cmd.wait, "wait", time.Hour, "Wait time for the VM obtain an IP address")
}
func (cmd *ip) Usage() string {
return "VM..."
}
func (cmd *ip) Description() string {
return `List IPs for VM.
By default the vm.ip command depends on vmware-tools to report the 'guest.ipAddress' field and will
wait until it has done so. This value can also be obtained using:
govc vm.info -json $vm | jq -r .VirtualMachines[].Guest.IpAddress
When given the '-a' flag, only IP addresses for which there is a corresponding virtual nic are listed.
If there are multiple nics, the listed addresses will be comma delimited. The '-a' flag depends on
vmware-tools to report the 'guest.net' field and will wait until it has done so for all nics.
Note that this list includes IPv6 addresses if any, use '-v4' to filter them out. IP addresses reported
by tools for which there is no virtual nic are not included, for example that of the 'docker0' interface.
These values can also be obtained using:
govc vm.info -json $vm | jq -r .VirtualMachines[].Guest.Net[].IpConfig.IpAddress[].IpAddress
When given the '-n' flag, filters '-a' behavior to the nic specified by MAC address or device name.
The 'esxcli' flag does not require vmware-tools to be installed, but does require the ESX host to
have the /Net/GuestIPHack setting enabled.
The 'wait' flag default to 1hr (original default was infinite). If a VM does not obtain an IP within
the wait time, the command will still exit with status 0.
Examples:
govc vm.ip $vm
govc vm.ip -wait 5m $vm
govc vm.ip -a -v4 $vm
govc vm.ip -n 00:0c:29:57:7b:c3 $vm
govc vm.ip -n ethernet-0 $vm
govc host.esxcli system settings advanced set -o /Net/GuestIPHack -i 1
govc vm.ip -esxcli $vm`
}
func (cmd *ip) Process(ctx context.Context) error {
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *ip) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return err
}
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
var get func(*object.VirtualMachine, context.Context) (string, error)
if cmd.esx {
get = func(vm *object.VirtualMachine, deadline context.Context) (string, error) {
guest := esxcli.NewGuestInfo(c)
ticker := time.NewTicker(time.Millisecond * 500)
defer ticker.Stop()
for {
select {
case <-ticker.C:
ip, err := guest.IpAddress(vm)
if err != nil {
return "", err
}
if ip != "0.0.0.0" {
return ip, nil
}
case <-deadline.Done():
return "", nil
}
}
}
} else {
var hwaddr []string
if cmd.nic != "" {
hwaddr = strings.Split(cmd.nic, ",")
}
get = func(vm *object.VirtualMachine, deadline context.Context) (string, error) {
if cmd.all || hwaddr != nil {
macs, err := vm.WaitForNetIP(deadline, cmd.v4, hwaddr...)
if err != nil {
return "", err
}
var ips []string
for _, addrs := range macs {
for _, ip := range addrs {
ips = append(ips, ip)
}
}
return strings.Join(ips, ","), nil
}
return vm.WaitForIP(deadline)
}
}
for _, vm := range vms {
deadline, cancel := context.WithDeadline(ctx, time.Now().Add(cmd.wait))
ip, err := get(vm, deadline)
if err != nil {
if deadline.Err() != context.DeadlineExceeded {
cancel()
return err
}
}
cancel()
if ip == "" {
continue
}
// TODO(PN): Display inventory path to VM
fmt.Fprintf(cmd, "%s\n", ip)
}
return nil
}

View File

@@ -0,0 +1,72 @@
/*
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"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type markastemplate struct {
*flags.SearchFlag
}
func init() {
cli.Register("vm.markastemplate", &markastemplate{})
}
func (cmd *markastemplate) Register(ctx context.Context, f *flag.FlagSet) {
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
}
func (cmd *markastemplate) Process(ctx context.Context) error {
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *markastemplate) Usage() string {
return "VM..."
}
func (cmd *markastemplate) Description() string {
return `Mark VM as a virtual machine template.
Examples:
govc vm.markastemplate $name`
}
func (cmd *markastemplate) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
for _, vm := range vms {
err := vm.MarkAsTemplate(ctx)
if err != nil {
return err
}
}
return nil
}

106
vendor/github.com/vmware/govmomi/govc/vm/markasvm.go generated vendored Normal file
View File

@@ -0,0 +1,106 @@
/*
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"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type markasvm struct {
*flags.SearchFlag
*flags.ResourcePoolFlag
*flags.HostSystemFlag
}
func init() {
cli.Register("vm.markasvm", &markasvm{})
}
func (cmd *markasvm) Register(ctx context.Context, f *flag.FlagSet) {
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
cmd.ResourcePoolFlag, ctx = flags.NewResourcePoolFlag(ctx)
cmd.ResourcePoolFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *markasvm) Process(ctx context.Context) error {
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
if err := cmd.ResourcePoolFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *markasvm) Usage() string {
return "VM..."
}
func (cmd *markasvm) Description() string {
return `Mark VM template as a virtual machine.
Examples:
govc vm.markasvm $name -host host1
govc vm.markasvm $name -pool cluster1/Resources`
}
func (cmd *markasvm) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
pool, err := cmd.ResourcePoolIfSpecified()
if err != nil {
return err
}
host, err := cmd.HostSystemFlag.HostSystemIfSpecified()
if err != nil {
return err
}
if pool == nil {
if host == nil {
return flag.ErrHelp
}
pool, err = host.ResourcePool(ctx)
if err != nil {
return err
}
}
for _, vm := range vms {
err := vm.MarkAsVirtualMachine(ctx, *pool, host)
if err != nil {
return err
}
}
return nil
}

147
vendor/github.com/vmware/govmomi/govc/vm/migrate.go generated vendored Normal file
View File

@@ -0,0 +1,147 @@
/*
Copyright (c) 2016 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"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
type migrate struct {
*flags.ResourcePoolFlag
*flags.HostSystemFlag
*flags.DatastoreFlag
*flags.SearchFlag
priority types.VirtualMachineMovePriority
spec types.VirtualMachineRelocateSpec
}
func init() {
cli.Register("vm.migrate", &migrate{})
}
func (cmd *migrate) Register(ctx context.Context, f *flag.FlagSet) {
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
cmd.ResourcePoolFlag, ctx = flags.NewResourcePoolFlag(ctx)
cmd.ResourcePoolFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
f.StringVar((*string)(&cmd.priority), "priority", string(types.VirtualMachineMovePriorityDefaultPriority), "The task priority")
}
func (cmd *migrate) Process(ctx context.Context) error {
if err := cmd.ResourcePoolFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *migrate) Usage() string {
return "VM..."
}
func (cmd *migrate) Description() string {
return `Migrates VM to a specific resource pool, host or datastore.
Examples:
govc vm.migrate -host another-host vm-1 vm-2 vm-3
govc vm.migrate -ds another-ds vm-1 vm-2 vm-3`
}
func (cmd *migrate) relocate(ctx context.Context, vm *object.VirtualMachine) error {
task, err := vm.Relocate(ctx, cmd.spec, cmd.priority)
if err != nil {
return err
}
logger := cmd.DatastoreFlag.ProgressLogger(fmt.Sprintf("migrating %s... ", vm.Reference()))
_, err = task.WaitForResult(ctx, logger)
if err != nil {
return err
}
logger.Wait()
return nil
}
func (cmd *migrate) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
host, err := cmd.HostSystemFlag.HostSystemIfSpecified()
if err != nil {
return err
}
if host != nil {
ref := host.Reference()
cmd.spec.Host = &ref
}
pool, err := cmd.ResourcePoolFlag.ResourcePoolIfSpecified()
if err != nil {
return err
}
if pool != nil {
ref := pool.Reference()
cmd.spec.Pool = &ref
}
ds, err := cmd.DatastoreFlag.DatastoreIfSpecified()
if err != nil {
return err
}
if ds != nil {
ref := ds.Reference()
cmd.spec.Datastore = &ref
}
for _, vm := range vms {
err = cmd.relocate(ctx, vm)
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,83 @@
/*
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 network
import (
"context"
"errors"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type add struct {
*flags.VirtualMachineFlag
*flags.NetworkFlag
}
func init() {
cli.Register("vm.network.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
cmd.NetworkFlag, ctx = flags.NewNetworkFlag(ctx)
cmd.NetworkFlag.Register(ctx, f)
}
func (cmd *add) Description() string {
return `Add network adapter to VM.
Examples:
govc vm.network.add -vm $vm -net "VM Network" -net.adapter e1000e
govc device.info -vm $vm ethernet-*`
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
if err := cmd.NetworkFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachineFlag.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return errors.New("please specify a vm")
}
// Set network if specified as extra argument.
if f.NArg() > 0 {
_ = cmd.NetworkFlag.Set(f.Arg(0))
}
net, err := cmd.NetworkFlag.Device()
if err != nil {
return err
}
return vm.AddDevice(ctx, net)
}

View File

@@ -0,0 +1,120 @@
/*
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 network
import (
"context"
"errors"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type change struct {
*flags.VirtualMachineFlag
*flags.NetworkFlag
}
func init() {
cli.Register("vm.network.change", &change{})
}
func (cmd *change) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
cmd.NetworkFlag, ctx = flags.NewNetworkFlag(ctx)
cmd.NetworkFlag.Register(ctx, f)
}
func (cmd *change) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
if err := cmd.NetworkFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *change) Usage() string {
return "DEVICE"
}
func (cmd *change) Description() string {
return `Change network DEVICE configuration.
Examples:
govc vm.network.change -vm $vm -net PG2 ethernet-0
govc vm.network.change -vm $vm -net.address 00:00:0f:2e:5d:69 ethernet-0
govc device.info -vm $vm ethernet-*`
}
func (cmd *change) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachineFlag.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return errors.New("please specify a vm")
}
name := f.Arg(0)
if name == "" {
return errors.New("please specify a device name")
}
// Set network if specified as extra argument.
if f.NArg() > 1 {
_ = cmd.NetworkFlag.Set(f.Arg(1))
}
devices, err := vm.Device(ctx)
if err != nil {
return err
}
net := devices.Find(name)
if net == nil {
return fmt.Errorf("device '%s' not found", name)
}
dev, err := cmd.NetworkFlag.Device()
if err != nil {
return err
}
current := net.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
changed := dev.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
current.Backing = changed.Backing
if changed.MacAddress != "" {
current.MacAddress = changed.MacAddress
}
if changed.AddressType != "" {
current.AddressType = changed.AddressType
}
return vm.EditDevice(ctx, net)
}

160
vendor/github.com/vmware/govmomi/govc/vm/power.go generated vendored Normal file
View File

@@ -0,0 +1,160 @@
/*
Copyright (c) 2014-2016 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"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type power struct {
*flags.ClientFlag
*flags.SearchFlag
On bool
Off bool
Reset bool
Reboot bool
Shutdown bool
Suspend bool
Force bool
}
func init() {
cli.Register("vm.power", &power{})
}
func (cmd *power) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
f.BoolVar(&cmd.On, "on", false, "Power on")
f.BoolVar(&cmd.Off, "off", false, "Power off")
f.BoolVar(&cmd.Reset, "reset", false, "Power reset")
f.BoolVar(&cmd.Suspend, "suspend", false, "Power suspend")
f.BoolVar(&cmd.Reboot, "r", false, "Reboot guest")
f.BoolVar(&cmd.Shutdown, "s", false, "Shutdown guest")
f.BoolVar(&cmd.Force, "force", false, "Force (ignore state error and hard shutdown/reboot if tools unavailable)")
}
func (cmd *power) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
opts := []bool{cmd.On, cmd.Off, cmd.Reset, cmd.Suspend, cmd.Reboot, cmd.Shutdown}
selected := false
for _, opt := range opts {
if opt {
if selected {
return flag.ErrHelp
}
selected = opt
}
}
if !selected {
return flag.ErrHelp
}
return nil
}
func isToolsUnavailable(err error) bool {
if soap.IsSoapFault(err) {
soapFault := soap.ToSoapFault(err)
if _, ok := soapFault.VimFault().(types.ToolsUnavailable); ok {
return ok
}
}
return false
}
func (cmd *power) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
for _, vm := range vms {
var task *object.Task
switch {
case cmd.On:
fmt.Fprintf(cmd, "Powering on %s... ", vm.Reference())
task, err = vm.PowerOn(ctx)
case cmd.Off:
fmt.Fprintf(cmd, "Powering off %s... ", vm.Reference())
task, err = vm.PowerOff(ctx)
case cmd.Reset:
fmt.Fprintf(cmd, "Reset %s... ", vm.Reference())
task, err = vm.Reset(ctx)
case cmd.Suspend:
fmt.Fprintf(cmd, "Suspend %s... ", vm.Reference())
task, err = vm.Suspend(ctx)
case cmd.Reboot:
fmt.Fprintf(cmd, "Reboot guest %s... ", vm.Reference())
err = vm.RebootGuest(ctx)
if err != nil && cmd.Force && isToolsUnavailable(err) {
task, err = vm.Reset(ctx)
}
case cmd.Shutdown:
fmt.Fprintf(cmd, "Shutdown guest %s... ", vm.Reference())
err = vm.ShutdownGuest(ctx)
if err != nil && cmd.Force && isToolsUnavailable(err) {
task, err = vm.PowerOff(ctx)
}
}
if err != nil {
return err
}
if task != nil {
err = task.Wait(ctx)
}
if err == nil {
fmt.Fprintf(cmd, "OK\n")
continue
}
if cmd.Force {
fmt.Fprintf(cmd, "Error: %s\n", err)
continue
}
return err
}
return nil
}

98
vendor/github.com/vmware/govmomi/govc/vm/question.go generated vendored Normal file
View File

@@ -0,0 +1,98 @@
/*
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"
"errors"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type question struct {
*flags.VirtualMachineFlag
answer string
}
func init() {
cli.Register("vm.question", &question{})
}
func (cmd *question) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.StringVar(&cmd.answer, "answer", "", "Answer to question")
}
func (cmd *question) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *question) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return err
}
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return errors.New("No VM specified")
}
var mvm mo.VirtualMachine
pc := property.DefaultCollector(c)
err = pc.RetrieveOne(ctx, vm.Reference(), []string{"runtime.question"}, &mvm)
if err != nil {
return err
}
q := mvm.Runtime.Question
if q == nil {
fmt.Printf("No pending question\n")
return nil
}
// Print question if no answer is specified
if cmd.answer == "" {
fmt.Printf("Question:\n%s\n\n", q.Text)
fmt.Printf("Possible answers:\n")
for _, e := range q.Choice.ChoiceInfo {
ed := e.(*types.ElementDescription)
fmt.Printf("%s) %s\n", ed.Key, ed.Description.Label)
}
return nil
}
// Answer question
return vm.Answer(ctx, q.Id, cmd.answer)
}

149
vendor/github.com/vmware/govmomi/govc/vm/rdm/attach.go generated vendored Normal file
View File

@@ -0,0 +1,149 @@
/*
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 rdm
import (
"context"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type attach struct {
*flags.VirtualMachineFlag
device string
}
func init() {
cli.Register("vm.rdm.attach", &attach{})
}
func (cmd *attach) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.StringVar(&cmd.device, "device", "", "Device Name")
}
func (cmd *attach) Description() string {
return `Attach DEVICE to VM with RDM.
Examples:
govc vm.rdm.attach -vm VM -device /vmfs/devices/disks/naa.000000000000000000000000000000000`
}
func (cmd *attach) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
//This piece of code was developped mainly thanks to the project govmax on github.com
//This file in particular https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
func (cmd *attach) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
devices, err := vm.Device(ctx)
if err != nil {
return err
}
controller, err := devices.FindSCSIController("")
if err != nil {
return err
}
vmConfigOptions, err := vm.QueryConfigTarget(ctx)
if err != nil {
return err
}
for _, scsiDisk := range vmConfigOptions.ScsiDisk {
if !strings.Contains(scsiDisk.Disk.CanonicalName, cmd.device) {
continue
}
var backing types.VirtualDiskRawDiskMappingVer1BackingInfo
backing.CompatibilityMode = string(types.VirtualDiskCompatibilityModePhysicalMode)
backing.DeviceName = scsiDisk.Disk.DeviceName
for _, descriptor := range scsiDisk.Disk.Descriptor {
if strings.HasPrefix(descriptor.Id, "vml.") {
backing.LunUuid = descriptor.Id
break
}
}
var device types.VirtualDisk
device.Backing = &backing
device.ControllerKey = controller.VirtualController.Key
var unitNumber *int32
scsiCtrlUnitNumber := controller.VirtualController.UnitNumber
var u int32
for u = 0; u < 16; u++ {
free := true
for _, d := range devices {
if d.GetVirtualDevice().ControllerKey == device.GetVirtualDevice().ControllerKey {
if u == *(d.GetVirtualDevice().UnitNumber) || u == *scsiCtrlUnitNumber {
free = false
}
}
}
if free {
unitNumber = &u
break
}
}
device.UnitNumber = unitNumber
spec := types.VirtualMachineConfigSpec{}
config := &types.VirtualDeviceConfigSpec{
Device: &device,
Operation: types.VirtualDeviceConfigSpecOperationAdd,
}
config.FileOperation = types.VirtualDeviceConfigSpecFileOperationCreate
spec.DeviceChange = append(spec.DeviceChange, config)
task, err := vm.Reconfigure(ctx, spec)
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return fmt.Errorf("Error adding device %+v \n with backing %+v \nLogged Item: %s", device, backing, err)
}
return nil
}
return fmt.Errorf("Error: No LUN with device name containing %s found", cmd.device)
}

109
vendor/github.com/vmware/govmomi/govc/vm/rdm/ls.go generated vendored Normal file
View File

@@ -0,0 +1,109 @@
/*
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 rdm
import (
"context"
"flag"
"fmt"
"io"
"os"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type ls struct {
*flags.VirtualMachineFlag
*flags.OutputFlag
}
func init() {
cli.Register("vm.rdm.ls", &ls{})
}
func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
}
func (cmd *ls) Description() string {
return `List available devices that could be attach to VM with RDM.
Examples:
govc vm.rdm.ls -vm VM`
}
func (cmd *ls) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
vmConfigOptions, err := vm.QueryConfigTarget(ctx)
if err != nil {
return err
}
res := infoResult{
Disks: vmConfigOptions.ScsiDisk,
}
return cmd.WriteResult(&res)
}
type infoResult struct {
Disks []types.VirtualMachineScsiDiskDeviceInfo
}
func (r *infoResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
for _, disk := range r.Disks {
fmt.Fprintf(tw, "Name:\t%s\n", disk.Name)
fmt.Fprintf(tw, " Device name:\t%s\n", disk.Disk.DeviceName)
fmt.Fprintf(tw, " Device path:\t%s\n", disk.Disk.DevicePath)
fmt.Fprintf(tw, " Canonical Name:\t%s\n", disk.Disk.CanonicalName)
var uids []string
for _, descriptor := range disk.Disk.Descriptor {
uids = append(uids, descriptor.Id)
}
fmt.Fprintf(tw, " UIDS:\t%s\n", strings.Join(uids, " ,"))
}
return tw.Flush()
}

160
vendor/github.com/vmware/govmomi/govc/vm/register.go generated vendored Normal file
View File

@@ -0,0 +1,160 @@
/*
Copyright (c) 2016 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"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25"
)
type register struct {
*flags.ClientFlag
*flags.DatacenterFlag
*flags.DatastoreFlag
*flags.ResourcePoolFlag
*flags.HostSystemFlag
*flags.FolderFlag
name string
template bool
Client *vim25.Client
Datacenter *object.Datacenter
Datastore *object.Datastore
ResourcePool *object.ResourcePool
HostSystem *object.HostSystem
Folder *object.Folder
}
func init() {
cli.Register("vm.register", &register{})
}
func (cmd *register) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
cmd.ResourcePoolFlag, ctx = flags.NewResourcePoolFlag(ctx)
cmd.ResourcePoolFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.FolderFlag, ctx = flags.NewFolderFlag(ctx)
cmd.FolderFlag.Register(ctx, f)
f.StringVar(&cmd.name, "name", "", "Name of the VM")
f.BoolVar(&cmd.template, "as-template", false, "Mark VM as template")
}
func (cmd *register) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
if err := cmd.ResourcePoolFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.FolderFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *register) Usage() string {
return "VMX"
}
func (cmd *register) Description() string {
return `Add an existing VM to the inventory.
VMX is a path to the vm config file, relative to DATASTORE.
Examples:
govc vm.register path/name.vmx`
}
func (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error {
var err error
if len(f.Args()) != 1 {
return flag.ErrHelp
}
cmd.Client, err = cmd.ClientFlag.Client()
if err != nil {
return err
}
cmd.Datacenter, err = cmd.DatacenterFlag.Datacenter()
if err != nil {
return err
}
cmd.Datastore, err = cmd.DatastoreFlag.Datastore()
if err != nil {
return err
}
cmd.HostSystem, err = cmd.HostSystemFlag.HostSystemIfSpecified()
if err != nil {
return err
}
if cmd.HostSystem != nil {
if cmd.ResourcePool, err = cmd.HostSystem.ResourcePool(ctx); err != nil {
return err
}
} else if !cmd.template {
if cmd.ResourcePool, err = cmd.ResourcePoolFlag.ResourcePool(); err != nil {
return err
}
}
if cmd.Folder, err = cmd.FolderFlag.Folder(); err != nil {
return err
}
path := cmd.Datastore.Path(f.Arg(0))
task, err := cmd.Folder.RegisterVM(ctx, path, cmd.name, cmd.template, cmd.ResourcePool, cmd.HostSystem)
if err != nil {
return err
}
return task.Wait(ctx)
}

View File

@@ -0,0 +1,86 @@
/*
Copyright (c) 2016 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 snapshot
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type create struct {
*flags.VirtualMachineFlag
description string
memory bool
quiesce bool
}
func init() {
cli.Register("snapshot.create", &create{})
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.BoolVar(&cmd.memory, "m", true, "Include memory state")
f.BoolVar(&cmd.quiesce, "q", false, "Quiesce guest file system")
f.StringVar(&cmd.description, "d", "", "Snapshot description")
}
func (cmd *create) Usage() string {
return "NAME"
}
func (cmd *create) Description() string {
return `Create snapshot of VM with NAME.
Examples:
govc snapshot.create -vm my-vm happy-vm-state`
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return flag.ErrHelp
}
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
task, err := vm.CreateSnapshot(ctx, f.Arg(0), cmd.description, cmd.memory, cmd.quiesce)
if err != nil {
return err
}
return task.Wait(ctx)
}

View File

@@ -0,0 +1,94 @@
/*
Copyright (c) 2016 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 snapshot
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
)
type remove struct {
*flags.VirtualMachineFlag
recursive bool
consolidate bool
}
func init() {
cli.Register("snapshot.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.BoolVar(&cmd.recursive, "r", false, "Remove snapshot children")
f.BoolVar(&cmd.consolidate, "c", true, "Consolidate disks")
}
func (cmd *remove) Usage() string {
return "NAME"
}
func (cmd *remove) Description() string {
return `Remove snapshot of VM with given NAME.
NAME can be the snapshot name, tree path, moid or '*' to remove all snapshots.
Examples:
govc snapshot.remove -vm my-vm happy-vm-state`
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return flag.ErrHelp
}
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
var task *object.Task
if f.Arg(0) == "*" {
task, err = vm.RemoveAllSnapshot(ctx, &cmd.consolidate)
} else {
task, err = vm.RemoveSnapshot(ctx, f.Arg(0), cmd.recursive, &cmd.consolidate)
}
if err != nil {
return err
}
return task.Wait(ctx)
}

View File

@@ -0,0 +1,93 @@
/*
Copyright (c) 2016 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 snapshot
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
)
type revert struct {
*flags.VirtualMachineFlag
suppressPowerOn bool
}
func init() {
cli.Register("snapshot.revert", &revert{})
}
func (cmd *revert) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.BoolVar(&cmd.suppressPowerOn, "s", false, "Suppress power on")
}
func (cmd *revert) Usage() string {
return "[NAME]"
}
func (cmd *revert) Description() string {
return `Revert to snapshot of VM with given NAME.
If NAME is not provided, revert to the current snapshot.
Otherwise, NAME can be the snapshot name, tree path or moid.
Examples:
govc snapshot.revert -vm my-vm happy-vm-state`
}
func (cmd *revert) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *revert) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() > 1 {
return flag.ErrHelp
}
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
var task *object.Task
if f.NArg() == 1 {
task, err = vm.RevertToSnapshot(ctx, f.Arg(0), cmd.suppressPowerOn)
} else {
task, err = vm.RevertToCurrentSnapshot(ctx, cmd.suppressPowerOn)
}
if err != nil {
return err
}
return task.Wait(ctx)
}

View File

@@ -0,0 +1,145 @@
/*
Copyright (c) 2016 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 snapshot
import (
"context"
"flag"
"fmt"
"path"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type tree struct {
*flags.VirtualMachineFlag
fullPath bool
current bool
date bool
id bool
info *types.VirtualMachineSnapshotInfo
}
func init() {
cli.Register("snapshot.tree", &tree{})
}
func (cmd *tree) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.BoolVar(&cmd.fullPath, "f", false, "Print the full path prefix for snapshot")
f.BoolVar(&cmd.current, "c", true, "Print the current snapshot")
f.BoolVar(&cmd.date, "D", false, "Print the snapshot creation date")
f.BoolVar(&cmd.id, "i", false, "Print the snapshot id")
}
func (cmd *tree) Description() string {
return `List VM snapshots in a tree-like format.
The command will exit 0 with no output if VM does not have any snapshots.
Examples:
govc snapshot.tree -vm my-vm
govc snapshot.tree -vm my-vm -D -i`
}
func (cmd *tree) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *tree) write(level int, parent string, st []types.VirtualMachineSnapshotTree) {
for _, s := range st {
sname := s.Name
if cmd.fullPath && parent != "" {
sname = path.Join(parent, sname)
}
names := []string{sname}
if cmd.current && s.Snapshot == *cmd.info.CurrentSnapshot {
names = append(names, ".")
}
for _, name := range names {
var attr []string
var meta string
if cmd.id {
attr = append(attr, s.Snapshot.Value)
}
if cmd.date {
attr = append(attr, s.CreateTime.Format("Jan 2 15:04"))
}
if len(attr) > 0 {
meta = fmt.Sprintf("[%s] ", strings.Join(attr, " "))
}
fmt.Printf("%s%s%s\n", strings.Repeat(" ", level), meta, name)
}
cmd.write(level+2, sname, s.ChildSnapshotList)
}
}
func (cmd *tree) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 0 {
return flag.ErrHelp
}
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil {
return flag.ErrHelp
}
var o mo.VirtualMachine
err = vm.Properties(ctx, vm.Reference(), []string{"snapshot"}, &o)
if err != nil {
return err
}
if o.Snapshot == nil {
return nil
}
if cmd.current && o.Snapshot.CurrentSnapshot == nil {
cmd.current = false
}
cmd.info = o.Snapshot
cmd.write(0, "", o.Snapshot.RootSnapshotList)
return nil
}

76
vendor/github.com/vmware/govmomi/govc/vm/unregister.go generated vendored Normal file
View File

@@ -0,0 +1,76 @@
/*
Copyright (c) 2016 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"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type unregister struct {
*flags.ClientFlag
*flags.SearchFlag
}
func init() {
cli.Register("vm.unregister", &unregister{})
}
func (cmd *unregister) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines)
cmd.SearchFlag.Register(ctx, f)
}
func (cmd *unregister) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *unregister) Usage() string {
return "VM..."
}
func (cmd *unregister) Description() string {
return `Remove VM from inventory without removing any of the VM files on disk.`
}
func (cmd *unregister) Run(ctx context.Context, f *flag.FlagSet) error {
vms, err := cmd.VirtualMachines(f.Args())
if err != nil {
return err
}
for _, vm := range vms {
err := vm.Unregister(ctx)
if err != nil {
return err
}
}
return nil
}

487
vendor/github.com/vmware/govmomi/govc/vm/vnc.go generated vendored Normal file
View File

@@ -0,0 +1,487 @@
/*
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, _ := strconv.Atoi(m[1])
high, _ := strconv.Atoi(m[2])
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{}
cmd.PortRange.Set("5900-5999")
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:
vm.enable(cmd.Port, cmd.Password)
case cmd.Disable:
vm.disable()
}
}
// 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, 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
}