File spacewalk-koan-git-0.bdf9ba0.obscpio of Package spacewalk-koan

07070100000000000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000000F00000000spacewalk-koan07070100000001000081B40000000000000000000000015FB636EB00000008000000000000000000000000000000000000001A00000000spacewalk-koan/.gitignorereports
07070100000002000081B40000000000000000000000015FB636EB000046AC000000000000000000000000000000000000001700000000spacewalk-koan/COPYING                    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.
07070100000003000081B40000000000000000000000015FB636EB00000023000000000000000000000000000000000000001800000000spacewalk-koan/Makefile
include ../../../rel-eng/Makefile
07070100000004000081B40000000000000000000000015FB636EB000007E6000000000000000000000000000000000000001D00000000spacewalk-koan/Makefile.defs# Common pathnames and programs for the Spacewalk project
#

# if not defined, definit as a noop
TOP		?= .

# global defines which control this build and where we deploy files
ROOT		?= /usr/share/rhn
export ROOT

PREFIX		?=
export PREFIX

# Compilation stuff
CC		= gcc
PYTHON_INCLUDE	= -I/usr/include/python$(PythonVersion)
CFLAGS		= -Wall -O2 -fomit-frame-pointer $(PYTHON_INCLUDE) -fPIC
SOFLAGS		= -shared -fPIC

# Installation stuff
INSTALL		= /usr/bin/install -c --verbose
INSTALL_BIN	= $(INSTALL) -m 755
INSTALL_DATA	= $(INSTALL) -m 644
INSTALL_DIR	= $(INSTALL) -m 755 -d

# This is for the subdir part
PYFILES		= $(addsuffix .py,$(FILES))

# This is for the subdir part
VIRT_PYFILES		= $(addsuffix .py,$(VIRT_FILES))

# what do we need to install and where
INSTALL_FILES	+= $(PYFILES)
INSTALL_DEST	?= $(ROOT)/$(SUBDIR)

VIRT_INSTALL_FILES =  $(VIRT_PYFILES)

DIRS		+= $(addprefix $(PREFIX), \
			$(sort $(EXTRA_DIRS)) $(INSTALL_DEST))

all :: $(INSTALL_FILES) $(VIRT_INSTALL_FILES)

install :: all $(DIRS) $(INSTALL_FILES) 
	@mkdir -p $(PREFIX)$(ROOT)
	@$(foreach f,$(INSTALL_FILES) $(VIRT_INSTALL_FILES), \
		$(INSTALL_DATA) $(f) $(PREFIX)$(INSTALL_DEST)/$(f) ; )

$(DIRS):
	$(INSTALL_DIR) $@

clean ::
	@rm -fv *~ *.pyc *.pyo .??*~
	@rm -fv .\#*
	@rm -fv core

# useful macro
descend-subdirs = @$(foreach d,$(SUBDIRS), $(MAKE) -C $(d) $@ || exit 1; )

# subdirs are treated at the end
all install clean:: $(SUBDIRS)
	$(descend-subdirs)


# extra toy targets
# Python checker support
PYTHONPATH      = $(TOP)
PYCHECKER       = pychecker
PYCHECKEROPTS   = --maxreturns 10 --maxbranches 15
DBCHECKER       = db-checker.py
DBCHECKEROPTS   =
DB              = user/pass@instance

pychecker :: $(PYFILES)
	@PYTHONPATH=$(PYTHONPATH) $(PYCHECKER) $(PYCHECKEROPTS) $(PYFILES) || :
	$(descend-subdirs)

db-checker :: $(PYFILES)
	@PYTHONPATH=$(PYTHONPATH) $(TOP)/$(DBCHECKER) $(DBCHECKEROPTS) $(PYFILES) || :
	$(descend-subdirs)

graphviz :: 
	@PYTHONPATH=$(PYTHONPATH) $(PYCHECKER) -Z $(PYCHECKEROPTS) $(PYFILES) || exit 0

07070100000005000081B40000000000000000000000015FB636EB0000034A000000000000000000000000000000000000001F00000000spacewalk-koan/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/spacewalk-koan; 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
07070100000006000081B40000000000000000000000015FB636EB00000512000000000000000000000000000000000000002700000000spacewalk-koan/Makefile.spacewalk-koan# what is the top dir
TOP     = .

# Specific stuff
SUBDIRS = 	actions \
            spacewalkkoan

SBIN_DIR        = /usr/sbin
INSTALL_DEST    = $(SBIN_DIR)
INSTALL_FILES   = merge-rd.sh


include $(TOP)/Makefile.defs

# Install files as binaries
INSTALL_DATA    = $(INSTALL_BIN)

# Docker tests variables
DOCKER_IMAGE          = suma-head-spacewalkkoan
DOCKER_REGISTRY       = registry.mgr.suse.de
DOCKER_RUN_EXPORT     = "PYTHONPATH=/manager/client/tools/"
DOCKER_VOLUMES        = -v "$(CURDIR)/../../../:/manager"
INITIAL_CMD           = /manager/susemanager-utils/testing/automation/initial-objects.sh
TEST_CMD              = nosetests --with-xunit --xunit-file /manager/client/tools/spacewalk-koan/reports/spacewalk-koan_tests.xml -s /manager/client/tools/spacewalk-koan/test
CHOWN_CMD             = /manager/susemanager-utils/testing/automation/chown-objects.sh $(shell id -u) $(shell id -g)

docker_tests ::
	mkdir -p $(CURDIR)/reports
	docker pull $(DOCKER_REGISTRY)/$(DOCKER_IMAGE)
	docker run --rm -e $(DOCKER_RUN_EXPORT) $(DOCKER_VOLUMES) $(DOCKER_REGISTRY)/$(DOCKER_IMAGE) /bin/bash -c "$(INITIAL_CMD); $(TEST_CMD); RET=\$${?}; $(CHOWN_CMD) && exit \$${RET}"

docker_shell ::
	docker run --rm -ti -e $(DOCKER_RUN_EXPORT) $(DOCKER_VOLUMES) $(DOCKER_REGISTRY)/$(DOCKER_IMAGE) /bin/bash

07070100000007000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000001700000000spacewalk-koan/actions07070100000008000081B40000000000000000000000015FB636EB000001B3000000000000000000000000000000000000002000000000spacewalk-koan/actions/Makefile# Makefile for the backend directory
#

TOP         = ..
ROOT        = /usr/share/rhn
SUBDIR      = rhn/actions
FILES       = kickstart
CAPS        = kickstart
CAPS_DIR    = /etc/sysconfig/rhn/clientCaps.d
EXTRA_DIRS  = $(CAPS_DIR)

VIRT_FILES = kickstart_guest

# now include some Macros
include $(TOP)/Makefile.defs

install :: install-caps

install-caps :: $(CAPS) $(PREFIX)$(CAPS_DIR)
	$(INSTALL_DATA) $(CAPS) $(PREFIX)$(CAPS_DIR)
07070100000009000081B40000000000000000000000015FB636EB00000036000000000000000000000000000000000000002100000000spacewalk-koan/actions/kickstartkickstart.initiate(1)=1
kickstart_guest.initiate(1)=1
0707010000000A000081B40000000000000000000000015FB636EB000004BC000000000000000000000000000000000000002400000000spacewalk-koan/actions/kickstart.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

rhnpath="/usr/share/rhn"
if rhnpath not in sys.path:
    sys.path.append(rhnpath)

from spacewalkkoan import spacewalkkoan
from up2date_client import up2dateLog

__rhnexport__ = [
    'initiate',
]

def initiate(kickstart_host, base, extra_append, static_device="", system_record="", preserve_files=[], cache_only=False):
    log = up2dateLog.initLog()
    log.log_me("initiating spacewalkkoan kickstart")
    return spacewalkkoan.initiate(kickstart_host, base, extra_append=extra_append,
        static_device=static_device, system_record=system_record, preserve_files=preserve_files)
0707010000000B000081B40000000000000000000000015FB636EB00000A34000000000000000000000000000000000000002A00000000spacewalk-koan/actions/kickstart_guest.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 sys

rhnpath="/usr/share/rhn"
if rhnpath not in sys.path:
    sys.path.append(rhnpath)

from spacewalkkoan import spacewalkkoan

from virtualization.batching_log_notifier import BatchNotifyHandler
from virtualization.constants             import PropertyType
from virtualization.notification          import Plan,                \
                                                 EventType,           \
                                                 TargetType

__rhnexport__ = [
    'initiate'
]

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

def initiate(kickstart_host, cobbler_system_name, virt_type, ks_session_id, name, mem_kb, vcpus, disk_gb, virt_bridge, disk_path, extra_append, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    error_code = 0
    status_message = 'Guest kickstart initiated successfully.'
    error_messages = {}

    log_notify_handler = KickstartLogNotifyHandler(ks_session_id)

    return  spacewalkkoan.initiate_guest(kickstart_host, cobbler_system_name,
                virt_type, name, mem_kb, vcpus, disk_gb, virt_bridge, disk_path, extra_append, log_notify_handler)

###############################################################################
# LogNotifyHandler Class
###############################################################################

class KickstartLogNotifyHandler(BatchNotifyHandler):

    def __init__(self, ks_session_id):
        self.__ks_session_id = ks_session_id
        self.__plan = None

    def batch_began(self):
        self.__plan = Plan()

    def log_message_discovered(self, log_message):
        self.__plan.add(
            EventType.EXISTS,
            TargetType.LOG_MSG,
            { PropertyType.ID      : self.__ks_session_id,
              PropertyType.MESSAGE : log_message })

    def batch_ended(self):
        self.__plan.execute()

0707010000000C000081B40000000000000000000000015FB636EB00001965000000000000000000000000000000000000001B00000000spacewalk-koan/merge-rd.sh#!/bin/bash

# a fairly simple script to merge a given tree into an existing,
# bootable ramdisk.  a new ramdisk is created since space may be an
# issue (especially if we start letting people put their own files in
# here to preserve across the install).

set -e

unset LANG

unset PATH
export PATH=/sbin:/bin:/usr/sbin:/usr/bin

SOURCE_INITRD=$1
DEST_INITRD=$2
USER_TREE=$3

fatal() {
    err=$1; shift; >&2 echo "$*"; exit $err
}

usage() {
    fatal 1 "Usage: $0 SOURCERD DESTRD /path/to/merge/from"
}

tarcp() {
    source=$1
    dest=$2

    mkdir -p $dest
    tar cf - -C $source . | tar xf - -C $dest
}

# Constants for use with the below function.
INITRD_TYPE_CPIO=1
INITRD_TYPE_EXT2=2

# $1 - The file to check.
get_initrd_type() {
    local UNCOMPRESSED_INITRD=$1

    INITRD_TYPE=-1
    if file $UNCOMPRESSED_INITRD | grep cpio > /dev/null 2>&1 ; then
        INITRD_TYPE=$INITRD_TYPE_CPIO
    elif file $UNCOMPRESSED_INITRD | grep ext2 > /dev/null 2>&1 ; then
        INITRD_TYPE=$INITRD_TYPE_EXT2
    else
        fatal 9 "Cannot get initrd type"
    fi

    echo $INITRD_TYPE
}

uncompress_rd() {
    local COMPRESSED_INITRD=$1
    local UNCOMPRESSED_INITRD=$2
    if ! zcat $COMPRESSED_INITRD > $UNCOMPRESSED_INITRD 2> /dev/null; then
        if ! xzcat $COMPRESSED_INITRD > $UNCOMPRESSED_INITRD 2> /dev/null; then
          fatal 9 "Error uncompressing $COMPRESSED_INITRD"
        fi
    fi
}

# Expands the provided initrd file into the specified directory.  Returns the
# uncompressed directory in the EXPANDED_TREE argument.
expand_rd() {
    local UNCOMPRESSED_INITRD=$1
    local TARGET_TREE=$2

    local INITRD_TYPE=$(get_initrd_type $UNCOMPRESSED_SOURCE_INITRD)

    mkdir -p $TARGET_TREE

    if [ $INITRD_TYPE -eq $INITRD_TYPE_EXT2 ] ; then

        mount -o loop $UNCOMPRESSED_INITRD $TARGET_TREE \
            || fatal 3 "mount loopback failed"

    elif [ $INITRD_TYPE -eq $INITRD_TYPE_CPIO ] ; then

        cd $TARGET_TREE
        ( cat $UNCOMPRESSED_INITRD | \
            cpio -i -d -H newc --no-absolute-filenames ) > /dev/null 2>&1
        cd - > /dev/null 2>&1

    else
        fatal 9 "Unknown initrd type"
    fi
}

create_rd() {
    local INITRD_TYPE=$1
    local TARGET_INITRD=$2
    local EXISTING_TREE=$3
    local ESTIMATED_INITRD_SIZE=$4

    if [ $INITRD_TYPE -eq $INITRD_TYPE_EXT2 ] ; then

        dd if=/dev/zero      \
           of=$TARGET_INITRD \
           bs=1024           \
           count=$(($ESTIMATED_INITRD_SIZE/1024)) &> /dev/null
        mke2fs -Fq -i 4096 $TARGET_INITRD &> /dev/null

        # Now that we've created the target image, copy the contents of the
        # tree into it.

        local TARGET_MOUNTED=$TEMP_DIR/target-mounted
        mkdir $TARGET_MOUNTED
        mount -o loop $TARGET_INITRD $TARGET_MOUNTED || \
            fatal 6 "mount of dest image"
        tarcp $EXISTING_TREE $TARGET_MOUNTED || fatal 9 "Error while extracting archive to final destination"
        umount $TARGET_MOUNTED

    elif [ $INITRD_TYPE -eq $INITRD_TYPE_CPIO ] ; then

        cd $EXISTING_TREE
        ( find . | cpio -o -H newc > $TARGET_INITRD ) > /dev/null 2>&1
        cd - > /dev/null 2>&1

    else
        fatal 9 "Unknown initrd type"
    fi
}

compress_rd() {
    local UNCOMPRESSED_INITRD=$1
    local COMPRESSED_INITRD=$2

    (gzip -9c $UNCOMPRESSED_INITRD > $COMPRESSED_INITRD) \
        || fatal 7 "compressing into dest"
}

estimate_merged_rd_size() {
    local SOURCE_TREE=$1
    local MERGED_TREE=$2
    local RESULT_ASSN=$3

    # time for some arithmetic; add 20% to the dest size, even though we
    # should have a pretty good estimate of space.  nothing lost since
    # gzip will turn the empty expanses of zeros into almost nothing

    local ORIG_SIZE=$(du -s -b $SOURCE_TREE | cut -f 1)
    local MERGED_SIZE=$(du -s -b $MERGED_TREE | cut -f 1)
    local DELTA="$(($MERGED_SIZE - $ORIG_SIZE))"
    if ! zcat $SOURCE_INITRD >& /dev/null && local ORIG_RD_SIZE=$(zcat $SOURCE_INITRD | wc -c); then
      if ! xzcat $SOURCE_INITRD >& /dev/null && local ORIG_RD_SIZE=$(xzcat $SOURCE_INITRD | wc -c); then
        fatal 9 "Unable to estimate merge size"
      fi
    fi
    local MERGED_RD_SIZE="$(( 12 * ($ORIG_RD_SIZE + $DELTA) / 10 ))"

    eval "$RESULT_ASSN=\"$MERGED_RD_SIZE\""
}

remove_tree() {
    local TREE_TO_REMOVE=$1

    # The tree may or may not be mounted, depending on the type of initrd
    # that was used to create it.

    # Force 'true' even when umount exits with an error to not block the
    # execution of the script (see set -e at the top of the file).
    # The script forces the umount even when mount has not been used.
    umount $TREE_TO_REMOVE > /dev/null 2>&1 || true
    rm -rf $TREE_TO_REMOVE
}

################################ Main #########################################

[ -e "$SOURCE_INITRD" ] || fatal 1 "Cannot find initrd $SOURCE_INITRD"
[ -d "$(dirname $DEST_INITRD)" ] || fatal 1 "Cannot find final destination dir: $(dirname $DEST_INITRD)"
[ -d "$USER_TREE" ] || fatal 1 "Cannot find user tree: $USER_TREE"

# Make sure we get the full pathnames.

SOURCE_INITRD=`(cd \`dirname $SOURCE_INITRD\` ; pwd)`/`basename $SOURCE_INITRD`
DEST_INITRD=`(cd \`dirname $DEST_INITRD\` ; pwd)`/`basename $DEST_INITRD`
USER_TREE=`(cd $USER_TREE ; pwd)`


TEMP_DIR=$(mktemp -d /tmp/mergerd.XXXXXX)
[ -d $TEMP_DIR ] || fatal 2 "mktemp failed"

COMPRESSED_SOURCE_INITRD=$SOURCE_INITRD
UNCOMPRESSED_SOURCE_INITRD=$TEMP_DIR/source-rd
SOURCE_TREE=$TEMP_DIR/source-tree

COMPRESSED_MERGED_INITRD=$DEST_INITRD
UNCOMPRESSED_MERGED_INITRD=$TEMP_DIR/merged-rd
MERGED_TREE=$TEMP_DIR/merged-tree

# Uncompress and expand the source initrd image.

uncompress_rd $COMPRESSED_SOURCE_INITRD $UNCOMPRESSED_SOURCE_INITRD
expand_rd $UNCOMPRESSED_SOURCE_INITRD $SOURCE_TREE

# Merge the source's and the user's trees together into a new tree.

tarcp $SOURCE_TREE $MERGED_TREE || fatal 4 "copy from source to dest"
tarcp $USER_TREE $MERGED_TREE || fatal 5 "copy of merge tree into rd"

# Determine the type of the initrd and create a new one.

estimate_merged_rd_size $SOURCE_TREE $MERGED_TREE ESTIMATED_SIZE
SOURCE_INITRD_TYPE=$(get_initrd_type $UNCOMPRESSED_SOURCE_INITRD)
create_rd $SOURCE_INITRD_TYPE         \
          $UNCOMPRESSED_MERGED_INITRD \
          $MERGED_TREE                \
          $ESTIMATED_SIZE

# Compress the new initrd image.

compress_rd $UNCOMPRESSED_MERGED_INITRD $COMPRESSED_MERGED_INITRD

# Clean up.

remove_tree $SOURCE_TREE
remove_tree $MERGED_TREE
rm -Rf $TEMP_DIR

0707010000000D000081B40000000000000000000000015FB636EB0000139C000000000000000000000000000000000000001800000000spacewalk-koan/pylintrc# spacewalk koan 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=
0707010000000E000081B40000000000000000000000015FB636EB0000003C000000000000000000000000000000000000002800000000spacewalk-koan/spacewalk-koan-rpmlintrcaddFilter("suse-filelist-forbidden-sysconfig .*/sysconfig")
0707010000000F000081B40000000000000000000000015FB636EB00001F9E000000000000000000000000000000000000002600000000spacewalk-koan/spacewalk-koan.changes- Fix tests

-------------------------------------------------------------------
Mon Sep 21 12:00:53 CEST 2020 - jgonzalez@suse.com

- version 4.2.2-1
- Fix for spacewalk-koan test

-------------------------------------------------------------------
Fri Sep 18 12:16:50 CEST 2020 - jgonzalez@suse.com

- version 4.2.1-1
- Update package version to 4.2.0

-------------------------------------------------------------------
Wed Nov 27 17:02:01 CET 2019 - jgonzalez@suse.com

- version 4.1.1-1
- gfx_type needs to default to 'vnc' (bsc#1156211)
- Bump version to 4.1.0 (bsc#1154940)
- require commands we use in merge-rd.sh

-------------------------------------------------------------------
Wed May 15 15:11:51 CEST 2019 - jgonzalez@suse.com

- version 4.0.5-1
- SPEC cleanup

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

- version 4.0.4-1
- Enable pylint

-------------------------------------------------------------------
Wed Feb 27 13:02:19 CET 2019 - jgonzalez@suse.com

- version 4.0.3-1
- port unit tests to python3

-------------------------------------------------------------------
Fri Oct 26 10:30:21 CEST 2018 - jgonzalez@suse.com

- version 4.0.2-1
- Fix building on openSUSE 15.0
- Add Uyuni URL to package

-------------------------------------------------------------------
Fri Aug 10 15:22:31 CEST 2018 - jgonzalez@suse.com

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

-------------------------------------------------------------------
Mon Mar 26 08:56:41 CEST 2018 - jgonzalez@suse.com

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

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

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

-------------------------------------------------------------------
Fri Feb 23 10:57:22 CET 2018 - jgonzalez@suse.com

- version 2.8.7.1-1
- Sync with upstream

-------------------------------------------------------------------
Fri Feb 02 12:08:08 CET 2018 - jgonzalez@suse.com

- version 2.8.5.2-1
- replace ifconfig with ip command

-------------------------------------------------------------------
Fri Nov 10 16:37:00 CET 2017 - mc@suse.de

- version 2.8.5.1-1
- add missing directories to filelist

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

- version 2.8.4.1-1
- split spacewalk-koan into python2/python3 specific packages
- replace koan20 with koan
- remove dependency to rhn-virtualization

-------------------------------------------------------------------
Mon Mar 06 16:41:25 CET 2017 - mc@suse.de

- version 2.7.0.2-1
- Updated links to github in spec files

-------------------------------------------------------------------
Wed Jan 11 16:17:50 CET 2017 - michele.bologna@suse.com

- version 2.7.0.1-1
- Bumping package versions for 2.7.

-------------------------------------------------------------------
Mon Mar 21 16:37:46 CET 2016 - mc@suse.de

- version 2.5.0.2-1
- fix file permissions (bsc#970550)

-------------------------------------------------------------------
Wed Oct 07 16:03:50 CEST 2015 - mc@suse.de

- version 2.5.0.1-1
- switch to KVM if possible
- fixing duplicate BuildArch

-------------------------------------------------------------------
Tue Mar 31 14:35:53 CEST 2015 - mc@suse.de

- version 2.1.4.12-1
- make file preservation work again with new upstream koan

-------------------------------------------------------------------
Tue Feb 03 11:51:59 CET 2015 - mc@suse.de

- version 2.1.4.11-1
- spacewalk-koan: improved merge-rd

-------------------------------------------------------------------
Thu Dec 18 13:32:51 CET 2014 - mc@suse.de

- version 2.1.4.10-1
- spacewalk-koan: Fix netmask calculation on SUSE systems (bnc#883487)

-------------------------------------------------------------------
Thu Dec 04 13:17:40 CET 2014 - mc@suse.de

- version 2.1.4.9-1
- make spacewalk-koan work with newer cobbler/koan version
  (bsc#908152)

-------------------------------------------------------------------
Thu Sep 04 12:18:54 CEST 2014 - mc@suse.de

- version 2.1.4.8-1
- Fix crash when installing via DHCP.

-------------------------------------------------------------------
Wed Sep 03 12:11:38 CEST 2014 - mc@suse.de

- version 2.1.4.7-1
- spacewalk-koan: fix package requirements

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

- sanitize release line in specfile

-------------------------------------------------------------------
Wed Jul 16 14:28:30 CEST 2014 - mc@suse.de

- version 2.1.4.6-1
- Adding requirement for patched Koan to fix bnc#880936
- Fix provisioning of a registered server on SLES with static
  IP address (bnc#880936)

-------------------------------------------------------------------
Fri May 16 12:51:18 CEST 2014 - mc@suse.de

- version 2.1.4.5-1
- try ifconfig if ipcalc is not installed

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

- version 2.1.4.4-1
- guest provisioned on RHEL 7 host have no graphical console

-------------------------------------------------------------------
Thu Apr 10 17:36:22 CEST 2014 - mc@suse.de

- version 2.1.4.3-1

-------------------------------------------------------------------
Thu Apr 10 17:36:14 CEST 2014 - mc@suse.de

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

-------------------------------------------------------------------
Mon Feb 17 11:27:28 CET 2014 - mc@suse.de

- version 2.1.4.2-1
- add COPYING

-------------------------------------------------------------------
Mon Jan 13 09:38:45 CET 2014 - mc@suse.de

- version 2.1.4.1-1
- use new Koan attribute

-------------------------------------------------------------------
Mon Dec 09 16:18:46 CET 2013 - mc@suse.de

- version 2.1.3.1-1
- switch to 2.1

-------------------------------------------------------------------
Wed Aug 21 15:52:11 CEST 2013 - mc@suse.de

- version 1.7.1.6-1
- Enable VNC for all virt types (bnc#826909)

-------------------------------------------------------------------
Thu Apr 04 15:35:30 CEST 2013 - mc@suse.de

- version 1.7.1.5-1
- do not call not existing function

-------------------------------------------------------------------
Fri Oct 05 09:46:24 CEST 2012 - mc@suse.de

- version 1.7.1.4-1

-------------------------------------------------------------------
Fri Sep 28 16:44:33 CEST 2012 - mc@suse.de

- version 1.7.1.3-1
- Show pretty error if customer specifies a MAC address already in use
  (bnc#783667)

-------------------------------------------------------------------
Fri Apr 27 17:00:12 CEST 2012 - mc@suse.de

- version 1.7.1.2-1
- support for xz packed ramdisk

-------------------------------------------------------------------
Wed Mar 21 17:04:54 CET 2012 - mc@suse.de

- version 1.7.1.1-1
- Bumping package version

-------------------------------------------------------------------
Thu Nov  3 19:25:33 CET 2011 - ma@suse.de

- Adapt dependencies to renamed packages (bnc#722052)

-------------------------------------------------------------------
Fri Jul  8 12:14:39 CEST 2011 - mc@suse.de

- do not require rhn-virtualization on Code10

-------------------------------------------------------------------
Tue Feb 15 11:54:03 CET 2011 - ug@suse.de

- requires rhn-virtualization-host now

-------------------------------------------------------------------
Tue Feb 15 10:52:44 CET 2011 - ug@suse.de

- requires rhn-virtualization-common now

-------------------------------------------------------------------
Wed Sep 15 12:21:11 CEST 2010 - mantel@suse.de

- fix post-build-checks

-------------------------------------------------------------------
Wed Sep 15 09:30:51 CEST 2010 - mantel@suse.de

- Initial release of spacewalk-koan

-------------------------------------------------------------------
07070100000010000081B40000000000000000000000015FB636EB00000FD6000000000000000000000000000000000000002300000000spacewalk-koan/spacewalk-koan.spec#
# spec file for package spacewalk-koan
#
# 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_check	 spacewalk-check
#
%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}

Summary:        Support package for spacewalk koan interaction
License:        GPL-2.0-only
Group:          System Environment/Kernel
Name:           spacewalk-koan
Version:        4.2.2
Release:        1%{?dist}
Source0:        https://github.com/spacewalkproject/spacewalk/archive/%{name}-%{version}.tar.gz
Source1:        %{name}-rpmlintrc
Url:            https://github.com/uyuni-project/uyuni
BuildRoot:      %{_tmppath}/%{name}-%{version}-build
%if 0%{?fedora} || 0%{?rhel} || 0%{?suse_version} >= 1210
BuildArch:      noarch
%endif
Requires:       %{pythonX}-%{name} = %{version}-%{release}
Requires:       koan
# dd, du
Requires:       coreutils
Requires:       cpio
Requires:       e2fsprogs
# gzip, zcat
Requires:       gzip
Requires:       tar
# mount, umount
Requires:       util-linux
Requires:       xz
Conflicts:      rhn-kickstart
Conflicts:      rhn-kickstart-common
Conflicts:      rhn-kickstart-virtualization

Requires:       %{rhn_check}

%description
Support package for spacewalk koan interaction.

%if 0%{?build_py2}
%package -n python2-%{name}
Summary:        Support package for spacewalk koan interaction
Group:          System Environment/Kernel
BuildRequires:  python
Requires:       %{name} = %{version}-%{release}
Requires:       python

%description -n python2-%{name}
Python 2 specific files for %{name}.
%endif

%if 0%{?build_py3}
%package -n python3-%{name}
Summary:        Support package for spacewalk koan interaction
Group:          System Environment/Kernel
BuildRequires:  python3
BuildRequires:  python3-rpm-macros
Requires:       %{name} = %{version}-%{release}
Requires:       python3

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

%prep
%setup -q

%build
make -f Makefile.spacewalk-koan all

%install
%if 0%{?build_py2}
make -f Makefile.spacewalk-koan install PREFIX=$RPM_BUILD_ROOT ROOT=%{python_sitelib} \
    MANDIR=%{_mandir}
%endif

%if 0%{?build_py3}
make -f Makefile.spacewalk-koan install PREFIX=$RPM_BUILD_ROOT ROOT=%{python3_sitelib} \
    MANDIR=%{_mandir}
%endif

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

%files
%defattr(-,root,root,-)
%doc COPYING
%dir %{_sysconfdir}/sysconfig/rhn
%dir %{_sysconfdir}/sysconfig/rhn/clientCaps.d
%config(noreplace)  %{_sysconfdir}/sysconfig/rhn/clientCaps.d/kickstart
%{_sbindir}/*

%if 0%{?build_py2}
%files -n python2-%{name}
%defattr(-,root,root,-)
%dir %{python_sitelib}/rhn
%{python_sitelib}/spacewalkkoan/
%{python_sitelib}/rhn/actions/
%if 0%{?suse_version}
%dir %{python_sitelib}/rhn
%endif
%endif

%if 0%{?build_py3}
%files -n python3-%{name}
%defattr(-,root,root,-)
%dir %{python3_sitelib}/rhn
%{python3_sitelib}/spacewalkkoan/
%{python3_sitelib}/rhn/actions/
%if 0%{?suse_version}
%dir %{python3_sitelib}/rhn
%endif
%endif

%changelog
07070100000011000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000001D00000000spacewalk-koan/spacewalkkoan07070100000012000081B40000000000000000000000015FB636EB000000C5000000000000000000000000000000000000002600000000spacewalk-koan/spacewalkkoan/MakefileTOP         = ..
ROOT        = /usr/share/rhn
SUBDIR      = spacewalkkoan
FILES       = __init__ \
                          spacewalkkoan \

# now include some Macros
include $(TOP)/Makefile.defs
07070100000013000081B40000000000000000000000015FB636EB00000266000000000000000000000000000000000000002900000000spacewalk-koan/spacewalkkoan/__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.
#

07070100000014000081B40000000000000000000000015FB636EB00003F60000000000000000000000000000000000000002E00000000spacewalk-koan/spacewalkkoan/spacewalkkoan.py#
# Copyright (c) 2008--2016 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.
#
# Kickstart a system using koan.
#

import traceback
import stat
import shutil
import sys
import os
import os.path
import tempfile

if sys.version_info[0] == 3:
    import xmlrpc.client as xmlrpclib
else:
    import xmlrpclib

from koan.app import Koan

SHADOW      = "/tmp/ks-tree-shadow"

def execute(cmd):
    tmp = tempfile.mktemp()
    status = os.system(cmd + " > " + tmp)
    data = open(tmp).readlines()
    ret = []
    for l in data:
        ret.append(l.strip())
    if status == 0:
        return ret
    raise Exception('Error executing command:\n %s\noutput:\n%s' % (cmd, '\n'.join(ret)))

def find_host_name():
    return execute("hostname")[0]

def find_netmask(device):
    try:
        nm = execute("LANG=C ipcalc -4ms $(ip -4 -o addr show dev %s | awk '{print $4}')|awk -F= '{print $2}'" % device)
    except:
        nm = execute("LANG=C ip -4 -o addr show dev %s | perl -lne 'print $1 if m!/(.+) brd!'" % device)
    if nm:
        return nm[0]
    else:
        return ""

def find_netmask6(device):
    nm6 = execute("LANG=C ip -6 -o addr show dev %s | perl -lne 'print $1 if m!/(.+) scope global!'" % device)
    if nm6:
        return nm6[0]
    else:
        return ""

def find_ip(device):
    ip = execute("LANG=C ip -4 -o addr show dev %s | perl -lne 'print $1 if m!.+\s(.+)/.+ scope global!'" % device)
    if ip:
        return ip[0]
    else:
        return ""

def find_ip6(device):
    ip6 = execute("LANG=C ip -6 -o addr show dev %s | perl -lne 'print $1 if m!.+\s(.+)/.+ scope global!'" % device)
    if ip6:
        return ip6[0]
    else:
        return ""

def find_name_servers():
    servers = execute("cat /etc/resolv.conf | perl -lne '/^nameserver\s+(\S+)/ and print $1'")
    ret = []
    for s in servers:
        if s not in ("127.0.0.1", "::1"):
            ret.append(s)
    return ret

def find_gateway(device):
    response = execute("ip -f inet route list dev %s|awk '/^default/ {print $3}'" % device)
    if response:
        return response[0]
    else:
        return ""

def find_gateway6(device):
    response = execute("ip -f inet6 route list dev %s|awk '/^default/ {print $3}'" % device)
    if response:
        return response[0]
    else:
        return ""

def getSystemId():
    path = "/etc/sysconfig/rhn/systemid"
    if not os.access(path, os.R_OK):
        return None
    return open(path, "r").read()

def getInitrdPath():
    path = '/boot/initrd.img'
    if os.access(path + "_koan", os.R_OK):
        return path + "_koan"
    return path

def update_static_device_records(kickstart_host, static_device):
    client = xmlrpclib.Server("https://" + kickstart_host + "/rpc/api")
    data = {"gateway" : find_gateway(static_device),\
            "nameservers": find_name_servers(),\
            "hostname" : find_host_name(),\
            "device" :  static_device,\
            "ip": find_ip(static_device),\
            "netmask" : find_netmask(static_device)}

    data6 = {"gateway" : find_gateway6(static_device), \
             "device" : static_device, \
             "ip" : find_ip6(static_device), \
             "netmask" : find_netmask6(static_device)}

    api_version = client.api.get_version()

    # Since api_version >= 11.1 we support setup_static_network with IPv6 data
    if float(api_version) <= 11.00:
        client.system.setup_static_network(getSystemId(), data)
    else:
        client.system.setup_static_network(getSystemId(), data, data6)

def initiate(kickstart_host, base, extra_append, static_device=None, system_record="", preserve_files=[]):

    error_messages = {}
    success = 0

    # cleanup previous attempt
    rm_rf(SHADOW)
    os.mkdir(SHADOW)

    print("Preserve files! : %s"  % preserve_files)

    try:
        if static_device:
            update_static_device_records(kickstart_host, static_device)

        k = Koan()
        k.list_items          = 0
        k.server              = kickstart_host
        k.is_virt             = 0
        k.is_replace          = 1
        k.is_display          = 0
        k.profile             = None
        if static_device:
           k.static_interface    = static_device

        if system_record != "":
           k.system          = system_record
        else:
           k.system          = None
        k.port                = 443
        k.image               = None
        k.live_cd             = None
        k.virt_path           = None
        k.virt_type           = None
        k.virt_bridge         = None
        k.no_gfx              = 0
        if hasattr(k, 'gfx_type'):
            k.gfx_type        = 'vnc'
        k.add_reinstall_entry = None
        k.kopts_override      = None
        k.use_kexec           = None
        k.embed_kickstart = k.embed_autoinst =  None
        if hasattr(k, 'no_copy_default'):
            k.no_copy_default = 1
        else: # older koan
            k.grubby_copy_default = 0
        if static_device:
            k.embed_kickstart = k.embed_autoinst = 1
        k.run()

    except Exception:
        (xa, xb, tb) = sys.exc_info()
        try:
            getattr(xb, "from_koan")
            error_messages['koan'] = str(xb)[1:-1]
            print(str(xb)[1:-1])  # nice exception, no traceback needed
        except:
            print(xa)
            print(xb)
            print(" ".join(traceback.format_list(traceback.extract_tb(tb))))
            error_messages['koan'] = " ".join(traceback.format_list(traceback.extract_tb(tb)))
        return (1, "Kickstart failed. Koan error.", error_messages)

    # Now process preserve_files if there are any
    initrd = getInitrdPath()
    if preserve_files:
        ret = create_new_rd(initrd, preserve_files)
        if ret:
            # Error
            return ret
        initrd = initrd + ".merged"



    return (0, "Kickstart initiate succeeded", error_messages)


class VirtDiskPathExistsError(Exception):
    def __init__(self, disk_path):
        self.value = disk_path
    def __str__(self):
        return "Virt Disk Path %s already exists on the host system. Please provide another disk path for the virt guest and reschedule your guest kickstart." % self.value


class BlockDeviceNonexistentError(Exception):
    def __init__(self, device_path):
        self.value = device_path
    def __str__(self):
        return "Block Device Path %s does not exist on the host system. Please create the device for the virtual guest and reschedule your guest kickstart." % self.value


def initiate_guest(kickstart_host, cobbler_system_name, virt_type, name, mem_kb,
                   vcpus, disk_gb, virt_bridge, disk_path, extra_append, log_notify_handler=None):

    error_messages = {}
    success = 0
    try:
        if disk_path.startswith('/dev/'):
            if not os.path.exists(disk_path):
               raise BlockDeviceNonexistentError(disk_path)
        else:
            if os.path.exists(disk_path):
                raise VirtDiskPathExistsError(disk_path)
        # Switch to KVM if possible
        if virt_type == "qemu":
            if os.path.exists("/dev/kvm"):
                virt_type = "kvm"
            else:
                print("Warning: KVM not available, using QEMU.")
        k = Koan()
        k.list_items          = 0
        k.server              = kickstart_host
        k.is_virt             = 1
        k.is_replace          = 0
        k.is_display          = 0
        k.port                = 443
        k.profile             = None
        k.system              = cobbler_system_name
        k.should_poll         = 1
        k.image               = None
        k.live_cd             = None
        k.virt_name           = name
        k.virt_path           = disk_path
        k.virt_type           = virt_type
        k.virt_bridge         = virt_bridge
        k.no_gfx              = False
        k.add_reinstall_entry = None
        k.kopts_override      = None
        k.virt_auto_boot      = None
        if hasattr(k, 'no_copy_default'):
            k.no_copy_default = 1
        else: # older koan
            k.grubby_copy_default = 0
        if hasattr(k, 'virtinstall_wait'):
            k.virtinstall_wait = 0
        k.run()

        # refresh current virtualization state on the server
        import virtualization.support
        virtualization.support.refresh()
    except Exception:
        (xa, xb, tb) = sys.exc_info()
        if str(xb).startswith("The MAC address you entered is already in use"):
            # I really wish there was a better way to check for this
            error_messages['koan'] = str(xb)
            print(str(xb))
        elif hasattr(xb, "from_koan") and len(str(xb)) > 1:
            error_messages['koan'] = str(xb)[1:-1]
            print(str(xb)[1:-1])  # nice exception, no traceback needed
        else:
            print(xa)
            print(xb)
            print(" ".join(traceback.format_list(traceback.extract_tb(tb))))
            error_messages['koan'] = str(xb) + ' ' + " ".join(traceback.format_list(traceback.extract_tb(tb)))
        return (1, "Virtual kickstart failed. Koan error.", error_messages)

    return (0, "Virtual kickstart initiate succeeded", error_messages)

def create_new_rd(initrd, preserve_files=[]):
    """
    Returns None if everything went well, or a tuple
    (err_code, err_string, dict) if problems were found
    """
    if not initrd:
        return (3, "Kickstart create new init failed: initrd not found: %s" %
            initrd, {})

    # quota should be configurable from the UI
    quota = 1000000
    # lame naming below to use /tmp/ks-tres-shadow 2X
    # but needed to get it here the ks.cfg expects it
    preserve_shadow = SHADOW + SHADOW
    # new FileCopier class handles the dirty work of getting the
    # preserved file set copied w/ all permissions, owners, etc
    # kept intact and in the correct location
    c = FileCopier(preserve_files, preserve_shadow, quota=quota)
    try:
        c.copy()
    except QuotaExceeded:
        return (3, "Quota of %s bytes exceeded" % quota, {})

    (status, stdout, stderr) = my_popen([
        "/usr/sbin/merge-rd.sh", initrd, initrd, SHADOW])
    if status:
        return (status, 'Error creating the new RAM disk',
            _build_error(status, stdout, stderr))

    return None


def rm_rf(path):
    "Equivalent of rm -rf"
    # We need to make sure path exists
    if os.path.islink(path):
        # Broken links will be reported as non-existent
        os.unlink(path)
        return
    # Now make sure path exists before we call the recursive function
    if os.path.exists(path):
        return _remove_func(path)


def _remove_func(path):
    "Recursive function for rm -rf; will fail if path doesn't exist"
    if not os.path.isdir(path):
        # Attempt to remove the file/link/etc
        os.unlink(path)
        return

    # It's a directory!
    files = os.listdir(path)
    # We need to add the path since listdir only returns a relative path
    files = list(map(lambda x, p=path: os.path.join(p, x), files))
    # Recursive call
    map(_remove_func, files)
    # After we remove everything from this directory we can also remove
    # the directory
    os.rmdir(path)
    return

def my_popen(cmd):
    print("CMD: %s " % cmd)

    subproc = 1
    try:
        import subprocess
    except ImportError:
        #RHEL 4 (python 2.3) doesn't have subprocess
        import popen2
        subproc = 0

    if subproc:
        c = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE, close_fds=True, bufsize=-1)
        c.stdin.close()
        while 1:
            status = c.poll()
            if status is not None:
                # Save the exit code, we still have to read from
                # the pipes
                return status, c.stdout, c.stderr
    else:
        c = popen2.Popen3(cmd, capturestderr=1, bufsize=-1)
        c.tochild.close()

        while 1:
            status = c.poll()
            if os.WIFEXITED(status):
                # Save the exit code, we still have to read from
                # the pipes
                return os.WEXITSTATUS(status), c.fromchild, c.childerr

def _build_error(status, stdout, stderr):
    params = {
        'status'    : status,
        'stdout'    : stdout.read(),
        'stderr'    : stderr.read(),
    }
    return params


class FileCopier:
    """A class that copies a list of files/directories to the specified
    destination
    """
    def __init__(self, files, dest, quota=None):
        self.files = files
        self.dest = dest
        self.quota = quota
        self.current_quota = 0

    def copy(self):
        return self._copy(self.files)

    def _copy(self, files):
        assert(isinstance(files, list))
        for f in files:
            try:
                st = os.lstat(f)
            except OSError:
                # Ignore it
                continue

            st_mode = st[stat.ST_MODE]

            if stat.S_ISLNK(st_mode):
                self._copy_link(f, st)
            elif stat.S_ISDIR(st_mode):
                self._copy_dir(f, st)
            elif stat.S_ISREG(st_mode):
                self._copy_file(f, st)


    def _copy_file(self, f, st):
        # Check quota first
        file_size = st[stat.ST_SIZE]
        self._check_quota(f, file_size)
        self._create_dirs(f)

        # Now copy the file
        dest = self._build_dest(f)
        shutil.copy2(f, dest)
        self._copy_perms(dest, st)
        # Update space usage
        self._update_quota(f, file_size)


    def _check_quota(self, f, file_size):
        if not self.quota:
            return
        # Quota enabled
        if self.current_quota + file_size > self.quota:
            raise QuotaExceeded(f)


    def _update_quota(self, f, file_size):
        self.current_quota = self.current_quota + file_size


    def _create_dirs(self, f):
        dirname = os.path.dirname(f)
        self._copy_dir_modes(dirname, self.dest)


    def _copy_perms(self, dest, st):
        os.chmod(dest, st[stat.ST_MODE])
        os.chown(dest, st[stat.ST_UID], st[stat.ST_GID])
        os.utime(dest, (st[stat.ST_ATIME], st[stat.ST_MTIME]))


    def _copy_dir(self, f, st):
        files = list(map(lambda x, d=f: os.path.join(d, x), os.listdir(f)))
        # Create this directory since it may be empty
        self._copy_dir_modes(f, self.dest)
        return self._copy(files)


    def _copy_link(self, f, st):
        file_size = st[stat.ST_SIZE]
        self._check_quota(f, file_size)
        deref_link = os.readlink(f)
        self._create_dirs(f)

        # Create the symlink
        dest = self._build_dest(f)
        os.symlink(deref_link, dest)

        self._update_quota(f, file_size)


    def _build_dest(self, f):
        return os.path.normpath(self.dest + f)


    def _copy_dir_modes(self, srcdir, dest):
        if not os.path.exists(dest):
            os.makedirs(dest)
        l = []
        srcdir = os.path.normpath(srcdir)
        while 1:
            h, t = os.path.split(srcdir)
            if not t:
                break
            l.append(t)
            srcdir = h

        l.reverse()
        dest_dir = dest
        src_dir = os.sep
        for d in l:
            src_dir = os.path.join(src_dir, d)
            src_st = os.lstat(src_dir)
            dest_dir = os.path.join(dest_dir, d)
            if not os.path.exists(dest_dir):
                os.mkdir(dest_dir)
            os.chmod(dest_dir, src_st[stat.ST_MODE])
            os.chown(dest_dir, src_st[stat.ST_UID], src_st[stat.ST_GID])

class QuotaExceeded(Exception):
    pass
07070100000015000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000001400000000spacewalk-koan/test07070100000016000081B40000000000000000000000015FB636EB00000000000000000000000000000000000000000000002000000000spacewalk-koan/test/__init__.py07070100000017000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000001D00000000spacewalk-koan/test/fixtures07070100000018000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000002C00000000spacewalk-koan/test/fixtures/ks-tree-shadow07070100000019000041FD0000000000000000000000015FB636EB00000000000000000000000000000000000000000000003800000000spacewalk-koan/test/fixtures/ks-tree-shadow/susemanager0707010000001A000081B40000000000000000000000015FB636EB00000028000000000000000000000000000000000000004200000000spacewalk-koan/test/fixtures/ks-tree-shadow/susemanager/test_fileThis should be part of the final initrd
0707010000001B000081B40000000000000000000000015FB636EB0000041C000000000000000000000000000000000000001E00000000spacewalk-koan/test/helper.py# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
#   This library is free software; you can redistribute it and/or modify
# it only under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
#   This library 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 Lesser General Public License for more
# details.
#
#   You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA


import os

def read_data_from_fixture(filename):
    with open(path_to_fixture(filename), 'r') as file:
        return file.read()


def path_to_fixture(filename):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        "fixtures", filename)



0707010000001C000081B40000000000000000000000015FB636EB00001ECB000000000000000000000000000000000000002500000000spacewalk-koan/test/test_merge_rd.py#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
#   This library is free software; you can redistribute it and/or modify
# it only under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
#   This library 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 Lesser General Public License for more
# details.
#
#   You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

try:
    import unittest2 as unittest
except ImportError:
    import unittest
import shutil
import os
import tempfile
from spacewalkkoan.spacewalkkoan import my_popen
from . import helper

MERGE_RD_CMD = os.path.join(
    os.path.dirname(os.path.realpath(__file__)),
    "..", "merge-rd.sh"
)

class MergeRdTest(unittest.TestCase):

    def setUp(self):
        self.data_dir = tempfile.mkdtemp("", "spacewalkkoan")
        self.initrd_xz = "/root/initrd.xz"
        self.final_initrd = os.path.join(self.data_dir, "initrd.gz")

    def tearDown(self):
        shutil.rmtree(self.data_dir)

    def test_should_fail_when_tar_is_not_installed(self):
        self.ensure_package_is_not_installed("tar")
        self.ensure_package_is_installed("xz")
        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            self.initrd_xz,
            self.final_initrd,
            helper.path_to_fixture("ks-tree-shadow/")
        ])

        errors = b"".join(stderr.readlines()).decode()

        self.assertNotEqual(0, status)
        if not "tar: command not found" in errors:
            self.fail("Command failed for a different reason: {0}".format(errors))

    def test_should_fail_when_xz_is_not_installed(self):
        self.ensure_package_is_not_installed("xz")
        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            self.initrd_xz,
            self.final_initrd,
            helper.path_to_fixture("ks-tree-shadow/")
        ])

        errors = b"".join(stderr.readlines()).decode()

        self.assertNotEqual(0, status)
        if not "Error uncompressing" in errors:
            self.fail("Command failed for a different reason: {0}".format(errors))

    def test_should_fail_when_the_initrd_is_not_a_valid_file(self):
        (status, stdout, stderr) = my_popen(["touch", "/etc/fstab"])
        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            "/etc/fstab",
            self.final_initrd,
            helper.path_to_fixture("ks-tree-shadow/")
        ])

        errors = b"".join(stderr.readlines()).decode()

        self.assertNotEqual(0, status)
        if not "Error uncompressing" in errors:
            self.fail("Command failed for a different reason: {0}".format(errors))

    def test_should_fail_when_the_initrd_is_not_found(self):
        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            "/fake_initrd",
            self.final_initrd,
            helper.path_to_fixture("ks-tree-shadow/")
        ])

        errors = b"".join(stderr.readlines()).decode()

        self.assertNotEqual(0, status)
        if not "Cannot find initrd" in errors:
            self.fail("Command failed for a different reason: {0}".format(errors))

    def test_should_fail_when_directory_containing_final_initrd_does_not_exist(self):
        self.ensure_package_is_installed("tar", "xz")
        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            self.initrd_xz,
            "/new_dir/initrd.out",
            helper.path_to_fixture("ks-tree-shadow/")
        ])

        errors = b"".join(stderr.readlines()).decode()

        self.assertNotEqual(0, status)
        if not "Cannot find final destination dir" in errors:
            self.fail("Command failed for a different reason: {0}".format(errors))

    def test_should_fail_when_the_user_tree_directory_is_missing(self):
        self.ensure_package_is_installed("tar", "xz")
        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            self.initrd_xz,
            self.final_initrd,
            "/does/not/exist/ks-tree-shadow/"
        ])

        errors = b"".join(stderr.readlines()).decode()

        self.assertNotEqual(0, status)
        if not "Cannot find user tree" in errors:
            self.fail("Command failed for a different reason: {0}".format(errors))

    def test_should_create_a_new_initrd_starting_from_a_xz_compressed_one(self):
        self.ensure_package_is_installed("tar", "xz")
        self.ensure_package_is_installed("xz")

        (status, stdout, stderr) = my_popen([
            "/bin/sh",
            MERGE_RD_CMD,
            self.initrd_xz,
            self.final_initrd,
            helper.path_to_fixture("ks-tree-shadow/")
        ])

        # ensure the new initrd has been created
        errors = b"".join(stderr.readlines()).decode()
        self.assertEqual(0, status,
            "Something wrong happened: {0}".format(errors))
        self.assertTrue(os.path.exists(self.final_initrd))

        # ensure the new initrd is compressed using gzip
        (status, stdout, stderr) = my_popen([
            "file",
            self.final_initrd,
        ])
        errors = b"".join(stderr.readlines()).decode()
        self.assertEqual(0, status,
            "Something wrong happened: {0}".format(errors))
        self.assertTrue("gzip compressed data" in b"".join(stdout.readlines()).decode())

        # uncompress the initrd
        (status, stdout, stderr) = my_popen([
            "gzip", "-d", self.final_initrd 
        ])
        errors = b"".join(stderr.readlines()).decode()
        self.assertEqual(0, status,
            "Something wrong happened: {0}".format(errors))

        # extract the contents of the initrd
        uncomp_dir = os.path.join(self.data_dir, "uncompressed")
        os.mkdir(uncomp_dir)

        os.chdir(uncomp_dir)
        (status, stdout, stderr) = my_popen([
            "cpio", "-idF", self.final_initrd.replace(".gz", "")
        ])
        errors = b"".join(stderr.readlines()).decode()
        self.assertEqual(0, status,
            "Something wrong happened: {0}".format(errors))

        test_file = os.path.join(
            uncomp_dir, "susemanager", "test_file")
        self.assertTrue(os.path.exists(test_file))

        expected_data = helper.read_data_from_fixture("ks-tree-shadow/susemanager/test_file")
        with open(test_file) as file:
            self.assertEqual(
                file.read(),
                expected_data
            )

        # the "uncomp_dir" is going to be removed at the end of the tests
        os.chdir("/")


    def ensure_package_is_installed(self, *pkgs):
        cmd = ["zypper", "in", "-y"]
        for pkg in pkgs:
            cmd.append(pkg)

        (status, stdout, stderr) = my_popen(cmd)

        if status != 0:
            self.fail(
                "Something went wrong while ensuring {0} was "
                "installed: {1}".format(pkg, b"".join(stderr.readlines()).decode())
            )

    def ensure_package_is_not_installed(self, *pkgs):
        cmd = ["zypper", "rm", "-y"]
        for pkg in pkgs:
            cmd.append(pkg)

        (status, stdout, stderr) = my_popen(cmd)

        if status != 0:
            self.fail(
                "Something went wrong while ensuring {0} was not "
                "installed: {1}".format(pkg, b"".join(stderr.readlines()).decode())
            )

07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!
openSUSE Build Service is sponsored by