3 # Tool for upgrading/converting a db
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
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
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"
27 print "Usage: %s [OPTION] UPGRADE_CONFIG_FILE " % sys.argv[0]
29 print " -s, --schema=FILE Upgraded Database Schema"
30 print " -t, --temp-dir=DIR Temp Directory"
31 print " --help This message"
35 (opts, argv) = getopt.getopt(sys.argv[1:],
40 except getopt.GetoptError, err:
41 print "Error: ", err.msg
44 for (opt, optval) in opts:
45 if opt == "-s" or opt == "--schema":
47 elif opt == "-d" or opt == "--temp-dir":
52 upgrade_config_file = argv[0]
54 print "Error: too few arguments"
59 schema_items_ordered = []
64 # load conf file for this upgrade
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']
72 except IOError, fault:
73 print "Error: upgrade config file (%s) not found. Exiting" % \
76 except KeyError, fault:
77 print "Error: %s not set in upgrade confing (%s). Exiting" % \
78 (fault, upgrade_config_file)
85 db = pgdb.connect(user = config['PLC_DB_USER'],
86 database = config['PLC_DB_NAME'])
89 def archive_db(database, archived_database):
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)
97 print "Error: unable to archive database. Upgrade failed"
99 #print "Status: %s has been archived. now named %s" % (database, archived_database)
102 def encode_utf8(inputfile_name, outputfile_name):
103 # rewrite a iso-8859-1 encoded file in utf8
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:
110 outputfile.write(unicode(line, 'iso-8859-1').encode('utf8'))
114 print 'error encoding file'
117 def create_item_from_schema(item_name):
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) ) )
125 except Exception, fault:
126 print 'Error: create %s failed. Check schema.' % item_name
131 print "Error: cannot create %s. definition not found in %s" % \
135 def fix_row(row, table_name, table_fields):
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):
142 elif row[bwlimit_index].find('mbit') > -1:
143 row[bwlimit_index] = int(row[bwlimit_index].split('mbit')[0]) \
145 elif row[bwlimit_index].find('kbit') > -1:
146 row[bwlimit_index] = int(row[bwlimit_index].split('kbit')[0]) \
148 elif table_name in ['person_keys']:
149 deleted_index = table_fields.index('deleted')
150 if row[deleted_index] == True:
152 elif table_name in ['slice_attribute']:
153 # modify some invalid foreign keys
154 attribute_type_index = table_fields.index('attribute_type_id')
155 if row[attribute_type_index] == 10004:
156 row[attribute_type_index] = 10016
157 elif row[attribute_type_index] == 10006:
158 row[attribute_type_index] = 10017
159 elif row[attribute_type_index] in [10031, 10033]:
160 row[attribute_type_index] = 10037
161 elif row[attribute_type_index] in [10034, 10035]:
162 row[attribute_type_index] = 10036
163 elif table_name in ['slice_attribute_types']:
164 type_id_index = table_fields.index('attribute_type_id')
165 if row[type_id_index] in [10004, 10006, 10031, 10033, 10034, 10035]:
169 def fix_table(table, table_name, table_fields):
170 if table_name in ['slice_attribute_types']:
171 # remove duplicate/redundant primary keys
172 type_id_index = table_fields.index('attribute_type_id')
174 if row[type_id_index] in [10004, 10006, 10031, 10033, 10034, 10035]:
178 def remove_temp_tables():
181 for temp_table in temp_tables:
182 os.remove(temp_tables[temp_table])
186 def generate_temp_table(table_name, db):
189 # get upgrade directions
190 table_def = upgrade_config[table_name].replace('(', '').replace(')', '').split(',')
191 table_fields, old_fields, joins, wheres = [], [], set(), set()
192 for field in table_def:
193 field_parts = field.strip().split(':')
194 table_fields.append(field_parts[0])
195 old_fields.append(field_parts[1])
197 joins.update(set(filter(lambda x: not x.find('=') > -1, field_parts[2:])))
198 wheres.update(set(filter(lambda x: x.find('=') > -1, field_parts[2:])))
200 # get indices of fields that cannot be null
201 (type, body_list) = schema[table_name]
202 not_null_indices = []
203 for field in table_fields:
204 for body_line in body_list:
205 if body_line.find(field) > -1 and \
206 body_line.upper().find("NOT NULL") > -1:
207 not_null_indices.append(table_fields.index(field))
209 # get index of primary key
210 primary_key_indices = []
211 for body_line in body_list:
212 if body_line.find("PRIMARY KEY") > -1:
213 primary_key = body_line
214 for field in table_fields:
215 if primary_key.find(field) > -1:
216 primary_key_indices.append(table_fields.index(field))
220 get_old_data = "SELECT DISTINCT %s FROM %s" % \
221 (", ".join(old_fields), old_fields[0].split(".")[0])
223 get_old_data = get_old_data + " INNER JOIN %s USING (%s) " % \
224 (join.split('.')[0], join.split('.')[1])
226 get_old_data = get_old_data + " WHERE "
228 get_old_data = get_old_data + " %s" % where
229 cursor.execute(get_old_data)
230 rows = cursor.fetchall()
232 # write data to a temp file
233 temp_file_name = '%s/%s.tmp' % (temp_dir, table_name)
234 temp_file = open(temp_file_name, 'w')
236 # attempt to make any necessary fixes to data
237 row = fix_row(row, table_name, table_fields)
238 # do not attempt to write null rows
241 # do not attempt to write rows with null primary keys
242 if filter(lambda x: row[x] == None, primary_key_indices):
244 for i in range(len(row)):
245 # convert nulls into something pg can understand
247 if i in not_null_indices:
248 # XX doesnt work if column is int type
252 if isinstance(row[i], int) or isinstance(row[i], float):
254 # escape whatever can mess up the data format
255 if isinstance(row[i], str):
256 row[i] = row[i].replace('\t', '\\t')
257 row[i] = row[i].replace('\n', '\\n')
258 row[i] = row[i].replace('\r', '\\r')
259 data_row = "\t".join(row)
260 temp_file.write(data_row + "\n")
261 temp_file.write("\.\n")
263 temp_tables[table_name] = temp_file_name
266 #print "WARNING: cannot upgrade %s. upgrade def not found. skipping" % \
269 except IndexError, fault:
270 print "Error: error found in upgrade config file. " \
271 "check %s configuration. Aborting " % \
275 print "Error: configuration for %s doesnt match db schema. " \
276 " Aborting" % (table_name)
284 # Connect to current db
288 # determin current db version
290 cursor.execute("SELECT relname from pg_class where relname = 'plc_db_version'")
291 rows = cursor.fetchall()
293 print "Warning: current db has no version. Unable to validate config file."
295 cursor.execute("SELECT version FROM plc_db_version")
296 rows = cursor.fetchall()
297 if not rows or not rows[0]:
298 print "Warning: current db has no version. Unable to validate config file."
299 elif rows[0][0] == db_version_new:
300 print "Status: Versions are the same. No upgrade necessary."
302 elif not rows[0][0] == db_version_previous:
303 print "Stauts: DB_VERSION_PREVIOUS in config file (%s) does not" \
304 " match current db version %d" % (upgrade_config_file, rows[0][0])
307 print "STATUS: attempting upgrade from %d to %d" % \
308 (db_version_previous, db_version_new)
311 sql = " SELECT pg_catalog.pg_encoding_to_char(d.encoding)" \
312 " FROM pg_catalog.pg_database d " \
313 " WHERE d.datname = '%s' " % config['PLC_DB_NAME']
315 rows = cursor.fetchall()
316 if rows[0][0] not in ['UTF8', 'UNICODE']:
317 print "WARNING: db encoding is not utf8. Attempting to encode"
320 dump_file = '%s/dump.sql' % (temp_dir)
321 dump_file_encoded = dump_file + ".utf8"
322 dump_cmd = 'pg_dump -i %s -U postgres -f %s > /dev/null 2>&1' % \
323 (config['PLC_DB_NAME'], dump_file)
324 if os.system(dump_cmd):
325 print "ERROR: during db dump. Exiting."
327 # encode dump to utf8
328 print "Status: encoding database dump"
329 encode_utf8(dump_file, dump_file_encoded)
330 # archive original db
331 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_sqlascii_archived')
332 # create a utf8 database and upload encoded data
333 recreate_cmd = 'createdb -U postgres -E UTF8 %s > /dev/null; ' \
334 'psql -a -U %s %s < %s > /dev/null 2>&1;' % \
335 (config['PLC_DB_NAME'], config['PLC_DB_USER'], \
336 config['PLC_DB_NAME'], dump_file_encoded)
337 print "Status: recreating database as utf8"
338 if os.system(recreate_cmd):
339 print "Error: database encoding failed. Aborting"
342 os.remove(dump_file_encoded)
351 # parse the schema user wishes to upgrade to
353 file = open(schema_file, 'r')
355 lines = file.readlines()
356 while index < len(lines):
358 # find all created objects
359 if line.startswith("CREATE"):
360 line_parts = line.split(" ")
361 if line_parts[1:3] == ['OR', 'REPLACE']:
362 line_parts = line_parts[2:]
363 item_type = line_parts[1]
364 item_name = line_parts[2]
365 schema_items_ordered.append(item_name)
366 if item_type in ['INDEX']:
367 schema[item_name] = (item_type, line)
369 # functions, tables, views span over multiple lines
370 # handle differently than indexes
371 elif item_type in ['AGGREGATE', 'TABLE', 'VIEW']:
373 while index < len(lines):
375 nextline =lines[index]
376 # look for any sequences
377 if item_type in ['TABLE'] and nextline.find('serial') > -1:
378 sequences[item_name] = nextline.strip().split()[0]
379 fields.append(nextline)
380 if nextline.find(";") >= 0:
382 schema[item_name] = (item_type, fields)
384 print "Error: unknown type %s" % item_type
385 elif line.startswith("INSERT"):
392 print "Status: generating temp tables"
393 # generate all temp tables
394 for key in schema_items_ordered:
395 (type, body_list) = schema[key]
397 generate_temp_table(key, db)
399 # disconenct from current database and archive it
403 print "Status: archiving database"
404 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived')
405 os.system('createdb -U postgres -E UTF8 %s > /dev/null; ' % config['PLC_DB_NAME'])
407 print "Status: upgrading database"
408 # attempt to create and load all items from schema into temp db
410 for key in schema_items_ordered:
411 (type, body_list) = schema[key]
412 create_item_from_schema(key)
414 if upgrade_config.has_key(key):
415 # attempt to populate with temp table data
416 table_def = upgrade_config[key].replace('(', '').replace(')', '').split(',')
417 table_fields = [field.strip().split(':')[0] for field in table_def]
418 insert_cmd = "psql %s %s -c " \
419 " 'COPY %s (%s) FROM stdin;' < %s " % \
420 (config['PLC_DB_NAME'], config['PLC_DB_USER'], key,
421 ", ".join(table_fields), temp_tables[key] )
422 exit_status = os.system(insert_cmd)
424 print "Error: upgrade %s failed" % key
426 # update the primary key sequence
427 if sequences.has_key(key):
428 sequence = key +"_"+ sequences[key] +"_seq"
429 update_seq = "psql %s %s -c " \
430 " \"select setval('%s', max(%s)) FROM %s;\" > /dev/null" % \
431 (config['PLC_DB_NAME'], config['PLC_DB_USER'], sequence,
433 exit_status = os.system(update_seq)
435 print "Error: sequence %s update failed" % sequence
438 # check if there are any insert stmts in schema for this table
439 print "Warning: %s has no temp data file. Unable to populate with old data" % key
440 for insert_stmt in inserts:
441 if insert_stmt.find(key) > -1:
442 insert_cmd = 'psql %s postgres -qc "%s;" > /dev/null 2>&1' % \
443 (config['PLC_DB_NAME'], insert_stmt)
444 os.system(insert_cmd)
446 print "Error: failed to populate db. Unarchiving original database and aborting"
447 undo_command = "dropdb -U postgres %s > /dev/null; psql template1 postgres -qc" \
448 " 'ALTER DATABASE %s RENAME TO %s;'; > /dev/null" % \
449 (config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived', config['PLC_DB_NAME'])
450 os.system(undo_command)
456 print "upgrade complete"