示例#1
0
文件: virt.py 项目: T-D-Oe/spacewalk
def refresh(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.refresh()
    except errors.VirtualizationException, ve:
        return (1, str(ve), {})
示例#2
0
文件: virt.py 项目: lpramuk/spacewalk
def refresh(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.refresh()
    except errors.VirtualizationException, ve:
        return (1, str(ve), {})
示例#3
0
def refresh(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.refresh()
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Virtualization Info refreshed.", {})
示例#4
0
文件: virt.py 项目: jdobes/spacewalk
def refresh(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.refresh()
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Virtualization Info refreshed.", {})
示例#5
0
    def main(self):
        if not up2dateAuth.getSystemId():
            needToRegister = \
                _("You need to register this system by running " \
                "`rhn_register` before using this option")
            print(needToRegister)
            sys.exit(1)

        if not self._testRhnLogin():
            sys.exit(1)

        print(_("Updating package profile..."))
        rhnPackageInfo.updatePackageProfile()

        print(_("Updating hardware profile..."))
        rhnHardware.updateHardware()

        if support is not None:
            print(_("Updating virtualization profile..."))
            support.refresh(True)
示例#6
0
    def main(self):
        if not up2dateAuth.getSystemId():
            needToRegister = \
                _("You need to register this system by running " \
                "`rhn_register` before using this option")
            print(needToRegister)
            sys.exit(1)

        if not self._testRhnLogin():
            sys.exit(1)

        print(_("Updating package profile..."))
        rhnPackageInfo.updatePackageProfile()

        print(_("Updating hardware profile..."))
        rhnHardware.updateHardware()

        if support is not None:
            print(_("Updating virtualization profile..."))
            support.refresh(True)
示例#7
0
def deploy(params, extraParams="", cache_only=None):
    """start and connect a local image with SUSE Manager"""

    urlParts = params["downloadURL"].split('/')
    studioArchiveFileName = urlParts[-1]
    checksum = urlParts[-2]

    # studioArchiveFileName = workshop_test_sles11sp1.i686-0.0.1.vmx.tar.gz
    # studioArchiveFileName = Just_enough_OS_openSUSE_12.1.x86_64-0.0.1.xen.tar.gz
    m = re.search('(.*)\.(x86_64|i\d86)-(\d+\.\d+\.\d+)\.(xen|vmx|qcow2)',
                  studioArchiveFileName)

    imageName = m.group(1)
    imageArch = m.group(2)
    imageVersion = m.group(3)
    imageType = m.group(4)
    studioImageDiskFileName = imageName + "." + imageArch + "-" + imageVersion

    try:
        connection = _connect_to_hypervisor()
    except Exception:
        e = sys.exc_info()[1]
        return (1, "%s" % e, {})

    # if we got an explicit name, we'll use it
    if "domainName" in params and params["domainName"] != "":
        imageName = params["domainName"]
    # if not, we'll try to find a free name
    elif (_domainExists(imageName, connection)):
        for i in itertools.count(1):
            newImageName = ("%s-%i" % (imageName, i))
            if not _domainExists(newImageName, connection):
                log.log_debug("free domain found")
                imageName = newImageName
                break
    log.log_debug("name=%s arch=%s ver=%s type=%s" %
                  (imageName, imageArch, imageVersion, imageType))

    if len(imageName) < 1 or len(imageArch) < 1:
        log.log_debug("invalid image name or arch")
        return (1,
                "invalid image name or arch: name=%s arch=%s ver=%s type=%s" %
                (imageName, imageArch, imageVersion, imageType), {})

    httpResponseCode = -1
    if not _fileExists("%s/%s" %
                       (IMAGE_BASE_PATH, studioArchiveFileName), checksum):
        try:
            httpResponseCode = _downloadFile(studioArchiveFileName,
                                             params["downloadURL"],
                                             params["proxySettings"])
            if not _fileExists(
                    "%s/%s" %
                (IMAGE_BASE_PATH, studioArchiveFileName), checksum):
                log.log_debug(
                    "downloading image file failed. HTTP Code is: %s" %
                    httpResponseCode)
                return (
                    1, "downloading image file failed: %s/%s (%s)" %
                    (IMAGE_BASE_PATH, studioArchiveFileName, httpResponseCode),
                    {})
        except Exception:
            e = sys.exc_info()[1]
            return (1, "getting the image failed with: %s" % e)
    if cache_only:
        return (0, "image fetched and cached for later deployment", {})
    try:
        targetDir = _createTargetDir("%s/%s" % (IMAGE_BASE_PATH, imageName))
        _extractImage("%s/%s" % (IMAGE_BASE_PATH, studioArchiveFileName),
                      targetDir, imageType)
    except Exception:
        e = sys.exc_info()[1]
        return (1, "extracting the image tarball failed with: %s" % e, {})

    # image exists in $IMAGE_BASE_PATH/$imageName now

    uuid = generate_uuid()
    # FIXME: check for the extensions. There might be more
    studioFileExtension = "vmdk"
    if imageType == "xen":
        studioFileExtension = "raw"
    elif imageType == "qcow2":
        studioFileExtension = "qcow2"
    extractedImagePath = "%s/%s.%s" % (targetDir, studioImageDiskFileName,
                                       studioFileExtension)
    log.log_debug("working on image in %s" % extractedImagePath)
    if not os.path.exists(extractedImagePath):
        return (1, "extracted image not found at %s" % extractedImagePath, {})
    if imageArch in ('i386', 'i486', 'i568'):
        imageArch = 'i686'

    create_params = {
        'name': imageName,
        'arch': imageArch,
        'extra': extraParams,
        'mem_kb': params["memKB"],
        'vcpus': params["vCPUs"],
        'uuid': uuid,
        'disk': extractedImagePath,
        'imageType': imageType,
        'virtBridge': params["virtBridge"],
    }
    create_xml = _generateXML(create_params)
    domain = None
    try:
        domain = connection.defineXML(create_xml)
    except Exception:
        e = sys.exc_info()[1]
        return (1, "failed to pass XML to libvirt: %s" % e, {})

    domain.create()
    virt_support.refresh()

    return (0, "image '%s' deployed and started" % imageName, {})
示例#8
0
def deploy(params, extra_params="", cache_only=None):
    """Download and start a new image."""

    image_filename  = params["downloadURL"].split('/')[-1]
    domain_name, image_extension = os.path.splitext(image_filename)
    if not image_extension or image_extension != ".qcow2":
        return (1, "image type is not qcow2: %s" % image_filename, {})
    image_arch = platform.machine() or 'x86_64'

    try:
        connection = _connect_to_hypervisor()
    except Exception as e:
        return (1, "%s" % e, {})

    # If we got an explicit domain name then use it and update the filename
    if "domainName" in params and params["domainName"] != "":
        domain_name = params["domainName"]
    image_filename = domain_name + image_extension

    # If domain or file exists try to find a free name for both
    if _domain_exists(domain_name, connection) or _file_exists("%s/%s" % (IMAGE_BASE_PATH, image_filename)):
        for i in itertools.count(1):
            new_domain_name = ("%s-%i" % (domain_name, i))
            image_filename = new_domain_name + image_extension
            if not _domain_exists(new_domain_name, connection) and not _file_exists("%s/%s" % (IMAGE_BASE_PATH, image_filename)):
                log.log_debug("free domain and matching filename found")
                domain_name = new_domain_name
                break

    log.log_debug("filename=%s domain=%s arch=%s" % (image_filename, domain_name, image_arch))

    if not domain_name or image_arch not in ['x86_64', 'i686', 'ppc64le', 's390x']:
        log.log_debug("invalid domain name or arch")
        return (1, "invalid domain name or arch: domain=%s arch=%s" % (domain_name, image_arch), {})

    http_response_code = -1
    try:
        http_response_code = _download_file(image_filename, params["downloadURL"], params["proxySettings"])
        if not _file_exists("%s/%s" % (IMAGE_BASE_PATH, image_filename)):
            log.log_debug("downloading image file failed, HTTP return code: %s" % http_response_code)
            return (1, "downloading image file failed: %s/%s (%s)" % (IMAGE_BASE_PATH, image_filename, http_response_code), {})
    except Exception as e:
        return (1, "getting the image failed with: %s" % e, {})
    if cache_only:
        return (0, "image fetched and cached for later deployment", {})

    image_path = "%s/%s" % (IMAGE_BASE_PATH, image_filename)
    if not os.path.exists(image_path):
        return (1, "image not found at %s" % image_path, {})
    log.log_debug("working on image in %s" % image_path)

    create_params = { 'name'           : domain_name,
                      'arch'           : image_arch,
                      'extra'          : extra_params,
                      'mem_kb'         : params["memKB"],
                      'vcpus'          : params["vCPUs"],
                      'uuid'           : generate_uuid(),
                      'disk'           : image_path,
                      'imageType'      : 'qcow2',
                      'virtBridge'     : params["virtBridge"],
                    }
    create_xml = _generate_xml(create_params)
    domain = None
    try:
        domain = connection.defineXML(create_xml)
    except Exception as e:
        return (1, "failed to pass XML to libvirt: %s" % e, {})

    domain.create()
    virt_support.refresh()

    return (0, "image '%s' deployed and started" % domain_name, {})
示例#9
0
 def commit(self):
     # Syncing the profile resolves a problem with guests not
     # showing
     sys.path.append("/usr/share/rhn")
     from virtualization import support
     support.refresh(True)
示例#10
0
文件: image.py 项目: m47ik/uyuni
def deploy(params, extra_params="", cache_only=None):
    """Download and start a new image."""

    image_filename  = params["downloadURL"].split('/')[-1]
    domain_name, image_extension = os.path.splitext(image_filename)
    if not image_extension or image_extension != ".qcow2":
        return (1, "image type is not qcow2: %s" % image_filename, {})
    image_arch = platform.machine() or 'x86_64'

    try:
        connection = _connect_to_hypervisor()
    except Exception as e:
        return (1, "%s" % e, {})

    # If we got an explicit domain name then use it and update the filename
    if "domainName" in params and params["domainName"] != "":
        domain_name = params["domainName"]
    image_filename = domain_name + image_extension

    # If domain or file exists try to find a free name for both
    if _domain_exists(domain_name, connection) or _file_exists("%s/%s" % (IMAGE_BASE_PATH, image_filename)):
        for i in itertools.count(1):
            new_domain_name = ("%s-%i" % (domain_name, i))
            image_filename = new_domain_name + image_extension
            if not _domain_exists(new_domain_name, connection) and not _file_exists("%s/%s" % (IMAGE_BASE_PATH, image_filename)):
                log.log_debug("free domain and matching filename found")
                domain_name = new_domain_name
                break

    log.log_debug("filename=%s domain=%s arch=%s" % (image_filename, domain_name, image_arch))

    if not domain_name or image_arch not in ['x86_64', 'i686', 'ppc64le', 's390x']:
        log.log_debug("invalid domain name or arch")
        return (1, "invalid domain name or arch: domain=%s arch=%s" % (domain_name, image_arch), {})

    http_response_code = -1
    try:
        http_response_code = _download_file(image_filename, params["downloadURL"], params["proxySettings"])
        if not _file_exists("%s/%s" % (IMAGE_BASE_PATH, image_filename)):
            log.log_debug("downloading image file failed, HTTP return code: %s" % http_response_code)
            return (1, "downloading image file failed: %s/%s (%s)" % (IMAGE_BASE_PATH, image_filename, http_response_code), {})
    except Exception as e:
        return (1, "getting the image failed with: %s" % e, {})
    if cache_only:
        return (0, "image fetched and cached for later deployment", {})

    image_path = "%s/%s" % (IMAGE_BASE_PATH, image_filename)
    if not os.path.exists(image_path):
        return (1, "image not found at %s" % image_path, {})
    log.log_debug("working on image in %s" % image_path)

    create_params = { 'name'           : domain_name,
                      'arch'           : image_arch,
                      'extra'          : extra_params,
                      'mem_kb'         : params["memKB"],
                      'vcpus'          : params["vCPUs"],
                      'uuid'           : generate_uuid(),
                      'disk'           : image_path,
                      'imageType'      : 'qcow2',
                      'virtBridge'     : params["virtBridge"],
                    }
    create_xml = _generate_xml(create_params)
    domain = None
    try:
        domain = connection.defineXML(create_xml)
    except Exception as e:
        return (1, "failed to pass XML to libvirt: %s" % e, {})

    domain.create()
    virt_support.refresh()

    return (0, "image '%s' deployed and started" % domain_name, {})
示例#11
0
def initiate_guest(name, mem_kb, vcpus, disk_gb, extra_append,
        log_notify_handler=None):

    files_to_cleanup = []

    # We'll wrap this up in a try block so that we can clean up should an
    # exception occur.
    try:
        # First, download the kickstart file.
        kickstart_config = common.download_kickstart_file(extra_append)

        # This hack sucks, but it works around a race condition dealing with
        # the tiny url generation on the server.  Basically, if we request
        # the download images too soon after receiving the ks config file, we
        # are served a 404.  We'll remove this hack when we figure out what the
        # server-side issue is.
        time.sleep(5)

        # Download the kernel and initrd images.
        (install_kernel_path, install_initrd_path) = \
            common.download_install_images(kickstart_config, "images/xen",
                XEN_INSTALL_IMAGE_DIR)
        files_to_cleanup.append(install_kernel_path)
        files_to_cleanup.append(install_initrd_path)

        # Create the disk image for the instance.
        disk_image_path = _create_disk_image(name, disk_gb)
        files_to_cleanup.append(disk_image_path)

        # Determine the type of disk image.
        disk_image_type = _determine_disk_image_type(disk_image_path)

        # Generate a UUID for this new instance.
        uuid = _generate_uuid()

        # Generate a MAC address for this new instance.
        if DEBUG:
            mac = DEBUG_MAC_ADDRESS
        else:
            mac = _generate_mac_address()

        # Connect to the hypervisor.
        connection = _connect_to_hypervisor()

        # Now we have enough information to actually create and install the
        # domain.
        domain = _begin_domain_installation( \
            connection,
            name                = name,
            install_kernel_path = install_kernel_path,
            install_initrd_path = install_initrd_path,
            extra_append        = extra_append,
            mem_kb              = mem_kb,
            vcpus               = vcpus,
            uuid                = uuid,
            disk_image_path     = disk_image_path,
            disk_image_type     = disk_image_type,
            mac                 = mac)

        # Wait for the domain's installation to complete.  We must do this so
        # that we can restart the domain with a runnable configuration.
        _wait_for_domain_installation_completion(connection, domain)

        _check_guest_mbr(disk_image_path)

        # Write out the configuration file.
        config_file_path = _create_boot_config_file( \
            name                = name,
            mem_kb              = mem_kb,
            vcpus               = vcpus,
            uuid                = uuid,
            disk_image_path     = disk_image_path,
            disk_image_type     = disk_image_type,
            mac                 = mac)
        files_to_cleanup.append(config_file_path)

        # Restart the domain with the new configuration.
        _boot_domain(uuid)

        # The domain is now started.  Finally, refresh the current
        # virtualization state on the server.

        # VCPUs get plugged in one at a time, querying the hypervisor state
        # too soon was resulting in 1 always being returned. Sleep here
        # allows the hypervisor to plug in the VCPUs and us to get the correct
        # value reported back in RHN:
        time.sleep(5)

        virt_support.refresh()

        # If we got here, we know everything went ok.  We'll only remove the
        # temporary installation kernel and initrd files.
        files_to_cleanup = []
        files_to_cleanup.append(install_kernel_path)
        files_to_cleanup.append(install_initrd_path)

    finally:
        # If something went wrong, the logic will bounce out here before
        # returning to the caller.  We'll use this opportunity to clean up
        # any files that we might have created so far.  It would be quite rude
        # to leave multi-GB sized files laying around.
        for file in files_to_cleanup:
            if os.path.exists(file):
                os.unlink(file)
示例#12
0
        imageArch = 'i686'

    create_params = { 'name'           : imageName,
                      'arch'           : imageArch,
                      'extra'          : extraParams,
                      'mem_kb'         : params["memKB"],
                      'vcpus'          : params["vCPUs"],
                      'uuid'           : uuid,
                      'disk'           : extractedImagePath,
                      'imageType'      : imageType,
                      'virtBridge'     : params["virtBridge"],
                    }
    create_xml = _generateXML( create_params )
    domain = None
    try:
        domain = connection.defineXML(create_xml)
    except Exception, e:
        return (1, "failed to pass XML to libvirt: %s" % e, {})

    domain.create()
    virt_support.refresh()

    return (0, "image '%s' deployed and started" % imageName, {})

# just for testing
if __name__ == "__main__":
    # test code
    log.log_debug("actions/image.py called")
    print "You can not run this module by itself"
    sys.exit(-1)
示例#13
0
def initiate_guest(name, mem_kb, vcpus, disk_gb, extra_append,
        log_notify_handler=None):

    files_to_cleanup = []

    # We'll wrap this up in a try block so that we can clean up should an
    # exception occur.
    try:
        # First, download the kickstart file.
        kickstart_config = common.download_kickstart_file(extra_append)

        # This hack sucks, but it works around a race condition dealing with
        # the tiny url generation on the server.  Basically, if we request
        # the download images too soon after receiving the ks config file, we
        # are served a 404.  We'll remove this hack when we figure out what the
        # server-side issue is.
        time.sleep(5)

        # Download the kernel and initrd images.
        (install_kernel_path, install_initrd_path) = \
            common.download_install_images(kickstart_config, "images/xen",
                XEN_INSTALL_IMAGE_DIR)
        files_to_cleanup.append(install_kernel_path)
        files_to_cleanup.append(install_initrd_path)

        # Create the disk image for the instance.
        disk_image_path = _create_disk_image(name, disk_gb)
        files_to_cleanup.append(disk_image_path)

        # Determine the type of disk image.
        disk_image_type = _determine_disk_image_type(disk_image_path)

        # Generate a UUID for this new instance.
        uuid = _generate_uuid()

        # Generate a MAC address for this new instance.
        if DEBUG:
            mac = DEBUG_MAC_ADDRESS
        else:
            mac = _generate_mac_address()

        # Connect to the hypervisor.
        connection = _connect_to_hypervisor()

        # Now we have enough information to actually create and install the
        # domain.
        domain = _begin_domain_installation( \
            connection,
            name                = name,
            install_kernel_path = install_kernel_path,
            install_initrd_path = install_initrd_path,
            extra_append        = extra_append,
            mem_kb              = mem_kb,
            vcpus               = vcpus,
            uuid                = uuid,
            disk_image_path     = disk_image_path,
            disk_image_type     = disk_image_type,
            mac                 = mac)

        # Wait for the domain's installation to complete.  We must do this so
        # that we can restart the domain with a runnable configuration.
        _wait_for_domain_installation_completion(connection, domain)

        _check_guest_mbr(disk_image_path)

        # Write out the configuration file.
        config_file_path = _create_boot_config_file( \
            name                = name,
            mem_kb              = mem_kb,
            vcpus               = vcpus,
            uuid                = uuid,
            disk_image_path     = disk_image_path,
            disk_image_type     = disk_image_type,
            mac                 = mac)
        files_to_cleanup.append(config_file_path)

        # Restart the domain with the new configuration.
        _boot_domain(uuid)

        # The domain is now started.  Finally, refresh the current
        # virtualization state on the server.

        # VCPUs get plugged in one at a time, querying the hypervisor state
        # too soon was resulting in 1 always being returned. Sleep here
        # allows the hypervisor to plug in the VCPUs and us to get the correct
        # value reported back in RHN:
        time.sleep(5)

        virt_support.refresh()

        # If we got here, we know everything went ok.  We'll only remove the
        # temporary installation kernel and initrd files.
        files_to_cleanup = []
        files_to_cleanup.append(install_kernel_path)
        files_to_cleanup.append(install_initrd_path)

    finally:
        # If something went wrong, the logic will bounce out here before
        # returning to the caller.  We'll use this opportunity to clean up
        # any files that we might have created so far.  It would be quite rude
        # to leave multi-GB sized files laying around.
        for file in files_to_cleanup:
            if os.path.exists(file):
                os.unlink(file)
示例#14
0
 def commit(self):
     # Syncing the profile resolves a problem with guests not
     # showing
     sys.path.append("/usr/share/rhn")
     from virtualization import support
     support.refresh(True)
示例#15
0
def deploy(params, extraParams="",cache_only=None):
    """start and connect a local image with SUSE Manager"""

    urlParts  = params["downloadURL"].split('/')
    studioArchiveFileName  = urlParts[-1]
    checksum  = urlParts[-2]

    # studioArchiveFileName = workshop_test_sles11sp1.i686-0.0.1.vmx.tar.gz
    # studioArchiveFileName = Just_enough_OS_openSUSE_12.1.x86_64-0.0.1.xen.tar.gz
    m = re.search( '(.*)\.(x86_64|i\d86)-(\d+\.\d+\.\d+)\.(xen|vmx|qcow2)', studioArchiveFileName )

    imageName    = m.group(1)
    imageArch    = m.group(2)
    imageVersion = m.group(3)
    imageType    = m.group(4)
    studioImageDiskFileName = imageName+"."+imageArch+"-"+imageVersion

    try:
        connection = _connect_to_hypervisor()
    except Exception:
        e = sys.exc_info()[1]
        return (1, "%s" % e, {})

    # if we got an explicit name, we'll use it
    if "domainName" in params and params["domainName"] != "":
        imageName = params["domainName"]
    # if not, we'll try to find a free name
    elif( _domainExists(imageName, connection) ):
        for i in itertools.count(1):
            newImageName = ("%s-%i" % (imageName,i))
            if not _domainExists(newImageName, connection):
                log.log_debug("free domain found")
                imageName = newImageName
                break
    log.log_debug( "name=%s arch=%s ver=%s type=%s" % (imageName,imageArch,imageVersion,imageType) )

    if len(imageName) < 1 or len(imageArch) < 1:
        log.log_debug("invalid image name or arch")
        return (1, "invalid image name or arch: name=%s arch=%s ver=%s type=%s" % (imageName,imageArch,imageVersion,imageType), {})

    httpResponseCode = -1
    if not _fileExists("%s/%s" % (IMAGE_BASE_PATH,studioArchiveFileName), checksum):
        try:
            httpResponseCode = _downloadFile(studioArchiveFileName,params["downloadURL"],params["proxySettings"])
            if not _fileExists("%s/%s" % (IMAGE_BASE_PATH,studioArchiveFileName), checksum):
                log.log_debug("downloading image file failed. HTTP Code is: %s" % httpResponseCode)
                return (1, "downloading image file failed: %s/%s (%s)" % (IMAGE_BASE_PATH, studioArchiveFileName,httpResponseCode), {})
        except Exception:
            e = sys.exc_info()[1]
            return ( 1, "getting the image failed with: %s" % e )
    if cache_only:
        return (0, "image fetched and cached for later deployment", {})
    try:
        targetDir = _createTargetDir( "%s/%s" % (IMAGE_BASE_PATH, imageName) )
        _extractImage( "%s/%s" % (IMAGE_BASE_PATH,studioArchiveFileName), targetDir, imageType )
    except Exception:
        e = sys.exc_info()[1]
        return (1, "extracting the image tarball failed with: %s" % e, {})

    # image exists in $IMAGE_BASE_PATH/$imageName now

    uuid = generate_uuid()
    # FIXME: check for the extensions. There might be more
    studioFileExtension = "vmdk"
    if imageType == "xen":
        studioFileExtension = "raw"
    elif imageType == "qcow2":
        studioFileExtension = "qcow2"
    extractedImagePath = "%s/%s.%s" % (targetDir,studioImageDiskFileName,studioFileExtension)
    log.log_debug("working on image in %s" % extractedImagePath)
    if not os.path.exists( extractedImagePath ):
        return (1, "extracted image not found at %s" % extractedImagePath, {})
    if imageArch in ( 'i386', 'i486', 'i568' ):
        imageArch = 'i686'

    create_params = { 'name'           : imageName,
                      'arch'           : imageArch,
                      'extra'          : extraParams,
                      'mem_kb'         : params["memKB"],
                      'vcpus'          : params["vCPUs"],
                      'uuid'           : uuid,
                      'disk'           : extractedImagePath,
                      'imageType'      : imageType,
                      'virtBridge'     : params["virtBridge"],
                    }
    create_xml = _generateXML( create_params )
    domain = None
    try:
        domain = connection.defineXML(create_xml)
    except Exception:
        e = sys.exc_info()[1]
        return (1, "failed to pass XML to libvirt: %s" % e, {})

    domain.create()
    virt_support.refresh()

    return (0, "image '%s' deployed and started" % imageName, {})
示例#16
0
            def commit(self):
                cfg = RHN().retrieve()
                self.logger.debug(cfg)
                rhntype = cfg["rhntype"]
                serverurl = cfg["url"]
                cacert = cfg["ca_cert"]
                activationkey = cfg["activationkey"]
                username = cfg["username"]
                profilename = cfg["profile"]
                proxy = cfg["proxy"]
                proxyuser = cfg["proxyuser"]

                # novirtinfo: rhn-virtualization daemon refreshes virtinfo
                extra_args = ['--novirtinfo', '--norhnsd', '--nopackages',
                              '--force']
                args = ['/usr/sbin/rhnreg_ks']
                if rhntype == "rhn":
                    sys.path.append("/usr/share/rhn/up2date_client")
                    import rhnreg
                    rhnreg.cfg.set("serverURL", RHN_XMLRPC_ADDR)
                    rhnreg.cfg.set("sslCACert", RHN_SSL_CERT)
                    rhnreg.cfg.save()
                    self.logger.info("ran update")
                if serverurl:
                    cacert = cacert if cacert is not None else serverurl + \
                        "/pub/RHN-ORG-TRUSTED-SSL-CERT"
                    if not serverurl.endswith("/XMLRPC"):
                        serverurl = serverurl + "/XMLRPC"
                    args.append('--serverUrl')
                    args.append(serverurl)
                    location = "/etc/sysconfig/rhn/%s" % \
                               os.path.basename(cacert)
                    if cacert:
                        if not os.path.exists(cacert):
                            self.logger.info("Downloading CA cert.....")
                            self.logger.debug("From: %s To: %s" %
                                              (cacert, location))
                            RHN().retrieveCert(cacert, location)
                        if os.path.isfile(location):
                            if os.stat(location).st_size > 0:
                                args.append('--sslCACert')
                                args.append(location)
                                ovirt_store_config(location)
                            else:
                                raise RuntimeError("Error Downloading \
                                                   CA cert!")
                if activationkey:
                    args.append('--activationkey')
                    args.append(activationkey)
                elif username:
                    args.append('--username')
                    args.append(username)
                    if password:
                        args.append('--password')
                        args.append(password)
                else:
                    # skip RHN registration when neither activationkey
                    # nor username/password is supplied
                    self.logger.debug("No activationkey or "
                                      "username+password given")
                    return

                if profilename:
                    args.append('--profilename')
                    args.append(profilename)

                if proxy:
                    args.append('--proxy')
                    args.append(proxy)
                    if proxyuser:
                        args.append('--proxyUser')
                        args.append(proxyuser)
                        if proxypass:
                            args.append('--proxyPassword')
                            args.append(proxypass)
                args.extend(extra_args)

                self.logger.info("Registering to RHN account.....")
                remove_config("/etc/sysconfig/rhn/systemid")
                remove_config("/etc/sysconfig/rhn/up2date")
                logged_args = list(args)
                remove_values_from_args = ["--password", "--proxyPassword"]
                for idx, arg in enumerate(logged_args):
                    if arg in remove_values_from_args:
                        logged_args[idx+1] = "XXXXXXX"
                logged_args = str(logged_args)
                self.logger.debug(logged_args)
                try:
                    subprocess.check_call(args)
                    ovirt_store_config("/etc/sysconfig/rhn/up2date")
                    ovirt_store_config("/etc/sysconfig/rhn/systemid")
                    self.logger.info("System %s sucessfully registered to %s" %
                                     (profilename, serverurl))
                    # sync profile if reregistering, fixes problem with
                    # virt guests not showing
                    sys.path.append("/usr/share/rhn")
                    from virtualization import support
                    support.refresh(True)
                except:
                    self.logger.exception("Failed to call: %s" % logged_args)
                    raise RuntimeError("Error registering to RHN account")
示例#17
0
def sendVirtInfo(systemId):
    if support is not None:
        support.refresh()
示例#18
0
            def commit(self):
                cfg = RHN().retrieve()
                self.logger.debug(cfg)
                rhntype = cfg["rhntype"]
                serverurl = cfg["url"]
                cacert = cfg["ca_cert"]
                activationkey = cfg["activationkey"]
                username = cfg["username"]
                profilename = cfg["profile"]
                proxy = cfg["proxy"]
                proxyuser = cfg["proxyuser"]

                # novirtinfo: rhn-virtualization daemon refreshes virtinfo
                extra_args = [
                    '--novirtinfo', '--norhnsd', '--nopackages', '--force'
                ]
                args = ['/usr/sbin/rhnreg_ks']
                if rhntype == "rhn":
                    sys.path.append("/usr/share/rhn/up2date_client")
                    import rhnreg
                    rhnreg.cfg.set("serverURL", RHN_XMLRPC_ADDR)
                    rhnreg.cfg.set("sslCACert", RHN_SSL_CERT)
                    rhnreg.cfg.save()
                    self.logger.info("ran update")
                if serverurl:
                    cacert = cacert if cacert is not None else serverurl + \
                        "/pub/RHN-ORG-TRUSTED-SSL-CERT"
                    if not serverurl.endswith("/XMLRPC"):
                        serverurl = serverurl + "/XMLRPC"
                    args.append('--serverUrl')
                    args.append(serverurl)
                    location = "/etc/sysconfig/rhn/%s" % \
                               os.path.basename(cacert)
                    if cacert:
                        if not os.path.exists(cacert):
                            self.logger.info("Downloading CA cert.....")
                            self.logger.debug("From: %s To: %s" %
                                              (cacert, location))
                            RHN().retrieveCert(cacert, location)
                        if os.path.isfile(location):
                            if os.stat(location).st_size > 0:
                                args.append('--sslCACert')
                                args.append(location)
                                ovirt_store_config(location)
                            else:
                                raise RuntimeError("Error Downloading \
                                                   CA cert!")
                if activationkey:
                    args.append('--activationkey')
                    args.append(activationkey)
                elif username:
                    args.append('--username')
                    args.append(username)
                    if password:
                        args.append('--password')
                        args.append(password)
                else:
                    # skip RHN registration when neither activationkey
                    # nor username/password is supplied
                    self.logger.debug("No activationkey or "
                                      "username+password given")
                    return

                if profilename:
                    args.append('--profilename')
                    args.append(profilename)

                if proxy:
                    args.append('--proxy')
                    args.append(proxy)
                    if proxyuser:
                        args.append('--proxyUser')
                        args.append(proxyuser)
                        if proxypass:
                            args.append('--proxyPassword')
                            args.append(proxypass)
                args.extend(extra_args)

                self.logger.info("Registering to RHN account.....")
                remove_config("/etc/sysconfig/rhn/systemid")
                remove_config("/etc/sysconfig/rhn/up2date")
                logged_args = list(args)
                remove_values_from_args = ["--password", "--proxyPassword"]
                for idx, arg in enumerate(logged_args):
                    if arg in remove_values_from_args:
                        logged_args[idx + 1] = "XXXXXXX"
                logged_args = str(logged_args)
                self.logger.debug(logged_args)
                try:
                    subprocess.check_call(args)
                    ovirt_store_config("/etc/sysconfig/rhn/up2date")
                    ovirt_store_config("/etc/sysconfig/rhn/systemid")
                    self.logger.info("System %s sucessfully registered to %s" %
                                     (profilename, serverurl))
                    # sync profile if reregistering, fixes problem with
                    # virt guests not showing
                    sys.path.append("/usr/share/rhn")
                    from virtualization import support
                    support.refresh(True)
                except:
                    self.logger.exception("Failed to call: %s" % logged_args)
                    raise RuntimeError("Error registering to RHN account")