Fix ansible-server for supporting playbook of PNF
[ccsdk/distribution.git] / ansible-server / src / main / ansible-server / AnsibleSql.py
1 '''
2 /*-
3 * ============LICENSE_START=======================================================
4 * ONAP : APPC
5 * ================================================================================
6 * Copyright (C) 2017 AT&T Intellectual Property.  All rights reserved.
7 * ================================================================================
8 * Copyright (C) 2017 Amdocs
9 * =============================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 *      http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21
22 * ============LICENSE_END=========================================================
23 */
24 '''
25
26 import pymysql, sys
27 from os import listdir
28 from os.path import isfile, join
29
30 class mySql():
31
32     def __init__(self, myhost, myuser, mypasswd, mydb):
33         self.con = True
34         self.error = ''
35         self.db = None
36         try:
37             self.db = pymysql.connect(host=myhost,
38                                       user=myuser,
39                                       passwd=mypasswd,
40                                       db=mydb)
41             self.cur = self.db.cursor()
42         except Exception as e:
43             self.error = e[1]
44             self.con = False
45
46     def Query (self, myquery, val = None):
47         results = None
48         try:
49             if val:
50                 self.cur.execute(myquery, val)
51             else:
52                 self.cur.execute(myquery)
53             self.db.commit()
54             results = self.cur.fetchall()
55         except Exception, e:
56             results = repr(e)
57         return results
58     
59     def Close (self):
60         if self.db:
61             self.db.close()
62
63 def loadPlaybook (sqlintf, value, version, ext = '.yml'):
64
65     errorCode = 0
66     diag = ''
67     
68     # Test if primary key already defined
69     query = "SELECT name FROM playbook WHERE name='" + value +"'"
70     results = sqlintf.Query (query)
71     if len(results) > 0:
72         pass
73     else:
74         query = "INSERT INTO playbook (name) VALUES ('" + value + "')"
75         results = sqlintf.Query (query)
76         if len(results) > 0:
77             errorCode = 1
78             diag = results
79
80     # Load playbook
81     file = open(playbook_path + value + ext, 'r')
82     load_file = file.read()
83         
84     if not errorCode:
85         sql = "UPDATE playbook SET value=%s, version=%s, type=%s WHERE name=%s"
86
87         results = sqlintf.Query(sql, (load_file, version, ext, value))
88
89         if len (results) > 0:
90             # Error loading playbook
91             errorCode = 1
92             diag = results
93
94     return errorCode, diag
95
96 def loadCredentials (sqlintf, hostgroup, hostname, cred):
97     errorCode = 0
98     diag = ''
99     
100     # Load credentials
101
102     query = "SELECT hostname,hostgroup FROM inventory WHERE hostname='" + hostname +"'"
103     results = sqlintf.Query (query)
104
105     if hostname in str (results):
106
107         results_hostgroups = results[0][1]
108         
109         if hostgroup in results_hostgroups.split(','):
110             query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
111                     cred +\
112                     "' WHERE hostname='" + hostname + "'"
113         else:
114
115             results_hostgroups = results_hostgroups + ',' + hostgroup
116             
117             query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
118                     cred + "',hostgroup='" + results_hostgroups + \
119                     "' WHERE hostname='" + hostname + "'"
120                         
121         results = sqlintf.Query (query)
122         
123     else:
124         
125         query = "INSERT INTO inventory (hostgroup, hostname, credentials) VALUES ('" + \
126                 hostgroup + "','" + hostname + "','" + cred + "')"
127         results = sqlintf.Query (query)
128
129     if len (results) > 0:
130         # Error loading playbook
131         errorCode = 1
132         diag = results
133
134     return errorCode, diag
135     
136
137 def readPlaybook (sqlintf, value, version=None):
138
139     errorCode = 0
140     diag = ''
141
142     print "***> in AnsibleSql.readPlaybook"
143     
144     if not version:
145         query = "SELECT MAX(version) FROM playbook WHERE name like'" + value + "%'"
146         print "   Query:", query
147         results = sqlintf.Query (query)
148         version = results[0][0]
149
150     print "   Provided playbook name:", value 
151     print "   Used version:", version
152
153     results = []
154     if version:
155         query = "SELECT value,type FROM playbook WHERE name='" + value + "@" + version + "'"
156         results = sqlintf.Query (query)
157
158         print "Query:", query
159         print "Results:", results
160     
161     if len(results) == 0:
162         errorCode = 1
163     else:
164         if len(results[0]) == 0:
165             errorCode = 1
166             diag = results[0]
167         else:
168             diag = results[0]
169
170     return value, version, errorCode, diag
171
172 def readCredentials (sqlintf, tag):
173     errorCode = []
174     diag = []
175
176     print "***> in AnsibleSql.readCredential"
177     
178     # Load credentials
179
180     for rec in tag:
181
182         # Try hostgroup
183         query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostgroup LIKE '%" + \
184                 rec +"%'"
185         query_results = sqlintf.Query (query)
186
187         results = ()
188         for q in query_results:
189             if rec in q[0].split(','):
190                 l = list(q)
191                 l[0] = rec
192                 q = tuple(l)
193                 results = (q,) + results
194
195         if len(results) == 0:
196             # Try hostname
197             query = "SELECT hostgroup, hostname, credentials FROM inventory WHERE hostname='" + \
198                     rec +"'"
199             results = sqlintf.Query (query)
200
201         print "   Query:", query
202         print "   Results:", len(results), results
203
204         if len(results) == 0:
205             errorCode = 1
206             hostgroup = rec
207             hostname = rec
208             credentials = 'ansible_connection=ssh ansible_ssh_user=na ansible_ssh_private_key_file=na\n'
209             diag.append([hostgroup, hostname, credentials])
210         else:
211             errorCode = 0
212             for i in range(len (results)):
213                 for h in results[i][0].split(','):
214                     hostgroup = h
215                     hostname = results[i][1]
216                     credentials = results[i][2]
217                     diag.append([hostgroup, hostname, credentials])
218
219     return errorCode, diag
220     
221
222 if __name__ == '__main__':
223
224     ################################################################
225     # Change below
226     ################################################################
227     host="localhost"                    # your host, usually localhost
228     user="mysql_user_id"                # your username
229     passwd="password_4_mysql_user_id"   # your password
230     db="ansible"                        # name of the data base
231
232     playbook_path = "/home/ubuntu/RestServerOpenSource/"
233     inventory = "/home/ubuntu/RestServerOpenSource/Ansible_inventory"
234     ################################################################
235
236     onlyfiles = [f for f in listdir(playbook_path)
237                  if isfile(join(playbook_path, f))]
238
239     sqlintf = mySql (host, user, passwd, db)
240
241     # Load playbooks
242
243     print "Loading playbooks"
244     for file in onlyfiles:
245         if "yml" in file:
246
247             name = file.split (".yml")[0]
248             print "  Loading:", name
249             version = name.split("@")[1]
250             errorCode, diag = loadPlaybook (sqlintf, name, version, '.yml')
251             if errorCode:
252                 print "  Results: Failed - ", diag
253             else:
254                 print "  Results: Success"
255
256     print "\nLoading inventory"
257     
258     # Load inventory
259
260     hostgroup = None
261     inv = {}
262     file = open(inventory, 'r')
263
264     for line in file:
265
266         if '[' in line and ']' in line:
267             hostgroup = line.strip().replace('[','').replace(']','')
268             inv[hostgroup] = {}
269         elif hostgroup and len(line.strip())>0:
270             host = line.strip().split(" ")[0]
271             credentials = line.replace(host,"")
272             inv[hostgroup][host] = credentials
273                                
274     file.close()
275
276     for hostgroup in inv:
277         print "  Loading:", hostgroup
278         hostfqdn = ''
279         cred = ''
280         for hostname in inv[hostgroup]:
281             cred = inv[hostgroup][hostname]
282             errorCode, diag = loadCredentials (sqlintf, hostgroup, hostname, cred)
283             if errorCode:
284                 print "  Results: Failed - ", diag
285             else:
286                 print "  Results: Success"
287                 
288     print "\nReading playbook"
289     
290     # Read playbook
291
292     if not sqlintf.con:
293         print "Cannot connect to MySql:", sqlintf.error
294         sys.exit()
295         
296     name = "ansible_sleep"
297     print "Reading playbook:", name
298     value, version, errorCode, diag = readPlaybook (sqlintf, name)
299     if errorCode:
300         print "Results: Failed - ", diag
301     else:
302         print "Results: Success"
303         print value
304         print version
305         print diag
306
307     print "\nReading inventory"
308
309     # Read inventory
310
311     tag = ["your_inventory_test_group_name"]
312     print "Reading inventory tag:", tag
313     errorCode, diag = readCredentials (sqlintf, tag)
314     if errorCode:
315         print "Results: Failed - ", diag
316     else:
317         print "Results: Success"
318         print diag
319                 
320     sqlintf.Close()
321