summaryrefslogtreecommitdiffstats
path: root/testcases/config_functest.py
blob: f031d3ade9603e688e55bdedbb8940d2a96a0374 (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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
#
# Copyright (c) 2015 Ericsson
# jose.lausuch@ericsson.com
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
#

import re, json, os, urllib2, argparse, logging, shutil, subprocess
from git import Repo

actions = ['start', 'check', 'clean']

""" global variables """
functest_dir = os.environ['HOME'] + '/.functest/'
#image_url = 'http://mirror.us.leaseweb.net/ubuntu-releases/14.04.2/ubuntu-14.04.2-server-amd64.iso'
image_url = 'http://download.cirros-cloud.net/0.3.0/cirros-0.3.0-i386-disk.img'
image_disk_format = 'raw'
image_name = image_url.rsplit('/')[-1]
image_path = functest_dir + image_name
rally_repo_dir = functest_dir + "Rally_repo/"
rally_installation_dir = os.environ['HOME'] + "/.rally"

parser = argparse.ArgumentParser()
parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
args = parser.parse_args()


""" logging configuration """
logger = logging.getLogger('config_functest')
logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
if args.debug:
    ch.setLevel(logging.DEBUG)
else:
    ch.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)



def config_functest_start():
    """
    Start the functest environment installation
    """
    if config_functest_check():
        logger.info("Functest environment already installed in %s. Nothing to do." %functest_dir)
        exit(0)
    elif not check_internet_connectivity():
        logger.error("There is no Internet connectivity. Please check the network configuration.")
        exit(-1)
    elif not check_credentials():
        logger.error("Please source the openrc credentials and run the script again.")
        #TODO: source the credentials in this script
        exit(-1)
    else:
        config_functest_clean()

        logger.info("Starting installationg of functest environment in %s" %functest_dir)
        os.makedirs(functest_dir)
        if not os.path.exists(functest_dir):
            logger.error("There has been a problem while creating the environment directory")
            exit(-1)


        logger.info("Installing Rally...")
        if not install_rally():
            logger.error("There has been a problem while installing Rally")
            exit(-1)

        logger.info("Installing Robot...")
        if not install_robot():
            logger.error("There has been a problem while installing Robot")
            exit(-1)

        logger.info("Donwloading test scripts and scenarios...")
        download_tests()

        logger.info("Donwloading image...")
        download_url_with_progress(image_url, functest_dir)

        logger.info("Creating Glance image: %s ..." %image_name)
        create_glance_image(image_path,image_name,image_disk_format)
        
        exit(0)



def config_functest_check():
    """
    Check if the functest environment is installed
    """
    logger.info("Checking current functest configuration...")
    if os.path.exists(functest_dir) and os.path.exists(rally_installation_dir):
        logger.info("Functest environment directory found in %s" %functest_dir)
        return True
    else:
        logger.info("Functest environment directory not found")
        return False



def config_functest_clean():
    """
    Clean the existing functest environment
    """
    logger.info("Removing current functest environment...")
    if os.path.exists(rally_installation_dir):
        shutil.rmtree(rally_installation_dir,ignore_errors=True)

    if os.path.exists(functest_dir):
        cmd = "sudo rm -rf " + functest_dir #need to be sudo
        execute_command(cmd)

    return True


def install_rally():
    if check_rally():
        logger.info("Rally is already installed.")
    else:
        logger.debug("Cloning repository...")
        url = "https://git.openstack.org/openstack/rally"
        Repo.clone_from(url, rally_repo_dir)

        logger.debug("Executing %s./install_rally.sh..." %rally_repo_dir)
        install_script = rally_repo_dir + "./install_rally.sh"
        subprocess.call(['sudo', install_script])

        logger.debug("Creating Rally environment...")
        cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
        execute_command(cmd)

        logger.debug("Installing tempest...")
        cmd = "rally-manage tempest install"
        execute_command(cmd)

        cmd = "rally deployment check"
        execute_command(cmd)
        #TODO: check that everything is 'Available' and warn if not

        cmd = "rally show images"
        execute_command(cmd)

        cmd = "rally show flavors"
        execute_command(cmd)

    return True



def check_rally():
    """
    Check if Rally is installed and properly configured
    """
    if os.path.exists(os.environ['HOME']+"/.rally/"):
        #TODO: do a more consistent check, for example running the comand rally deployment check
        return True
    else:
        return False


def install_robot():
    cmd = "sudo pip install requests"
    execute_command(cmd)
    cmd = "sudo pip install robotframework"
    execute_command(cmd)
    cmd = "sudo pip install robotframework-sshlibrary"
    execute_command(cmd)
    cmd = "sudo pip install robotframework-requests"
    execute_command(cmd)
    cmd = "mkvirtualenv robot"
    execute_command(cmd)
    return True


def check_credentials():
    """
    Check if the OpenStack credentials (openrc) are sourced
    """
    #TODO: there must be a short way to do this, doing if os.environ["something"] == "" throws an error
    try:
       os.environ['OS_AUTH_URL']
    except KeyError:
        return False
    try:
       os.environ['OS_USERNAME']
    except KeyError:
        return False
    try:
       os.environ['OS_PASSWORD']
    except KeyError:
        return False
    try:
       os.environ['OS_TENANT_NAME']
    except KeyError:
        return False
    try:
       os.environ['OS_REGION_NAME']
    except KeyError:
        return False
    return True


def download_tests():
    vPing_dir = functest_dir + "vPing/"
    odl_dir = functest_dir + "ODL/"
    bench_tests_dir = functest_dir + "scenarios/"

    os.makedirs(vPing_dir)
    os.makedirs(odl_dir)
    os.makedirs(bench_tests_dir)

    logger.info("Downloading vPing test...")
    vPing_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/vPing/CI/libraries/vPing.py'
    download_url(vPing_url,vPing_dir)

    logger.info("Downloading Rally bench tests...")
    rally_bench_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites/'
    bench_tests = ['authenticate', 'cinder', 'glance', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'tempest', 'vm']
    for i in bench_tests:
        rally_bench_url = rally_bench_base_url + "opnfv-" + i + ".json"
        logger.debug("Downloading %s" %rally_bench_url)
        download_url(rally_bench_url,bench_tests_dir)

    logger.info("Downloading OLD tests...")
    odl_base_url = 'https://git.opnfv.org/cgit/functest/plain/testcases/Controllers/ODL/CI/'
    odl_tests = ['start_tests.sh', 'test_list.txt']
    for i in odl_tests:
        odl_url = odl_base_url + i
        logger.debug("Downloading %s" %odl_url)
        download_url(odl_url,odl_dir)
    #TODO: complete



def create_glance_image(path,name,disk_format):
    """
    Create a glance image given the absolute path of the image, its name and the disk format
    """
    cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
    execute_command(cmd)


def download_url(url, dest_path):
    """
    Download a file to a destination path given a URL
    """
    name = url.rsplit('/')[-1]
    dest = dest_path + name
    try:
        response = urllib2.urlopen(url)
    except (urllib2.HTTPError, urllib2.URLError):
        logger.error("Error in fetching %s" %url)
        return False

    with open(dest, 'wb') as f:
        f.write(response.read())
    return True


def download_url_with_progress(url, dest_path):
    """
    Download a file to a destination path given a URL showing the progress
    """
    name = url.rsplit('/')[-1]
    dest = dest_path + name
    try:
        response = urllib2.urlopen(url)
    except (urllib2.HTTPError, urllib2.URLError):
        logger.error("Error in fetching %s" %url)
        return False

    f = open(dest, 'wb')
    meta = response.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    logger.info("Downloading: %s Bytes: %s" %(dest, file_size))

    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = response.read(block_sz)
        if not buffer:
            break

        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print status,

    f.close()
    print("\n")


def check_internet_connectivity(url='http://www.google.com/'):
    """
    Check if there is access to the internet
    """
    try:
        urllib2.urlopen(url, timeout=5)
        return True
    except urllib.request.URLError:
        return False

def execute_command(cmd):
    """
    Execute Linux command
    """
    logger.debug('Executing command : {}'.format(cmd))
    p = os.popen(cmd,"r")
    logger.debug(p.read())



def main():
    if not (args.action in actions):
        logger.error('argument not valid')
        exit(-1)

    if args.action == "start":
        config_functest_start()

    if args.action == "check":
        config_functest_check()

    if args.action == "clean":
        while True:
            print("Are you sure? [y|n]")
            answer = raw_input("")
            if answer == "y":
                config_functest_clean()
                break
            elif answer == "n":
                break
            else:
                print("Invalid option.")
    exit(0)


if __name__ == '__main__':
    main()