automatic deploy a wholeset of TestAPI ecosystem
[releng.git] / modules / opnfv / installer_adapters / fuel / FuelAdapter.py
1 ##############################################################################
2 # Copyright (c) 2016 Ericsson AB and others.
3 # Author: Jose Lausuch (jose.lausuch@ericsson.com)
4 #         George Paraskevopoulos (geopar@intracom-telecom.com)
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 import opnfv.utils.SSHUtils as ssh_utils
12 import opnfv.utils.OPNFVLogger as logger
13
14
15 class FuelAdapter:
16
17     def __init__(self, installer_ip, user="root", password="r00tme"):
18         self.installer_ip = installer_ip
19         self.installer_user = user
20         self.installer_password = password
21         self.installer_connection = ssh_utils.get_ssh_client(
22             installer_ip,
23             self.installer_user,
24             password=self.installer_password)
25         self.logger = logger.Logger("FuelHandler").getLogger()
26
27     def runcmd_fuel_installer(self, cmd):
28         _, stdout, stderr = (self
29                              .installer_connection
30                              .exec_command(cmd))
31         error = stderr.readlines()
32         if len(error) > 0:
33             self.logger.error("error %s" % ''.join(error))
34             return error
35         output = ''.join(stdout.readlines())
36         return output
37
38     def runcmd_fuel_nodes(self):
39         return self.runcmd_fuel_installer('fuel nodes')
40
41     def runcmd_fuel_env(self):
42         return self.runcmd_fuel_installer('fuel env')
43
44     def get_clusters(self):
45         environments = []
46         output = self.runcmd_fuel_env()
47         lines = output.rsplit('\n')
48         if len(lines) < 2:
49             self.logger.infp("No environments found in the deployment.")
50             return None
51         else:
52             fields = lines[0].rsplit(' | ')
53
54             index_id = -1
55             index_status = -1
56             index_name = -1
57             index_release_id = -1
58
59             for i in range(0, len(fields) - 1):
60                 if "id" in fields[i]:
61                     index_id = i
62                 elif "status" in fields[i]:
63                     index_status = i
64                 elif "name" in fields[i]:
65                     index_name = i
66                 elif "release_id" in fields[i]:
67                     index_release_id = i
68
69             # order env info
70             for i in range(2, len(lines) - 1):
71                 fields = lines[i].rsplit(' | ')
72                 dict = {"id": fields[index_id].strip(),
73                         "status": fields[index_status].strip(),
74                         "name": fields[index_name].strip(),
75                         "release_id": fields[index_release_id].strip()}
76                 environments.append(dict)
77
78         return environments
79
80     def get_nodes(self, options=None):
81         nodes = []
82         output = self.runcmd_fuel_nodes()
83         lines = output.rsplit('\n')
84         if len(lines) < 2:
85             self.logger.info("No nodes found in the deployment.")
86             return None
87         else:
88             # get fields indexes
89             fields = lines[0].rsplit(' | ')
90
91             index_id = -1
92             index_status = -1
93             index_name = -1
94             index_cluster = -1
95             index_ip = -1
96             index_mac = -1
97             index_roles = -1
98             index_online = -1
99
100             for i in range(0, len(fields) - 1):
101                 if "id" in fields[i]:
102                     index_id = i
103                 elif "status" in fields[i]:
104                     index_status = i
105                 elif "name" in fields[i]:
106                     index_name = i
107                 elif "cluster" in fields[i]:
108                     index_cluster = i
109                 elif "ip" in fields[i]:
110                     index_ip = i
111                 elif "mac" in fields[i]:
112                     index_mac = i
113                 elif "roles " in fields[i]:
114                     index_roles = i
115                 elif "online" in fields[i]:
116                     index_online = i
117
118             # order nodes info
119             for i in range(2, len(lines) - 1):
120                 fields = lines[i].rsplit(' | ')
121                 dict = {"id": fields[index_id].strip(),
122                         "status": fields[index_status].strip(),
123                         "name": fields[index_name].strip(),
124                         "cluster": fields[index_cluster].strip(),
125                         "ip": fields[index_ip].strip(),
126                         "mac": fields[index_mac].strip(),
127                         "roles": fields[index_roles].strip(),
128                         "online": fields[index_online].strip()}
129                 if options and options['cluster']:
130                     if fields[index_cluster].strip() == options['cluster']:
131                         nodes.append(dict)
132                 else:
133                     nodes.append(dict)
134
135         return nodes
136
137     def get_controller_ips(self, options):
138         nodes = self.get_nodes(options=options)
139         controllers = []
140         for node in nodes:
141             if "controller" in node["roles"]:
142                 controllers.append(node['ip'])
143         return controllers
144
145     def get_compute_ips(self, options=None):
146         nodes = self.get_nodes(options=options)
147         computes = []
148         for node in nodes:
149             if "compute" in node["roles"]:
150                 computes.append(node['ip'])
151         return computes
152
153     def get_deployment_info(self):
154         str = "Deployment details:\n"
155         str += "\tInstaller:  Fuel\n"
156         str += "\tScenario:   Unknown\n"
157         sdn = "None"
158         clusters = self.get_clusters()
159         str += "\tN.Clusters: %s\n" % len(clusters)
160         for cluster in clusters:
161             cluster_dic = {'cluster': cluster['id']}
162             str += "\tCluster info:\n"
163             str += "\t   ID:          %s\n" % cluster['id']
164             str += "\t   NAME:        %s\n" % cluster['name']
165             str += "\t   STATUS:      %s\n" % cluster['status']
166             nodes = self.get_nodes(options=cluster_dic)
167             num_nodes = len(nodes)
168             for node in nodes:
169                 if "opendaylight" in node['roles']:
170                     sdn = "OpenDaylight"
171                 elif "onos" in node['roles']:
172                     sdn = "ONOS"
173             num_controllers = len(
174                 self.get_controller_ips(options=cluster_dic))
175             num_computes = len(self.get_compute_ips(options=cluster_dic))
176             ha = False
177             if num_controllers > 1:
178                 ha = True
179
180             str += "\t   HA:          %s\n" % ha
181             str += "\t   NUM.NODES:   %s\n" % num_nodes
182             str += "\t   CONTROLLERS: %s\n" % num_controllers
183             str += "\t   COMPUTES:    %s\n" % num_computes
184             str += "\t   SDN CONTR.:  %s\n\n" % sdn
185         str += self.runcmd_fuel_nodes()
186         return str
187
188     def get_file_from_installer(self, remote_path, local_path, options=None):
189         self.logger.debug("Fetching %s from %s" %
190                           (remote_path, self.installer_ip))
191         get_file_result = ssh_utils.get_file(self.installer_connection,
192                                              remote_path,
193                                              local_path)
194         if get_file_result is None:
195             self.logger.error("SFTP failed to retrieve the file.")
196             return 1
197         self.logger.info("%s successfully copied from Fuel to %s" %
198                          (remote_path, local_path))
199
200     def get_file_from_controller(self,
201                                  remote_path,
202                                  local_path,
203                                  ip=None,
204                                  user='root',
205                                  options=None):
206         if ip is None:
207             controllers = self.get_controller_ips(options=options)
208             if len(controllers) == 0:
209                 self.logger.info("No controllers found in the deployment.")
210                 return 1
211             else:
212                 target_ip = controllers[0]
213         else:
214             target_ip = ip
215
216         installer_jumphost = {
217             'ip': self.installer_ip,
218             'username': self.installer_user,
219             'password': self.installer_password
220         }
221         controller_conn = ssh_utils.get_ssh_client(
222             target_ip,
223             user,
224             jumphost=installer_jumphost)
225
226         self.logger.debug("Fetching %s from %s" %
227                           (remote_path, target_ip))
228
229         get_file_result = ssh_utils.get_file(controller_conn,
230                                              remote_path,
231                                              local_path)
232         if get_file_result is None:
233             self.logger.error("SFTP failed to retrieve the file.")
234             return 1
235         self.logger.info("%s successfully copied from %s to %s" %
236                          (remote_path, target_ip, local_path))