3 # Tool for upgrading a db based on db version #
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"
18 print "Usage: %s [OPTION] UPGRADE_CONFIG_FILE " % sys.argv[0]
20 print " -s, --schema=FILE Upgraded Database Schema"
21 print " -t, --temp-dir=DIR Temp Directory"
22 print " --help This message"
26 (opts, argv) = getopt.getopt(sys.argv[1:],
31 except getopt.GetoptError, err:
32 print "Error: ", err.msg
35 for (opt, optval) in opts:
36 if opt == "-s" or opt == "--schema":
38 elif opt == "-d" or opt == "--temp-dir":
43 upgrade_config_file = argv[0]
45 print "Error: too few arguments"
50 schema_items_ordered = []
55 # load conf file for this upgrade
58 execfile(upgrade_config_file, upgrade_config)
59 upgrade_config.pop('__builtins__')
60 db_version_previous = upgrade_config['DB_VERSION_PREVIOUS']
61 db_version_new = upgrade_config['DB_VERSION_NEW']
63 except IOError, fault:
64 print "Error: upgrade config file (%s) not found. Exiting" % \
67 except KeyError, fault:
68 print "Error: %s not set in upgrade confing (%s). Exiting" % \
69 (fault, upgrade_config_file)
76 db = pgdb.connect(user = config['PLC_DB_USER'],
77 database = config['PLC_DB_NAME'])
80 def archive_db(database, archived_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)
89 print "Error: unable to archive database. Upgrade failed"
91 #print "Status: %s has been archived. now named %s" % (database, archived_database)
94 def encode_utf8(inputfile_name, outputfile_name):
95 # rewrite a iso-8859-1 encoded file in utf8
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'))
104 print 'error encoding file'
107 def create_item_from_schema(item_name):
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) ) )
115 except Exception, fault:
116 print 'Error: create %s failed. Check schema.' % item_name
121 print "Error: cannot create %s. definition not found in %s" % \
125 def fix_row(row, table_name, table_fields):
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):
132 elif row[bwlimit_index].find('mbit') > -1:
133 row[bwlimit_index] = int(row[bwlimit_index].split('mbit')[0]) \
135 elif row[bwlimit_index].find('kbit') > -1:
136 row[bwlimit_index] = int(row[bwlimit_index].split('kbit')[0]) \
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]:
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')
156 if row[type_id_index] in [10004, 10006]:
160 def remove_temp_tables():
163 for temp_table in temp_tables:
164 os.remove(temp_tables[temp_table])
168 def generate_temp_table(table_name, db):
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])
179 required_joins.update(set(field_parts[2:]))
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))
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))
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])
207 cursor.execute(get_old_data)
208 rows = cursor.fetchall()
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')
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
219 # do not attempt to write rows with null primary keys
220 if filter(lambda x: row[x] == None, primary_key_indices):
222 for i in range(len(row)):
223 # convert nulls into something pg can understand
225 if i in not_null_indices:
226 # XX doesnt work if column is int type
230 if isinstance(row[i], int) or isinstance(row[i], float):
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")
241 temp_tables[table_name] = temp_file_name
244 #print "WARNING: cannot upgrade %s. upgrade def not found. skipping" % \
247 except IndexError, fault:
248 print "Error: error found in upgrade config file. " \
249 "check %s configuration. Aborting " % \
253 print "Error: configuration for %s doesnt match db schema. " \
254 " Aborting" % (table_name)
262 # Connect to current db
266 # determin current db version
268 cursor.execute("SELECT relname from pg_class where relname = 'plc_db_version'")
269 rows = cursor.fetchall()
271 print "Warning: current db has no version. Unable to validate config file."
273 cursor.execute("SELECT version FROM plc_db_version")
274 rows = cursor.fetchall()
275 if not rows or not rows[0]:
276 print "Warning: current db has no version. Unable to validate config file."
277 elif rows[0][0] == db_version_new:
278 print "Status: Versions are the same. No upgrade necessary."
280 elif not rows[0][0] == db_version_previous:
281 print "Stauts: DB_VERSION_PREVIOUS in config file (%s) does not" \
282 " match current db version %d" % (upgrade_config_file, rows[0][0])
285 print "STATUS: attempting upgrade from %d to %d" % \
286 (db_version_previous, db_version_new)
289 sql = " SELECT pg_catalog.pg_encoding_to_char(d.encoding)" \
290 " FROM pg_catalog.pg_database d " \
291 " LEFT JOIN pg_catalog.pg_user u ON d.datdba = u.usesysid " \
292 " WHERE d.datname = '%s' " % config['PLC_DB_NAME']
294 rows = cursor.fetchall()
295 if rows[0][0] not in ['UTF8']:
296 print "WARNING: db encoding is not utf8. Attempting to encode"
299 dump_file = '%s/dump.sql' % (temp_dir)
300 dump_file_encoded = dump_file + ".utf8"
301 dump_cmd = 'pg_dump -i %s -U postgres -f %s > /dev/null 2>&1' % \
302 (config['PLC_DB_NAME'], dump_file)
303 if os.system(dump_cmd):
304 print "ERROR: during db dump. Exiting."
306 # encode dump to utf8
307 print "Status: encoding database dump"
308 encode_utf8(dump_file, dump_file_encoded)
309 # archive original db
310 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_sqlascii_archived')
311 # create a utf8 database and upload encoded data
312 recreate_cmd = 'createdb -U postgres -E UTF8 %s > /dev/null 2>&1; ' \
313 'psql -a -U %s %s < %s > /dev/null 2>&1;' % \
314 (config['PLC_DB_NAME'], config['PLC_DB_USER'], \
315 config['PLC_DB_NAME'], dump_file_encoded)
316 print "Status: recreating database as utf8"
317 if os.system(recreate_cmd):
318 print "Error: database encoding failed. Aborting"
321 os.remove(dump_file_encoded)
330 # parse the schema user wishes to upgrade to
332 file = open(schema_file, 'r')
334 lines = file.readlines()
335 while index < len(lines):
337 # find all created objects
338 if line.startswith("CREATE"):
339 line_parts = line.split(" ")
340 item_type = line_parts[1]
341 item_name = line_parts[2]
342 schema_items_ordered.append(item_name)
343 if item_type in ['INDEX']:
344 schema[item_name] = (item_type, line)
346 # functions, tables, views span over multiple lines
347 # handle differently than indexes
348 elif item_type in ['AGGREGATE', 'TABLE', 'VIEW']:
350 while index < len(lines):
352 nextline =lines[index]
353 # look for any sequences
354 if item_type in ['TABLE'] and nextline.find('serial') > -1:
355 sequences[item_name] = nextline.strip().split()[0]
356 fields.append(nextline)
357 if nextline.find(";") >= 0:
359 schema[item_name] = (item_type, fields)
361 print "Error: unknown type %s" % item_type
362 elif line.startswith("INSERT"):
369 print "Status: generating temp tables"
370 # generate all temp tables
371 for key in schema_items_ordered:
372 (type, body_list) = schema[key]
374 generate_temp_table(key, db)
376 # disconenct from current database and archive it
380 print "Status: archiving database"
381 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived')
384 print "Status: upgrading database"
385 # attempt to create and load all items from schema into temp db
387 for key in schema_items_ordered:
388 (type, body_list) = schema[key]
389 create_item_from_schema(key)
391 if upgrade_config.has_key(key):
392 # attempt to populate with temp table data
393 table_def = upgrade_config[key].replace('(', '').replace(')', '').split(',')
394 table_fields = [field.strip().split(':')[0] for field in table_def]
395 insert_cmd = "psql %s %s -c " \
396 " 'COPY %s (%s) FROM stdin;' < %s " % \
397 (config['PLC_DB_NAME'], config['PLC_DB_USER'], key,
398 ", ".join(table_fields), temp_tables[key] )
399 exit_status = os.system(insert_cmd)
401 print "Error: upgrade %s failed" % key
403 # update the primary key sequence
404 if sequences.has_key(key):
405 sequence = key +"_"+ sequences[key] +"_seq"
406 update_seq = "psql %s %s -c " \
407 " \"select setval('%s', max(%s)) FROM %s;\" > /dev/null" % \
408 (config['PLC_DB_NAME'], config['PLC_DB_USER'], sequence,
410 exit_status = os.system(update_seq)
412 print "Error: sequence %s update failed" % sequence
415 # check if there are any insert stmts in schema for this table
416 print "Warning: %s has no temp data file. Unable to populate with old data" % key
417 for insert_stmt in inserts:
418 if insert_stmt.find(key) > -1:
419 insert_cmd = 'psql %s postgres -qc "%s;" > /dev/null 2>&1' % \
420 (config['PLC_DB_NAME'], insert_stmt)
421 os.system(insert_cmd)
423 print "Error: failed to populate db. Unarchiving original database and aborting"
424 undo_command = "dropdb -U postgres %s > /dev/null; psql template1 postgres -qc" \
425 " 'ALTER DATABASE %s RENAME TO %s;'; > /dev/null" % \
426 (config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived', config['PLC_DB_NAME'])
427 os.system(undo_command)
433 print "upgrade complete"