美文网首页
封装govmomi操作vsphere

封装govmomi操作vsphere

作者: brownchen | 来源:发表于2020-06-24 16:36 被阅读0次

    最近由于公司需求,需要云管平台操作vsphere,大致看了govmomi源码后用golang封装了操作vsphere的常用方法:

    • TestFindAllVM 列出vsphere中所有vm名及其uuid
    • TestFindVMByUuid 根据uuid查找vm
    • TestVMPowerOff 关闭vm
    • TestVMPowerOn 开启vm
    • TestResizeVMCPU 修改vm cpu
    • TestResizeVMMem 修改vm 内存
    • TestCreateDisk vm新增磁盘
    • TestVMDestory 销毁vm
    package test
    
    import (
        "context"
        "encoding/json"
        "fmt"
        "net/url"
        "testing"
    
        "github.com/vmware/govmomi"
        "github.com/vmware/govmomi/object"
        "github.com/vmware/govmomi/view"
        "github.com/vmware/govmomi/vim25"
        "github.com/vmware/govmomi/vim25/mo"
        "github.com/vmware/govmomi/vim25/types"
    )
    
    const (
        ip       = ""
        user     = ""
        password = ""
    )
    
    func Conn() (*vim25.Client, error) {
        ctx := context.Background()
        u := &url.URL{
            Scheme: "https",
            Host:   ip,
            Path:   "/sdk",
        }
        u.User = url.UserPassword(user, password)
        client, err := govmomi.NewClient(ctx, u, true)
        if err != nil {
            return nil, err
        }
        return client.Client, nil
    }
    func GetVM() (*object.VirtualMachine, error) {
        ctx := context.Background()
        c, err := Conn()
        if err != nil {
            return nil, err
        }
        uuid := "42320b75-02a3-3e4f-6fbe-31175fef0f06"
        // uuid := "4232d9d2-d01d-1dfc-0a8a-df2f8437df16"
        searchIndex := object.NewSearchIndex(c)
        reference, err := searchIndex.FindByUuid(ctx, nil, uuid, true, nil)
        if reference == nil {
            return nil, err
        }
        vm := object.NewVirtualMachine(c, reference.Reference())
        return vm, nil
    }
    
    func TestConn(t *testing.T) {
    
        u := &url.URL{
            Scheme: "https",
            Host:   ip,
            Path:   "/sdk",
        }
        ctx := context.Background()
        u.User = url.UserPassword(user, password)
        client, err := govmomi.NewClient(ctx, u, true)
        if err != nil {
            panic(err)
        }
        fmt.Println(client)
    }
    
    func TestFindAllVM(t *testing.T) {
        ctx := context.Background()
        c, err := Conn()
        if err != nil {
            panic(err)
        }
        m := view.NewManager(c)
        v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)
        if err != nil {
            panic(err)
        }
        defer v.Destroy(ctx)
        var vms []mo.VirtualMachine
        err = v.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary"}, &vms)
        if err != nil {
            panic(err)
        }
        for _, vm := range vms {
            fmt.Printf("Name:%s, UUID:%s\n", vm.Summary.Config.Name, vm.Summary.Config.Uuid)
        }
    }
    
    func TestFindVMByUuid(t *testing.T) {
        ctx := context.Background()
        c, err := Conn()
        if err != nil {
            panic(err)
        }
        // uuid := "42322ae0-6dd5-fe3a-539e-6603aeab80d4"
        uuid := "4232d9d2-d01d-1dfc-0a8a-df2f8437df16"
        searchIndex := object.NewSearchIndex(c)
        reference, err := searchIndex.FindByUuid(ctx, nil, uuid, true, nil)
        if reference == nil {
            panic("vm not found")
        }
        vm := object.NewVirtualMachine(c, reference.Reference())
        fmt.Println(vm)
    }
    
    func TestVMPowerOff(t *testing.T) {
        ctx := context.Background()
        vm, err := GetVM()
        if err != nil {
            panic(err)
        }
        task, err := vm.PowerOff(ctx)
        if err != nil {
            panic(err)
        }
        err = task.Wait(ctx)
        if err != nil {
            panic(err)
        }
        fmt.Println("vm is poweroff.")
    }
    
    func TestVMPowerOn(t *testing.T) {
        ctx := context.Background()
        vm, err := GetVM()
        if err != nil {
            panic(err)
        }
        task, err := vm.PowerOn(ctx)
        if err != nil {
            panic(err)
        }
        err = task.Wait(ctx)
        if err != nil {
            panic(err)
        }
        fmt.Println("vm is poweron.")
    }
    
    func TestResizeVMCPU(t *testing.T) {
        ctx := context.Background()
        vm, err := GetVM()
        if err != nil {
            panic(err)
        }
        config := types.VirtualMachineConfigSpec{
            NumCPUs: 2,
        }
        task, err := vm.Reconfigure(ctx, config)
        if err != nil {
            panic(err)
        }
        err = task.Wait(ctx)
        if err != nil {
            panic(err)
        }
        fmt.Println("resize cpu ok")
    }
    
    func TestResizeVMMem(t *testing.T) {
        ctx := context.Background()
        vm, err := GetVM()
        if err != nil {
            panic(err)
        }
        config := types.VirtualMachineConfigSpec{
            MemoryMB: 2 * 1024,
        }
        task, err := vm.Reconfigure(ctx, config)
        if err != nil {
            panic(err)
        }
        err = task.Wait(ctx)
        if err != nil {
            panic(err)
        }
        fmt.Println("resize mem ok")
    }
    
    func NewBool(v bool) *bool {
        return &v
    }
    func NewInt32(v int32) *int32 {
        return &v
    }
    func TestCreateDisk(t *testing.T) {
        ctx := context.Background()
        vm, err := GetVM()
        if err != nil {
            panic(err)
        }
        spec := types.VirtualMachineConfigSpec{}
        config := &types.VirtualDeviceConfigSpec{
            Operation:     types.VirtualDeviceConfigSpecOperationAdd,
            FileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,
            Device: &types.VirtualDisk{
                VirtualDevice: types.VirtualDevice{
                    Key:           2002,
                    ControllerKey: 1000,
                    UnitNumber:    NewInt32(3), // zero default value
                    Backing: &types.VirtualDiskFlatVer2BackingInfo{
                        DiskMode:        string(types.VirtualDiskModePersistent),
                        ThinProvisioned: NewBool(false),
                        VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
                            FileName: "[datastore1]",
                        },
                    },
                },
                CapacityInKB: 30 * 1024 * 1024,
            },
        }
        spec.DeviceChange = append(spec.DeviceChange, config)
        task, err := vm.Reconfigure(ctx, spec)
        if err != nil {
            panic(err)
        }
        err = task.Wait(ctx)
        if err != nil {
            panic(err)
        }
    }
    
    func TestVMDestory(t *testing.T) {
        ctx := context.Background()
        vm, err := GetVM()
        if err != nil {
            panic(err)
        }
        task, err := vm.Destroy(ctx)
        if err != nil {
            panic(err)
        }
        err = task.Wait(ctx)
        if err != nil {
            panic(err)
        }
        fmt.Println("vm is destory.")
    }
    

    相关文章

      网友评论

          本文标题:封装govmomi操作vsphere

          本文链接:https://www.haomeiwen.com/subject/baorfktx.html