Guest User

Untitled

a guest
Jan 20th, 2016
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.54 KB | None | 0 0
  1. #!/usr/bin/python
  2. import ovirtsdk.api
  3. from ovirtsdk.xml import params
  4. from ovirtsdk.infrastructure import errors
  5. import sys
  6. import time
  7. from vmtools import VMTools
  8. from config import Config
  9. from getopt import getopt, GetoptError
  10.  
  11. """
  12. Main class to make the backups
  13. """
  14.  
  15. backup_list = []
  16. vms_with_failures = []
  17. def main(argv):
  18.     usage = "backup.py -c <config.cfg>"
  19.     try:
  20.         opts, args = getopt(argv, "hc:d")
  21.         debug = False
  22.         if not opts:
  23.             print usage
  24.             sys.exit(1)
  25.         for opt, arg in opts:
  26.             if (opt == "-h") or (opt == "--help"):
  27.                 print usage
  28.                 sys.exit(0)
  29.             elif opt in ("-c"):
  30.                 config_file = arg
  31.             elif opt in ("-d"):
  32.                 debug = True
  33.     except GetoptError:
  34.         print usage
  35.         sys.exit(1)
  36.  
  37.     global config
  38.     config = Config(config_file, debug)
  39.  
  40.     time_start = int(time.time())
  41.  
  42.     has_errors = False
  43.  
  44.     # Connect to server
  45.     connect()
  46.     iterration = 0
  47.  
  48.     for vm_running in api.vms.list():
  49.         if vm_running.status.state == 'up':
  50.             backup_list.append(vm_running.name)
  51.         # Test if all VM names are valid
  52.         for vm_from_list in backup_list:
  53.             if not api.vms.get(vm_from_list):
  54.                 print "!!! There are no VM with the following name in your cluster: " + vm_from_list
  55.                 continue
  56.             for vm_from_list in backup_list:
  57.                 print "Start backup for: " + vm_from_list
  58.    
  59.                 try:
  60.                     # Get the VM
  61.                     vm = api.vms.get(vm_from_list)
  62.    
  63.                     # Cleanup: Delete the cloned VM
  64.                     VMTools.delete_vm(api, config, vm_from_list)
  65.    
  66.                     # Delete old backup snapshots
  67.    
  68.                     VMTools.delete_snapshots(vm, config, vm_from_list)
  69.                     # Create a VM snapshot:
  70.    
  71.                     try:
  72.    
  73.                         print "Snapshot creation started ..."
  74.    
  75.                         if not config.get_dry_run():
  76.                             vm.snapshots.add(params.Snapshot(description=config.get_snapshot_description(), vm=vm))
  77.                             VMTools.wait_for_snapshot_operation(vm, config, "creation")
  78.                             print "Snapshot created"
  79.    
  80.                     except Exception as e:
  81.                         print "Can't create snapshot for VM: " + vm_from_list
  82.                         print "DEBUG: " + str(e)
  83.                         vms_with_failures.append(vm_from_list)
  84.                         has_errors = True
  85.                         continue
  86.                     snapshot_edit = None
  87.    
  88.                     for current in vm.snapshots.list():
  89.                         if current.get_description() == config.get_snapshot_description():
  90.                             snapshot_edit = current
  91.                             break
  92.                             # Should probably end here, with an error
  93.                     sd = api.storagedomains.get(name="temp")
  94.                     #prepare disk list
  95.                     disk_ids = []
  96.                     for current in snapshot_edit.disks.list():
  97.                         disk_ids.append(current.get_id())
  98.                         disk_list = []
  99.                         for disk_id in disk_ids:
  100.                             disk = params.Disk(
  101.                                     image_id=disk_id,
  102.                                     storage_domains=params.StorageDomains(
  103.                                         storage_domain=[
  104.                                             params.StorageDomain(
  105.                                                 id=sd.get_id(),
  106.                                                 ),
  107.                                             ],
  108.                                         ),
  109.                                     )
  110.                             disk_list.append(disk)
  111.                     # Clone the snapshot into a VM
  112.                     snapshots = vm.snapshots.list(description=config.get_snapshot_description())
  113.    
  114.                     if not snapshots:
  115.                         print "!!! No snapshot found"
  116.                         vms_with_failures.append(vm_from_list)
  117.                         has_errors = True
  118.                         continue
  119.                     snapshot_param = params.Snapshot(id=snapshots[0].id)
  120.                     snapshots_param = params.Snapshots(snapshot=[snapshot_param])
  121.    
  122.                     print "Clone into VM started ..."
  123.                     if not config.get_dry_run():
  124.                         api.vms.add(
  125.                                 params.VM(
  126.                                     name=(vm_from_list + config.get_vm_middle()),
  127.                                     cluster=params.Cluster(name="Default"),
  128.                                     snapshots=params.Snapshots(
  129.                                         snapshot=[
  130.                                             params.Snapshot(
  131.                                                 id=snapshot_edit.get_id(),
  132.                                                 ),
  133.                                             ],
  134.                                         ),
  135.                                     disks=params.Disks(
  136.                                         disk=disk_list,
  137.                                         ),
  138.                                     )
  139.                                 )
  140.                     VMTools.wait_for_vm_operation(api, config, "Cloning", vm_from_list)
  141.                     print "Cloning finished"
  142.                     # Delete backup snapshots
  143.                     VMTools.delete_snapshots(vm, config, vm_from_list)
  144.                     # Delete old backups
  145.                     VMTools.delete_old_backups(api, config, vm_from_list)
  146.    
  147.                     # Export the VM
  148.                     try:
  149.                         vm_clone = api.vms.get(vm_from_list + config.get_vm_middle())
  150.                         print "Export started ..."
  151.                         if not config.get_dry_run():
  152.                             vm_clone.export(params.Action(storage_domain=api.storagedomains.get(config.get_export_domain())))
  153.                             VMTools.wait_for_vm_operation(api, config, "Exporting", vm_from_list)
  154.                         print "Exporting finished"
  155.                
  156.                     except Exception as e:
  157.                         print "Can't export cloned VM (" + vm_from_list + config.get_vm_middle() + config.get_vm_suffix() + ") to domain: " + config.get_export_domain()
  158.                         print "DEBUG: " + str(e)
  159.                         has_errors = True
  160.                         vms_with_failures.append(vm_from_list)
  161.                         continue
  162.                     # Delete the VM
  163.                     VMTools.delete_vm(api, config, vm_from_list)
  164.                     time_end = int(time.time())
  165.                     time_diff = (time_end - time_start)
  166.                     time_minutes = int(time_diff / 60)
  167.                     time_seconds = time_diff % 60
  168.                     print "Duration: " + str(time_minutes) + ":" + str(time_seconds) + " minutes"
  169.                     print "VM exported as " + vm_from_list + config.get_vm_middle()
  170.                     print "Backup done for: " + vm_from_list
  171.                 except errors.ConnectionError as e:
  172.                     print "!!! Can't connect to the server" + str(e)
  173.                     connect()
  174.                     continue
  175.                 except errors.RequestError as e:
  176.                     print "!!! Got a RequestError: " + str(e)
  177.                     has_errors = True
  178.                     continue
  179.                 except Exception as e:
  180.                     print "!!! Got unexpected exception: " + str(e)
  181.                     sys.exit(1)
  182.                 print "All backups done"
  183.                 if vms_with_failures:
  184.                     print "Backup failured for:"
  185.                     for i in vms_with_failures:
  186.                         print "  " + i
  187.                         if has_errors:
  188.                             print "Some errors occured during the backup, please check the log file"
  189.                             sys.exit(1)
  190.                
  191.         # Disconnect from the server
  192.         api.disconnect()
  193.  
  194. def connect():
  195.  
  196.  
  197.     global api
  198.     api = ovirtsdk.api.API(
  199.         url=config.get_server(),
  200.         username=config.get_username(),
  201.         password=config.get_password(),
  202.         insecure=True,
  203.         debug=False
  204.     )
  205.  
  206. if __name__ == "__main__":
  207.         main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment