Merge "Support to specify the valid external network name"
[functest.git] / functest / ci / check_deployment.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 Ericsson and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """
11 OpenStack deployment checker
12
13 Verifies that:
14  - Credentials file is given and contains the right information
15  - OpenStack endpoints are reachable
16 """
17
18 import logging
19 import logging.config
20 import os
21 import pkg_resources
22 import socket
23 from urlparse import urlparse
24
25 from functest.opnfv_tests.openstack.snaps import snaps_utils
26
27 from snaps.openstack.utils import glance_utils
28 from snaps.openstack.utils import keystone_utils
29 from snaps.openstack.utils import neutron_utils
30 from snaps.openstack.utils import nova_utils
31 from snaps.openstack.tests import openstack_tests
32
33 __author__ = "Jose Lausuch <jose.lausuch@ericsson.com>"
34
35 LOGGER = logging.getLogger(__name__)
36
37
38 def verify_connectivity(adress, port):
39     """ Returns true if an ip/port is reachable"""
40     connection = socket.socket()
41     connection.settimeout(10)
42     try:
43         connection.connect((adress, port))
44         LOGGER.debug('%s:%s is reachable!', adress, port)
45         return True
46     except socket.error:
47         LOGGER.error('%s:%s is not reachable.', adress, port)
48     return False
49
50
51 class CheckDeployment(object):
52     """ Check deployment class."""
53
54     def __init__(self, rc_file='/home/opnfv/functest/conf/openstack.creds'):
55         self.rc_file = rc_file
56         self.services = ('compute', 'network', 'image')
57         self.os_creds = None
58
59     def check_rc(self):
60         """ Check if RC file exists and contains OS_AUTH_URL """
61         if not os.path.isfile(self.rc_file):
62             raise IOError('RC file {} does not exist!'.format(self.rc_file))
63         if 'OS_AUTH_URL' not in open(self.rc_file).read():
64             raise SyntaxError('OS_AUTH_URL not defined in {}.'.
65                               format(self.rc_file))
66
67     def check_auth_endpoint(self):
68         """ Verifies connectivity to the OS_AUTH_URL given in the RC file """
69         rc_endpoint = self.os_creds.auth_url
70         if not (verify_connectivity(urlparse(rc_endpoint).hostname,
71                                     urlparse(rc_endpoint).port)):
72             raise Exception("OS_AUTH_URL {} is not reachable.".
73                             format(rc_endpoint))
74         LOGGER.info("Connectivity to OS_AUTH_URL %s ...OK", rc_endpoint)
75
76     def check_public_endpoint(self):
77         """ Gets the public endpoint and verifies connectivity to it """
78         public_endpoint = keystone_utils.get_endpoint(self.os_creds,
79                                                       'identity',
80                                                       interface='public')
81         if not (verify_connectivity(urlparse(public_endpoint).hostname,
82                                     urlparse(public_endpoint).port)):
83             raise Exception("Public endpoint {} is not reachable.".
84                             format(public_endpoint))
85         LOGGER.info("Connectivity to the public endpoint %s ...OK",
86                     public_endpoint)
87
88     def check_service_endpoint(self, service):
89         """ Verifies connectivity to a given openstack service """
90         endpoint = keystone_utils.get_endpoint(self.os_creds,
91                                                service,
92                                                interface='public')
93         if not (verify_connectivity(urlparse(endpoint).hostname,
94                                     urlparse(endpoint).port)):
95             raise Exception("{} endpoint {} is not reachable.".
96                             format(service, endpoint))
97         LOGGER.info("Connectivity to endpoint '%s' %s ...OK",
98                     service, endpoint)
99
100     def check_nova(self):
101         """ checks that a simple nova operation works """
102         try:
103             client = nova_utils.nova_client(self.os_creds)
104             client.servers.list()
105             LOGGER.info("Nova service ...OK")
106         except Exception as error:
107             LOGGER.error("Nova service ...FAILED")
108             raise error
109
110     def check_neutron(self):
111         """ checks that a simple neutron operation works """
112         try:
113             client = neutron_utils.neutron_client(self.os_creds)
114             client.list_networks()
115             LOGGER.info("Neutron service ...OK")
116         except Exception as error:
117             LOGGER.error("Neutron service ...FAILED")
118             raise error
119
120     def check_glance(self):
121         """ checks that a simple glance operation works """
122         try:
123             client = glance_utils.glance_client(self.os_creds)
124             client.images.list()
125             LOGGER.info("Glance service ...OK")
126         except Exception as error:
127             LOGGER.error("Glance service ...FAILED")
128             raise error
129
130     def check_ext_net(self):
131         """ checks if external network exists """
132         ext_net = snaps_utils.get_ext_net_name(self.os_creds)
133         if ext_net:
134             LOGGER.info("External network found: %s" % ext_net)
135         else:
136             raise Exception("ERROR: No external networks in the deployment.")
137
138     def check_all(self):
139         """
140         Calls all the class functions and returns 0 if all of them succeed.
141         This is the method called by prepare_env or CLI
142         """
143         self.check_rc()
144         try:
145             self.os_creds = openstack_tests.get_credentials(
146                 os_env_file=self.rc_file,
147                 proxy_settings_str=None,
148                 ssh_proxy_cmd=None)
149         except:
150             raise Exception("Problem while getting credentials object.")
151         if self.os_creds is None:
152             raise Exception("Credentials is None.")
153         self.check_auth_endpoint()
154         self.check_public_endpoint()
155         for service in self.services:
156             self.check_service_endpoint(service)
157         self.check_nova()
158         self.check_neutron()
159         self.check_glance()
160         self.check_ext_net()
161         return 0
162
163
164 def main():
165     """Entry point"""
166     logging.config.fileConfig(pkg_resources.resource_filename(
167         'functest', 'ci/logging.ini'))
168     logging.captureWarnings(True)
169     deployment = CheckDeployment()
170     return deployment.check_all()