Beispiel #1
0
def update(serverId, actionId, dry_run=0):
    log_debug(3)
    statement = """
        select r1.errata_id, r2.allow_vendor_change, e.advisory_status
        from rhnactionerrataupdate r1
        join rhnErrata e on r1.errata_id = e.id
        left join rhnactionpackagedetails r2 on r1.action_id = r2.action_id
        where r1.action_id = :action_id
    """
    h = rhnSQL.prepare(statement)
    h.execute(action_id=actionId)
    ret = h.fetchall_dict()
    if not ret:
        # No errata for this action
        raise InvalidAction("errata.update: Unknown action id "
                            "%s for server %s" % (actionId, serverId))

    retracted = [
        x['errata_id'] for x in ret if x['advisory_status'] == 'retracted'
    ]
    if retracted:
        # Do not install retracted patches
        raise InvalidAction(
            "errata.update: Action contains retracted errata %s" % retracted)
    if ret[0]['allow_vendor_change'] is None or ret[0][
            'allow_vendor_change'] is False:
        return [x['errata_id'] for x in ret]

    return {
        "errata_ids": [x['errata_id'] for x in ret],
        "allow_vendor_change": (ret[0]['allow_vendor_change'] == 'Y')
    }
Beispiel #2
0
def schedule_virt_guest_pkg_install(server_id, action_id, dry_run=0):
    """
        ShadowAction that schedules a package installation action for the
        rhn-virtualization-guest package.
    """
    log_debug(3)

    virt_host_package_name = "rhn-virtualization-guest"
    tools_channel = SubscribedChannel(server_id, "rhn-tools")
    found_tools_channel = tools_channel.is_subscribed_to_channel()

    if not found_tools_channel:
        raise InvalidAction("System not subscribed to the RHN Tools channel.")

    rhn_v12n_package = ChannelPackage(server_id, virt_host_package_name)

    if not rhn_v12n_package.exists():
        raise InvalidAction(
            "Could not find the rhn-virtualization-guest package.")

    try:
        install_scheduler = PackageInstallScheduler(server_id, action_id,
                                                    rhn_v12n_package)
        if (not dry_run):
            install_scheduler.schedule_package_install()
        else:
            log_debug(4, "dry run requested")
    except NoActionInfo, nai:
        raise InvalidAction(str(nai)), None, sys.exc_info()[2]
Beispiel #3
0
def initiate(server_id, action_id, dry_run=0):
    log_debug(3)
    h = rhnSQL.prepare(_query_initiate_guest)
    h.execute(action_id=action_id)
    row = h.fetchone_dict()

    if not row:
        raise InvalidAction("Kickstart action without an associated kickstart")

    kickstart_host = row['kickstart_host']
    virt_type = row['virt_type']
    name = row['guest_name']
    boot_image = "spacewalk-koan"
    append_string = row['append_string']
    vcpus = row['vcpus']
    disk_gb = row['disk_gb']
    mem_kb = row['mem_kb']
    ks_session_id = row['ks_session_id']
    virt_bridge = row['virt_bridge']
    disk_path = row['disk_path']
    cobbler_system_name = row['cobbler_system_name']

    if not boot_image:
        raise InvalidAction("Boot image missing")

    return (kickstart_host, cobbler_system_name, virt_type, ks_session_id,
            name, mem_kb, vcpus, disk_gb, virt_bridge, disk_path,
            append_string)
Beispiel #4
0
def action(action_name, query, server_id, action_id, dry_run=0):
    log_debug(3, action_name, dry_run)
    try:
        uuid = _get_uuid(query, action_id)
    except NoRowFoundException:
        raise_with_tb(InvalidAction("No %s actions found." % action_name.lower()), sys.exc_info()[2])
    except NoUUIDException:
        raise_with_tb(InvalidAction("%s action %s has no uuid associated with it." %
                            (action_name, str(action_id))), sys.exc_info()[2])
    return (uuid,)
Beispiel #5
0
def handle_action(serverId, actionId, packagesIn, dry_run=0):
    log_debug(3, serverId, actionId, dry_run)

    client_caps = rhnCapability.get_client_capabilities()
    log_debug(3, "Client Capabilities", client_caps)
    multiarch = 0
    if client_caps and 'packages.update' in client_caps:
        cap_info = client_caps['packages.update']
        if cap_info['version'] > 1:
            multiarch = 1
    if not packagesIn:
        raise InvalidAction(
            "Packages scheduled in action %s for server %s could not be found."
            % (actionId, serverId))

    packages = []
    for package in packagesIn:
        # Fix the epoch
        if package['epoch'] is None:
            package['epoch'] = ""
        pkg_arch = ''
        if multiarch:
            pkg_arch = package['arch'] or ''

        packages.append([
            package['name'], package['version'] or '', package['release']
            or '', package['epoch'], pkg_arch
        ])

    log_debug(4, packages)
    return packages
Beispiel #6
0
def deploy(serverId, actionId, dry_run=0):
    log_debug(3)
    statement = """
        select aid.mem_kb, aid.vcpus, aid.bridge_device,aid.download_url,
               aid.proxy_server, aid.proxy_user, aid.proxy_pass
          from rhnActionImageDeploy aid
	   where aid.action_id = :action_id"""
    h = rhnSQL.prepare(statement)
    h.execute(action_id = actionId)
    row = h.fetchone_dict()
    if not row:
        # No image for this action
        raise InvalidAction("image.deploy: No image found for action id "
            "%s and server %s" % (actionId, serverId))

    for key in [ 'download_url', 'proxy_server', 'proxy_user', 'proxy_pass', 'bridge_device' ]:
        if row[key] == None:
            row[key] = ""

    params = {
        "downloadURL"   : row['download_url'],
        "proxySettings" : { "proxyURL" : row['proxy_server'], "proxyUser" : row['proxy_user'], "proxyPass" : row['proxy_pass'] },
        "memKB"         : row['mem_kb'],
        "vCPUs"         : row['vcpus'],
        "domainName"    : "",
        "virtBridge"    : row['bridge_device'] }
    return (params)
Beispiel #7
0
def rollback(serverId, actionId, dry_run=0):
    log_debug(3, dry_run)
    # since rhnActionTransactions table is gone, this call have to fail
    log_error("Invalid rollback.rollback action %s for server id %s" %
              (actionId, serverId))
    raise InvalidAction(
        "Invalid rollback.rollback action %s for server id %s" %
        (actionId, serverId))
Beispiel #8
0
def setVCPUs(server_id, action_id, dry_run=0):
    log_debug(3, dry_run)

    prepared_query = rhnSQL.prepare(_query_getVCPUs)
    prepared_query.execute(action_id=action_id)
    row = prepared_query.fetchone_dict()

    if not row:
        raise InvalidAction("No VCPU actions found.")

    return row['uuid'], row['vcpu']
Beispiel #9
0
def setMemory(server_id, action_id, dry_run=0):
    log_debug(3, dry_run)

    prepared_query = rhnSQL.prepare(_query_setMemory)
    prepared_query.execute(action_id=action_id)
    row = prepared_query.fetchone_dict()

    if not row:
        raise InvalidAction("No setMemory actions found.")

    if 'uuid' not in row:
        raise InvalidAction("Set Memory action %s has no uuid." % str(action_id))

    if 'memory' not in row:
        raise InvalidAction("setMemory action %s has no memory set." % str(action_id))

    uuid = row['uuid']
    memory = row['memory']

    return (uuid, memory)
Beispiel #10
0
def schedule_virt_guest_pkg_install(server_id, action_id, dry_run=0):
    """
        ShadowAction that schedules a package installation action for the
        rhn-virtualization-guest package.
    """
    log_debug(3)

    virt_host_package_name = "rhn-virtualization-guest"
    tools_channel = SubscribedChannel(server_id, "rhn-tools")
    found_tools_channel = tools_channel.is_subscribed_to_channel()

    if not found_tools_channel:
        raise InvalidAction("System not subscribed to the Tools channel.")

    rhn_v12n_package = ChannelPackage(server_id, virt_host_package_name)

    if not rhn_v12n_package.exists():
        raise InvalidAction(
            "Could not find the rhn-virtualization-guest package.")

    try:
        install_scheduler = PackageInstallScheduler(server_id, action_id,
                                                    rhn_v12n_package)
        if (not dry_run):
            install_scheduler.schedule_package_install()
        else:
            log_debug(4, "dry run requested")
    except NoActionInfo:
        nai = sys.exc_info()[1]
        raise_with_tb(InvalidAction(str(nai)), sys.exc_info()[2])
    except PackageNotFound:
        pnf = sys.exc_info()[1]
        raise_with_tb(InvalidAction(str(pnf)), sys.exc_info()[2])
    except Exception:
        e = sys.exc_info()[1]
        raise_with_tb(InvalidAction(str(e)), sys.exc_info()[2])

    log_debug(3, "Completed scheduling install of rhn-virtualization-guest!")
    raise ShadowAction(
        "Scheduled installation of Virtualization Guest packages.")
Beispiel #11
0
def schedulePoller(server_id, action_id, dry_run=0):
    log_debug(3, dry_run)

    prepared_query = rhnSQL.prepare(_query_schedulePoller)
    prepared_query.execute(action_id=action_id)
    row = prepared_query.fetchone_dict()

    if not row:
        raise InvalidAction("No schedulePoller actions found.")

    if 'minute' not in row:
        raise InvalidAction("schedulePoller action %s has no minute associated with it." % str(action_id))

    if 'hour' not in row:
        raise InvalidAction("schedulePoller action %s has no hour associated with it." % str(action_id))

    if 'dom' not in row:
        raise InvalidAction("schedulePoller action %s has no day of the month associated with it." % str(action_id))

    if 'month' not in row:
        raise InvalidAction("schedulePoller action %s has no month associated with it." % str(action_id))

    if 'dow' not in row:
        raise InvalidAction("schedulePoller action %s has no day of the week associated with it." % str(action_id))

    return (row['minute'], row['hour'], row['dom'], row['month'], row['dow'])
Beispiel #12
0
def initiate(server_id, action_id, dry_run=0):
    log_debug(3)
    h = rhnSQL.prepare(_query_initiate)
    h.execute(action_id=action_id)
    row = h.fetchone_dict()
    if not row:
        raise InvalidAction("Kickstart action without an associated kickstart")
    boot_image, append_string = ('spacewalk-koan', row['append_string'])
    static_device = row['static_device'] or ""
    kickstart_host = row['kickstart_host']
    system_record = row['cobbler_system_name']
    if system_record is None:
        system_record = ''
    if not boot_image:
        raise InvalidAction("Boot image missing")
    if not kickstart_host:
        raise InvalidAction("Kickstart_host missing")

    h = rhnSQL.prepare(_query_file_list_initiate)
    h.execute(action_id=action_id)
    files = [x['path'] for x in h.fetchall_dict() or []]

    return (kickstart_host, boot_image, append_string, static_device,
            system_record, files)
Beispiel #13
0
def refresh(server_id, action_id, dry_run=0):
    log_debug(3, dry_run)

    prepared_query = rhnSQL.prepare(_query_refresh)
    prepared_query.execute(action_id=action_id)
    row = prepared_query.fetchone_dict()

    if not row:
        raise NoRowFoundException()

    # Sanity check. If this doesn't pass then something is definitely screwed up.
    if not row['action_id']:
        raise InvalidAction("Refresh action is missing an action_id.")

    return ()
Beispiel #14
0
def update(serverId, actionId, dry_run=0):
    log_debug(3)
    statement = """
        select errata_id
        from rhnActionErrataUpdate
        where action_id = :action_id"""
    h = rhnSQL.prepare(statement)
    h.execute(action_id=actionId)
    ret = h.fetchall_dict()
    if not ret:
        # No errata for this action
        raise InvalidAction("errata.update: Unknown action id "
                            "%s for server %s" % (actionId, serverId))

    return map(lambda x: x['errata_id'], ret)
Beispiel #15
0
def xccdf_eval(server_id, action_id, dry_run=0):
    log_debug(3)
    statement = """
        select path, parameters
        from rhnActionScap
        where action_id = :action_id"""
    h = rhnSQL.prepare(statement)
    h.execute(action_id=action_id)
    d = h.fetchone_dict()
    if not d:
        raise InvalidAction("scap.xccdf_eval: Unknown action id "
            "%s for server %s" % (action_id, server_id))
    return ({
        'path': d['path'],
        'id': action_id,
        'file_size': _scap_file_limit(server_id),
        'params': rhnSQL.read_lob(d['parameters']) or ''
        },)
Beispiel #16
0
 def __getV1(self, action):
     """ Fetches old queued actions for the client version 1. """
     log_debug(3, self.server_id)
     actionId = action['id']
     method = action["method"]
     if method == 'packages.update':
         xml = self.__packageUpdate(actionId)
     elif method == 'errata.update':
         xml = self.__errataUpdate(actionId)
     elif method == 'hardware.refresh_list':
         xml = xmlrpclib.dumps(("hardware",), methodname="client.refresh")
     elif method == 'packages.refresh_list':
         xml = xmlrpclib.dumps(("rpmlist",), methodname="client.refresh")
     else:  # Unrecognized, skip
         raise InvalidAction("Action method %s unsupported by "
                             "Update Agent Client" % method)
     # all good
     return {'id': actionId, 'version': 1, 'action': xml}
Beispiel #17
0
def verify(serverId, actionId, dry_run=0):
    log_debug(3, dry_run)
    h = rhnSQL.prepare(_query_action_verify_packages)
    h.execute(actionid=actionId)
    tmppackages = h.fetchall_dict()

    if not tmppackages:
        raise InvalidAction("invalid action %s for server %s" %
                            (actionId, serverId))

    packages = []

    for package in tmppackages:

        packages.append([
            package['name'], package['version'], package['release'],
            package['epoch'] or '', package['arch'] or ''
        ])
    log_debug(4, packages)
    return packages
Beispiel #18
0
def setLocks(serverId, actionId, dry_run=0):
    log_debug(3, serverId, actionId, dry_run)

    client_caps = rhnCapability.get_client_capabilities()
    log_debug(3, "Client Capabilities", client_caps)
    multiarch = 0
    if not client_caps or not client_caps.has_key('packages.setLocks'):
        raise InvalidAction("Client is not capable of locking packages.")

    h = rhnSQL.prepare(_query_action_setLocks)
    h.execute(actionid=actionId, serverid=serverId)
    tmppackages = h.fetchall_dict() or {}

    packages = []

    for package in tmppackages:
        packages.append([
            package['name'], package['version'], package['release'],
            package['epoch'] or '', package['arch'] or ''
        ])
    log_debug(4, packages)
    return packages
Beispiel #19
0
def update(serverId, actionId, dry_run=0):
    log_debug(3)
    statement = """
        select r1.errata_id, r2.allow_vendor_change
        from rhnactionerrataupdate r1
        left join rhnactionpackagedetails r2 on r1.action_id = r2.action_id
        where r1.action_id = :action_id
    """
    h = rhnSQL.prepare(statement)
    h.execute(action_id=actionId)
    ret = h.fetchall_dict()
    if not ret:
        # No errata for this action
        raise InvalidAction("errata.update: Unknown action id "
                            "%s for server %s" % (actionId, serverId))

    if ret[0]['allow_vendor_change'] is null or ret[0][
            'allow_vendor_change'] is False:
        return [x['errata_id'] for x in ret]

    return {
        "errata_ids": [x['errata_id'] for x in ret],
        "allow_vendor_change": (ret[0]['allow_vendor_change'] == 'Y')
    }
Beispiel #20
0
def runTransaction(server_id, action_id, dry_run=0):
    log_debug(3, server_id, action_id, dry_run)

    # Fetch package_delta_id
    h = rhnSQL.prepare("""
        select package_delta_id
        from rhnActionPackageDelta
        where action_id = :action_id
    """)
    h.execute(action_id=action_id)
    row = h.fetchone_dict()
    if row is None:
        raise InvalidAction(
            "invalid packages.runTransaction action %s for server %s" %
            (action_id, server_id))

    package_delta_id = row['package_delta_id']

    # Fetch packages
    h = rhnSQL.prepare("""
        select tro.label as operation, pn.name, pe.version, pe.release, pe.epoch,
               pa.label as package_arch
          from rhnPackageDeltaElement pde,
               rhnTransactionPackage rp
     left join rhnPackageArch pa
            on rp.package_arch_id = pa.id,
               rhnTransactionOperation tro, rhnPackageName pn, rhnPackageEVR pe
         where pde.package_delta_id = :package_delta_id
           and pde.transaction_package_id = rp.id
           and rp.operation = tro.id
           and rp.name_id = pn.id
           and rp.evr_id = pe.id
        order by tro.label, pn.name
    """)
    h.execute(package_delta_id=package_delta_id)

    result = []
    while 1:
        row = h.fetchone_dict()
        if not row:
            break

        operation = row['operation']

        # Need to map the operations into codes the client/rpm understands
        if operation == 'insert':
            operation = 'i'
        elif operation == 'delete':
            operation = 'e'
        elif operation == 'upgrade':
            operation = 'u'
        else:
            # Unsupported
            continue

        # Fix null epochs
        epoch = row['epoch']
        if epoch is None:
            epoch = ''

        name, version, release = row['name'], row['version'], row['release']
        # The package arch can be null now because of the outer join
        package_arch = row['package_arch'] or ""

        result.append([[name, version, release, epoch, package_arch],
                       operation])
    return {'packages': result}
Beispiel #21
0
def upgrade(serverId, actionId, dry_run=0):
    log_debug(3)

    if dry_run:
        # can happen if future actions are requested
        raise ShadowAction("dry run requested - skipping")

    h = rhnSQL.prepare(_query_dup_data)
    h.execute(action_id=actionId)
    row = h.fetchone_dict()
    if not row:
        # No dup for this action
        raise InvalidAction(
            "distupgrade.upgrade: No action found for action id "
            "%s and server %s" % (actionId, serverId))

    action_dup_id = row['id']

    # get product info

    h = rhnSQL.prepare(_query_products)
    h.execute(action_dup_id=action_dup_id)
    products = h.fetchall_dict() or []

    # only SLE10 products needs to be changed manually
    # remove all not SLE10 based products

    sle10_products = []
    do_change = False
    for product in products:
        if product['version'] == '10':
            do_change = True
            sle10_products.append(product)

    # switch the channels for this server

    h = rhnSQL.prepare(_query_channel_changes)
    h.execute(action_dup_id=action_dup_id)
    channel_changes = h.fetchall_dict() or None

    if not channel_changes:
        # this happens in case a distupgrade failed and the
        # another distupgrade is scheduled to fix the installation
        # we do not have the original channels anymore, so we need
        # to execute a full "dup" without channels
        params = {
            "full_update": (row['full_update'] == 'Y'),
            "change_product": do_change,
            "products": sle10_products,
            "dry_run": (row['dry_run'] == 'Y')
        }
        return (params)

    to_subscribe = filter(lambda x: x['task'] == 'S', channel_changes)
    to_unsubscribe = filter(lambda x: x['task'] == 'U', channel_changes)

    try:
        unsubscribe_channels(serverId, to_unsubscribe)
        subscribe_channels(serverId, to_subscribe)
    except rhnFault, f:
        if f.code == 38:
            # channel is already subscribed, ignore it
            pass
        else:
            raise InvalidAction(str(f)), None, sys.exc_info()[2]
Beispiel #22
0
    if not rhn_v12n_package.exists():
        raise InvalidAction(
            "Could not find the rhn-virtualization-guest package.")

    try:
        install_scheduler = PackageInstallScheduler(server_id, action_id,
                                                    rhn_v12n_package)
        if (not dry_run):
            install_scheduler.schedule_package_install()
        else:
            log_debug(4, "dry run requested")
    except NoActionInfo, nai:
        raise InvalidAction(str(nai)), None, sys.exc_info()[2]
    except PackageNotFound, pnf:
        raise InvalidAction(str(pnf)), None, sys.exc_info()[2]
    except Exception, e:
        raise InvalidAction(str(e)), None, sys.exc_info()[2]

    log_debug(3, "Completed scheduling install of rhn-virtualization-guest!")
    raise ShadowAction(
        "Scheduled installation of RHN Virtualization Guest packages.")


def initiate(server_id, action_id, dry_run=0):
    log_debug(3)
    h = rhnSQL.prepare(_query_initiate_guest)
    h.execute(action_id=action_id)
    row = h.fetchone_dict()

    if not row:
Beispiel #23
0
def schedule_sync(server_id, action_id, dry_run=0):
    log_debug(3, server_id, action_id)
    if dry_run:
        raise ShadowAction("dry run requested - skipping")

    kickstart_session_id = server_kickstart.get_kickstart_session_id(
        server_id, action_id)

    if kickstart_session_id is None:
        raise InvalidAction("Could not find kickstart session ID")

    row = server_kickstart.get_kickstart_session_info(kickstart_session_id,
                                                      server_id)
    deploy_configs = (row['deploy_configs'] == 'Y')

    ks_package_profile = server_kickstart.get_kisckstart_session_package_profile(
        kickstart_session_id)
    # if the session doesn't have a pkg profile, try from the ks profile itself
    if not ks_package_profile:
        ks_package_profile = server_kickstart.get_kickstart_profile_package_profile(
            kickstart_session_id)

    if not ks_package_profile:
        log_debug(4, "No kickstart package profile")
        # No profile to bring this system to
        if deploy_configs:
            # We have to deploy configs, so pass in a server profile
            server_profile = server_kickstart.get_server_package_profile(
                server_id)
        else:
            # No configs to be deployed
            server_profile = None

        server_kickstart.schedule_config_deploy(server_id,
                                                action_id,
                                                kickstart_session_id,
                                                server_profile=server_profile)
        raise ShadowAction(
            "Package sync not scheduled, missing kickstart "
            "package profile; proceeding with configfiles.deploy")

    server_profile = server_kickstart.get_server_package_profile(server_id)

    installs, removes = server_packages.package_delta(server_profile,
                                                      ks_package_profile)

    if not (installs or removes):
        log_debug(4, "No packages to be installed/removed")
        if not deploy_configs:
            server_profile = None

        server_kickstart.schedule_config_deploy(server_id,
                                                action_id,
                                                kickstart_session_id,
                                                server_profile=None)
        raise ShadowAction("Package sync not scheduled, nothing to do")

    log_debug(4, "Scheduling kickstart delta")
    server_kickstart.schedule_kickstart_delta(server_id, kickstart_session_id,
                                              installs, removes)

    raise ShadowAction("Package sync scheduled")