Merge "Fix typos in test_details.rst and test_overview.rst"
[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 class CheckDeployment(object):
56     """ Check deployment class."""
57
58     def __init__(self, rc_file='/home/opnfv/functest/conf/openstack.creds'):
59         self.rc_file = rc_file
60         self.services = ('compute', 'network', 'image')
61         self.os_creds = None
62
63     def check_rc(self):
64         """ Check if RC file exists and contains OS_AUTH_URL """
65         if not os.path.isfile(self.rc_file):
66             raise IOError('RC file {} does not exist!'.format(self.rc_file))
67         if 'OS_AUTH_URL' not in open(self.rc_file).read():
68             raise SyntaxError('OS_AUTH_URL not defined in {}.'.
69                               format(self.rc_file))
70
71     def check_auth_endpoint(self):
72         """ Verifies connectivity to the OS_AUTH_URL given in the RC file """
73         rc_endpoint = self.os_creds.auth_url
74         if not verify_connectivity(rc_endpoint):
75             raise Exception("OS_AUTH_URL {} is not reachable.".
76                             format(rc_endpoint))
77         LOGGER.info("Connectivity to OS_AUTH_URL %s ...OK", rc_endpoint)
78
79     def check_public_endpoint(self):
80         """ Gets the public endpoint and verifies connectivity to it """
81         public_endpoint = keystone_utils.get_endpoint(self.os_creds,
82                                                       'identity',
83                                                       interface='public')
84         if not verify_connectivity(public_endpoint):
85             raise Exception("Public endpoint {} is not reachable.".
86                             format(public_endpoint))
87         LOGGER.info("Connectivity to the public endpoint %s ...OK",
88                     public_endpoint)
89
90     def check_service_endpoint(self, service):
91         """ Verifies connectivity to a given openstack service """
92         endpoint = keystone_utils.get_endpoint(self.os_creds,
93                                                service,
94                                                interface='public')
95         if not verify_connectivity(endpoint):
96             raise Exception("{} endpoint {} is not reachable.".
97                             format(service, endpoint))
98         LOGGER.info("Connectivity to endpoint '%s' %s ...OK",
99                     service, endpoint)
100
101     def check_nova(self):
102         """ checks that a simple nova operation works """
103         try:
104             client = nova_utils.nova_client(self.os_creds)
105             client.servers.list()
106             LOGGER.info("Nova service ...OK")
107         except Exception as error:
108             LOGGER.error("Nova service ...FAILED")
109             raise error
110
111     def check_neutron(self):
112         """ checks that a simple neutron operation works """
113         try:
114             client = neutron_utils.neutron_client(self.os_creds)
115             client.list_networks()
116             LOGGER.info("Neutron service ...OK")
117         except Exception as error:
118             LOGGER.error("Neutron service ...FAILED")
119             raise error
120
121     def check_glance(self):
122         """ checks that a simple glance operation works """
123         try:
124             client = glance_utils.glance_client(self.os_creds)
125             client.images.list()
126             LOGGER.info("Glance service ...OK")
127         except Exception as error:
128             LOGGER.error("Glance service ...FAILED")
129             raise error
130
131     def check_ext_net(self):
132         """ checks if external network exists """
133         ext_net = snaps_utils.get_ext_net_name(self.os_creds)
134         if ext_net:
135             LOGGER.info("External network found: %s", ext_net)
136         else:
137             raise Exception("ERROR: No external networks in the deployment.")
138
139     def check_all(self):
140         """
141         Calls all the class functions and returns 0 if all of them succeed.
142         This is the method called by CLI
143         """
144         self.check_rc()
145         try:
146             self.os_creds = openstack_tests.get_credentials(
147                 os_env_file=self.rc_file,
148                 proxy_settings_str=None,
149                 ssh_proxy_cmd=None)
150         except:
151             raise Exception("Problem while getting credentials object.")
152         if self.os_creds is None:
153             raise Exception("Credentials is None.")
154         self.check_auth_endpoint()
155         self.check_public_endpoint()
156         for service in self.services:
157             self.check_service_endpoint(service)
158         self.check_nova()
159         self.check_neutron()
160         self.check_glance()
161         self.check_ext_net()
162         return 0
163
164
165 def main():
166     """Entry point"""
167     logging.config.fileConfig(pkg_resources.resource_filename(
168         'functest', 'ci/logging.ini'))
169     logging.captureWarnings(True)
170     deployment = CheckDeployment()
171     return deployment.check_all()