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

« back to all changes in this revision

Viewing changes to hooks/virshutils.py

  • Committer: Subbarayudu Mukkamala
  • Date: 2014-10-19 23:13:25 UTC
  • Revision ID: smukkamala@nuagenetworks.net-20141019231325-bu5f2dtlb7noru38
create nuage-vsd charm

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
 
 
3
import os
 
4
import sys
 
5
import time
 
6
import subprocess
 
7
 
 
8
 
 
9
ERROR = 1
 
10
 
 
11
def log(msg, level=1):
 
12
    print msg
 
13
 
 
14
charmconfig = {}
 
15
charmconfig['VSP_VM_NAME'] = 'vsc'
 
16
charmconfig['VSP_VM_DIR'] = '/home/ovs-6/charms/trusty/nuage-vsc/payload/'
 
17
charmconfig['VSP_VM_XML'] = 'vsc.xml'
 
18
charmconfig['VSP_VM_IMAGE_NAME'] = 'nuage_vsc.img'
 
19
charmconfig['VSP_VM_ORIG_IMAGE_NAME'] = 'vsc_singledisk.qcow2'
 
20
charmconfig['VSP_VM_IMAGE_DIR'] = '/home/ovs-6/charms/trusty/nuage-vsc/payload/'
 
21
 
 
22
def is_vm_running():
 
23
    try:
 
24
        run_state = subprocess.check_output(['bash', '-c', 'sudo virsh list --all | grep ${VSP_VM_NAME} | awk \'{print $NF}\')'])
 
25
        if run_state == 'running':
 
26
            return True
 
27
        else:
 
28
            return False
 
29
    except subprocess.CalledProcessError, e:
 
30
        log("Error: is_vm_running Failed with error:{}".format(e.returncode), level=ERROR)
 
31
        return None
 
32
 
 
33
def _run_virsh_command(cmd, vmconfig):
 
34
    """
 
35
    Run virsh command, checking output
 
36
 
 
37
    :param: cmd: str: The virsh command to run.
 
38
    """
 
39
    env = os.environ.copy()
 
40
    for key, value in vmconfig.iteritems():
 
41
        env[key] = value
 
42
 
 
43
    #env['VSP_VM_NAME'] = vmconfig['VSP_VM_NAME']
 
44
    #env['VSP_VM_DIR'] = vmconfig['VSP_VM_DIR']
 
45
    #env['VSP_VM_XML'] = vmconfig['VSP_VM_XML']
 
46
    #env['VSP_VM_IMAGE_NAME'] = vmconfig['VSP_VM_IMAGE_NAME']
 
47
    #env['VSP_VM_ORIG_IMAGE_NAME'] = vmconfig['VSP_VM_ORIG_IMAGE_NAME']
 
48
    #env['VSP_VM_IMAGE_DIR'] = vmconfig['VSP_VM_IMAGE_DIR']
 
49
 
 
50
    try:
 
51
        log("execute virsh cmd {0}\n".format(cmd))
 
52
        resultstr = subprocess.check_output(cmd, env=env)
 
53
    except ValueError:
 
54
        log("Error: virsh cmd {0} Failed with error:{1}".format(cmd, resultstr), level=ERROR)
 
55
        sys.exit(1)
 
56
    except subprocess.CalledProcessError, e:
 
57
        log("Error: virsh cmd {0} Failed with error:{1}".format(cmd, e.returncode), level=ERROR)
 
58
        sys.exit(1)
 
59
    log("virsh cmd result: {0}\n".format(resultstr))
 
60
    return resultstr
 
61
 
 
62
 
 
63
def createvm(vmconfig):
 
64
    _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && create_vsp_vm'], vmconfig)
 
65
    log("{} is successfully created.".format(vmconfig['VSP_VM_NAME']))
 
66
def startvm(vmconfig):
 
67
    _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && start_vsp_vm'], vmconfig)
 
68
    log("{} is successfully started.".format(vmconfig['VSP_VM_NAME']))
 
69
 
 
70
 
 
71
def stopvm(vmconfig):
 
72
    _run_virsh_command(['bash', '-c', 'source /home/ovs-6/charms/trusty/nuage-vsc/payload/nuage_common.sh && stop_vsp_vm'], vmconfig)
 
73
    log("{} is successfully shutdown.".format(vmconfig['VSP_VM_NAME']))
 
74
 
 
75
def get_vm_ip_address(vmconfig):
 
76
    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)
 
77
    return vm_ip_address
 
78
    #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
 
79
 
 
80
def get_domain_name(ip_address):
 
81
    try:
 
82
        result_str = subprocess.check_output(['bash', '-c', 'nslookup {} | grep -o -E \"name = .*.[net|com|org]\"'.format(ip_address)])
 
83
        if result_str.startswith('name = '):
 
84
            domain_name = result_str.replace('name = ', '')
 
85
        else:
 
86
            domain_name = None
 
87
        return domain_name
 
88
    except subprocess.CalledProcessError, e:
 
89
        log("Error: get_domain_name Failed with error:{}".format(e.returncode), level=ERROR)
 
90
        return None
 
91
 
 
92
 
 
93
    return vm_ip_address
 
94
 
 
95
import pexpect
 
96
def update_vsd_domain(vsc_host, username, password, vsd_domain):
 
97
    ssh_newkey = 'Are you sure you want to continue connecting'
 
98
    child = pexpect.spawn('ssh %s@%s' % (username, vsc_host))
 
99
    log('ssh %s@%s' % (username, vsc_host))
 
100
    i=child.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
 
101
    if i==0:
 
102
        print "I say yes"
 
103
        child.sendline('yes')
 
104
        i=child.expect([ssh_newkey,'password:',pexpect.EOF])
 
105
    if i==1:
 
106
        print "I give password",
 
107
        child.sendline(password)
 
108
    elif i==2:
 
109
        print "I either got key or connection timeout"
 
110
        pass
 
111
    elif i==3: #timeout
 
112
        pass
 
113
    child.sendline("\r")
 
114
    child.sendline("configure vswitch-controller xmpp-server \"{}\"".format(vsd_domain))
 
115
    #child.interact()
 
116
 
 
117
import paramiko
 
118
 
 
119
def update_vsd_domain1(vsc_host, username, password, vsd_domain):
 
120
    paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
 
121
    ssh = paramiko.SSHClient()
 
122
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
123
    try:
 
124
        ssh.connect(vsc_host, username, password=password, timeout=120)
 
125
    except Exception as e:
 
126
        err = 'Error(%s): Unable to ssh to VSM VM (%s)' % (e, vsc_host)
 
127
 
 
128
    stdin, stdout, stderr = ssh.exec_command("configure vswitch-controller xmpp-server \"{}\"".format(vsd_domain))
 
129
    msg = stdout.readlines()
 
130
    stdin, stdout, stderr = ssh.exec_command("show vswitch-controller xmpp-server")
 
131
    msg = stdout.readlines()
 
132
    if str(msg).find(vsd_domain) == -1:
 
133
        err = 'Error: {0}:{1} is not set' % (msg, vsd_domain)
 
134
    ssh.close()
 
 
b'\\ No newline at end of file'