First upload of vPing script, one of the 5 functest testcase. This Hello world exampl...
[functest.git] / testcases / vPing / CI / libraries / vPing.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2015 All rights reserved. This program and the accompanying materials
4 # are made available under the terms of the Apache License, Version 2.0
5 # which accompanies this distribution, and is available at
6
7 #               http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # This script boots the VM1 and allocates IP address from Nova
10 # Later, the VM2 boots then execute cloud-init to ping VM1.
11 # After successful ping, both the VMs are deleted.
12 #
13 # Note: this is script works only with Ubuntu image, not with Cirros image
14 #
15
16 import os
17 import pprint
18 import subprocess
19 import time
20 import novaclient.v1_1.client as novaclient
21 import cinderclient.v1.client as cinderclient
22 pp = pprint.PrettyPrinter(indent=4)
23
24 def pMsg(value):
25     """pretty printing"""
26     pp.pprint(value)
27
28 def print_title(title):
29     """Print titles"""
30     print "\n"+"#"*40+"\n# "+title+"\n"+"#"*40+"\n"
31
32 def get_credentials(service):
33     """Returns a creds dictionary filled with the following keys:
34     * username
35     * password/api_key (depending on the service)
36     * tenant_name/project_id (depending on the service)
37     * auth_url
38     :param service: a string indicating the name of the service
39                     requesting the credentials.
40     """
41     creds = {}
42     # Unfortunately, each of the OpenStack client will request slightly
43     # different entries in their credentials dict.
44     if service.lower() in ("nova", "cinder"):
45         password = "api_key"
46         tenant = "project_id"
47     else:
48         password = "password"
49         tenant = "tenant_name"
50
51     # The most common way to pass these info to the script is to do it through
52     # environment variables.
53     creds.update({
54         "username": os.environ.get('OS_USERNAME', "admin"),                                                             # add your cloud username details
55         password: os.environ.get("OS_PASSWORD", "test"),                                                                # add password
56         "auth_url": os.environ.get("OS_AUTH_URL","http://192.168.20.71:5000/v2.0"),             # Auth URL
57         tenant: os.environ.get("OS_TENANT_NAME", "invisible_to_admin"),
58     })
59
60     return creds
61
62
63 def get_server(creds, servername):
64     nova = novaclient.Client(**creds)
65     return nova.servers.find(name=servername)
66
67
68 def waitVmActive(nova,vm):
69     # sleep and wait for VM status change
70     pMsg(vm.status)
71     while vm.status == "BUILD":
72         time.sleep(1)
73         vm = nova.servers.get(vm.id)
74         pMsg(vm.status)
75
76 def main():
77     creds = get_credentials("nova")
78     nova = novaclient.Client(**creds)
79     cinder = cinderclient.Client(**creds)
80     
81     #print images and server resources
82     print_title("images list")
83     pMsg(nova.images.list())
84     
85     print_title("servers list")
86     pMsg(nova.servers.list())
87     
88
89     # boot VM 1
90     # basic boot
91         # tune (e.g. flavor, images, network) to your specific openstack configuration here
92     f = nova.flavors.find(name = 'm1.small')
93     i = nova.images.find(name = 'Ubuntu 14.04 (amd64)')
94     n = nova.networks.find(label = 'private')
95     u = "#cloud-config\npassword: opnfv\nchpasswd: { expire: False }\nssh_pwauth: True"
96     #k = "demo-key"
97
98     # create VM
99     vm1 = nova.servers.create(
100         name               = "opnfv-vping-1",
101         flavor             = f,
102         image              = i,
103         nics               = [{"net-id": n.id}],
104         #key_name           = k,
105         userdata           = u,
106     )
107
108     pMsg(vm1)
109
110
111     #wait until VM status is active
112     waitVmActive(nova,vm1)
113     
114     #retrieve IP of first VM
115     server = get_server(creds, "opnfv-vping-1")
116     pMsg(server.networks)
117     # theoretically there is only one IP address so we take the first element of the table
118     test_ip = server.networks.get('private')[0]
119     test_cmd = '/tmp/vping.sh %s'%test_ip
120
121    
122     # boot VM 2 
123     # we will boot then execute a ping script with cloud-init
124     # the long chain corresponds to the ping procedure converted with base 64
125         # tune (e.g. flavor, images, network) to your specific openstack configuration here
126     f = nova.flavors.find(name = 'm1.small')
127     i = nova.images.find(name = 'Ubuntu 14.04 (amd64)')
128     n = nova.networks.find(label = 'private')
129     # use base 64 format becaus bad surprises with sh script with cloud-init but script is just pinging
130     u = "#cloud-config\npassword: opnfv\nchpasswd: { expire: False }\nssh_pwauth: True\nwrite_files:\n-  encoding: b64\n   path: /tmp/vping.sh\n   permissions: '0777'\n   owner: root:root\n   content: IyEvYmluL2Jhc2gKCgoKcGluZyAtYyAxICQxIDI+JjEgPi9kZXYvbnVsbApSRVM9JD8KaWYgWyAiWiRSRVMiID0gIlowIiBdIDsgdGhlbgogIGVjaG8gInZQaW5nIE9LIgplbHNlCiAgZWNobyAidlBpbmcgS08iCmZpCg==\nruncmd:\n - [ sh, -c, %s]"%test_cmd
131     #k = "demo-key"
132     
133     # create VM
134     vm2 = nova.servers.create(
135         name               = "opnfv-vping-2", 
136         flavor             = f,
137         image              = i,
138         nics               = [{"net-id": n.id}],
139         #key_name           = k,
140         userdata           = u,
141         #security_groups    = s,
142         #config_drive       = v.id
143     )
144     
145     pMsg(vm2)
146    
147     waitVmActive(nova,vm2)
148  
149     console_log = vm2.get_console_output()
150     
151
152     while not ("vPing" in console_log):
153         time.sleep(1)
154         console_log = vm2.get_console_output()
155
156         # report if the test is failed
157         if "vPing" in console_log:
158             pMsg("vPing is OK")
159         else:
160             pMsg("no vPing detected....")
161
162     # delete both VMs
163     nova.servers.delete(vm1)
164     nova.servers.delete(vm2)
165     pMsg ("VM instances have been terminated!")
166
167
168 if __name__ == '__main__':
169     main()