delete_branch_ebs.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. #
  8. import boto3
  9. import time
  10. import logging
  11. TIMEOUT = 300
  12. log = logging.getLogger(__name__)
  13. log.setLevel(logging.INFO)
  14. def delete_ebs_volumes(repository_name, branch_name):
  15. """
  16. Delete all EBS volumes that are tagged with repository_name and branch_name
  17. :param repository_name: Full repository name.
  18. :param branch_name: Branch name that is deleted.
  19. :return: Number of EBS volumes that are deleted successfully, number of EBS volumes that are not deleted.
  20. """
  21. success = 0
  22. failure = 0
  23. ec2_client = boto3.resource('ec2')
  24. response = ec2_client.volumes.filter(Filters=[
  25. {
  26. 'Name': 'tag:RepositoryName',
  27. 'Values': [repository_name]
  28. },
  29. {
  30. 'Name': 'tag:BranchName',
  31. 'Values': [branch_name]
  32. }
  33. ])
  34. log.info(f'Deleting EBS volumes for remote-branch {branch_name} in repository {repository_name}.')
  35. for volume in response:
  36. if volume.attachments:
  37. ec2_instance_id = volume.attachments[0]['InstanceId']
  38. try:
  39. log.info(f'Detaching volume {volume.volume_id} from ec2 {ec2_instance_id}.')
  40. volume.detach_from_instance(Device='xvdf',
  41. Force=True,
  42. InstanceId=ec2_instance_id,
  43. VolumeId=volume.volume_id)
  44. except Exception as e:
  45. log.error(f'Failed to detach volume {volume.volume_id} from {ec2_instance_id}.')
  46. log.error(e)
  47. timeout_init = time.clock()
  48. while len(volume.attachments) and volume.attachments[0]['State'] != 'detached':
  49. time.sleep(1)
  50. volume.load()
  51. if (time.clock() - timeout_init) > TIMEOUT:
  52. log.error('Timeout reached trying to detach EBS.')
  53. try:
  54. log.info(f'Deleting volume {volume.volume_id}')
  55. volume.delete()
  56. success += 1
  57. except Exception as e:
  58. log.error(f'Failed to delete volume {volume.volume_id}.')
  59. log.error(e)
  60. failure += 1
  61. return success, failure
  62. def lambda_handler(event, context):
  63. repository_name = event['repository_name']
  64. branch_name = event['branch_name']
  65. (success, failure) = delete_ebs_volumes(repository_name, branch_name)
  66. return {
  67. 'success': success,
  68. 'failure': failure
  69. }