摘要

到目前,我们完成了SQL Server备份还原专题系列八篇月报分享:三种常见的数据库备份、备份策略的制定、查找备份链、数据库的三种恢复模式与备份之间的关系、利用文件组实现冷热数据隔离备份方案、如何监控备份还原进度、阿里云RDS SQL自动化迁移上云的一种解决方案以及上个月分享的RDS SDK实现数据库迁移上阿里云,本期我们分享如何将用户线下或者ECS上自建实例级别数据库一键迁移上阿里云RDS SQL Server。

适用场景

在我们上一个月分享的RDS SDK实现数据库迁移上阿里云RDS SQL Server方案中,我们实现了如何将用户线下或者ECS上自建的SQL Server实例中的一个用户数据库自动化迁移上云到RDS SQL Server,话句话说,它实现的是数据库级别的迁移上云方案,即每次迁移上云用户线下一个数据库。

但是,有的用户可能会遇到这样的场景,我的线下有几十上百SQL Server实例,每个实例又有几十上百个数据库,总共就有成千上万个数据库迁移上云。如果是数据库级别的迁移上云方案显得力不从心,效率低下。为了解决用户大批量数据库迁移上云RDS for SQL Server,简化上云操作步骤,提高上云效率,实例级别数据库上云RDS SQL Server是我们迫切需要解决场景。

实现分析

由于在前一个月分享的RDS SDK实现数据库迁移上阿里云RDS SQL Server中,我们已经实现了单个数据库迁移上云方法,因此实现实例级别的迁移上云我们可以采用如下方案:

将用户线下实例上所有的数据库全量备份文件上传到OSS的一个文件夹中

遍历OSS上该文件夹所有的数据库备份文件

每一个备份文件生成一个迁移上云任务

输入参数

基于以上的分析,我们的实现方法需要包含如下六个输入参数,以及这六个输入参数的解析参见下表:

  1. access_key_id : 阿里云用户 access key id
  2. access_key_secret : 阿里云用户access key secret
  3. rds_instance_id : RDS SQL实例ID
  4. oss_endpoint : OSS Endpoint地址
  5. oss_bucket : OSS Bucket
  6. directory : 用户数据库备份文件在OSS上文件夹路径,如果是根目录,请传入“/”

具体实现

准备工作

参见上一个月的月报分享MSSQL · 最佳实践 · RDS SDK实现数据库迁移上阿里云RDS SQL Server中的准备工作部分。

代码实现

在本文,我们使用python版RDS SDK实现数据库迁移上云RDS SQL Server,当然你也可以使用C#版、Java版等其他版本,详细的代码实现如下:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """***************************************************************************************
  4. # Script name : RDSSQLCreateMigrateTasksBatchly.py
  5. # Author : jianming.wjm@alibaba-inc.com
  6. # Create Date : 2018-05-17 19:27
  7. # Language : Python 2.7.10
  8. # Run platform : Mac OS X 10.12.6
  9. # Purpose :
  10. This script is for batchly Migration user offline SQL Server databases to alibaba cloud RDS SQL Server.
  11. Users' FULL backup files are located on theirselves' OSS Bucket folder already.
  12. This script helps users to do migration all offline databases backed-up under the OSS Bucket folder to RDS SQL.
  13. We achieve those accomplishments by call alibaba cloud RDS OPENAPI.
  14. # Limitation :
  15. RDS Edition : Support RDS edition listed below
  16. '2012','2012_web','2012_std', '2012_ent', '2012_std_ha', '2012_ent_ha',
  17. '2014_web','2014_std', '2014_ent', '2014_std_ha', '2014_ent_ha',
  18. '2016_web','2016_std', '2016_ent', '2016_std_ha', '2016_ent_ha'
  19. # Preparation :
  20. 1. python 2.7.x installing (I'm using 2.7.10)
  21. 2. pip install aliyun-python-sdk-rds
  22. 3. pip install oss2
  23. # Usage :
  24. Help : python RDSSQLCreateMigrateTasksBatchly.py -h
  25. Example :
  26. python ~/Downloads/RDSSQLCreateMigrateTasksBatchly.py -k <access_key_id> -s <access_key_secret> -i <rds_instance_id> -e <oss_endpoint> -b <oss_bucket> -d <directory>
  27. variables description
  28. access_key_id : alibaba cloud user access key id, fg: LTAIKeRvKPRwkaU3
  29. access_key_secret : alibaba cloud user access key secret, fg: BbZ7xhrertQ0dfgMqfAZPByhnp4G2k
  30. rds_instance_id : RDS SQL instance ID, fg: rm-2zesz4564ud8s7123
  31. oss_endpoint : OSS Endpoint address, fg: oss-cn-beijing.aliyuncs.com
  32. oss_bucket : OSS Bucket name, fg: atp-test-on-ecs
  33. directory : Sub folder name under OSS Bucket, fg: Migration/OPENAPIDemo
  34. # Output : There two sesction output, one is the input variables and the other is the migration requests and response.
  35. *********************Input variables*************************************
  36. ************************************************************************
  37. *********************Migration requests**********************************
  38. ************************************************************************
  39. # Modify Author : jianming.wjm@alibaba-inc.com
  40. # Modify Date : 2018-05-19 21:43
  41. # Function:
  42. #**************************************************************************************
  43. """
  44. import json
  45. import os
  46. import sys, getopt
  47. import re
  48. import oss2
  49. import time
  50. from aliyunsdkcore.client import AcsClient
  51. from aliyunsdkrds.request.v20140815 import DescribeMigrateTasksForSQLServerRequest
  52. from aliyunsdkrds.request.v20140815 import CreateMigrateTaskRequest
  53. from aliyunsdkrds.request.v20140815 import DescribeDBInstanceAttributeRequest
  54. def main(argv):
  55. access_key_id = access_key_secret = rds_instance_id = oss_endpoint = oss_bucket = directory = ''
  56. # usage help
  57. try:
  58. opts, args = getopt.getopt(argv,"hk:s:i:e:b:d:",["access_key_id=", "access_key_secret=", "rds_instance_id=", "oss_endpoint=", "oss_bucket=", "directory="])
  59. except getopt.GetoptError:
  60. print ('%s -k <access_key_id> -s <access_key_secret> -i <rds_instance_id> -e <oss_endpoint> -b <oss_bucket> -d <directory>' % (sys.argv[0]))
  61. sys.exit(2)
  62. for opt, arg in opts:
  63. if opt == '-h':
  64. print ('%s -k <access_key_id> -s <access_key_secret> -i <rds_instance_id> -e <oss_endpoint> -b <oss_bucket> -d <directory>' % (sys.argv[0]))
  65. sys.exit()
  66. elif opt in ("-k", "-K", "--access_key_id"):
  67. access_key_id = arg
  68. elif opt in ("-s", "-S", "--access_key_secret"):
  69. access_key_secret = arg
  70. elif opt in ("-i", "-I", "--rds_instance_id"):
  71. rds_instance_id = arg
  72. elif opt in ("-e", "-E", "--oss_endpoint"):
  73. oss_endpoint = arg
  74. elif opt in ("-b", "-B", "--oss_bucket"):
  75. oss_bucket = arg
  76. elif opt in ("-d", "-D", "--directory"):
  77. if arg.endswith("/"):
  78. directory = arg
  79. else:
  80. directory = str("%s/" % arg)
  81. # show the input parameters
  82. print ("\n*********************Input variables*************************************\n" \
  83. "access_key_id = %s\naccess_key_secret = %s\nrds_instance_id = %s\noss_endpoint = %s\noss_bucket = %s\ndirectory = %s\n" \
  84. "************************************************************************"
  85. % (access_key_id, access_key_secret, rds_instance_id, oss_endpoint, oss_bucket, directory))
  86. # check RDS & OSS region to make sure they are located in the same region.
  87. success, rds_details = rds_instnace_details(access_key_id, access_key_secret, rds_instance_id)
  88. if not success:
  89. print ("%s" % rds_details)
  90. sys.exit()
  91. rds_db_version, rds_engine, rds_region = rds_details["EngineVersion"], rds_details["Engine"], rds_details["RegionId"]
  92. success, oss_details = oss_bucket_details(access_key_id, access_key_secret, oss_endpoint, oss_bucket)
  93. if not success:
  94. print ("%s" % oss_details)
  95. sys.exit()
  96. oss_region = oss_details.location
  97. # support db version checking.
  98. if rds_engine != 'SQLServer' \
  99. or rds_db_version not in [ '2008r2', '2012','2012_web','2012_std', '2012_ent', '2012_std_ha', '2012_ent_ha',
  100. '2014_web','2014_std', '2014_ent', '2014_std_ha', '2014_ent_ha',
  101. '2016_web','2016_std', '2016_ent', '2016_std_ha', '2016_ent_ha']:
  102. print("RDS engine doesn't support, this is only for RDS SQL Server engine.")
  103. sys.exit()
  104. # RDS & OSS Bucket are not under the same region.
  105. if not oss_region.endswith(rds_region):
  106. print("RDS & OSS Bucket are not located in the same region.")
  107. sys.exit()
  108. # RDS & OSS Bucket are in the same region.
  109. print ("\n*********************Migration requests**********************************")
  110. full_migrate(access_key_id, access_key_secret, rds_instance_id, oss_endpoint, oss_bucket, directory, rds_db_version)
  111. print ("************************************************************************")
  112. def rds_instnace_details(access_key_id, access_key_secret, rds_instance_id):
  113. request = DescribeDBInstanceAttributeRequest.DescribeDBInstanceAttributeRequest()
  114. request.set_DBInstanceId(rds_instance_id)
  115. success, response = _send_request(access_key_id, access_key_secret, request)
  116. if success:
  117. if response["Items"]["DBInstanceAttribute"]:
  118. # print response["Items"]["DBInstanceAttribute"][0]["EngineVersion"]
  119. # print response["Items"]["DBInstanceAttribute"][0]["RegionId"]
  120. return True, response["Items"]["DBInstanceAttribute"][0]
  121. else:
  122. return False, "Couldn't find specify RDS [%s]." % rds_instance_id
  123. return False, response
  1. def full_migrate(access_key_id, access_key_secret, rds_instance_id, oss_endpoint, oss_bucket, directory, rds_db_version):
  2. """
  3. this supoort full backup files migration.
  4. """
  5. # get all backup objects under sub_folder
  6. key_parts_list, do = oss_list_objects(access_key_id, access_key_secret, oss_endpoint, oss_bucket, directory), 0
  7. # foreach object
  8. for key_parts in key_parts_list:
  9. print ("\n--%s. [%s] migrate to your RDS: [%s] and the database name will be: [%s]." % (do, key_parts.file_key, rds_instance_id, key_parts.db_name))
  10. do += 1
  11. # print ("%s" % key_parts.sign_url)
  12. request = CreateMigrateTaskRequest.CreateMigrateTaskRequest()
  13. request.set_DBInstanceId(rds_instance_id)
  14. request.set_DBName(key_parts.db_name)
  15. request.set_BackupMode("FULL")
  16. request.set_IsOnlineDB(True)
  17. if rds_db_version == '2008r2':
  18. request.set_DBName(key_parts.db_name.lower())
  19. request.set_OSSUrls(key_parts.sign_url)
  20. else:
  21. request.set_OSSUrls("")
  22. request.set_OssObjectPositions("%s:%s:%s" % (oss_endpoint, oss_bucket, key_parts.file_key)) # OSSEndpoint:OSSBucket:OSSFileKey
  23. request.set_CheckDBMode("SyncExecuteDBCheck")
  24. success, response = _send_request(access_key_id, access_key_secret, request)
  25. if success:
  26. print response
  27. print ("--I'm sleeping for 2 seconds....")
  28. time.sleep(2)
  29. else:
  30. print ("OPENAPI Response Error !!!!! : %s" % response)
  31. """
  32. send request to OPENAPI
  33. and get the response details
  34. """
  35. def _send_request(access_key_id, access_key_secret, request, region='cn-hangzhou'):
  36. request.set_accept_format('json')
  37. try:
  38. # clt = AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
  39. clt = AcsClient(access_key_id, access_key_secret, region)
  40. response_str = clt.do_action_with_exception(request)
  41. response_detail = json.loads(response_str)
  42. return True, response_detail
  43. except Exception as e:
  44. return False, e
  45. class oss_key_parts(object):
  46. """
  47. if the whole object file key looks like blow:
  48. Migration/OPENAPIDemo/TestMigration_FULL_20180518153544.bak
  49. then
  50. : param str file_key: OSS object file key.
  51. : param str sub_folder: OSS sub folder name, such as Migration/OPENAPIDemo
  52. : param str file_name: OSS object file name, such as TestMigration_FULL_20180518153544.bak
  53. : param str db_name: database name, such as 'TestMigration'
  54. : param str bak_type: backup type , such as 'FULL'
  55. : param str date: backup date time, such as '20180518153544'
  56. : param str ext: backup file extendsion, such as 'bak'
  57. """
  58. def __init__(self):
  59. self.file_key = ''
  60. self.sub_folder = ''
  61. self.file_name = ''
  62. self.db_name = ''
  63. self.bak_type = ''
  64. self.date = ''
  65. self.ext = ''
  66. self.sign_url = ''
  67. """
  68. parse the OSS file key string into oss key parts
  69. and return oss_key_parts object.
  70. """
  71. def oss_key_parse(file_key):
  72. key_parts = oss_key_parts()
  73. try:
  74. if file_key.find('/') >= 0:
  75. file_key_parts = file_key.rsplit('/', 1)
  76. else:
  77. file_key_parts = file_key
  78. file_key_parts = ['/', file_key]
  79. key_parts.file_key = file_key
  80. key_parts.sub_folder = file_key_parts[0]
  81. key_parts.file_name = file_key_parts[1]
  82. key_list = file_key_parts[1].rsplit('_', 2)
  83. key_parts.db_name, \
  84. key_parts.bak_type, \
  85. key_parts.date, \
  86. key_parts.ext = key_list[0], \
  87. key_list[1], \
  88. key_list[2].rsplit('.', 1)[0], \
  89. key_list[2].rsplit('.', 1)[1]
  90. except Exception, e:
  91. pass
  92. return key_parts
  93. def oss_list_objects(access_key_id, access_key_secret, oss_endpoint, oss_bucket, directory):
  94. """
  95. list all OSS objects under the specified sub folder
  96. and return the objects list.
  97. """
  98. bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), oss_endpoint, oss_bucket)
  99. key_parts_list = []
  100. # OSS Bucket Root
  101. if directory == '/':
  102. for object_info in oss2.ObjectIterator(bucket, delimiter='/'):
  103. if not object_info.is_prefix():
  104. key_part = oss_key_parse(object_info.key)
  105. # get object sign_url
  106. key_part.sign_url = bucket.sign_url('GET', object_info.key, 24 * 3600)
  107. if key_part.ext in['bak', 'trn', 'log', 'diff']:
  108. key_parts_list.append(key_part)
  109. else:
  110. print ("Warning!!!!!, [%s] is not backup file, filtered." % (key_part.file_key))
  111. else:
  112. for i, object_info in enumerate(oss2.ObjectIterator(bucket, prefix=directory)):
  113. # have to the backup files, not folder
  114. if not object_info.is_prefix():
  115. if object_info.key.startswith(directory) and object_info.key != directory:
  116. # print ("%s" % (object_info.key))
  117. key_part = oss_key_parse(object_info.key)
  118. # get object sign_url
  119. key_part.sign_url = bucket.sign_url('GET', object_info.key, 24 * 3600)
  120. if key_part.ext in['bak', 'trn', 'log', 'diff']:
  121. key_parts_list.append(key_part)
  122. else:
  123. print ("Warning!!!!!, [%s] is not a vaild backup file, filtered." % (key_part.file_key))
  124. if not key_parts_list:
  125. print("There is no backup file on OSS Bucket [%s] under [%s] folder, check please." % (oss_bucket, directory))
  126. return key_parts_list
  127. def oss_bucket_details(access_key_id, access_key_secret, oss_endpoint, oss_bucket):
  128. try:
  129. bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), oss_endpoint, oss_bucket)
  130. bucket_info = bucket.get_bucket_info()
  131. # print ("bucket name:%s, region: %s" % (bucket_info.name, bucket_info.location))
  132. return True, bucket_info
  133. except Exception as e:
  134. return False, e
  135. if __name__ == '__main__':
  136. main(sys.argv[1:])

当然,以上代码,你也可以去下载以上python脚本。

使用方法

我们从以下三个方面简要介绍下如何使用实例级别一键迁移上云:

查看Help

一个例子

输出结果

查看Help

你只需要使用-h来查看脚本的使用方法:

  1. python ~/Downloads/RDSSQLCreateMigrateTasksBatchly.py -h
  2. ~/Downloads/RDSSQLCreateMigrateTasksBatchly.py -k <access_key_id> -s <access_key_secret> -i <rds_instance_id> -e <oss_endpoint> -b <oss_bucket> -d <directory>

一个例子

以下是一个具体的例子:

  1. python ~/Downloads/RDSSQLCreateMigrateTasksBatchly.py -k LTAIQazXKPRwwErT -s BMkIUhroubQOLpOMqfA09IKlqp4G2k -i rm-2zesz5774ud8s71i5 -e oss-cn-beijing.aliyuncs.com -b atp-test-on-ecs -d Migration/OPENAPIDemo

输出结果

执行以上命令以后的结果输出,分为两个部分:

第一部分输入参数:展示所有你的输入参数,以便查询输入错误

第二部分提示信息:告诉你,哪一个备份文件会被迁移到哪个实例的哪一个数据库 如下的一个实例的输出信息:

  1. *********************Input variables*************************************
  2. access_key_id = LTAIQazXKPRwwErT
  3. access_key_secret = BMkIUhroubQOLpOMqfA09IKlqp4G2k
  4. rds_instance_id = rm-2zesz5774ud8s71i5
  5. oss_endpoint = oss-cn-beijing.aliyuncs.com
  6. oss_bucket = atp-test-on-ecs
  7. directory = Migration/OPENAPIDemo/
  8. ************************************************************************
  9. *********************Migration requests**********************************
  10. --0. [Migration/OPENAPIDemo/TestCollation_FULL_20180523225534.bak] migrate to your RDS: [rm-2zesz5774ud8s71i5] and the database name will be: [TestCollation].
  11. {u'DBInstanceId': u'rm-2zesz5774ud8s71i5', u'BackupMode': u'FULL', u'MigrateTaskId': u'106121', u'RequestId': u'67E0DD7F-7219-4F67-AAE7-B27273921303', u'TaskId': u'68244691', u'DBName': u'TestCollation'}
  12. --I'm sleeping for 2 seconds....
  13. --1. [Migration/OPENAPIDemo/TestMigration_FULL_20180523225534.bak] migrate to your RDS: [rm-2zesz5774ud8s71i5] and the database name will be: [TestMigration].
  14. {u'DBInstanceId': u'rm-2zesz5774ud8s71i5', u'BackupMode': u'FULL', u'MigrateTaskId': u'106122', u'RequestId': u'0916CD14-861B-4BF7-A68A-409E3996B0D3', u'TaskId': u'68244695', u'DBName': u'TestMigration'}
  15. --I'm sleeping for 2 seconds....
  16. --2. [Migration/OPENAPIDemo/testdb_FULL_20180523225534.bak] migrate to your RDS: [rm-2zesz5774ud8s71i5] and the database name will be: [testdb].
  17. {u'DBInstanceId': u'rm-2zesz5774ud8s71i5', u'BackupMode': u'FULL', u'MigrateTaskId': u'106123', u'RequestId': u'5835B154-2EE3-4059-BFC4-6F798CDCE546', u'TaskId': u'68244699', u'DBName': u'testdb'}
  18. --I'm sleeping for 2 seconds....
  19. ************************************************************************

最后总结

利用本篇文章,我们可以轻松实现用户线下或者ECS自建的SQL Server实例级别数据库一键迁移上云,以此来极大的提高迁移上云效率,简化操作,大大提升了用户迁移上云体验。

参考链接

SQL Server实例级别数据库上云