File mgr-virtualization-git-0.1d575b5.obscpio of Package mgr-virtualization.11261

07070100000000000041FD0000000000000000000000015CDC5C8900000000000000000000000000000000000000000000001300000000mgr-virtualization07070100000001000081B40000000000000000000000015CDC5C89000046AC000000000000000000000000000000000000001B00000000mgr-virtualization/LICENSE                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
07070100000002000081B40000000000000000000000015CDC5C8900000026000000000000000000000000000000000000001C00000000mgr-virtualization/Makefileinclude ../../../rel-eng/Makefile.git
07070100000003000081B40000000000000000000000015CDC5C890000034E000000000000000000000000000000000000002300000000mgr-virtualization/Makefile.pythonTHIS_MAKEFILE := $(realpath $(lastword $(MAKEFILE_LIST)))
CURRENT_DIR := $(dir $(THIS_MAKEFILE))
include $(CURRENT_DIR)../../../rel-eng/Makefile.python

# Docker tests variables
DOCKER_CONTAINER_BASE = uyuni-master
DOCKER_REGISTRY       = registry.mgr.suse.de
DOCKER_RUN_EXPORT     = "PYTHONPATH=$PYTHONPATH"
DOCKER_VOLUMES        = -v "$(CURDIR)/../../../:/manager"

__pylint ::
	$(call update_pip_env)
	pylint --rcfile=pylintrc $(shell find -name '*.py') > reports/pylint.log || true

docker_pylint ::
	docker run --rm -e $(DOCKER_RUN_EXPORT) $(DOCKER_VOLUMES) $(DOCKER_REGISTRY)/$(DOCKER_CONTAINER_BASE)-pgsql /bin/sh -c "cd /manager/client/tools/mgr-virtualization; make -f Makefile.python __pylint"

docker_shell ::
	docker run -t -i --rm -e $(DOCKER_RUN_EXPORT) $(DOCKER_VOLUMES) $(DOCKER_REGISTRY)/$(DOCKER_CONTAINER_BASE)-pgsql /bin/bash
07070100000004000081B40000000000000000000000015CDC5C89000003E3000000000000000000000000000000000000002F00000000mgr-virtualization/Makefile.rhn-virtualizationSUBDIRS = actions virtualization scripts
PYFILES = $(wildcard *.py)

PKGNAME = rhn-virtualization
VERSION = $(shell echo `awk '{ print $$1 }' version`)
RELEASE = $(shell echo `awk '{ print $$2 }' version`)
PYTHON=python

all: subdirs

clean:
	rm -f *.pyc *.pyo *~ *.bak *.tar.gz
	for d in $(SUBDIRS); do make -C $$d clean ; done

subdirs:
	for d in $(SUBDIRS); do make PYTHON=$(PYTHON) -C $$d; [ $$? = 0 ] || exit 1 ; done

install:
	for d in $(SUBDIRS); do make PYTHON=$(PYTHON) DESTDIR=$(DESTDIR) -C $$d install; [ $$? = 0 ] || exit 1; done

archive: _archive

_archive:
	@rm -rf ${PKGNAME}-%{VERSION}.tar.gz
	@rm -rf /tmp/${PKGNAME}-$(VERSION) /tmp/${PKGNAME}
	@dir=$$PWD; cd /tmp; cp -a $$dir ${PKGNAME}
	@mv /tmp/${PKGNAME} /tmp/${PKGNAME}-$(VERSION)
	@dir=$$PWD; cd /tmp; tar cvzf $$dir/${PKGNAME}-$(VERSION).tar.gz ${PKGNAME}-$(VERSION)
	@rm -rf /tmp/${PKGNAME}-$(VERSION)	
	@echo "The archive is in ${PKGNAME}-$(VERSION).tar.gz"

rpm: archive
	rpmbuild -ta ${PKGNAME}-$(VERSION).tar.gz

07070100000005000041FD0000000000000000000000015CDC5C8900000000000000000000000000000000000000000000001B00000000mgr-virtualization/actions07070100000006000081B40000000000000000000000015CDC5C8900000104000000000000000000000000000000000000002400000000mgr-virtualization/actions/MakefilePYTHON=python
PYFILES = $(wildcard *.py)
PKGDIR = $(PYTHONPATH)/rhn/actions/

all: 
	echo "Nothing to do"

clean:
	rm -f *.pyc *.pyo *~

install:
	mkdir -p $(DESTDIR)/$(PKGDIR)
	for p in $(PYFILES) ; do \
		install -m 644 $$p $(DESTDIR)/$(PKGDIR)/$$p; \
	done
07070100000007000081B40000000000000000000000015CDC5C8900001DC4000000000000000000000000000000000000002400000000mgr-virtualization/actions/image.py#!/usr/bin/python
import base64
try:
    # python2
    import ConfigParser
except ImportError:
    # python3
    import configparser as ConfigParser
import itertools
import os
import platform
import pycurl
import sys

import virtualization.support as virt_support
from virtualization.util import generate_uuid
from virtualization.errors import VirtualizationException
from up2date_client import up2dateLog

log = up2dateLog.initLog()

config = ConfigParser.ConfigParser({
    "IMAGE_BASE_PATH"      : "/var/lib/libvirt/images/",
    "IMAGE_CFG_TEMPLATE"   : "/etc/sysconfig/rhn/kvm-template.xml",
    "PRE_SCRIPT"           : "",
})
config.read('/etc/sysconfig/rhn/image.cfg')
IMAGE_BASE_PATH    = config.get("global", "IMAGE_BASE_PATH")
IMAGE_CFG_TEMPLATE = config.get("global", "IMAGE_CFG_TEMPLATE")
PRE_SCRIPT         = config.get("global", "PRE_SCRIPT")

# mark this module as acceptable
__rhnexport__ = [
    'deploy'
]

def _download_file(target_filename, server_url, proxy_settings):
    """Download file from a URL to given filename using given proxy settings."""
    log.log_debug("downloading %s" % server_url)

    # get the file via pycurl
    c = pycurl.Curl()
    c.setopt(pycurl.URL, server_url)

    # proxy_settings: { proxyURL  : http://myproxy.site:3128
    #                   proxyUser : user
    #                   proxyPass : s3cr3t }
    # proxyUser and proxyPass are optional
    if "proxyURL" in proxy_settings and proxy_settings["proxyURL"] is not None and proxy_settings["proxyURL"] != "":
        server = proxy_settings["proxyURL"]
        c.setopt(pycurl.PROXY, server )
        if "proxyUser" in proxy_settings and proxy_settings["proxyUser"] is not None and proxy_settings["proxyUser"] != "":
            user     = proxy_settings["proxyUser"]
            password = base64.b64decode(proxy_settings["proxyPass"])
            c.setopt(pycurl.PROXYUSERPWD, "%s:%s" % (user, password))
    # default IMAGE_BASE_PATH is /var/lib/libvirt/images
    file_path = "/%s/%s" % (IMAGE_BASE_PATH, target_filename)
    f = open(file_path, 'w')
    c.setopt(pycurl.FOLLOWLOCATION, 1)
    c.setopt(pycurl.WRITEFUNCTION, f.write)
    c.setopt(pycurl.SSL_VERIFYPEER, 0)
    c.perform()
    log.log_debug("curl got HTTP code: %s" % c.getinfo(pycurl.HTTP_CODE))
    f.close()
    return c.getinfo(pycurl.HTTP_CODE)

def _connect_to_hypervisor():
    """Connect to the hypervisor."""
    # First, attempt to import libvirt.  If we don't have that, we can't do
    # much else.
    try:
        import libvirt
    except ImportError as ie:
        raise VirtualizationException("Unable to locate libvirt: %s" % str(ie))

    # Attempt to connect to the hypervisor.
    try:
        connection = libvirt.open(None)
    except Exception as e:
        raise VirtualizationException("Could not connect to hypervisor: %s" % str(e))

    return connection

def _file_exists(name):
    return os.path.exists(name)

def _domain_exists(dom, connection):
    try:
        connection.lookupByName(dom)
    except Exception:
        log.log_debug("domain %s does not exist" % dom)
        return False
    log.log_debug("domain %s exists" % dom)
    return True

def _generate_xml(params):
    """Populate the variables in the XML template file."""
    if PRE_SCRIPT != "":
        log.log_debug("running image pre-script %s" % PRE_SCRIPT)
        os.system(PRE_SCRIPT)

    if os.path.isfile(IMAGE_CFG_TEMPLATE):
        f = open(IMAGE_CFG_TEMPLATE, 'r')
        CREATE_TEMPLATE = f.read()
        f.close()

    created_xml = CREATE_TEMPLATE % params
    log.log_debug("libvirt XML: %s" % created_xml)
    return created_xml

# Download and start a new image given by the following parameters:
#
# downloadURL   : http://download.suse.de/install/SLE-15-JeOS-RC2/SLES15-JeOS.x86_64-15.0-kvm-and-xen-RC2.qcow2
# proxySettings : { proxyURL  : http://myproxy.site:3128
#                  proxyUser : user
#                  proxyPass : s3cr3t }
# memKB         : 524288
# vCPUs         : 1
# domainName    : virt_test_machine
# virtBridge    : br0
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, {})

# 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)
07070100000008000081B40000000000000000000000015CDC5C89000010A3000000000000000000000000000000000000002300000000mgr-virtualization/actions/virt.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
from virtualization import support, errors

__rhnexport__ = [
    'refresh',
    'shutdown',
    'suspend',
    'start',
    'resume',
    'reboot',
    'destroy',
    'setMemory',
    'setVCPUs',
    'schedulePoller']

##
# Refreshes the virtualization info for this host and any subdomains on the
# server.
#
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.", {})

def shutdown(uuid, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.shutdown(uuid)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Domain %s shutdown." % str(uuid), {})

def start(uuid, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.start(uuid)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Domain %s started." % str(uuid), {})

def suspend(uuid, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.suspend(uuid)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Domain %s suspended." % str(uuid), {})

def resume(uuid, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.resume(uuid)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Domain %s resumed." % str(uuid), {})

def reboot(uuid, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.reboot(uuid)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Domain %s rebooted." % str(uuid), {})

def destroy(uuid, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.destroy(uuid)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Domain %s destroyed." % str(uuid), {})

def setMemory(uuid, memory, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.setMemory(uuid, memory)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "Memory set to %s on %s." % (str(memory), str(uuid)), {})

def setVCPUs(uuid, vcpus, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    try:
        support.setVCPUs(uuid, vcpus)
    except errors.VirtualizationException:
        ve = sys.exc_info()[1]
        return (1, str(ve), {})
    return (0, "VCPUs set to %s on %s." % (str(vcpus), str(uuid)), {})

def schedulePoller(minute, hour, dom, month, dow, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    ret_val = support.schedulePoller(minute, hour, dom, month, dow)
    return (ret_val[0], ret_val[1], {})

###############################################################################
# Test Routine
###############################################################################

if __name__ == "__main__":
    import sys
    import actions.virt
    func = getattr(actions.virt, sys.argv[1])
    print(func(*tuple(sys.argv[2:])))

07070100000009000081B40000000000000000000000015CDC5C890000003C000000000000000000000000000000000000003000000000mgr-virtualization/mgr-virtualization-rpmlintrcaddFilter("suse-filelist-forbidden-sysconfig .*/sysconfig")
0707010000000A000081B40000000000000000000000015CDC5C8900002450000000000000000000000000000000000000002E00000000mgr-virtualization/mgr-virtualization.changes-------------------------------------------------------------------
Wed May 15 20:08:58 CEST 2019 - jgonzalez@suse.com

- version 4.0.6-1
- Obsolete newer versions of rhn-virtualization

-------------------------------------------------------------------
Wed May 15 15:00:56 CEST 2019 - jgonzalez@suse.com

- version 4.0.5-1
- SPEC cleanup
- Fix wrong bugzilla entry at changelog

-------------------------------------------------------------------
Mon Apr 22 12:04:03 CEST 2019 - jgonzalez@suse.com

- version 4.0.4-1
- add makefile and pylint configuration

-------------------------------------------------------------------
Mon Mar 25 16:37:47 CET 2019 - jgonzalez@suse.com

- version 4.0.3-1
- convert poller to systemd timer (bsc#1115414)

-------------------------------------------------------------------
Fri Oct 26 09:59:54 CEST 2018 - jgonzalez@suse.com

- version 4.0.2-1
- Fix Obsolete/Provides for subpackage python2-mgr-virtualization-host
  (bsc#1104034)

-------------------------------------------------------------------
Fri Aug 10 16:03:24 CEST 2018 - jgonzalez@suse.com

- version 4.0.1-1
- Bump version to 4.0.0 (bsc#1104034)
- Rename package to mgr-virtualization to allow version 4.0.0 (bsc#1104034)
- Fix copyright for the package specfile (bsc#1103696)

-------------------------------------------------------------------
Wed Apr 25 12:20:06 CEST 2018 - jgonzalez@suse.com

- version 5.4.72.2-1
- Remove SUSE Studio based image deployments (bsc#1090504)

-------------------------------------------------------------------
Mon Mar 26 08:35:00 CEST 2018 - jgonzalez@suse.com

- version 5.4.72.1-1
- Sync with upstream (bsc#1083294)
- Build python2 packages on SUSE systems

-------------------------------------------------------------------
Mon Mar 05 09:15:28 CET 2018 - jgonzalez@suse.com

- version 5.4.71.2-1
- remove empty clean section from spec (bsc#1083294)

-------------------------------------------------------------------
Fri Feb 23 10:49:53 CET 2018 - jgonzalez@suse.com

- version 5.4.71.1-1
- Sync with upstream

-------------------------------------------------------------------
Fri Nov 10 16:26:59 CET 2017 - mc@suse.de

- version 5.4.69.1-1
- simplify status check
- open cache file in binary mode
- fixing traceback from poller.py on Python 3
- fixing a bytes-like object is required, not 'str'

-------------------------------------------------------------------
Thu Oct 26 17:17:59 CEST 2017 - mc@suse.de

- version 5.4.64.1-1
- move files into proper python2/python3 subpackages

-------------------------------------------------------------------
Tue Mar 07 16:02:10 CET 2017 - mc@suse.de

- version 5.4.57.1-1
- Updated links to github in spec files
- require spacewalk-usix indead of spacewalk-backend-usix

-------------------------------------------------------------------
Wed Jan 11 15:35:45 CET 2017 - michele.bologna@suse.com

- version 5.4.56.1-1
- Version 5.4.56-1

-------------------------------------------------------------------
Thu Oct 22 16:35:14 CEST 2015 - mc@suse.de

- version 5.4.55.2-1
- fix guest report of virtual hosts (bsc#950372)

-------------------------------------------------------------------
Wed Oct 07 16:00:20 CEST 2015 - mc@suse.de

- version 5.4.55.1-1
- Bump version

-------------------------------------------------------------------
Tue Feb 03 13:09:08 CET 2015 - mc@suse.de

- version 5.4.50.5-1
- Getting rid of Tabs and trailing spaces

-------------------------------------------------------------------
Thu Dec 18 13:53:25 CET 2014 - mc@suse.de

- version 5.4.50.4-1

-------------------------------------------------------------------
Wed Sep  3 01:41:38 CEST 2014 - ro@suse.de

- sanitize release line in specfile

-------------------------------------------------------------------
Tue May 06 15:25:12 CEST 2014 - mc@suse.de

- version 5.4.50.3-1
- some systems to not have /sbin in path
- service location is not platform independent
- rhn-virt-host should not spam root if libvirtd is stopped

-------------------------------------------------------------------
Thu Apr 10 17:28:06 CEST 2014 - mc@suse.de

- version 5.4.50.2-1

-------------------------------------------------------------------
Thu Apr 10 17:27:58 CEST 2014 - mc@suse.de

- fix release in specfile for SLE12 (bnc#872970)

-------------------------------------------------------------------
Mon Dec 09 16:15:43 CET 2013 - mc@suse.de

- version 5.4.50.1-1
- switch to 2.1

-------------------------------------------------------------------
Wed Jun 12 10:54:12 CEST 2013 - mc@suse.de

- version 5.4.34.13-1
- python 2.4 fix for 'exit'
- define a utf8_encode wrapper

-------------------------------------------------------------------
Thu Apr 04 15:11:06 CEST 2013 - mc@suse.de

- version 5.4.34.12-1
- isInstallerConfig should check for autoyast in commandline
- catch libvirtError to return meaningfull error messages
- remove wrong kernel and initrd pathes from config
- Fix deployment of vmdk studio images (bnc#806202)

-------------------------------------------------------------------
Fri Feb 08 10:55:54 CET 2013 - mc@suse.de

- version 5.4.34.11-1
- rhn-virtualization-host needs to consistantly use the new function
  definition
- support studio KVM image type (bnc#797057)

-------------------------------------------------------------------
Thu Nov 22 15:54:13 CET 2012 - jrenner@suse.de

- version 5.4.34.10-1
- fix invalid return value in image deployment (bnc#786159)

-------------------------------------------------------------------
Mon Jul 16 15:27:10 CEST 2012 - ug@suse.de

- version 5.4.34.9-1
- rhn-profile-sync exits with status 1 if libvirtd is not running

-------------------------------------------------------------------
Mon Jun 25 13:38:05 CEST 2012 - mc@suse.de

- version 5.4.34.8-1
- fix typo in type checking

-------------------------------------------------------------------
Mon Jun 25 10:26:37 CEST 2012 - mc@suse.de

- version 5.4.34.7-1
- better support VirtualBox using listDefinedDomains in poller
  tool

-------------------------------------------------------------------
Thu Jun 21 11:10:55 CEST 2012 - jrenner@suse.de

- version 5.4.34.6-1
- Support for studio image deployments, upstream integration

-------------------------------------------------------------------
Thu May 31 10:43:07 CEST 2012 - mc@suse.de

- version 5.4.34.5-1
- requires python-pycurl on redhat/fedora now
- remove debugging code

-------------------------------------------------------------------
Mon May 14 10:42:43 CEST 2012 - mc@suse.de

- version 5.4.34.4-1
- fixed proxySettings for image fetching

-------------------------------------------------------------------
Wed May  9 15:30:25 CEST 2012 - ug@suse.de

- packaging of config file fixed

-------------------------------------------------------------------
Wed May 09 13:46:45 CEST 2012 - mc@suse.de

- version 5.4.34.3-1
- no use of /var/lock/subsys/ anymore

-------------------------------------------------------------------
Tue May  8 14:46:41 CEST 2012 - ug@suse.de

- added generate_uuid to utils.py
- inegrated upstream feedback to studio integration (bnc#764532)

-------------------------------------------------------------------
Fri Apr 27 16:28:52 CEST 2012 - mc@suse.de

- version 5.4.34.2-1
- rhn-virtualization-host should not delete chkconfig settings on
  upgrade

-------------------------------------------------------------------
Wed Mar 21 18:14:26 CET 2012 - mc@suse.de

- version 5.4.34.1-1
- Bumping package version

-------------------------------------------------------------------
Thu Mar 15 17:14:01 CET 2012 - jrenner@suse.de

- Add support for studio image deployments

-------------------------------------------------------------------
Thu Nov  3 19:24:12 CET 2011 - ma@suse.de

- Adapt dependencies to renamed packages (bnc#722052)

-------------------------------------------------------------------
Fri Oct 28 11:59:00 CEST 2011 - ug@suse.de

- Status of Virtual Machines is not properly recognized
  (bnc#683075)

-------------------------------------------------------------------
Fri Oct 21 16:31:28 CEST 2011 - ug@suse.de

- catch an exception when libvirtd is not running (bnc#696294)

-------------------------------------------------------------------
Mon Feb  7 17:26:30 CET 2011 - mc@suse.de

- add missing dir 

-------------------------------------------------------------------
Mon Feb  7 15:36:03 CET 2011 - mc@suse.de

- add rc link (bnc#669894) 

-------------------------------------------------------------------
Tue Jan 11 16:29:58 CET 2011 - mc@suse.de

- change strings in init script 

-------------------------------------------------------------------
Tue Nov  2 16:57:53 CET 2010 - mantel@suse.de

- don't ignore post-build-checks

-------------------------------------------------------------------
Wed Sep 22 15:20:47 CEST 2010 - mantel@suse.de

- move SuSE specific init script to scripts to make tito happy

-------------------------------------------------------------------
Wed Sep 15 12:18:19 CEST 2010 - mantel@suse.de

- fix post-build-checks

-------------------------------------------------------------------
Tue Sep 14 18:02:32 CEST 2010 - mantel@suse.de

- Initial release of rhn-virtualization

-------------------------------------------------------------------
0707010000000B000081B40000000000000000000000015CDC5C89000036D1000000000000000000000000000000000000002B00000000mgr-virtualization/mgr-virtualization.spec#
# spec file for package mgr-virtualization
#
# Copyright (c) 2019 SUSE LINUX GmbH, Nuernberg, Germany.
# Copyright (c) 2008-2018 Red Hat, Inc.
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.

# Please submit bugfixes or comments via https://bugs.opensuse.org/
#


# package renaming fun :(
%define rhn_client_tools spacewalk-client-tools
%define rhn_setup	 spacewalk-client-setup
%define rhn_check	 spacewalk-check
%define rhnsd		 spacewalksd
# Old name and version+1 before renaming to mgr-push
%define oldname          rhn-virtualization
%define oldversion       5.4.73
#
%define rhn_dir %{_datadir}/rhn
%define rhn_conf_dir %{_sysconfdir}/sysconfig/rhn
%define cron_dir %{_sysconfdir}/cron.d

%if 0%{?fedora} || 0%{?suse_version} > 1320 || 0%{?rhel} >= 8
%global build_py3   1
%global default_py3 1
%endif

%if ( 0%{?fedora} && 0%{?fedora} < 28 ) || ( 0%{?rhel} && 0%{?rhel} < 8 ) || 0%{?suse_version}
%global build_py2   1
%endif

%define pythonX %{?default_py3: python3}%{!?default_py3: python2}

Name:           mgr-virtualization
Summary:        Spacewalk action support for virualization
License:        GPL-2.0-only
Group:          System Environment/Base
Version:        4.0.6
Provides:       rhn-virtualization = %{oldversion}
Obsoletes:      rhn-virtualization < %{oldversion}
Release:        1%{?dist}

Url:            https://github.com/uyuni-project/uyuni
Source0:        https://github.com/spacewalkproject/spacewalk/archive/%{name}-%{version}.tar.gz
Source1:        %{name}-rpmlintrc

BuildRoot:      %{_tmppath}/%{name}-%{version}-build
%if 0%{?fedora} || 0%{?rhel} || 0%{?suse_version} >= 1210
BuildArch:      noarch
%endif
%if 0%{?suse_version}
# make chkconfig work in OBS
BuildRequires:  sysconfig
BuildRequires:  syslog
%endif

%description
rhn-virtualization provides various Spacewalk actions for manipulation
virtual machine guest images.

%if 0%{?build_py2}
%package -n python2-%{name}-common
Summary:        Files needed by rhn-virtualization-host
Group:          System Environment/Base
%{?python_provide:%python_provide python2-%{name}-common}
Provides:       python-%{name}-common = %{oldversion}
Obsoletes:      python-%{name}-common < %{oldversion}
Provides:       python-%{oldname}-common = %{oldversion}
Obsoletes:      python-%{oldname}-common < %{oldversion}
Provides:       %{name}-common = %{oldversion}
Obsoletes:      %{name}-common < %{oldversion}
Provides:       %{oldname}-common = %{oldversion}
Obsoletes:      %{oldname}-common < %{oldversion}
Requires:       python2-rhn-client-tools
Requires:       spacewalk-usix
BuildRequires:  python
%if 0%{?suse_version}
# aaa_base provide chkconfig
Requires:       aaa_base
# provide directories for filelist check in obs
BuildRequires:  rhn-check
BuildRequires:  rhn-client-tools
%else
Requires:       chkconfig
%endif
%description -n python2-%{name}-common
This package contains files that are needed by the rhn-virtualization-host
package.
%endif

%if 0%{?build_py3}
%package -n python3-%{name}-common
Summary:        Files needed by rhn-virtualization-host
Group:          System Environment/Base
Provides:       python3-%{oldname}-common = %{oldversion}
Obsoletes:      python3-%{oldname}-common < %{oldversion}
Obsoletes:      %{name}-common < %{oldversion}
Obsoletes:      %{oldname}-common < %{oldversion}
Requires:       python3-rhn-client-tools
Requires:       python3-spacewalk-usix
BuildRequires:  python3-devel

%description -n python3-%{name}-common
This package contains files that are needed by the rhn-virtualization-host
package.
%endif

%package host
Summary:        Spacewalk Virtualization support specific to the Host system
Group:          System Environment/Base
Provides:       %{oldname}-host = %{oldversion}
Obsoletes:      %{oldname}-host < %{oldversion}
Requires:       %{pythonX}-%{name}-host = %{version}-%{release}

%if 0%{?default_py3}
BuildRequires:  systemd
Requires(pre): systemd
Requires(post): systemd
Requires(preun): systemd
Requires(postun): systemd
%else
%if 0%{?suse_version}
Requires:       cron
%else
Requires:       /usr/sbin/crond
%endif
%endif

%description host
This package contains code for Spacewalk's Virtualization support
that is specific to the Host system (a.k.a. Dom0).

%if 0%{?build_py2}
%package -n python2-%{name}-host
Summary:        RHN/Spacewalk Virtualization support specific to the Host system
Group:          System Environment/Base
Provides:       python2-%{oldname}-host = %{oldversion}
Obsoletes:      python2-%{oldname}-host < %{oldversion}
Requires:       %{name}-host = %{version}-%{release}
Requires:       libvirt-python
Requires:       python2-%{name}-common = %{version}-%{release}
%if 0%{?suse_version}
Requires:       python-curl
%else
Requires:       python-pycurl
%endif
%description -n python2-%{name}-host
Python 2 files for %{name}-host.
%endif

%if 0%{?build_py3}
%package -n python3-%{name}-host
Summary:        RHN/Spacewalk Virtualization support specific to the Host system
Group:          System Environment/Base
Provides:       python3-%{oldname}-host = %{oldversion}
Obsoletes:      python3-%{oldname}-host < %{oldversion}
Requires:       %{name}-host = %{version}-%{release}
%if 0%{?suse_version}
Requires:       python3-libvirt-python
%else
Requires:       libvirt-python3
%endif
Requires:       python3-%{name}-common = %{version}-%{release}
Requires:       python3-pycurl

%description -n python3-%{name}-host
Python 3 files for %{name}-host.
%endif

%prep
%setup -q

%build
make -f Makefile.rhn-virtualization

%install
%if 0%{?build_py2}
make -f Makefile.rhn-virtualization DESTDIR=$RPM_BUILD_ROOT PKGDIR0=%{_initrddir} \
        PYTHONPATH=%{python_sitelib} install
sed -i 's,@PYTHON@,python,; s,@PYTHONPATH@,%{python_sitelib},;' \
        $RPM_BUILD_ROOT/%{_initrddir}/rhn-virtualization-host
%endif

%if 0%{?build_py3}
make -f Makefile.rhn-virtualization DESTDIR=$RPM_BUILD_ROOT PKGDIR0=%{_initrddir} \
        PYTHONPATH=%{python3_sitelib} install
        sed -i 's,@PYTHON@,python3,; s,@PYTHONPATH@,%{python3_sitelib},;' \
                $RPM_BUILD_ROOT/%{_initrddir}/rhn-virtualization-host
%endif

%if 0%{?default_py3}
install -d %{buildroot}%{_unitdir}
install -D -m 0644 scripts/mgr-virtualization.timer %{buildroot}%{_unitdir}/mgr-virtualization.timer
install -D -m 0644 scripts/mgr-virtualization.service %{buildroot}%{_unitdir}/mgr-virtualization.service
sed -i 's,@PYTHON@,python3,; s,@PYTHONPATH@,%{python3_sitelib},;' \
       %{buildroot}%{_unitdir}/mgr-virtualization.service

%else
install -d $RPM_BUILD_ROOT%{cron_dir}
install -D -m 0644 scripts/rhn-virtualization.cron $RPM_BUILD_ROOT%{cron_dir}/rhn-virtualization.cron
sed -i 's,@PYTHON@,python,; s,@PYTHONPATH@,%{python_sitelib},;' \
        $RPM_BUILD_ROOT/%{cron_dir}/rhn-virtualization.cron
%endif

%if 0%{?suse_version}
rm -f $RPM_BUILD_ROOT/%{_initrddir}/rhn-virtualization-host
%endif

%if 0%{?suse_version}
%py_compile -O %{buildroot}/%{python_sitelib}
%if 0%{?build_py3}
%py3_compile -O %{buildroot}/%{python3_sitelib}
%endif
%endif

%if 0%{?suse_version}
rm -f $RPM_BUILD_ROOT/%{_initrddir}/rhn-virtualization-host
%py_compile -O %{buildroot}/%{python_sitelib}
%if 0%{?build_py3}
%py3_compile -O %{buildroot}/%{python3_sitelib}
%endif
%endif

%if 0%{?suse_version}
%post host
if [ -d /proc/xen ]; then
    # xen kernel is running
    # change the default template to the xen version
    sed -i 's@^IMAGE_CFG_TEMPLATE=/etc/sysconfig/rhn/kvm-template.xml@IMAGE_CFG_TEMPLATE=/etc/sysconfig/rhn/xen-template.xml@' /etc/sysconfig/rhn/image.cfg
fi
%if 0%{?default_py3}
%service_add_post mgr-virtualization.timer

%pre
%service_add_pre mgr-virtualization.timer

%preun
%service_del_preun mgr-virtualization.timer

%postun
%service_del_postun mgr-virtualization.timer
%endif

%else

%if 0%{?default_py3}
%{!?systemd_post: %global systemd_post() if [ $1 -eq 1 ] ; then /usr/bin/systemctl enable %%{?*} >/dev/null 2>&1 || : ; fi; }
%{!?systemd_preun: %global systemd_preun() if [ $1 -eq 0 ] ; then /usr/bin/systemctl --no-reload disable %%{?*} > /dev/null 2>&1 || : ; /usr/bin/systemctl stop %%{?*} > /dev/null 2>&1 || : ; fi; }
%{!?systemd_postun_with_restart: %global systemd_postun_with_restart() /usr/bin/systemctl daemon-reload >/dev/null 2>&1 || : ; if [ $1 -ge 1 ] ; then /usr/bin/systemctl try-restart %%{?*} >/dev/null 2>&1 || : ; fi; }
%endif

%post host
%if 0%{?default_py3}
%systemd_post mgr-virtualization.timer
%else
/sbin/chkconfig --add rhn-virtualization-host
/sbin/service crond condrestart
%endif
if [ -d /proc/xen ]; then
    # xen kernel is running
    # change the default template to the xen version
    sed -i 's@^IMAGE_CFG_TEMPLATE=/etc/sysconfig/rhn/kvm-template.xml@IMAGE_CFG_TEMPLATE=/etc/sysconfig/rhn/xen-template.xml@' /etc/sysconfig/rhn/image.cfg
fi

%preun host
%if 0%{?default_py3}
%systemd_preun mgr-virtualization.timer
%else
if [ $1 = 0 ]; then
  /sbin/chkconfig --del rhn-virtualization-host
fi
%endif

%postun host
%if 0%{?default_py3}
%systemd_postun_with_restart mgr-virtualization.timer
%else
/sbin/service crond condrestart
%endif
%endif

%if 0%{?build_py2}
%files -n python2-%{name}-common
%defattr(-,root,root,-)
%dir %{python_sitelib}/virtualization
%{python_sitelib}/virtualization/__init__.py*
%{python_sitelib}/virtualization/batching_log_notifier.py*
%{python_sitelib}/virtualization/constants.py*
%{python_sitelib}/virtualization/errors.py*
%{python_sitelib}/virtualization/notification.py*
%{python_sitelib}/virtualization/util.py*
%doc LICENSE
%if 0%{?suse_version}
%dir %{python_sitelib}/virtualization
%endif
%endif

%if 0%{?build_py3}
%files -n python3-%{name}-common
%defattr(-,root,root,-)
%dir %{python3_sitelib}/virtualization
%{python3_sitelib}/virtualization/__init__.py*
%{python3_sitelib}/virtualization/batching_log_notifier.py*
%{python3_sitelib}/virtualization/constants.py*
%{python3_sitelib}/virtualization/errors.py*
%{python3_sitelib}/virtualization/notification.py*
%{python3_sitelib}/virtualization/util.py*
%doc LICENSE
%dir %{python3_sitelib}/virtualization/__pycache__
%{python3_sitelib}/virtualization/__pycache__/__init__.*
%{python3_sitelib}/virtualization/__pycache__/batching_log_notifier.*
%{python3_sitelib}/virtualization/__pycache__/constants.*
%{python3_sitelib}/virtualization/__pycache__/errors.*
%{python3_sitelib}/virtualization/__pycache__/notification.*
%{python3_sitelib}/virtualization/__pycache__/util.*
%if 0%{?suse_version}
%dir %{python3_sitelib}/virtualization
%endif
%endif

%files host
%defattr(-,root,root,-)
%if 0%{?suse_version}
%dir %{rhn_conf_dir}
%else
%{_initrddir}/rhn-virtualization-host
%endif
%dir %{rhn_conf_dir}/virt
%dir %{rhn_conf_dir}/virt/auto
%if 0%{?default_py3}
%{_unitdir}/mgr-virtualization.service
%{_unitdir}/mgr-virtualization.timer
%else
%config(noreplace) %attr(644,root,root) %{cron_dir}/rhn-virtualization.cron
%endif
%{rhn_conf_dir}/*-template.xml
%config(noreplace) %{rhn_conf_dir}/image.cfg
%doc LICENSE

%if 0%{?build_py2}
%files -n python2-%{name}-host
%defattr(-,root,root,-)
%dir %{python_sitelib}/rhn
%dir %{python_sitelib}/rhn/actions
%{python_sitelib}/virtualization/domain_config.py*
%{python_sitelib}/virtualization/domain_control.py*
%{python_sitelib}/virtualization/domain_directory.py*
%{python_sitelib}/virtualization/get_config_value.py*
%{python_sitelib}/virtualization/init_action.py*
%{python_sitelib}/virtualization/poller.py*
%{python_sitelib}/virtualization/schedule_poller.py*
%{python_sitelib}/virtualization/poller_state_cache.py*
%{python_sitelib}/virtualization/start_domain.py*
%{python_sitelib}/virtualization/state.py*
%{python_sitelib}/virtualization/support.py*
%{python_sitelib}/rhn/actions/virt.py*
%{python_sitelib}/rhn/actions/image.py*
%if 0%{?suse_version}
%dir %{python_sitelib}/rhn
%dir %{python_sitelib}/rhn/actions
%endif
%endif

%if 0%{?build_py3}
%files -n python3-%{name}-host
%defattr(-,root,root,-)
%dir %{python3_sitelib}/rhn
%dir %{python3_sitelib}/rhn/actions
%dir %{python3_sitelib}/rhn/actions/__pycache__
%{python3_sitelib}/virtualization/domain_config.py*
%{python3_sitelib}/virtualization/domain_control.py*
%{python3_sitelib}/virtualization/domain_directory.py*
%{python3_sitelib}/virtualization/get_config_value.py*
%{python3_sitelib}/virtualization/init_action.py*
%{python3_sitelib}/virtualization/poller.py*
%{python3_sitelib}/virtualization/schedule_poller.py*
%{python3_sitelib}/virtualization/poller_state_cache.py*
%{python3_sitelib}/virtualization/start_domain.py*
%{python3_sitelib}/virtualization/state.py*
%{python3_sitelib}/virtualization/support.py*
%{python3_sitelib}/rhn/actions/virt.py*
%{python3_sitelib}/rhn/actions/image.py*
%{python3_sitelib}/virtualization/__pycache__/domain_config.*
%{python3_sitelib}/virtualization/__pycache__/domain_control.*
%{python3_sitelib}/virtualization/__pycache__/domain_directory.*
%{python3_sitelib}/virtualization/__pycache__/get_config_value.*
%{python3_sitelib}/virtualization/__pycache__/init_action.*
%{python3_sitelib}/virtualization/__pycache__/poller.*
%{python3_sitelib}/virtualization/__pycache__/schedule_poller.*
%{python3_sitelib}/virtualization/__pycache__/poller_state_cache.*
%{python3_sitelib}/virtualization/__pycache__/start_domain.*
%{python3_sitelib}/virtualization/__pycache__/state.*
%{python3_sitelib}/virtualization/__pycache__/support.*
%{python3_sitelib}/rhn/actions/__pycache__/virt.*
%{python3_sitelib}/rhn/actions/__pycache__/image.*
%if 0%{?suse_version}
%dir %{python3_sitelib}/rhn
%dir %{python3_sitelib}/rhn/actions
%dir %{python3_sitelib}/rhn/actions/__pycache__
%endif
%endif

%changelog
0707010000000C000081B40000000000000000000000015CDC5C89000013A0000000000000000000000000000000000000001C00000000mgr-virtualization/pylintrc# mgr virtualisation package pylint configuration

[MASTER]

# Profiled execution.
profile=no

# Pickle collected data for later comparisons.
persistent=no


[MESSAGES CONTROL]

# Disable the message(s) with the given id(s).


disable=I0011,
	C0302,
	C0111,
	R0801,
	R0902,
	R0903,
	R0904,
	R0912,
	R0913,
	R0914,
	R0915,
	R0921,
	R0922,
	W0142,
	W0403,
	W0603,
	C1001,
	W0121,
	useless-else-on-loop,
	bad-whitespace,
	unpacking-non-sequence,
	superfluous-parens,
	cyclic-import,
	redefined-variable-type,
	no-else-return,

        # Uyuni disabled
	E0203,
	E0611,
	E1101,
	E1102

# list of disabled messages:
#I0011: 62: Locally disabling R0201
#C0302:  1: Too many lines in module (2425)
#C0111:  1: Missing docstring
#R0902: 19:RequestedChannels: Too many instance attributes (9/7)
#R0903:  Too few public methods
#R0904: 26:Transport: Too many public methods (22/20)
#R0912:171:set_slots_from_cert: Too many branches (59/20)
#R0913:101:GETServer.__init__: Too many arguments (11/10)
#R0914:171:set_slots_from_cert: Too many local variables (38/20)
#R0915:171:set_slots_from_cert: Too many statements (169/50)
#W0142:228:MPM_Package.write: Used * or ** magic
#W0403: 28: Relative import 'rhnLog', should be 'backend.common.rhnLog'
#W0603: 72:initLOG: Using the global statement
# for pylint-1.0 we also disable
#C1001: 46, 0: Old-style class defined. (old-style-class)
#W0121: 33,16: Use raise ErrorClass(args) instead of raise ErrorClass, args. (old-raise-syntax)
#W:243, 8: Else clause on loop without a break statement (useless-else-on-loop)
# pylint-1.1 checks
#C:334, 0: No space allowed after bracket (bad-whitespace)
#W:162, 8: Attempting to unpack a non-sequence defined at line 6 of (unpacking-non-sequence)
#C: 37, 0: Unnecessary parens after 'not' keyword (superfluous-parens)
#C:301, 0: Unnecessary parens after 'if' keyword (superfluous-parens)

[REPORTS]

# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html
output-format=parseable

# Include message's id in output
include-ids=yes

# Tells whether to display a full report or only the messages
reports=yes

# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}"

[VARIABLES]

# A regular expression matching names used for dummy variables (i.e. not used).
dummy-variables-rgx=_|dummy


[BASIC]

# Regular expression which should only match correct module names
#module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
module-rgx=([a-zA-Z_][a-zA-Z0-9_]+)$

# Regular expression which should only match correct module level names
const-rgx=(([a-zA-Z_][a-zA-Z0-9_]*)|(__.*__))$

# Regular expression which should only match correct class names
class-rgx=[a-zA-Z_][a-zA-Z0-9_]+$

# Regular expression which should only match correct function names
function-rgx=[a-z_][a-zA-Z0-9_]{,42}$

# Regular expression which should only match correct method names
method-rgx=[a-z_][a-zA-Z0-9_]{,42}$

# Regular expression which should only match correct instance attribute names
attr-rgx=[a-z_][a-zA-Z0-9_]{,30}$

# Regular expression which should only match correct argument names
argument-rgx=[a-z_][a-zA-Z0-9_]{,30}$

# Regular expression which should only match correct variable names
variable-rgx=[a-z_][a-zA-Z0-9_]{,30}$

# Regular expression which should only match correct list comprehension /
# generator expression variable names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$

# Regular expression which should only match correct class sttribute names
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,42}|(__.*__))$

# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,ex,Run,_

# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata

# List of builtins function names that should not be used, separated by a comma
bad-functions=apply,input


[DESIGN]

# Maximum number of arguments for function / method
max-args=10

# Maximum number of locals for function / method body
max-locals=20

# Maximum number of return / yield for function / method body
max-returns=6

# Maximum number of branch for function / method body
max-branchs=20

# Maximum number of statements in function / method body
max-statements=50

# Maximum number of parents for a class (see R0901).
max-parents=7

# Maximum number of attributes for a class (see R0902).
max-attributes=7

# Minimum number of public methods for a class (see R0903).
min-public-methods=1

# Maximum number of public methods for a class (see R0904).
max-public-methods=20


[CLASSES]


[FORMAT]

# Maximum number of characters on a single line.
max-line-length=120

# Maximum number of lines in a module
max-module-lines=1000

# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string='    '


[MISCELLANEOUS]

# List of note tags to take in consideration, separated by a comma.
notes=
0707010000000D000041FD0000000000000000000000015CDC5C8900000000000000000000000000000000000000000000001B00000000mgr-virtualization/scripts0707010000000E000081B40000000000000000000000015CDC5C890000025F000000000000000000000000000000000000002400000000mgr-virtualization/scripts/MakefilePKGDIR0 = /etc/rc.d/init.d
SYSCONF_DIR = /etc/sysconfig/rhn
CONF_DIR = /etc/sysconfig/rhn/virt
CONF_DIR_AUTO = /etc/sysconfig/rhn/virt/auto

SCRIPTS = rhn-virtualization-host
CONF = kvm-template.xml xen-template.xml image.cfg

all: 
	echo "Nothing to do"

clean:
	echo "No cleaning to do"

install:
	mkdir -p $(DESTDIR)/$(PKGDIR0)
	mkdir -p $(DESTDIR)/$(CONF_DIR)
	mkdir -p $(DESTDIR)/$(CONF_DIR_AUTO)
	mkdir -p $(DESTDIR)/$(SYSCONF_DIR)
	for p in $(SCRIPTS) ; do \
		install -m 755 $$p $(DESTDIR)/$(PKGDIR0)/$$p; \
	done
	for r in $(CONF) ; do \
		install -m 644 $$r $(DESTDIR)/$(SYSCONF_DIR)/$$r; \
	done
0707010000000F000081B40000000000000000000000015CDC5C8900000075000000000000000000000000000000000000002500000000mgr-virtualization/scripts/image.cfg[global]
IMAGE_BASE_PATH=/var/lib/libvirt/images/
IMAGE_CFG_TEMPLATE=/etc/sysconfig/rhn/kvm-template.xml
PRE_SCRIPT=
07070100000010000081B40000000000000000000000015CDC5C8900000477000000000000000000000000000000000000002C00000000mgr-virtualization/scripts/kvm-template.xml<domain type='kvm'>
  <name>%(name)s</name>
  <uuid>%(uuid)s</uuid>
  <memory>%(mem_kb)s</memory>
  <vcpu>%(vcpus)s</vcpu>
  <os>
    <type arch='%(arch)s' machine='pc-0.12'>hvm</type>
    <boot dev='hd'/>
  </os>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
  <devices>
    <emulator>/usr/bin/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='%(imageType)s'/>
      <source file='%(disk)s'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' unit='0'/>
    </disk>
    <controller type='ide' index='0'/>

    <!-- if you don't want a bridge, remove this interface -->
    <interface type='bridge'>
      <source bridge='%(virtBridge)s'/>
    </interface>

    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target port='0'/>
    </console>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='-1' autoport='yes' keymap='en-us'/>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
    </video>
  </devices>
</domain>
07070100000011000081B40000000000000000000000015CDC5C890000009B000000000000000000000000000000000000003600000000mgr-virtualization/scripts/mgr-virtualization.service[Unit]
Description=Check libvirtd for VMs and report it to Uyuni Server

[Service]
Type=oneshot
ExecStart=@PYTHON@ < @PYTHONPATH@/virtualization/poller.py
07070100000012000081B40000000000000000000000015CDC5C8900000097000000000000000000000000000000000000003400000000mgr-virtualization/scripts/mgr-virtualization.timer[Unit]
Description=Check libvirtd for VMs and report it to Uyuni Server

[Timer]
OnCalendar=*:*/2:00
Persistent=true

[Install]
WantedBy=timers.target
07070100000013000081FD0000000000000000000000015CDC5C89000008E7000000000000000000000000000000000000003300000000mgr-virtualization/scripts/rhn-virtualization-host#!/bin/sh
# chkconfig: 2345 99 99
# description: Starts up xen domains when the host boots.

. /etc/rc.d/init.d/functions

auto_dir="/etc/sysconfig/rhn/virt/auto"
script_path="@PYTHONPATH@/virtualization"
get_config_value="@PYTHON@ $script_path/get_config_value.py"
get_uuid="$get_config_value uuid"
get_name="$get_config_value name"
init_action="@PYTHON@ $script_path/init_action.py"
start_action="$init_action start"
stop_action="$init_action shutdown"

if [ -d $auto_dir ]; then
    list_of_files=$(ls $auto_dir)
else
    list_of_files=
fi

start() {
    RETVAL=0
 
   for NAME in $list_of_files; do
        dom_uuid=$(eval $get_uuid $auto_dir/$NAME)
        eval $start_action $dom_uuid > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            RETVAL=1
        fi
    done

    touch /var/lock/subsys/rhn-virtualization-host

    echo -n "Starting RHN Managed Xen Domains:"
    if [ $RETVAL -eq 0 ]; then echo_success; else echo_failure; fi
    echo

    return $RETVAL
}

stop() {
    RETVAL=0

    for NAME in $list_of_files; do
        dom_uuid=$(eval $get_uuid $auto_dir/$NAME)
        eval $stop_action $dom_uuid > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            RETVAL=1
        fi
    done

    rm -f /var/lock/subsys/rhn-virtualization-host

    echo -n "Stopping RHN Managed Xen Domains:"
    if [ $RETVAL -eq 0 ]; then echo_success; else echo_failure; fi
    echo

    return $RETVAL
}

status() {
    RETVAL=0

    found_guests=0

    for NAME in $list_of_files; do
        found_guests=1
        dom_name=$(eval $get_name $auto_dir/$NAME)
        dom_state=$(virsh domstate $dom_name 2> /dev/null)

        if [ $? -eq 0 ]; then
            echo "$dom_name: $dom_state"
        else
            echo "Error getting the status for $dom_name."
            RETVAL=1
        fi
    done

    if [ $found_guests -eq 0 ]; then
        echo "No guest configurations symlinked in $auto_dir."
    fi

    return $RETVAL
}


case $1 in
    "start")
        start
        ;;
    "stop")
        stop
        ;;
    "restart")
        stop
        start
        ;;
    "reload")
        stop
        start
        ;;
    "status")
        status
        ;;
    *)
        echo "Usage: service rhn-virtualization [start|stop|restart|reload|status]"
        ;;
esac
07070100000014000081B40000000000000000000000015CDC5C8900000045000000000000000000000000000000000000003300000000mgr-virtualization/scripts/rhn-virtualization.cron0-59/2 * * * * root @PYTHON@ < @PYTHONPATH@/virtualization/poller.py
07070100000015000081B40000000000000000000000015CDC5C89000003A8000000000000000000000000000000000000002C00000000mgr-virtualization/scripts/xen-template.xml<domain type='xen'>
  <name>%(name)s</name>
  <uuid>%(uuid)s</uuid>
  <memory>%(mem_kb)s</memory>
  <vcpu>%(vcpus)s</vcpu>
  <bootloader>/usr/bin/pygrub</bootloader>
  <os>
    <type arch='%(arch)s' machine='xenpv'>linux</type>
  </os>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
  <devices>
    <disk type='file' device='disk'>
      <driver name='tap' type='aio'/>
      <source file='%(disk)s'/>
      <target dev='xvda' bus='xen'/>
      <address type='drive' controller='0' bus='0' unit='0'/>
    </disk>

    <!-- if you don't want a bridge, remove this interface -->
    <interface type='bridge'>
      <source bridge='%(virtBridge)s'/>
    </interface>

    <console type='pty'>
      <target port='0'/>
    </console>
    <input type='mouse' bus='xen'/>
    <graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0'/>
  </devices>
</domain>
07070100000016000041FD0000000000000000000000015CDC5C8900000000000000000000000000000000000000000000002200000000mgr-virtualization/virtualization07070100000017000081B40000000000000000000000015CDC5C8900000106000000000000000000000000000000000000002B00000000mgr-virtualization/virtualization/MakefilePYTHON=python
PYFILES = $(wildcard *.py)
PKGDIR = $(PYTHONPATH)/virtualization

all: 
	echo "Nothing to do"

clean:
	rm -f *.pyc *.pyo *~

install:
	mkdir -p $(DESTDIR)/$(PKGDIR)
	for p in $(PYFILES) ; do \
		install -m 644 $$p $(DESTDIR)/$(PKGDIR)/$$p; \
	done
07070100000018000081B40000000000000000000000015CDC5C8900000282000000000000000000000000000000000000002E00000000mgr-virtualization/virtualization/__init__.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

#
# Virtualization module
#
07070100000019000081B40000000000000000000000015CDC5C8900001461000000000000000000000000000000000000003B00000000mgr-virtualization/virtualization/batching_log_notifier.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

#
# This module provides the BatchingLogNotifier class, which has the ability to
# queue up log messages and periodically forward them in a batch to the server.
#

from threading import Thread, Event, Lock

###############################################################################
# Constants
###############################################################################

POLL_INTERVAL = 5  # Seconds

###############################################################################
# BatchingLogNotifier Class
###############################################################################

class BatchingLogNotifier:

    def __init__(self, batch_notify_handler):
        self.__log_message_queue = LockableLogMessageQueue()
        self.__notify_thread = NotifyThread(self.__log_message_queue,
                                            batch_notify_handler)

    def add_log_message(self, log_message):
        self.__log_message_queue.lock()
        try:
            self.__log_message_queue.add(log_message)
        finally:
            self.__log_message_queue.unlock()

    def start(self):
        self.__notify_thread.start()

    def stop(self):
        self.__notify_thread.stop()
        if self.__notify_thread.isAlive():
            self.__notify_thread.join()

###############################################################################
# LogQueue Class
###############################################################################

class LockableLogMessageQueue:

    def __init__(self):
        self.__log_message_queue = []
        self.__queue_lock = Lock()

    def lock(self):
        self.__queue_lock.acquire()

    def unlock(self):
        self.__queue_lock.release()

    def add(self, log_message):
        self.__log_message_queue.append(log_message)

    def pop(self):
        first_item = self.__log_message_queue[0]
        self.__log_message_queue.remove(first_item)
        return first_item

    def is_empty(self):
        return len(self.__log_message_queue) == 0

###############################################################################
# BatchNotifyHandler Class
###############################################################################

class BatchNotifyHandler:
    """
    This class provides a generic mechanism for processing logging callbacks.
    This is just a stub class, which should be inherited by anyone who wants
    to respond to logging events.
    """

    def __init__(self):
        pass

    def batch_began():
        pass

    def log_message_discovered(log_message):
        pass

    def batch_ended():
        pass

###############################################################################
# NotifyThread Class
###############################################################################

class NotifyThread(Thread):

    ###########################################################################
    # Public Interface
    ###########################################################################

    def __init__(self, log_message_queue, batch_notify_handler):
        Thread.__init__(self)
        self.__log_message_queue = log_message_queue
        self.__batch_notify_handler = batch_notify_handler
        self.__stop_event = Event()

    def run(self):
        # First, clear the stop event in case it was already set.
        self.__stop_event.clear()

        # Enter the main loop, flushing the queue every interval.
        while not self.__stop_event.isSet():
            self.__flush_log_message_queue()
            self.__stop_event.wait(POLL_INTERVAL)

        # We've been signaled to stop, but flush the queue one more time before
        # exiting.
        self.__flush_log_message_queue()

    def stop(self):
        self.__stop_event.set()

    ###########################################################################
    # Helper Methods
    ###########################################################################

    def __flush_log_message_queue(self):
        self.__log_message_queue.lock()
        try:
            if not self.__log_message_queue.is_empty():
                self.__batch_notify_handler.batch_began()
                while not self.__log_message_queue.is_empty():
                    log_message = self.__log_message_queue.pop()
                    self.__batch_notify_handler.log_message_discovered(
                        log_message)
                self.__batch_notify_handler.batch_ended()
        finally:
            self.__log_message_queue.unlock()

if __name__ == "__main__":
    notifier = BatchingLogNotifier()
    notifier.start()

0707010000001A000081FD0000000000000000000000015CDC5C890000097A000000000000000000000000000000000000002F00000000mgr-virtualization/virtualization/constants.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

###############################################################################
# Constants
###############################################################################

class StateType:
    NOSTATE     = 'nostate'
    RUNNING     = 'running'
    BLOCKED     = 'blocked'
    PAUSED      = 'paused'
    SHUTDOWN    = 'shutdown'
    SHUTOFF     = 'shutoff'
    CRASHED     = 'crashed'

class VirtualizationType:
    PARA  = 'para_virtualized'
    FULLY = 'fully_virtualized'

class IdentityType:
    HOST        = 'host'
    GUEST       = 'guest'

class PropertyType:
    NAME        = 'name'
    UUID        = 'uuid'
    TYPE        = 'virt_type'
    MEMORY      = 'memory_size'
    VCPUS       = 'vcpus'
    STATE       = 'state'
    IDENTITY    = 'identity'
    ID          = 'id'
    MESSAGE     = 'message'

##
# This structure maps the libvirt state enumeration to labels that
# Red Hat Satellite understands.
# Reasons we don't care about differences between NOSTATE, RUNNING and BLOCKED:
# 1. technically, the domain is still "running"
# 2. RHN Classic / Red Hat Satellite / Spacewalk are not able to
# display 'blocked' & 'nostate'
#    as valid states
# 3. to avoid 'Abuse of Service' messages: bugs #230106 and #546676

VIRT_STATE_NAME_MAP = ( StateType.RUNNING,  # VIR_DOMAIN_NOSTATE
                        StateType.RUNNING,  # VIR_DOMAIN_RUNNING
                        StateType.RUNNING,  # VIR_DOMAIN_BLOCKED
                        StateType.PAUSED,   # VIR_DOMAIN_PAUSED
                        StateType.SHUTDOWN, # VIR_DOMAIN_SHUTDOWN
                        StateType.SHUTOFF,  # VIR_DOMAIN_SHUTOFF
                        StateType.CRASHED)  # VIR_DOMAIN_CRASHED

VIRT_VDSM_STATUS_MAP = {
  'Up'  : 'running',
  'Down': 'shutdown',
  'Paused' : 'paused',
  'Powering down' : 'shutoff',
}
0707010000001B000081B40000000000000000000000015CDC5C89000032AC000000000000000000000000000000000000003300000000mgr-virtualization/virtualization/domain_config.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from xml.dom.minidom import parse
import os
import sys

from spacewalk.common.usix import raise_with_tb


###############################################################################
# Exceptions
###############################################################################

class DomainConfigError(Exception): pass

###############################################################################
# Classes
###############################################################################

class DataType:
    ATTRIBUTE = "attribute"
    VALUE     = "value"

class DomainConfigItem:
    def __init__(self, path, data_type):
        self.path      = path
        self.data_type = data_type

class DomainConfig:

    ###########################################################################
    # Constants
    ###########################################################################

    NAME            = DomainConfigItem("domain/name",       DataType.VALUE)
    UUID            = DomainConfigItem("domain/uuid",       DataType.VALUE)
    BOOTLOADER      = DomainConfigItem("domain/bootloader", DataType.VALUE)
    MEMORY          = DomainConfigItem("domain/memory",     DataType.VALUE)
    VCPU            = DomainConfigItem("domain/vcpu",       DataType.VALUE)
    OS              = DomainConfigItem("domain/os",         DataType.VALUE)
    OS_TYPE         = DomainConfigItem("domain/os/type",    DataType.VALUE)
    ROOT_DEVICE     = DomainConfigItem("domain/os/root",    DataType.VALUE)
    COMMAND_LINE    = DomainConfigItem("domain/os/cmdline", DataType.VALUE)
    KERNEL_PATH     = DomainConfigItem("domain/os/kernel",  DataType.VALUE)
    RAMDISK_PATH    = DomainConfigItem("domain/os/initrd",  DataType.VALUE)
    DISK_IMAGE_PATH = DomainConfigItem("domain/devices/disk/source/file",
                                       DataType.ATTRIBUTE)
    DOMAIN_ID       = DomainConfigItem("domain/id",         DataType.ATTRIBUTE)

    ###########################################################################
    # Public Interface
    ###########################################################################

    def __init__(self, config_path, uuid):
        # Prepare the file name and parse the XML file.
        if uuid.find(".xml") > 1 and os.path.exists(uuid):
            self.__file_name = uuid
        else:
            self.__file_name = "%s/%s.xml" % (config_path, uuid)

        self.__dom_tree = None
        try:
            self.__dom_tree = parse(self.__file_name).documentElement
        except Exception:
            e = sys.exc_info()[1]
            raise_with_tb(DomainConfigError("Error reading config file '%s': %s" % (self.__file_name, str(e))),
                          sys.exc_info()[2])


    def save(self):
        """Saves any changes made to this configuration."""
        file = None
        try:
            try:
                file = open(self.__file_name, "w")
                file.write(self.__dom_tree.toxml())
            except IOError:
                ioe = sys.exc_info()[1]
                raise_with_tb(DomainConfigError("Error saving config file '%s': %s" % (self.__file_name, str(ioe))),
                              sys.exc_info()[2])

        finally:
            if file is not None:
                file.close()

    def getFileName(self):
        """
        Returns the path to the configuration file represented by this
        object.
        """
        return self.__file_name

    def toXML(self):
        """Returns the XML representation of this configuration."""
        return self.__dom_tree.toxml()

    def getConfigItem(self, config_item):
        if config_item.data_type == DataType.ATTRIBUTE:
            return self.__getElementAttribute(
                self.__dom_tree,
                *config_item.path.split("/"))
        elif config_item.data_type == DataType.VALUE:
            return self.__getElementValue(
                self.__dom_tree,
                *config_item.path.split("/"))

        raise DomainConfigError("Unknown config item data type '%s'" % \
                                    str(config_item.data_type))

    def hasConfigItem(self, config_item):
        try:
            self.getConfigItem(config_item)
        except DomainConfigError:
            return 0
        return 1

    def removeConfigItem(self, config_item):
        if config_item.data_type == DataType.ATTRIBUTE:
            return self.__removeElementAttribute(
                self.__dom_tree,
                *config_item.path.split("/"))
        elif config_item.data_type == DataType.VALUE:
            return self.__removeElementValue(
                self.__dom_tree,
                *config_item.path.split("/"))

        raise DomainConfigError("Unknown config item data type '%s'" % \
                                    str(config_item.data_type))

    def setConfigItem(self, config_item, value):
        """
        Sets the value of an item in the tree.  If the item does not yet exist,
        it will be created.
        """
        if config_item.data_type == DataType.ATTRIBUTE:
            return self.__setElementAttribute(
                self.__dom_tree,
                value,
                *config_item.path.split("/"))
        elif config_item.data_type == DataType.VALUE:
            return self.__setElementValue(
                self.__dom_tree,
                value,
                *config_item.path.split("/"))

        raise DomainConfigError("Unknown config item data type '%s'" % \
                                    str(config_item.data_type))

    def isInstallerConfig(self):
        """
        Returns true if this configuration indicates that the domain was
        started in a method that would put it into the installer.
        """
        result = 0
        if self.hasConfigItem(DomainConfig.COMMAND_LINE):
            # Convert the command line to a dict for easy parsability.
            command_line = self.getConfigItem(DomainConfig.COMMAND_LINE)
            command_line_parts = command_line.strip().split(" ")
            command_line_dict = {}
            for part in command_line_parts:
                command_line_args = part.split("=")
                key = command_line_args[0]
                command_line_dict[key] = None
                if len(command_line_args) >= 2:
                    command_line_dict[key] = '='.join(command_line_args[1:])

            # Look for the "method" argument.  This is a good indication that
            # the instance is in the installer.
            if "method" in command_line_dict or "ks" in command_line_dict or "autoyast" in command_line_dict:
                result = 1

        return result

    ###########################################################################
    # Helpers
    ###########################################################################

    def __getElementValue(self, start_tree, *tag_path):
        found = self.__extractElement(start_tree, *tag_path)

        if len(found.childNodes) == 0:
            raise DomainConfigError("Unable to find config value: " + "/".join(tag_path))

        return found.childNodes[0].data

    def __getElementAttribute(self, start_tree, *tag_path):
        """
        Returns the value of the requested XML attribute.  The attribute name
        is the last value in the tag_path.
        """
        attribute_name = tag_path[-1]
        found = self.__extractElement(start_tree, *tag_path[:-1])

        # Dig out the value of the requested attribute.
        if not found.hasAttribute(attribute_name):
            raise DomainConfigError("Unable to find config attribute: " + "/".join(tag_path))

        return found.getAttribute(attribute_name)

    def __removeElementValue(self, start_tree, *tag_path):
        found = self.__extractElement(start_tree, *tag_path)

        if len(found.childNodes) == 0:
            raise DomainConfigError("Unable to find config value: " + "/".join(tag_path))

        found.parentNode.removeChild(found)

    def __removeElementAttribute(self, start_tree, *tag_path):
        attribute_name = tag_path[-1]
        found = self.__extractElement(start_tree, *tag_path[:-1])

        if not found.hasAttribute(attribute_name):
            raise DomainConfigError("Unable to find config attribute: " + "/".join(tag_path))

        found.removeAttribute(attribute_name)

    def __setElementValue(self, start_tree, value, *tag_path):
        try:
            found = self.__extractElement(start_tree, *tag_path)
        except DomainConfigError:
            # If an exception was thrown, the element did not exist.  We'll
            # add it.
            found = self.__makeElement(start_tree, *tag_path)

        if len(found.childNodes) == 0:
            document = self.__dom_tree.parentNode
            element_text = document.createTextNode('')
            found.appendChild(element_text)

        try:
            found.childNodes[0].data = str(value)
        except IndexError:
            raise_with_tb(DomainConfigError("Error writing %s tag in '%s'." % ('/'.join(tag_path), self.__file_name)),
                          sys.exc_info()[2])

    def __setElementAttribute(self, start_tree, value, *tag_path):
        attribute_name = tag_path[-1]
        found = self.__extractElement(start_tree, *tag_path[:-1])
        found.setAttribute(attribute_name, str(value))

    def __makeElement(self, start_tree, *tag_path):
        # If there are no more tags left in the path, there's nothing more to
        # add.
        if len(tag_path) == 0:
            return start_tree

        # Look for the first part of the tag.
        tag = tag_path[0]
        try:
            element = self.__extractElement(start_tree, tag)
        except DomainConfigError:
            # No matching tag found.  Create one.
            document = self.__dom_tree.parentNode
            element = document.createElement(tag)
            start_tree.appendChild(element)

        tag_path = tag_path[1:]
        return self.__makeElement(element, *tag_path)

    def __extractElement(self, start_tree, *tag_path):
        # If there are no more tags left in the path, we're done.
        if len(tag_path) == 0:
            return start_tree

        # Extract the first matching child from this tree.
        tag = tag_path[0]

        if start_tree == self.__dom_tree:
            # If this is the root node, ensure that the first part of the path
            # matches.  This is a special case because the getElementsByTagName
            # only applies to elements below the root node.
            if start_tree.nodeName != tag:
                # First part of the tag path didn't match.  Raise exception.
               raise DomainConfigError("Could not locate tag <%s>." % tag)
            else:
               # First part matched; adjust the tag pointer, if there's any
               # thing left.
               tag_path = tag_path[1:]
               if len(tag_path) == 0:
                   return start_tree
               else:
                   tag = tag_path[0]

        node_list = start_tree.getElementsByTagName(tag)

        if node_list is not None and len(node_list) > 0:
            tag_node = node_list[0]
            return self.__extractElement(tag_node, *tag_path[1:])

        # If we got here, we couldn't find the tag in question.  Raise an
        # exception
        raise DomainConfigError("Could not locate tag " + str(tag))

###############################################################################
# Test Method
###############################################################################

if __name__ == "__main__":
    import sys
    uuid = sys.argv[1]
    f = DomainConfig("/etc/sysconfig/rhn/virt", uuid)
    print("name=", f.getConfigItem(DomainConfig.NAME))
    print("memory=", f.getConfigItem(DomainConfig.MEMORY))
    print("domain_id=", f.getConfigItem(DomainConfig.DOMAIN_ID))
    f.setConfigItem(DomainConfig.DOMAIN_ID, 22322)
    f.setConfigItem(DomainConfigItem("domain/argh", DataType.ATTRIBUTE), 22322)
    f.setConfigItem(DomainConfigItem("domain/pete", DataType.VALUE), "hello")
    f.setConfigItem(DomainConfigItem("domain/vcpu", DataType.VALUE), "22")
    f.setConfigItem(DomainConfig.BOOTLOADER, "/usr/pete/bin/pygrub")
    f.removeConfigItem(DomainConfigItem("domain/os", DataType.VALUE))
    print(f.toXML())

0707010000001C000081FD0000000000000000000000015CDC5C89000012A5000000000000000000000000000000000000003400000000mgr-virtualization/virtualization/domain_control.py#
# Copyright (c) 2006--2012 Red Hat, Inc.  Distributed under GPL.
#
# Author: Peter Vetere <pvetere@redhat.com>
#
# This module handles virtual domain control requests.
#

import sys

from virtualization import poller, start_domain

from virtualization.errors import VirtualizationException
from virtualization.util   import hyphenize_uuid

try:
    import libvirt
except:
    # The libvirt library is not installed.  That's ok, we can't assume it will
    # be on every system.
    libvirt = None

from spacewalk.common.usix import raise_with_tb


###############################################################################
# Public Interface
###############################################################################

def shutdown(uuid):
    """
    Shuts down the domain with the given UUID.  If the instance is crashed, it
    is destroyed.  If the instance is paused, it is unpaused and shutdown
    cleanly.
    """
    state = poller.poll_state(uuid)
    if state.is_crashed():
        destroy(uuid)
    elif state.is_paused():
        resume(uuid)
        shutdown(uuid)
    else:
        _call_domain_control_routine(uuid, "shutdown")

def start(uuid):
    """
    Starts up the domain with the given UUID.
    """
    state = poller.poll_state(uuid)
    if state.is_crashed():
        destroy(uuid)
        start(uuid)
    elif state.is_paused():
        resume(uuid)
    else:
        start_domain.start_domain(uuid)

def suspend(uuid):
    """
    Suspends the domain with the given UUID.
    """
    _call_domain_control_routine(uuid, "suspend")

def resume(uuid):
    """
    Resumes the domain with the given UUID.
    """
    _call_domain_control_routine(uuid, "resume")

def reboot(uuid):
    """
    Reboots the domain with the given UUID.  If the system is paused, we
    unpause and reboot it.  If the system is stopped, we start it.  If the
    system is crashed, we destroy and restart it.
    """
    state = poller.poll_state(uuid)
    if state.is_stopped():
        start(uuid)
    elif state.is_paused():
        resume(uuid)
        reboot(uuid)
    elif state.is_crashed():
        destroy(uuid)
        start(uuid)
    else:
        _call_domain_control_routine(uuid, "reboot", 0)

def destroy(uuid):
    """
    Destroys the domain with the given UUID.
    """
    _call_domain_control_routine(uuid, "destroy")

def setMemory(uuid, memory):
    """
    Sets the max memory usage for the domain with the given UUID.
    """
    _call_domain_control_routine(uuid, "setMemory", memory)

def setVCPUs(uuid, vcpus):
    """
    Sets the number of vcpus for the domain with the given UUID.
    """
    _call_domain_control_routine(uuid, "setVcpus", vcpus)


###############################################################################
# Helper Routines
###############################################################################

def _get_domain(uuid):
    """
    Lookup the domain by its UUID.  If not found, raise an exception.
    """
    conn = libvirt.open(None)
    domain = None
    hyphenized_uuid = hyphenize_uuid(uuid)
    try:
        domain = conn.lookupByUUIDString(hyphenized_uuid)
    except libvirt.libvirtError:
        lve = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("Domain UUID '%s' not found: %s" % (hyphenized_uuid, str(lve))),
                      sys.exc_info()[2])
    return (conn, domain)

def _call_domain_control_routine(uuid, routine_name, *args):
    """
    Call a function in a domain, optionally with a set of arguments.
    """

    # If libvirt is not available, this is a no-op.
    if not libvirt: return

    # Lookup the domain by its UUID.
    (conn, domain) = _get_domain(uuid)

    # Get a reference to the domain's control routine.
    ctrl_func = None
    try:
        ctrl_func = getattr(domain, routine_name)
    except AttributeError:
        raise_with_tb(VirtualizationException("Unknown function: %s" % routine_name), sys.exc_info()[2])

    result = 0
    try:
        if sys.version_info[0] == 3:
            result = ctrl_func(*args)
        else:
            result = apply(ctrl_func, args)
    except TypeError:
        te = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("Invalid arguments (%s) to %s: %s" % (str(args), routine_name, str(te))),
                      sys.exc_info()[2])
    except libvirt.libvirtError:
        le = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("LibVirt Error %s: %s" % (routine_name, str(le))), sys.exc_info()[2])

    # Handle the return code.  Anything non-zero is an error.
    if result != 0:
        raise_with_tb(VirtualizationException("Could not perform function '%s' on domain %s.  Error: %s" %
                      (routine_name, uuid, str(result))), sys.exc_info()[2])

0707010000001D000081B40000000000000000000000015CDC5C8900002186000000000000000000000000000000000000003600000000mgr-virtualization/virtualization/domain_directory.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import binascii
import os
import sys

try:
    import libvirt
except ImportError:
    # There might not be a libvirt; we won't die here so that other modules
    # who import us can exit gracefully.
    libvirt = None

from rhn.i18n import sstr

from virtualization.domain_config import DomainConfig
from virtualization.errors        import VirtualizationException
from virtualization.util          import dehyphenize_uuid, \
                                         hyphenize_uuid,   \
                                         is_host_uuid

###############################################################################
# Constants
###############################################################################

CONFIG_DIR = '/etc/sysconfig/rhn/virt'
STANDARD_CONFIG_TEMPLATE = """
    <domain type='xen'>
        <name>%(name)s</name>
        <bootloader>/usr/bin/pygrub</bootloader>
        <memory>%(mem_kb)s</memory>
        <vcpu>%(vcpus)s</vcpu>
        <uuid>%(uuid)s</uuid>
        <on_reboot>restart</on_reboot>
        <on_poweroff>destroy</on_poweroff>
        <on_crash>preserve</on_crash>
        <devices>
            <disk type='file'>
                <source file='%(disk)s'/>
                <target dev='xvda'/>
            </disk>
            <interface type='bridge'>
                <source bridge='xenbr0'/>
                <mac address='%(mac)s'/>
                <script path='/etc/xen/scripts/vif-bridge'/>
            </interface>
        </devices>
</domain>
"""

###############################################################################
# Classes
###############################################################################

class DomainDirectory:

    def __init__(self):
        self.__path = CONFIG_DIR
        self.conn = libvirt.openReadOnly(None)
        if not self.conn:
            raise VirtualizationException("Failed to open connection to hypervisor.")

    def get_config_path(self, uuid):
        cfg_filename = "%s.xml" % uuid
        cfg_pathname = os.path.join(self.__path, cfg_filename)
        return cfg_pathname

    def is_known_config(self, uuid):
        """
        Returns true if a config for the given uuid is saved in the directory.
        """
        path = self.get_config_path(uuid)
        return os.path.exists(path)

    def load_config(self, uuid):
        """
        This function loads a domain's configuration by its UUID.  A
        DomainConfig object is returned.
        """
        return DomainConfig(self.__path, uuid)

    def create_standard_config(self, uuid, name, mem_kb, vcpus, disk, mac):
        # First, populate the XML with the appropriate values.
        boot_params = { 'name'       : name,
                        'mem_kb'     : mem_kb,
                        'vcpus'      : vcpus,
                        'uuid'       : hyphenize_uuid(uuid),
                        'disk'       : disk,
                        'mac'        : mac }

        xml = STANDARD_CONFIG_TEMPLATE % boot_params

        self.__write_xml_file(uuid, xml)

    def save_unknown_domain_configs(self, domain_uuids):
        """
        This function saves the configuration for any domains whose UUIDs are
        passed in the domain_uuids list.  If the UUID is already known, it is
        skipped.
        """

        for uuid in domain_uuids:

            uuid = sstr(uuid)
            # If we already have a config for this uuid, skip it.  Also, don't
            # try to figure out a config for a host UUID.
            if not is_host_uuid(uuid) and not self.is_known_config(uuid):

                # The UUID is a formatted string.  Turn it back into a number,
                # since that's what libvirt wants.
                dehyphenized_uuid = dehyphenize_uuid(uuid)
                uuid_as_num = binascii.unhexlify(dehyphenized_uuid)

                # Lookup the domain by its uuid.
                try:
                    domain = self.conn.lookupByUUID(uuid_as_num)
                except libvirt.libvirtError:
                    lve = sys.exc_info()[1]
                    raise VirtualizationException("Failed to obtain handle to domain %s: %s" % (uuid, repr(lve)))

                # Now grab the XML description of the configuration.
                xml = domain.XMLDesc(0)

                # Write the xml out to a file so that we can load it into our
                # abstract DomainConfig object and manipulate it easily.
                cfg_file_path = self.__write_xml_file(uuid, xml)
                new_config = DomainConfig(self.__path, uuid)

                # Don't record the config this time if the domain is
                # installing; we don't want to restart the domain later and
                # make it re-install itself.
                if not new_config.isInstallerConfig():

                    # Now we'll reformat the configuration object so that it's
                    # valid the next time this domain runs..
                    self.__fixup_config_for_restart(new_config)

                    # The config is now prepared.  Save it and move on to the
                    # next uuid.
                    new_config.save()

                else:
                    # Remove the config file we just wrote.
                    os.unlink(cfg_file_path)

    def __fixup_config_for_restart(self, config):
        """
        This function edits the given configuration so that it can be used in
        subsequent calls to libvirt's createLinux call.  Specifically, the
        following modifications are made:

            - Remove the "id" attribute from the <domain> tag.  The "id" is
              whatever the hypervisor wants to assign to it, so we should not
              try to assign it explicitly.

            - Determine whether the config contains an <os> section.
                - If it does, check whether the kernel and the initrd files
                  it refers to actually exist on disk.
                    - If so, do nothing.
                    - If not, remove the entire <os> section and insert a
                      <bootloader> section if one does not yet exist.  These
                      files might not exist if the instance was started by xm
                      using a bootloader such as pygrub, which makes temporary
                      copies of the kernel & initrd and then removes them after
                      starting the instance.
                - If it does not, ensure there is a <bootloader> section or
                  add one if needed.
        """
        # Remove the domain ID from the XML.  This is a runtime value that
        # should not be assigned statically.
        if config.hasConfigItem(DomainConfig.DOMAIN_ID):
            config.removeConfigItem(DomainConfig.DOMAIN_ID)

        if self.conn.getType() == 'QEMU':
            # Dont worry about bootloader if its kvm
            return

        boot_images_exist = 0

        if config.hasConfigItem(DomainConfig.KERNEL_PATH) and \
           config.hasConfigItem(DomainConfig.RAMDISK_PATH):

            kernel_path = config.getConfigItem(DomainConfig.KERNEL_PATH)
            ramdisk_path = config.getConfigItem(DomainConfig.RAMDISK_PATH)

            if os.path.exists(kernel_path) and os.path.exists(ramdisk_path):
                boot_images_exist = 1

        # If we've determined that the referenced boot images do not exist,
        # remove the OS section and insert a bootloader piece.
        if not boot_images_exist:
            if config.hasConfigItem(DomainConfig.OS):
                config.removeConfigItem(DomainConfig.OS)

            if not config.hasConfigItem(DomainConfig.BOOTLOADER):
                config.setConfigItem(DomainConfig.BOOTLOADER, "/usr/bin/pygrub")


    def __write_xml_file(self, uuid, xml):
        cfg_pathname = self.get_config_path(uuid)
        cfg_file = open(cfg_pathname, "w")
        cfg_file.write(xml.strip())
        cfg_file.close()

        return cfg_pathname
0707010000001E000081B40000000000000000000000015CDC5C89000002EB000000000000000000000000000000000000002C00000000mgr-virtualization/virtualization/errors.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

class VirtualizationException(Exception): pass

class UUIDError(VirtualizationException): pass

class NotRegistered(Exception): pass
0707010000001F000081B40000000000000000000000015CDC5C890000060B000000000000000000000000000000000000003600000000mgr-virtualization/virtualization/get_config_value.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
from virtualization.domain_config import DomainConfig

fieldname = sys.argv[1]
filename = sys.argv[2]
dc = DomainConfig('/usr/share/rhn/virt/auto', filename)

fields = {
            'name'          :   DomainConfig.NAME,
            'uuid'          :   DomainConfig.UUID,
            'memory'        :   DomainConfig.MEMORY,
            'vcpu'          :   DomainConfig.VCPU,
            'root_device'   :   DomainConfig.ROOT_DEVICE,
            'cmdline'       :   DomainConfig.COMMAND_LINE,
            'os_kernel'     :   DomainConfig.KERNEL_PATH,
            'os_initrd'     :   DomainConfig.RAMDISK_PATH,
            'disk_source'   :   DomainConfig.DISK_IMAGE_PATH
         }

if fieldname not in fields:
    sys.stdout.write("Unknown configuration element %s \n" % fieldname)
    sys.exit(1)

result = dc.getConfigItem(fields[fieldname])
if fieldname == "uuid":
    result = result.replace("-", "")

print(result)

07070100000020000081B40000000000000000000000015CDC5C8900000506000000000000000000000000000000000000003100000000mgr-virtualization/virtualization/init_action.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
from virtualization import support

actions =   {
                'shutdown'  :   support.shutdown,
                'start'     :   support.start,
                'suspend'   :   support.suspend,
                'resume'    :   support.resume,
                'reboot'    :   support.reboot,
                'destroy'   :   support.destroy,
            }

action_type = sys.argv[1]
uuid = sys.argv[2]

if not action_type in list(actions.keys()):
    sys.stderr.write("Unknown action: %s \n" % action_type)
    sys.exit(1)

try:
    actions[action_type](uuid)
except Exception:
    e = sys.exc_info()[1]
    sys.stderr.write(str(e))
    sys.exit(1)

sys.exit(0)
07070100000021000081B40000000000000000000000015CDC5C8900000A26000000000000000000000000000000000000003200000000mgr-virtualization/virtualization/notification.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

#
# This module defines notification-related functions and constants, for use
# with the client-side virtualization code.
#

import sys

import time

from up2date_client import up2dateAuth
from up2date_client import up2dateErrors
from up2date_client import rhnserver
from up2date_client import up2dateLog
from virtualization.errors import NotRegistered

log = up2dateLog.initLog()

###############################################################################
# Constants
###############################################################################

class EventType:
    EXISTS      = 'exists'
    REMOVED     = 'removed'
    CRAWL_BEGAN = 'crawl_began'
    CRAWL_ENDED = 'crawl_ended'

class TargetType:
    SYSTEM      = 'system'
    DOMAIN      = 'domain'
    LOG_MSG     = 'log_message'

###############################################################################
# Plan Class
###############################################################################

class Plan:

    def __init__(self):
        self.__items = []

    def add(self, event, target = None, properties = {}):
        """
        Creates a new plan item and adds it to the list.
        """
        self.__items.append(self.__make_item(event, target, properties))

    def execute(self):
        """
        Sends all items in the plan to the satellite.
        """
        systemid = up2dateAuth.getSystemId()

        if systemid is None:
            raise NotRegistered("System ID not found.")

        server = rhnserver.RhnServer()

        try:
            server.registration.virt_notify(systemid, self.__items)
        except up2dateErrors.CommunicationError:
            e = sys.exc_info()[1]
            log.trace_me()
            log.log_me(e)


    def __make_item(self, event, target, properties):
        """
        Creates a new plan item.
        """

        # Get the current time.
        current_time = int(time.time())
        return ( current_time, event, target, properties )

07070100000022000081B40000000000000000000000015CDC5C8900003167000000000000000000000000000000000000002C00000000mgr-virtualization/virtualization/poller.py#
# Copyright (c) 2008--2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import os
import subprocess
import sys

import binascii
import traceback
import gettext
t = gettext.translation('rhn-virtualization', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

from up2date_client import rhncli

try:
    import libvirt
except ImportError:
    # There might not be a libvirt.
    libvirt = None

from optparse import OptionParser

from virtualization.state              import State
from virtualization.errors             import VirtualizationException
from virtualization.constants          import PropertyType,        \
                                              VirtualizationType,  \
                                              IdentityType,        \
                                              VIRT_STATE_NAME_MAP, \
                                              VIRT_VDSM_STATUS_MAP
from virtualization.notification       import Plan,                \
                                              EventType,           \
                                              TargetType
from virtualization.util               import hyphenize_uuid,      \
                                              is_fully_virt
from virtualization.poller_state_cache import PollerStateCache

from virtualization.domain_directory   import DomainDirectory

from spacewalk.common.usix import raise_with_tb
###############################################################################
# Globals
###############################################################################

options = None

###############################################################################
# Public Interface
###############################################################################

def poll_hypervisor():
    """
    This function polls the hypervisor for information about the currently
    running set of domains.  It returns a dictionary object that looks like the
    following:

    { uuid : { 'name'        : '...',
               'uuid'        : '...',
               'virt_type'   : '...',
               'memory_size' : '...',
               'vcpus'       : '...',
               'state'       : '...' }, ... }
    """
    if not libvirt:
        return {}

    try:
        conn = libvirt.openReadOnly(None)
    except libvirt.libvirtError:
        # virConnectOpen() failed
        sys.stderr.write(rhncli.utf8_encode(_("Warning: Could not retrieve virtualization information!\n\t" +
                                              "libvirtd service needs to be running.\n")))
        conn = None

    if not conn:
        # No connection to hypervisor made
        return {}

    domainIDs = conn.listDomainsID()

    if not domainIDs:
        domainIDs = []
    if len(domainIDs) == 0:
        domainIDs.extend(conn.listDefinedDomains())

    state = {}

    for domainID in domainIDs:
        if type(domainID) == int:
            try:
                domain = conn.lookupByID(domainID)
            except libvirt.libvirtError:
                lve = sys.exc_info()[1]
                raise_with_tb(VirtualizationException("Failed to obtain handle to domain %d: %s" % (domainID, repr(lve)),
                                                      sys.exc_info()[2]))
        else:
            try:
                domain = conn.lookupByName(domainID)
            except libvirt.libvirtError:
                lve = sys.exc_info()[1]
                raise_with_tb(VirtualizationException("Failed to obtain handle to domain %d: %s" % (domainID, repr(lve)),
                                                      sys.exc_info()[2]))

        uuid = binascii.hexlify(domain.UUID())
        # SEE: http://libvirt.org/html/libvirt-libvirt.html#virDomainInfo
        # for more info.
        domain_info = domain.info()

        # Set the virtualization type.  We can tell if the domain is fully virt
        # by checking the domain's OSType() attribute.
        virt_type = VirtualizationType.PARA
        if is_fully_virt(domain):
            virt_type = VirtualizationType.FULLY

        # we need to filter out the small per/minute KB changes
        # that occur inside a vm.  To do this we divide by 1024 to
        # drop our precision down to megabytes with an int then
        # back up to KB
        memory = int(domain_info[2] / 1024);
        memory = memory * 1024;
        properties = {
            PropertyType.NAME   : domain.name(),
            PropertyType.UUID   : uuid,
            PropertyType.TYPE   : virt_type,
            PropertyType.MEMORY : str(memory), # current memory
            PropertyType.VCPUS  : domain_info[3],
            PropertyType.STATE  : VIRT_STATE_NAME_MAP[domain_info[0]] }

        state[uuid] = properties

    if state: _log_debug("Polled state: %s" % repr(state))

    return state

def poll_through_vdsm(server):
    """
     This method polls all the virt guests running on a VDSM enabled Host.
     Libvirt is disabled by default on RHEV-M managed clients.
     * Imports the localvdsm client that talks to the localhost
       and fetches the list of vms and their info.
     * Extract the data and construct the state to pass it to the
       execution plan for guest polling.
     * The server should account for business rules similar to
       xen/kvm.
    """
    # Extract list of vm's. True returns full list
    try:
        domains = server.list(True)
    except:
        # Something went wrong in vdsm, exit
        return {}

    if not len(domains['vmList']):
        # No domains, exit.
        return {}

    state = {}
    for domain in domains['vmList']:
        #trim uuid
        uuid = domain['vmId'].lower().replace('-', '')
        # Map the VDSM status to libvirt for server compatibility
        status = 'nostate'
        if domain['status'] in VIRT_VDSM_STATUS_MAP:
            status = VIRT_VDSM_STATUS_MAP[domain['status']]
        # This is gonna be fully virt as its managed by VDSM
        virt_type = VirtualizationType.FULLY

        #Memory
        memory = int(domain['memSize']) * 1024

        # vcpus
        if 'smp' in domain:
            vcpus = domain['smp']
        else:
            vcpus = '1'

        properties = {
            PropertyType.NAME   : domain['vmName'],
            PropertyType.UUID   : uuid,
            PropertyType.TYPE   : virt_type,
            PropertyType.MEMORY : memory, # current memory
            PropertyType.VCPUS  : vcpus,
            PropertyType.STATE  : status}

        state[uuid] = properties

    if state: _log_debug("Polled state: %s" % repr(state))

    return state


def poll_state(uuid):
    """
    Polls just the state of the guest with the provided UUID.  This state is
    returned.
    """
    conn = libvirt.openReadOnly(None)
    if not conn:
        raise VirtualizationException("Failed to open connection to hypervisor.")

    # Attempt to connect to the domain.  Since there is technically no
    # "stopped" state, we will assume that if we cannot connect the domain is
    # not running.  Unfortunately, we can't really determine if the domain
    # actually exists.
    domain = None
    try:
        domain = conn.lookupByUUIDString(hyphenize_uuid(uuid))
    except libvirt.libvirtError:
        # Can't find domain.  Return stopped state.
        return State(None)

    # Now that we have the domain, lookup the state.
    domain_info = domain.info()
    return State(VIRT_STATE_NAME_MAP[domain_info[0]])

###############################################################################
# Helper Functions
###############################################################################

def _send_notifications(poller_state):
    """
    This function will send notifications based on vm state change to the
    server.  To reduce the possibility of spamming the server but still
    maintain an element of consistency, it will compare the previous poll state
    against the current poll state and only send notifications if something has
    changed.  In the event that the cache might have gotten into an
    inconsistent state, the cache will be removed after every 50 polls (this is
    about every 1.5 hours).  This will cause the full state to be re-uploaded
    and put things back in sync, if necessary.
    """
    # Now, if anything changed, send the appropriate notification for it.
    if poller_state.is_changed():
        added    = poller_state.get_added()
        removed  = poller_state.get_removed()
        modified = poller_state.get_modified()

        plan = Plan()

        # Declare virtualization host first
        plan.add(EventType.EXISTS,
                 TargetType.SYSTEM,
                 { PropertyType.IDENTITY : IdentityType.HOST,
                   PropertyType.UUID     : '0000000000000000' })

        for (uuid, data) in added.items():
            plan.add(EventType.EXISTS, TargetType.DOMAIN, data)

        for (uuid, data) in modified.items():
            plan.add(EventType.EXISTS, TargetType.DOMAIN, data)

        for (uuid, data) in removed.items():
            plan.add(EventType.REMOVED, TargetType.DOMAIN, data)

        plan.execute()

def _parse_options():
    usage = "Usage: %prog [options]"
    parser = OptionParser(usage)
    parser.set_defaults(debug=False)
    parser.add_option("-d", "--debug", action="store_true", dest="debug")
    global options
    (options, args) = parser.parse_args()

def _log_debug(msg, include_trace = 0):
    if options and options.debug:
        print("DEBUG: " + str(msg))
        if include_trace:
            e_info = sys.exc_info()
            traceback.print_exception(e_info[0], e_info[1], e_info[2])

###############################################################################
# Main Program
###############################################################################

if __name__ == "__main__":

    # First, handle the options.
    _parse_options()

    vdsm_enabled = False
    server = None
    try:
        from virtualization import localvdsm

        status = subprocess.call(['/sbin/service','vdsmd','status'],
                                 stdout=open(os.devnull, 'wb'),
                                 stderr=subprocess.STDOUT)
        if status == 0:
            server = localvdsm.connect()
            vdsm_enabled = True
    except ImportError:
        pass

    # Crawl each of the domains on this host and obtain the new state.
    if vdsm_enabled:
        domain_list = poll_through_vdsm(server)
    elif libvirt:
        # If libvirt is present but not running, this program is useless.
        # Libvirt currently writes to stderr if you attempt to connect
        # and the daemon is not running. The libvirt python bindings provide
        # no way to change this behavior. Anything written to stderr or stdout
        # will cause cron to email root with the output. It is not our
        # job to nag the user every two minutes if libvirt is not running.
        # The only way to avoid this is to shell out to check if libvirt
        # is running, and exit if it's not.
        # See if the libvirtd service is running, discarding all output.
        # Non-zero exit code means it's not running.
        if (subprocess.call(['/sbin/service','libvirtd','status'],
                stdout=open(os.devnull, 'wb'),
                stderr=subprocess.STDOUT) != 0):
            sys.exit(0)
        domain_list = poll_hypervisor()
    else:
        # If no libvirt nor vdsm is present, this program is pretty much
        # useless.  Just exit.
        sys.exit(0)

    # create the unkonwn domain config files (for libvirt only)
    if libvirt and not vdsm_enabled:
        uuid_list = list(domain_list.keys())
        domain = DomainDirectory()
        domain.save_unknown_domain_configs(uuid_list)

    cached_state = PollerStateCache(domain_list,
                                    debug = options and options.debug)

    # Send notifications, if necessary.
    _send_notifications(cached_state)

    # Save the new state.
    cached_state.save()
07070100000023000081B40000000000000000000000015CDC5C8900001E5C000000000000000000000000000000000000003800000000mgr-virtualization/virtualization/poller_state_cache.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
import os
try:
    # python2
    import cPickle
except ImportError:
    import pickle as cPickle
import time
import traceback

from spacewalk.common.usix import LongType

###############################################################################
# Constants
###############################################################################

CACHE_DATA_PATH = '/var/cache/rhn/virt_state.cache'
CACHE_EXPIRE_SECS = 60 * 60 * 6   # 6 hours, in seconds

###############################################################################
# PollerStateCache Class
###############################################################################

class PollerStateCache:

    ###########################################################################
    # Public Interface
    ###########################################################################

    def __init__(self, domain_data, debug = 0):
        """
        This method creates a new poller state based on the provided domain
        list.  The domain_data list should be in the form returned from
        poller.poll_hypervisor.  That is,

             { uuid : { 'name'        : '...',
                        'uuid'        : '...',
                        'virt_type'   : '...',
                        'memory_size' : '...',
                        'vcpus'       : '...',
                        'state'       : '...' }, ... }
        """
        self.__debug = debug

        # Start by loading the old state, if necessary.
        self._load_state()
        self.__new_domain_data = domain_data

        # Now compare the given domain_data against the one loaded in the old
        # state.
        self._compare_domain_data()

        self._log_debug("Added: %s"    % repr(self.__added))
        self._log_debug("Removed: %s"  % repr(self.__removed))
        self._log_debug("Modified: %s" % repr(self.__modified))

    def save(self):
        """
        Updates the cache on disk with the latest domain data.
        """
        self._save_state()

    def is_expired(self):
        """
        Returns true if this cache is expired.
        """
        if self.__expire_time is None:
            return False
        else:
            return LongType(time.time()) >= self.__expire_time

    def is_changed(self):
        return self.__added or self.__removed or self.__modified

    def get_added(self):
        """
        Returns a list of uuids for each domain that has been added since the
        last state poll.
        """
        return self.__added

    def get_modified(self):
        """
        Returns a list of uuids for each domain that has been modified since
        the last state poll.
        """
        return self.__modified

    def get_removed(self):
        """
        Returns a list of uuids for each domain that has been removed since
        the last state poll.
        """
        return self.__removed

    ###########################################################################
    # Helper Methods
    ###########################################################################

    def _load_state(self):
        """
        Loads the last hypervisor state from disk.
        """
        # Attempt to open up the cache file.
        cache_file = None
        try:
            cache_file = open(CACHE_DATA_PATH, 'rb')
        except IOError:
            ioe = sys.exc_info()[1]
            # Couldn't open the cache file.  That's ok, there might not be one.
            # We'll only complain if debugging is enabled.
            self._log_debug("Could not open cache file '%s': %s" % \
                               (CACHE_DATA_PATH, str(ioe)))

        # Now, if a previous state was cached, load it.
        state = {}
        if cache_file:
            try:
                state = cPickle.load(cache_file)
            except cPickle.PickleError:
                pe = sys.exc_info()[1]
                # Strange.  Possibly, the file is corrupt.  We'll load an empty
                # state instead.
                self._log_debug("Error occurred while loading state: %s" % \
                                    str(pe))
            except EOFError:
                self._log_debug("Unexpected EOF. Probably an empty file.")
                cache_file.close()

            cache_file.close()

        if state:
            self._log_debug("Loaded state: %s" % repr(state))

            self.__expire_time = LongType(state['expire_time'])

            # If the cache is expired, set the old data to None so we force
            # a refresh.
            if self.is_expired():
                self.__old_domain_data = None
                os.unlink(CACHE_DATA_PATH)
            else:
                self.__old_domain_data = state['domain_data']

        else:
            self.__old_domain_data = None
            self.__expire_time     = None

    def _save_state(self):
        """
        Saves the given polling state to disk.
        """
        # First, ensure that the proper parent directory is created.
        cache_dir_path = os.path.dirname(CACHE_DATA_PATH)
        if not os.path.exists(cache_dir_path):
            os.makedirs(cache_dir_path, int('0700', 8))

        state = {}
        state['domain_data'] = self.__new_domain_data
        if self.__expire_time is None or self.is_expired():
            state['expire_time'] = LongType(time.time()) + CACHE_EXPIRE_SECS
        else:
            state['expire_time'] = self.__expire_time

        # Now attempt to open the file for writing.  We'll just overwrite
        # whatever's already there.  Also, let any exceptions bounce out.
        cache_file = open(CACHE_DATA_PATH, "wb")
        cPickle.dump(state, cache_file)
        cache_file.close()

    def _compare_domain_data(self):
        """
        Compares the old domain_data to the new domain_data.  Returns a tuple
        of lists, relative to the new domain_data:

            (added, removed, modified)
        """
        self.__added    = {}
        self.__removed  = {}
        self.__modified = {}

        # First, figure out the modified and added uuids.
        if self.__new_domain_data:
            for (uuid, new_properties) in self.__new_domain_data.items():
                if not self.__old_domain_data or uuid not in self.__old_domain_data:

                    self.__added[uuid] = self.__new_domain_data[uuid]
                else:
                    old_properties = self.__old_domain_data[uuid]
                    if old_properties != new_properties:
                        self.__modified[uuid] = self.__new_domain_data[uuid]

        # Now, figure out the removed uuids.
        if self.__old_domain_data:
            for uuid in self.__old_domain_data.keys():
                if not self.__new_domain_data or uuid not in self.__new_domain_data:

                    self.__removed[uuid] = self.__old_domain_data[uuid]

    def _log_debug(self, msg, include_trace = 0):
        if self.__debug:
            print("DEBUG: " + str(msg))
            if include_trace:
                e_info = sys.exc_info()
                traceback.print_exception(e_info[0], e_info[1], e_info[2])


07070100000024000081B40000000000000000000000015CDC5C8900000ACA000000000000000000000000000000000000003500000000mgr-virtualization/virtualization/schedule_poller.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
try:
    # Python 2
    import commands
except ImportError:
    import subprocess as commands

from spacewalk.common.usix import StringType
from distutils.sysconfig import get_python_lib

COMMAND = "python%s %s/virtualization/poller.py" % (sys.version[0], get_python_lib())

def create_crontab_line(minute  =   None,\
                        hour    =   None,\
                        dom     =   None,\
                        month   =   None,\
                        dow     =   None,
                        command =   COMMAND):
    user = "root"

    if minute == None:
        minute = "*"
    if hour == None:
        hour = "*"
    if dom == None:
        dom = "*"
    if month == None:
        month = "*"
    if dow == None:
        dow = "*"

    if type(minute) != StringType:
        minute = str(minute).strip()
    if type(hour) != StringType:
        hour = str(hour).strip()
    if type(dom) != StringType:
        dom = str(dom).strip()
    if type(month) != StringType:
        month = str(month).strip()
    if type(dow) != StringType:
        dow = str(dow).strip()

    str_template = "%s %s %s %s %s %s %s\n"

    output_string = str_template % (minute, hour, dom, month, dow, user, command)
    return output_string


def schedule_poller(minute=None, hour=None, dom=None, month=None, dow=None):
    try:
        #create a crontab file
        filename = "/etc/cron.d/rhn-virtualization.cron"
        cronfile = open(filename, "w")

        #create a crontab line
        cron_line = create_crontab_line(minute, hour, dom, month, dow)

        #write crontab line to the temp file
        cronfile.write(cron_line)

        #close the temp file
        cronfile.close()

    except Exception:
        e = sys.exc_info()[1]
        return (1, str(e))

    #pass the temp file to crontab
    status, output = commands.getstatusoutput("/sbin/service crond restart")

    if status != 0:
        return (1, "Attempt to schedule poller failed: %s, %s" % (str(status), str(output)))
    else:
        return (0, "Scheduling of poller succeeded!")



if __name__ == "__main__":
    schedule_poller(minute="0-59/2")



07070100000025000081B40000000000000000000000015CDC5C89000013DA000000000000000000000000000000000000003200000000mgr-virtualization/virtualization/start_domain.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

try:
    # python 2
    import commands
except ImportError:
    import subprocess as commands

import libvirt
import os
import os.path
import re
import sys

from virtualization.domain_directory import DomainDirectory
from virtualization.domain_config    import DomainConfig, DomainConfigError
from virtualization.errors           import VirtualizationException
from spacewalk.common.usix import raise_with_tb

###############################################################################
# Constants
###############################################################################

PYGRUB = "/usr/bin/pygrub"

###############################################################################
# Public Interface
###############################################################################

def start_domain(uuid):
    """
    Boots the domain for the first time after installation is complete.
    """
    # Load the configuration file for this UUID.
    domain = DomainDirectory()
    config = domain.load_config(uuid)

    # Connect to the hypervisor.
    connection = libvirt.open(None)

    # We will attempt to determine if the domain is configured to use a
    # bootloader.  If not, we'll have to explicitly use the kernel and initrd
    # data provided in the config to start the domain.
    try:
        config.getConfigItem(DomainConfig.BOOTLOADER)
    except DomainConfigError:
        dce = sys.exc_info()[1]
        # No bootloader tag present.  Use pygrub to extract the kernel from
        # the disk image if its Xen. For fully virt we dont have pygrub, it
        # directly emulates the BIOS loading the first sector of the boot disk.
        if connection.getType() == 'Xen':
            # This uses pygrub which comes only with xen
            _prepare_guest_kernel_and_ramdisk(config)

    # Now, we'll restart the instance, this time using the re-create XML.
    try:
        domain = connection.createLinux(config.toXML(), 0)
    except Exception:
        e = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("Error occurred while attempting to recreate domain %s: %s" %
                                              (uuid, str(e))), sys.exc_info()[2])

###############################################################################
# Helper Methods
###############################################################################

def _prepare_guest_kernel_and_ramdisk(config):
    """
    Use PyGrub to extract the kernel and ramdisk from the given disk image.
    """

    disk_image = config.getConfigItem(DomainConfig.DISK_IMAGE_PATH)

    # Use pygrub to extract the initrd and the kernel from the disk image.
    (status, output) = \
        commands.getstatusoutput("%s -q %s" % (PYGRUB, disk_image))
    if status != 0:
        raise VirtualizationException("Error occurred while executing '%s' (status=%d). Output=%s" %
                                      (PYGRUB, status, output))

    # Now analyze the output and extract the names of the new kernel and initrd
    # images from it.
    (pygrub_kernel_path, pygrub_initrd_path) = \
        _extract_image_paths_from_pygrub_output(output)

    # Rename the extracted images to the names we are pointing to in the
    # configuration file.
    runtime_kernel_path = config.getConfigItem(DomainConfig.KERNEL_PATH)
    runtime_initrd_path = config.getConfigItem(DomainConfig.RAMDISK_PATH)

    try:
        os.rename(pygrub_kernel_path, runtime_kernel_path)
        os.rename(pygrub_initrd_path, runtime_initrd_path)
    except OSError:
        oe = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("Error occurred while renaming runtime image paths: %s" % str(oe)),
                      sys.exc_info()[2])


def _extract_image_paths_from_pygrub_output(output):
    """
    Searches for the paths of the kernel and initrd files in the output of
    pygrub.  If not found, a VirtualizationException is raised.  Otherwise,
    the (kernel_path, initrd_path) tuple is returned.
    """
    match = re.search("^linux \(kernel (\S+)\)\(ramdisk (\S+)\)",
                      output,
                      re.MULTILINE)
    if match is None or len(match.groups()) != 2:
        raise VirtualizationException("Could not locate kernel and initrd in pygrub output: %s" % output)

    kernel_path = match.group(1)
    initrd_path = match.group(2)

    return (kernel_path, initrd_path)

if __name__ == "__main__":
    print("result=", start_domain(sys.argv[1]))
07070100000026000081FD0000000000000000000000015CDC5C890000091B000000000000000000000000000000000000002B00000000mgr-virtualization/virtualization/state.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from virtualization.constants import StateType

###############################################################################
# Classes
###############################################################################

class State:
    """
    This class represents the state of a virtual instance.  It provides
    abstraction to categorize the state into running, stopped, paused, or
    crashed.
    """

    def __init__(self, state_type):
        """
        Create a new state.  If state_type is None, this state is assumed to be
        stopped.  If state_type is not None, it must be a StateType type.
        """
        self.__state_type = state_type

    def get_state_type(self):
        """
        Returns the state type used to create this instance.
        """
        return self.__state_type

    def is_running(self):
        """
        Returns true if this object represents a running state.
        """
        return self.__state_type == StateType.NOSTATE or \
               self.__state_type == StateType.RUNNING or \
               self.__state_type == StateType.BLOCKED or \
               self.__state_type == StateType.SHUTDOWN

    def is_paused(self):
        """
        Returns true if this object represents a paused instance.
        """
        return self.__state_type == StateType.PAUSED

    def is_stopped(self):
        """
        Returns true if this object represents a stopped instance.
        """
        return self.__state_type == None or \
               self.__state_type == StateType.SHUTOFF

    def is_crashed(self):
        """
        Returns true if this object represents a crashed instance.
        """
        return self.__state_type == StateType.CRASHED

07070100000027000081FD0000000000000000000000015CDC5C8900001C06000000000000000000000000000000000000002D00000000mgr-virtualization/virtualization/support.py#
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
import gettext

from up2date_client import rhncli
from virtualization import domain_control, poller, schedule_poller

from virtualization.constants        import IdentityType,            \
                                            PropertyType
from virtualization.notification     import Plan,                    \
                                            EventType,               \
                                            TargetType
from virtualization.domain_config    import DomainConfig
from virtualization.domain_directory import DomainDirectory
from spacewalk.common.usix import UnicodeType


t = gettext.translation('rhn-virtualization', fallback=True)
_ = t.ugettext

try:
    import libvirt
except:
    # The libvirt library is not installed.  That's ok, we can't assume it will
    # be on every system.
    libvirt = None

def utf8_encode(msg):
    """
    for RHEL6 just pass the function to rhncli
    for RHEL5 do the same within this module
    """
    if hasattr(rhncli, 'utf8_encode'):
        return rhncli.utf8_encode(msg)
    if isinstance(msg, UnicodeType):
        msg = msg.encode('utf-8')
    return(msg)


def _check_status(daemon):
    """
     Checks to see if daemon is running.
    """
    try:
        # python 2
        import commands
    except ImportError:
        import subprocess as commands

    cmd = "/etc/init.d/%s status" % daemon
    status, msg = commands.getstatusoutput(cmd)
    if status != 0:
        return False
    return True

vdsm_enabled = _check_status("vdsmd")
# override vdsm_enabled if we can't read information from it
try:
    from virtualization import localvdsm
except ImportError:
    vdsm_enabled = False


###############################################################################
# Public Interface
###############################################################################

def refresh(fail_on_error=False):
    """
    Refreshes the virtualization info for this host and any subdomains on the
    server.
    """
    if _is_host_domain(fail_on_error):
        domain_identity = IdentityType.HOST
        my_uuid = _fetch_host_uuid()
    else:
        # Not a host.  No-op.
        return

    # Now that we've gathered some preliminary information, create a plan of
    # actions that we will eventually pass to the server.
    plan = Plan()

    # First, declare our own existence.
    plan.add(
        EventType.EXISTS,
        TargetType.SYSTEM,
        { PropertyType.IDENTITY : domain_identity,
          PropertyType.UUID     : my_uuid          })

    # Now, crawl each of the domains on this host.
    if vdsm_enabled:
        server = localvdsm.connect()
        domains = poller.poll_through_vdsm(server)
    else:
        domains = poller.poll_hypervisor()

        if not len(domains) and libvirt.openReadOnly(None).getType() == 'Xen':
           # On a KVM/QEMU host, libvirt reports no domain entry for host itself
           # On a Xen host, either there were no domains or xend might not be
           # running. Don't proceed further.
           return
    domain_list = list(domains.values())
    domain_uuids = list(domains.keys())

    if not vdsm_enabled:
        # We need this only for libvirt
        domain_dir = DomainDirectory()
        domain_dir.save_unknown_domain_configs(domain_uuids)

    plan.add(EventType.CRAWL_BEGAN, TargetType.SYSTEM)
    for domain_properties in domain_list:
        plan.add(EventType.EXISTS, TargetType.DOMAIN, domain_properties)
    plan.add(EventType.CRAWL_ENDED, TargetType.SYSTEM)

    # Finally, execute the actions queued up in the plan.
    plan.execute()

def shutdown(uuid):
    """
    Shuts down the domain with the given UUID.
    """
    domain_control.shutdown(uuid)

def start(uuid):
    """
    Starts up the domain with the given UUID.
    """
    domain_control.start(uuid)

def suspend(uuid):
    """
    Suspends the domain with the given UUID.
    """
    domain_control.suspend(uuid)

def resume(uuid):
    """
    Resumes the domain with the given UUID.
    """
    domain_control.resume(uuid)

def reboot(uuid):
    """
    Reboots the domain with the given UUID.
    """
    domain_control.reboot(uuid)

def destroy(uuid):
    """
    Destroys the domain with the given UUID.
    """
    domain_control.destroy(uuid)

def setMemory(uuid, memory):
    """
    Sets the max memory usage for the domain with the given UUID.
    """
    domain_dir = DomainDirectory()
    config = domain_dir.load_config(uuid)
    config.setConfigItem(DomainConfig.MEMORY, memory)
    config.save()
    domain_control.setMemory(uuid, memory)

def setVCPUs(uuid, vcpus):
    """
    Sets the number of vcpus for the domain with the given UUID.
    """
    domain_dir = DomainDirectory()
    config = domain_dir.load_config(uuid)
    config.setConfigItem(DomainConfig.VCPU, vcpus)
    config.save()
    domain_control.setVCPUs(uuid, vcpus)

def schedulePoller(minute, hour, dom, month, dow):
    """
    Sets when poller should run.
    """
    return schedule_poller.schedule_poller(minute, hour, dom, month, dow)

###############################################################################
# Helper Routines
###############################################################################

def _is_host_domain(fail_on_error=False):
    """
    This function returns true if this system is currently a host domain.
    Simply having virtualization enabled is sufficient.

    We can figure out if Xen/Qemu is running by checking for the type
    """
    if vdsm_enabled:
        # since vdsm is enabled, lets move further and
        # see what we get
        return True
    if not libvirt:
        # No libvirt, dont bother with the rest
        return False
    try:
        conn = libvirt.openReadOnly(None)
    except libvirt.libvirtError: # libvirtd is not running
        sys.stderr.write(utf8_encode(_("Warning: Could not retrieve virtualization information!\n\tlibvirtd service needs to be running.\n")))
        if fail_on_error:
            sys.exit(1)
        return False
    if conn and conn.getType() in ['Xen', 'QEMU']:
        return True
    return False

def _fetch_host_uuid():
    """
    This function returns the UUID of the host system.  This will always be
    16 zeros.
    """
    return '0000000000000000'

###############################################################################
# Test Routine
###############################################################################

if __name__ == "__main__":
    #refresh()
    print(_retrieve_virtual_domain_list())

07070100000028000081B40000000000000000000000015CDC5C8900000724000000000000000000000000000000000000002A00000000mgr-virtualization/virtualization/util.py#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import random
from virtualization.errors import UUIDError

def generate_uuid():
    """Generate a random UUID and return it."""

    uuid_list = [ random.randint(0, 255) for _ in range(0, 16) ]
    return ("%02x" * 16) % tuple(uuid_list)

def hyphenize_uuid(uuid):
    # Determine whether the string is already hyphenized.
    if len(uuid) == 36 and len(uuid.replace('-', '')) == 32:
        return uuid[:]

    if len(uuid) != 32:
        raise UUIDError("UUID %s is not 32 characters long." % (uuid,))

    formatstr = "%s-%s-%s-%s-%s"
    new_uuid = formatstr % (uuid[0:8],
                            uuid[8:12],
                            uuid[12:16],
                            uuid[16:20],
                            uuid[20:])
    return new_uuid

def dehyphenize_uuid(uuid):
    if uuid is None:
        return uuid

    return uuid.replace('-', '')

def is_host_uuid(uuid):
    """
    Returns true if the given UUID represents a host.  We can tell because
    host UUIDs are always 0.
    """
    return int(eval("0x" + dehyphenize_uuid(uuid))) == 0

def is_fully_virt(domain):
    """
    Returns true if the given domain is a fully-virt domain.
    """
    return domain.OSType().lower() == 'hvm'

07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!