Leverage on SDN_CONTROLLER_IP if fuel
[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 socket
22
23 import pkg_resources
24 from six.moves import urllib
25 from snaps.openstack.tests import openstack_tests
26 from snaps.openstack.utils import glance_utils
27 from snaps.openstack.utils import keystone_utils
28 from snaps.openstack.utils import neutron_utils
29 from snaps.openstack.utils import nova_utils
30
31 from functest.utils import constants
32 from functest.opnfv_tests.openstack.snaps import snaps_utils
33
34 __author__ = "Jose Lausuch <jose.lausuch@ericsson.com>"
35
36 LOGGER = logging.getLogger(__name__)
37
38
39 def verify_connectivity(endpoint):
40     """ Returns true if an hostname/port is reachable"""
41     try:
42         connection = socket.socket()
43         connection.settimeout(10)
44         url = urllib.parse.urlparse(endpoint)
45         port = url.port
46         if not port:
47             port = 443 if url.scheme == "https" else 80
48         connection.connect((url.hostname, port))
49         LOGGER.debug('%s:%s is reachable!', url.hostname, port)
50         return True
51     except socket.error:
52         LOGGER.error('%s:%s is not reachable.', url.hostname, port)
53     except Exception:  # pylint: disable=broad-except
54         LOGGER.exception(
55             'Errors when verifying connectivity to %s:%s', url.hostname, port)
56     return False
57
58
59 def get_auth_token(os_creds):
60     """ Get auth token """
61     sess = keystone_utils.keystone_session(os_creds)
62     try:
63         return sess.get_token()
64     except Exception as error:
65         LOGGER.error("Got token ...FAILED")
66         raise error
67
68
69 class CheckDeployment(object):
70     """ Check deployment class."""
71
72     def __init__(self, rc_file=constants.ENV_FILE):
73         self.rc_file = rc_file
74         self.services = ('compute', 'network', 'image')
75         self.os_creds = None
76
77     def check_rc(self):
78         """ Check if RC file exists and contains OS_AUTH_URL """
79         if not os.path.isfile(self.rc_file):
80             raise IOError('RC file {} does not exist!'.format(self.rc_file))
81         if 'OS_AUTH_URL' not in open(self.rc_file).read():
82             raise SyntaxError('OS_AUTH_URL not defined in {}.'.
83                               format(self.rc_file))
84
85     def check_auth_endpoint(self):
86         """ Verifies connectivity to the OS_AUTH_URL given in the RC file
87         and get auth token"""
88         rc_endpoint = self.os_creds.auth_url
89         if not verify_connectivity(rc_endpoint):
90             raise Exception("OS_AUTH_URL {} is not reachable.".
91                             format(rc_endpoint))
92         LOGGER.info("Connectivity to OS_AUTH_URL %s ...OK", rc_endpoint)
93         if get_auth_token(self.os_creds):
94             LOGGER.info("Got token ...OK")
95
96     def check_public_endpoint(self):
97         """ Gets the public endpoint and verifies connectivity to it """
98         public_endpoint = keystone_utils.get_endpoint(self.os_creds,
99                                                       'identity',
100                                                       interface='public')
101         if not verify_connectivity(public_endpoint):
102             raise Exception("Public endpoint {} is not reachable.".
103                             format(public_endpoint))
104         LOGGER.info("Connectivity to the public endpoint %s ...OK",
105                     public_endpoint)
106
107     def check_service_endpoint(self, service):
108         """ Verifies connectivity to a given openstack service """
109         endpoint = keystone_utils.get_endpoint(self.os_creds,
110                                                service,
111                                                interface='public')
112         if not verify_connectivity(endpoint):
113             raise Exception("{} endpoint {} is not reachable.".
114                             format(service, endpoint))
115         LOGGER.info("Connectivity to endpoint '%s' %s ...OK",
116                     service, endpoint)
117
118     def check_nova(self):
119         """ checks that a simple nova operation works """
120         try:
121             client = nova_utils.nova_client(self.os_creds)
122             client.servers.list()
123             LOGGER.info("Nova service ...OK")
124         except Exception as error:
125             LOGGER.error("Nova service ...FAILED")
126             raise error
127
128     def check_neutron(self):
129         """ checks that a simple neutron operation works """
130         try:
131             client = neutron_utils.neutron_client(self.os_creds)
132             client.list_networks()
133             LOGGER.info("Neutron service ...OK")
134         except Exception as error:
135             LOGGER.error("Neutron service ...FAILED")
136             raise error
137
138     def check_glance(self):
139         """ checks that a simple glance operation works """
140         try:
141             client = glance_utils.glance_client(self.os_creds)
142             client.images.list()
143             LOGGER.info("Glance service ...OK")
144         except Exception as error:
145             LOGGER.error("Glance service ...FAILED")
146             raise error
147
148     def check_ext_net(self):
149         """ checks if external network exists """
150         ext_net = snaps_utils.get_ext_net_name(self.os_creds)
151         if ext_net:
152             LOGGER.info("External network found: %s", ext_net)
153         else:
154             raise Exception("ERROR: No external networks in the deployment.")
155
156     def check_all(self):
157         """
158         Calls all the class functions and returns 0 if all of them succeed.
159         This is the method called by CLI
160         """
161         self.check_rc()
162         try:
163             self.os_creds = openstack_tests.get_credentials(
164                 os_env_file=self.rc_file,
165                 proxy_settings_str=None,
166                 ssh_proxy_cmd=None)
167         except:
168             raise Exception("Problem while getting credentials object.")
169         if self.os_creds is None:
170             raise Exception("Credentials is None.")
171         self.check_auth_endpoint()
172         self.check_public_endpoint()
173         for service in self.services:
174             self.check_service_endpoint(service)
175         self.check_nova()
176         self.check_neutron()
177         self.check_glance()
178         self.check_ext_net()
179         return 0
180
181
182 def main():
183     """Entry point"""
184     logging.config.fileConfig(pkg_resources.resource_filename(
185         'functest', 'ci/logging.ini'))
186     logging.captureWarnings(True)
187     deployment = CheckDeployment()
188     return deployment.check_all()