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

add vendoring with go dep

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

View File

@@ -0,0 +1,74 @@
/*
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 account
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
type AccountFlag struct {
*flags.ClientFlag
*flags.DatacenterFlag
*flags.HostSystemFlag
types.HostAccountSpec
}
func newAccountFlag(ctx context.Context) (*AccountFlag, context.Context) {
f := &AccountFlag{}
f.ClientFlag, ctx = flags.NewClientFlag(ctx)
f.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
f.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
return f, ctx
}
func (f *AccountFlag) Register(ctx context.Context, fs *flag.FlagSet) {
f.ClientFlag.Register(ctx, fs)
f.DatacenterFlag.Register(ctx, fs)
f.HostSystemFlag.Register(ctx, fs)
fs.StringVar(&f.Id, "id", "", "The ID of the specified account")
fs.StringVar(&f.Password, "password", "", "The password for the specified account id")
fs.StringVar(&f.Description, "description", "", "The description of the specified account")
}
func (f *AccountFlag) Process(ctx context.Context) error {
if err := f.ClientFlag.Process(ctx); err != nil {
return err
}
if err := f.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := f.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (f *AccountFlag) HostAccountManager(ctx context.Context) (*object.HostAccountManager, error) {
h, err := f.HostSystem()
if err != nil {
return nil, err
}
return h.ConfigManager().AccountManager(ctx)
}

View File

@@ -0,0 +1,59 @@
/*
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 account
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
)
type create struct {
*AccountFlag
}
func init() {
cli.Register("host.account.create", &create{})
}
func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AccountFlag, ctx = newAccountFlag(ctx)
cmd.AccountFlag.Register(ctx, f)
}
func (cmd *create) Description() string {
return `Create local account on HOST.
Examples:
govc host.account.create -id $USER -password password-for-esx60`
}
func (cmd *create) Process(ctx context.Context) error {
if err := cmd.AccountFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.AccountFlag.HostAccountManager(ctx)
if err != nil {
return err
}
return m.Create(ctx, &cmd.HostAccountSpec)
}

View File

@@ -0,0 +1,59 @@
/*
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 account
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
)
type remove struct {
*AccountFlag
}
func init() {
cli.Register("host.account.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AccountFlag, ctx = newAccountFlag(ctx)
cmd.AccountFlag.Register(ctx, f)
}
func (cmd *remove) Description() string {
return `Remove local account on HOST.
Examples:
govc host.account.remove -id $USER`
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.AccountFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.AccountFlag.HostAccountManager(ctx)
if err != nil {
return err
}
return m.Remove(ctx, cmd.HostAccountSpec.Id)
}

View File

@@ -0,0 +1,59 @@
/*
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 account
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
)
type update struct {
*AccountFlag
}
func init() {
cli.Register("host.account.update", &update{})
}
func (cmd *update) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AccountFlag, ctx = newAccountFlag(ctx)
cmd.AccountFlag.Register(ctx, f)
}
func (cmd *update) Description() string {
return `Update local account on HOST.
Examples:
govc host.account.update -id root -password password-for-esx60`
}
func (cmd *update) Process(ctx context.Context) error {
if err := cmd.AccountFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *update) Run(ctx context.Context, f *flag.FlagSet) error {
m, err := cmd.AccountFlag.HostAccountManager(ctx)
if err != nil {
return err
}
return m.Update(ctx, &cmd.HostAccountSpec)
}

116
vendor/github.com/vmware/govmomi/govc/host/add.go generated vendored Normal file
View File

@@ -0,0 +1,116 @@
/*
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 host
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type add struct {
*flags.FolderFlag
*flags.HostConnectFlag
connect bool
}
func init() {
cli.Register("host.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.FolderFlag, ctx = flags.NewFolderFlag(ctx)
cmd.FolderFlag.Register(ctx, f)
cmd.HostConnectFlag, ctx = flags.NewHostConnectFlag(ctx)
cmd.HostConnectFlag.Register(ctx, f)
f.BoolVar(&cmd.connect, "connect", true, "Immediately connect to host")
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.FolderFlag.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 datacenter.
The host is added to the folder specified by the 'folder' flag. If not given,
this defaults to the host folder in the specified or default datacenter.
Examples:
thumbprint=$(govc about.cert -k -u host.example.com -thumbprint | awk '{print $2}')
govc host.add -hostname host.example.com -username root -password pass -thumbprint $thumbprint
govc host.add -hostname 10.0.6.1 -username root -password pass -noverify`
}
func (cmd *add) Add(ctx context.Context, parent *object.Folder) error {
spec := cmd.Spec(parent.Client())
req := types.AddStandaloneHost_Task{
This: parent.Reference(),
Spec: spec,
AddConnected: cmd.connect,
}
res, err := methods.AddStandaloneHost_Task(ctx, parent.Client(), &req)
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("adding %s to folder %s... ", spec.HostName, parent.InventoryPath))
defer logger.Wait()
task := object.NewTask(parent.Client(), res.Returnval)
_, 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
}
folder, err := cmd.FolderOrDefault("host")
if err != nil {
return err
}
return cmd.Fault(cmd.Add(ctx, folder))
}

View File

@@ -0,0 +1,88 @@
/*
Copyright (c) 2015-2017 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package autostart
import (
"context"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type add struct {
*AutostartFlag
// from types.AutoStartPowerInfo
StartOrder int32
StartDelay int32
WaitForHeartbeat string
StartAction string
StopDelay int32
StopAction string
}
func init() {
cli.Register("host.autostart.add", &add{})
}
var waitHeartbeatTypes = []string{
string(types.AutoStartWaitHeartbeatSettingSystemDefault),
string(types.AutoStartWaitHeartbeatSettingYes),
string(types.AutoStartWaitHeartbeatSettingNo),
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AutostartFlag, ctx = newAutostartFlag(ctx)
cmd.AutostartFlag.Register(ctx, f)
cmd.StartOrder = -1
cmd.StartDelay = -1
cmd.StopDelay = -1
f.Var(flags.NewInt32(&cmd.StartOrder), "start-order", "Start Order")
f.Var(flags.NewInt32(&cmd.StartDelay), "start-delay", "Start Delay")
f.Var(flags.NewInt32(&cmd.StopDelay), "stop-delay", "Stop Delay")
f.StringVar(&cmd.StartAction, "start-action", "powerOn", "Start Action")
f.StringVar(&cmd.StopAction, "stop-action", "systemDefault", "Stop Action")
f.StringVar(&cmd.WaitForHeartbeat, "wait", waitHeartbeatTypes[0],
fmt.Sprintf("Wait for Hearbeat Setting (%s)", strings.Join(waitHeartbeatTypes, "|")))
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.AutostartFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *add) Usage() string {
return "VM..."
}
func (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {
powerInfo := types.AutoStartPowerInfo{
StartOrder: cmd.StartOrder,
StartDelay: cmd.StartDelay,
WaitForHeartbeat: types.AutoStartWaitHeartbeatSetting(cmd.WaitForHeartbeat),
StartAction: cmd.StartAction,
StopDelay: cmd.StopDelay,
StopAction: cmd.StopAction,
}
return cmd.ReconfigureVMs(f.Args(), powerInfo)
}

View File

@@ -0,0 +1,177 @@
/*
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 autostart
import (
"context"
"errors"
"flag"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type AutostartFlag struct {
*flags.ClientFlag
*flags.DatacenterFlag
*flags.HostSystemFlag
}
func newAutostartFlag(ctx context.Context) (*AutostartFlag, context.Context) {
f := &AutostartFlag{}
f.ClientFlag, ctx = flags.NewClientFlag(ctx)
f.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
f.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
return f, ctx
}
func (f *AutostartFlag) Register(ctx context.Context, fs *flag.FlagSet) {
f.ClientFlag.Register(ctx, fs)
f.DatacenterFlag.Register(ctx, fs)
f.HostSystemFlag.Register(ctx, fs)
}
func (f *AutostartFlag) Process(ctx context.Context) error {
if err := f.ClientFlag.Process(ctx); err != nil {
return err
}
if err := f.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := f.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
// VirtualMachines returns list of virtual machine objects based on the
// arguments specified on the command line. This helper is defined in
// flags.SearchFlag as well, but that pulls in other virtual machine flags that
// are not relevant here.
func (f *AutostartFlag) VirtualMachines(args []string) ([]*object.VirtualMachine, error) {
ctx := context.TODO()
if len(args) == 0 {
return nil, errors.New("no argument")
}
finder, err := f.Finder()
if err != nil {
return nil, err
}
var out []*object.VirtualMachine
for _, arg := range args {
vms, err := finder.VirtualMachineList(ctx, arg)
if err != nil {
return nil, err
}
out = append(out, vms...)
}
return out, nil
}
func (f *AutostartFlag) HostAutoStartManager() (*mo.HostAutoStartManager, error) {
ctx := context.TODO()
h, err := f.HostSystem()
if err != nil {
return nil, err
}
var mhs mo.HostSystem
err = h.Properties(ctx, h.Reference(), []string{"configManager.autoStartManager"}, &mhs)
if err != nil {
return nil, err
}
var mhas mo.HostAutoStartManager
err = h.Properties(ctx, *mhs.ConfigManager.AutoStartManager, nil, &mhas)
if err != nil {
return nil, err
}
return &mhas, nil
}
func (f *AutostartFlag) ReconfigureDefaults(template types.AutoStartDefaults) error {
ctx := context.TODO()
c, err := f.Client()
if err != nil {
return err
}
mhas, err := f.HostAutoStartManager()
if err != nil {
return err
}
req := types.ReconfigureAutostart{
This: mhas.Reference(),
Spec: types.HostAutoStartManagerConfig{
Defaults: &template,
},
}
_, err = methods.ReconfigureAutostart(ctx, c, &req)
if err != nil {
return err
}
return nil
}
func (f *AutostartFlag) ReconfigureVMs(args []string, template types.AutoStartPowerInfo) error {
ctx := context.TODO()
c, err := f.Client()
if err != nil {
return err
}
mhas, err := f.HostAutoStartManager()
if err != nil {
return err
}
req := types.ReconfigureAutostart{
This: mhas.Reference(),
Spec: types.HostAutoStartManagerConfig{
PowerInfo: make([]types.AutoStartPowerInfo, 0),
},
}
vms, err := f.VirtualMachines(args)
if err != nil {
return err
}
for _, vm := range vms {
pi := template
pi.Key = vm.Reference()
req.Spec.PowerInfo = append(req.Spec.PowerInfo, pi)
}
_, err = methods.ReconfigureAutostart(ctx, c, &req)
if err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,62 @@
/*
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 autostart
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type configure struct {
*AutostartFlag
types.AutoStartDefaults
}
func init() {
cli.Register("host.autostart.configure", &configure{})
}
func (cmd *configure) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AutostartFlag, ctx = newAutostartFlag(ctx)
cmd.AutostartFlag.Register(ctx, f)
f.Var(flags.NewOptionalBool(&cmd.Enabled), "enabled", "")
f.Var(flags.NewInt32(&cmd.StartDelay), "start-delay", "")
f.StringVar(&cmd.StopAction, "stop-action", "", "")
f.Var(flags.NewInt32(&cmd.StopDelay), "stop-delay", "")
f.Var(flags.NewOptionalBool(&cmd.WaitForHeartbeat), "wait-for-heartbeat", "")
}
func (cmd *configure) Process(ctx context.Context) error {
if err := cmd.AutostartFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *configure) Usage() string {
return ""
}
func (cmd *configure) Run(ctx context.Context, f *flag.FlagSet) error {
return cmd.ReconfigureDefaults(cmd.AutoStartDefaults)
}

View File

@@ -0,0 +1,144 @@
/*
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 autostart
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
)
type info struct {
cli.Command
*AutostartFlag
*flags.OutputFlag
}
func init() {
cli.Register("host.autostart.info", &info{})
}
func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AutostartFlag, ctx = newAutostartFlag(ctx)
cmd.AutostartFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
}
func (cmd *info) Process(ctx context.Context) error {
if err := cmd.AutostartFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Usage() string {
return ""
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
client, err := cmd.Client()
if err != nil {
return err
}
mhas, err := cmd.HostAutoStartManager()
if err != nil {
return err
}
return cmd.WriteResult(&infoResult{client, mhas})
}
type infoResult struct {
client *vim25.Client
mhas *mo.HostAutoStartManager
}
func (r *infoResult) MarshalJSON() ([]byte, error) {
return json.Marshal(r.mhas)
}
// vmPaths resolves the paths for the VMs in the result.
func (r *infoResult) vmPaths() (map[string]string, error) {
ctx := context.TODO()
paths := make(map[string]string)
for _, info := range r.mhas.Config.PowerInfo {
mes, err := mo.Ancestors(ctx, r.client, r.client.ServiceContent.PropertyCollector, info.Key)
if err != nil {
return nil, err
}
path := ""
for _, me := range mes {
// Skip root entity in building inventory path.
if me.Parent == nil {
continue
}
path += "/" + me.Name
}
paths[info.Key.Value] = path
}
return paths, nil
}
func (r *infoResult) Write(w io.Writer) error {
paths, err := r.vmPaths()
if err != nil {
return err
}
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "VM")
fmt.Fprintf(tw, "\tStartAction")
fmt.Fprintf(tw, "\tStartDelay")
fmt.Fprintf(tw, "\tStartOrder")
fmt.Fprintf(tw, "\tStopAction")
fmt.Fprintf(tw, "\tStopDelay")
fmt.Fprintf(tw, "\tWaitForHeartbeat")
fmt.Fprintf(tw, "\n")
for _, info := range r.mhas.Config.PowerInfo {
fmt.Fprintf(tw, "%s", paths[info.Key.Value])
fmt.Fprintf(tw, "\t%s", info.StartAction)
fmt.Fprintf(tw, "\t%d", info.StartDelay)
fmt.Fprintf(tw, "\t%d", info.StartOrder)
fmt.Fprintf(tw, "\t%s", info.StopAction)
fmt.Fprintf(tw, "\t%d", info.StopDelay)
fmt.Fprintf(tw, "\t%s", info.WaitForHeartbeat)
fmt.Fprintf(tw, "\n")
}
_ = tw.Flush()
return nil
}

View File

@@ -0,0 +1,62 @@
/*
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 autostart
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/vim25/types"
)
type remove struct {
*AutostartFlag
}
func init() {
cli.Register("host.autostart.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.AutostartFlag, ctx = newAutostartFlag(ctx)
cmd.AutostartFlag.Register(ctx, f)
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.AutostartFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Usage() string {
return "VM..."
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
var powerInfo = types.AutoStartPowerInfo{
StartAction: "none",
StartDelay: -1,
StartOrder: -1,
StopAction: "none",
StopDelay: -1,
WaitForHeartbeat: types.AutoStartWaitHeartbeatSettingSystemDefault,
}
return cmd.ReconfigureVMs(f.Args(), powerInfo)
}

74
vendor/github.com/vmware/govmomi/govc/host/cert/csr.go generated vendored Normal file
View File

@@ -0,0 +1,74 @@
/*
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 cert
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type csr struct {
*flags.HostSystemFlag
ip bool
}
func init() {
cli.Register("host.cert.csr", &csr{})
}
func (cmd *csr) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.BoolVar(&cmd.ip, "ip", false, "Use IP address as CN")
}
func (cmd *csr) Description() string {
return `Generate a certificate-signing request (CSR) for HOST.`
}
func (cmd *csr) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *csr) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
m, err := host.ConfigManager().CertificateManager(ctx)
if err != nil {
return err
}
output, err := m.GenerateCertificateSigningRequest(ctx, cmd.ip)
if err != nil {
return err
}
_, err = fmt.Println(output)
return err
}

View File

@@ -0,0 +1,75 @@
/*
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 cert
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type info struct {
*flags.HostSystemFlag
*flags.OutputFlag
}
func init() {
cli.Register("host.cert.info", &info{})
}
func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
}
func (cmd *info) Description() string {
return `Display SSL certificate info for HOST.`
}
func (cmd *info) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
m, err := host.ConfigManager().CertificateManager(ctx)
if err != nil {
return err
}
info, err := m.CertificateInfo(ctx)
if err != nil {
return err
}
return cmd.WriteResult(info)
}

View File

@@ -0,0 +1,90 @@
/*
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 cert
import (
"bytes"
"context"
"flag"
"io"
"io/ioutil"
"os"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type install struct {
*flags.HostSystemFlag
}
func init() {
cli.Register("host.cert.import", &install{})
}
func (cmd *install) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *install) Usage() string {
return "FILE"
}
func (cmd *install) Description() string {
return `Install SSL certificate FILE on HOST.
If FILE name is "-", read certificate from stdin.`
}
func (cmd *install) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *install) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
m, err := host.ConfigManager().CertificateManager(ctx)
if err != nil {
return err
}
var cert string
name := f.Arg(0)
if name == "-" || name == "" {
var buf bytes.Buffer
if _, err := io.Copy(&buf, os.Stdin); err != nil {
return err
}
cert = buf.String()
} else {
b, err := ioutil.ReadFile(name)
if err != nil {
return err
}
cert = string(b)
}
return m.InstallServerCertificate(ctx, cert)
}

View File

@@ -0,0 +1,103 @@
/*
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 date
import (
"context"
"flag"
"strings"
"time"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type change struct {
*flags.HostSystemFlag
types.HostNtpConfig
types.HostDateTimeConfig
date string
}
func init() {
cli.Register("host.date.change", &change{})
}
type serverConfig types.HostNtpConfig
func (s *serverConfig) String() string {
return strings.Join(s.Server, ",")
}
func (s *serverConfig) Set(v string) error {
s.Server = append(s.Server, v)
return nil
}
func (cmd *change) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.Var((*serverConfig)(&cmd.HostNtpConfig), "server", "IP or FQDN for NTP server(s)")
f.StringVar(&cmd.TimeZone, "tz", "", "Change timezone of the host")
f.StringVar(&cmd.date, "date", "", "Update the date/time on the host")
}
func (cmd *change) Description() string {
return `Change date and time for HOST.
Examples:
govc host.date.change -date "$(date -u)"
govc host.date.change -server time.vmware.com
govc host.service enable ntpd
govc host.service start ntpd`
}
func (cmd *change) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *change) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
s, err := host.ConfigManager().DateTimeSystem(ctx)
if err != nil {
return err
}
if cmd.date != "" {
d, err := time.Parse(time.UnixDate, cmd.date)
if err != nil {
return err
}
return s.Update(ctx, d)
}
if len(cmd.HostNtpConfig.Server) > 0 {
cmd.NtpConfig = &cmd.HostNtpConfig
}
return s.UpdateConfig(ctx, cmd.HostDateTimeConfig)
}

133
vendor/github.com/vmware/govmomi/govc/host/date/info.go generated vendored Normal file
View File

@@ -0,0 +1,133 @@
/*
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 date
import (
"context"
"flag"
"fmt"
"io"
"strings"
"text/tabwriter"
"time"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/govc/host/service"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type info struct {
*flags.HostSystemFlag
*flags.OutputFlag
}
func init() {
cli.Register("host.date.info", &info{})
}
func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
}
func (cmd *info) Description() string {
return `Display date and time info for HOST.`
}
func (cmd *info) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
return nil
}
type dateInfo struct {
types.HostDateTimeInfo
Service *types.HostService
Current *time.Time
}
func (info *dateInfo) servers() string {
if len(info.NtpConfig.Server) == 0 {
return "None"
}
return strings.Join(info.NtpConfig.Server, ", ")
}
func (info *dateInfo) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Current date and time:\t%s\n", info.Current.Format(time.UnixDate))
if info.Service != nil {
fmt.Fprintf(tw, "NTP client status:\t%s\n", service.Policy(*info.Service))
fmt.Fprintf(tw, "NTP service status:\t%s\n", service.Status(*info.Service))
}
fmt.Fprintf(tw, "NTP servers:\t%s\n", info.servers())
return tw.Flush()
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
s, err := host.ConfigManager().DateTimeSystem(ctx)
if err != nil {
return err
}
var hs mo.HostDateTimeSystem
if err = s.Properties(ctx, s.Reference(), nil, &hs); err != nil {
return nil
}
ss, err := host.ConfigManager().ServiceSystem(ctx)
if err != nil {
return err
}
services, err := ss.Service(ctx)
if err != nil {
return err
}
res := &dateInfo{HostDateTimeInfo: hs.DateTimeInfo}
for i, service := range services {
if service.Key == "ntpd" {
res.Service = &services[i]
break
}
}
res.Current, err = s.Query(ctx)
if err != nil {
return err
}
return cmd.WriteResult(res)
}

View File

@@ -0,0 +1,80 @@
/*
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 host
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
)
type disconnect struct {
*flags.HostSystemFlag
}
func init() {
cli.Register("host.disconnect", &disconnect{})
}
func (cmd *disconnect) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *disconnect) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *disconnect) Description() string {
return `Disconnect HOST from vCenter.`
}
func (cmd *disconnect) Disconnect(ctx context.Context, host *object.HostSystem) error {
task, err := host.Disconnect(ctx)
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("%s disconnecting... ", host.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *disconnect) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
err = cmd.Disconnect(ctx, host)
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,149 @@
/*
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.
*/
package esxcli
import (
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
type Command struct {
name []string
args []string
}
type CommandInfoItem struct {
Name string `xml:"name"`
DisplayName string `xml:"displayName"`
Help string `xml:"help"`
}
type CommandInfoParam struct {
CommandInfoItem
Aliases []string `xml:"aliases"`
Flag bool `xml:"flag"`
}
type CommandInfoHint struct {
Key string `xml:"key"`
Value string `xml:"value"`
}
type CommandInfoHints []CommandInfoHint
type CommandInfoMethod struct {
CommandInfoItem
Param []CommandInfoParam `xml:"param"`
Hints CommandInfoHints `xml:"hints"`
}
type CommandInfo struct {
CommandInfoItem
Method []*CommandInfoMethod `xml:"method"`
}
func NewCommand(args []string) *Command {
c := &Command{}
for i, arg := range args {
if strings.HasPrefix(arg, "-") {
c.args = args[i:]
break
} else {
c.name = append(c.name, arg)
}
}
return c
}
func (c *Command) Namespace() string {
return strings.Join(c.name[:len(c.name)-1], ".")
}
func (c *Command) Name() string {
return c.name[len(c.name)-1]
}
func (c *Command) Method() string {
return "vim.EsxCLI." + strings.Join(c.name, ".")
}
func (c *Command) Moid() string {
return "ha-cli-handler-" + strings.Join(c.name[:len(c.name)-1], "-")
}
// Parse generates a flag.FlagSet based on the given []CommandInfoParam and
// returns arguments for use with methods.ExecuteSoap
func (c *Command) Parse(params []CommandInfoParam) ([]types.ReflectManagedMethodExecuterSoapArgument, error) {
flags := flag.NewFlagSet(strings.Join(c.name, " "), flag.ExitOnError)
vals := make([]string, len(params))
for i, p := range params {
v := &vals[i]
for _, a := range p.Aliases {
a = strings.TrimPrefix(a[1:], "-")
flags.StringVar(v, a, "", p.Help)
}
}
err := flags.Parse(c.args)
if err != nil {
return nil, err
}
args := []types.ReflectManagedMethodExecuterSoapArgument{}
for i, p := range params {
if vals[i] == "" {
continue
}
args = append(args, c.Argument(p.Name, vals[i]))
}
return args, nil
}
func (c *Command) Argument(name string, val string) types.ReflectManagedMethodExecuterSoapArgument {
return types.ReflectManagedMethodExecuterSoapArgument{
Name: name,
Val: fmt.Sprintf("<%s>%s</%s>", name, val, name),
}
}
func (h CommandInfoHints) Formatter() string {
for _, hint := range h {
if hint.Key == "formatter" {
return hint.Value
}
}
return "simple"
}
func (h CommandInfoHints) Fields() []string {
for _, hint := range h {
if strings.HasPrefix(hint.Key, "fields:") {
return strings.Split(hint.Value, ",")
}
}
return nil
}

View File

@@ -0,0 +1,124 @@
/*
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.
*/
package esxcli
import (
"reflect"
"testing"
"github.com/vmware/govmomi/vim25/types"
)
func TestSystemSettingsAdvancedSetCommand(t *testing.T) {
c := NewCommand([]string{"system", "settings", "advanced", "set", "-o", "/Net/GuestIPHack", "-i", "1"})
tests := []struct {
f func() string
expect string
}{
{c.Name, "set"},
{c.Namespace, "system.settings.advanced"},
{c.Method, "vim.EsxCLI.system.settings.advanced.set"},
{c.Moid, "ha-cli-handler-system-settings-advanced"},
}
for _, test := range tests {
actual := test.f()
if actual != test.expect {
t.Errorf("%s != %s", actual, test.expect)
}
}
params := []CommandInfoParam{
{
CommandInfoItem: CommandInfoItem{Name: "default", DisplayName: "default", Help: "Reset the option to its default value."},
Aliases: []string{"-d", "--default"},
Flag: true,
},
{
CommandInfoItem: CommandInfoItem{Name: "intvalue", DisplayName: "int-value", Help: "If the option is an integer value use this option."},
Aliases: []string{"-i", "--int-value"},
Flag: false,
},
{
CommandInfoItem: CommandInfoItem{Name: "option", DisplayName: "option", Help: "The name of the option to set the value of. Example: \"/Misc/HostName\""},
Aliases: []string{"-o", "--option"},
Flag: false,
},
{
CommandInfoItem: CommandInfoItem{Name: "stringvalue", DisplayName: "string-value", Help: "If the option is a string use this option."},
Aliases: []string{"-s", "--string-value"},
Flag: false,
},
}
args, err := c.Parse(params)
if err != nil {
t.Fatal(err)
}
expect := []types.ReflectManagedMethodExecuterSoapArgument{
{
DynamicData: types.DynamicData{},
Name: "intvalue",
Val: "<intvalue>1</intvalue>",
},
{
DynamicData: types.DynamicData{},
Name: "option",
Val: "<option>/Net/GuestIPHack</option>",
},
}
if !reflect.DeepEqual(args, expect) {
t.Errorf("%s != %s", args, expect)
}
}
func TestNetworkVmListCommand(t *testing.T) {
c := NewCommand([]string{"network", "vm", "list"})
tests := []struct {
f func() string
expect string
}{
{c.Name, "list"},
{c.Namespace, "network.vm"},
{c.Method, "vim.EsxCLI.network.vm.list"},
{c.Moid, "ha-cli-handler-network-vm"},
}
for _, test := range tests {
actual := test.f()
if actual != test.expect {
t.Errorf("%s != %s", actual, test.expect)
}
}
var params []CommandInfoParam
args, err := c.Parse(params)
if err != nil {
t.Fatal(err)
}
expect := []types.ReflectManagedMethodExecuterSoapArgument{}
if !reflect.DeepEqual(args, expect) {
t.Errorf("%s != %s", args, expect)
}
}

View File

@@ -0,0 +1,172 @@
/*
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 esxcli
import (
"context"
"flag"
"fmt"
"io"
"sort"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type esxcli struct {
*flags.HostSystemFlag
hints bool
}
func init() {
cli.Register("host.esxcli", &esxcli{})
}
func (cmd *esxcli) Usage() string {
return "COMMAND [ARG]..."
}
func (cmd *esxcli) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.BoolVar(&cmd.hints, "hints", true, "Use command info hints when formatting output")
}
func (cmd *esxcli) Description() string {
return `Invoke esxcli command on HOST.
Output is rendered in table form when possible, unless disabled with '-hints=false'.
Examples:
govc host.esxcli network ip connection list
govc host.esxcli system settings advanced set -o /Net/GuestIPHack -i 1
govc host.esxcli network firewall ruleset set -r remoteSerialPort -e true
govc host.esxcli network firewall set -e false`
}
func (cmd *esxcli) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *esxcli) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return nil
}
host, err := cmd.HostSystem()
if err != nil {
return err
}
e, err := NewExecutor(c, host)
if err != nil {
return err
}
res, err := e.Run(f.Args())
if err != nil {
return err
}
if len(res.Values) == 0 {
return nil
}
return cmd.WriteResult(&result{res, cmd})
}
type result struct {
*Response
cmd *esxcli
}
func (r *result) Write(w io.Writer) error {
var formatType string
if r.cmd.hints {
formatType = r.Info.Hints.Formatter()
}
switch formatType {
case "table":
r.cmd.formatTable(w, r.Response)
default:
r.cmd.formatSimple(w, r.Response)
}
return nil
}
func (cmd *esxcli) formatSimple(w io.Writer, res *Response) {
var keys []string
for key := range res.Values[0] {
keys = append(keys, key)
}
sort.Strings(keys)
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
for i, rv := range res.Values {
if i > 0 {
fmt.Fprintln(tw)
_ = tw.Flush()
}
for _, key := range keys {
fmt.Fprintf(tw, "%s:\t%s\n", key, strings.Join(rv[key], ", "))
}
}
_ = tw.Flush()
}
func (cmd *esxcli) formatTable(w io.Writer, res *Response) {
fields := res.Info.Hints.Fields()
tw := tabwriter.NewWriter(w, len(fields), 0, 2, ' ', 0)
var hr []string
for _, name := range fields {
hr = append(hr, strings.Repeat("-", len(name)))
}
fmt.Fprintln(tw, strings.Join(fields, "\t"))
fmt.Fprintln(tw, strings.Join(hr, "\t"))
for _, vals := range res.Values {
var row []string
for _, name := range fields {
key := strings.Replace(name, " ", "", -1)
if val, ok := vals[key]; ok {
row = append(row, strings.Join(val, ", "))
} else {
row = append(row, "")
}
}
fmt.Fprintln(tw, strings.Join(row, "\t"))
}
_ = tw.Flush()
}

View File

@@ -0,0 +1,168 @@
/*
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 esxcli
import (
"context"
"errors"
"fmt"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"github.com/vmware/govmomi/vim25/xml"
)
type Executor struct {
c *vim25.Client
host *object.HostSystem
mme *types.ReflectManagedMethodExecuter
dtm *types.InternalDynamicTypeManager
info map[string]*CommandInfo
}
func NewExecutor(c *vim25.Client, host *object.HostSystem) (*Executor, error) {
ctx := context.TODO()
e := &Executor{
c: c,
host: host,
info: make(map[string]*CommandInfo),
}
{
req := types.RetrieveManagedMethodExecuter{
This: host.Reference(),
}
res, err := methods.RetrieveManagedMethodExecuter(ctx, c, &req)
if err != nil {
return nil, err
}
e.mme = res.Returnval
}
{
req := types.RetrieveDynamicTypeManager{
This: host.Reference(),
}
res, err := methods.RetrieveDynamicTypeManager(ctx, c, &req)
if err != nil {
return nil, err
}
e.dtm = res.Returnval
}
return e, nil
}
func (e *Executor) CommandInfo(c *Command) (*CommandInfoMethod, error) {
ns := c.Namespace()
var info *CommandInfo
var ok bool
if info, ok = e.info[ns]; !ok {
req := types.ExecuteSoap{
Moid: "ha-dynamic-type-manager-local-cli-cliinfo",
Method: "vim.CLIInfo.FetchCLIInfo",
Argument: []types.ReflectManagedMethodExecuterSoapArgument{
c.Argument("typeName", "vim.EsxCLI."+ns),
},
}
info = new(CommandInfo)
if err := e.Execute(&req, info); err != nil {
return nil, err
}
e.info[ns] = info
}
name := c.Name()
for _, method := range info.Method {
if method.Name == name {
return method, nil
}
}
return nil, fmt.Errorf("method '%s' not found in name space '%s'", name, c.Namespace())
}
func (e *Executor) NewRequest(args []string) (*types.ExecuteSoap, *CommandInfoMethod, error) {
c := NewCommand(args)
info, err := e.CommandInfo(c)
if err != nil {
return nil, nil, err
}
sargs, err := c.Parse(info.Param)
if err != nil {
return nil, nil, err
}
sreq := types.ExecuteSoap{
Moid: c.Moid(),
Method: c.Method(),
Argument: sargs,
}
return &sreq, info, nil
}
func (e *Executor) Execute(req *types.ExecuteSoap, res interface{}) error {
ctx := context.TODO()
req.This = e.mme.ManagedObjectReference
req.Version = "urn:vim25/5.0"
x, err := methods.ExecuteSoap(ctx, e.c, req)
if err != nil {
return err
}
if x.Returnval != nil {
if x.Returnval.Fault != nil {
return errors.New(x.Returnval.Fault.FaultMsg)
}
if err := xml.Unmarshal([]byte(x.Returnval.Response), res); err != nil {
return err
}
}
return nil
}
func (e *Executor) Run(args []string) (*Response, error) {
req, info, err := e.NewRequest(args)
if err != nil {
return nil, err
}
res := &Response{
Info: info,
}
if err := e.Execute(req, res); err != nil {
return nil, err
}
return res, nil
}

View File

@@ -0,0 +1,48 @@
/*
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 esxcli
import "github.com/vmware/govmomi/object"
type FirewallInfo struct {
Loaded bool
Enabled bool
DefaultAction string
}
// GetFirewallInfo via 'esxcli network firewall get'
// The HostFirewallSystem type does not expose this data.
// This helper can be useful in particular to determine if the firewall is enabled or disabled.
func GetFirewallInfo(s *object.HostSystem) (*FirewallInfo, error) {
x, err := NewExecutor(s.Client(), s)
if err != nil {
return nil, err
}
res, err := x.Run([]string{"network", "firewall", "get"})
if err != nil {
return nil, err
}
info := &FirewallInfo{
Loaded: res.Values[0]["Loaded"][0] == "true",
Enabled: res.Values[0]["Enabled"][0] == "true",
DefaultAction: res.Values[0]["DefaultAction"][0],
}
return info, nil
}

View File

@@ -0,0 +1,15 @@
<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="5.0" xsi:type="ArrayOfDataObject">
<DataObject xsi:type="VimEsxCLInetworkvmlistVM">
<Name>foo</Name>
<Networks>VM Network</Networks>
<Networks>dougm</Networks>
<NumPorts>2</NumPorts>
<WorldID>98842</WorldID>
</DataObject>
<DataObject xsi:type="VimEsxCLInetworkvmlistVM">
<Name>bar</Name>
<Networks>VM Network</Networks>
<NumPorts>1</NumPorts>
<WorldID>236235</WorldID>
</DataObject>
</obj>

View File

@@ -0,0 +1,12 @@
<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="5.0" xsi:type="ArrayOfDataObject">
<DataObject xsi:type="VimEsxCLInetworkvmportlistPort">
<DVPortID></DVPortID>
<IPAddress>192.168.247.149</IPAddress>
<MACAddress>00:0c:29:12:b2:cf</MACAddress>
<PortID>33554438</PortID>
<Portgroup>VM Network</Portgroup>
<TeamUplink>vmnic0</TeamUplink>
<UplinkPortID>33554434</UplinkPortID>
<vSwitch>vSwitch0</vSwitch>
</DataObject>
</obj>

View File

@@ -0,0 +1,5 @@
<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="5.0" xsi:type="VimEsxCLIsystemhostnamegetFullyQualifiedHostName">
<DomainName>localdomain</DomainName>
<FullyQualifiedDomainName>esxbox.localdomain</FullyQualifiedDomainName>
<HostName>esxbox</HostName>
</obj>

View File

@@ -0,0 +1,120 @@
/*
Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package esxcli
import (
"context"
"strings"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type hostInfo struct {
*Executor
wids map[string]string
}
type GuestInfo struct {
c *vim25.Client
hosts map[string]*hostInfo
}
func NewGuestInfo(c *vim25.Client) *GuestInfo {
return &GuestInfo{
c: c,
hosts: make(map[string]*hostInfo),
}
}
func (g *GuestInfo) hostInfo(ref *types.ManagedObjectReference) (*hostInfo, error) {
// cache exectuor and uuid -> worldid map
if h, ok := g.hosts[ref.Value]; ok {
return h, nil
}
host := object.NewHostSystem(g.c, *ref)
e, err := NewExecutor(g.c, host)
if err != nil {
return nil, err
}
res, err := e.Run([]string{"vm", "process", "list"})
if err != nil {
return nil, err
}
ids := make(map[string]string, len(res.Values))
for _, process := range res.Values {
// Normalize uuid, esxcli and mo.VirtualMachine have different formats
uuid := strings.Replace(process["UUID"][0], " ", "", -1)
uuid = strings.Replace(uuid, "-", "", -1)
ids[uuid] = process["WorldID"][0]
}
h := &hostInfo{e, ids}
g.hosts[ref.Value] = h
return h, nil
}
// IpAddress attempts to find the guest IP address using esxcli.
// ESX hosts must be configured with the /Net/GuestIPHack enabled.
// For example:
// $ govc host.esxcli -- system settings advanced set -o /Net/GuestIPHack -i 1
func (g *GuestInfo) IpAddress(vm *object.VirtualMachine) (string, error) {
ctx := context.TODO()
const any = "0.0.0.0"
var mvm mo.VirtualMachine
pc := property.DefaultCollector(g.c)
err := pc.RetrieveOne(ctx, vm.Reference(), []string{"runtime.host", "config.uuid"}, &mvm)
if err != nil {
return "", err
}
h, err := g.hostInfo(mvm.Runtime.Host)
if err != nil {
return "", err
}
// Normalize uuid, esxcli and mo.VirtualMachine have different formats
uuid := strings.Replace(mvm.Config.Uuid, "-", "", -1)
if wid, ok := h.wids[uuid]; ok {
res, err := h.Run([]string{"network", "vm", "port", "list", "--world-id", wid})
if err != nil {
return "", err
}
for _, val := range res.Values {
if ip, ok := val["IPAddress"]; ok {
if ip[0] != any {
return ip[0], nil
}
}
}
}
return any, nil
}

View File

@@ -0,0 +1,97 @@
/*
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 esxcli
import (
"io"
"github.com/vmware/govmomi/vim25/xml"
)
type Values map[string][]string
type Response struct {
Info *CommandInfoMethod
Values []Values
}
func (v Values) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
for {
t, err := d.Token()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if s, ok := t.(xml.StartElement); ok {
t, err = d.Token()
if err != nil {
return err
}
key := s.Name.Local
var val string
if c, ok := t.(xml.CharData); ok {
val = string(c)
}
v[key] = append(v[key], val)
}
}
}
func (r *Response) Type(start xml.StartElement) string {
for _, a := range start.Attr {
if a.Name.Local == "type" {
return a.Value
}
}
return ""
}
func (r *Response) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
stype := r.Type(start)
if stype != "ArrayOfDataObject" {
v := Values{}
if err := d.DecodeElement(&v, &start); err != nil {
return err
}
r.Values = append(r.Values, v)
return nil
}
for {
t, err := d.Token()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if s, ok := t.(xml.StartElement); ok {
if s.Name.Local == "DataObject" {
v := Values{}
if err := d.DecodeElement(&v, &s); err != nil {
return err
}
r.Values = append(r.Values, v)
}
}
}
}

View File

@@ -0,0 +1,105 @@
/*
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.
*/
package esxcli
import (
"os"
"reflect"
"testing"
"github.com/vmware/govmomi/vim25/types"
"github.com/vmware/govmomi/vim25/xml"
)
func load(name string) *Response {
f, err := os.Open(name)
if err != nil {
panic(err)
}
defer f.Close()
var b Response
dec := xml.NewDecoder(f)
dec.TypeFunc = types.TypeFunc()
if err := dec.Decode(&b); err != nil {
panic(err)
}
return &b
}
func TestSystemHostnameGetResponse(t *testing.T) {
res := load("fixtures/system_hostname_get.xml")
expect := []Values{
{
"DomainName": {"localdomain"},
"FullyQualifiedDomainName": {"esxbox.localdomain"},
"HostName": {"esxbox"},
},
}
if !reflect.DeepEqual(res.Values, expect) {
t.Errorf("%s != %s", res.Values, expect)
}
}
func TestNetworkVmList(t *testing.T) {
res := load("fixtures/network_vm_list.xml")
expect := []Values{
{
"Name": {"foo"},
"Networks": {"VM Network", "dougm"},
"NumPorts": {"2"},
"WorldID": {"98842"},
},
{
"Name": {"bar"},
"Networks": {"VM Network"},
"NumPorts": {"1"},
"WorldID": {"236235"},
},
}
if !reflect.DeepEqual(res.Values, expect) {
t.Errorf("%s != %s", res.Values, expect)
}
}
func TestNetworkVmPortList(t *testing.T) {
r := load("fixtures/network_vm_port_list.xml")
expect := []Values{
{
"IPAddress": {"192.168.247.149"},
"MACAddress": {"00:0c:29:12:b2:cf"},
"PortID": {"33554438"},
"Portgroup": {"VM Network"},
"TeamUplink": {"vmnic0"},
"UplinkPortID": {"33554434"},
"vSwitch": {"vSwitch0"},
"DVPortID": {""},
},
}
if !reflect.DeepEqual(r.Values, expect) {
t.Errorf("%s != %s", r.Values, expect)
}
}

View File

@@ -0,0 +1,131 @@
/*
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 firewall
import (
"context"
"flag"
"fmt"
"os"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/govc/host/esxcli"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
type find struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.HostSystemFlag
enabled bool
check bool
types.HostFirewallRule
}
func init() {
cli.Register("firewall.ruleset.find", &find{})
}
func (cmd *find) 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.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.BoolVar(&cmd.check, "c", true, "Check if esx firewall is enabled")
f.BoolVar(&cmd.enabled, "enabled", true, "Find enabled rule sets if true, disabled if false")
f.StringVar((*string)(&cmd.Direction), "direction", string(types.HostFirewallRuleDirectionOutbound), "Direction")
f.StringVar((*string)(&cmd.PortType), "type", string(types.HostFirewallRulePortTypeDst), "Port type")
f.StringVar((*string)(&cmd.Protocol), "proto", string(types.HostFirewallRuleProtocolTcp), "Protocol")
f.Var(flags.NewInt32(&cmd.Port), "port", "Port")
}
func (cmd *find) 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.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *find) Description() string {
return `Find firewall rulesets matching the given rule.
For a complete list of rulesets: govc host.esxcli network firewall ruleset list
For a complete list of rules: govc host.esxcli network firewall ruleset rule list
Examples:
govc firewall.ruleset.find -direction inbound -port 22
govc firewall.ruleset.find -direction outbound -port 2377`
}
func (cmd *find) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
fs, err := host.ConfigManager().FirewallSystem(ctx)
if err != nil {
return err
}
if cmd.check {
esxfw, err := esxcli.GetFirewallInfo(host)
if err != nil {
return err
}
if !esxfw.Enabled {
fmt.Fprintln(os.Stderr, "host firewall is disabled")
}
}
info, err := fs.Info(ctx)
if err != nil {
return err
}
if f.NArg() != 0 {
// TODO: f.Args() -> types.HostFirewallRulesetIpList
return flag.ErrHelp
}
rs := object.HostFirewallRulesetList(info.Ruleset)
matched, err := rs.EnabledByRule(cmd.HostFirewallRule, cmd.enabled)
if err != nil {
return err
}
for _, r := range matched {
fmt.Println(r.Key)
}
return nil
}

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

@@ -0,0 +1,158 @@
/*
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 host
import (
"context"
"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"
)
type info struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.HostSystemFlag
}
func init() {
cli.Register("host.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.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.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.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
c, err := cmd.Client()
if err != nil {
return err
}
var res infoResult
var props []string
if cmd.OutputFlag.JSON {
props = nil // Load everything
} else {
props = []string{"summary"} // Load summary
}
// We could do without the -host flag, leaving it for compat
host, err := cmd.HostSystemIfSpecified()
if err != nil {
return err
}
// Default only if there is a single host
if host == nil && f.NArg() == 0 {
host, err = cmd.HostSystem()
if err != nil {
return err
}
}
if host != nil {
res.objects = append(res.objects, host)
} else {
res.objects, err = cmd.HostSystems(f.Args())
if err != nil {
return err
}
}
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.HostSystems)
if err != nil {
return err
}
}
return cmd.WriteResult(&res)
}
type infoResult struct {
HostSystems []mo.HostSystem
objects []*object.HostSystem
}
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.HostSystem, len(r.HostSystems))
for _, o := range r.HostSystems {
objects[o.Reference()] = o
}
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
for _, o := range r.objects {
host := objects[o.Reference()]
s := host.Summary
h := s.Hardware
z := s.QuickStats
ncpu := int32(h.NumCpuPkgs * h.NumCpuCores)
cpuUsage := 100 * float64(z.OverallCpuUsage) / float64(ncpu*h.CpuMhz)
memUsage := 100 * float64(z.OverallMemoryUsage<<20) / float64(h.MemorySize)
fmt.Fprintf(tw, "Name:\t%s\n", s.Config.Name)
fmt.Fprintf(tw, " Path:\t%s\n", o.InventoryPath)
fmt.Fprintf(tw, " Manufacturer:\t%s\n", h.Vendor)
fmt.Fprintf(tw, " Logical CPUs:\t%d CPUs @ %dMHz\n", ncpu, h.CpuMhz)
fmt.Fprintf(tw, " Processor type:\t%s\n", h.CpuModel)
fmt.Fprintf(tw, " CPU usage:\t%d MHz (%.1f%%)\n", z.OverallCpuUsage, cpuUsage)
fmt.Fprintf(tw, " Memory:\t%dMB\n", h.MemorySize/(1024*1024))
fmt.Fprintf(tw, " Memory usage:\t%d MB (%.1f%%)\n", z.OverallMemoryUsage, memUsage)
fmt.Fprintf(tw, " Boot time:\t%s\n", s.Runtime.BootTime)
}
return tw.Flush()
}

View File

@@ -0,0 +1,93 @@
/*
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 maintenance
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
)
type enter struct {
*flags.HostSystemFlag
timeout int32
evacuate bool
}
func init() {
cli.Register("host.maintenance.enter", &enter{})
}
func (cmd *enter) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.Var(flags.NewInt32(&cmd.timeout), "timeout", "Timeout")
f.BoolVar(&cmd.evacuate, "evacuate", false, "Evacuate powered off VMs")
}
func (cmd *enter) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *enter) Usage() string {
return "HOST..."
}
func (cmd *enter) Description() string {
return `Put HOST in maintenance mode.
While this task is running and when the host is in maintenance mode,
no VMs can be powered on and no provisioning operations can be performed on the host.`
}
func (cmd *enter) EnterMaintenanceMode(ctx context.Context, host *object.HostSystem) error {
task, err := host.EnterMaintenanceMode(ctx, cmd.timeout, cmd.evacuate, nil) // TODO: spec param
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("%s entering maintenance mode... ", host.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *enter) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
err = cmd.EnterMaintenanceMode(ctx, host)
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,94 @@
/*
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 maintenance
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
)
type exit struct {
*flags.HostSystemFlag
timeout int32
}
func init() {
cli.Register("host.maintenance.exit", &exit{})
}
func (cmd *exit) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.Var(flags.NewInt32(&cmd.timeout), "timeout", "Timeout")
}
func (cmd *exit) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *exit) Usage() string {
return "HOST..."
}
func (cmd *exit) Description() string {
return `Take HOST out of maintenance mode.
This blocks if any concurrent running maintenance-only host configurations operations are being performed.
For example, if VMFS volumes are being upgraded.
The 'timeout' flag is the number of seconds to wait for the exit maintenance mode to succeed.
If the timeout is less than or equal to zero, there is no timeout.`
}
func (cmd *exit) ExitMaintenanceMode(ctx context.Context, host *object.HostSystem) error {
task, err := host.ExitMaintenanceMode(ctx, cmd.timeout)
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("%s exiting maintenance mode... ", host.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *exit) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
err = cmd.ExitMaintenanceMode(ctx, host)
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,80 @@
/*
Copyright (c) 2016-2017 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package option
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/govc/option"
)
type ls struct {
*option.List
*flags.HostSystemFlag
}
func init() {
cli.Register("host.option.ls", &ls{})
}
func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {
cmd.List = &option.List{}
cmd.List.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.List.ClientFlag.Register(ctx, f)
cmd.List.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.List.OutputFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *ls) Process(ctx context.Context) error {
if err := cmd.List.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *ls) Description() string {
return option.ListDescription + `
Examples:
govc host.option.ls
govc host.option.ls Config.HostAgent.
govc host.option.ls Config.HostAgent.plugins.solo.enableMob`
}
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
m, err := host.ConfigManager().OptionManager(ctx)
if err != nil {
return err
}
return cmd.Query(ctx, f, m)
}

View File

@@ -0,0 +1,76 @@
/*
Copyright (c) 2016-2017 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package option
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/govc/option"
)
type set struct {
*option.Set
*flags.HostSystemFlag
}
func init() {
cli.Register("host.option.set", &set{})
}
func (cmd *set) Register(ctx context.Context, f *flag.FlagSet) {
cmd.Set = &option.Set{}
cmd.Set.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.Set.ClientFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *set) Process(ctx context.Context) error {
if err := cmd.Set.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *set) Description() string {
return option.SetDescription + `
Examples:
govc host.option.set Config.HostAgent.plugins.solo.enableMob true
govc host.option.set Config.HostAgent.log.level verbose`
}
func (cmd *set) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
m, err := host.ConfigManager().OptionManager(ctx)
if err != nil {
return err
}
return cmd.Update(ctx, f, m)
}

View File

@@ -0,0 +1,73 @@
/*
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 portgroup
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type add struct {
*flags.HostSystemFlag
spec types.HostPortGroupSpec
}
func init() {
cli.Register("host.portgroup.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.StringVar(&cmd.spec.VswitchName, "vswitch", "", "vSwitch Name")
f.Var(flags.NewInt32(&cmd.spec.VlanId), "vlan", "VLAN ID")
}
func (cmd *add) Description() string {
return `Add portgroup to HOST.
Examples:
govc host.portgroup.add -vswitch vSwitch0 -vlan 3201 bridge`
}
func (cmd *add) Usage() string {
return "NAME"
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
cmd.spec.Name = f.Arg(0)
return ns.AddPortGroup(ctx, cmd.spec)
}

View File

@@ -0,0 +1,118 @@
/*
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 portgroup
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type change struct {
*flags.ClientFlag
*flags.HostSystemFlag
types.HostPortGroupSpec
types.HostNetworkSecurityPolicy
}
func init() {
cli.Register("host.portgroup.change", &change{})
}
func (cmd *change) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.VlanId = -1
f.Var(flags.NewInt32(&cmd.VlanId), "vlan-id", "VLAN ID")
f.StringVar(&cmd.Name, "name", "", "Portgroup name")
f.StringVar(&cmd.VswitchName, "vswitch-name", "", "vSwitch name")
f.Var(flags.NewOptionalBool(&cmd.AllowPromiscuous), "allow-promiscuous", "Allow promiscuous mode")
f.Var(flags.NewOptionalBool(&cmd.ForgedTransmits), "forged-transmits", "Allow forged transmits")
f.Var(flags.NewOptionalBool(&cmd.MacChanges), "mac-changes", "Allow MAC changes")
}
func (cmd *change) Description() string {
return `Change configuration of HOST portgroup NAME.
Examples:
govc host.portgroup.change -allow-promiscuous -forged-transmits -mac-changes "VM Network"
govc host.portgroup.change -vswitch-name vSwitch1 "Management Network"`
}
func (cmd *change) Usage() string {
return "NAME"
}
func (cmd *change) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *change) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return flag.ErrHelp
}
pg, err := networkInfoPortgroup(ctx, cmd.ClientFlag, cmd.HostSystemFlag)
if err != nil {
return err
}
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
name := f.Arg(0)
var current *types.HostPortGroupSpec
for _, g := range pg {
if g.Spec.Name == name {
current = &g.Spec
break
}
}
if current != nil {
if cmd.Name == "" {
cmd.Name = current.Name
}
if cmd.VswitchName == "" {
cmd.VswitchName = current.VswitchName
}
if cmd.VlanId < 0 {
cmd.VlanId = current.VlanId
}
}
cmd.HostPortGroupSpec.Policy.Security = &cmd.HostNetworkSecurityPolicy
return ns.UpdatePortGroup(ctx, name, cmd.HostPortGroupSpec)
}

View File

@@ -0,0 +1,118 @@
/*
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 portgroup
import (
"context"
"flag"
"fmt"
"io"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/govc/host/vswitch"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type info struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.HostSystemFlag
}
func init() {
cli.Register("host.portgroup.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.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.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.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func networkInfoPortgroup(ctx context.Context, c *flags.ClientFlag, h *flags.HostSystemFlag) ([]types.HostPortGroup, error) {
client, err := c.Client()
if err != nil {
return nil, err
}
ns, err := h.HostNetworkSystem()
if err != nil {
return nil, err
}
var mns mo.HostNetworkSystem
pc := property.DefaultCollector(client)
err = pc.RetrieveOne(ctx, ns.Reference(), []string{"networkInfo.portgroup"}, &mns)
if err != nil {
return nil, err
}
return mns.NetworkInfo.Portgroup, nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
pg, err := networkInfoPortgroup(ctx, cmd.ClientFlag, cmd.HostSystemFlag)
if err != nil {
return err
}
r := &infoResult{pg}
return cmd.WriteResult(r)
}
type infoResult struct {
Portgroup []types.HostPortGroup
}
func (r *infoResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
for i, s := range r.Portgroup {
if i > 0 {
fmt.Fprintln(tw)
}
fmt.Fprintf(tw, "Name:\t%s\n", s.Spec.Name)
fmt.Fprintf(tw, "Virtual switch:\t%s\n", s.Spec.VswitchName)
fmt.Fprintf(tw, "VLAN ID:\t%d\n", s.Spec.VlanId)
fmt.Fprintf(tw, "Active ports:\t%d\n", len(s.Port))
vswitch.HostNetworkPolicy(tw, &s.ComputedPolicy)
}
return tw.Flush()
}

View File

@@ -0,0 +1,65 @@
/*
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 portgroup
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type remove struct {
*flags.HostSystemFlag
}
func init() {
cli.Register("host.portgroup.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *remove) Description() string {
return `Remove portgroup from HOST.
Examples:
govc host.portgroup.remove bridge`
}
func (cmd *remove) Usage() string {
return "NAME"
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
return ns.RemovePortGroup(ctx, f.Arg(0))
}

View File

@@ -0,0 +1,96 @@
/*
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 host
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
type reconnect struct {
*flags.HostSystemFlag
*flags.HostConnectFlag
types.HostSystemReconnectSpec
}
func init() {
cli.Register("host.reconnect", &reconnect{})
}
func (cmd *reconnect) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.HostConnectFlag, ctx = flags.NewHostConnectFlag(ctx)
cmd.HostConnectFlag.Register(ctx, f)
cmd.HostSystemReconnectSpec.SyncState = types.NewBool(false)
f.BoolVar(cmd.HostSystemReconnectSpec.SyncState, "sync-state", false, "Sync state")
}
func (cmd *reconnect) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostConnectFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *reconnect) Description() string {
return `Reconnect HOST to vCenter.
This command can also be used to change connection properties (hostname, fingerprint, username, password),
without disconnecting the host.`
}
func (cmd *reconnect) Reconnect(ctx context.Context, host *object.HostSystem) error {
task, err := host.Reconnect(ctx, &cmd.HostConnectSpec, &cmd.HostSystemReconnectSpec)
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("%s reconnecting... ", host.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *reconnect) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
err = cmd.Reconnect(ctx, host)
if err != nil {
return err
}
}
return nil
}

100
vendor/github.com/vmware/govmomi/govc/host/remove.go generated vendored Normal file
View File

@@ -0,0 +1,100 @@
/*
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 host
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/mo"
)
type remove struct {
*flags.HostSystemFlag
}
func init() {
cli.Register("host.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Usage() string {
return "HOST..."
}
func (cmd *remove) Description() string {
return `Remove HOST from vCenter.`
}
func (cmd *remove) Remove(ctx context.Context, host *object.HostSystem) error {
var h mo.HostSystem
err := host.Properties(ctx, host.Reference(), []string{"parent"}, &h)
if err != nil {
return err
}
remove := host.Destroy
if h.Parent.Type == "ComputeResource" {
// Standalone host. From the docs:
// "Invoking remove on a HostSystem of standalone type throws a NotSupported fault.
// A standalone HostSystem can be removeed only by invoking remove on its parent ComputeResource."
remove = object.NewComputeResource(host.Client(), *h.Parent).Destroy
}
task, err := remove(ctx)
if err != nil {
return err
}
logger := cmd.ProgressLogger(fmt.Sprintf("%s removing... ", host.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
err = cmd.Remove(ctx, host)
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,125 @@
/*
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 service
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
type service struct {
*flags.ClientFlag
*flags.HostSystemFlag
}
func init() {
cli.Register("host.service", &service{})
}
func (cmd *service) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *service) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *service) Usage() string {
return "ACTION ID"
}
func (cmd *service) Description() string {
return `Apply host service ACTION to service ID.
Where ACTION is one of: start, stop, restart, status, enable, disable
Examples:
govc host.service enable TSM-SSH
govc host.service start TSM-SSH`
}
func (cmd *service) status(ctx context.Context, s *object.HostServiceSystem, id string) (string, error) {
services, err := s.Service(ctx)
if err != nil {
return "", err
}
for _, service := range services {
if id == service.Key {
return Status(service), nil
}
}
return "N/A", nil
}
func (cmd *service) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
if f.NArg() != 2 {
return flag.ErrHelp
}
arg := f.Arg(0)
id := f.Arg(1)
s, err := host.ConfigManager().ServiceSystem(ctx)
if err != nil {
return err
}
switch arg {
case "start":
return s.Start(ctx, id)
case "stop":
return s.Stop(ctx, id)
case "restart":
return s.Restart(ctx, id)
case "status":
ss, err := cmd.status(ctx, s, id)
if err != nil {
return err
}
fmt.Println(ss)
return nil
case "enable":
return s.UpdatePolicy(ctx, id, string(types.HostServicePolicyOn))
case "disable":
return s.UpdatePolicy(ctx, id, string(types.HostServicePolicyOff))
}
return flag.ErrHelp
}

View File

@@ -0,0 +1,120 @@
/*
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 service
import (
"context"
"flag"
"fmt"
"io"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type ls struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.HostSystemFlag
}
func init() {
cli.Register("host.service.ls", &ls{})
}
func (cmd *ls) 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.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *ls) 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.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *ls) Description() string {
return `List HOST services.`
}
func Status(s types.HostService) string {
if s.Running {
return "Running"
}
return "Stopped"
}
func Policy(s types.HostService) string {
switch types.HostServicePolicy(s.Policy) {
case types.HostServicePolicyOff:
return "Disabled"
case types.HostServicePolicyOn:
return "Enabled"
case types.HostServicePolicyAutomatic:
return "Automatic"
default:
return s.Policy
}
}
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
s, err := host.ConfigManager().ServiceSystem(ctx)
if err != nil {
return err
}
services, err := s.Service(ctx)
if err != nil {
return err
}
return cmd.WriteResult(optionResult(services))
}
type optionResult []types.HostService
func (services optionResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "%s\t%s\t%v\t%s\n", "Key", "Policy", "Status", "Label")
for _, s := range services {
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", s.Key, s.Policy, Status(s), s.Label)
}
return tw.Flush()
}

92
vendor/github.com/vmware/govmomi/govc/host/shutdown.go generated vendored Normal file
View File

@@ -0,0 +1,92 @@
/*
Copyright (c) 2017 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package host
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type shutdown struct {
*flags.HostSystemFlag
force bool
}
func init() {
cli.Register("host.shutdown", &shutdown{})
}
func (cmd *shutdown) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.BoolVar(&cmd.force, "f", false, "Force shutdown when host is not in maintenance mode")
}
func (cmd *shutdown) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *shutdown) Description() string {
return `Shutdown HOST.`
}
func (cmd *shutdown) Shutdown(ctx context.Context, host *object.HostSystem) error {
req := types.ShutdownHost_Task{
This: host.Reference(),
Force: cmd.force,
}
res, err := methods.ShutdownHost_Task(ctx, host.Client(), &req)
if err != nil {
return err
}
task := object.NewTask(host.Client(), res.Returnval)
logger := cmd.ProgressLogger(fmt.Sprintf("%s shutdown... ", host.InventoryPath))
defer logger.Wait()
_, err = task.WaitForResult(ctx, logger)
return err
}
func (cmd *shutdown) Run(ctx context.Context, f *flag.FlagSet) error {
hosts, err := cmd.HostSystems(f.Args())
if err != nil {
return err
}
for _, host := range hosts {
err = cmd.Shutdown(ctx, host)
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,227 @@
/*
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 storage
import (
"context"
"flag"
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/units"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
var infoTypes = []string{"hba", "lun"}
type infoType string
func (t *infoType) Set(s string) error {
s = strings.ToLower(s)
for _, e := range infoTypes {
if s == e {
*t = infoType(s)
return nil
}
}
return fmt.Errorf("invalid type")
}
func (t *infoType) String() string {
return string(*t)
}
func (t *infoType) Result(hss mo.HostStorageSystem) flags.OutputWriter {
switch string(*t) {
case "hba":
return hbaResult(hss)
case "lun":
return lunResult(hss)
default:
panic("unsupported")
}
}
type info struct {
*flags.HostSystemFlag
*flags.OutputFlag
typ infoType
rescan bool
unclaimed bool
}
func init() {
cli.Register("host.storage.info", &info{})
}
func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
err := cmd.typ.Set("lun")
if err != nil {
panic(err)
}
f.Var(&cmd.typ, "t", fmt.Sprintf("Type (%s)", strings.Join(infoTypes, ",")))
f.BoolVar(&cmd.rescan, "rescan", false, "Rescan for new storage devices")
f.BoolVar(&cmd.unclaimed, "unclaimed", false, "Only show disks that can be used as new VMFS datastores")
}
func (cmd *info) Description() string {
return `Show HOST storage system information.
Examples:
govc ls -t HostSystem host/* | xargs -n1 govc host.storage.info -unclaimed -host`
}
func (cmd *info) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
ss, err := host.ConfigManager().StorageSystem(ctx)
if err != nil {
return err
}
if cmd.rescan {
err = ss.RescanAllHba(ctx)
if err != nil {
return err
}
}
var hss mo.HostStorageSystem
err = ss.Properties(ctx, ss.Reference(), nil, &hss)
if err != nil {
return nil
}
if cmd.unclaimed {
ds, err := host.ConfigManager().DatastoreSystem(ctx)
if err != nil {
return err
}
disks, err := ds.QueryAvailableDisksForVmfs(ctx)
if err != nil {
return err
}
var luns []types.BaseScsiLun
for i := range disks {
luns = append(luns, &disks[i])
}
hss.StorageDeviceInfo.ScsiLun = luns
}
return cmd.WriteResult(cmd.typ.Result(hss))
}
type hbaResult mo.HostStorageSystem
func (r hbaResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Device\t")
fmt.Fprintf(tw, "PCI\t")
fmt.Fprintf(tw, "Driver\t")
fmt.Fprintf(tw, "Status\t")
fmt.Fprintf(tw, "Model\t")
fmt.Fprintf(tw, "\n")
for _, e := range r.StorageDeviceInfo.HostBusAdapter {
hba := e.GetHostHostBusAdapter()
fmt.Fprintf(tw, "%s\t", hba.Device)
fmt.Fprintf(tw, "%s\t", hba.Pci)
fmt.Fprintf(tw, "%s\t", hba.Driver)
fmt.Fprintf(tw, "%s\t", hba.Status)
fmt.Fprintf(tw, "%s\t", hba.Model)
fmt.Fprintf(tw, "\n")
}
return tw.Flush()
}
type lunResult mo.HostStorageSystem
func (r lunResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Name\t")
fmt.Fprintf(tw, "Type\t")
fmt.Fprintf(tw, "Capacity\t")
fmt.Fprintf(tw, "Model\t")
fmt.Fprintf(tw, "\n")
for _, e := range r.StorageDeviceInfo.ScsiLun {
var tags []string
var capacity int64
lun := e.GetScsiLun()
if disk, ok := e.(*types.HostScsiDisk); ok {
capacity = int64(disk.Capacity.Block) * int64(disk.Capacity.BlockSize)
if disk.LocalDisk != nil && *disk.LocalDisk {
tags = append(tags, "local")
}
if disk.Ssd != nil && *disk.Ssd {
tags = append(tags, "ssd")
}
}
fmt.Fprintf(tw, "%s\t", lun.DeviceName)
fmt.Fprintf(tw, "%s\t", lun.DeviceType)
if capacity == 0 {
fmt.Fprintf(tw, "-\t")
} else {
fmt.Fprintf(tw, "%s\t", units.ByteSize(capacity))
}
fmt.Fprintf(tw, "%s", lun.Model)
if len(tags) > 0 {
fmt.Fprintf(tw, " (%s)", strings.Join(tags, ","))
}
fmt.Fprintf(tw, "\n")
}
return tw.Flush()
}

View File

@@ -0,0 +1,141 @@
/*
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 storage
import (
"context"
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type mark struct {
*flags.HostSystemFlag
ssd *bool
local *bool
}
func init() {
cli.Register("host.storage.mark", &mark{})
}
func (cmd *mark) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.Var(flags.NewOptionalBool(&cmd.ssd), "ssd", "Mark as SSD")
f.Var(flags.NewOptionalBool(&cmd.local), "local", "Mark as local")
}
func (cmd *mark) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mark) Usage() string {
return "DEVICE_PATH"
}
func (cmd *mark) Description() string {
return `Mark device at DEVICE_PATH.`
}
func (cmd *mark) Mark(ctx context.Context, ss *object.HostStorageSystem, uuid string) error {
var err error
var task *object.Task
if cmd.ssd != nil {
if *cmd.ssd {
task, err = ss.MarkAsSsd(ctx, uuid)
} else {
task, err = ss.MarkAsNonSsd(ctx, uuid)
}
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return err
}
}
if cmd.local != nil {
if *cmd.local {
task, err = ss.MarkAsLocal(ctx, uuid)
} else {
task, err = ss.MarkAsNonLocal(ctx, uuid)
}
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return err
}
}
return nil
}
func (cmd *mark) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return fmt.Errorf("specify device path")
}
path := f.Args()[0]
host, err := cmd.HostSystem()
if err != nil {
return err
}
ss, err := host.ConfigManager().StorageSystem(ctx)
if err != nil {
return err
}
var hss mo.HostStorageSystem
err = ss.Properties(ctx, ss.Reference(), nil, &hss)
if err != nil {
return nil
}
for _, e := range hss.StorageDeviceInfo.ScsiLun {
disk, ok := e.(*types.HostScsiDisk)
if !ok {
continue
}
if disk.DevicePath == path {
return cmd.Mark(ctx, ss, disk.Uuid)
}
}
return fmt.Errorf("%s not found", path)
}

View File

@@ -0,0 +1,126 @@
/*
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 storage
import (
"context"
"flag"
"fmt"
"io"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/units"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type partition struct {
*flags.HostSystemFlag
*flags.OutputFlag
}
func init() {
cli.Register("host.storage.partition", &partition{})
}
func (cmd *partition) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)
}
func (cmd *partition) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
if err := cmd.OutputFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *partition) Usage() string {
return "DEVICE_PATH"
}
func (cmd *partition) Description() string {
return `Show partition table for device at DEVICE_PATH.`
}
func (cmd *partition) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return fmt.Errorf("specify device path")
}
path := f.Args()[0]
host, err := cmd.HostSystem()
if err != nil {
return err
}
ss, err := host.ConfigManager().StorageSystem(ctx)
if err != nil {
return err
}
var hss mo.HostStorageSystem
err = ss.Properties(ctx, ss.Reference(), nil, &hss)
if err != nil {
return nil
}
info, err := ss.RetrieveDiskPartitionInfo(ctx, path)
if err != nil {
return err
}
return cmd.WriteResult(partitionInfo(*info))
}
type partitionInfo types.HostDiskPartitionInfo
func (p partitionInfo) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Table format: %s\n", p.Spec.PartitionFormat)
fmt.Fprintf(tw, "Number of sectors: %d\n", p.Spec.TotalSectors)
fmt.Fprintf(tw, "\n")
fmt.Fprintf(tw, "Number\t")
fmt.Fprintf(tw, "Start\t")
fmt.Fprintf(tw, "End\t")
fmt.Fprintf(tw, "Size\t")
fmt.Fprintf(tw, "Type\t")
fmt.Fprintf(tw, "\n")
for _, e := range p.Spec.Partition {
sectors := e.EndSector - e.StartSector
fmt.Fprintf(tw, "%d\t", e.Partition)
fmt.Fprintf(tw, "%d\t", e.StartSector)
fmt.Fprintf(tw, "%d\t", e.EndSector)
fmt.Fprintf(tw, "%s\t", units.ByteSize(sectors*512))
fmt.Fprintf(tw, "%s\t", e.Type)
fmt.Fprintf(tw, "\n")
}
return tw.Flush()
}

146
vendor/github.com/vmware/govmomi/govc/host/vnic/info.go generated vendored Normal file
View File

@@ -0,0 +1,146 @@
/*
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 vnic
import (
"context"
"flag"
"fmt"
"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/mo"
"github.com/vmware/govmomi/vim25/types"
)
type info struct {
*flags.HostSystemFlag
}
func init() {
cli.Register("host.vnic.info", &info{})
}
func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *info) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
host, err := cmd.HostSystem()
if err != nil {
return err
}
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
var mns mo.HostNetworkSystem
m, err := host.ConfigManager().VirtualNicManager(ctx)
if err != nil {
return err
}
info, err := m.Info(ctx)
if err != nil {
return err
}
err = ns.Properties(ctx, ns.Reference(), []string{"networkInfo"}, &mns)
if err != nil {
return err
}
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
type dnet struct {
dvp mo.DistributedVirtualPortgroup
dvs mo.VmwareDistributedVirtualSwitch
}
dnets := make(map[string]*dnet)
for _, nic := range mns.NetworkInfo.Vnic {
fmt.Fprintf(tw, "Device:\t%s\n", nic.Device)
if dvp := nic.Spec.DistributedVirtualPort; dvp != nil {
dn, ok := dnets[dvp.PortgroupKey]
if !ok {
dn = new(dnet)
o := object.NewDistributedVirtualPortgroup(host.Client(), types.ManagedObjectReference{
Type: "DistributedVirtualPortgroup",
Value: dvp.PortgroupKey,
})
err = o.Properties(ctx, o.Reference(), []string{"name", "config.distributedVirtualSwitch"}, &dn.dvp)
if err != nil {
return err
}
err = o.Properties(ctx, *dn.dvp.Config.DistributedVirtualSwitch, []string{"name"}, &dn.dvs)
if err != nil {
return err
}
dnets[dvp.PortgroupKey] = dn
}
fmt.Fprintf(tw, "Network label:\t%s\n", dn.dvp.Name)
fmt.Fprintf(tw, "Switch:\t%s\n", dn.dvs.Name)
} else {
fmt.Fprintf(tw, "Network label:\t%s\n", nic.Portgroup)
for _, pg := range mns.NetworkInfo.Portgroup {
if pg.Spec.Name == nic.Portgroup {
fmt.Fprintf(tw, "Switch:\t%s\n", pg.Spec.VswitchName)
break
}
}
}
fmt.Fprintf(tw, "IP address:\t%s\n", nic.Spec.Ip.IpAddress)
fmt.Fprintf(tw, "TCP/IP stack:\t%s\n", nic.Spec.NetStackInstanceKey)
var services []string
for _, nc := range info.NetConfig {
for _, dev := range nc.SelectedVnic {
key := nc.NicType + "." + nic.Key
if dev == key {
services = append(services, nc.NicType)
}
}
}
fmt.Fprintf(tw, "Enabled services:\t%s\n", strings.Join(services, ", "))
}
return tw.Flush()
}

View File

@@ -0,0 +1,114 @@
/*
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 vnic
import (
"context"
"flag"
"fmt"
"strings"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type service struct {
*flags.HostSystemFlag
Enable bool
}
func init() {
cli.Register("host.vnic.service", &service{})
}
func (cmd *service) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.BoolVar(&cmd.Enable, "enable", true, "Enable service")
}
func (cmd *service) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *service) Usage() string {
return "SERVICE DEVICE"
}
func (cmd *service) Description() string {
nicTypes := []string{
string(types.HostVirtualNicManagerNicTypeVmotion),
string(types.HostVirtualNicManagerNicTypeFaultToleranceLogging),
string(types.HostVirtualNicManagerNicTypeVSphereReplication),
string(types.HostVirtualNicManagerNicTypeVSphereReplicationNFC),
string(types.HostVirtualNicManagerNicTypeManagement),
string(types.HostVirtualNicManagerNicTypeVsan),
string(types.HostVirtualNicManagerNicTypeVSphereProvisioning),
}
return fmt.Sprintf(`
Enable or disable service on a virtual nic device.
Where SERVICE is one of: %s
Where DEVICE is one of: %s
Examples:
govc host.vnic.service -host hostname -enable vsan vmk0
govc host.vnic.service -host hostname -enable=false vmotion vmk1`,
strings.Join(nicTypes, "|"),
strings.Join([]string{"vmk0", "vmk1", "..."}, "|"))
}
func (cmd *service) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 2 {
return flag.ErrHelp
}
service := f.Arg(0)
device := f.Arg(1)
host, err := cmd.HostSystem()
if err != nil {
return err
}
m, err := host.ConfigManager().VirtualNicManager(ctx)
if err != nil {
return err
}
var method func(context.Context, string, string) error
if cmd.Enable {
method = m.SelectVnic
} else {
method = m.DeselectVnic
}
if method == nil {
return flag.ErrHelp
}
return method(ctx, service, device)
}

View File

@@ -0,0 +1,73 @@
/*
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 vswitch
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25/types"
)
type add struct {
*flags.HostSystemFlag
nic string
spec types.HostVirtualSwitchSpec
}
func init() {
cli.Register("host.vswitch.add", &add{})
}
func (cmd *add) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
cmd.spec.NumPorts = 128 // default
f.Var(flags.NewInt32(&cmd.spec.NumPorts), "ports", "Number of ports")
f.Var(flags.NewInt32(&cmd.spec.Mtu), "mtu", "MTU")
f.StringVar(&cmd.nic, "nic", "", "Bridge nic device")
}
func (cmd *add) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *add) Usage() string {
return "NAME"
}
func (cmd *add) Run(ctx context.Context, f *flag.FlagSet) error {
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
if cmd.nic != "" {
cmd.spec.Bridge = &types.HostVirtualSwitchBondBridge{
NicDevice: []string{cmd.nic},
}
}
return ns.AddVirtualSwitch(ctx, f.Arg(0), &cmd.spec)
}

View File

@@ -0,0 +1,134 @@
/*
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 vswitch
import (
"context"
"flag"
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type info struct {
*flags.ClientFlag
*flags.OutputFlag
*flags.HostSystemFlag
}
func init() {
cli.Register("host.vswitch.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.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.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.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
client, err := cmd.Client()
if err != nil {
return err
}
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
var mns mo.HostNetworkSystem
pc := property.DefaultCollector(client)
err = pc.RetrieveOne(ctx, ns.Reference(), []string{"networkInfo.vswitch"}, &mns)
if err != nil {
return err
}
r := &infoResult{mns.NetworkInfo.Vswitch}
return cmd.WriteResult(r)
}
type infoResult struct {
Vswitch []types.HostVirtualSwitch
}
func (r *infoResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
for i, s := range r.Vswitch {
if i > 0 {
fmt.Fprintln(tw)
}
fmt.Fprintf(tw, "Name:\t%s\n", s.Name)
fmt.Fprintf(tw, "Portgroup:\t%s\n", keys("key-vim.host.PortGroup-", s.Portgroup))
fmt.Fprintf(tw, "Pnic:\t%s\n", keys("key-vim.host.PhysicalNic-", s.Pnic))
fmt.Fprintf(tw, "MTU:\t%d\n", s.Mtu)
fmt.Fprintf(tw, "Ports:\t%d\n", s.NumPorts)
fmt.Fprintf(tw, "Ports Available:\t%d\n", s.NumPortsAvailable)
HostNetworkPolicy(tw, s.Spec.Policy)
}
return tw.Flush()
}
func keys(key string, vals []string) string {
for i, val := range vals {
vals[i] = strings.TrimPrefix(val, key)
}
return strings.Join(vals, ", ")
}
func enabled(b *bool) string {
if b != nil && *b {
return "Yes"
}
return "No"
}
func HostNetworkPolicy(w io.Writer, p *types.HostNetworkPolicy) {
if p == nil || p.Security == nil {
return // e.g. Workstation
}
fmt.Fprintf(w, "Allow promiscuous mode:\t%s\n", enabled(p.Security.AllowPromiscuous))
fmt.Fprintf(w, "Allow forged transmits:\t%s\n", enabled(p.Security.ForgedTransmits))
fmt.Fprintf(w, "Allow MAC changes:\t%s\n", enabled(p.Security.MacChanges))
}

View File

@@ -0,0 +1,58 @@
/*
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 vswitch
import (
"context"
"flag"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type remove struct {
*flags.HostSystemFlag
}
func init() {
cli.Register("host.vswitch.remove", &remove{})
}
func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
}
func (cmd *remove) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *remove) Usage() string {
return "NAME"
}
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
ns, err := cmd.HostNetworkSystem()
if err != nil {
return err
}
return ns.RemoveVirtualSwitch(ctx, f.Arg(0))
}