summaryrefslogtreecommitdiffstats
path: root/vio/vio/vsphere/utils.py
blob: 8d2a648867f9fd9a110b301a9c51c51dc1ba91c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from pyVim import connect
from pyVmomi import vim

import os
# import json
import yaml

vcontent = None


def get_obj(content, vimtype, name):
    """
    Return an object by name, if name is None the
    first found object is returned
    """
    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for c in container.view:
        if name:
            if c.name == name:
                obj = c
                break
        else:
            obj = c
            break

    return obj


def get_objs(content, vimtype):
    """
    Get all the vsphere objects associated with a given type
    """
    obj = {}
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for c in container.view:
        obj.update({c: c.name})
    return obj


def wait_for_task(task):
    """ wait for a vCenter task to finish """
    task_done = False
    while not task_done:
        if task.info.state == 'success':
            return task.info.result

        if task.info.state == 'error':
            print("there was an error")
            task_done = True


def GetClient():
    global vcontent
    if vcontent is not None:
        return vcontent
    vsphere_conf_path = os.getenv("VSPHERE_CONF", "/opt/etc/vsphere.yml")
    vsphere_conf = yaml.load(open(vsphere_conf_path, "r"))['vsphere']
    # vsphere_conf = json.load(open(vsphere_conf_path, "r"))['vsphere']
    host = vsphere_conf['host']
    username = vsphere_conf['username']
    password = vsphere_conf['password']
    insecure = vsphere_conf.get("insecure", True)
    if insecure:
        service_instance = connect.SmartConnectNoSSL(
            host=host, user=username, pwd=password)
    else:
        service_instance = connect.SmartConnect(
            host=host, user=username, pwd=password, port=443)
    vcontent = service_instance.RetrieveContent()
    return vcontent


def CloneVM(src, dst, power_on=False, wait=True):
    assert src != dst
    vcontent = GetClient()
    vm = get_obj(vcontent, [vim.VirtualMachine], src)
    print("src vm:", vm)
    relospec = vim.vm.RelocateSpec(pool=vm.resourcePool)
    clonespec = vim.vm.CloneSpec(location=relospec)
    clonespec.powerOn = power_on
    task = vm.Clone(name=dst, folder=vm.parent, spec=clonespec)
    print("clone task:", task)
    if wait:
        print("wait for task:", task)
        result = wait_for_task(task)
        print("task result:", result)
    return task


def DeployOVA(src, datacenter, resource_pool, datastore):
    pass