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