~nuage-canonical/charms/trusty/nuage-vsd/trunk

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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#!/usr/bin/python

import os
import sys
import time
import subprocess


ERROR = 1

def log(msg, level=1):
    print msg

charmconfig = {}
charmconfig['VSP_VM_NAME'] = 'vsc'
charmconfig['VSP_VM_DIR'] = '/home/ovs-6/charms/trusty/nuage-vsc/payload/'
charmconfig['VSP_VM_XML'] = 'vsc.xml'
charmconfig['VSP_VM_IMAGE_NAME'] = 'nuage_vsc.img'
charmconfig['VSP_VM_ORIG_IMAGE_NAME'] = 'vsc_singledisk.qcow2'
charmconfig['VSP_VM_IMAGE_DIR'] = '/home/ovs-6/charms/trusty/nuage-vsc/payload/'

def is_vm_running():
    try:
        run_state = subprocess.check_output(['bash', '-c', 'sudo virsh list --all | grep ${VSP_VM_NAME} | awk \'{print $NF}\')'])
        if run_state == 'running':
            return True
        else:
            return False
    except subprocess.CalledProcessError, e:
        log("Error: is_vm_running Failed with error:{}".format(e.returncode), level=ERROR)
        return None

def _run_virsh_command(cmd, vmconfig):
    """
    Run virsh command, checking output

    :param: cmd: str: The virsh command to run.
    """
    env = os.environ.copy()
    for key, value in vmconfig.iteritems():
        env[key] = value

    #env['VSP_VM_NAME'] = vmconfig['VSP_VM_NAME']
    #env['VSP_VM_DIR'] = vmconfig['VSP_VM_DIR']
    #env['VSP_VM_XML'] = vmconfig['VSP_VM_XML']
    #env['VSP_VM_IMAGE_NAME'] = vmconfig['VSP_VM_IMAGE_NAME']
    #env['VSP_VM_ORIG_IMAGE_NAME'] = vmconfig['VSP_VM_ORIG_IMAGE_NAME']
    #env['VSP_VM_IMAGE_DIR'] = vmconfig['VSP_VM_IMAGE_DIR']

    try:
        log("execute virsh cmd {0}\n".format(cmd))
        resultstr = subprocess.check_output(cmd, env=env)
    except ValueError:
        log("Error: virsh cmd {0} Failed with error:{1}".format(cmd, resultstr), level=ERROR)
        sys.exit(1)
    except subprocess.CalledProcessError, e:
        log("Error: virsh cmd {0} Failed with error:{1}".format(cmd, e.returncode), level=ERROR)
        sys.exit(1)
    log("virsh cmd result: {0}\n".format(resultstr))
    return resultstr


def createvm(vmconfig):
    _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && create_vsp_vm'], vmconfig)
    log("{} is successfully created.".format(vmconfig['VSP_VM_NAME']))
def startvm(vmconfig):
    _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && start_vsp_vm'], vmconfig)
    log("{} is successfully started.".format(vmconfig['VSP_VM_NAME']))


def stopvm(vmconfig):
    _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && stop_vsp_vm'], vmconfig)
    log("{} is successfully shutdown.".format(vmconfig['VSP_VM_NAME']))

def get_vm_ip_address(vmconfig):
    vm_ip_address = _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && get_vsp_vm_ip_address'], vmconfig)
    return vm_ip_address
    #for mac in `virsh domiflist vsc |grep -o -E "([0-9a-f]{2}:){5}([0-9a-f]{2})"` ; do arp -e |grep $mac  |grep -o -P "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" ; done

def get_domain_name(ip_address):
    try:
        result_str = subprocess.check_output(['bash', '-c', 'nslookup {} | grep -o -E \"name = .*.[net|com|org]\"'.format(ip_address)])
        if result_str.startswith('name = '):
            domain_name = result_str.replace('name = ', '')
        else:
            domain_name = None
        return domain_name
    except subprocess.CalledProcessError, e:
        log("Error: get_domain_name Failed with error:{}".format(e.returncode), level=ERROR)
        return None


    return vm_ip_address

import pexpect
def update_vsd_domain(vsc_host, username, password, vsd_domain):
    ssh_newkey = 'Are you sure you want to continue connecting'
    child = pexpect.spawn('ssh %s@%s' % (username, vsc_host))
    log('ssh %s@%s' % (username, vsc_host))
    i=child.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
    if i==0:
        print "I say yes"
        child.sendline('yes')
        i=child.expect([ssh_newkey,'password:',pexpect.EOF])
    if i==1:
        print "I give password",
        child.sendline(password)
    elif i==2:
        print "I either got key or connection timeout"
        pass
    elif i==3: #timeout
        pass
    child.sendline("\r")
    child.sendline("configure vswitch-controller xmpp-server \"{}\"".format(vsd_domain))
    #child.interact()

import paramiko

def update_vsd_domain1(vsc_host, username, password, vsd_domain):
    paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(vsc_host, username, password=password, timeout=120)
    except Exception as e:
        err = 'Error(%s): Unable to ssh to VSM VM (%s)' % (e, vsc_host)

    stdin, stdout, stderr = ssh.exec_command("configure vswitch-controller xmpp-server \"{}\"".format(vsd_domain))
    msg = stdout.readlines()
    stdin, stdout, stderr = ssh.exec_command("show vswitch-controller xmpp-server")
    msg = stdout.readlines()
    if str(msg).find(vsd_domain) == -1:
        err = 'Error: {0}:{1} is not set' % (msg, vsd_domain)
    ssh.close()