Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import ovirtsdk.api
- from ovirtsdk.xml import params
- from ovirtsdk.infrastructure import errors
- import sys
- import time
- from vmtools import VMTools
- from config import Config
- from getopt import getopt, GetoptError
- """
- Main class to make the backups
- """
- backup_list = []
- vms_with_failures = []
- def main(argv):
- usage = "backup.py -c <config.cfg>"
- try:
- opts, args = getopt(argv, "hc:d")
- debug = False
- if not opts:
- print usage
- sys.exit(1)
- for opt, arg in opts:
- if (opt == "-h") or (opt == "--help"):
- print usage
- sys.exit(0)
- elif opt in ("-c"):
- config_file = arg
- elif opt in ("-d"):
- debug = True
- except GetoptError:
- print usage
- sys.exit(1)
- global config
- config = Config(config_file, debug)
- time_start = int(time.time())
- has_errors = False
- # Connect to server
- connect()
- iterration = 0
- for vm_running in api.vms.list():
- if vm_running.status.state == 'up':
- backup_list.append(vm_running.name)
- # Test if all VM names are valid
- for vm_from_list in backup_list:
- if not api.vms.get(vm_from_list):
- print "!!! There are no VM with the following name in your cluster: " + vm_from_list
- continue
- for vm_from_list in backup_list:
- print "Start backup for: " + vm_from_list
- try:
- # Get the VM
- vm = api.vms.get(vm_from_list)
- # Cleanup: Delete the cloned VM
- VMTools.delete_vm(api, config, vm_from_list)
- # Delete old backup snapshots
- VMTools.delete_snapshots(vm, config, vm_from_list)
- # Create a VM snapshot:
- try:
- print "Snapshot creation started ..."
- if not config.get_dry_run():
- vm.snapshots.add(params.Snapshot(description=config.get_snapshot_description(), vm=vm))
- VMTools.wait_for_snapshot_operation(vm, config, "creation")
- print "Snapshot created"
- except Exception as e:
- print "Can't create snapshot for VM: " + vm_from_list
- print "DEBUG: " + str(e)
- vms_with_failures.append(vm_from_list)
- has_errors = True
- continue
- snapshot_edit = None
- for current in vm.snapshots.list():
- if current.get_description() == config.get_snapshot_description():
- snapshot_edit = current
- break
- # Should probably end here, with an error
- sd = api.storagedomains.get(name="temp")
- #prepare disk list
- disk_ids = []
- for current in snapshot_edit.disks.list():
- disk_ids.append(current.get_id())
- disk_list = []
- for disk_id in disk_ids:
- disk = params.Disk(
- image_id=disk_id,
- storage_domains=params.StorageDomains(
- storage_domain=[
- params.StorageDomain(
- id=sd.get_id(),
- ),
- ],
- ),
- )
- disk_list.append(disk)
- # Clone the snapshot into a VM
- snapshots = vm.snapshots.list(description=config.get_snapshot_description())
- if not snapshots:
- print "!!! No snapshot found"
- vms_with_failures.append(vm_from_list)
- has_errors = True
- continue
- snapshot_param = params.Snapshot(id=snapshots[0].id)
- snapshots_param = params.Snapshots(snapshot=[snapshot_param])
- print "Clone into VM started ..."
- if not config.get_dry_run():
- api.vms.add(
- params.VM(
- name=(vm_from_list + config.get_vm_middle()),
- cluster=params.Cluster(name="Default"),
- snapshots=params.Snapshots(
- snapshot=[
- params.Snapshot(
- id=snapshot_edit.get_id(),
- ),
- ],
- ),
- disks=params.Disks(
- disk=disk_list,
- ),
- )
- )
- VMTools.wait_for_vm_operation(api, config, "Cloning", vm_from_list)
- print "Cloning finished"
- # Delete backup snapshots
- VMTools.delete_snapshots(vm, config, vm_from_list)
- # Delete old backups
- VMTools.delete_old_backups(api, config, vm_from_list)
- # Export the VM
- try:
- vm_clone = api.vms.get(vm_from_list + config.get_vm_middle())
- print "Export started ..."
- if not config.get_dry_run():
- vm_clone.export(params.Action(storage_domain=api.storagedomains.get(config.get_export_domain())))
- VMTools.wait_for_vm_operation(api, config, "Exporting", vm_from_list)
- print "Exporting finished"
- except Exception as e:
- print "Can't export cloned VM (" + vm_from_list + config.get_vm_middle() + config.get_vm_suffix() + ") to domain: " + config.get_export_domain()
- print "DEBUG: " + str(e)
- has_errors = True
- vms_with_failures.append(vm_from_list)
- continue
- # Delete the VM
- VMTools.delete_vm(api, config, vm_from_list)
- time_end = int(time.time())
- time_diff = (time_end - time_start)
- time_minutes = int(time_diff / 60)
- time_seconds = time_diff % 60
- print "Duration: " + str(time_minutes) + ":" + str(time_seconds) + " minutes"
- print "VM exported as " + vm_from_list + config.get_vm_middle()
- print "Backup done for: " + vm_from_list
- except errors.ConnectionError as e:
- print "!!! Can't connect to the server" + str(e)
- connect()
- continue
- except errors.RequestError as e:
- print "!!! Got a RequestError: " + str(e)
- has_errors = True
- continue
- except Exception as e:
- print "!!! Got unexpected exception: " + str(e)
- sys.exit(1)
- print "All backups done"
- if vms_with_failures:
- print "Backup failured for:"
- for i in vms_with_failures:
- print " " + i
- if has_errors:
- print "Some errors occured during the backup, please check the log file"
- sys.exit(1)
- # Disconnect from the server
- api.disconnect()
- def connect():
- global api
- api = ovirtsdk.api.API(
- url=config.get_server(),
- username=config.get_username(),
- password=config.get_password(),
- insecure=True,
- debug=False
- )
- if __name__ == "__main__":
- main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment