harbor/tools/migration/export

110 lines
3.2 KiB
Plaintext
Raw Normal View History

#!/usr/bin/python
import json
import fileinput
from optparse import OptionParser
import os
import MySQLdb
import sys
class Parameters(object):
def __init__(self):
self.dbuser = ''
self.dbpwd = ''
self.exportpath = ''
self.init_from_input()
@staticmethod
def parse_input():
usage = "usage: %prog [options] <dbuser> <dbpwd> <exportpath>"
parser = OptionParser(usage)
parser.add_option("-u", "--dbuser", dest="dbuser", help="db user")
parser.add_option("-p", "--dbpwd", dest="dbpwd", help="db password")
parser.add_option("-o", "--exportpath", dest="exportpath", help="the path of exported json file")
(options, args) = parser.parse_args()
return (options.dbuser, options.dbpwd, options.exportpath)
def init_from_input(self):
(self.dbuser, self.dbpwd, self.exportpath) = Parameters.parse_input()
class Project:
def __init__(self, project_id, name, public):
self.project_id = project_id
self.project_name = name
if public == 0:
self.public = "false"
elif public == 1:
self.public = "true"
else:
self.public = "false"
class HarborUtil:
def __init__(self, dbuser, dbpwd):
self.serverName = 'localhost'
self.user = dbuser
self.password = dbpwd
self.port = '3306'
self.subDB = 'registry'
self.db = None
self.cursor = None
def connect(self):
try:
self.db = MySQLdb.connect(host=self.serverName, user=self.user,
passwd=self.password, db=self.subDB)
self.cursor = self.db.cursor()
except Exception, e:
raise Exception(e)
def close(self):
try:
self.cursor.close()
self.db.close()
except Exception, e:
print str(e)
def get_projects(self):
projects = []
try:
query = "SELECT project_id, name, public from registry.project where deleted=0"
self.cursor.execute(query)
self.cursor.fetchall()
for result in self.cursor:
projects.append(Project(int(result[0]), result[1], result[2]))
return projects
except Exception, e:
raise Exception(e)
def delfile(src):
if not os.path.exists(src):
return
try:
os.remove(src)
except Exception, e:
raise Exception("unable to delete file: %s, error: %s" % (src, str(e)))
def main():
commandline_input = Parameters()
harbor = HarborUtil(commandline_input.dbuser, commandline_input.dbpwd)
try:
harbor.connect()
projects = harbor.get_projects()
if len(projects) == 0:
return
harbor_projects_json = commandline_input.exportpath + '/harbor_projects.json'
delfile(harbor_projects_json)
with open(harbor_projects_json, 'w') as outfile:
json.dump({'projects': [project.__dict__ for project in projects]}, outfile, sort_keys=True, indent=4)
except Exception, e:
print e
sys.exit(1)
finally:
harbor.close()
if __name__ == '__main__':
main()