migrate ansible server python scripts to python3
[ccsdk/distribution.git] / ansible-server / src / main / ansible-server / LoadAnsibleMySql.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 #!/usr/bin/python
27 import pymysql
28 from os import listdir
29 from os.path import isfile, join
30
31 class mySql():
32     
33     def __init__(self, myhost, myuser, mypasswd, mydb):
34         self.db = pymysql.connect(host=myhost,
35                                   user=myuser,
36                                   passwd=mypasswd,
37                                   db=mydb)
38         self.cur = self.db.cursor()
39
40     def Query (self, myquery, val = None):
41         results = None
42         error = None
43         try:
44             if val:
45                 self.cur.execute(myquery, val)
46             else:
47                 self.cur.execute(myquery)
48             self.db.commit()
49             results = self.cur.fetchall()
50         except Exception as e:
51             error = str (e)
52         return results, error
53
54     def Close (self):
55         self.db.close()
56
57 def loadPlaybook (value, version, ext = '.yml'):
58
59     errorCode = 0
60     diag = ''
61     
62     # Test if primary key already defined
63     query = "SELECT name FROM playbook WHERE name='" + value +"'"
64     results, error = sqlintf.Query (query)
65     if results:
66         # print "Primary key already defined: Updating playbook"
67         pass
68     else:
69         # print "Primary key not defined: Insert new playbook"
70         query = "INSERT INTO playbook (name) VALUES ('" + value + "')"
71         results, error = sqlintf.Query (query)
72         if error:
73             errorCode = 1
74             diag = error
75
76     # Load playbook
77     file = open(playbook_path + value + ext, 'r')
78     load_file = file.read()
79         
80     # Load playbook
81
82     if not errorCode:
83         sql = "UPDATE playbook SET value=%s, version=%s, type=%s WHERE name=%s"
84
85         results, error = sqlintf.Query(sql, (load_file, version, ext, value))
86
87         if error:
88             # Error loading playbook
89             errorCode = 1
90             diag = error
91             
92     return errorCode, diag
93
94 def loadCredentials (hostgroup, hostname, cred):
95     errorCode = 0
96     diag = ''
97     
98     # Load credentials
99
100     query = "SELECT hostname,hostgroup FROM inventory WHERE hostname='" + hostname +"'"
101     results = sqlintf.Query (query)
102
103     print('==>', results)
104     
105     if hostname in str(results):
106
107         results_hostgroups = results[0][0][1]
108
109         # print "Record already defined: Updating inventory"
110         if hostgroup in results_hostgroups.split(','):
111             query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
112                     cred +\
113                     "' WHERE hostname='" + hostname + "'"
114         else:
115             
116             results_hostgroups = results_hostgroups + ',' + hostgroup
117
118             query = "UPDATE inventory SET hostname='" + hostname + "',credentials='" +\
119                     cred + "',hostgroup='" + results_hostgroups + \
120                     "' WHERE hostname='" + hostname + "'"
121
122         results, error = sqlintf.Query (query)
123         
124     else:
125         
126         query = "INSERT INTO inventory (hostgroup, hostname, credentials) VALUES ('" + \
127                 hostgroup + "','" + hostname + "','" + cred + "')"
128         results, error = sqlintf.Query (query)
129
130     if error:
131         # Error loading credentials
132         errorCode = 1
133         diag = results
134
135     return errorCode, diag
136     
137
138 if __name__ == '__main__':
139
140     ################################################################
141     # Change below
142     ################################################################
143     host="localhost"                    # your host, usually localhost
144     user="mysql_user_id"                # your username
145     passwd="password_4_mysql_user_id"   # your password
146     db="ansible"                        # name of the data base
147
148     playbook_path = "/home/ubuntu/RestServerOpenSource/"
149     inventory = "/home/ubuntu/RestServerOpenSource/Ansible_inventory"
150     ################################################################
151     
152     onlyfiles = [f for f in listdir(playbook_path)
153                  if isfile(join(playbook_path, f))]
154
155     sqlintf = mySql (host, user, passwd, db)
156
157     # Load playbooks
158     print("Loading playbooks")
159     for file in onlyfiles:
160         if "yml" in file:
161             name = file.split (".yml")[0]
162             print("  Loading:", name)
163             version = name.split("@")[1]
164             errorCode, diag = loadPlaybook (name, version)
165             if errorCode:
166                 print("  Results: Failed - ", diag)
167             else:
168                 print("  Results: Success")
169         if "tar.gz" in file:
170             name = file.split (".tar.gz")[0]
171             print("  Loading:", name)
172             version = name.split("@")[1]
173             errorCode, diag = loadPlaybook (name, version, ".tar.gz")
174
175     print("\nLoading inventory")
176     
177     # Load inventory
178     hostgroup = None
179     inv = {}
180     file = open(inventory, 'r')
181
182     for line in file:
183
184         if '[' in line and ']' in line:
185             hostgroup = line.strip().replace('[','').replace(']','')
186             inv[hostgroup] = {}
187         elif hostgroup and len(line.strip())>0:
188             host = line.strip().split(" ")[0]
189             credentials = line.replace(host,"")
190             inv[hostgroup][host] = credentials
191                                
192     file.close()
193
194     for hostgroup in inv:
195         print("  Loading:", hostgroup)
196         hostfqdn = ''
197         cred = ''
198         for hostname in inv[hostgroup]:
199             cred = inv[hostgroup][hostname]
200             errorCode, diag = loadCredentials (hostgroup, hostname, cred)
201             if errorCode:
202                 print("  Results: Failed - ", diag)
203             else:
204                 print("  Results: Success")
205                 
206     sqlintf.Close()