Commit e1fa044d authored by k8s-merge-robot's avatar k8s-merge-robot

Merge pull request #24703 from hpcloud/hpe/vsphere-instance

Automatic merge from submit-queue vSphere Cloud Provider Implementation This is the first PR towards implementation for vSphere cloud provider support in Kubernetes (ref. issue #23932).
parents b79a1bb6 f7b3cf39
...@@ -1028,6 +1028,11 @@ ...@@ -1028,6 +1028,11 @@
"Rev": "1e2e08e8a2dcdacaae3f14ac44c5cfa31361f270" "Rev": "1e2e08e8a2dcdacaae3f14ac44c5cfa31361f270"
}, },
{ {
"ImportPath": "github.com/vmware/govmomi",
"Comment": "v0.5.0",
"Rev": "c1b29993f383c32fc3fadb90892909668699810a"
},
{
"ImportPath": "github.com/xiang90/probing", "ImportPath": "github.com/xiang90/probing",
"Rev": "6a0cc1ae81b4cc11db5e491e030e4b98fba79c19" "Rev": "6a0cc1ae81b4cc11db5e491e030e4b98fba79c19"
}, },
......
...@@ -24,4 +24,5 @@ import ( ...@@ -24,4 +24,5 @@ import (
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack" _ "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack"
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt" _ "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt"
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace" _ "k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace"
_ "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere"
) )
maintainers:
- dagnello
- abithap
/*
Copyright 2016 The Kubernetes Authors 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 vsphere
import (
"log"
"os"
"strconv"
"strings"
"testing"
"golang.org/x/net/context"
)
func configFromEnv() (cfg VSphereConfig, ok bool) {
var InsecureFlag bool
var err error
cfg.Global.VCenterIP = os.Getenv("VSPHERE_VCENTER")
cfg.Global.VCenterPort = os.Getenv("VSPHERE_VCENTER_PORT")
cfg.Global.User = os.Getenv("VSPHERE_USER")
cfg.Global.Password = os.Getenv("VSPHERE_PASSWORD")
cfg.Global.Datacenter = os.Getenv("VSPHERE_DATACENTER")
cfg.Network.PublicNetwork = os.Getenv("VSPHERE_PUBLIC_NETWORK")
if os.Getenv("VSPHERE_INSECURE") != "" {
InsecureFlag, err = strconv.ParseBool(os.Getenv("VSPHERE_INSECURE"))
} else {
InsecureFlag = false
}
if err != nil {
log.Fatal(err)
}
cfg.Global.InsecureFlag = InsecureFlag
ok = (cfg.Global.VCenterIP != "" &&
cfg.Global.User != "")
return
}
func TestReadConfig(t *testing.T) {
_, err := readConfig(nil)
if err == nil {
t.Errorf("Should fail when no config is provided: %s", err)
}
cfg, err := readConfig(strings.NewReader(`
[Global]
server = 0.0.0.0
port = 443
user = user
password = password
insecure-flag = true
datacenter = us-west
`))
if err != nil {
t.Fatalf("Should succeed when a valid config is provided: %s", err)
}
if cfg.Global.VCenterIP != "0.0.0.0" {
t.Errorf("incorrect vcenter ip: %s", cfg.Global.VCenterIP)
}
if cfg.Global.VCenterPort != "443" {
t.Errorf("incorrect vcenter port: %s", cfg.Global.VCenterPort)
}
if cfg.Global.Datacenter != "us-west" {
t.Errorf("incorrect datacenter: %s", cfg.Global.Datacenter)
}
}
func TestNewVSphere(t *testing.T) {
cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
_, err := newVSphere(cfg)
if err != nil {
t.Fatalf("Failed to construct/authenticate vSphere: %s", err)
}
}
func TestVSphereLogin(t *testing.T) {
cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
// Create vSphere configuration object
vs, err := newVSphere(cfg)
if err != nil {
t.Fatalf("Failed to construct/authenticate vSphere: %s", err)
}
// Create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create vSphere client
c, err := vsphereLogin(vs.cfg, ctx)
if err != nil {
t.Errorf("Failed to create vSpere client: %s", err)
}
defer c.Logout(ctx)
}
func TestZones(t *testing.T) {
cfg := VSphereConfig{}
cfg.Global.Datacenter = "myDatacenter"
// Create vSphere configuration object
vs := VSphere{
cfg: &cfg,
}
z, ok := vs.Zones()
if !ok {
t.Fatalf("Zones() returned false")
}
zone, err := z.GetZone()
if err != nil {
t.Fatalf("GetZone() returned error: %s", err)
}
if zone.Region != vs.cfg.Global.Datacenter {
t.Fatalf("GetZone() returned wrong region (%s)", zone.Region)
}
}
func TestInstances(t *testing.T) {
cfg, ok := configFromEnv()
if !ok {
t.Skipf("No config found in environment")
}
vs, err := newVSphere(cfg)
if err != nil {
t.Fatalf("Failed to construct/authenticate vSphere: %s", err)
}
i, ok := vs.Instances()
if !ok {
t.Fatalf("Instances() returned false")
}
srvs, err := i.List("*")
if err != nil {
t.Fatalf("Instances.List() failed: %s", err)
}
if len(srvs) == 0 {
t.Fatalf("Instances.List() returned zero servers")
}
t.Logf("Found servers (%d): %s\n", len(srvs), srvs)
externalId, err := i.ExternalID(srvs[0])
if err != nil {
t.Fatalf("Instances.ExternalID(%s) failed: %s", srvs[0], err)
}
t.Logf("Found ExternalID(%s) = %s\n", srvs[0], externalId)
instanceId, err := i.InstanceID(srvs[0])
if err != nil {
t.Fatalf("Instances.InstanceID(%s) failed: %s", srvs[0], err)
}
t.Logf("Found InstanceID(%s) = %s\n", srvs[0], instanceId)
addrs, err := i.NodeAddresses(srvs[0])
if err != nil {
t.Fatalf("Instances.NodeAddresses(%s) failed: %s", srvs[0], err)
}
t.Logf("Found NodeAddresses(%s) = %s\n", srvs[0], addrs)
}
clone:
tags: true
path: github.com/vmware/govmomi
build:
image: golang:1.6
pull: true
environment:
- GOVC_TEST_URL=$$GOVC_TEST_URL
- GOVC_INSECURE=1
- VCA=1
commands:
- go get golang.org/x/tools/cmd/vet
- go get golang.org/x/tools/cmd/goimports
- go get github.com/davecgh/go-spew/spew
- go get
- make all
- make install
- git clone https://github.com/sstephenson/bats.git /tmp/bats
- /tmp/bats/install.sh /usr/local
- apt-get -qq update && apt-get install -yqq uuid-runtime bsdmainutils jq
- govc/test/images/update.sh
- bats govc/test
- govc/test/clean.sh
sudo: false
language: go
go: 1.4
before_install:
- go get golang.org/x/tools/cmd/vet
- go get golang.org/x/tools/cmd/goimports
- go get github.com/davecgh/go-spew/spew
script:
- make check test
# changelog
### 0.5.0 (2016-03-30)
Generated fields using xsd type 'int' change to Go type 'int32'
VirtualDevice.UnitNumber field changed to pointer type
### 0.4.0 (2016-02-26)
* Add method to convert virtual device list to array with virtual device
changes that can be used in the VirtualMachineConfigSpec.
* Make datastore cluster traversable in lister
* Add finder.DatastoreCluster methods (also known as storage pods)
* Add Drone CI check
* Add object.Datastore Type and AttachedClusterHosts methods
* Add finder.*OrDefault methods
### 0.3.0 (2016-01-16)
* Add object.VirtualNicManager wrapper
* Add object.HostVsanSystem wrapper
* Add object.HostSystem methods: EnterMaintenanceMode, ExitMaintenanceMode, Disconnect, Reconnect
* Add finder.Folder method
* Add object.Common.Destroy method
* Add object.ComputeResource.Reconfigure method
* Add license.AssignmentManager wrapper
* Add object.HostFirewallSystem wrapper
* Add object.DiagnosticManager wrapper
* Add LoginExtensionByCertificate support
* Add object.ExtensionManager
...
### 0.2.0 (2015-09-15)
* Update to vim25/6.0 API
* Stop returning children from `ManagedObjectList`
Change the `ManagedObjectList` function in the `find` package to only
return the managed objects specified by the path argument and not their
children. The original behavior was used by govc's `ls` command and is
now available in the newly added function `ManagedObjectListChildren`.
* Add retry functionality to vim25 package
* Change finder functions to no longer take varargs
The `find` package had functions to return a list of objects, given a
variable number of patterns. This makes it impossible to distinguish which
patterns produced results and which ones didn't.
In particular for govc, where multiple arguments can be passed from the
command line, it is useful to let the user know which ones produce results
and which ones don't.
To evaluate multiple patterns, the user should call the find functions
multiple times (either serially or in parallel).
* Make optional boolean fields pointers (`vim25/types`).
False is the zero value of a boolean field, which means they are not serialized
if the field is marked "omitempty". If the field is a pointer instead, the zero
value will be the nil pointer, and both true and false values are serialized.
### 0.1.0 (2015-03-17)
Prior to this version the API of this library was in flux.
Notable changes w.r.t. the state of this library before March 2015 are:
* All functions that may execute a request take a `context.Context` parameter.
* The `vim25` package contains a minimal client implementation.
* The property collector and its convenience functions live in the `property` package.
# Contributing to govmomi
## Getting started
First, fork the repository on GitHub to your personal account.
Note that _GOPATH_ can be any directory, the example below uses _$HOME/govmomi_.
Change _$USER_ below to your github username if they are not the same.
``` shell
export GOPATH=$HOME/govmomi
mkdir -p $GOPATH/src/github.com/vmware
cd $GOPATH/src/github.com/vmware
git clone git@github.com:vmware/govmomi.git
cd govmomi
git config push.default nothing # anything to avoid pushing to vmware/govmomi by default
git remote rename origin vmware
git remote add $USER git@github.com:$USER/govmomi.git
git fetch $USER
```
## Contribution flow
This is a rough outline of what a contributor's workflow looks like:
- Create a topic branch from where you want to base your work.
- Make commits of logical units.
- Make sure your commit messages are in the proper format (see below).
- Push your changes to a topic branch in your fork of the repository.
- Submit a pull request to vmware/govmomi.
Example:
``` shell
git checkout -b my-new-feature vmware/master
git commit -a
git push $USER my-new-feature
```
### Stay in sync with upstream
When your branch gets out of sync with the vmware/master branch, use the following to update:
``` shell
git checkout my-new-feature
git fetch -a
git rebase vmware/master
git push --force-with-lease $USER my-new-feature
```
### Updating pull requests
If your PR fails to pass CI or needs changes based on code review, you'll most likely want to squash these changes into
existing commits.
If your pull request contains a single commit or your changes are related to the most recent commit, you can simply
amend the commit.
``` shell
git add .
git commit --amend
git push --force-with-lease $USER my-new-feature
```
If you need to squash changes into an earlier commit, you can use:
``` shell
git add .
git commit --fixup <commit>
git rebase -i --autosquash vmware/master
git push --force-with-lease $USER my-new-feature
```
Be sure to add a comment to the PR indicating your new changes are ready to review, as github does not generate a
notification when you git push.
### Code style
The coding style suggested by the Golang community is used in govmomi. See the
[style doc](https://github.com/golang/go/wiki/CodeReviewComments) for details.
Try to limit column width to 120 characters for both code and markdown documents such as this one.
### Format of the Commit Message
We follow the conventions on [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/).
Be sure to include any related GitHub issue references in the commit message.
## Reporting Bugs and Creating Issues
When opening a new issue, try to roughly follow the commit message format conventions above.
# People who can (and typically have) contributed to this repository.
#
# Please keep the list sorted.
#
Alvaro Miranda <kikitux@gmail.com>
Amit Bathla <abathla@.vmware.com>
Andrew Chin <andrew@andrewtchin.com>
Arran Walker <arran.walker@zopa.com>
Bob Killen <killen.bob@gmail.com>
Bruce Downs <bdowns@vmware.com>
Clint Greenwood <cgreenwood@vmware.com> <clint.greenwood@gmail.com>
Cédric Blomart <cblomart@gmail.com>
Danny Lockard <danny.lockard@banno.com>
Doug MacEachern <dougm@vmware.com>
Eloy Coto <eloy.coto@gmail.com>
Eric Yutao <eric.yutao@gmail.com>
Fabio Rapposelli <fabio@vmware.com>
Faiyaz Ahmed <ahmedf@vmware.com>
Gavin Gray <gavin@infinio.com>
Gavrie Philipson <gavrie@philipson.co.il> <gavrie.philipson@elastifile.com>
George Hicken <ghicken@vmware.com>
Gerrit Renker <Gerrit.Renker@ctl.io>
gthombare <gthombare@vmware.com>
Isaac Rodman <isaac@eyz.us>
Louie Jiang <jiangl@vmware.com>
Mevan Samaratunga <mevansam@gmail.com>
Pieter Noordhuis <pnoordhuis@vmware.com> <pcnoordhuis@gmail.com>
runner.mei <runner.mei@gmail.com>
S.Çağlar Onur <conur@vmware.com>
Takaaki Furukawa <takaaki.frkw@gmail.com> <takaaki.furukawa@mail.rakuten.com>
Steve Purcell <steve@sanityinc.com>
Yang Yang <yangy@vmware.com>
Yuya Kusakabe <yuya.kusakabe@gmail.com>
Zach Tucker <ztucker@vmware.com>
Zee Yang <zeey@vmware.com> <zee.yang@gmail.com>
.PHONY: test
all: check test
check: goimports govet
goimports:
@echo checking go imports...
@! goimports -d . 2>&1 | egrep -v '^$$'
govet:
@echo checking go vet...
@go tool vet -structtags=false -methods=false .
test:
go get
go test -v $(TEST_OPTS) ./...
install:
go install github.com/vmware/govmomi/govc
[![Build Status](https://travis-ci.org/vmware/govmomi.png?branch=master)](https://travis-ci.org/vmware/govmomi)
[![Build Status](https://ci.vmware.run/api/badges/vmware/govmomi/status.svg)](https://ci.vmware.run/vmware/govmomi)
# govmomi
A Go library for interacting with VMware vSphere APIs (ESXi and/or vCenter).
For `govc`, a CLI built on top of govmomi, check out the [govc](./govc) directory.
## Compatibility
This library is built for and tested against ESXi and vCenter 5.5 and 6.0.
If you're able to use it against older versions of ESXi and/or vCenter, please
leave a note and we'll include it in this compatibility list.
## Documentation
The APIs exposed by this library very closely follow the API described in the [VMware vSphere API Reference Documentation][apiref].
Refer to this document to become familiar with the upstream API.
The code in the `govmomi` package is a wrapper for the code that is generated from the vSphere API description.
It primarily provides convenience functions for working with the vSphere API.
See [godoc.org][godoc] for documentation.
[apiref]:http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.wssdk.apiref.doc/right-pane.html
[godoc]:http://godoc.org/github.com/vmware/govmomi
[drone]:https://drone.io
[dronesrc]:https://github.com/drone/drone
[dronecli]:http://readme.drone.io/devs/cli/
#### Building with CI
Merges to this repository will trigger builds in both Travis and [Drone][drone].
To build locally with Drone:
- Ensure that you have Docker 1.6 or higher installed.
- Install the [Drone command line tools][dronecli].
- Run `drone exec` from within the root directory of the govmomi repository.
## Status
Changes to the API are subject to [semantic versioning](http://semver.org).
Refer to the [CHANGELOG](CHANGELOG.md) for version to version changes.
## Projects using govmomi
* [Docker Machine](https://github.com/docker/machine/tree/master/drivers/vmwarevsphere)
* [Terraform](https://github.com/hashicorp/terraform/tree/master/builtin/providers/vsphere)
## License
govmomi is available under the [Apache 2 license](LICENSE).
/*
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.
*/
/*
This package is the root package of the govmomi library.
The library is structured as follows:
Package vim25
The minimal usable functionality is available through the vim25 package.
It contains subpackages that contain generated types, managed objects, and all
available methods. The vim25 package is entirely independent of the other
packages in the govmomi tree -- it has no dependencies on its peers.
The vim25 package itself contains a client structure that is
passed around throughout the entire library. It abstracts a session and its
immutable state. See the vim25 package for more information.
Package session
The session package contains an abstraction for the session manager that allows
a user to login and logout. It also provides access to the current session
(i.e. to determine if the user is in fact logged in)
Package object
The object package contains wrappers for a selection of managed objects. The
constructors of these objects all take a *vim25.Client, which they pass along
to derived objects, if applicable.
Package govc
The govc package contains the govc CLI. The code in this tree is not intended
to be used as a library. Any functionality that govc contains that _could_ be
used as a library function but isn't, _should_ live in a root level package.
Other packages
Other packages, such as "event", "guest", or "license", provide wrappers for
the respective subsystems. They are typically not needed in normal workflows so
are kept outside the object package.
*/
package govmomi
import (
"crypto/tls"
"net/url"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/session"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type Client struct {
*vim25.Client
SessionManager *session.Manager
}
// NewClient creates a new client from a URL. The client authenticates with the
// server with username/password before returning if the URL contains user information.
func NewClient(ctx context.Context, u *url.URL, insecure bool) (*Client, error) {
soapClient := soap.NewClient(u, insecure)
vimClient, err := vim25.NewClient(ctx, soapClient)
if err != nil {
return nil, err
}
c := &Client{
Client: vimClient,
SessionManager: session.NewManager(vimClient),
}
// Only login if the URL contains user information.
if u.User != nil {
err = c.Login(ctx, u.User)
if err != nil {
return nil, err
}
}
return c, nil
}
// NewClientWithCertificate creates a new client from a URL. The client authenticates with the
// server with the certificate before returning if the URL contains user information.
func NewClientWithCertificate(ctx context.Context, u *url.URL, insecure bool, cert tls.Certificate) (*Client, error) {
soapClient := soap.NewClient(u, insecure)
soapClient.SetCertificate(cert)
vimClient, err := vim25.NewClient(ctx, soapClient)
if err != nil {
return nil, err
}
c := &Client{
Client: vimClient,
SessionManager: session.NewManager(vimClient),
}
if u.User != nil {
err = c.LoginExtensionByCertificate(ctx, u.User.Username(), "")
if err != nil {
return nil, err
}
}
return c, nil
}
// Login dispatches to the SessionManager.
func (c *Client) Login(ctx context.Context, u *url.Userinfo) error {
return c.SessionManager.Login(ctx, u)
}
// Login dispatches to the SessionManager.
func (c *Client) LoginExtensionByCertificate(ctx context.Context, key string, locale string) error {
return c.SessionManager.LoginExtensionByCertificate(ctx, key, locale)
}
// Logout dispatches to the SessionManager.
func (c *Client) Logout(ctx context.Context) error {
// Close any idle connections after logging out.
defer c.Client.CloseIdleConnections()
return c.SessionManager.Logout(ctx)
}
// PropertyCollector returns the session's default property collector.
func (c *Client) PropertyCollector() *property.Collector {
return property.DefaultCollector(c.Client)
}
// RetrieveOne dispatches to the Retrieve function on the default property collector.
func (c *Client) RetrieveOne(ctx context.Context, obj types.ManagedObjectReference, p []string, dst interface{}) error {
return c.PropertyCollector().RetrieveOne(ctx, obj, p, dst)
}
// Retrieve dispatches to the Retrieve function on the default property collector.
func (c *Client) Retrieve(ctx context.Context, objs []types.ManagedObjectReference, p []string, dst interface{}) error {
return c.PropertyCollector().Retrieve(ctx, objs, p, dst)
}
// Wait dispatches to property.Wait.
func (c *Client) Wait(ctx context.Context, obj types.ManagedObjectReference, ps []string, f func([]types.PropertyChange) bool) error {
return property.Wait(ctx, c.PropertyCollector(), obj, ps, f)
}
// IsVC returns true if we are connected to a vCenter
func (c *Client) IsVC() bool {
return c.Client.IsVC()
}
/*
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 event
import (
"fmt"
"golang.org/x/net/context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/view"
"github.com/vmware/govmomi/vim25/types"
)
func multipleObjectEvents(ctx context.Context, m Manager, objects []types.ManagedObjectReference, pageSize int32, tail bool, force bool, prop []string, f func([]types.BaseEvent) error) error {
// create an EventHistoryCollector for each object
var collectors []types.ManagedObjectReference
for _, o := range objects {
filter := types.EventFilterSpec{
Entity: &types.EventFilterSpecByEntity{
Entity: o,
Recursion: types.EventFilterSpecRecursionOptionAll,
},
}
collector, err := m.CreateCollectorForEvents(ctx, filter)
if err != nil {
return fmt.Errorf("[%#v] %s", o, err)
}
defer collector.Destroy(ctx)
err = collector.SetPageSize(ctx, pageSize)
if err != nil {
return err
}
collectors = append(collectors, collector.Reference())
}
// create and populate a ListView
viewMgr := view.NewManager(m.Client())
listView, err := viewMgr.CreateListView(ctx, collectors)
if err != nil {
return err
}
count := 0
// Retrieve the property from the objects in the ListView
return property.WaitForView(ctx, property.DefaultCollector(m.Client()), listView.Reference(), collectors[0], prop, func(pc []types.PropertyChange) bool {
for _, u := range pc {
if u.Name != prop[0] {
continue
}
if u.Val == nil {
continue
}
f(u.Val.(types.ArrayOfEvent).Event)
}
count++
if count == len(collectors) && !tail {
return true
}
return false
})
}
func singleObjectEvents(ctx context.Context, m Manager, object types.ManagedObjectReference, pageSize int32, tail bool, force bool, prop []string, f func([]types.BaseEvent) error) error {
filter := types.EventFilterSpec{
Entity: &types.EventFilterSpecByEntity{
Entity: object,
Recursion: types.EventFilterSpecRecursionOptionAll,
},
}
collector, err := m.CreateCollectorForEvents(ctx, filter)
if err != nil {
return fmt.Errorf("[%#v] %s", object, err)
}
defer collector.Destroy(ctx)
err = collector.SetPageSize(ctx, pageSize)
if err != nil {
return err
}
return property.Wait(ctx, property.DefaultCollector(m.Client()), collector.Reference(), prop, func(pc []types.PropertyChange) bool {
for _, u := range pc {
if u.Name != prop[0] {
continue
}
if u.Val == nil {
continue
}
f(u.Val.(types.ArrayOfEvent).Event)
}
if !tail {
return true
}
return false
})
}
/*
Copyright (c) 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 event
import (
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HistoryCollector struct {
*object.HistoryCollector
}
func NewHistoryCollector(c *vim25.Client, ref types.ManagedObjectReference) *HistoryCollector {
return &HistoryCollector{
HistoryCollector: object.NewHistoryCollector(c, ref),
}
}
func (h HistoryCollector) LatestPage(ctx context.Context) ([]types.BaseEvent, error) {
var o mo.EventHistoryCollector
err := h.Properties(ctx, h.Reference(), []string{"latestPage"}, &o)
if err != nil {
return nil, err
}
return o.LatestPage, nil
}
func (h HistoryCollector) ReadNextEvents(ctx context.Context, maxCount int32) ([]types.BaseEvent, error) {
req := types.ReadNextEvents{
This: h.Reference(),
MaxCount: maxCount,
}
res, err := methods.ReadNextEvents(ctx, h.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (h HistoryCollector) ReadPreviousEvents(ctx context.Context, maxCount int32) ([]types.BaseEvent, error) {
req := types.ReadPreviousEvents{
This: h.Reference(),
MaxCount: maxCount,
}
res, err := methods.ReadPreviousEvents(ctx, h.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
/*
Copyright (c) 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 event
import (
"fmt"
"reflect"
"sync"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type Manager struct {
object.Common
eventCategory map[string]string
eventCategoryMu *sync.Mutex
maxObjects int
}
func NewManager(c *vim25.Client) *Manager {
m := Manager{
Common: object.NewCommon(c, *c.ServiceContent.EventManager),
eventCategory: make(map[string]string),
eventCategoryMu: new(sync.Mutex),
maxObjects: 10,
}
return &m
}
func (m Manager) CreateCollectorForEvents(ctx context.Context, filter types.EventFilterSpec) (*HistoryCollector, error) {
req := types.CreateCollectorForEvents{
This: m.Common.Reference(),
Filter: filter,
}
res, err := methods.CreateCollectorForEvents(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return NewHistoryCollector(m.Client(), res.Returnval), nil
}
func (m Manager) LogUserEvent(ctx context.Context, entity types.ManagedObjectReference, msg string) error {
req := types.LogUserEvent{
This: m.Common.Reference(),
Entity: entity,
Msg: msg,
}
_, err := methods.LogUserEvent(ctx, m.Client(), &req)
if err != nil {
return err
}
return nil
}
func (m Manager) PostEvent(ctx context.Context, eventToPost types.BaseEvent, taskInfo types.TaskInfo) error {
req := types.PostEvent{
This: m.Common.Reference(),
EventToPost: eventToPost,
TaskInfo: &taskInfo,
}
_, err := methods.PostEvent(ctx, m.Client(), &req)
if err != nil {
return err
}
return nil
}
func (m Manager) QueryEvents(ctx context.Context, filter types.EventFilterSpec) ([]types.BaseEvent, error) {
req := types.QueryEvents{
This: m.Common.Reference(),
Filter: filter,
}
res, err := methods.QueryEvents(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m Manager) RetrieveArgumentDescription(ctx context.Context, eventTypeID string) ([]types.EventArgDesc, error) {
req := types.RetrieveArgumentDescription{
This: m.Common.Reference(),
EventTypeId: eventTypeID,
}
res, err := methods.RetrieveArgumentDescription(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m Manager) eventCategoryMap(ctx context.Context) (map[string]string, error) {
m.eventCategoryMu.Lock()
defer m.eventCategoryMu.Unlock()
if len(m.eventCategory) != 0 {
return m.eventCategory, nil
}
var o mo.EventManager
ps := []string{"description.eventInfo"}
err := property.DefaultCollector(m.Client()).RetrieveOne(ctx, m.Common.Reference(), ps, &o)
if err != nil {
return nil, err
}
for _, info := range o.Description.EventInfo {
m.eventCategory[info.Key] = info.Category
}
return m.eventCategory, nil
}
// EventCategory returns the category for an event, such as "info" or "error" for example.
func (m Manager) EventCategory(ctx context.Context, event types.BaseEvent) (string, error) {
// Most of the event details are included in the Event.FullFormattedMessage, but the category
// is only available via the EventManager description.eventInfo property. The value of this
// property is static, so we fetch and once and cache.
eventCategory, err := m.eventCategoryMap(ctx)
if err != nil {
return "", err
}
class := reflect.TypeOf(event).Elem().Name()
return eventCategory[class], nil
}
// Get the events from the specified object(s) and optionanlly tail the event stream
func (m Manager) Events(ctx context.Context, objects []types.ManagedObjectReference, pageSize int32, tail bool, force bool, f func([]types.BaseEvent) error) error {
if len(objects) >= m.maxObjects && !force {
return fmt.Errorf("Maximum number of objects to monitor (%d) exceeded, refine search \n", m.maxObjects)
}
// property that will be monitored
prop := []string{"latestPage"}
// call to helper functions to reduce the number of temporary objects
if len(objects) > 1 {
return multipleObjectEvents(ctx, m, objects, pageSize, tail, force, prop, f)
}
return singleObjectEvents(ctx, m, objects[0], pageSize, tail, force, prop, f)
}
/*
Copyright (c) 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 event
import (
"sort"
"github.com/vmware/govmomi/vim25/types"
)
// Sort events in accending order base on Key
// From the EventHistoryCollector.latestPage sdk docs:
// The "oldest event" is the one with the smallest key (event ID).
// The events in the returned page are unordered.
func Sort(events []types.BaseEvent) {
sort.Sort(baseEvent(events))
}
type baseEvent []types.BaseEvent
func (d baseEvent) Len() int {
return len(d)
}
func (d baseEvent) Less(i, j int) bool {
return d[i].GetEvent().Key < d[j].GetEvent().Key
}
func (d baseEvent) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
/*
Copyright (c) 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.
*/
/*
This example program shows how the `finder` and `property` packages can
be used to navigate a vSphere inventory structure using govmomi.
*/
package main
import (
"flag"
"fmt"
"net/url"
"os"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/units"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// GetEnvString returns string from environment variable.
func GetEnvString(v string, def string) string {
r := os.Getenv(v)
if r == "" {
return def
}
return r
}
// GetEnvBool returns boolean from environment variable.
func GetEnvBool(v string, def bool) bool {
r := os.Getenv(v)
if r == "" {
return def
}
switch strings.ToLower(r[0:1]) {
case "t", "y", "1":
return true
}
return false
}
const (
envURL = "GOVMOMI_URL"
envUserName = "GOVMOMI_USERNAME"
envPassword = "GOVMOMI_PASSWORD"
envInsecure = "GOVMOMI_INSECURE"
)
var urlDescription = fmt.Sprintf("ESX or vCenter URL [%s]", envURL)
var urlFlag = flag.String("url", GetEnvString(envURL, "https://username:password@host/sdk"), urlDescription)
var insecureDescription = fmt.Sprintf("Don't verify the server's certificate chain [%s]", envInsecure)
var insecureFlag = flag.Bool("insecure", GetEnvBool(envInsecure, false), insecureDescription)
func processOverride(u *url.URL) {
envUsername := os.Getenv(envUserName)
envPassword := os.Getenv(envPassword)
// Override username if provided
if envUsername != "" {
var password string
var ok bool
if u.User != nil {
password, ok = u.User.Password()
}
if ok {
u.User = url.UserPassword(envUsername, password)
} else {
u.User = url.User(envUsername)
}
}
// Override password if provided
if envPassword != "" {
var username string
if u.User != nil {
username = u.User.Username()
}
u.User = url.UserPassword(username, envPassword)
}
}
func exit(err error) {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
flag.Parse()
// Parse URL from string
u, err := url.Parse(*urlFlag)
if err != nil {
exit(err)
}
// Override username and/or password as required
processOverride(u)
// Connect and log in to ESX or vCenter
c, err := govmomi.NewClient(ctx, u, *insecureFlag)
if err != nil {
exit(err)
}
f := find.NewFinder(c.Client, true)
// Find one and only datacenter
dc, err := f.DefaultDatacenter(ctx)
if err != nil {
exit(err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
// Find datastores in datacenter
dss, err := f.DatastoreList(ctx, "*")
if err != nil {
exit(err)
}
pc := property.DefaultCollector(c.Client)
// Convert datastores into list of references
var refs []types.ManagedObjectReference
for _, ds := range dss {
refs = append(refs, ds.Reference())
}
// Retrieve summary property for all datastores
var dst []mo.Datastore
err = pc.Retrieve(ctx, refs, []string{"summary"}, &dst)
if err != nil {
exit(err)
}
// Print summary per datastore
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Name:\tType:\tCapacity:\tFree:\n")
for _, ds := range dst {
fmt.Fprintf(tw, "%s\t", ds.Summary.Name)
fmt.Fprintf(tw, "%s\t", ds.Summary.Type)
fmt.Fprintf(tw, "%s\t", units.ByteSize(ds.Summary.Capacity))
fmt.Fprintf(tw, "%s\t", units.ByteSize(ds.Summary.FreeSpace))
fmt.Fprintf(tw, "\n")
}
tw.Flush()
}
/*
Copyright (c) 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 find
import "fmt"
type NotFoundError struct {
kind string
path string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s '%s' not found", e.kind, e.path)
}
type MultipleFoundError struct {
kind string
path string
}
func (e *MultipleFoundError) Error() string {
return fmt.Sprintf("path '%s' resolves to multiple %ss", e.path, e.kind)
}
type DefaultNotFoundError struct {
kind string
}
func (e *DefaultNotFoundError) Error() string {
return fmt.Sprintf("no default %s found", e.kind)
}
type DefaultMultipleFoundError struct {
kind string
}
func (e DefaultMultipleFoundError) Error() string {
return fmt.Sprintf("default %s resolves to multiple instances, please specify", e.kind)
}
func toDefaultError(err error) error {
switch e := err.(type) {
case *NotFoundError:
return &DefaultNotFoundError{e.kind}
case *MultipleFoundError:
return &DefaultMultipleFoundError{e.kind}
default:
return err
}
}
source "https://rubygems.org"
gem "nokogiri"
GEM
remote: https://rubygems.org/
specs:
mini_portile (0.6.0)
nokogiri (1.6.3.1)
mini_portile (= 0.6.0)
PLATFORMS
ruby
DEPENDENCIES
nokogiri
#!/bin/bash
# Copyright (c) 2014 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.
set -e
if [ ! -f rbvmomi/vmodl.db ]; then
git clone https://github.com/vmware/rbvmomi
fi
dst=../vim25
pkgs=$(echo $dst/{types,methods,mo})
mkdir -p $pkgs
bundle exec ruby gen_from_wsdl.rb $dst
bundle exec ruby gen_from_vmodl.rb $dst
for p in $pkgs
do
echo $p
cd $p
goimports -w *.go
go install
cd -
done
# Copyright (c) 2014 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.
$:.unshift(File.expand_path(File.dirname(__FILE__)))
require "vim_wsdl"
require "test/unit"
PATH = File.expand_path("../rbvmomi", __FILE__)
def read(file)
File.open(File.join(PATH, file))
end
class Prop
def initialize(vmodl, data)
@vmodl = vmodl
@data = data
end
def slice?
@data["is-array"]
end
def optional?
@data["is-optional"]
end
def name
@data["name"]
end
def var_field
n = name
n[0].capitalize + n[1..-1]
end
def var_type_prefix(base=false)
if slice?
"[]"
else
if optional? && !base
"*"
else
""
end
end
end
def var_type
type = @data["wsdl_type"]
if @vmodl.managed_hash.has_key?(type)
type = "ManagedObjectReference"
end
# Fix up type from vmodl
case type
when "TypeName", "MethodName"
type = "xsd:string"
when "ManagedObject"
type = "ManagedObjectReference"
when "xsd:anyType"
type = "AnyType"
end
if type =~ /^xsd:(.*)$/
type = $1
case type
when "string"
when "int"
type = "int32"
when "boolean"
type ="bool"
when "long"
type ="int64"
when "dateTime"
type ="time.Time"
prefix += "*" if !slice? && optional?
when "byte"
when "double"
type ="float64"
when "float"
type ="float32"
when "short"
type ="int16"
when "base64Binary"
type ="[]byte"
else
raise "unknown type: %s" % type
end
else
if Peek.base?(type)
type = "Base" + type
base = true
end
type = "types." + type
end
var_type_prefix(base) + type
end
def var_tag
"mo:\"%s\"" % name
end
def dump(io)
io.print "%s %s `%s`\n" % [var_field, var_type, var_tag]
end
end
class Managed
def initialize(vmodl, name, data)
@vmodl = vmodl
@name = name
@data = data
end
def name
@name
end
def props
@data["props"].map do |p|
Prop.new(@vmodl, p)
end
end
def dump(io)
include_ref_getter = false
io.print "type %s struct {\n" % name
case @data["wsdl_base"]
when nil, "ManagedObject", "View"
include_ref_getter = true
io.print "Self types.ManagedObjectReference\n\n"
else
io.print "%s\n\n" % @data["wsdl_base"]
end
props.each do |p|
p.dump(io)
end
io.print "}\n\n"
if include_ref_getter
io.print "func (m %s) Reference() types.ManagedObjectReference {\n" % [name]
io.print "return m.Self\n"
io.print "}\n\n"
end
end
def dump_init(io)
io.print "func init() {\n"
io.print "t[\"%s\"] = reflect.TypeOf((*%s)(nil)).Elem()\n" % [name, name]
io.print "}\n\n"
end
end
class Vmodl
def initialize(data)
@data = Marshal.load(data)
end
def managed_hash
@managed_hash ||= begin
h = {}
managed.each do |m|
h[m.name] = m
end
h
end
end
def managed
@data.map do |k,v|
next if !v.is_a?(Hash)
next if v["kind"] != "managed"
next if k =~ /^pbm/i
Managed.new(self, k, v)
end.compact
end
end
if !File.directory?(ARGV.first)
raise "first argument not a directory"
end
wsdl = WSDL.new(WSDL.read "vim.wsdl")
wsdl.validate_assumptions!
wsdl.peek()
File.open(File.join(ARGV.first, "mo/mo.go"), "w") do |io|
io.print WSDL.header("mo")
vmodl = Vmodl.new(read "vmodl.db")
vmodl.
managed.
sort_by { |m| m.name }.
each { |m| m.dump(io); m.dump_init(io); }
end
exit(0)
# Copyright (c) 2014 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.
$:.unshift(File.expand_path(File.dirname(__FILE__)))
require "vim_wsdl"
if !File.directory?(ARGV.first)
raise "first argument not a directory"
end
wsdl = WSDL.new(WSDL.read "vim.wsdl")
wsdl.validate_assumptions!
wsdl.peek()
ifs = Peek.types.keys.select { |name| Peek.base?(name) }.size()
puts "%d classes, %d interfaces" % [Peek.types.size(), ifs]
File.open(File.join(ARGV.first, "types/enum.go"), "w") do |io|
io.print WSDL.header("types")
wsdl.
types.
sort_by { |x| x.name }.
uniq { |x| x.name }.
select { |x| x.name[0] == x.name[0].upcase }. # Only capitalized methods for now...
select { |t| t.is_enum? }.
each { |e| e.dump(io); e.dump_init(io) }
end
File.open(File.join(ARGV.first, "types/types.go"), "w") do |io|
io.print WSDL.header("types")
wsdl.
types.
sort_by { |x| x.name }.
uniq { |x| x.name }.
select { |x| x.name[0] == x.name[0].upcase }. # Only capitalized methods for now...
select { |t| !t.is_enum? }.
each { |e| e.dump(io); e.dump_init(io) }
end
File.open(File.join(ARGV.first, "types/if.go"), "w") do |io|
io.print WSDL.header("types")
Peek.dump_interfaces(io)
end
File.open(File.join(ARGV.first, "methods/methods.go"), "w") do |io|
io.print WSDL.header("methods")
wsdl.
operations.
sort_by { |x| x.name }.
select { |x| x.name[0] == x.name[0].upcase }. # Only capitalized methods for now...
each { |e| e.dump(io) }
end
exit(0)
# changelog
### 0.5.0 (2016-03-30)
* Add dvs.portgroup.info command
* Add `-folder` flag to vm.create command
* Add `-dump` flag to OutputFlag
* Add `-f` flag to events command
* Add `-mode` flag to vm.disk.create command
* Add `-net` flag to device.info command
* Add `-eager` and `-thick` options to vm.create command
### 0.4.0 (2016-02-26)
* Add support for placement in datastore cluster to vm.create command
* Add support for creating new disks in vm.create command
* Add `-p` and `-a` options to govc datastore.ls command
### 0.3.0 (2016-01-16)
* Add permissions.{ls,set,remove} commands
* Add datastore.{create,remove} commands.
The new create command supports both creating NAS and VMFS datastores.
* Add dvs.{create,add} and dvs.portgroup.add commands
* Add host.vnic.{service,info} commands
* Add cluster.{create,change,add} commands
* Add host.{disconnect,reconnect,remove,maintenance.enter,maintenance.exit} commands
* Add license.decode, license.assigned.list and license.assign commands
* Add firewall.ruleset.find command
* Add logs, logs.ls and logs.download commands
* Add support for LoginExtensionByCertificate with new `-cert` and `-key` flags
* Add govc extension.{info,register,unregister,setcert} commands
* Add govc vapp.{info,destroy,power} commands
### 0.2.0 (2015-09-15)
* The `vm.power` guest `-s` and `-r` options will fallback to hard `-off` / `-reset` if tools is unavailable and `-force` flag is given
* Add `PowerOn, InjectOvfEnv, WaitForIP` options to `import.ovf` and `import.ova` option spec file
* Add `import.spec` to produce an example json document
* Add `-options` to `import.ovf` and `import.ova`
* Add `-folder` to `import.ovf` and `import.ova`
* Add `fields` command to manage custom fields
* Add `datastore.info` command
* Add `events` command
* Add `-net.address` (Hardware Address) option to `vm.change` and `vm.create`
* Add `host.add` command to add host to datacenter.
* Add `GOVC_USERNAME` and `GOVC_PASSWORD` to allow overriding username and/or
password (used when they contain special characters that prevent them from
being embedded in the URL).
* Add `-e' (ExtraConfig) option to `vm.change` and `vm.info`
* Retry twice on temporary network errors.
* Add `host.autostart` commands to manage VM autostart.
* Add `-persist-session` flag to control whether or not the session is
persisted to disk (defaults to true).
### 0.1.0 (2015-03-17)
Prior to this version the changes to govc's command set were not documented.
# govc
govc is a vSphere CLI built on top of govmomi.
## Installation
You can find prebuilt govc binaries on the [releases page](https://github.com/vmware/govmomi/releases).
Download and install a binary locally like this:
```sh
curl $URL_TO_BINARY | gzip -d > /usr/local/bin/govc
chmod +x /usr/local/bin/govc
```
### Source
You can install the latest govc version from source if you have the Go toolchain installed.
```sh
go get github.com/vmware/govmomi/govc
```
(make sure `$GOPATH/bin` is in your `PATH`)
## Usage
govc exposes its functionality through subcommands. Option flags
to these subcommands are often shared.
Common flags include:
* `-u`: ESXi or vCenter URL (ex: `user:pass@host`)
* `-debug`: Trace requests and responses (to `~/.govmomi/debug`)
Managed entities can be referred to by their absolute path or by their relative
path. For example, when specifying a datastore to use for a subcommand, you can
either specify it as `/mydatacenter/datastore/mydatastore`, or as
`mydatastore`. If you're not sure about the name of the datastore, or even the
full path to the datastore, you can specify a pattern to match. Both
`/*center/*/my*` (absolute) and `my*store` (relative) will resolve to the same
datastore, given there are no other datastores that match those globs.
The relative path in this example can only be used if the command can
umambigously resolve a datacenter to use as origin for the query. If no
datacenter is specified, govc defaults to the only datacenter, if there is only
one. The datacenter itself can be specified as a pattern as well, enabling the
following arguments: `-dc='my*' -ds='*store'`. The datastore pattern is looked
up and matched relative to the datacenter which itself is specified as a
pattern.
Besides specifying managed entities as arguments, they can also be specified
using environment variables. The following environment variables are used by govc
to set defaults:
* `GOVC_USERNAME`: USERNAME to use.
* `GOVC_PASSWORD`: PASSWORD to use.
* `GOVC_URL`: URL of ESXi or vCenter instance to connect to.
> The URL scheme defaults to `https` and the URL path defaults to `/sdk`.
> This means that specifying `user:pass@host` is equivalent to
> `https://user:pass@host/sdk`.
> If password include special characters like `#` or `:` you can use
> `GOVC_USERNAME` and `GOVC_PASSWORD` to have a simple `GOVC_URL`
* `GOVC_INSECURE`: Allow establishing insecure connections.
> Use this option when the host you're connecting is using self-signed
> certificates, or is otherwise trusted. Set this option to `1` to enable.
* `GOVC_DATACENTER`
* `GOVC_DATASTORE`
* `GOVC_NETWORK`
* `GOVC_RESOURCE_POOL`
* `GOVC_HOST`
* `GOVC_GUEST_LOGIN`: Guest credentials for guest operations
* `GOVC_VIM_NAMESPACE`: Vim namespace defaults to `urn:vim25`
* `GOVC_VIM_VERSION`: Vim version defaults to `6.0`
## Examples
* About
```
$ export GOVC_URL="192.168.1.20"
$ export GOVC_USERNAME="domain\administrator"
$ export GOVC_PASSWORD="Password123#"
$ govc about
Name: VMware vCenter Server
Vendor: VMware, Inc.
Version: 6.0.0
Build: 2656761
OS type: linux-x64
API type: VirtualCenter
API version: 6.0
Product ID: vpx
UUID: c9f0242f-10e3-4e10-85d7-5eea7c855188
```
* [Upload ssh public key to a VM](examples/lib/ssh.sh)
* [Create and configure a vCenter VM](examples/vcsa.sh)
## Projects using govc
* [Kubernetes vSphere Provider](https://github.com/GoogleCloudPlatform/kubernetes/tree/master/cluster/vsphere)
* [Emacs govc package](./emacs)
## License
govc is available under the [Apache 2 license](../LICENSE).
/*
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 about
import (
"flag"
"fmt"
"os"
"text/tabwriter"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type about struct {
*flags.ClientFlag
}
func init() {
cli.Register("about", &about{})
}
func (cmd *about) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
}
func (cmd *about) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *about) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return err
}
a := c.ServiceContent.About
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Name:\t%s\n", a.Name)
fmt.Fprintf(tw, "Vendor:\t%s\n", a.Vendor)
fmt.Fprintf(tw, "Version:\t%s\n", a.Version)
fmt.Fprintf(tw, "Build:\t%s\n", a.Build)
fmt.Fprintf(tw, "OS type:\t%s\n", a.OsType)
fmt.Fprintf(tw, "API type:\t%s\n", a.ApiType)
fmt.Fprintf(tw, "API version:\t%s\n", a.ApiVersion)
fmt.Fprintf(tw, "Product ID:\t%s\n", a.ProductLineId)
fmt.Fprintf(tw, "UUID:\t%s\n", a.InstanceUuid)
return tw.Flush()
}
#!/bin/bash -e
git_version=$(git describe)
if git_status=$(git status --porcelain 2>/dev/null) && [ -n "${git_status}" ]; then
git_version="${git_version}-dirty"
fi
ldflags="-X github.com/vmware/govmomi/govc/version.gitVersion=${git_version}"
BUILD_OS=${BUILD_OS:-darwin linux windows freebsd}
BUILD_ARCH=${BUILD_ARCH:-386 amd64}
for os in ${BUILD_OS}; do
export GOOS="${os}"
for arch in ${BUILD_ARCH}; do
export GOARCH="${arch}"
out="govc_${os}_${arch}"
if [ "${os}" == "windows" ]; then
out="${out}.exe"
fi
set -x
go build \
-o="${out}" \
-pkgdir="./_pkg" \
-compiler='gc' \
-ldflags="${ldflags}" \
github.com/vmware/govmomi/govc
set +x
done
done
/*
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 cli
import (
"flag"
"fmt"
"io/ioutil"
"os"
"sort"
"text/tabwriter"
"golang.org/x/net/context"
)
type HasFlags interface {
// Register may be called more than once and should be idempotent.
Register(ctx context.Context, f *flag.FlagSet)
// Process may be called more than once and should be idempotent.
Process(ctx context.Context) error
}
type Command interface {
HasFlags
Run(ctx context.Context, f *flag.FlagSet) error
}
func generalHelp() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
cmds := []string{}
for name := range commands {
cmds = append(cmds, name)
}
sort.Strings(cmds)
for _, name := range cmds {
fmt.Fprintf(os.Stderr, " %s\n", name)
}
}
func commandHelp(name string, cmd Command, f *flag.FlagSet) {
type HasUsage interface {
Usage() string
}
fmt.Fprintf(os.Stderr, "Usage: %s %s [OPTIONS]", os.Args[0], name)
if u, ok := cmd.(HasUsage); ok {
fmt.Fprintf(os.Stderr, " %s", u.Usage())
}
fmt.Fprintf(os.Stderr, "\n")
type HasDescription interface {
Description() string
}
if u, ok := cmd.(HasDescription); ok {
fmt.Fprintf(os.Stderr, "%s\n", u.Description())
}
n := 0
f.VisitAll(func(_ *flag.Flag) {
n += 1
})
if n > 0 {
fmt.Fprintf(os.Stderr, "\nOptions:\n")
tw := tabwriter.NewWriter(os.Stderr, 2, 0, 2, ' ', 0)
f.VisitAll(func(f *flag.Flag) {
fmt.Fprintf(tw, "\t-%s=%s\t%s\n", f.Name, f.DefValue, f.Usage)
})
tw.Flush()
}
}
func Run(args []string) int {
var err error
if len(args) == 0 {
generalHelp()
return 1
}
// Look up real command name in aliases table.
name, ok := aliases[args[0]]
if !ok {
name = args[0]
}
cmd, ok := commands[name]
if !ok {
generalHelp()
return 1
}
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.SetOutput(ioutil.Discard)
ctx := context.Background()
cmd.Register(ctx, fs)
if err = fs.Parse(args[1:]); err != nil {
goto error
}
if err = cmd.Process(ctx); err != nil {
goto error
}
if err = cmd.Run(ctx, fs); err != nil {
goto error
}
return 0
error:
if err == flag.ErrHelp {
commandHelp(args[0], cmd, fs)
} else {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
}
return 1
}
/*
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 cli
var commands = map[string]Command{}
var aliases = map[string]string{}
func Register(name string, c Command) {
commands[name] = c
}
func Alias(name string, alias string) {
aliases[alias] = name
}
func Commands() map[string]Command {
return commands
}
/*
Copyright (c) 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 cluster
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"golang.org/x/net/context"
)
type add struct {
*flags.DatacenterFlag
*flags.HostConnectFlag
cluster string
connect bool
license string
}
func init() {
cli.Register("cluster.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
cmd.HostConnectFlag, ctx = flags.NewHostConnectFlag(ctx)
cmd.HostConnectFlag.Register(ctx, f)
f.StringVar(&cmd.cluster, "cluster", "*", "Path to cluster")
f.StringVar(&cmd.license, "license", "", "Assign license key")
f.BoolVar(&cmd.connect, "connect", true, "Immediately connect to host")
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostConnectFlag.Process(ctx); err != nil {
return err
}
if cmd.HostName == "" {
return flag.ErrHelp
}
if cmd.UserName == "" {
return flag.ErrHelp
}
if cmd.Password == "" {
return flag.ErrHelp
}
return nil
}
func (cmd *add) Description() string {
return `Add host to cluster.
The host is added to the cluster specified by the 'cluster' flag.`
}
func (cmd *add) Add(ctx context.Context, cluster *object.ClusterComputeResource) error {
spec := cmd.HostConnectSpec
var license *string
if cmd.license != "" {
license = &cmd.license
}
task, err := cluster.AddHost(ctx, spec, cmd.connect, license, nil)
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("adding %s to cluster %s... ", spec.HostName, cluster.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 0 {
return flag.ErrHelp
}
finder, err := cmd.Finder()
if err != nil {
return err
}
cluster, err := finder.ClusterComputeResource(ctx, cmd.cluster)
if err != nil {
return nil
}
err = cmd.Add(ctx, cluster)
if err == nil {
return nil
}
// Check if we failed due to SSLVerifyFault and -noverify is set
if err := cmd.AcceptThumbprint(err); err != nil {
return err
}
// Accepted unverified thumbprint, try again
return cmd.Add(ctx, cluster)
}
/*
Copyright (c) 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 cluster
import (
"flag"
"strings"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type change struct {
*flags.DatacenterFlag
types.ClusterConfigSpecEx
}
func init() {
cli.Register("cluster.change", &change{})
}
func (cmd *change) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
cmd.DrsConfig = new(types.ClusterDrsConfigInfo)
cmd.DasConfig = new(types.ClusterDasConfigInfo)
cmd.VsanConfig = new(types.VsanClusterConfigInfo)
cmd.VsanConfig.DefaultConfig = new(types.VsanClusterConfigInfoHostDefaultInfo)
// DRS
f.Var(flags.NewOptionalBool(&cmd.DrsConfig.Enabled), "drs-enabled", "Enable DRS")
drsModes := []string{
string(types.DrsBehaviorManual),
string(types.DrsBehaviorPartiallyAutomated),
string(types.DrsBehaviorFullyAutomated),
}
f.StringVar((*string)(&cmd.DrsConfig.DefaultVmBehavior), "drs-mode", "",
"DRS behavior for virtual machines: "+strings.Join(drsModes, ", "))
// HA
f.Var(flags.NewOptionalBool(&cmd.DasConfig.Enabled), "ha-enabled", "Enable HA")
// vSAN
f.Var(flags.NewOptionalBool(&cmd.VsanConfig.Enabled), "vsan-enabled", "Enable vSAN")
f.Var(flags.NewOptionalBool(&cmd.VsanConfig.DefaultConfig.AutoClaimStorage), "vsan-autoclaim", "")
}
func (cmd *change) Process(ctx context.Context) error {
if err := cmd.DatacenterFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *change) Usage() string {
return "CLUSTER..."
}
func (cmd *change) Description() string {
return `Change configuration of the given clusters.`
}
func (cmd *change) Run(ctx context.Context, f *flag.FlagSet) error {
finder, err := cmd.Finder()
if err != nil {
return err
}
for _, path := range f.Args() {
clusters, err := finder.ClusterComputeResourceList(ctx, path)
if err != nil {
return err
}
for _, cluster := range clusters {
task, err := cluster.Reconfigure(ctx, &cmd.ClusterConfigSpecEx, true)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
}
}
return nil
}
/*
Copyright (c) 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 cluster
import (
"flag"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
type create struct {
*flags.DatacenterFlag
parent string
types.ClusterConfigSpecEx
}
func init() {
cli.Register("cluster.create", &create{})
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
f.StringVar(&cmd.parent, "parent", "", "Path to parent folder for the new cluster")
}
func (cmd *create) Usage() string {
return "CLUSTER"
}
func (cmd *create) Description() string {
return `Create CLUSTER in datacenter.
The cluster is added to the folder specified by the 'parent' flag. If not given,
this defaults to the hosts folder in the specified or default datacenter.`
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.DatacenterFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
var parent *object.Folder
if f.NArg() != 1 {
return flag.ErrHelp
}
if cmd.parent == "" {
dc, err := cmd.Datacenter()
if err != nil {
return err
}
folders, err := dc.Folders(ctx)
if err != nil {
return err
}
parent = folders.HostFolder
} else {
finder, err := cmd.Finder()
if err != nil {
return err
}
parent, err = finder.Folder(ctx, cmd.parent)
if err != nil {
return err
}
}
_, err := parent.CreateCluster(ctx, f.Arg(0), cmd.ClusterConfigSpecEx)
if err != nil {
return err
}
return nil
}
/*
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 datacenter
import (
"flag"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"golang.org/x/net/context"
)
type create struct {
*flags.ClientFlag
}
func init() {
cli.Register("datacenter.create", &create{})
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
}
func (cmd *create) Usage() string {
return "[DATACENTER NAME]..."
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
datacenters := f.Args()
if len(datacenters) < 1 {
return flag.ErrHelp
}
client, err := cmd.ClientFlag.Client()
if err != nil {
return err
}
finder := find.NewFinder(client, false)
rootFolder := object.NewRootFolder(client)
for _, datacenterToCreate := range datacenters {
_, err := finder.Datacenter(context.TODO(), datacenterToCreate)
if err == nil {
// The datacenter was found, no need to create it
continue
}
switch err.(type) {
case *find.NotFoundError:
_, err = rootFolder.CreateDatacenter(context.TODO(), datacenterToCreate)
if err != nil {
return err
}
default:
return err
}
}
return nil
}
/*
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 datacenter
import (
"flag"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type destroy struct {
*flags.ClientFlag
}
func init() {
cli.Register("datacenter.destroy", &destroy{})
}
func (cmd *destroy) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
}
func (cmd *destroy) Usage() string {
return "[DATACENTER NAME]..."
}
func (cmd *destroy) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
if len(f.Args()) < 1 {
return flag.ErrHelp
}
datacentersToDestroy := f.Args()
client, err := cmd.ClientFlag.Client()
if err != nil {
return err
}
finder := find.NewFinder(client, false)
for _, datacenterToDestroy := range datacentersToDestroy {
foundDatacenters, err := finder.DatacenterList(context.TODO(), datacenterToDestroy)
if err != nil {
return err
}
for _, foundDatacenter := range foundDatacenters {
task, err := foundDatacenter.Destroy(context.TODO())
if err != nil {
return err
}
if err := task.Wait(context.TODO()); err != nil {
return err
}
}
}
return nil
}
/*
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 datastore
import (
"errors"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"golang.org/x/net/context"
)
type cp struct {
*flags.OutputFlag
*flags.DatastoreFlag
force bool
}
func init() {
cli.Register("datastore.cp", &cp{})
}
func (cmd *cp) Register(ctx context.Context, f *flag.FlagSet) {
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
f.BoolVar(&cmd.force, "f", false, "If true, overwrite any identically named file at the destination")
}
func (cmd *cp) Process(ctx context.Context) error {
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *cp) Usage() string {
return "SRC DST"
}
func (cmd *cp) Run(ctx context.Context, f *flag.FlagSet) error {
args := f.Args()
if len(args) != 2 {
return errors.New("SRC and DST arguments are required")
}
c, err := cmd.Client()
if err != nil {
return err
}
dc, err := cmd.Datacenter()
if err != nil {
return err
}
// TODO: support cross-datacenter copy
src, err := cmd.DatastorePath(args[0])
if err != nil {
return err
}
dst, err := cmd.DatastorePath(args[1])
if err != nil {
return err
}
m := object.NewFileManager(c)
task, err := m.CopyDatastoreFile(context.TODO(), src, dc, dst, dc, cmd.force)
if err != nil {
return err
}
return task.Wait(context.TODO())
}
/*
Copyright (c) 2015-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 datastore
import (
"errors"
"flag"
"fmt"
"os"
"strings"
"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"
"golang.org/x/net/context"
)
type create struct {
*flags.HostSystemFlag
// Generic options
Type typeFlag
Name string
Force bool
// Options for NAS
RemoteHost string
RemotePath string
AccessMode string
UserName string
Password string
// Options for VMFS
DiskCanonicalName string
}
func init() {
cli.Register("datastore.create", &create{})
}
var nasTypes = []string{
string(types.HostFileSystemVolumeFileSystemTypeNFS),
string(types.HostFileSystemVolumeFileSystemTypeNFS41),
string(types.HostFileSystemVolumeFileSystemTypeCIFS),
}
var vmfsTypes = []string{
string(types.HostFileSystemVolumeFileSystemTypeVMFS),
}
var allTypes = []string{}
func init() {
allTypes = append(allTypes, nasTypes...)
allTypes = append(allTypes, vmfsTypes...)
}
type typeFlag string
func (t *typeFlag) Set(s string) error {
s = strings.ToLower(s)
for _, e := range allTypes {
if s == strings.ToLower(e) {
*t = typeFlag(e)
return nil
}
}
return fmt.Errorf("unknown type")
}
func (t *typeFlag) String() string {
return string(*t)
}
func (t *typeFlag) partOf(m []string) bool {
for _, e := range m {
if t.String() == e {
return true
}
}
return false
}
func (t *typeFlag) IsNasType() bool {
return t.partOf(nasTypes)
}
func (t *typeFlag) IsVmfsType() bool {
return t.partOf(vmfsTypes)
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
modes := []string{
string(types.HostMountModeReadOnly),
string(types.HostMountModeReadWrite),
}
f.StringVar(&cmd.Name, "name", "", "Datastore name")
f.Var(&cmd.Type, "type", fmt.Sprintf("Datastore type (%s)", strings.Join(allTypes, "|")))
f.BoolVar(&cmd.Force, "force", false, "Ignore DuplicateName error if datastore is already mounted on a host")
// Options for NAS
f.StringVar(&cmd.RemoteHost, "remote-host", "", "Remote hostname of the NAS datastore")
f.StringVar(&cmd.RemotePath, "remote-path", "", "Remote path of the NFS mount point")
f.StringVar(&cmd.AccessMode, "mode", modes[0],
fmt.Sprintf("Access mode for the mount point (%s)", strings.Join(modes, "|")))
f.StringVar(&cmd.UserName, "username", "", "Username to use when connecting (CIFS only)")
f.StringVar(&cmd.Password, "password", "", "Password to use when connecting (CIFS only)")
// Options for VMFS
f.StringVar(&cmd.DiskCanonicalName, "disk", "", "Canonical name of disk (VMFS only)")
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *create) Usage() string {
return "HOST..."
}
func (cmd *create) Description() string {
return `Create datastore on HOST.
Examples:
govc datastore.create -type nfs -name nfsDatastore -remote-host 10.143.2.232 -remote-path /share cluster1
govc datastore.create -type vmfs -name localDatastore -disk=mpx.vmhba0:C0:T0:L0 cluster1`
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
switch {
case cmd.Type.IsNasType():
return cmd.CreateNasDatastore(ctx, hosts)
case cmd.Type.IsVmfsType():
return cmd.CreateVmfsDatastore(ctx, hosts)
default:
return fmt.Errorf("unhandled type %#v", cmd.Type)
}
}
func (cmd *create) GetHostNasVolumeSpec() types.HostNasVolumeSpec {
s := types.HostNasVolumeSpec{
LocalPath: cmd.Name,
Type: cmd.Type.String(),
RemoteHost: cmd.RemoteHost,
RemotePath: cmd.RemotePath,
AccessMode: cmd.AccessMode,
UserName: cmd.UserName,
Password: cmd.Password,
}
return s
}
func (cmd *create) CreateNasDatastore(ctx context.Context, hosts []*object.HostSystem) error {
object := types.ManagedObjectReference{
Type: "Datastore",
Value: fmt.Sprintf("%s:%s", cmd.RemoteHost, cmd.RemotePath),
}
spec := cmd.GetHostNasVolumeSpec()
for _, host := range hosts {
ds, err := host.ConfigManager().DatastoreSystem(ctx)
if err != nil {
return err
}
_, err = ds.CreateNasDatastore(ctx, spec)
if err != nil {
if soap.IsSoapFault(err) {
switch fault := soap.ToSoapFault(err).VimFault().(type) {
case types.PlatformConfigFault:
if len(fault.FaultMessage) != 0 {
return errors.New(fault.FaultMessage[0].Message)
}
case types.DuplicateName:
if cmd.Force && fault.Object == object {
fmt.Fprintf(os.Stderr, "%s: '%s' already mounted\n",
host.InventoryPath, cmd.Name)
continue
}
}
}
return fmt.Errorf("%s: %s", host.InventoryPath, err)
}
}
return nil
}
func (cmd *create) CreateVmfsDatastore(ctx context.Context, hosts []*object.HostSystem) error {
for _, host := range hosts {
ds, err := host.ConfigManager().DatastoreSystem(ctx)
if err != nil {
return err
}
// Find the specified disk
disks, err := ds.QueryAvailableDisksForVmfs(ctx)
if err != nil {
return err
}
var disk *types.HostScsiDisk
for _, e := range disks {
if e.CanonicalName == cmd.DiskCanonicalName {
disk = &e
break
}
}
if disk == nil {
return fmt.Errorf("no eligible disk found for name %#v", cmd.DiskCanonicalName)
}
// Query for creation options and pick the right one
options, err := ds.QueryVmfsDatastoreCreateOptions(ctx, disk.DevicePath)
if err != nil {
return err
}
var option *types.VmfsDatastoreOption
for _, e := range options {
if _, ok := e.Info.(*types.VmfsDatastoreAllExtentOption); ok {
option = &e
break
}
}
if option == nil {
return fmt.Errorf("cannot use entire disk for datastore for name %#v", cmd.DiskCanonicalName)
}
spec := *option.Spec.(*types.VmfsDatastoreCreateSpec)
spec.Vmfs.VolumeName = cmd.Name
_, err = ds.CreateVmfsDatastore(ctx, spec)
if err != nil {
return err
}
}
return nil
}
/*
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 datastore
import (
"errors"
"flag"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/soap"
)
type download struct {
*flags.DatastoreFlag
}
func init() {
cli.Register("datastore.download", &download{})
}
func (cmd *download) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
}
func (cmd *download) Process(ctx context.Context) error {
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *download) Usage() string {
return "REMOTE LOCAL"
}
func (cmd *download) Run(ctx context.Context, f *flag.FlagSet) error {
args := f.Args()
if len(args) != 2 {
return errors.New("invalid arguments")
}
ds, err := cmd.Datastore()
if err != nil {
return err
}
p := soap.DefaultDownload
if cmd.OutputFlag.TTY {
logger := cmd.ProgressLogger("Downloading... ")
p.Progress = logger
defer logger.Wait()
}
return ds.DownloadFile(context.TODO(), args[0], args[1], &p)
}
/*
Copyright (c) 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 datastore
import (
"flag"
"fmt"
"io"
"os"
"text/tabwriter"
"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/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type info struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.DatacenterFlag
}
func init() {
cli.Register("datastore.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.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
}
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.DatacenterFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Usage() string {
return "[PATH]..."
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return err
}
finder, err := cmd.Finder()
if err != nil {
return err
}
args := f.Args()
if len(args) == 0 {
args = []string{"*"}
}
var res infoResult
var props []string
if cmd.OutputFlag.JSON {
props = nil // Load everything
} else {
props = []string{"info", "summary"} // Load summary
}
for _, arg := range args {
objects, err := finder.DatastoreList(ctx, arg)
if err != nil {
return err
}
res.objects = append(res.objects, objects...)
}
if len(res.objects) != 0 {
refs := make([]types.ManagedObjectReference, 0, len(res.objects))
for _, o := range res.objects {
refs = append(refs, o.Reference())
}
pc := property.DefaultCollector(c)
err = pc.Retrieve(ctx, refs, props, &res.Datastores)
if err != nil {
return err
}
}
return cmd.WriteResult(&res)
}
type infoResult struct {
Datastores []mo.Datastore
objects []*object.Datastore
}
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.Datastore, len(r.Datastores))
for _, o := range r.Datastores {
objects[o.Reference()] = o
}
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
for _, o := range r.objects {
ds := objects[o.Reference()]
s := ds.Summary
fmt.Fprintf(tw, "Name:\t%s\n", s.Name)
fmt.Fprintf(tw, " Path:\t%s\n", o.InventoryPath)
fmt.Fprintf(tw, " Type:\t%s\n", s.Type)
fmt.Fprintf(tw, " URL:\t%s\n", s.Url)
fmt.Fprintf(tw, " Capacity:\t%.1f GB\n", float64(s.Capacity)/(1<<30))
fmt.Fprintf(tw, " Free:\t%.1f GB\n", float64(s.FreeSpace)/(1<<30))
switch info := ds.Info.(type) {
case *types.NasDatastoreInfo:
fmt.Fprintf(tw, " Remote:\t%s:%s\n", info.Nas.RemoteHost, info.Nas.RemotePath)
}
}
return tw.Flush()
}
/*
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 datastore
import (
"encoding/json"
"flag"
"fmt"
"io"
"path"
"text/tabwriter"
"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"
"golang.org/x/net/context"
)
type ls struct {
*flags.DatastoreFlag
*flags.OutputFlag
long bool
slash bool
all bool
}
func init() {
cli.Register("datastore.ls", &ls{})
}
func (cmd *ls) 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)
f.BoolVar(&cmd.long, "l", false, "Long listing format")
f.BoolVar(&cmd.slash, "p", false, "Write a slash (`/') after each filename if that file is a directory")
f.BoolVar(&cmd.all, "a", false, "Include entries whose names begin with a dot (.)")
}
func (cmd *ls) 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
}
return nil
}
func (cmd *ls) Usage() string {
return "[FILE]..."
}
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
ds, err := cmd.Datastore()
if err != nil {
return err
}
b, err := ds.Browser(context.TODO())
if err != nil {
return err
}
args := f.Args()
if len(args) == 0 {
args = []string{""}
}
result := &listOutput{
rs: make([]types.HostDatastoreBrowserSearchResults, 0),
cmd: cmd,
}
for _, arg := range args {
spec := types.HostDatastoreBrowserSearchSpec{
MatchPattern: []string{"*"},
}
if cmd.long {
spec.Details = &types.FileQueryFlags{
FileType: true,
FileSize: true,
FileOwner: types.NewBool(true), // TODO: omitempty is generated, but seems to be required
Modification: true,
}
}
for i := 0; ; i++ {
r, err := cmd.ListPath(b, arg, spec)
if err != nil {
// Treat the argument as a match pattern if not found as directory
if i == 0 && types.IsFileNotFound(err) {
spec.MatchPattern[0] = path.Base(arg)
arg = path.Dir(arg)
continue
}
return err
}
// Treat an empty result against match pattern as file not found
if i == 1 && len(r.File) == 0 {
return fmt.Errorf("File %s/%s was not found", r.FolderPath, spec.MatchPattern[0])
}
result.add(r)
break
}
}
return cmd.WriteResult(result)
}
func (cmd *ls) ListPath(b *object.HostDatastoreBrowser, path string, spec types.HostDatastoreBrowserSearchSpec) (types.HostDatastoreBrowserSearchResults, error) {
var res types.HostDatastoreBrowserSearchResults
path, err := cmd.DatastorePath(path)
if err != nil {
return res, err
}
task, err := b.SearchDatastore(context.TODO(), path, &spec)
if err != nil {
return res, err
}
info, err := task.WaitForResult(context.TODO(), nil)
if err != nil {
return res, err
}
res = info.Result.(types.HostDatastoreBrowserSearchResults)
return res, nil
}
type listOutput struct {
rs []types.HostDatastoreBrowserSearchResults
cmd *ls
}
func (o *listOutput) add(r types.HostDatastoreBrowserSearchResults) {
res := r
res.File = nil
for _, f := range r.File {
if f.GetFileInfo().Path[0] == '.' && !o.cmd.all {
continue
}
if o.cmd.slash {
if d, ok := f.(*types.FolderFileInfo); ok {
d.Path += "/"
}
}
res.File = append(res.File, f)
}
o.rs = append(o.rs, res)
}
// hasMultiplePaths returns whether or not the slice of search results contains
// results from more than one folder path.
func (o *listOutput) hasMultiplePaths() bool {
if len(o.rs) == 0 {
return false
}
p := o.rs[0].FolderPath
// Multiple paths if any entry is not equal to the first one.
for _, e := range o.rs {
if e.FolderPath != p {
return true
}
}
return false
}
func (o *listOutput) MarshalJSON() ([]byte, error) {
return json.Marshal(o.rs)
}
func (o *listOutput) Write(w io.Writer) error {
// Only include path header if we're dealing with more than one path.
includeHeader := false
if o.hasMultiplePaths() {
includeHeader = true
}
tw := tabwriter.NewWriter(w, 3, 0, 2, ' ', 0)
for i, r := range o.rs {
if includeHeader {
if i > 0 {
fmt.Fprintf(tw, "\n")
}
fmt.Fprintf(tw, "%s:\n", r.FolderPath)
}
for _, file := range r.File {
info := file.GetFileInfo()
if o.cmd.long {
fmt.Fprintf(tw, "%s\t%s\t%s\n", units.ByteSize(info.FileSize), info.Modification.Format("Mon Jan 2 15:04:05 2006"), info.Path)
} else {
fmt.Fprintf(tw, "%s\n", info.Path)
}
}
}
tw.Flush()
return nil
}
/*
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 datastore
import (
"errors"
"flag"
"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"
"golang.org/x/net/context"
)
type mkdir struct {
*flags.DatastoreFlag
createParents bool
}
func init() {
cli.Register("datastore.mkdir", &mkdir{})
}
func (cmd *mkdir) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.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.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mkdir) Usage() string {
return "DIRECTORY"
}
func (cmd *mkdir) Run(ctx context.Context, f *flag.FlagSet) error {
args := f.Args()
if len(args) == 0 {
return errors.New("missing operand")
}
c, err := cmd.Client()
if err != nil {
return err
}
dc, err := cmd.Datacenter()
if err != nil {
return err
}
// TODO(PN): Accept multiple args
path, err := cmd.DatastorePath(args[0])
if err != nil {
return err
}
m := object.NewFileManager(c)
err = m.MakeDirectory(context.TODO(), path, dc, 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
}
/*
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 datastore
import (
"errors"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"golang.org/x/net/context"
)
type mv struct {
*flags.DatastoreFlag
force bool
}
func init() {
cli.Register("datastore.mv", &mv{})
}
func (cmd *mv) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
f.BoolVar(&cmd.force, "f", false, "If true, overwrite any identically named file at the destination")
}
func (cmd *mv) Process(ctx context.Context) error {
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mv) Usage() string {
return "SRC DST"
}
func (cmd *mv) Run(ctx context.Context, f *flag.FlagSet) error {
args := f.Args()
if len(args) != 2 {
return errors.New("SRC and DST arguments are required")
}
c, err := cmd.Client()
if err != nil {
return err
}
dc, err := cmd.Datacenter()
if err != nil {
return err
}
// TODO: support cross-datacenter move
src, err := cmd.DatastorePath(args[0])
if err != nil {
return err
}
dst, err := cmd.DatastorePath(args[1])
if err != nil {
return err
}
m := object.NewFileManager(c)
task, err := m.MoveDatastoreFile(context.TODO(), src, dc, dst, dc, cmd.force)
if err != nil {
return err
}
return task.Wait(context.TODO())
}
/*
Copyright (c) 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 datastore
import (
"flag"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type remove struct {
*flags.HostSystemFlag
*flags.DatastoreFlag
}
func init() {
cli.Register("datastore.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Usage() string {
return "HOST..."
}
func (cmd *remove) Description() string {
return `Remove datastore from HOST.
Example:
govc datastore.remove -ds nfsDatastore cluster1
`
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
ds, err := cmd.Datastore()
if err != nil {
return err
}
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
hds, err := host.ConfigManager().DatastoreSystem(ctx)
if err != nil {
return err
}
err = hds.Remove(ctx, ds)
if err != nil {
return err
}
}
return nil
}
/*
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 datastore
import (
"errors"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type rm struct {
*flags.DatastoreFlag
force bool
}
func init() {
cli.Register("datastore.rm", &rm{})
cli.Alias("datastore.rm", "datastore.delete")
}
func (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
f.BoolVar(&cmd.force, "f", false, "Force; ignore nonexistent files and arguments")
}
func (cmd *rm) Process(ctx context.Context) error {
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *rm) Usage() string {
return "FILE"
}
func (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {
args := f.Args()
if len(args) == 0 {
return errors.New("missing operand")
}
c, err := cmd.Client()
if err != nil {
return err
}
dc, err := cmd.Datacenter()
if err != nil {
return err
}
// TODO(PN): Accept multiple args
path, err := cmd.DatastorePath(args[0])
if err != nil {
return err
}
m := object.NewFileManager(c)
task, err := m.DeleteDatastoreFile(context.TODO(), path, dc)
if err != nil {
return err
}
err = task.Wait(context.TODO())
if err != nil {
if types.IsFileNotFound(err) && cmd.force {
// Ignore error
return nil
}
}
return err
}
/*
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 datastore
import (
"errors"
"flag"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/soap"
)
type upload struct {
*flags.OutputFlag
*flags.DatastoreFlag
}
func init() {
cli.Register("datastore.upload", &upload{})
}
func (cmd *upload) Register(ctx context.Context, f *flag.FlagSet) {
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)
cmd.DatastoreFlag.Register(ctx, f)
}
func (cmd *upload) Process(ctx context.Context) error {
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
if err := cmd.DatastoreFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *upload) Usage() string {
return "LOCAL REMOTE"
}
func (cmd *upload) Run(ctx context.Context, f *flag.FlagSet) error {
args := f.Args()
if len(args) != 2 {
return errors.New("invalid arguments")
}
ds, err := cmd.Datastore()
if err != nil {
return err
}
p := soap.DefaultUpload
if cmd.OutputFlag.TTY {
logger := cmd.ProgressLogger("Uploading... ")
p.Progress = logger
defer logger.Wait()
}
return ds.UploadFile(context.TODO(), args[0], args[1], &p)
}
/*
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 device
import (
"flag"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type boot struct {
*flags.VirtualMachineFlag
order string
types.VirtualMachineBootOptions
}
func init() {
cli.Register("device.boot", &boot{})
}
func (cmd *boot) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.Int64Var(&cmd.BootDelay, "delay", 0, "Delay in ms before starting the boot sequence")
f.StringVar(&cmd.order, "order", "", "Boot device order")
f.Int64Var(&cmd.BootRetryDelay, "retry-delay", 0, "Delay in ms before a boot retry")
cmd.BootRetryEnabled = types.NewBool(false)
f.BoolVar(cmd.BootRetryEnabled, "retry", false, "If true, retry boot after retry-delay")
cmd.EnterBIOSSetup = types.NewBool(false)
f.BoolVar(cmd.EnterBIOSSetup, "setup", false, "If true, enter BIOS setup on next boot")
}
func (cmd *boot) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *boot) 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(context.TODO())
if err != nil {
return err
}
if cmd.order != "" {
o := strings.Split(cmd.order, ",")
cmd.BootOrder = devices.BootOrder(o)
}
return vm.SetBootOptions(context.TODO(), &cmd.VirtualMachineBootOptions)
}
/*
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 cdrom
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type add struct {
*flags.VirtualMachineFlag
controller string
}
func init() {
cli.Register("device.cdrom.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.StringVar(&cmd.controller, "controller", "", "IDE controller name")
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *add) 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(context.TODO())
if err != nil {
return err
}
c, err := devices.FindIDEController(cmd.controller)
if err != nil {
return err
}
d, err := devices.CreateCdrom(c)
if err != nil {
return err
}
err = vm.AddDevice(context.TODO(), d)
if err != nil {
return err
}
// output name of device we just created
devices, err = vm.Device(context.TODO())
if err != nil {
return err
}
devices = devices.SelectByType(d)
name := devices.Name(devices[len(devices)-1])
fmt.Println(name)
return nil
}
/*
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 cdrom
import (
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type eject struct {
*flags.VirtualMachineFlag
device string
}
func init() {
cli.Register("device.cdrom.eject", &eject{})
}
func (cmd *eject) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.StringVar(&cmd.device, "device", "", "CD-ROM device name")
}
func (cmd *eject) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *eject) Description() string {
return `Eject media from CD-ROM device.
If device is not specified, the first CD-ROM device is used.`
}
func (cmd *eject) 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(context.TODO())
if err != nil {
return err
}
c, err := devices.FindCdrom(cmd.device)
if err != nil {
return err
}
return vm.EditDevice(context.TODO(), devices.EjectIso(c))
}
/*
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 cdrom
import (
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type insert struct {
*flags.DatastoreFlag
*flags.VirtualMachineFlag
device string
}
func init() {
cli.Register("device.cdrom.insert", &insert{})
}
func (cmd *insert) 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.StringVar(&cmd.device, "device", "", "CD-ROM device name")
}
func (cmd *insert) 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 *insert) Usage() string {
return "ISO"
}
func (cmd *insert) Description() string {
return `Insert media on datastore into CD-ROM device.
If device is not specified, the first CD-ROM device is used.`
}
func (cmd *insert) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil || f.NArg() != 1 {
return flag.ErrHelp
}
devices, err := vm.Device(context.TODO())
if err != nil {
return err
}
c, err := devices.FindCdrom(cmd.device)
if err != nil {
return err
}
iso, err := cmd.DatastorePath(f.Arg(0))
if err != nil {
return nil
}
return vm.EditDevice(context.TODO(), devices.InsertIso(c, iso))
}
/*
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 device
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type connect struct {
*flags.VirtualMachineFlag
}
func init() {
cli.Register("device.connect", &connect{})
}
func (cmd *connect) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
}
func (cmd *connect) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *connect) Usage() string {
return "DEVICE..."
}
func (cmd *connect) 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(context.TODO())
if err != nil {
return err
}
for _, name := range f.Args() {
device := devices.Find(name)
if device == nil {
return fmt.Errorf("device '%s' not found", name)
}
if err = devices.Connect(device); err != nil {
return err
}
if err = vm.EditDevice(context.TODO(), device); err != nil {
return err
}
}
return nil
}
/*
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 device
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type disconnect struct {
*flags.VirtualMachineFlag
}
func init() {
cli.Register("device.disconnect", &disconnect{})
}
func (cmd *disconnect) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
}
func (cmd *disconnect) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *disconnect) Usage() string {
return "DEVICE..."
}
func (cmd *disconnect) 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(context.TODO())
if err != nil {
return err
}
for _, name := range f.Args() {
device := devices.Find(name)
if device == nil {
return fmt.Errorf("device '%s' not found", name)
}
if err = devices.Disconnect(device); err != nil {
return err
}
if err = vm.EditDevice(context.TODO(), device); err != nil {
return err
}
}
return nil
}
/*
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 floppy
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type add struct {
*flags.VirtualMachineFlag
}
func init() {
cli.Register("device.floppy.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *add) 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(context.TODO())
if err != nil {
return err
}
d, err := devices.CreateFloppy()
if err != nil {
return err
}
err = vm.AddDevice(context.TODO(), d)
if err != nil {
return err
}
// output name of device we just created
devices, err = vm.Device(context.TODO())
if err != nil {
return err
}
devices = devices.SelectByType(d)
name := devices.Name(devices[len(devices)-1])
fmt.Println(name)
return nil
}
/*
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 floppy
import (
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type eject struct {
*flags.VirtualMachineFlag
device string
}
func init() {
cli.Register("device.floppy.eject", &eject{})
}
func (cmd *eject) Register(ctx context.Context, f *flag.FlagSet) {
cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
cmd.VirtualMachineFlag.Register(ctx, f)
f.StringVar(&cmd.device, "device", "", "Floppy device name")
}
func (cmd *eject) Process(ctx context.Context) error {
if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *eject) Description() string {
return `Eject image from floppy device.
If device is not specified, the first floppy device is used.`
}
func (cmd *eject) 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(context.TODO())
if err != nil {
return err
}
c, err := devices.FindFloppy(cmd.device)
if err != nil {
return err
}
return vm.EditDevice(context.TODO(), devices.EjectImg(c))
}
/*
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 floppy
import (
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"golang.org/x/net/context"
)
type insert struct {
*flags.DatastoreFlag
*flags.VirtualMachineFlag
device string
}
func init() {
cli.Register("device.floppy.insert", &insert{})
}
func (cmd *insert) 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.StringVar(&cmd.device, "device", "", "Floppy device name")
}
func (cmd *insert) 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 *insert) Usage() string {
return "IMG"
}
func (cmd *insert) Description() string {
return `Insert image on datastore into floppy device.
If device is not specified, the first floppy device is used.`
}
func (cmd *insert) Run(ctx context.Context, f *flag.FlagSet) error {
vm, err := cmd.VirtualMachine()
if err != nil {
return err
}
if vm == nil || f.NArg() != 1 {
return flag.ErrHelp
}
devices, err := vm.Device(context.TODO())
if err != nil {
return err
}
c, err := devices.FindFloppy(cmd.device)
if err != nil {
return err
}
img, err := cmd.DatastorePath(f.Arg(0))
if err != nil {
return nil
}
return vm.EditDevice(context.TODO(), devices.InsertImg(c, img))
}
/*
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 device
import (
"flag"
"fmt"
"io"
"os"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type info struct {
*flags.VirtualMachineFlag
*flags.OutputFlag
*flags.NetworkFlag
}
func init() {
cli.Register("device.info", &info{})
}
func (cmd *info) 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)
cmd.NetworkFlag, ctx = flags.NewNetworkFlag(ctx)
cmd.NetworkFlag.Register(ctx, f)
}
func (cmd *info) 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
}
if err := cmd.NetworkFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Usage() string {
return "[DEVICE]..."
}
func (cmd *info) 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(context.TODO())
if err != nil {
return err
}
res := infoResult{
list: devices,
}
if cmd.NetworkFlag.IsSet() {
net, err := cmd.Network()
if err != nil {
return err
}
backing, err := net.EthernetCardBackingInfo(context.TODO())
if err != nil {
return err
}
devices = devices.SelectByBackingInfo(backing)
}
if f.NArg() == 0 {
res.Devices = devices
} else {
for _, name := range f.Args() {
device := devices.Find(name)
if device == nil {
return fmt.Errorf("device '%s' not found", name)
}
res.Devices = append(res.Devices, device)
}
}
return cmd.WriteResult(&res)
}
type infoResult struct {
Devices object.VirtualDeviceList
// need the full list of devices to lookup attached devices and controllers
list object.VirtualDeviceList
}
func (r *infoResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
for _, device := range r.Devices {
d := device.GetVirtualDevice()
info := d.DeviceInfo.GetDescription()
fmt.Fprintf(tw, "Name:\t%s\n", r.Devices.Name(device))
fmt.Fprintf(tw, " Type:\t%s\n", r.Devices.TypeName(device))
fmt.Fprintf(tw, " Label:\t%s\n", info.Label)
fmt.Fprintf(tw, " Summary:\t%s\n", info.Summary)
fmt.Fprintf(tw, " Key:\t%d\n", d.Key)
if c, ok := device.(types.BaseVirtualController); ok {
var attached []string
for _, key := range c.GetVirtualController().Device {
attached = append(attached, r.Devices.Name(r.list.FindByKey(key)))
}
fmt.Fprintf(tw, " Devices:\t%s\n", strings.Join(attached, ", "))
} else {
if c := r.list.FindByKey(d.ControllerKey); c != nil {
fmt.Fprintf(tw, " Controller:\t%s\n", r.Devices.Name(c))
if d.UnitNumber != nil {
fmt.Fprintf(tw, " Unit number:\t%d\n", *d.UnitNumber)
} else {
fmt.Fprintf(tw, " Unit number:\t<nil>\n")
}
}
}
if ca := d.Connectable; ca != nil {
fmt.Fprintf(tw, " Connected:\t%t\n", ca.Connected)
fmt.Fprintf(tw, " Start connected:\t%t\n", ca.StartConnected)
fmt.Fprintf(tw, " Guest control:\t%t\n", ca.AllowGuestControl)
fmt.Fprintf(tw, " Status:\t%s\n", ca.Status)
}
switch md := device.(type) {
case types.BaseVirtualEthernetCard:
fmt.Fprintf(tw, " MAC Address:\t%s\n", md.GetVirtualEthernetCard().MacAddress)
fmt.Fprintf(tw, " Address type:\t%s\n", md.GetVirtualEthernetCard().AddressType)
case *types.VirtualDisk:
if b, ok := md.Backing.(types.BaseVirtualDeviceFileBackingInfo); ok {
fmt.Fprintf(tw, " File:\t%s\n", b.GetVirtualDeviceFileBackingInfo().FileName)
}
if b, ok := md.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok && b.Parent != nil {
fmt.Fprintf(tw, " Parent:\t%s\n", b.Parent.GetVirtualDeviceFileBackingInfo().FileName)
}
case *types.VirtualSerialPort:
if b, ok := md.Backing.(*types.VirtualSerialPortURIBackingInfo); ok {
fmt.Fprintf(tw, " Direction:\t%s\n", b.Direction)
fmt.Fprintf(tw, " Service URI:\t%s\n", b.ServiceURI)
fmt.Fprintf(tw, " Proxy URI:\t%s\n", b.ProxyURI)
}
}
}
return tw.Flush()
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment