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