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 = []
54 # load conf file for this upgrade
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']
62 except IOError, fault:
63 print "Error: upgrade config file (%s) not found. Exiting" % \
66 except KeyError, fault:
67 print "Error: %s not set in upgrade confing (%s). Exiting" % \
68 (fault, upgrade_config_file)
75 db = pgdb.connect(user = config['PLC_DB_USER'],
76 database = config['PLC_DB_NAME'])
79 def archive_db(database, archived_database):
81 archive_db = " dropdb -U postgres %s > /dev/null 2>&1;" \
82 " psql template1 postgres -qc " \
83 " 'ALTER DATABASE %s RENAME TO %s;';" \
84 " createdb -U postgres %s > /dev/null; " % \
85 (archived_database, database, archived_database, database)
86 exit_status = os.system(archive_db)
88 print "Error: unable to archive database. Upgrade failed"
90 #print "Status: %s has been archived. now named %s" % (database, archived_database)
93 def encode_utf8(inputfile_name, outputfile_name):
94 # rewrite a iso-8859-1 encoded file in utf8
96 inputfile = open(inputfile_name, 'r')
97 outputfile = open(outputfile_name, 'w')
98 for line in inputfile:
99 outputfile.write(unicode(line, 'iso-8859-1').encode('utf8'))
103 print 'error encoding file'
106 def create_item_from_schema(item_name):
109 (type, body_list) = schema[item_name]
110 exit_status = os.system('psql %s %s -qc "%s" > /dev/null 2>&1' % \
111 (config['PLC_DB_NAME'], config['PLC_DB_USER'],"".join(body_list) ) )
114 except Exception, fault:
115 print 'Error: create %s failed. Check schema.' % item_name
120 print "Error: cannot create %s. definition not found in %s" % \
124 def fix_row(row, table_name, table_fields):
126 if table_name in ['nodenetworks']:
127 # convert str bwlimit to bps int
128 bwlimit_index = table_fields.index('bwlimit')
129 if isinstance(row[bwlimit_index], int):
131 elif row[bwlimit_index].find('mbit') > -1:
132 row[bwlimit_index] = int(row[bwlimit_index].split('mbit')[0]) \
134 elif row[bwlimit_index].find('kbit') > -1:
135 row[bwlimit_index] = int(row[bwlimit_index].split('kbit')[0]) \
137 elif table_name in ['slice_attribute']:
138 # modify some invalid foreign keys
139 attribute_type_index = table_fields.index('attribute_type_id')
140 if row[attribute_type_index] == 10004:
141 row[attribute_type_index] = 10016
142 elif row[attribute_type_index] == 10006:
143 row[attribute_type_index] = 10017
144 elif table_name in ['slice_attribute_types']:
145 type_id_index = table_fields.index('attribute_type_id')
146 if row[type_id_index] in [10004, 10006]:
150 def fix_table(table, table_name, table_fields):
151 if table_name in ['slice_attribute_types']:
152 # remove duplicate/redundant primary keys
153 type_id_index = table_fields.index('attribute_type_id')
155 if row[type_id_index] in [10004, 10006]:
159 def remove_temp_tables():
162 for temp_table in temp_tables:
163 os.remove(temp_tables[temp_table])
167 def generate_temp_table(table_name, db):
170 # get upgrade directions
171 table_def = upgrade_config[table_name].replace('(', '').replace(')', '').split(',')
172 table_fields, old_fields, required_joins = [], [], set()
173 for field in table_def:
174 field_parts = field.strip().split(':')
175 table_fields.append(field_parts[0])
176 old_fields.append(field_parts[1])
178 required_joins.update(set(field_parts[2:]))
180 # get indices of fields that cannot be null
181 (type, body_list) = schema[table_name]
182 not_null_indices = []
183 for field in table_fields:
184 for body_line in body_list:
185 if body_line.find(field) > -1 and \
186 body_line.upper().find("NOT NULL") > -1:
187 not_null_indices.append(table_fields.index(field))
189 # get index of primary key
190 primary_key_indices = []
191 for body_line in body_list:
192 if body_line.find("PRIMARY KEY") > -1:
193 primary_key = body_line
194 for field in table_fields:
195 if primary_key.find(field) > -1:
196 primary_key_indices.append(table_fields.index(field))
200 get_old_data = "SELECT DISTINCT %s FROM %s" % \
201 (", ".join(old_fields), old_fields[0].split(".")[0])
202 for join in required_joins:
203 get_old_data = get_old_data + " INNER JOIN %s USING (%s) " % \
204 (join.split('.')[0], join.split('.')[1])
206 cursor.execute(get_old_data)
207 rows = cursor.fetchall()
209 # write data to a temp file
210 temp_file_name = '%s/%s.tmp' % (temp_dir, table_name)
211 temp_file = open(temp_file_name, 'w')
213 # attempt to make any necessary fixes to data
214 row = fix_row(row, table_name, table_fields)
215 # do not attempt to write null rows
218 # do not attempt to write rows with null primary keys
219 if filter(lambda x: row[x] == None, primary_key_indices):
221 for i in range(len(row)):
222 # convert nulls into something pg can understand
224 if i in not_null_indices:
225 # XX doesnt work if column is int type
229 if isinstance(row[i], int) or isinstance(row[i], float):
231 # escape whatever can mess up the data format
232 if isinstance(row[i], str):
233 row[i] = row[i].replace('\t', '\\t')
234 row[i] = row[i].replace('\n', '\\n')
235 row[i] = row[i].replace('\r', '\\r')
236 data_row = "\t".join(row)
237 temp_file.write(data_row + "\n")
238 temp_file.write("\.\n")
240 temp_tables[table_name] = temp_file_name
243 #print "WARNING: cannot upgrade %s. upgrade def not found. skipping" % \
246 except IndexError, fault:
247 print "Error: error found in upgrade config file. " \
248 "check %s configuration. Aborting " % \
252 print "Error: configuration for %s doesnt match db schema. " \
253 " Aborting" % (table_name)
261 # Connect to current db
265 # determin current db version
267 cursor.execute("SELECT relname from pg_class where relname = 'plc_db_version'")
268 rows = cursor.fetchall()
270 print "Warning: current db has no version. Unable to validate config file."
272 cursor.execute("SELECT version FROM plc_db_version")
273 rows = cursor.fetchall()
274 if not rows or not rows[0]:
275 print "Warning: current db has no version. Unable to validate config file."
276 elif rows[0][0] == db_version_new:
277 print "Status: Versions are the same. No upgrade necessary."
279 elif not rows[0][0] == db_version_previous:
280 print "Stauts: DB_VERSION_PREVIOUS in config file (%s) does not" \
281 " match current db version %d" % (upgrade_config_file, rows[0][0])
284 print "STATUS: attempting upgrade from %d to %d" % \
285 (db_version_previous, db_version_new)
288 sql = " SELECT pg_catalog.pg_encoding_to_char(d.encoding)" \
289 " FROM pg_catalog.pg_database d " \
290 " LEFT JOIN pg_catalog.pg_user u ON d.datdba = u.usesysid " \
291 " WHERE d.datname = '%s' " % config['PLC_DB_NAME']
293 rows = cursor.fetchall()
294 if rows[0][0] not in ['UTF8']:
295 print "WARNING: db encoding is not utf8. Attempting to encode"
298 dump_file = '%s/dump.sql' % (temp_dir)
299 dump_file_encoded = dump_file + ".utf8"
300 dump_cmd = 'pg_dump -i %s -U %s -f %s > /dev/null 2>&1' % \
301 (config['PLC_DB_NAME'], config['PLC_DB_USER'], dump_file)
302 if os.system(dump_cmd):
303 print "ERROR: during db dump. Exiting."
305 # encode dump to utf8
306 print "Status: encoding database dump"
307 encode_utf8(dump_file, dump_file_encoded)
308 # archive original db
309 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_sqlascii_archived')
310 # create a utf8 database and upload encoded data
311 recreate_cmd = 'createdb -U postgres -E UTF8 %s > /dev/null 2>&1; ' \
312 'psql -a -U %s %s < %s > /dev/null 2>&1;' % \
313 (config['PLC_DB_NAME'], config['PLC_DB_USER'], \
314 config['PLC_DB_NAME'], dump_file_encoded)
315 print "Status: recreating database as utf8"
316 if os.system(recreate_cmd):
317 print "Error: database encoding failed. Aborting"
320 os.remove(dump_file_encoded)
329 # parse the schema user wishes to upgrade to
331 file = open(schema_file, 'r')
333 lines = file.readlines()
334 while index < len(lines):
336 # find all created objects
337 if line.startswith("CREATE"):
338 line_parts = line.split(" ")
339 item_type = line_parts[1]
340 item_name = line_parts[2]
341 schema_items_ordered.append(item_name)
342 if item_type in ['INDEX']:
343 schema[item_name] = (item_type, line)
345 # functions, tables, views span over multiple lines
346 # handle differently than indexes
347 elif item_type in ['AGGREGATE', 'TABLE', 'VIEW']:
349 while index < len(lines):
351 nextline =lines[index]
352 fields.append(nextline)
353 if nextline.find(";") >= 0:
355 schema[item_name] = (item_type, fields)
357 print "Error: unknown type %s" % item_type
358 elif line.startswith("INSERT"):
365 print "Status: generating temp tables"
366 # generate all temp tables
367 for key in schema_items_ordered:
368 (type, body_list) = schema[key]
370 generate_temp_table(key, db)
372 # disconenct from current database and archive it
376 print "Status: archiving database"
377 archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived')
380 print "Status: upgrading database"
381 # attempt to create and load all items from schema into temp db
383 for key in schema_items_ordered:
384 (type, body_list) = schema[key]
385 create_item_from_schema(key)
387 if upgrade_config.has_key(key):
388 table_def = upgrade_config[key].replace('(', '').replace(')', '').split(',')
389 table_fields = [field.strip().split(':')[0] for field in table_def]
390 insert_cmd = "psql %s %s -c " \
391 " 'COPY %s (%s) FROM stdin;' < %s " % \
392 (config['PLC_DB_NAME'], config['PLC_DB_USER'], key, ", ".join(table_fields), temp_tables[key] )
393 exit_status = os.system(insert_cmd)
395 print "Error: upgrade %s failed" % key
398 # check if there are any insert stmts in schema for this table
399 print "Warning: %s has no temp data file. Unable to populate with old data" % key
400 for insert_stmt in inserts:
401 if insert_stmt.find(key) > -1:
402 insert_cmd = 'psql %s postgres -qc "%s;" > /dev/null 2>&1' % \
403 (config['PLC_DB_NAME'], insert_stmt)
404 os.system(insert_cmd)
406 print "Error: failed to populate db. Unarchiving original database and aborting"
407 undo_command = "dropdb -U postgres %s > /dev/null; psql template1 postgres -qc" \
408 " 'ALTER DATABASE %s RENAME TO %s;'; > /dev/null" % \
409 (config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived', config['PLC_DB_NAME'])
410 os.system(undo_command)
416 print "upgrade complete"