- fix random bugs
[plcapi.git] / tools / upgrade-db.py
1 #!/usr/bin/python
2 #
3 # Tool for upgrading a db based on db version #
4 import sys
5 import os
6 import getopt
7 import pgdb
8
9 config = {}
10 config_file = "/etc/planetlab/plc_config"
11 execfile(config_file, config)
12 upgrade_config_file = "plcdb.3-4.conf"
13 schema_file = "planetlab4.sql"
14 temp_dir = "/tmp"
15
16
17 def usage():
18         print "Usage: %s [OPTION] UPGRADE_CONFIG_FILE " % sys.argv[0]
19         print "Options:"
20         print "     -s, --schema=FILE       Upgraded Database Schema"
21         print "     -t, --temp-dir=DIR      Temp Directory"
22         print "     --help                  This message"
23         sys.exit(1)
24
25 try:
26         (opts, argv) = getopt.getopt(sys.argv[1:],
27                                      "s:d:",
28                                      ["schema=",
29                                       "temp-dir=",
30                                       "help"])
31 except getopt.GetoptError, err:
32         print "Error: ", err.msg
33         usage()
34
35 for (opt, optval) in opts:
36         if opt == "-s" or opt == "--schema":
37                 schema_file = optval
38         elif opt == "-d" or opt == "--temp-dir":
39                 temp_dir = optval
40         elif opt == "--help":
41                 usage()
42 try:
43         upgrade_config_file = argv[0]
44 except IndexError:
45         print "Error: too few arguments"
46         usage()
47
48 schema = {}
49 inserts = []
50 schema_items_ordered = []
51 temp_tables = {}
52
53
54 # load conf file for this upgrade
55 try:
56         upgrade_config = {}
57         execfile(upgrade_config_file, upgrade_config)
58         upgrade_config.pop('__builtins__')
59         db_version_previous = upgrade_config['DB_VERSION_PREVIOUS']
60         db_version_new = upgrade_config['DB_VERSION_NEW']
61
62 except IOError, fault:
63         print "Error: upgrade config file (%s) not found. Exiting" % \
64                 (fault)
65         sys.exit(1) 
66 except KeyError, fault:
67         print "Error: %s not set in upgrade confing (%s). Exiting" % \
68                 (fault, upgrade_config_file)
69         sys.exit(1)
70
71
72
73
74 def connect():
75         db = pgdb.connect(user = config['PLC_DB_USER'],
76                   database = config['PLC_DB_NAME'])     
77         return db
78
79 def archive_db(database, archived_database):
80
81         print "Status: archiving old database"
82         archive_db = " dropdb -U postgres %s; > /dev/null 2>&1" \
83                      " psql template1 postgres -qc " \
84                      " 'ALTER DATABASE %s RENAME TO %s;';" \
85                      " createdb -U postgres %s > /dev/null; " % \
86                      (archived_database, database, archived_database, database)
87         exit_status = os.system(archive_db)
88         if exit_status:
89                 print "Error: unable to archive database. Upgrade failed"
90                 sys.exit(1)
91         print "Status: %s has been archived. now named %s" % (database, archived_database)
92
93
94 def encode_utf8(inputfile_name, outputfile_name):
95         # rewrite a iso-8859-1 encoded file and in utf8
96         try:
97                 inputfile = open(inputfile_name, 'r')
98                 outputfile = open(outputfile_name, 'w')
99                 for line in inputfile:
100                         outputfile.write(unicode(line, 'iso-8859-1').encode('utf8'))
101                 inputfile.close()
102                 outputfile.close()              
103         except:
104                 print 'error encoding file'
105                 raise
106
107 def create_item_from_schema(item_name):
108
109         try:
110                 (type, body_list) = schema[item_name]
111                 exit_status = os.system('psql %s %s -qc "%s" > /dev/null 2>&1' % \
112                             (config['PLC_DB_NAME'], config['PLC_DB_USER'],"".join(body_list) ) )
113                 if exit_status:
114                         raise Exception
115         except Exception, fault:
116                 print 'Error: create %s failed. Check schema.' % item_name
117                 sys.exit(1)
118                 raise fault
119
120         except KeyError:
121                 print "Error: cannot create %s. definition not found in %s" % \
122                         (key, schema_file)
123                 return False
124
125 def fix_row(row, table_name, table_fields):
126
127         if table_name in ['nodenetworks']:
128                 # convert str bwlimit to bps int
129                 bwlimit_index = table_fields.index('bwlimit')
130                 if isinstance(row[bwlimit_index], int):
131                         pass
132                 elif row[bwlimit_index].find('mbit') > -1:
133                         row[bwlimit_index] = int(row[bwlimit_index].split('mbit')[0]) \
134                                             * 1000000
135                 elif row[bwlimit_index].find('kbit') > -1:
136                         row[bwlimit_index] = int(row[bwlimit_index].split('kbit')[0]) \
137                                              * 1000
138         elif table_name in ['slice_attribute']:
139                 # modify some invalid foreign keys
140                 attribute_type_index = table_fields.index('attribute_type_id')
141                 if row[attribute_type_index] == 10004:
142                         row[attribute_type_index] = 10016
143                 elif row[attribute_type_index] == 10006:
144                         row[attribute_type_index] = 10017
145         elif table_name in ['slice_attribute_types']:
146                 type_id_index = table_fields.index('attribute_type_id')
147                 if row[type_id_index] in [10004, 10006]:
148                         return None
149         return row
150         
151 def fix_table(table, table_name, table_fields):
152         if table_name in ['slice_attribute_types']:
153                 # remove duplicate/redundant primary keys
154                 type_id_index = table_fields.index('attribute_type_id')
155                 for row in table:
156                         if row[type_id_index] in [10004, 10006]:
157                                 table.remove(row)
158         return table
159
160 def remove_temp_tables():
161         # remove temp_tables
162         try:
163                 for temp_table in temp_tables:
164                         os.remove(temp_tables[temp_table])
165         except:
166                 raise
167
168 def generate_temp_table(table_name, db):
169         cursor = db.cursor()
170         try:
171                 # get upgrade directions
172                 table_def = upgrade_config[table_name].replace('(', '').replace(')', '').split(',')
173                 table_fields, old_fields, required_joins = [], [], set()
174                 for field in table_def:
175                         field_parts = field.strip().split(':')
176                         table_fields.append(field_parts[0])
177                         old_fields.append(field_parts[1])
178                         if field_parts[2:]:
179                                 required_joins.update(set(field_parts[2:]))
180                 
181                 # get indices of fields that cannot be null
182                 (type, body_list) = schema[table_name]
183                 not_null_indices = []
184                 for field in table_fields:
185                         for body_line in body_list:
186                                 if body_line.find(field) > -1 and \
187                                    body_line.upper().find("NOT NULL") > -1:
188                                         not_null_indices.append(table_fields.index(field))
189
190                 # get index of primary key
191                 primary_key_indices = []
192                 for body_line in body_list:
193                         if body_line.find("PRIMARY KEY") > -1:
194                                 primary_key = body_line
195                                 for field in table_fields:
196                                         if primary_key.find(field) > -1:
197                                                 primary_key_indices.append(table_fields.index(field))
198                                 break
199
200                 # get old data
201                 get_old_data = "SELECT DISTINCT %s FROM %s" % \
202                       (", ".join(old_fields), old_fields[0].split(".")[0])
203                 for join in required_joins:
204                         get_old_data = get_old_data + " INNER JOIN %s USING (%s) " % \
205                                        (join.split('.')[0], join.split('.')[1])
206
207                 cursor.execute(get_old_data)
208                 rows = cursor.fetchall()
209
210                 # write data to a temp file
211                 temp_file_name = '%s/%s.tmp' % (temp_dir, table_name)
212                 temp_file = open(temp_file_name, 'w')
213                 for row in rows:
214                         # attempt to make any necessary fixes to data
215                         row = fix_row(row, table_name, table_fields)
216                         # do not attempt to write null rows
217                         if row == None:
218                                 continue
219                         # do not attempt to write rows with null primary keys
220                         if filter(lambda x: row[x] == None, primary_key_indices):
221                                 continue 
222                         for i in range(len(row)):
223                                 # convert nulls into something pg can understand
224                                 if row[i] == None:
225                                         if i in not_null_indices:
226                                                 # XX doesnt work if column is int type
227                                                 row[i] = ""
228                                         else: 
229                                                 row[i] = "\N"
230                                 if isinstance(row[i], int) or isinstance(row[i], float):
231                                         row[i] = str(row[i])
232                                 # escape whatever can mess up the data format
233                                 if isinstance(row[i], str):
234                                         row[i] = row[i].replace('\t', '\\t')
235                                         row[i] = row[i].replace('\n', '\\n')
236                                         row[i] = row[i].replace('\r', '\\r')
237                         data_row = "\t".join(row)
238                         temp_file.write(data_row + "\n")
239                 temp_file.write("\.\n")
240                 temp_file.close()
241                 temp_tables[table_name] = temp_file_name
242
243         except KeyError:
244                 #print "WARNING: cannot upgrade %s. upgrade def not found. skipping" % \
245                 #       (table_name)
246                 return False
247         except IndexError, fault:
248                 print "Error: error found in upgrade config file. " \
249                       "check %s configuration. Aborting " % \
250                       (table_name)
251                 sys.exit(1)
252         except:
253                 print "Error: configuration for %s doesnt match db schema. " \
254                       " Aborting" % (table_name)
255                 try:
256                         db.rollback()
257                 except:
258                         pass
259                 raise
260
261
262 # Connect to current db
263 db = connect()
264 cursor = db.cursor()
265
266 # determin current db version
267 try:
268         cursor.execute("SELECT relname from pg_class where relname = 'plc_db_version'")
269         rows = cursor.fetchall()
270         if not rows or not rows[0] or not rows[0][0]:
271                 print "WARNING: current db has no version. Unable to validate config file."
272         else:
273                 cursor.execute("SELECT version FROM plc_db_version")
274                 rows = cursor.fetchall()
275                 if rows[0][0] == db_version_new:
276                         print "Status: Versions are the same. No upgrade necessary."
277                         sys.exit()
278                 elif not rows[0][0] == db_version_previous:
279                         print "Stauts: DB_VERSION_PREVIOUS in config file (%s) does not" \
280                               " match current db version %d" % (upgrade_config_file, rows[0][0])
281                         sys.exit()
282                 else:
283                         print "STATUS: attempting upgrade from %d to %d" % \
284                                 (db_version_previous, db_version_new)   
285         
286         # check db encoding
287         sql = " SELECT pg_catalog.pg_encoding_to_char(d.encoding)" \
288               " FROM pg_catalog.pg_database d " \
289               " LEFT JOIN pg_catalog.pg_user u ON d.datdba = u.usesysid " \
290               " WHERE d.datname = '%s' " % config['PLC_DB_NAME']
291         cursor.execute(sql)
292         rows = cursor.fetchall()
293         if rows[0][0] not in ['UTF8']:
294                 print "WARNING: db encoding is not utf8. Attempting to encode"
295                 db.close()
296                 # generate db dump
297                 dump_file = '%s/dump.sql' % (temp_dir)
298                 dump_file_encoded = dump_file + ".utf8"
299                 dump_cmd = 'pg_dump -i %s -U %s -f %s > /dev/null 2>&1' % \
300                            (config['PLC_DB_NAME'], config['PLC_DB_USER'], dump_file)
301                 if os.system(dump_cmd):
302                         print "ERROR: during db dump. Exiting."
303                         sys.exit(1)
304                 # encode dump to utf8
305                 print "Status: encoding database dump"
306                 encode_utf8(dump_file, dump_file_encoded)
307                 # archive original db
308                 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_sqlascii_archived')
309                 # create a utf8 database and upload encoded data
310                 recreate_cmd = 'createdb -U postgres -E UTF8 %s > /dev/null 2>&1; ' \
311                                'psql -a -U  %s %s < %s > /dev/null 2>&1;'   % \
312                           (config['PLC_DB_NAME'], config['PLC_DB_USER'], \
313                            config['PLC_DB_NAME'], dump_file_encoded) 
314                 print "Status: recreating database as utf8"
315                 if os.system(recreate_cmd):
316                         print "Error: database encoding failed. Aborting"
317                         sys.exit(1)
318                 
319                 os.remove(dump_file_encoded)
320                 os.remove(dump_file)
321 except:
322         raise
323
324
325 db = connect()
326 cursor = db.cursor()
327
328 # parse the schema user wishes to upgrade to
329 try:
330         file = open(schema_file, 'r')
331         index = 0
332         lines = file.readlines()
333         while index < len(lines):
334                 line = lines[index] 
335                 # find all created objects
336                 if line.startswith("CREATE"):
337                         line_parts = line.split(" ")
338                         item_type = line_parts[1]
339                         item_name = line_parts[2]
340                         schema_items_ordered.append(item_name)
341                         if item_type in ['INDEX']:
342                                 schema[item_name] = (item_type, line)
343                         
344                         # functions, tables, views span over multiple lines
345                         # handle differently than indexes
346                         elif item_type in ['AGGREGATE', 'TABLE', 'VIEW']:
347                                 fields = [line]
348                                 while index < len(lines):
349                                         index = index + 1
350                                         nextline =lines[index]
351                                         fields.append(nextline)
352                                         if nextline.find(";") >= 0:
353                                                 break
354                                 schema[item_name] = (item_type, fields)
355                         else:
356                                 print "Error: unknown type %s" % item_type
357                 elif line.startswith("INSERT"):
358                         inserts.append(line)
359                 index = index + 1
360                                 
361 except:
362         raise
363
364 print "Status: generating temp tables"
365 # generate all temp tables
366 for key in schema_items_ordered:
367         (type, body_list) = schema[key]
368         if type == 'TABLE':
369                 generate_temp_table(key, db)
370
371 # disconenct from current database and archive it
372 cursor.close()
373 db.close()
374
375 print "Status: archiving database"
376 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived')
377
378
379 print "Status: upgrading database"
380 # attempt to create and load all items from schema into temp db
381 try:
382         for key in schema_items_ordered:
383                 (type, body_list) = schema[key]
384                 create_item_from_schema(key)
385                 if type == 'TABLE':
386                         if upgrade_config.has_key(key):                         
387                                 table_def = upgrade_config[key].replace('(', '').replace(')', '').split(',')
388                                 table_fields = [field.strip().split(':')[0] for field in table_def]
389                                 insert_cmd = "psql %s %s -c " \
390                                              " 'COPY %s (%s) FROM stdin;' < %s " % \
391                                              (config['PLC_DB_NAME'], config['PLC_DB_USER'], key, ", ".join(table_fields), temp_tables[key] )
392                                 exit_status = os.system(insert_cmd)
393                                 if exit_status:
394                                         print "Error: upgrade %s failed" % key
395                                         raise
396                         else:
397                                 # check if there are any insert stmts in schema for this table
398                                 print "Warning: %s has no temp data file. Unable to populate with old data" % key
399                                 for insert_stmt in inserts:
400                                         if insert_stmt.find(key) > -1:
401                                                 insert_cmd = 'psql %s postgres -qc "%s;" > /dev/null 2>&1' % \
402                                                 (config['PLC_DB_NAME'], insert_stmt)
403                                                 os.system(insert_cmd) 
404 except:
405         print "Error: failed to populate db. Unarchiving original database and aborting"
406         undo_command = "dropdb -U postgres %s; psql template1 postgres -qc" \
407                        " 'ALTER DATABASE %s RENAME TO %s;';  > /dev/null" % \
408                        (config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived', config['PLC_DB_NAME'])
409         os.system(undo_command) 
410         remove_temp_tables()
411         raise
412         
413 remove_temp_tables()
414
415 print "upgrade complete"