Adding OWNERS file for vSphere cloud-provider package

also updating license file for Govmomi library
This commit is contained in:
dagnello
2016-04-26 14:12:53 -07:00
parent 4fd02f54ef
commit f7b3cf39d6
350 changed files with 241 additions and 31 deletions

View File

@@ -0,0 +1,108 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type AuthorizationManager struct {
Common
}
func NewAuthorizationManager(c *vim25.Client) *AuthorizationManager {
m := AuthorizationManager{
Common: NewCommon(c, *c.ServiceContent.AuthorizationManager),
}
return &m
}
type AuthorizationRoleList []types.AuthorizationRole
func (l AuthorizationRoleList) ById(id int32) *types.AuthorizationRole {
for _, role := range l {
if role.RoleId == id {
return &role
}
}
return nil
}
func (l AuthorizationRoleList) ByName(name string) *types.AuthorizationRole {
for _, role := range l {
if role.Name == name {
return &role
}
}
return nil
}
func (m AuthorizationManager) RoleList(ctx context.Context) (AuthorizationRoleList, error) {
var am mo.AuthorizationManager
err := m.Properties(ctx, m.Reference(), []string{"roleList"}, &am)
if err != nil {
return nil, err
}
return AuthorizationRoleList(am.RoleList), nil
}
func (m AuthorizationManager) RetrieveEntityPermissions(ctx context.Context, entity types.ManagedObjectReference, inherited bool) ([]types.Permission, error) {
req := types.RetrieveEntityPermissions{
This: m.Reference(),
Entity: entity,
Inherited: inherited,
}
res, err := methods.RetrieveEntityPermissions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m AuthorizationManager) RemoveEntityPermission(ctx context.Context, entity types.ManagedObjectReference, user string, isGroup bool) error {
req := types.RemoveEntityPermission{
This: m.Reference(),
Entity: entity,
User: user,
IsGroup: isGroup,
}
_, err := methods.RemoveEntityPermission(ctx, m.Client(), &req)
return err
}
func (m AuthorizationManager) SetEntityPermissions(ctx context.Context, entity types.ManagedObjectReference, permission []types.Permission) error {
req := types.SetEntityPermissions{
This: m.Reference(),
Entity: entity,
Permission: permission,
}
_, err := methods.SetEntityPermissions(ctx, m.Client(), &req)
return err
}

View File

@@ -0,0 +1,87 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type ClusterComputeResource struct {
ComputeResource
InventoryPath string
}
func NewClusterComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ClusterComputeResource {
return &ClusterComputeResource{
ComputeResource: *NewComputeResource(c, ref),
}
}
func (c ClusterComputeResource) ReconfigureCluster(ctx context.Context, spec types.ClusterConfigSpec) (*Task, error) {
req := types.ReconfigureCluster_Task{
This: c.Reference(),
Spec: spec,
Modify: true,
}
res, err := methods.ReconfigureCluster_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ClusterComputeResource) AddHost(ctx context.Context, spec types.HostConnectSpec, asConnected bool, license *string, resourcePool *types.ManagedObjectReference) (*Task, error) {
req := types.AddHost_Task{
This: c.Reference(),
Spec: spec,
AsConnected: asConnected,
}
if license != nil {
req.License = *license
}
if resourcePool != nil {
req.ResourcePool = resourcePool
}
res, err := methods.AddHost_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ClusterComputeResource) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: c.Reference(),
}
res, err := methods.Destroy_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}

71
vendor/github.com/vmware/govmomi/object/common.go generated vendored Normal file
View File

@@ -0,0 +1,71 @@
/*
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 object
import (
"errors"
"fmt"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
var (
ErrNotSupported = errors.New("not supported (vCenter only)")
)
// Common contains the fields and functions common to all objects.
type Common struct {
c *vim25.Client
r types.ManagedObjectReference
}
func (c Common) String() string {
return fmt.Sprintf("%v", c.Reference())
}
func NewCommon(c *vim25.Client, r types.ManagedObjectReference) Common {
return Common{c: c, r: r}
}
func (c Common) Reference() types.ManagedObjectReference {
return c.r
}
func (c Common) Client() *vim25.Client {
return c.c
}
func (c Common) Properties(ctx context.Context, r types.ManagedObjectReference, ps []string, dst interface{}) error {
return property.DefaultCollector(c.c).RetrieveOne(ctx, r, ps, dst)
}
func (c Common) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: c.Reference(),
}
res, err := methods.Destroy_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}

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 object
import (
"path"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type ComputeResource struct {
Common
InventoryPath string
}
func NewComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ComputeResource {
return &ComputeResource{
Common: NewCommon(c, ref),
}
}
func (c ComputeResource) Hosts(ctx context.Context) ([]*HostSystem, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"host"}, &cr)
if err != nil {
return nil, err
}
if len(cr.Host) == 0 {
return nil, nil
}
var hs []mo.HostSystem
pc := property.DefaultCollector(c.Client())
err = pc.Retrieve(ctx, cr.Host, []string{"name"}, &hs)
if err != nil {
return nil, err
}
var hosts []*HostSystem
for _, h := range hs {
host := NewHostSystem(c.Client(), h.Reference())
host.InventoryPath = path.Join(c.InventoryPath, h.Name)
hosts = append(hosts, host)
}
return hosts, nil
}
func (c ComputeResource) Datastores(ctx context.Context) ([]*Datastore, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"datastore"}, &cr)
if err != nil {
return nil, err
}
var dss []*Datastore
for _, ref := range cr.Datastore {
ds := NewDatastore(c.c, ref)
dss = append(dss, ds)
}
return dss, nil
}
func (c ComputeResource) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var cr mo.ComputeResource
err := c.Properties(ctx, c.Reference(), []string{"resourcePool"}, &cr)
if err != nil {
return nil, err
}
return NewResourcePool(c.c, *cr.ResourcePool), nil
}
func (c ComputeResource) Reconfigure(ctx context.Context, spec types.BaseComputeResourceConfigSpec, modify bool) (*Task, error) {
req := types.ReconfigureComputeResource_Task{
This: c.Reference(),
Spec: spec,
Modify: modify,
}
res, err := methods.ReconfigureComputeResource_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}
func (c ComputeResource) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: c.Reference(),
}
res, err := methods.Destroy_Task(ctx, c.c, &req)
if err != nil {
return nil, err
}
return NewTask(c.c, res.Returnval), nil
}

View File

@@ -0,0 +1,135 @@
/*
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 object
import (
"errors"
"strconv"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
var (
ErrKeyNameNotFound = errors.New("key name not found")
)
type CustomFieldsManager struct {
Common
}
// GetCustomFieldsManager wraps NewCustomFieldsManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetCustomFieldsManager(c *vim25.Client) (*CustomFieldsManager, error) {
if c.ServiceContent.CustomFieldsManager == nil {
return nil, ErrNotSupported
}
return NewCustomFieldsManager(c), nil
}
func NewCustomFieldsManager(c *vim25.Client) *CustomFieldsManager {
m := CustomFieldsManager{
Common: NewCommon(c, *c.ServiceContent.CustomFieldsManager),
}
return &m
}
func (m CustomFieldsManager) Add(ctx context.Context, name string, moType string, fieldDefPolicy *types.PrivilegePolicyDef, fieldPolicy *types.PrivilegePolicyDef) (*types.CustomFieldDef, error) {
req := types.AddCustomFieldDef{
This: m.Reference(),
Name: name,
MoType: moType,
FieldDefPolicy: fieldDefPolicy,
FieldPolicy: fieldPolicy,
}
res, err := methods.AddCustomFieldDef(ctx, m.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (m CustomFieldsManager) Remove(ctx context.Context, key int32) error {
req := types.RemoveCustomFieldDef{
This: m.Reference(),
Key: key,
}
_, err := methods.RemoveCustomFieldDef(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Rename(ctx context.Context, key int32, name string) error {
req := types.RenameCustomFieldDef{
This: m.Reference(),
Key: key,
Name: name,
}
_, err := methods.RenameCustomFieldDef(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Set(ctx context.Context, entity types.ManagedObjectReference, key int32, value string) error {
req := types.SetField{
This: m.Reference(),
Entity: entity,
Key: key,
Value: value,
}
_, err := methods.SetField(ctx, m.c, &req)
return err
}
func (m CustomFieldsManager) Field(ctx context.Context) ([]types.CustomFieldDef, error) {
var fm mo.CustomFieldsManager
err := m.Properties(ctx, m.Reference(), []string{"field"}, &fm)
if err != nil {
return nil, err
}
return fm.Field, nil
}
func (m CustomFieldsManager) FindKey(ctx context.Context, key string) (int32, error) {
field, err := m.Field(ctx)
if err != nil {
return -1, err
}
for _, def := range field {
if def.Name == key {
return def.Key, nil
}
}
k, err := strconv.Atoi(key)
if err == nil {
// assume literal int key
return int32(k), nil
}
return -1, ErrKeyNameNotFound
}

View File

@@ -0,0 +1,165 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type CustomizationSpecManager struct {
Common
}
func NewCustomizationSpecManager(c *vim25.Client) *CustomizationSpecManager {
cs := CustomizationSpecManager{
Common: NewCommon(c, *c.ServiceContent.CustomizationSpecManager),
}
return &cs
}
func (cs CustomizationSpecManager) DoesCustomizationSpecExist(ctx context.Context, name string) (bool, error) {
req := types.DoesCustomizationSpecExist{
This: cs.Reference(),
Name: name,
}
res, err := methods.DoesCustomizationSpecExist(ctx, cs.c, &req)
if err != nil {
return false, err
}
return res.Returnval, nil
}
func (cs CustomizationSpecManager) GetCustomizationSpec(ctx context.Context, name string) (*types.CustomizationSpecItem, error) {
req := types.GetCustomizationSpec{
This: cs.Reference(),
Name: name,
}
res, err := methods.GetCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (cs CustomizationSpecManager) CreateCustomizationSpec(ctx context.Context, item types.CustomizationSpecItem) error {
req := types.CreateCustomizationSpec{
This: cs.Reference(),
Item: item,
}
_, err := methods.CreateCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) OverwriteCustomizationSpec(ctx context.Context, item types.CustomizationSpecItem) error {
req := types.OverwriteCustomizationSpec{
This: cs.Reference(),
Item: item,
}
_, err := methods.OverwriteCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) DeleteCustomizationSpec(ctx context.Context, name string) error {
req := types.DeleteCustomizationSpec{
This: cs.Reference(),
Name: name,
}
_, err := methods.DeleteCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) DuplicateCustomizationSpec(ctx context.Context, name string, newName string) error {
req := types.DuplicateCustomizationSpec{
This: cs.Reference(),
Name: name,
NewName: newName,
}
_, err := methods.DuplicateCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) RenameCustomizationSpec(ctx context.Context, name string, newName string) error {
req := types.RenameCustomizationSpec{
This: cs.Reference(),
Name: name,
NewName: newName,
}
_, err := methods.RenameCustomizationSpec(ctx, cs.c, &req)
if err != nil {
return err
}
return nil
}
func (cs CustomizationSpecManager) CustomizationSpecItemToXml(ctx context.Context, item types.CustomizationSpecItem) (string, error) {
req := types.CustomizationSpecItemToXml{
This: cs.Reference(),
Item: item,
}
res, err := methods.CustomizationSpecItemToXml(ctx, cs.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
func (cs CustomizationSpecManager) XmlToCustomizationSpecItem(ctx context.Context, xml string) (*types.CustomizationSpecItem, error) {
req := types.XmlToCustomizationSpecItem{
This: cs.Reference(),
SpecItemXml: xml,
}
res, err := methods.XmlToCustomizationSpecItem(ctx, cs.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

90
vendor/github.com/vmware/govmomi/object/datacenter.go generated vendored Normal file
View File

@@ -0,0 +1,90 @@
/*
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 object
import (
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type DatacenterFolders struct {
VmFolder *Folder
HostFolder *Folder
DatastoreFolder *Folder
NetworkFolder *Folder
}
type Datacenter struct {
Common
}
func NewDatacenter(c *vim25.Client, ref types.ManagedObjectReference) *Datacenter {
return &Datacenter{
Common: NewCommon(c, ref),
}
}
func (d *Datacenter) Folders(ctx context.Context) (*DatacenterFolders, error) {
var md mo.Datacenter
ps := []string{"name", "vmFolder", "hostFolder", "datastoreFolder", "networkFolder"}
err := d.Properties(ctx, d.Reference(), ps, &md)
if err != nil {
return nil, err
}
df := &DatacenterFolders{
VmFolder: NewFolder(d.c, md.VmFolder),
HostFolder: NewFolder(d.c, md.HostFolder),
DatastoreFolder: NewFolder(d.c, md.DatastoreFolder),
NetworkFolder: NewFolder(d.c, md.NetworkFolder),
}
paths := []struct {
name string
path *string
}{
{"vm", &df.VmFolder.InventoryPath},
{"host", &df.HostFolder.InventoryPath},
{"datastore", &df.DatastoreFolder.InventoryPath},
{"network", &df.NetworkFolder.InventoryPath},
}
for _, p := range paths {
*p.path = fmt.Sprintf("/%s/%s", md.Name, p.name)
}
return df, nil
}
func (d Datacenter) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: d.Reference(),
}
res, err := methods.Destroy_Task(ctx, d.c, &req)
if err != nil {
return nil, err
}
return NewTask(d.c, res.Returnval), nil
}

351
vendor/github.com/vmware/govmomi/object/datastore.go generated vendored Normal file
View File

@@ -0,0 +1,351 @@
/*
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 object
import (
"fmt"
"io"
"math/rand"
"path"
"strings"
"net/http"
"net/url"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/session"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// DatastoreNoSuchDirectoryError is returned when a directory could not be found.
type DatastoreNoSuchDirectoryError struct {
verb string
subject string
}
func (e DatastoreNoSuchDirectoryError) Error() string {
return fmt.Sprintf("cannot %s '%s': No such directory", e.verb, e.subject)
}
// DatastoreNoSuchFileError is returned when a file could not be found.
type DatastoreNoSuchFileError struct {
verb string
subject string
}
func (e DatastoreNoSuchFileError) Error() string {
return fmt.Sprintf("cannot %s '%s': No such file", e.verb, e.subject)
}
type Datastore struct {
Common
InventoryPath string
}
func NewDatastore(c *vim25.Client, ref types.ManagedObjectReference) *Datastore {
return &Datastore{
Common: NewCommon(c, ref),
}
}
func (d Datastore) Name() string {
return path.Base(d.InventoryPath)
}
func (d Datastore) Path(path string) string {
name := d.Name()
if name == "" {
panic("expected non-empty name")
}
return fmt.Sprintf("[%s] %s", name, path)
}
// URL for datastore access over HTTP
func (d Datastore) URL(ctx context.Context, dc *Datacenter, path string) (*url.URL, error) {
var mdc mo.Datacenter
if err := dc.Properties(ctx, dc.Reference(), []string{"name"}, &mdc); err != nil {
return nil, err
}
var mds mo.Datastore
if err := d.Properties(ctx, d.Reference(), []string{"name"}, &mds); err != nil {
return nil, err
}
u := d.c.URL()
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: fmt.Sprintf("/folder/%s", path),
RawQuery: url.Values{
"dcPath": []string{mdc.Name},
"dsName": []string{mds.Name},
}.Encode(),
}, nil
}
func (d Datastore) Browser(ctx context.Context) (*HostDatastoreBrowser, error) {
var do mo.Datastore
err := d.Properties(ctx, d.Reference(), []string{"browser"}, &do)
if err != nil {
return nil, err
}
return NewHostDatastoreBrowser(d.c, do.Browser), nil
}
// ServiceTicket obtains a ticket via AcquireGenericServiceTicket and returns it an http.Cookie with the url.URL
// that can be used along with the ticket cookie to access the given path.
func (d Datastore) ServiceTicket(ctx context.Context, path string, method string) (*url.URL, *http.Cookie, error) {
// We are uploading to an ESX host
u := &url.URL{
Scheme: d.c.URL().Scheme,
Host: d.c.URL().Host,
Path: fmt.Sprintf("/folder/%s", path),
RawQuery: url.Values{
"dsName": []string{d.Name()},
}.Encode(),
}
// If connected to VC, the ticket request must be for an ESX host.
if d.c.IsVC() {
hosts, err := d.AttachedHosts(ctx)
if err != nil {
return nil, nil, err
}
if len(hosts) == 0 {
return nil, nil, fmt.Errorf("no hosts attached to datastore %#v", d.Reference())
}
// Pick a random attached host
host := hosts[rand.Intn(len(hosts))]
name, err := host.Name(ctx)
if err != nil {
return nil, nil, err
}
u.Host = name
}
spec := types.SessionManagerHttpServiceRequestSpec{
Url: u.String(),
// See SessionManagerHttpServiceRequestSpecMethod enum
Method: fmt.Sprintf("http%s%s", method[0:1], strings.ToLower(method[1:])),
}
sm := session.NewManager(d.Client())
ticket, err := sm.AcquireGenericServiceTicket(ctx, &spec)
if err != nil {
return nil, nil, err
}
cookie := &http.Cookie{
Name: "vmware_cgi_ticket",
Value: ticket.Id,
}
return u, cookie, nil
}
func (d Datastore) uploadTicket(ctx context.Context, path string, param *soap.Upload) (*url.URL, *soap.Upload, error) {
p := soap.DefaultUpload
if param != nil {
p = *param // copy
}
u, ticket, err := d.ServiceTicket(ctx, path, p.Method)
if err != nil {
return nil, nil, err
}
p.Ticket = ticket
return u, &p, nil
}
func (d Datastore) downloadTicket(ctx context.Context, path string, param *soap.Download) (*url.URL, *soap.Download, error) {
p := soap.DefaultDownload
if param != nil {
p = *param // copy
}
u, ticket, err := d.ServiceTicket(ctx, path, p.Method)
if err != nil {
return nil, nil, err
}
p.Ticket = ticket
return u, &p, nil
}
// Upload via soap.Upload with an http service ticket
func (d Datastore) Upload(ctx context.Context, f io.Reader, path string, param *soap.Upload) error {
u, p, err := d.uploadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().Upload(f, u, p)
}
// UploadFile via soap.Upload with an http service ticket
func (d Datastore) UploadFile(ctx context.Context, file string, path string, param *soap.Upload) error {
u, p, err := d.uploadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().UploadFile(file, u, p)
}
// DownloadFile via soap.Upload with an http service ticket
func (d Datastore) DownloadFile(ctx context.Context, path string, file string, param *soap.Download) error {
u, p, err := d.downloadTicket(ctx, path, param)
if err != nil {
return err
}
return d.Client().DownloadFile(file, u, p)
}
// AttachedHosts returns hosts that have this Datastore attached, accessible and writable.
func (d Datastore) AttachedHosts(ctx context.Context) ([]*HostSystem, error) {
var ds mo.Datastore
var hosts []*HostSystem
pc := property.DefaultCollector(d.Client())
err := pc.RetrieveOne(ctx, d.Reference(), []string{"host"}, &ds)
if err != nil {
return nil, err
}
mounts := make(map[types.ManagedObjectReference]types.DatastoreHostMount)
var refs []types.ManagedObjectReference
for _, host := range ds.Host {
refs = append(refs, host.Key)
mounts[host.Key] = host
}
var hs []mo.HostSystem
err = pc.Retrieve(ctx, refs, []string{"runtime.connectionState", "runtime.powerState"}, &hs)
if err != nil {
return nil, err
}
for _, host := range hs {
if host.Runtime.ConnectionState == types.HostSystemConnectionStateConnected &&
host.Runtime.PowerState == types.HostSystemPowerStatePoweredOn {
mount := mounts[host.Reference()]
info := mount.MountInfo
if *info.Mounted && *info.Accessible && info.AccessMode == string(types.HostMountModeReadWrite) {
hosts = append(hosts, NewHostSystem(d.Client(), mount.Key))
}
}
}
return hosts, nil
}
// AttachedHosts returns hosts that have this Datastore attached, accessible and writable and are members of the given cluster.
func (d Datastore) AttachedClusterHosts(ctx context.Context, cluster *ComputeResource) ([]*HostSystem, error) {
var hosts []*HostSystem
clusterHosts, err := cluster.Hosts(ctx)
if err != nil {
return nil, err
}
attachedHosts, err := d.AttachedHosts(ctx)
if err != nil {
return nil, err
}
refs := make(map[types.ManagedObjectReference]bool)
for _, host := range attachedHosts {
refs[host.Reference()] = true
}
for _, host := range clusterHosts {
if refs[host.Reference()] {
hosts = append(hosts, host)
}
}
return hosts, nil
}
func (d Datastore) Stat(ctx context.Context, file string) (types.BaseFileInfo, error) {
b, err := d.Browser(ctx)
if err != nil {
return nil, err
}
spec := types.HostDatastoreBrowserSearchSpec{
Details: &types.FileQueryFlags{
FileType: true,
FileOwner: types.NewBool(true), // TODO: omitempty is generated, but seems to be required
},
MatchPattern: []string{path.Base(file)},
}
dsPath := d.Path(path.Dir(file))
task, err := b.SearchDatastore(context.TODO(), dsPath, &spec)
if err != nil {
return nil, err
}
info, err := task.WaitForResult(context.TODO(), nil)
if err != nil {
if info == nil || info.Error != nil {
_, ok := info.Error.Fault.(*types.FileNotFound)
if ok {
// FileNotFound means the base path doesn't exist.
return nil, DatastoreNoSuchDirectoryError{"stat", dsPath}
}
}
return nil, err
}
res := info.Result.(types.HostDatastoreBrowserSearchResults)
if len(res.File) == 0 {
// File doesn't exist
return nil, DatastoreNoSuchFileError{"stat", d.Path(file)}
}
return res.File[0], nil
}
// Type returns the type of file system volume.
func (d Datastore) Type(ctx context.Context) (types.HostFileSystemVolumeFileSystemType, error) {
var mds mo.Datastore
if err := d.Properties(ctx, d.Reference(), []string{"summary.type"}, &mds); err != nil {
return types.HostFileSystemVolumeFileSystemType(""), err
}
return types.HostFileSystemVolumeFileSystemType(mds.Summary.Type), nil
}

View File

@@ -0,0 +1,95 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type DiagnosticManager struct {
Common
}
func NewDiagnosticManager(c *vim25.Client) *DiagnosticManager {
m := DiagnosticManager{
Common: NewCommon(c, *c.ServiceContent.DiagnosticManager),
}
return &m
}
func (m DiagnosticManager) BrowseLog(ctx context.Context, host *HostSystem, key string, start, lines int32) (*types.DiagnosticManagerLogHeader, error) {
req := types.BrowseDiagnosticLog{
This: m.Reference(),
Key: key,
Start: start,
Lines: lines,
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.BrowseDiagnosticLog(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (m DiagnosticManager) GenerateLogBundles(ctx context.Context, includeDefault bool, host []*HostSystem) (*Task, error) {
req := types.GenerateLogBundles_Task{
This: m.Reference(),
IncludeDefault: includeDefault,
}
if host != nil {
for _, h := range host {
req.Host = append(req.Host, h.Reference())
}
}
res, err := methods.GenerateLogBundles_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
func (m DiagnosticManager) QueryDescriptions(ctx context.Context, host *HostSystem) ([]types.DiagnosticManagerLogDescriptor, error) {
req := types.QueryDescriptions{
This: m.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.QueryDescriptions(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

View File

@@ -0,0 +1,64 @@
/*
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 object
import (
"path"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type DistributedVirtualPortgroup struct {
Common
InventoryPath string
}
func NewDistributedVirtualPortgroup(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualPortgroup {
return &DistributedVirtualPortgroup{
Common: NewCommon(c, ref),
}
}
func (p DistributedVirtualPortgroup) Name() string {
return path.Base(p.InventoryPath)
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this DistributedVirtualPortgroup
func (p DistributedVirtualPortgroup) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
var dvp mo.DistributedVirtualPortgroup
var dvs mo.VmwareDistributedVirtualSwitch // TODO: should be mo.BaseDistributedVirtualSwitch
if err := p.Properties(ctx, p.Reference(), []string{"key", "config.distributedVirtualSwitch"}, &dvp); err != nil {
return nil, err
}
if err := p.Properties(ctx, *dvp.Config.DistributedVirtualSwitch, []string{"uuid"}, &dvs); err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{
Port: types.DistributedVirtualSwitchPortConnection{
PortgroupKey: dvp.Key,
SwitchUuid: dvs.Uuid,
},
}
return backing, nil
}

View File

@@ -0,0 +1,68 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type DistributedVirtualSwitch struct {
Common
InventoryPath string
}
func NewDistributedVirtualSwitch(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualSwitch {
return &DistributedVirtualSwitch{
Common: NewCommon(c, ref),
}
}
func (s DistributedVirtualSwitch) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
return nil, ErrNotSupported // TODO: just to satisfy NetworkReference interface for the finder
}
func (s DistributedVirtualSwitch) Reconfigure(ctx context.Context, spec types.BaseDVSConfigSpec) (*Task, error) {
req := types.ReconfigureDvs_Task{
This: s.Reference(),
Spec: spec,
}
res, err := methods.ReconfigureDvs_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
func (s DistributedVirtualSwitch) AddPortgroup(ctx context.Context, spec []types.DVPortgroupConfigSpec) (*Task, error) {
req := types.AddDVPortgroup_Task{
This: s.Reference(),
Spec: spec,
}
res, err := methods.AddDVPortgroup_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}

View File

@@ -0,0 +1,112 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type ExtensionManager struct {
Common
}
// GetExtensionManager wraps NewExtensionManager, returning ErrNotSupported
// when the client is not connected to a vCenter instance.
func GetExtensionManager(c *vim25.Client) (*ExtensionManager, error) {
if c.ServiceContent.ExtensionManager == nil {
return nil, ErrNotSupported
}
return NewExtensionManager(c), nil
}
func NewExtensionManager(c *vim25.Client) *ExtensionManager {
o := ExtensionManager{
Common: NewCommon(c, *c.ServiceContent.ExtensionManager),
}
return &o
}
func (m ExtensionManager) List(ctx context.Context) ([]types.Extension, error) {
var em mo.ExtensionManager
err := m.Properties(ctx, m.Reference(), []string{"extensionList"}, &em)
if err != nil {
return nil, err
}
return em.ExtensionList, nil
}
func (m ExtensionManager) Find(ctx context.Context, key string) (*types.Extension, error) {
req := types.FindExtension{
This: m.Reference(),
ExtensionKey: key,
}
res, err := methods.FindExtension(ctx, m.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (m ExtensionManager) Register(ctx context.Context, extension types.Extension) error {
req := types.RegisterExtension{
This: m.Reference(),
Extension: extension,
}
_, err := methods.RegisterExtension(ctx, m.c, &req)
return err
}
func (m ExtensionManager) SetCertificate(ctx context.Context, key string, certificatePem string) error {
req := types.SetExtensionCertificate{
This: m.Reference(),
ExtensionKey: key,
CertificatePem: certificatePem,
}
_, err := methods.SetExtensionCertificate(ctx, m.c, &req)
return err
}
func (m ExtensionManager) Unregister(ctx context.Context, key string) error {
req := types.UnregisterExtension{
This: m.Reference(),
ExtensionKey: key,
}
_, err := methods.UnregisterExtension(ctx, m.c, &req)
return err
}
func (m ExtensionManager) Update(ctx context.Context, extension types.Extension) error {
req := types.UpdateExtension{
This: m.Reference(),
Extension: extension,
}
_, err := methods.UpdateExtension(ctx, m.c, &req)
return err
}

125
vendor/github.com/vmware/govmomi/object/file_manager.go generated vendored Normal file
View File

@@ -0,0 +1,125 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type FileManager struct {
Common
}
func NewFileManager(c *vim25.Client) *FileManager {
f := FileManager{
Common: NewCommon(c, *c.ServiceContent.FileManager),
}
return &f
}
func (f FileManager) CopyDatastoreFile(ctx context.Context, sourceName string, sourceDatacenter *Datacenter, destinationName string, destinationDatacenter *Datacenter, force bool) (*Task, error) {
req := types.CopyDatastoreFile_Task{
This: f.Reference(),
SourceName: sourceName,
DestinationName: destinationName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destinationDatacenter != nil {
ref := destinationDatacenter.Reference()
req.DestinationDatacenter = &ref
}
res, err := methods.CopyDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
// DeleteDatastoreFile deletes the specified file or folder from the datastore.
func (f FileManager) DeleteDatastoreFile(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.DeleteDatastoreFile_Task{
This: f.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.DeleteDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
// MakeDirectory creates a folder using the specified name.
func (f FileManager) MakeDirectory(ctx context.Context, name string, dc *Datacenter, createParentDirectories bool) error {
req := types.MakeDirectory{
This: f.Reference(),
Name: name,
CreateParentDirectories: types.NewBool(createParentDirectories),
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
_, err := methods.MakeDirectory(ctx, f.c, &req)
return err
}
func (f FileManager) MoveDatastoreFile(ctx context.Context, sourceName string, sourceDatacenter *Datacenter, destinationName string, destinationDatacenter *Datacenter, force bool) (*Task, error) {
req := types.MoveDatastoreFile_Task{
This: f.Reference(),
SourceName: sourceName,
DestinationName: destinationName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destinationDatacenter != nil {
ref := destinationDatacenter.Reference()
req.DestinationDatacenter = &ref
}
res, err := methods.MoveDatastoreFile_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}

198
vendor/github.com/vmware/govmomi/object/folder.go generated vendored Normal file
View File

@@ -0,0 +1,198 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type Folder struct {
Common
InventoryPath string
}
func NewFolder(c *vim25.Client, ref types.ManagedObjectReference) *Folder {
return &Folder{
Common: NewCommon(c, ref),
}
}
func NewRootFolder(c *vim25.Client) *Folder {
return NewFolder(c, c.ServiceContent.RootFolder)
}
func (f Folder) Children(ctx context.Context) ([]Reference, error) {
var mf mo.Folder
err := f.Properties(ctx, f.Reference(), []string{"childEntity"}, &mf)
if err != nil {
return nil, err
}
var rs []Reference
for _, e := range mf.ChildEntity {
if r := NewReference(f.c, e); r != nil {
rs = append(rs, r)
}
}
return rs, nil
}
func (f Folder) CreateDatacenter(ctx context.Context, datacenter string) (*Datacenter, error) {
req := types.CreateDatacenter{
This: f.Reference(),
Name: datacenter,
}
res, err := methods.CreateDatacenter(ctx, f.c, &req)
if err != nil {
return nil, err
}
// Response will be nil if this is an ESX host that does not belong to a vCenter
if res == nil {
return nil, nil
}
return NewDatacenter(f.c, res.Returnval), nil
}
func (f Folder) CreateCluster(ctx context.Context, cluster string, spec types.ClusterConfigSpecEx) (*ClusterComputeResource, error) {
req := types.CreateClusterEx{
This: f.Reference(),
Name: cluster,
Spec: spec,
}
res, err := methods.CreateClusterEx(ctx, f.c, &req)
if err != nil {
return nil, err
}
// Response will be nil if this is an ESX host that does not belong to a vCenter
if res == nil {
return nil, nil
}
return NewClusterComputeResource(f.c, res.Returnval), nil
}
func (f Folder) CreateFolder(ctx context.Context, name string) (*Folder, error) {
req := types.CreateFolder{
This: f.Reference(),
Name: name,
}
res, err := methods.CreateFolder(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewFolder(f.c, res.Returnval), err
}
func (f Folder) AddStandaloneHost(ctx context.Context, spec types.HostConnectSpec, addConnected bool, license *string, compResSpec *types.BaseComputeResourceConfigSpec) (*Task, error) {
req := types.AddStandaloneHost_Task{
This: f.Reference(),
Spec: spec,
AddConnected: addConnected,
}
if license != nil {
req.License = *license
}
if compResSpec != nil {
req.CompResSpec = *compResSpec
}
res, err := methods.AddStandaloneHost_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) CreateVM(ctx context.Context, config types.VirtualMachineConfigSpec, pool *ResourcePool, host *HostSystem) (*Task, error) {
req := types.CreateVM_Task{
This: f.Reference(),
Config: config,
Pool: pool.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.CreateVM_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) RegisterVM(ctx context.Context, path string, name string, asTemplate bool, pool *ResourcePool, host *HostSystem) (*Task, error) {
req := types.RegisterVM_Task{
This: f.Reference(),
Path: path,
AsTemplate: asTemplate,
}
if name != "" {
req.Name = name
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
if pool != nil {
ref := pool.Reference()
req.Pool = &ref
}
res, err := methods.RegisterVM_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}
func (f Folder) CreateDVS(ctx context.Context, spec types.DVSCreateSpec) (*Task, error) {
req := types.CreateDVS_Task{
This: f.Reference(),
Spec: spec,
}
res, err := methods.CreateDVS_Task(ctx, f.c, &req)
if err != nil {
return nil, err
}
return NewTask(f.c, res.Returnval), nil
}

View File

@@ -0,0 +1,71 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HistoryCollector struct {
Common
}
func NewHistoryCollector(c *vim25.Client, ref types.ManagedObjectReference) *HistoryCollector {
return &HistoryCollector{
Common: NewCommon(c, ref),
}
}
func (h HistoryCollector) Destroy(ctx context.Context) error {
req := types.DestroyCollector{
This: h.Reference(),
}
_, err := methods.DestroyCollector(ctx, h.c, &req)
return err
}
func (h HistoryCollector) Reset(ctx context.Context) error {
req := types.ResetCollector{
This: h.Reference(),
}
_, err := methods.ResetCollector(ctx, h.c, &req)
return err
}
func (h HistoryCollector) Rewind(ctx context.Context) error {
req := types.RewindCollector{
This: h.Reference(),
}
_, err := methods.RewindCollector(ctx, h.c, &req)
return err
}
func (h HistoryCollector) SetPageSize(ctx context.Context, maxCount int32) error {
req := types.SetCollectorPageSize{
This: h.Reference(),
MaxCount: maxCount,
}
_, err := methods.SetCollectorPageSize(ctx, h.c, &req)
return err
}

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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostConfigManager struct {
Common
}
func NewHostConfigManager(c *vim25.Client, ref types.ManagedObjectReference) *HostConfigManager {
return &HostConfigManager{
Common: NewCommon(c, ref),
}
}
func (m HostConfigManager) DatastoreSystem(ctx context.Context) (*HostDatastoreSystem, error) {
var h mo.HostSystem
err := m.Properties(ctx, m.Reference(), []string{"configManager.datastoreSystem"}, &h)
if err != nil {
return nil, err
}
return NewHostDatastoreSystem(m.c, *h.ConfigManager.DatastoreSystem), nil
}
func (m HostConfigManager) NetworkSystem(ctx context.Context) (*HostNetworkSystem, error) {
var h mo.HostSystem
err := m.Properties(ctx, m.Reference(), []string{"configManager.networkSystem"}, &h)
if err != nil {
return nil, err
}
return NewHostNetworkSystem(m.c, *h.ConfigManager.NetworkSystem), nil
}
func (m HostConfigManager) FirewallSystem(ctx context.Context) (*HostFirewallSystem, error) {
var h mo.HostSystem
err := m.Properties(ctx, m.Reference(), []string{"configManager.firewallSystem"}, &h)
if err != nil {
return nil, err
}
return NewHostFirewallSystem(m.c, *h.ConfigManager.FirewallSystem), nil
}
func (m HostConfigManager) StorageSystem(ctx context.Context) (*HostStorageSystem, error) {
var h mo.HostSystem
err := m.Properties(ctx, m.Reference(), []string{"configManager.storageSystem"}, &h)
if err != nil {
return nil, err
}
return NewHostStorageSystem(m.c, *h.ConfigManager.StorageSystem), nil
}
func (m HostConfigManager) VirtualNicManager(ctx context.Context) (*HostVirtualNicManager, error) {
var h mo.HostSystem
err := m.Properties(ctx, m.Reference(), []string{"configManager.virtualNicManager"}, &h)
if err != nil {
return nil, err
}
return NewHostVirtualNicManager(m.c, *h.ConfigManager.VirtualNicManager, m.Reference()), nil
}
func (m HostConfigManager) VsanSystem(ctx context.Context) (*HostVsanSystem, error) {
var h mo.HostSystem
err := m.Properties(ctx, m.Reference(), []string{"configManager.vsanSystem"}, &h)
if err != nil {
return nil, err
}
return NewHostVsanSystem(m.c, *h.ConfigManager.VsanSystem), nil
}

View File

@@ -0,0 +1,64 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostDatastoreBrowser struct {
Common
}
func NewHostDatastoreBrowser(c *vim25.Client, ref types.ManagedObjectReference) *HostDatastoreBrowser {
return &HostDatastoreBrowser{
Common: NewCommon(c, ref),
}
}
func (b HostDatastoreBrowser) SearchDatastore(ctx context.Context, datastorePath string, searchSpec *types.HostDatastoreBrowserSearchSpec) (*Task, error) {
req := types.SearchDatastore_Task{
This: b.Reference(),
DatastorePath: datastorePath,
SearchSpec: searchSpec,
}
res, err := methods.SearchDatastore_Task(ctx, b.c, &req)
if err != nil {
return nil, err
}
return NewTask(b.c, res.Returnval), nil
}
func (b HostDatastoreBrowser) SearchDatastoreSubFolders(ctx context.Context, datastorePath string, searchSpec *types.HostDatastoreBrowserSearchSpec) (*Task, error) {
req := types.SearchDatastoreSubFolders_Task{
This: b.Reference(),
DatastorePath: datastorePath,
SearchSpec: searchSpec,
}
res, err := methods.SearchDatastoreSubFolders_Task(ctx, b.c, &req)
if err != nil {
return nil, err
}
return NewTask(b.c, res.Returnval), nil
}

View File

@@ -0,0 +1,103 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostDatastoreSystem struct {
Common
}
func NewHostDatastoreSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostDatastoreSystem {
return &HostDatastoreSystem{
Common: NewCommon(c, ref),
}
}
func (s HostDatastoreSystem) CreateNasDatastore(ctx context.Context, spec types.HostNasVolumeSpec) (*Datastore, error) {
req := types.CreateNasDatastore{
This: s.Reference(),
Spec: spec,
}
res, err := methods.CreateNasDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) CreateVmfsDatastore(ctx context.Context, spec types.VmfsDatastoreCreateSpec) (*Datastore, error) {
req := types.CreateVmfsDatastore{
This: s.Reference(),
Spec: spec,
}
res, err := methods.CreateVmfsDatastore(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewDatastore(s.Client(), res.Returnval), nil
}
func (s HostDatastoreSystem) Remove(ctx context.Context, ds *Datastore) error {
req := types.RemoveDatastore{
This: s.Reference(),
Datastore: ds.Reference(),
}
_, err := methods.RemoveDatastore(ctx, s.Client(), &req)
if err != nil {
return err
}
return nil
}
func (s HostDatastoreSystem) QueryAvailableDisksForVmfs(ctx context.Context) ([]types.HostScsiDisk, error) {
req := types.QueryAvailableDisksForVmfs{
This: s.Reference(),
}
res, err := methods.QueryAvailableDisksForVmfs(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (s HostDatastoreSystem) QueryVmfsDatastoreCreateOptions(ctx context.Context, devicePath string) ([]types.VmfsDatastoreOption, error) {
req := types.QueryVmfsDatastoreCreateOptions{
This: s.Reference(),
DevicePath: devicePath,
}
res, err := methods.QueryVmfsDatastoreCreateOptions(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

View File

@@ -0,0 +1,181 @@
/*
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 object
import (
"errors"
"fmt"
"strings"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostFirewallSystem struct {
Common
}
func NewHostFirewallSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostFirewallSystem {
return &HostFirewallSystem{
Common: NewCommon(c, ref),
}
}
func (s HostFirewallSystem) DisableRuleset(ctx context.Context, id string) error {
req := types.DisableRuleset{
This: s.Reference(),
Id: id,
}
_, err := methods.DisableRuleset(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) EnableRuleset(ctx context.Context, id string) error {
req := types.EnableRuleset{
This: s.Reference(),
Id: id,
}
_, err := methods.EnableRuleset(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) Refresh(ctx context.Context) error {
req := types.RefreshFirewall{
This: s.Reference(),
}
_, err := methods.RefreshFirewall(ctx, s.c, &req)
return err
}
func (s HostFirewallSystem) Info(ctx context.Context) (*types.HostFirewallInfo, error) {
var fs mo.HostFirewallSystem
err := s.Properties(ctx, s.Reference(), []string{"firewallInfo"}, &fs)
if err != nil {
return nil, err
}
return fs.FirewallInfo, nil
}
// HostFirewallRulesetList provides helpers for a slice of types.HostFirewallRuleset
type HostFirewallRulesetList []types.HostFirewallRuleset
// ByRule returns a HostFirewallRulesetList where Direction, PortType and Protocol are equal and Port is within range
func (l HostFirewallRulesetList) ByRule(rule types.HostFirewallRule) HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
for _, r := range rs.Rule {
if r.PortType != rule.PortType ||
r.Protocol != rule.Protocol ||
r.Direction != rule.Direction {
continue
}
if r.EndPort == 0 && rule.Port == r.Port ||
rule.Port >= r.Port && rule.Port <= r.EndPort {
matches = append(matches, rs)
break
}
}
}
return matches
}
// EnabledByRule returns a HostFirewallRulesetList with Match(rule) applied and filtered via Enabled()
// if enabled param is true, otherwise filtered via Disabled().
// An error is returned if the resulting list is empty.
func (l HostFirewallRulesetList) EnabledByRule(rule types.HostFirewallRule, enabled bool) (HostFirewallRulesetList, error) {
var matched, skipped HostFirewallRulesetList
var matchedKind, skippedKind string
l = l.ByRule(rule)
if enabled {
matched = l.Enabled()
matchedKind = "enabled"
skipped = l.Disabled()
skippedKind = "disabled"
} else {
matched = l.Disabled()
matchedKind = "disabled"
skipped = l.Enabled()
skippedKind = "enabled"
}
if len(matched) == 0 {
msg := fmt.Sprintf("%d %s firewall rulesets match %s %s %s %d, %d %s rulesets match",
len(matched), matchedKind,
rule.Direction, rule.Protocol, rule.PortType, rule.Port,
len(skipped), skippedKind)
if len(skipped) != 0 {
msg += fmt.Sprintf(": %s", strings.Join(skipped.Keys(), ", "))
}
return nil, errors.New(msg)
}
return matched, nil
}
// Enabled returns a HostFirewallRulesetList with enabled rules
func (l HostFirewallRulesetList) Enabled() HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
if rs.Enabled {
matches = append(matches, rs)
}
}
return matches
}
// Disabled returns a HostFirewallRulesetList with disabled rules
func (l HostFirewallRulesetList) Disabled() HostFirewallRulesetList {
var matches HostFirewallRulesetList
for _, rs := range l {
if !rs.Enabled {
matches = append(matches, rs)
}
}
return matches
}
// Keys returns the HostFirewallRuleset.Key for each ruleset in the list
func (l HostFirewallRulesetList) Keys() []string {
var keys []string
for _, rs := range l {
keys = append(keys, rs.Key)
}
return keys
}

View File

@@ -0,0 +1,357 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostNetworkSystem struct {
Common
}
func NewHostNetworkSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostNetworkSystem {
return &HostNetworkSystem{
Common: NewCommon(c, ref),
}
}
// AddPortGroup wraps methods.AddPortGroup
func (o HostNetworkSystem) AddPortGroup(ctx context.Context, portgrp types.HostPortGroupSpec) error {
req := types.AddPortGroup{
This: o.Reference(),
Portgrp: portgrp,
}
_, err := methods.AddPortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// AddServiceConsoleVirtualNic wraps methods.AddServiceConsoleVirtualNic
func (o HostNetworkSystem) AddServiceConsoleVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error) {
req := types.AddServiceConsoleVirtualNic{
This: o.Reference(),
Portgroup: portgroup,
Nic: nic,
}
res, err := methods.AddServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// AddVirtualNic wraps methods.AddVirtualNic
func (o HostNetworkSystem) AddVirtualNic(ctx context.Context, portgroup string, nic types.HostVirtualNicSpec) (string, error) {
req := types.AddVirtualNic{
This: o.Reference(),
Portgroup: portgroup,
Nic: nic,
}
res, err := methods.AddVirtualNic(ctx, o.c, &req)
if err != nil {
return "", err
}
return res.Returnval, nil
}
// AddVirtualSwitch wraps methods.AddVirtualSwitch
func (o HostNetworkSystem) AddVirtualSwitch(ctx context.Context, vswitchName string, spec *types.HostVirtualSwitchSpec) error {
req := types.AddVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
Spec: spec,
}
_, err := methods.AddVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// QueryNetworkHint wraps methods.QueryNetworkHint
func (o HostNetworkSystem) QueryNetworkHint(ctx context.Context, device []string) error {
req := types.QueryNetworkHint{
This: o.Reference(),
Device: device,
}
_, err := methods.QueryNetworkHint(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RefreshNetworkSystem wraps methods.RefreshNetworkSystem
func (o HostNetworkSystem) RefreshNetworkSystem(ctx context.Context) error {
req := types.RefreshNetworkSystem{
This: o.Reference(),
}
_, err := methods.RefreshNetworkSystem(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemovePortGroup wraps methods.RemovePortGroup
func (o HostNetworkSystem) RemovePortGroup(ctx context.Context, pgName string) error {
req := types.RemovePortGroup{
This: o.Reference(),
PgName: pgName,
}
_, err := methods.RemovePortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveServiceConsoleVirtualNic wraps methods.RemoveServiceConsoleVirtualNic
func (o HostNetworkSystem) RemoveServiceConsoleVirtualNic(ctx context.Context, device string) error {
req := types.RemoveServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RemoveServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveVirtualNic wraps methods.RemoveVirtualNic
func (o HostNetworkSystem) RemoveVirtualNic(ctx context.Context, device string) error {
req := types.RemoveVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RemoveVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RemoveVirtualSwitch wraps methods.RemoveVirtualSwitch
func (o HostNetworkSystem) RemoveVirtualSwitch(ctx context.Context, vswitchName string) error {
req := types.RemoveVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
}
_, err := methods.RemoveVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// RestartServiceConsoleVirtualNic wraps methods.RestartServiceConsoleVirtualNic
func (o HostNetworkSystem) RestartServiceConsoleVirtualNic(ctx context.Context, device string) error {
req := types.RestartServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
}
_, err := methods.RestartServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateConsoleIpRouteConfig wraps methods.UpdateConsoleIpRouteConfig
func (o HostNetworkSystem) UpdateConsoleIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error {
req := types.UpdateConsoleIpRouteConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateConsoleIpRouteConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateDnsConfig wraps methods.UpdateDnsConfig
func (o HostNetworkSystem) UpdateDnsConfig(ctx context.Context, config types.BaseHostDnsConfig) error {
req := types.UpdateDnsConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateDnsConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateIpRouteConfig wraps methods.UpdateIpRouteConfig
func (o HostNetworkSystem) UpdateIpRouteConfig(ctx context.Context, config types.BaseHostIpRouteConfig) error {
req := types.UpdateIpRouteConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateIpRouteConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateIpRouteTableConfig wraps methods.UpdateIpRouteTableConfig
func (o HostNetworkSystem) UpdateIpRouteTableConfig(ctx context.Context, config types.HostIpRouteTableConfig) error {
req := types.UpdateIpRouteTableConfig{
This: o.Reference(),
Config: config,
}
_, err := methods.UpdateIpRouteTableConfig(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateNetworkConfig wraps methods.UpdateNetworkConfig
func (o HostNetworkSystem) UpdateNetworkConfig(ctx context.Context, config types.HostNetworkConfig, changeMode string) (*types.HostNetworkConfigResult, error) {
req := types.UpdateNetworkConfig{
This: o.Reference(),
Config: config,
ChangeMode: changeMode,
}
res, err := methods.UpdateNetworkConfig(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// UpdatePhysicalNicLinkSpeed wraps methods.UpdatePhysicalNicLinkSpeed
func (o HostNetworkSystem) UpdatePhysicalNicLinkSpeed(ctx context.Context, device string, linkSpeed *types.PhysicalNicLinkInfo) error {
req := types.UpdatePhysicalNicLinkSpeed{
This: o.Reference(),
Device: device,
LinkSpeed: linkSpeed,
}
_, err := methods.UpdatePhysicalNicLinkSpeed(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdatePortGroup wraps methods.UpdatePortGroup
func (o HostNetworkSystem) UpdatePortGroup(ctx context.Context, pgName string, portgrp types.HostPortGroupSpec) error {
req := types.UpdatePortGroup{
This: o.Reference(),
PgName: pgName,
Portgrp: portgrp,
}
_, err := methods.UpdatePortGroup(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateServiceConsoleVirtualNic wraps methods.UpdateServiceConsoleVirtualNic
func (o HostNetworkSystem) UpdateServiceConsoleVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error {
req := types.UpdateServiceConsoleVirtualNic{
This: o.Reference(),
Device: device,
Nic: nic,
}
_, err := methods.UpdateServiceConsoleVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateVirtualNic wraps methods.UpdateVirtualNic
func (o HostNetworkSystem) UpdateVirtualNic(ctx context.Context, device string, nic types.HostVirtualNicSpec) error {
req := types.UpdateVirtualNic{
This: o.Reference(),
Device: device,
Nic: nic,
}
_, err := methods.UpdateVirtualNic(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// UpdateVirtualSwitch wraps methods.UpdateVirtualSwitch
func (o HostNetworkSystem) UpdateVirtualSwitch(ctx context.Context, vswitchName string, spec types.HostVirtualSwitchSpec) error {
req := types.UpdateVirtualSwitch{
This: o.Reference(),
VswitchName: vswitchName,
Spec: spec,
}
_, err := methods.UpdateVirtualSwitch(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}

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 object
import (
"errors"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostStorageSystem struct {
Common
}
func NewHostStorageSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostStorageSystem {
return &HostStorageSystem{
Common: NewCommon(c, ref),
}
}
func (s HostStorageSystem) RetrieveDiskPartitionInfo(ctx context.Context, devicePath string) (*types.HostDiskPartitionInfo, error) {
req := types.RetrieveDiskPartitionInfo{
This: s.Reference(),
DevicePath: []string{devicePath},
}
res, err := methods.RetrieveDiskPartitionInfo(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil || len(res.Returnval) == 0 {
return nil, errors.New("no partition info")
}
return &res.Returnval[0], nil
}
func (s HostStorageSystem) ComputeDiskPartitionInfo(ctx context.Context, devicePath string, layout types.HostDiskPartitionLayout) (*types.HostDiskPartitionInfo, error) {
req := types.ComputeDiskPartitionInfo{
This: s.Reference(),
DevicePath: devicePath,
Layout: layout,
}
res, err := methods.ComputeDiskPartitionInfo(ctx, s.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (s HostStorageSystem) UpdateDiskPartitionInfo(ctx context.Context, devicePath string, spec types.HostDiskPartitionSpec) error {
req := types.UpdateDiskPartitions{
This: s.Reference(),
DevicePath: devicePath,
Spec: spec,
}
_, err := methods.UpdateDiskPartitions(ctx, s.c, &req)
return err
}

173
vendor/github.com/vmware/govmomi/object/host_system.go generated vendored Normal file
View File

@@ -0,0 +1,173 @@
/*
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 object
import (
"fmt"
"net"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostSystem struct {
Common
InventoryPath string
}
func (h HostSystem) String() string {
if h.InventoryPath == "" {
return h.Common.String()
}
return fmt.Sprintf("%v @ %v", h.Common, h.InventoryPath)
}
func NewHostSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostSystem {
return &HostSystem{
Common: NewCommon(c, ref),
}
}
func (h HostSystem) Name(ctx context.Context) (string, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"name"}, &mh)
if err != nil {
return "", err
}
return mh.Name, nil
}
func (h HostSystem) ConfigManager() *HostConfigManager {
return NewHostConfigManager(h.c, h.Reference())
}
func (h HostSystem) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"parent"}, &mh)
if err != nil {
return nil, err
}
var mcr *mo.ComputeResource
var parent interface{}
switch mh.Parent.Type {
case "ComputeResource":
mcr = new(mo.ComputeResource)
parent = mcr
case "ClusterComputeResource":
mcc := new(mo.ClusterComputeResource)
mcr = &mcc.ComputeResource
parent = mcc
default:
return nil, fmt.Errorf("unknown host parent type: %s", mh.Parent.Type)
}
err = h.Properties(ctx, *mh.Parent, []string{"resourcePool"}, parent)
if err != nil {
return nil, err
}
pool := NewResourcePool(h.c, *mcr.ResourcePool)
return pool, nil
}
func (h HostSystem) ManagementIPs(ctx context.Context) ([]net.IP, error) {
var mh mo.HostSystem
err := h.Properties(ctx, h.Reference(), []string{"config.virtualNicManagerInfo.netConfig"}, &mh)
if err != nil {
return nil, err
}
var ips []net.IP
for _, nc := range mh.Config.VirtualNicManagerInfo.NetConfig {
if nc.NicType == "management" && len(nc.CandidateVnic) > 0 {
ip := net.ParseIP(nc.CandidateVnic[0].Spec.Ip.IpAddress)
if ip != nil {
ips = append(ips, ip)
}
}
}
return ips, nil
}
func (h HostSystem) Disconnect(ctx context.Context) (*Task, error) {
req := types.DisconnectHost_Task{
This: h.Reference(),
}
res, err := methods.DisconnectHost_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) Reconnect(ctx context.Context, cnxSpec *types.HostConnectSpec, reconnectSpec *types.HostSystemReconnectSpec) (*Task, error) {
req := types.ReconnectHost_Task{
This: h.Reference(),
CnxSpec: cnxSpec,
ReconnectSpec: reconnectSpec,
}
res, err := methods.ReconnectHost_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) EnterMaintenanceMode(ctx context.Context, timeout int32, evacuate bool, spec *types.HostMaintenanceSpec) (*Task, error) {
req := types.EnterMaintenanceMode_Task{
This: h.Reference(),
Timeout: timeout,
EvacuatePoweredOffVms: types.NewBool(evacuate),
MaintenanceSpec: spec,
}
res, err := methods.EnterMaintenanceMode_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}
func (h HostSystem) ExitMaintenanceMode(ctx context.Context, timeout int32) (*Task, error) {
req := types.ExitMaintenanceMode_Task{
This: h.Reference(),
Timeout: timeout,
}
res, err := methods.ExitMaintenanceMode_Task(ctx, h.c, &req)
if err != nil {
return nil, err
}
return NewTask(h.c, res.Returnval), nil
}

View File

@@ -0,0 +1,92 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostVirtualNicManager struct {
Common
Host *HostSystem
}
func NewHostVirtualNicManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostVirtualNicManager {
return &HostVirtualNicManager{
Common: NewCommon(c, ref),
Host: NewHostSystem(c, host),
}
}
func (m HostVirtualNicManager) Info(ctx context.Context) (*types.HostVirtualNicManagerInfo, error) {
var vnm mo.HostVirtualNicManager
err := m.Properties(ctx, m.Reference(), []string{"info"}, &vnm)
if err != nil {
return nil, err
}
return &vnm.Info, nil
}
func (m HostVirtualNicManager) DeselectVnic(ctx context.Context, nicType string, device string) error {
if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
// Avoid fault.NotSupported:
// "Error deselecting device '$device': VSAN interfaces must be deselected using vim.host.VsanSystem"
s, err := m.Host.ConfigManager().VsanSystem(ctx)
if err != nil {
return err
}
return s.updateVnic(ctx, device, false)
}
req := types.DeselectVnicForNicType{
This: m.Reference(),
NicType: nicType,
Device: device,
}
_, err := methods.DeselectVnicForNicType(ctx, m.Client(), &req)
return err
}
func (m HostVirtualNicManager) SelectVnic(ctx context.Context, nicType string, device string) error {
if nicType == string(types.HostVirtualNicManagerNicTypeVsan) {
// Avoid fault.NotSupported:
// "Error selecting device '$device': VSAN interfaces must be selected using vim.host.VsanSystem"
s, err := m.Host.ConfigManager().VsanSystem(ctx)
if err != nil {
return err
}
return s.updateVnic(ctx, device, true)
}
req := types.SelectVnicForNicType{
This: m.Reference(),
NicType: nicType,
Device: device,
}
_, err := methods.SelectVnicForNicType(ctx, m.Client(), &req)
return err
}

View File

@@ -0,0 +1,87 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HostVsanSystem struct {
Common
}
func NewHostVsanSystem(c *vim25.Client, ref types.ManagedObjectReference) *HostVsanSystem {
return &HostVsanSystem{
Common: NewCommon(c, ref),
}
}
func (s HostVsanSystem) Update(ctx context.Context, config types.VsanHostConfigInfo) (*Task, error) {
req := types.UpdateVsan_Task{
This: s.Reference(),
Config: config,
}
res, err := methods.UpdateVsan_Task(ctx, s.Client(), &req)
if err != nil {
return nil, err
}
return NewTask(s.Client(), res.Returnval), nil
}
// updateVnic in support of the HostVirtualNicManager.{SelectVnic,DeselectVnic} methods
func (s HostVsanSystem) updateVnic(ctx context.Context, device string, enable bool) error {
var vsan mo.HostVsanSystem
err := s.Properties(ctx, s.Reference(), []string{"config.networkInfo.port"}, &vsan)
if err != nil {
return err
}
info := vsan.Config
var port []types.VsanHostConfigInfoNetworkInfoPortConfig
for _, p := range info.NetworkInfo.Port {
if p.Device == device {
continue
}
port = append(port, p)
}
if enable {
port = append(port, types.VsanHostConfigInfoNetworkInfoPortConfig{
Device: device,
})
}
info.NetworkInfo.Port = port
task, err := s.Update(ctx, info)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
return err
}

View File

@@ -0,0 +1,143 @@
/*
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 object
import (
"errors"
"fmt"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type HttpNfcLease struct {
Common
}
func NewHttpNfcLease(c *vim25.Client, ref types.ManagedObjectReference) *HttpNfcLease {
return &HttpNfcLease{
Common: NewCommon(c, ref),
}
}
// HttpNfcLeaseAbort wraps methods.HttpNfcLeaseAbort
func (o HttpNfcLease) HttpNfcLeaseAbort(ctx context.Context, fault *types.LocalizedMethodFault) error {
req := types.HttpNfcLeaseAbort{
This: o.Reference(),
Fault: fault,
}
_, err := methods.HttpNfcLeaseAbort(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// HttpNfcLeaseComplete wraps methods.HttpNfcLeaseComplete
func (o HttpNfcLease) HttpNfcLeaseComplete(ctx context.Context) error {
req := types.HttpNfcLeaseComplete{
This: o.Reference(),
}
_, err := methods.HttpNfcLeaseComplete(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// HttpNfcLeaseGetManifest wraps methods.HttpNfcLeaseGetManifest
func (o HttpNfcLease) HttpNfcLeaseGetManifest(ctx context.Context) error {
req := types.HttpNfcLeaseGetManifest{
This: o.Reference(),
}
_, err := methods.HttpNfcLeaseGetManifest(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
// HttpNfcLeaseProgress wraps methods.HttpNfcLeaseProgress
func (o HttpNfcLease) HttpNfcLeaseProgress(ctx context.Context, percent int32) error {
req := types.HttpNfcLeaseProgress{
This: o.Reference(),
Percent: percent,
}
_, err := methods.HttpNfcLeaseProgress(ctx, o.c, &req)
if err != nil {
return err
}
return nil
}
func (o HttpNfcLease) Wait(ctx context.Context) (*types.HttpNfcLeaseInfo, error) {
var lease mo.HttpNfcLease
pc := property.DefaultCollector(o.c)
err := property.Wait(ctx, pc, o.Reference(), []string{"state", "info", "error"}, func(pc []types.PropertyChange) bool {
done := false
for _, c := range pc {
if c.Val == nil {
continue
}
switch c.Name {
case "error":
val := c.Val.(types.LocalizedMethodFault)
lease.Error = &val
done = true
case "info":
val := c.Val.(types.HttpNfcLeaseInfo)
lease.Info = &val
case "state":
lease.State = c.Val.(types.HttpNfcLeaseState)
if lease.State != types.HttpNfcLeaseStateInitializing {
done = true
}
}
}
return done
})
if err != nil {
return nil, err
}
if lease.State == types.HttpNfcLeaseStateReady {
return lease.Info, nil
}
if lease.Error != nil {
return nil, errors.New(lease.Error.LocalizedMessage)
}
return nil, fmt.Errorf("unexpected nfc lease state: %s", lease.State)
}

43
vendor/github.com/vmware/govmomi/object/list_view.go generated vendored Normal file
View File

@@ -0,0 +1,43 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type ListView struct {
Common
}
func NewListView(c *vim25.Client, ref types.ManagedObjectReference) *ListView {
return &ListView{
Common: NewCommon(c, ref),
}
}
func (v ListView) Destroy(ctx context.Context) error {
req := types.DestroyView{
This: v.Reference(),
}
_, err := methods.DestroyView(ctx, v.c, &req)
return err
}

54
vendor/github.com/vmware/govmomi/object/network.go generated vendored Normal file
View File

@@ -0,0 +1,54 @@
/*
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 object
import (
"path"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type Network struct {
Common
InventoryPath string
}
func NewNetwork(c *vim25.Client, ref types.ManagedObjectReference) *Network {
return &Network{
Common: NewCommon(c, ref),
}
}
func (n Network) Name() string {
return path.Base(n.InventoryPath)
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n Network) EthernetCardBackingInfo(_ context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
name := n.Name()
backing := &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: name,
},
}
return backing, nil
}

View File

@@ -0,0 +1,30 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
Reference
EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}

103
vendor/github.com/vmware/govmomi/object/ovf_manager.go generated vendored Normal file
View File

@@ -0,0 +1,103 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type OvfManager struct {
Common
}
func NewOvfManager(c *vim25.Client) *OvfManager {
o := OvfManager{
Common: NewCommon(c, *c.ServiceContent.OvfManager),
}
return &o
}
// CreateDescriptor wraps methods.CreateDescriptor
func (o OvfManager) CreateDescriptor(ctx context.Context, obj Reference, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error) {
req := types.CreateDescriptor{
This: o.Reference(),
Obj: obj.Reference(),
Cdp: cdp,
}
res, err := methods.CreateDescriptor(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// CreateImportSpec wraps methods.CreateImportSpec
func (o OvfManager) CreateImportSpec(ctx context.Context, ovfDescriptor string, resourcePool Reference, datastore Reference, cisp types.OvfCreateImportSpecParams) (*types.OvfCreateImportSpecResult, error) {
req := types.CreateImportSpec{
This: o.Reference(),
OvfDescriptor: ovfDescriptor,
ResourcePool: resourcePool.Reference(),
Datastore: datastore.Reference(),
Cisp: cisp,
}
res, err := methods.CreateImportSpec(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// ParseDescriptor wraps methods.ParseDescriptor
func (o OvfManager) ParseDescriptor(ctx context.Context, ovfDescriptor string, pdp types.OvfParseDescriptorParams) (*types.OvfParseDescriptorResult, error) {
req := types.ParseDescriptor{
This: o.Reference(),
OvfDescriptor: ovfDescriptor,
Pdp: pdp,
}
res, err := methods.ParseDescriptor(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
// ValidateHost wraps methods.ValidateHost
func (o OvfManager) ValidateHost(ctx context.Context, ovfDescriptor string, host Reference, vhp types.OvfValidateHostParams) (*types.OvfValidateHostResult, error) {
req := types.ValidateHost{
This: o.Reference(),
OvfDescriptor: ovfDescriptor,
Host: host.Reference(),
Vhp: vhp,
}
res, err := methods.ValidateHost(ctx, o.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}

View File

@@ -0,0 +1,159 @@
/*
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 object
import (
"fmt"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type ResourcePool struct {
Common
InventoryPath string
}
func (p ResourcePool) String() string {
if p.InventoryPath == "" {
return p.Common.String()
}
return fmt.Sprintf("%v @ %v", p.Common, p.InventoryPath)
}
func NewResourcePool(c *vim25.Client, ref types.ManagedObjectReference) *ResourcePool {
return &ResourcePool{
Common: NewCommon(c, ref),
}
}
func (p ResourcePool) Name(ctx context.Context) (string, error) {
var o mo.ResourcePool
err := p.Properties(ctx, p.Reference(), []string{"name"}, &o)
if err != nil {
return "", err
}
return o.Name, nil
}
func (p ResourcePool) ImportVApp(ctx context.Context, spec types.BaseImportSpec, folder *Folder, host *HostSystem) (*HttpNfcLease, error) {
req := types.ImportVApp{
This: p.Reference(),
Spec: spec,
}
if folder != nil {
ref := folder.Reference()
req.Folder = &ref
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.ImportVApp(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewHttpNfcLease(p.c, res.Returnval), nil
}
func (p ResourcePool) Create(ctx context.Context, name string, spec types.ResourceConfigSpec) (*ResourcePool, error) {
req := types.CreateResourcePool{
This: p.Reference(),
Name: name,
Spec: spec,
}
res, err := methods.CreateResourcePool(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewResourcePool(p.c, res.Returnval), nil
}
func (p ResourcePool) CreateVApp(ctx context.Context, name string, resSpec types.ResourceConfigSpec, configSpec types.VAppConfigSpec, folder *Folder) (*VirtualApp, error) {
req := types.CreateVApp{
This: p.Reference(),
Name: name,
ResSpec: resSpec,
ConfigSpec: configSpec,
}
if folder != nil {
ref := folder.Reference()
req.VmFolder = &ref
}
res, err := methods.CreateVApp(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewVirtualApp(p.c, res.Returnval), nil
}
func (p ResourcePool) UpdateConfig(ctx context.Context, name string, config *types.ResourceConfigSpec) error {
req := types.UpdateConfig{
This: p.Reference(),
Name: name,
Config: config,
}
if config != nil && config.Entity == nil {
ref := p.Reference()
// Create copy of config so changes won't leak back to the caller
newConfig := *config
newConfig.Entity = &ref
req.Config = &newConfig
}
_, err := methods.UpdateConfig(ctx, p.c, &req)
return err
}
func (p ResourcePool) DestroyChildren(ctx context.Context) error {
req := types.DestroyChildren{
This: p.Reference(),
}
_, err := methods.DestroyChildren(ctx, p.c, &req)
return err
}
func (p ResourcePool) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: p.Reference(),
}
res, err := methods.Destroy_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}

162
vendor/github.com/vmware/govmomi/object/search_index.go generated vendored Normal file
View File

@@ -0,0 +1,162 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type SearchIndex struct {
Common
}
func NewSearchIndex(c *vim25.Client) *SearchIndex {
s := SearchIndex{
Common: NewCommon(c, *c.ServiceContent.SearchIndex),
}
return &s
}
// FindByDatastorePath finds a virtual machine by its location on a datastore.
func (s SearchIndex) FindByDatastorePath(ctx context.Context, dc *Datacenter, path string) (Reference, error) {
req := types.FindByDatastorePath{
This: s.Reference(),
Datacenter: dc.Reference(),
Path: path,
}
res, err := methods.FindByDatastorePath(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByDnsName finds a virtual machine or host by DNS name.
func (s SearchIndex) FindByDnsName(ctx context.Context, dc *Datacenter, dnsName string, vmSearch bool) (Reference, error) {
req := types.FindByDnsName{
This: s.Reference(),
DnsName: dnsName,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByDnsName(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByInventoryPath finds a managed entity based on its location in the inventory.
func (s SearchIndex) FindByInventoryPath(ctx context.Context, path string) (Reference, error) {
req := types.FindByInventoryPath{
This: s.Reference(),
InventoryPath: path,
}
res, err := methods.FindByInventoryPath(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByIp finds a virtual machine or host by IP address.
func (s SearchIndex) FindByIp(ctx context.Context, dc *Datacenter, ip string, vmSearch bool) (Reference, error) {
req := types.FindByIp{
This: s.Reference(),
Ip: ip,
VmSearch: vmSearch,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByIp(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindByUuid finds a virtual machine or host by UUID.
func (s SearchIndex) FindByUuid(ctx context.Context, dc *Datacenter, uuid string, vmSearch bool, instanceUuid *bool) (Reference, error) {
req := types.FindByUuid{
This: s.Reference(),
Uuid: uuid,
VmSearch: vmSearch,
InstanceUuid: instanceUuid,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.FindByUuid(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}
// FindChild finds a particular child based on a managed entity name.
func (s SearchIndex) FindChild(ctx context.Context, entity Reference, name string) (Reference, error) {
req := types.FindChild{
This: s.Reference(),
Entity: entity.Reference(),
Name: name,
}
res, err := methods.FindChild(ctx, s.c, &req)
if err != nil {
return nil, err
}
if res.Returnval == nil {
return nil, nil
}
return NewReference(s.c, *res.Returnval), nil
}

34
vendor/github.com/vmware/govmomi/object/storage_pod.go generated vendored Normal file
View File

@@ -0,0 +1,34 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type StoragePod struct {
*Folder
}
func NewStoragePod(c *vim25.Client, ref types.ManagedObjectReference) *StoragePod {
return &StoragePod{
Folder: &Folder{
Common: NewCommon(c, ref),
},
}
}

View File

@@ -0,0 +1,178 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type StorageResourceManager struct {
Common
}
func NewStorageResourceManager(c *vim25.Client) *StorageResourceManager {
sr := StorageResourceManager{
Common: NewCommon(c, *c.ServiceContent.StorageResourceManager),
}
return &sr
}
func (sr StorageResourceManager) ApplyStorageDrsRecommendation(ctx context.Context, key []string) (*Task, error) {
req := types.ApplyStorageDrsRecommendation_Task{
This: sr.Reference(),
Key: key,
}
res, err := methods.ApplyStorageDrsRecommendation_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) ApplyStorageDrsRecommendationToPod(ctx context.Context, pod *StoragePod, key string) (*Task, error) {
req := types.ApplyStorageDrsRecommendationToPod_Task{
This: sr.Reference(),
Key: key,
}
if pod != nil {
req.Pod = pod.Reference()
}
res, err := methods.ApplyStorageDrsRecommendationToPod_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) CancelStorageDrsRecommendation(ctx context.Context, key []string) error {
req := types.CancelStorageDrsRecommendation{
This: sr.Reference(),
Key: key,
}
_, err := methods.CancelStorageDrsRecommendation(ctx, sr.c, &req)
return err
}
func (sr StorageResourceManager) ConfigureDatastoreIORM(ctx context.Context, datastore *Datastore, spec types.StorageIORMConfigSpec, key string) (*Task, error) {
req := types.ConfigureDatastoreIORM_Task{
This: sr.Reference(),
Spec: spec,
}
if datastore != nil {
req.Datastore = datastore.Reference()
}
res, err := methods.ConfigureDatastoreIORM_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) ConfigureStorageDrsForPod(ctx context.Context, pod *StoragePod, spec types.StorageDrsConfigSpec, modify bool) (*Task, error) {
req := types.ConfigureStorageDrsForPod_Task{
This: sr.Reference(),
Spec: spec,
Modify: modify,
}
if pod != nil {
req.Pod = pod.Reference()
}
res, err := methods.ConfigureStorageDrsForPod_Task(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return NewTask(sr.c, res.Returnval), nil
}
func (sr StorageResourceManager) QueryDatastorePerformanceSummary(ctx context.Context, datastore *Datastore) ([]types.StoragePerformanceSummary, error) {
req := types.QueryDatastorePerformanceSummary{
This: sr.Reference(),
}
if datastore != nil {
req.Datastore = datastore.Reference()
}
res, err := methods.QueryDatastorePerformanceSummary(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
func (sr StorageResourceManager) QueryIORMConfigOption(ctx context.Context, host *HostSystem) (*types.StorageIORMConfigOption, error) {
req := types.QueryIORMConfigOption{
This: sr.Reference(),
}
if host != nil {
req.Host = host.Reference()
}
res, err := methods.QueryIORMConfigOption(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sr StorageResourceManager) RecommendDatastores(ctx context.Context, storageSpec types.StoragePlacementSpec) (*types.StoragePlacementResult, error) {
req := types.RecommendDatastores{
This: sr.Reference(),
StorageSpec: storageSpec,
}
res, err := methods.RecommendDatastores(ctx, sr.c, &req)
if err != nil {
return nil, err
}
return &res.Returnval, nil
}
func (sr StorageResourceManager) RefreshStorageDrsRecommendation(ctx context.Context, pod *StoragePod) error {
req := types.RefreshStorageDrsRecommendation{
This: sr.Reference(),
}
if pod != nil {
req.Pod = pod.Reference()
}
_, err := methods.RefreshStorageDrsRecommendation(ctx, sr.c, &req)
return err
}

52
vendor/github.com/vmware/govmomi/object/task.go generated vendored Normal file
View File

@@ -0,0 +1,52 @@
/*
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 object
import (
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/task"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// Task is a convenience wrapper around task.Task that keeps a reference to
// the client that was used to create it. This allows users to call the Wait()
// function with only a context parameter, instead of a context parameter, a
// soap.RoundTripper, and reference to the root property collector.
type Task struct {
Common
}
func NewTask(c *vim25.Client, ref types.ManagedObjectReference) *Task {
t := Task{
Common: NewCommon(c, ref),
}
return &t
}
func (t *Task) Wait(ctx context.Context) error {
_, err := t.WaitForResult(ctx, nil)
return err
}
func (t *Task) WaitForResult(ctx context.Context, s progress.Sinker) (*types.TaskInfo, error) {
p := property.DefaultCollector(t.c)
return task.Wait(ctx, t.Reference(), p, s)
}

65
vendor/github.com/vmware/govmomi/object/types.go generated vendored Normal file
View File

@@ -0,0 +1,65 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)
type Reference interface {
Reference() types.ManagedObjectReference
}
func NewReference(c *vim25.Client, e types.ManagedObjectReference) Reference {
switch e.Type {
case "Folder":
return NewFolder(c, e)
case "StoragePod":
return &StoragePod{
NewFolder(c, e),
}
case "Datacenter":
return NewDatacenter(c, e)
case "VirtualMachine":
return NewVirtualMachine(c, e)
case "VirtualApp":
return &VirtualApp{
NewResourcePool(c, e),
}
case "ComputeResource":
return NewComputeResource(c, e)
case "ClusterComputeResource":
return NewClusterComputeResource(c, e)
case "HostSystem":
return NewHostSystem(c, e)
case "Network":
return NewNetwork(c, e)
case "ResourcePool":
return NewResourcePool(c, e)
case "DistributedVirtualSwitch":
return NewDistributedVirtualSwitch(c, e)
case "VmwareDistributedVirtualSwitch":
return &VmwareDistributedVirtualSwitch{*NewDistributedVirtualSwitch(c, e)}
case "DistributedVirtualPortgroup":
return NewDistributedVirtualPortgroup(c, e)
case "Datastore":
return NewDatastore(c, e)
default:
panic("Unknown managed entity: " + e.Type)
}
}

126
vendor/github.com/vmware/govmomi/object/virtual_app.go generated vendored Normal file
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 object
import (
"fmt"
"golang.org/x/net/context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type VirtualApp struct {
*ResourcePool
}
func NewVirtualApp(c *vim25.Client, ref types.ManagedObjectReference) *VirtualApp {
return &VirtualApp{
ResourcePool: NewResourcePool(c, ref),
}
}
func (p VirtualApp) String() string {
if p.InventoryPath == "" {
return p.Common.String()
}
return fmt.Sprintf("%v @ %v", p.Common, p.InventoryPath)
}
func (p VirtualApp) Name(ctx context.Context) (string, error) {
var o mo.VirtualApp
err := p.Properties(ctx, p.Reference(), []string{"name"}, &o)
if err != nil {
return "", err
}
return o.Name, nil
}
func (p VirtualApp) CreateChildVM_Task(ctx context.Context, config types.VirtualMachineConfigSpec, host *HostSystem) (*Task, error) {
req := types.CreateChildVM_Task{
This: p.Reference(),
Config: config,
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
res, err := methods.CreateChildVM_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) UpdateVAppConfig(ctx context.Context, spec types.VAppConfigSpec) error {
req := types.UpdateVAppConfig{
This: p.Reference(),
Spec: spec,
}
_, err := methods.UpdateVAppConfig(ctx, p.c, &req)
return err
}
func (p VirtualApp) PowerOnVApp_Task(ctx context.Context) (*Task, error) {
req := types.PowerOnVApp_Task{
This: p.Reference(),
}
res, err := methods.PowerOnVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) PowerOffVApp_Task(ctx context.Context, force bool) (*Task, error) {
req := types.PowerOffVApp_Task{
This: p.Reference(),
Force: force,
}
res, err := methods.PowerOffVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}
func (p VirtualApp) SuspendVApp_Task(ctx context.Context) (*Task, error) {
req := types.SuspendVApp_Task{
This: p.Reference(),
}
res, err := methods.SuspendVApp_Task(ctx, p.c, &req)
if err != nil {
return nil, err
}
return NewTask(p.c, res.Returnval), nil
}

View File

@@ -0,0 +1,828 @@
/*
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 object
import (
"errors"
"fmt"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"github.com/vmware/govmomi/vim25/types"
)
// Type values for use in BootOrder
const (
DeviceTypeCdrom = "cdrom"
DeviceTypeDisk = "disk"
DeviceTypeEthernet = "ethernet"
DeviceTypeFloppy = "floppy"
)
// VirtualDeviceList provides helper methods for working with a list of virtual devices.
type VirtualDeviceList []types.BaseVirtualDevice
// SCSIControllerTypes are used for adding a new SCSI controller to a VM.
func SCSIControllerTypes() VirtualDeviceList {
// Return a mutable list of SCSI controller types, initialized with defaults.
return VirtualDeviceList([]types.BaseVirtualDevice{
&types.VirtualLsiLogicController{},
&types.VirtualBusLogicController{},
&types.ParaVirtualSCSIController{},
&types.VirtualLsiLogicSASController{},
}).Select(func(device types.BaseVirtualDevice) bool {
c := device.(types.BaseVirtualSCSIController).GetVirtualSCSIController()
c.SharedBus = types.VirtualSCSISharingNoSharing
c.BusNumber = -1
return true
})
}
// EthernetCardTypes are used for adding a new ethernet card to a VM.
func EthernetCardTypes() VirtualDeviceList {
return VirtualDeviceList([]types.BaseVirtualDevice{
&types.VirtualE1000{},
&types.VirtualE1000e{},
&types.VirtualVmxnet3{},
}).Select(func(device types.BaseVirtualDevice) bool {
c := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard()
c.AddressType = string(types.VirtualEthernetCardMacTypeGenerated)
c.GetVirtualDevice().Key = -1
return true
})
}
// Select returns a new list containing all elements of the list for which the given func returns true.
func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList {
var found VirtualDeviceList
for _, device := range l {
if f(device) {
found = append(found, device)
}
}
return found
}
// SelectByType returns a new list with devices that are equal to or extend the given type.
func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList {
dtype := reflect.TypeOf(deviceType)
dname := dtype.Elem().Name()
return l.Select(func(device types.BaseVirtualDevice) bool {
t := reflect.TypeOf(device)
if t == dtype {
return true
}
_, ok := t.Elem().FieldByName(dname)
return ok
})
}
// SelectByBackingInfo returns a new list with devices matching the given backing info.
// If the value of backing is nil, any device with a backing of the same type will be returned.
func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList {
t := reflect.TypeOf(backing)
return l.Select(func(device types.BaseVirtualDevice) bool {
db := device.GetVirtualDevice().Backing
if db == nil {
return false
}
if reflect.TypeOf(db) != t {
return false
}
if reflect.ValueOf(backing).IsNil() {
// selecting by backing type
return true
}
switch a := db.(type) {
case *types.VirtualEthernetCardNetworkBackingInfo:
b := backing.(*types.VirtualEthernetCardNetworkBackingInfo)
return a.DeviceName == b.DeviceName
case *types.VirtualEthernetCardDistributedVirtualPortBackingInfo:
b := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo)
return a.Port.SwitchUuid == b.Port.SwitchUuid &&
a.Port.PortgroupKey == b.Port.PortgroupKey
case *types.VirtualDiskFlatVer2BackingInfo:
b := backing.(*types.VirtualDiskFlatVer2BackingInfo)
if a.Parent != nil && b.Parent != nil {
return a.Parent.FileName == b.Parent.FileName
}
return a.FileName == b.FileName
case *types.VirtualSerialPortURIBackingInfo:
b := backing.(*types.VirtualSerialPortURIBackingInfo)
return a.ServiceURI == b.ServiceURI
case types.BaseVirtualDeviceFileBackingInfo:
b := backing.(types.BaseVirtualDeviceFileBackingInfo)
return a.GetVirtualDeviceFileBackingInfo().FileName == b.GetVirtualDeviceFileBackingInfo().FileName
default:
return false
}
})
}
// Find returns the device matching the given name.
func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice {
for _, device := range l {
if l.Name(device) == name {
return device
}
}
return nil
}
// FindByKey returns the device matching the given key.
func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice {
for _, device := range l {
if device.GetVirtualDevice().Key == key {
return device
}
}
return nil
}
// FindIDEController will find the named IDE controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an IDE controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualIDEController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not an IDE controller", name)
}
c := l.PickController((*types.VirtualIDEController)(nil))
if c == nil {
return nil, errors.New("no available IDE controller")
}
return c.(*types.VirtualIDEController), nil
}
// CreateIDEController creates a new IDE controller.
func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error) {
ide := &types.VirtualIDEController{}
ide.Key = l.NewKey()
return ide, nil
}
// FindSCSIController will find the named SCSI controller if given, otherwise will pick an available controller.
// An error is returned if the named controller is not found or not an SCSI controller. Or, if name is not
// given and no available controller can be found.
func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(types.BaseVirtualSCSIController); ok {
return c.GetVirtualSCSIController(), nil
}
return nil, fmt.Errorf("%s is not an SCSI controller", name)
}
c := l.PickController((*types.VirtualSCSIController)(nil))
if c == nil {
return nil, errors.New("no available SCSI controller")
}
return c.(types.BaseVirtualSCSIController).GetVirtualSCSIController(), nil
}
// CreateSCSIController creates a new SCSI controller of type name if given, otherwise defaults to lsilogic.
func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error) {
ctypes := SCSIControllerTypes()
if name == "scsi" || name == "" {
name = ctypes.Type(ctypes[0])
}
found := ctypes.Select(func(device types.BaseVirtualDevice) bool {
return l.Type(device) == name
})
if len(found) == 0 {
return nil, fmt.Errorf("unknown SCSI controller type '%s'", name)
}
c, ok := found[0].(types.BaseVirtualSCSIController)
if !ok {
return nil, fmt.Errorf("invalid SCSI controller type '%s'", name)
}
scsi := c.GetVirtualSCSIController()
scsi.BusNumber = l.newSCSIBusNumber()
scsi.Key = l.NewKey()
return c.(types.BaseVirtualDevice), nil
}
var scsiBusNumbers = []int{0, 1, 2, 3}
// newSCSIBusNumber returns the bus number to use for adding a new SCSI bus device.
// -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newSCSIBusNumber() int32 {
var used []int
for _, d := range l.SelectByType((*types.VirtualSCSIController)(nil)) {
num := d.(types.BaseVirtualSCSIController).GetVirtualSCSIController().BusNumber
if num >= 0 {
used = append(used, int(num))
} // else caller is creating a new vm using SCSIControllerTypes
}
sort.Ints(used)
for i, n := range scsiBusNumbers {
if i == len(used) || n != used[i] {
return int32(n)
}
}
return -1
}
// FindDiskController will find an existing ide or scsi disk controller.
func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error) {
switch {
case name == "ide":
return l.FindIDEController("")
case name == "scsi" || name == "":
return l.FindSCSIController("")
default:
if c, ok := l.Find(name).(types.BaseVirtualController); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a valid controller", name)
}
}
// PickController returns a controller of the given type(s).
// If no controllers are found or have no available slots, then nil is returned.
func (l VirtualDeviceList) PickController(kind types.BaseVirtualController) types.BaseVirtualController {
l = l.SelectByType(kind.(types.BaseVirtualDevice)).Select(func(device types.BaseVirtualDevice) bool {
num := len(device.(types.BaseVirtualController).GetVirtualController().Device)
switch device.(type) {
case types.BaseVirtualSCSIController:
return num < 15
case *types.VirtualIDEController:
return num < 2
default:
return true
}
})
if len(l) == 0 {
return nil
}
return l[0].(types.BaseVirtualController)
}
// newUnitNumber returns the unit number to use for attaching a new device to the given controller.
func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController) int32 {
key := c.GetVirtualController().Key
var max int32 = -1
for _, device := range l {
d := device.GetVirtualDevice()
if d.ControllerKey == key {
if d.UnitNumber != nil && *d.UnitNumber > max {
max = *d.UnitNumber
}
}
}
return max + 1
}
// NewKey returns the key to use for adding a new device to the device list.
// The device list we're working with here may not be complete (e.g. when
// we're only adding new devices), so any positive keys could conflict with device keys
// that are already in use. To avoid this type of conflict, we can use negative keys
// here, which will be resolved to positive keys by vSphere as the reconfiguration is done.
func (l VirtualDeviceList) NewKey() int32 {
var key int32 = -200
for _, device := range l {
d := device.GetVirtualDevice()
if d.Key < key {
key = d.Key
}
}
return key - 1
}
// AssignController assigns a device to a controller.
func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController) {
d := device.GetVirtualDevice()
d.ControllerKey = c.GetVirtualController().Key
d.UnitNumber = new(int32)
*d.UnitNumber = l.newUnitNumber(c)
if d.Key == 0 {
d.Key = -1
}
}
// CreateDisk creates a new VirtualDisk device which can be added to a VM.
func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk {
// If name is not specified, one will be chosen for you.
// But if when given, make sure it ends in .vmdk, otherwise it will be treated as a directory.
if len(name) > 0 && filepath.Ext(name) != ".vmdk" {
name += ".vmdk"
}
device := &types.VirtualDisk{
VirtualDevice: types.VirtualDevice{
Backing: &types.VirtualDiskFlatVer2BackingInfo{
DiskMode: string(types.VirtualDiskModePersistent),
ThinProvisioned: types.NewBool(true),
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: name,
Datastore: &ds,
},
},
},
}
l.AssignController(device, c)
return device
}
// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM.
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk {
disk := *parent
backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
ds := strings.SplitN(backing.FileName[1:], "]", 2)
// Use specified disk as parent backing to a new disk.
disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: fmt.Sprintf("[%s]", ds[0]),
Datastore: backing.Datastore,
},
Parent: backing,
DiskMode: backing.DiskMode,
ThinProvisioned: backing.ThinProvisioned,
}
return &disk
}
func (l VirtualDeviceList) connectivity(device types.BaseVirtualDevice, v bool) error {
c := device.GetVirtualDevice().Connectable
if c == nil {
return fmt.Errorf("%s is not connectable", l.Name(device))
}
c.Connected = v
c.StartConnected = v
return nil
}
// Connect changes the device to connected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error {
return l.connectivity(device, true)
}
// Disconnect changes the device to disconnected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error {
return l.connectivity(device, false)
}
// FindCdrom finds a cdrom device with the given name, defaulting to the first cdrom device if any.
func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualCdrom); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a cdrom device", name)
}
c := l.SelectByType((*types.VirtualCdrom)(nil))
if len(c) == 0 {
return nil, errors.New("no cdrom device found")
}
return c[0].(*types.VirtualCdrom), nil
}
// CreateCdrom creates a new VirtualCdrom device which can be added to a VM.
func (l VirtualDeviceList) CreateCdrom(c *types.VirtualIDEController) (*types.VirtualCdrom, error) {
device := &types.VirtualCdrom{}
l.AssignController(device, c)
l.setDefaultCdromBacking(device)
device.Connectable = &types.VirtualDeviceConnectInfo{
AllowGuestControl: true,
Connected: true,
StartConnected: true,
}
return device, nil
}
// InsertIso changes the cdrom device backing to use the given iso file.
func (l VirtualDeviceList) InsertIso(device *types.VirtualCdrom, iso string) *types.VirtualCdrom {
device.Backing = &types.VirtualCdromIsoBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: iso,
},
}
return device
}
// EjectIso removes the iso file based backing and replaces with the default cdrom backing.
func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom {
l.setDefaultCdromBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultCdromBacking(device *types.VirtualCdrom) {
device.Backing = &types.VirtualCdromAtapiBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: fmt.Sprintf("%s-%d-%d", DeviceTypeCdrom, device.ControllerKey, device.UnitNumber),
UseAutoDetect: types.NewBool(false),
},
}
}
// FindFloppy finds a floppy device with the given name, defaulting to the first floppy device if any.
func (l VirtualDeviceList) FindFloppy(name string) (*types.VirtualFloppy, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualFloppy); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a floppy device", name)
}
c := l.SelectByType((*types.VirtualFloppy)(nil))
if len(c) == 0 {
return nil, errors.New("no floppy device found")
}
return c[0].(*types.VirtualFloppy), nil
}
// CreateFloppy creates a new VirtualFloppy device which can be added to a VM.
func (l VirtualDeviceList) CreateFloppy() (*types.VirtualFloppy, error) {
device := &types.VirtualFloppy{}
c := l.PickController((*types.VirtualSIOController)(nil))
if c == nil {
return nil, errors.New("no available SIO controller")
}
l.AssignController(device, c)
l.setDefaultFloppyBacking(device)
device.Connectable = &types.VirtualDeviceConnectInfo{
AllowGuestControl: true,
Connected: true,
StartConnected: true,
}
return device, nil
}
// InsertImg changes the floppy device backing to use the given img file.
func (l VirtualDeviceList) InsertImg(device *types.VirtualFloppy, img string) *types.VirtualFloppy {
device.Backing = &types.VirtualFloppyImageBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
FileName: img,
},
}
return device
}
// EjectImg removes the img file based backing and replaces with the default floppy backing.
func (l VirtualDeviceList) EjectImg(device *types.VirtualFloppy) *types.VirtualFloppy {
l.setDefaultFloppyBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultFloppyBacking(device *types.VirtualFloppy) {
device.Backing = &types.VirtualFloppyDeviceBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: fmt.Sprintf("%s-%d", DeviceTypeFloppy, device.UnitNumber),
UseAutoDetect: types.NewBool(false),
},
}
}
// FindSerialPort finds a serial port device with the given name, defaulting to the first serial port device if any.
func (l VirtualDeviceList) FindSerialPort(name string) (*types.VirtualSerialPort, error) {
if name != "" {
d := l.Find(name)
if d == nil {
return nil, fmt.Errorf("device '%s' not found", name)
}
if c, ok := d.(*types.VirtualSerialPort); ok {
return c, nil
}
return nil, fmt.Errorf("%s is not a serial port device", name)
}
c := l.SelectByType((*types.VirtualSerialPort)(nil))
if len(c) == 0 {
return nil, errors.New("no serial port device found")
}
return c[0].(*types.VirtualSerialPort), nil
}
// CreateSerialPort creates a new VirtualSerialPort device which can be added to a VM.
func (l VirtualDeviceList) CreateSerialPort() (*types.VirtualSerialPort, error) {
device := &types.VirtualSerialPort{
YieldOnPoll: true,
}
c := l.PickController((*types.VirtualSIOController)(nil))
if c == nil {
return nil, errors.New("no available SIO controller")
}
l.AssignController(device, c)
l.setDefaultSerialPortBacking(device)
return device, nil
}
// ConnectSerialPort connects a serial port to a server or client uri.
func (l VirtualDeviceList) ConnectSerialPort(device *types.VirtualSerialPort, uri string, client bool) *types.VirtualSerialPort {
direction := types.VirtualDeviceURIBackingOptionDirectionServer
if client {
direction = types.VirtualDeviceURIBackingOptionDirectionClient
}
device.Backing = &types.VirtualSerialPortURIBackingInfo{
VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{
Direction: string(direction),
ServiceURI: uri,
},
}
return device
}
// DisconnectSerialPort disconnects the serial port backing.
func (l VirtualDeviceList) DisconnectSerialPort(device *types.VirtualSerialPort) *types.VirtualSerialPort {
l.setDefaultSerialPortBacking(device)
return device
}
func (l VirtualDeviceList) setDefaultSerialPortBacking(device *types.VirtualSerialPort) {
device.Backing = &types.VirtualSerialPortURIBackingInfo{
VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{
Direction: "client",
ServiceURI: "localhost:0",
},
}
}
// CreateEthernetCard creates a new VirtualEthernetCard of the given name name and initialized with the given backing.
func (l VirtualDeviceList) CreateEthernetCard(name string, backing types.BaseVirtualDeviceBackingInfo) (types.BaseVirtualDevice, error) {
ctypes := EthernetCardTypes()
if name == "" {
name = ctypes.deviceName(ctypes[0])
}
found := ctypes.Select(func(device types.BaseVirtualDevice) bool {
return l.deviceName(device) == name
})
if len(found) == 0 {
return nil, fmt.Errorf("unknown ethernet card type '%s'", name)
}
c, ok := found[0].(types.BaseVirtualEthernetCard)
if !ok {
return nil, fmt.Errorf("invalid ethernet card type '%s'", name)
}
c.GetVirtualEthernetCard().Backing = backing
return c.(types.BaseVirtualDevice), nil
}
// PrimaryMacAddress returns the MacAddress field of the primary VirtualEthernetCard
func (l VirtualDeviceList) PrimaryMacAddress() string {
eth0 := l.Find("ethernet-0")
if eth0 == nil {
return ""
}
return eth0.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard().MacAddress
}
// convert a BaseVirtualDevice to a BaseVirtualMachineBootOptionsBootableDevice
var bootableDevices = map[string]func(device types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice{
DeviceTypeCdrom: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableCdromDevice{}
},
DeviceTypeDisk: func(d types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableDiskDevice{
DeviceKey: d.GetVirtualDevice().Key,
}
},
DeviceTypeEthernet: func(d types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableEthernetDevice{
DeviceKey: d.GetVirtualDevice().Key,
}
},
DeviceTypeFloppy: func(types.BaseVirtualDevice) types.BaseVirtualMachineBootOptionsBootableDevice {
return &types.VirtualMachineBootOptionsBootableFloppyDevice{}
},
}
// BootOrder returns a list of devices which can be used to set boot order via VirtualMachine.SetBootOptions.
// The order can any of "ethernet", "cdrom", "floppy" or "disk" or by specific device name.
func (l VirtualDeviceList) BootOrder(order []string) []types.BaseVirtualMachineBootOptionsBootableDevice {
var devices []types.BaseVirtualMachineBootOptionsBootableDevice
for _, name := range order {
if kind, ok := bootableDevices[name]; ok {
for _, device := range l {
if l.Type(device) == name {
devices = append(devices, kind(device))
}
}
continue
}
if d := l.Find(name); d != nil {
if kind, ok := bootableDevices[l.Type(d)]; ok {
devices = append(devices, kind(d))
}
}
}
return devices
}
// SelectBootOrder returns an ordered list of devices matching the given bootable device order
func (l VirtualDeviceList) SelectBootOrder(order []types.BaseVirtualMachineBootOptionsBootableDevice) VirtualDeviceList {
var devices VirtualDeviceList
for _, bd := range order {
for _, device := range l {
if kind, ok := bootableDevices[l.Type(device)]; ok {
if reflect.DeepEqual(kind(device), bd) {
devices = append(devices, device)
}
}
}
}
return devices
}
// TypeName returns the vmodl type name of the device
func (l VirtualDeviceList) TypeName(device types.BaseVirtualDevice) string {
return reflect.TypeOf(device).Elem().Name()
}
var deviceNameRegexp = regexp.MustCompile(`(?:Virtual)?(?:Machine)?(\w+?)(?:Card|Device|Controller)?$`)
func (l VirtualDeviceList) deviceName(device types.BaseVirtualDevice) string {
name := "device"
typeName := l.TypeName(device)
m := deviceNameRegexp.FindStringSubmatch(typeName)
if len(m) == 2 {
name = strings.ToLower(m[1])
}
return name
}
// Type returns a human-readable name for the given device
func (l VirtualDeviceList) Type(device types.BaseVirtualDevice) string {
switch device.(type) {
case types.BaseVirtualEthernetCard:
return DeviceTypeEthernet
case *types.ParaVirtualSCSIController:
return "pvscsi"
case *types.VirtualLsiLogicSASController:
return "lsilogic-sas"
default:
return l.deviceName(device)
}
}
// Name returns a stable, human-readable name for the given device
func (l VirtualDeviceList) Name(device types.BaseVirtualDevice) string {
var key string
var UnitNumber int32
d := device.GetVirtualDevice()
if d.UnitNumber != nil {
UnitNumber = *d.UnitNumber
}
dtype := l.Type(device)
switch dtype {
case DeviceTypeEthernet:
key = fmt.Sprintf("%d", UnitNumber-7)
case DeviceTypeDisk:
key = fmt.Sprintf("%d-%d", d.ControllerKey, UnitNumber)
default:
key = fmt.Sprintf("%d", d.Key)
}
return fmt.Sprintf("%s-%s", dtype, key)
}
// ConfigSpec creates a virtual machine configuration spec for
// the specified operation, for the list of devices in the device list.
func (l VirtualDeviceList) ConfigSpec(op types.VirtualDeviceConfigSpecOperation) ([]types.BaseVirtualDeviceConfigSpec, error) {
var fop types.VirtualDeviceConfigSpecFileOperation
switch op {
case types.VirtualDeviceConfigSpecOperationAdd:
fop = types.VirtualDeviceConfigSpecFileOperationCreate
case types.VirtualDeviceConfigSpecOperationEdit:
fop = types.VirtualDeviceConfigSpecFileOperationReplace
case types.VirtualDeviceConfigSpecOperationRemove:
fop = types.VirtualDeviceConfigSpecFileOperationDestroy
default:
panic("unknown op")
}
var res []types.BaseVirtualDeviceConfigSpec
for _, device := range l {
config := &types.VirtualDeviceConfigSpec{
Device: device,
Operation: op,
}
if disk, ok := device.(*types.VirtualDisk); ok {
config.FileOperation = fop
// Special case to attach an existing disk
if op == types.VirtualDeviceConfigSpecOperationAdd && disk.CapacityInKB == 0 {
childDisk := false
if b, ok := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {
childDisk = b.Parent != nil
}
if !childDisk {
// Existing disk, clear file operation
config.FileOperation = ""
}
}
}
res = append(res, config)
}
return res, nil
}

View File

@@ -0,0 +1,145 @@
/*
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 object
import (
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
type VirtualDiskManager struct {
Common
}
func NewVirtualDiskManager(c *vim25.Client) *VirtualDiskManager {
m := VirtualDiskManager{
Common: NewCommon(c, *c.ServiceContent.VirtualDiskManager),
}
return &m
}
// CopyVirtualDisk copies a virtual disk, performing conversions as specified in the spec.
func (m VirtualDiskManager) CopyVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
destSpec *types.VirtualDiskSpec, force bool) (*Task, error) {
req := types.CopyVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
DestSpec: destSpec,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.CopyVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// CreateVirtualDisk creates a new virtual disk.
func (m VirtualDiskManager) CreateVirtualDisk(
ctx context.Context,
name string, datacenter *Datacenter,
spec types.BaseVirtualDiskSpec) (*Task, error) {
req := types.CreateVirtualDisk_Task{
This: m.Reference(),
Name: name,
Spec: spec,
}
if datacenter != nil {
ref := datacenter.Reference()
req.Datacenter = &ref
}
res, err := methods.CreateVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// MoveVirtualDisk moves a virtual disk.
func (m VirtualDiskManager) MoveVirtualDisk(
ctx context.Context,
sourceName string, sourceDatacenter *Datacenter,
destName string, destDatacenter *Datacenter,
force bool) (*Task, error) {
req := types.MoveVirtualDisk_Task{
This: m.Reference(),
SourceName: sourceName,
DestName: destName,
Force: types.NewBool(force),
}
if sourceDatacenter != nil {
ref := sourceDatacenter.Reference()
req.SourceDatacenter = &ref
}
if destDatacenter != nil {
ref := destDatacenter.Reference()
req.DestDatacenter = &ref
}
res, err := methods.MoveVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}
// DeleteVirtualDisk deletes a virtual disk.
func (m VirtualDiskManager) DeleteVirtualDisk(ctx context.Context, name string, dc *Datacenter) (*Task, error) {
req := types.DeleteVirtualDisk_Task{
This: m.Reference(),
Name: name,
}
if dc != nil {
ref := dc.Reference()
req.Datacenter = &ref
}
res, err := methods.DeleteVirtualDisk_Task(ctx, m.c, &req)
if err != nil {
return nil, err
}
return NewTask(m.c, res.Returnval), nil
}

View File

@@ -0,0 +1,468 @@
/*
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 object
import (
"errors"
"fmt"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
const (
PropRuntimePowerState = "summary.runtime.powerState"
)
type VirtualMachine struct {
Common
InventoryPath string
}
func (v VirtualMachine) String() string {
if v.InventoryPath == "" {
return v.Common.String()
}
return fmt.Sprintf("%v @ %v", v.Common, v.InventoryPath)
}
func NewVirtualMachine(c *vim25.Client, ref types.ManagedObjectReference) *VirtualMachine {
return &VirtualMachine{
Common: NewCommon(c, ref),
}
}
func (v VirtualMachine) Name(ctx context.Context) (string, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"name"}, &o)
if err != nil {
return "", err
}
return o.Name, nil
}
func (v VirtualMachine) PowerState(ctx context.Context) (types.VirtualMachinePowerState, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{PropRuntimePowerState}, &o)
if err != nil {
return "", err
}
return o.Summary.Runtime.PowerState, nil
}
func (v VirtualMachine) PowerOn(ctx context.Context) (*Task, error) {
req := types.PowerOnVM_Task{
This: v.Reference(),
}
res, err := methods.PowerOnVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) PowerOff(ctx context.Context) (*Task, error) {
req := types.PowerOffVM_Task{
This: v.Reference(),
}
res, err := methods.PowerOffVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Reset(ctx context.Context) (*Task, error) {
req := types.ResetVM_Task{
This: v.Reference(),
}
res, err := methods.ResetVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Suspend(ctx context.Context) (*Task, error) {
req := types.SuspendVM_Task{
This: v.Reference(),
}
res, err := methods.SuspendVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) ShutdownGuest(ctx context.Context) error {
req := types.ShutdownGuest{
This: v.Reference(),
}
_, err := methods.ShutdownGuest(ctx, v.c, &req)
return err
}
func (v VirtualMachine) RebootGuest(ctx context.Context) error {
req := types.RebootGuest{
This: v.Reference(),
}
_, err := methods.RebootGuest(ctx, v.c, &req)
return err
}
func (v VirtualMachine) Destroy(ctx context.Context) (*Task, error) {
req := types.Destroy_Task{
This: v.Reference(),
}
res, err := methods.Destroy_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Clone(ctx context.Context, folder *Folder, name string, config types.VirtualMachineCloneSpec) (*Task, error) {
req := types.CloneVM_Task{
This: v.Reference(),
Folder: folder.Reference(),
Name: name,
Spec: config,
}
res, err := methods.CloneVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Customize(ctx context.Context, spec types.CustomizationSpec) (*Task, error) {
req := types.CustomizeVM_Task{
This: v.Reference(),
Spec: spec,
}
res, err := methods.CustomizeVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Relocate(ctx context.Context, config types.VirtualMachineRelocateSpec, priority types.VirtualMachineMovePriority) (*Task, error) {
req := types.RelocateVM_Task{
This: v.Reference(),
Spec: config,
Priority: priority,
}
res, err := methods.RelocateVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) Reconfigure(ctx context.Context, config types.VirtualMachineConfigSpec) (*Task, error) {
req := types.ReconfigVM_Task{
This: v.Reference(),
Spec: config,
}
res, err := methods.ReconfigVM_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
func (v VirtualMachine) WaitForIP(ctx context.Context) (string, error) {
var ip string
p := property.DefaultCollector(v.c)
err := property.Wait(ctx, p, v.Reference(), []string{"guest.ipAddress"}, func(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Name != "guest.ipAddress" {
continue
}
if c.Op != types.PropertyChangeOpAssign {
continue
}
if c.Val == nil {
continue
}
ip = c.Val.(string)
return true
}
return false
})
if err != nil {
return "", err
}
return ip, nil
}
// Device returns the VirtualMachine's config.hardware.device property.
func (v VirtualMachine) Device(ctx context.Context) (VirtualDeviceList, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"config.hardware.device"}, &o)
if err != nil {
return nil, err
}
return VirtualDeviceList(o.Config.Hardware.Device), nil
}
func (v VirtualMachine) HostSystem(ctx context.Context) (*HostSystem, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"summary"}, &o)
if err != nil {
return nil, err
}
host := o.Summary.Runtime.Host
if host == nil {
return nil, errors.New("VM doesn't have a HostSystem")
}
return NewHostSystem(v.c, *host), nil
}
func (v VirtualMachine) ResourcePool(ctx context.Context) (*ResourcePool, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"resourcePool"}, &o)
if err != nil {
return nil, err
}
rp := o.ResourcePool
if rp == nil {
return nil, errors.New("VM doesn't have a resourcePool")
}
return NewResourcePool(v.c, *rp), nil
}
func (v VirtualMachine) configureDevice(ctx context.Context, op types.VirtualDeviceConfigSpecOperation, fop types.VirtualDeviceConfigSpecFileOperation, devices ...types.BaseVirtualDevice) error {
spec := types.VirtualMachineConfigSpec{}
for _, device := range devices {
config := &types.VirtualDeviceConfigSpec{
Device: device,
Operation: op,
}
if disk, ok := device.(*types.VirtualDisk); ok {
config.FileOperation = fop
// Special case to attach an existing disk
if op == types.VirtualDeviceConfigSpecOperationAdd && disk.CapacityInKB == 0 {
childDisk := false
if b, ok := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {
childDisk = b.Parent != nil
}
if !childDisk {
config.FileOperation = "" // existing disk
}
}
}
spec.DeviceChange = append(spec.DeviceChange, config)
}
task, err := v.Reconfigure(ctx, spec)
if err != nil {
return err
}
return task.Wait(ctx)
}
// AddDevice adds the given devices to the VirtualMachine
func (v VirtualMachine) AddDevice(ctx context.Context, device ...types.BaseVirtualDevice) error {
return v.configureDevice(ctx, types.VirtualDeviceConfigSpecOperationAdd, types.VirtualDeviceConfigSpecFileOperationCreate, device...)
}
// EditDevice edits the given (existing) devices on the VirtualMachine
func (v VirtualMachine) EditDevice(ctx context.Context, device ...types.BaseVirtualDevice) error {
return v.configureDevice(ctx, types.VirtualDeviceConfigSpecOperationEdit, types.VirtualDeviceConfigSpecFileOperationReplace, device...)
}
// RemoveDevice removes the given devices on the VirtualMachine
func (v VirtualMachine) RemoveDevice(ctx context.Context, device ...types.BaseVirtualDevice) error {
return v.configureDevice(ctx, types.VirtualDeviceConfigSpecOperationRemove, types.VirtualDeviceConfigSpecFileOperationDestroy, device...)
}
// BootOptions returns the VirtualMachine's config.bootOptions property.
func (v VirtualMachine) BootOptions(ctx context.Context) (*types.VirtualMachineBootOptions, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"config.bootOptions"}, &o)
if err != nil {
return nil, err
}
return o.Config.BootOptions, nil
}
// SetBootOptions reconfigures the VirtualMachine with the given options.
func (v VirtualMachine) SetBootOptions(ctx context.Context, options *types.VirtualMachineBootOptions) error {
spec := types.VirtualMachineConfigSpec{}
spec.BootOptions = options
task, err := v.Reconfigure(ctx, spec)
if err != nil {
return err
}
return task.Wait(ctx)
}
// Answer answers a pending question.
func (v VirtualMachine) Answer(ctx context.Context, id, answer string) error {
req := types.AnswerVM{
This: v.Reference(),
QuestionId: id,
AnswerChoice: answer,
}
_, err := methods.AnswerVM(ctx, v.c, &req)
if err != nil {
return err
}
return nil
}
// CreateSnapshot creates a new snapshot of a virtual machine.
func (v VirtualMachine) CreateSnapshot(ctx context.Context, name string, description string, memory bool, quiesce bool) (*Task, error) {
req := types.CreateSnapshot_Task{
This: v.Reference(),
Name: name,
Description: description,
Memory: memory,
Quiesce: quiesce,
}
res, err := methods.CreateSnapshot_Task(ctx, v.c, &req)
if err != nil {
return nil, err
}
return NewTask(v.c, res.Returnval), nil
}
// IsToolsRunning returns true if VMware Tools is currently running in the guest OS, and false otherwise.
func (v VirtualMachine) IsToolsRunning(ctx context.Context) (bool, error) {
var o mo.VirtualMachine
err := v.Properties(ctx, v.Reference(), []string{"guest.toolsRunningStatus"}, &o)
if err != nil {
return false, err
}
return o.Guest.ToolsRunningStatus == string(types.VirtualMachineToolsRunningStatusGuestToolsRunning), nil
}
// Wait for the VirtualMachine to change to the desired power state.
func (v VirtualMachine) WaitForPowerState(ctx context.Context, state types.VirtualMachinePowerState) error {
p := property.DefaultCollector(v.c)
err := property.Wait(ctx, p, v.Reference(), []string{PropRuntimePowerState}, func(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Name != PropRuntimePowerState {
continue
}
if c.Val == nil {
continue
}
ps := c.Val.(types.VirtualMachinePowerState)
if ps == state {
return true
}
}
return false
})
return err
}
func (v VirtualMachine) MarkAsTemplate(ctx context.Context) error {
req := types.MarkAsTemplate{
This: v.Reference(),
}
_, err := methods.MarkAsTemplate(ctx, v.c, &req)
if err != nil {
return err
}
return nil
}
func (v VirtualMachine) MarkAsVirtualMachine(ctx context.Context, pool ResourcePool, host *HostSystem) error {
req := types.MarkAsVirtualMachine{
This: v.Reference(),
Pool: pool.Reference(),
}
if host != nil {
ref := host.Reference()
req.Host = &ref
}
_, err := methods.MarkAsVirtualMachine(ctx, v.c, &req)
if err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,21 @@
/*
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 object
type VmwareDistributedVirtualSwitch struct {
DistributedVirtualSwitch
}