Ejemplo n.º 1
0
def initalize_hypervisor_instances(hypervisor):
  conn = hypervisor.get_connection(True)
  if conn:
    # create dummy network
    network, created = Network.objects.get_or_create(
      hypervisor=hypervisor,
      netmask="255.255.255.255",
      gateway="0.0.0.0",
      broadcast="0.0.0.255",
      network="0.0.0.0",
      start="0.0.0.0",
      end="255.255.255.255"
    )

    domains = []
    for dom_id in conn.listDomainsID():
      dom = conn.lookupByID(dom_id)
      xml = minidom.parseString(dom.XMLDesc(0))
      items = xml.getElementsByTagName('name')
      name = items[0].childNodes[0].data
      domains.append(name)
    domains += conn.listDefinedDomains()
    print domains
    dummy_user = User.objects.all()[0]
    for name in domains:
      print name
      dom = conn.lookupByName(name)
      xml = minidom.parseString(dom.XMLDesc(0))
      items = xml.getElementsByTagName('memory')
      memory = int(items[0].childNodes[0].data)
      memory_size = Size.objects.filter(size=memory*1024)
      if not memory_size:
        memory_size, created = Size.objects.get_or_create(
          name="%d KiB" % (memory), # make more robust, i.e. detect unit size
          size=memory*1024
        )
      else: memory_size = memory_size[0]
      items = xml.getElementsByTagName('vcpu')
      vcpus = int(items[0].childNodes[0].data)
      items = xml.getElementsByTagName('mac')
      mac = items[0].getAttributeNode('address').nodeValue
      volume_path = None
      for disk in xml.getElementsByTagName('disk'):
        if disk.getAttributeNode('device').nodeValue == 'disk':
          items = disk.getElementsByTagName('source')
          volume_path = items[0].getAttributeNode('file').nodeValue
      if not volume_path:
        # print error
        print "no volume path for %s" % (name)
        continue
      try:
        vol = conn.storageVolLookupByPath(volume_path)
        storagepool = StoragePool.objects.get(
          name=vol.storagePoolLookupByVolume().name()
        )
      except libvirt.libvirtError as e:
        print e
        print "HERRRO"
        continue
      if not storagepool:
        # print error
        print "no storage pool for %s" % (name)
        continue
      capacity = Size.objects.get(size=vol.info()[1])
      if not capacity:
        capacity, created = Size.objects.get_or_create(
          name=vol.info()[1],
          size=vol.info()[1]
        )
      volume = Volume.objects.filter(name=volume_path.split('/')[-1].split('.')[0])
      if not volume:
        volume = Volume(
          name=volume_path.split('/')[-1].split('.')[0],
          capacity=capacity,
          allocated=vol.info()[2],
          storagepool=storagepool
        )
        volume.save()
      else: volume = volume[0]

      instance_network = None
      # might need to detect multiple networks here, apeend to list
#      for param in xml.getElementsByTagName('parameter'):
#        if param.getAttributeNode('name').nodeValue == 'IP':
#          instance_network = param.getAttributeNode('value').nodeValue
#      if instance_network:
#        instance_network, created = InstanceNetwork.objects.get_or_create(
#          ip=instance_network,
#          network=network,
#          
#        )
#      else:
#        instance_network = network.create_unique_address()

      print "Create instance object..."

      instance = Instance.objects.filter(name=name)
      if not instance:
        instance = Instance(
          name=name,
          user=dummy_user,
          creator=dummy_user,
          vcpu=vcpus,
          memory=memory_size,
          volume=volume,
        )
        instance.save() 
  print "DONE..." 
Ejemplo n.º 2
0
def create_instance(instancetask_name):
  try:
    instancetask = InstanceTask.objects.get(name=instancetask_name)
  except InstanceTask.DoesNotExist:
    return {'custum_state': 'FAILURE', 'msg': 'Unable to find InstanceTask with name: %s' % (instancetask_name)}

  request = HttpRequest()
  storagepool = instancetask.storagepool.get_storagepool()
  if not storagepool:
    return {'custom_state': 'FAILURE', 'msg': 'Unable to get Storage Pool %s' % (instancetask.storagepool)}

  volume_name = Volume.create_random_name()
  (volume, created) = Volume.objects.get_or_create(
    name=volume_name,
    storagepool=instancetask.storagepool,
    capacity=instancetask.capacity
  )
  if created: volume.save()
  if not volume.create(request):
    volume.delete()
    return {'custom_state': 'FAILURE', 'msg': 'Unable to create Volume on %s' % (instancetask.storagepool)}
  instancetask.volume = volume
  instancetask.save()

  installationdisk_path = ''
  if instancetask.disk:
    installationdisk_path = instancetask.disk.path()
  
  xml = """
    <domain type='kvm'>
        <name>%s</name>
        <memory unit="b">%d</memory>
        <currentMemory unit="b">%d</currentMemory>
        <vcpu>%s</vcpu>
        <os>
            <type arch='x86_64' machine='pc'>hvm</type>
            <boot dev='hd'/>
            <boot dev='cdrom'/>
            <bootmenu enable='yes'/>
        </os>
        <features>
            <acpi/>
            <apic/>
            <pae/>
        </features>
        <clock offset='utc'/>
            <on_poweroff>destroy</on_poweroff>
            <on_reboot>restart</on_reboot>
            <on_crash>restart</on_crash>
        <devices>
            <emulator>/usr/bin/kvm</emulator>
            <disk type='file' device='disk'>
                <driver name='qemu' type='qcow2'/>
                <source file='%s'/>
                <target dev='hda' bus='ide'/>
                <alias name='ide0-0-0'/>
                <address type='drive' controller='0' bus='0' target='0' unit='0'/>
            </disk>
            <disk type='file' device='cdrom'>
                <driver name='qemu' type='raw'/>
                <source file='%s'/>
                <target dev='hdc' bus='ide'/>
                <readonly/>
                <address type='drive' controller='0' bus='1' unit='0'/>
            </disk>
            <controller type='ide' index='0'>
                <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
            </controller>
            <interface type='bridge'>
                <source bridge='br0' />
                <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
            </interface>
            <input type='tablet' bus='usb'/>
            <input type='mouse' bus='ps2'/>
            <graphics type='vnc' port='-1' autoport='yes'/>
            <video>
                <model type='cirrus' vram='9216' heads='1'/>
                <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
            </video>
            <memballoon model='virtio'>
                <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
          </memballoon>
      </devices>
  </domain>""" \
    % (instancetask.name, instancetask.memory, instancetask.memory, 
      instancetask.vcpu, volume.path(), installationdisk_path)
  print xml
  con = instancetask.storagepool.hypervisor.get_connection()
  if not con:
    return {'custom_state': 'FAILURE', 'msg': 'Unable to get Hypervisor %s' % (instancetask.storagepool.hypervisor)}
    
  try:
    con.defineXML(xml)
    current_task.update_state(state='PROGRESS', meta={
      'percent': 15,
      'msg': 'Defined XML'
    })
    instance = con.lookupByName(instancetask.name)
    instance.setAutostart(1)
    current_task.update_state(state='PROGRESS', meta={
      'percent': 50,
      'msg': 'Set Autostart',
    })
    instance.create()
    current_task.update_state(state='PROGRESS', meta={
      'percent': 75,
      'msg': 'Creating the Instance on the Hypervisor..',
    })
    # switch instance task for an instance
    new_instance = Instance.objects.create(
      name=instancetask.name,
      volume=instancetask.volume,
      user=instancetask.user,
      creator=instancetask.creator,
      vcpu=instancetask.vcpu,
      memory=instancetask.memory,
      disk=instancetask.disk,
      created=instancetask.created
    )
    new_instance.save()
    instancetask.delete(False)
  except libvirt.libvirtError as e:
    return {'custom_state': 'FAILURE', 'msg': 'Error while creating instance: %s' % (e)}
Ejemplo n.º 3
0
def create_instance(instancetask_name):
  try:
    instancetask = InstanceTask.objects.get(name=instancetask_name)
  except InstanceTask.DoesNotExist:
    return {'custum_state': 'FAILURE', 'msg': 'Unable to find InstanceTask with name: %s' % (instancetask_name)}

  try:
    network_address = instancetask.network.create_unique_address()
  except NoUniqueAddress:
    return {'custum_state': 'FAILURE', 'msg': 'Error while creating instance: No unique address available on specified network (%s)' % (instancetask.network)}

  request = HttpRequest()
  storagepool = instancetask.storagepool.get_storagepool()
  if not storagepool:
    return {'custom_state': 'FAILURE', 'msg': 'Unable to get Storage Pool %s' % (instancetask.storagepool)}

  volume_name = Volume.create_random_name()
  (volume, created) = Volume.objects.get_or_create(
    name=volume_name,
    storagepool=instancetask.storagepool,
    capacity=instancetask.capacity
  )
  if created: volume.save()
  if not volume.create(request):
    volume.delete()
    return {'custom_state': 'FAILURE', 'msg': 'Unable to create Volume on %s' % (instancetask.storagepool)}
  instancetask.volume = volume
  instancetask.save()

  xml = """
    <domain type='kvm'>
        <name>%s</name>
        <memory unit="b">%d</memory>
        <currentMemory unit="b">%d</currentMemory>
        <vcpu>%s</vcpu>
        <os>
            <type arch='x86_64' machine='pc'>hvm</type>
            <boot dev='cdrom'/>
            <boot dev='hd'/>
            <bootmenu enable='yes'/>
        </os>
        <features>
            <acpi/>
            <apic/>
            <pae/>
        </features>
        <clock offset='utc'/>
            <on_poweroff>destroy</on_poweroff>
            <on_reboot>restart</on_reboot>
            <on_crash>restart</on_crash>
        <devices>
            <emulator>/usr/bin/kvm</emulator>
            <disk type='file' device='cdrom'>
                <driver name='qemu' type='raw'/>
                <target dev='hdc' bus='ide'/>
            </disk>
            <disk type='file' device='disk'>
                <driver name='qemu' type='qcow2'/>
                <source file='%s'/>
                <target dev='hda' bus='virtio'/>
                <alias name='ide0-0-0'/>
            </disk>
            <controller type='ide' index='0'>
                <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
            </controller>
            <interface type='bridge'>
                <source bridge='br0' />
                <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
                <filterref filter='clean-traffic'>
                  <parameter name='IP' value='%s' />
                </filterref>
                <model type='virtio'/>
            </interface>
            <input type='tablet' bus='usb'/>
            <input type='mouse' bus='ps2'/>
            <graphics type='vnc' port='-1' autoport='yes'>
              <listen type='address' address='%s' />
            </graphics>
            <video>
                <model type='cirrus' vram='9216' heads='1'/>
                <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
            </video>
            <memballoon model='virtio'>
                <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
          </memballoon>
      </devices>
  </domain>""" \
    % (instancetask.name, instancetask.memory.size, instancetask.memory.size, 
      instancetask.vcpu, volume.path(), network_address.ip, volume.storagepool.hypervisor.address)
  print xml
  con = instancetask.storagepool.hypervisor.get_connection()
  if not con:
    return {'custom_state': 'FAILURE', 'msg': 'Unable to get Hypervisor %s' % (instancetask.storagepool.hypervisor)}
    
  try:
    con.defineXML(xml)
    current_task.update_state(state='PROGRESS', meta={
      'percent': 15,
      'msg': 'Defined XML'
    })
    instance = con.lookupByName(instancetask.name)
    instance.setAutostart(1)
    current_task.update_state(state='PROGRESS', meta={
      'percent': 50,
      'msg': 'Set Autostart',
    })
    instance.create()
    current_task.update_state(state='PROGRESS', meta={
      'percent': 75,
      'msg': 'Creating the Instance on the Hypervisor..',
    })

    # shutdown initially so that user can pick their own install medium
    instance.destroy()

    # get mac info and setup network
    tree = ElementTree.fromstring(instance.XMLDesc(0))
    address = tree.findall('devices/interface/mac')
    mac = address[0].get('address').upper()
    print "MAC: %s" % (mac)
    if Instance.objects.filter(mac=mac).count() > 0:
      return {'custum_state': 'FAILURE', 'msg': 'Error while creating instance: MAC address is already being used (%s)' % (mac)}

      

    # switch instance task for an instance
    new_instance = Instance.objects.create(
      name=instancetask.name,
      volume=instancetask.volume,
      user=instancetask.user,
      creator=instancetask.creator,
      vcpu=instancetask.vcpu,
      memory=instancetask.memory,
      disk=instancetask.disk,
      created=instancetask.created,
      mac=mac,
      network=network_address,
      initialised=False,
    )
    new_instance.save()
    instancetask.delete(False)
  except libvirt.libvirtError as e:
    return {'custom_state': 'FAILURE', 'msg': 'Error while creating instance: %s' % (e)}