packer-cn/builder/vsphere/driver/folder.go

94 lines
1.9 KiB
Go
Raw Normal View History

2017-08-23 17:23:29 -04:00
package driver
import (
2018-10-31 17:42:24 -04:00
"fmt"
2020-06-10 09:12:21 -04:00
"path"
2020-06-11 10:37:24 -04:00
"strings"
2020-06-11 10:37:24 -04:00
"github.com/vmware/govmomi/find"
2017-08-23 17:23:29 -04:00
"github.com/vmware/govmomi/object"
2017-08-23 17:54:23 -04:00
"github.com/vmware/govmomi/vim25/mo"
2018-10-31 17:42:24 -04:00
"github.com/vmware/govmomi/vim25/types"
2017-08-23 17:23:29 -04:00
)
2017-08-23 20:06:50 -04:00
type Folder struct {
driver *VCenterDriver
2017-08-23 20:06:50 -04:00
folder *object.Folder
2017-08-23 17:23:29 -04:00
}
func (d *VCenterDriver) NewFolder(ref *types.ManagedObjectReference) *Folder {
2017-08-23 20:06:50 -04:00
return &Folder{
folder: object.NewFolder(d.client.Client, *ref),
driver: d,
}
}
func (d *VCenterDriver) FindFolder(name string) (*Folder, error) {
2020-06-11 10:37:24 -04:00
if name != "" {
// create folders if they don't exist
parent := ""
parentFolder, err := d.finder.Folder(d.ctx, path.Join(d.datacenter.InventoryPath, "vm"))
if err != nil {
return nil, err
}
folders := strings.Split(name, "/")
for _, folder := range folders {
parent = path.Join(parent, folder)
f, err := d.finder.Folder(d.ctx, path.Join(d.datacenter.InventoryPath, "vm", parent))
if _, ok := err.(*find.NotFoundError); ok {
f, err = parentFolder.CreateFolder(d.ctx, folder)
}
if err != nil {
return nil, err
}
parentFolder = f
}
}
2020-06-10 09:12:21 -04:00
f, err := d.finder.Folder(d.ctx, path.Join(d.datacenter.InventoryPath, "vm", name))
2017-08-23 20:06:50 -04:00
if err != nil {
return nil, err
}
2020-06-11 10:37:24 -04:00
2017-08-23 20:06:50 -04:00
return &Folder{
folder: f,
driver: d,
}, nil
}
func (f *Folder) Info(params ...string) (*mo.Folder, error) {
2017-08-23 17:54:23 -04:00
var p []string
if len(params) == 0 {
p = []string{"*"}
} else {
p = params
}
2017-08-23 20:06:50 -04:00
var info mo.Folder
err := f.folder.Properties(f.driver.ctx, f.folder.Reference(), p, &info)
2017-08-23 17:54:23 -04:00
if err != nil {
return nil, err
}
2017-08-23 20:06:50 -04:00
return &info, nil
2017-08-23 17:54:23 -04:00
}
2017-08-23 20:06:50 -04:00
func (f *Folder) Path() (string, error) {
info, err := f.Info("name", "parent")
2017-08-23 17:54:23 -04:00
if err != nil {
return "", err
}
2017-08-23 20:06:50 -04:00
if info.Parent.Type == "Datacenter" {
2017-08-23 17:54:23 -04:00
return "", nil
} else {
2017-08-23 20:06:50 -04:00
parent := f.driver.NewFolder(info.Parent)
path, err := parent.Path()
2017-08-23 17:54:23 -04:00
if err != nil {
return "", err
}
2017-08-23 20:06:50 -04:00
if path == "" {
return info.Name, nil
2017-08-23 17:54:23 -04:00
} else {
2017-08-23 20:06:50 -04:00
return fmt.Sprintf("%v/%v", path, info.Name), nil
2017-08-23 17:54:23 -04:00
}
}
2017-08-23 17:23:29 -04:00
}