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