def promote(target_env, ver_list, ver_descr, ver_version, env_list, prior_list, dry_run):
    """Promote Content View"""
    target_env_id = env_list[target_env]
    source_env_id = prior_list[target_env_id]

    # Extract the name of the source environment so we can inform the user
    for key, val in env_list.items():
        if val == source_env_id:
            prior_env = key

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Promotion from " + prior_env + " to " + target_env

    # Now we have all the info needed, we can actually trigger the promotion.
    # Loop through each CV with promotable versions
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching promotion criteria
    if not ver_list:
        msg = "No content view versions found matching promotion criteria"
        helpers.log_msg(msg, 'WARNING')
        sys.exit(1)

    for cvid in ver_list.keys():

        # Check if there is a publish/promote already running on this content view
        locked = helpers.check_running_publish(cvid, ver_descr[cvid])

        if not locked:
            msg = "Promoting '" + str(ver_descr[cvid]) + "' Version " + str(ver_version[cvid]) +\
                " from " + prior_env + " to " + str(target_env)
            helpers.log_msg(msg, 'INFO')
            print helpers.HEADER + msg + helpers.ENDC

        if not dry_run and not locked:
            try:
                task_id = helpers.post_json(
                    helpers.KATELLO_API + "content_view_versions/" + str(ver_list[cvid]) +\
                    "/promote/", json.dumps(
                        {
                            "environment_id": target_env_id
                        }
                        ))["id"]
            except Warning:
                msg = "Failed to initiate promotion of " + str(ver_descr[cvid])
                helpers.log_msg(msg, 'WARNING')
            else:
                task_list.append(task_id)
                ref_list[task_id] = ver_descr[cvid]

    # Exit in the case of a dry-run
    if dry_run:
        msg = "Dry run - not actually performing promotion"
        helpers.log_msg(msg, 'WARNING')
        sys.exit(2)


    return task_list, ref_list, task_name
Пример #2
0
def publish(ver_list, ver_descr, ver_version, dry_run, runuser):
    """Publish Content View"""

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Publish content view to Library"

    # Now we have all the info needed, we can actually trigger the publish.
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching publish criteria
    if not ver_list:
        msg = "No content view versions found matching publication criteria"
        helpers.log_msg(msg, 'ERROR')
        sys.exit(1)

    for cvid in ver_list.keys():

        # Check if there is a publish/promote already running on this content view
        locked = helpers.check_running_publish(ver_list[cvid], ver_descr[cvid])

        if not locked:
            msg = "Publishing '" + str(ver_descr[cvid]) + "' Version " + str(ver_version[cvid]) + ".0"
            helpers.log_msg(msg, 'INFO')
            print helpers.HEADER + msg + helpers.ENDC

        # Set up the description that will be added to the published version
        description = "Published by " + runuser + "\n via API script"

        if not dry_run and not locked:
            try:
                task_id = helpers.post_json(
                    helpers.KATELLO_API + "content_views/" + str(ver_list[cvid]) +\
                    "/publish", json.dumps(
                        {
                            "description": description
                        }
                        ))["id"]
            except Warning:
                msg = "Failed to initiate publication of " + str(ver_descr[cvid])
                helpers.log_msg(msg, 'WARNING')
            else:
                task_list.append(task_id)
                ref_list[task_id] = ver_descr[cvid]

    # Exit in the case of a dry-run
    if dry_run:
        msg = "Dry run - not actually performing publish"
        helpers.log_msg(msg, 'WARNING')
        sys.exit(2)


    return task_list, ref_list, task_name
Пример #3
0
def cleanup(ver_list, ver_descr, dry_run, runuser, ver_keep, cleanall,
            ignorefirstpromoted):
    """Clean Content Views"""

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Cleanup content views"

    # Now we have all the info needed, we can actually trigger the cleanup.
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching cleanup criteria
    if not ver_list:
        msg = "No content view versions found matching cleanup criteria"
        helpers.log_msg(msg, 'ERROR')
        sys.exit(1)

    for cvid in ver_list.keys():
        msg = "Cleaning content view '" + str(ver_descr[cvid]) + "'"
        helpers.log_msg(msg, 'INFO')
        print helpers.HEADER + msg + helpers.ENDC

        # Check if there is a publish/promote already running on this content view
        locked = helpers.check_running_publish(ver_list[cvid], ver_descr[cvid])
        if locked:
            continue

        # For the given content view we need to find the orphaned versions
        cvinfo = get_content_view_info(cvid)

        # Find the oldest published version
        version_list = []
        orphan_versions = []
        orphan_dict = {}
        all_versions = []
        ccv_versions = []
        for version in cvinfo['versions']:

            # Check if the version is part of a published view.
            # This is not returned in cvinfo, and we need to see if we are part of a CCV
            version_in_use, version_in_ccv = check_version_views(version['id'])

            # Build a list of ALL version numbers
            all_versions.append(float(version['version']))
            # Add any version numbers that are part of a CCV to a list
            if version_in_ccv:
                ccv_versions.append(float(version['version']))
            if not version['environment_ids']:
                # These are the versions that don't belong to an environment (i.e. orphans)
                # We also cross-check for versions that may be in a CCV here.
                # We add the version name and id into a dictionary so we can delete by id.
                if not version_in_use:
                    orphan_versions.append(float(version['version']))
                    orphan_dict[version['version']] = version['id']
                    continue
            else:
                msg = "Found version " + str(version['version'])
                helpers.log_msg(msg, 'DEBUG')
                # Add the version id to a list
                version_list.append(float(version['version']))

        # Find the oldest 'in use' version id
        if not version_list:
            msg = "No oldest in-use version found"
        else:
            lastver = min(version_list)
            msg = "Oldest in-use version is " + str(lastver)
        helpers.log_msg(msg, 'DEBUG')

        # Find the oldest 'NOT in use' version id
        if not orphan_versions:
            msg = "No oldest NOT-in-use version found"
        else:
            msg = "Oldest NOT-in-use version is " + str(min(orphan_versions))
        helpers.log_msg(msg, 'DEBUG')

        # Find the element position in the all_versions list of the oldest in-use version
        # e.g. vers 102.0 is oldest in-use and is element [5] in the all_versions list
        list_position = [i for i, x in enumerate(all_versions) if x == lastver]
        # Remove the number of views to keep from the element position of the oldest in-use
        # e.g. keep=2 results in an adjusted list element position [3]
        num_to_delete = list_position[0] - int(ver_keep[cvid])
        # Delete from position [0] to the first 'keep' position
        # e.g. first keep element is [3] so list of elements [0, 1, 2] is created
        list_pos_to_delete = [i for i in range(num_to_delete)]

        # Find versions to delete (based on keep parameter)
        # Make sure the version list is in order
        orphan_versions.sort()

        if cleanall:
            # Remove all orphaned versions
            todelete = orphan_versions
        elif ignorefirstpromoted:
            # Remove the last 'keep' elements from the orphans list (from PR #26)
            todelete = orphan_versions[:(len(orphan_versions) -
                                         int(ver_keep[cvid]))]
        else:
            todelete = []
            # Remove the element numbers for deletion from the list all versions
            for i in sorted(list_pos_to_delete, reverse=True):
                todelete.append(orphan_versions[i])

        msg = "Versions to remove: " + str(todelete)
        helpers.log_msg(msg, 'DEBUG')

        for version in all_versions:
            if not locked:
                if version in todelete:
                    msg = "Orphan view version " + str(version) + " found in '" +\
                        str(ver_descr[cvid]) + "'"
                    helpers.log_msg(msg, 'DEBUG')

                    # Lookup the version_id from our orphan_dict
                    delete_id = orphan_dict.get(str(version))

                    msg = "Removing version " + str(version)
                    helpers.log_msg(msg, 'INFO')
                    print helpers.HEADER + msg + helpers.ENDC
                else:
                    if version in ccv_versions:
                        msg = "Skipping delete of version " + str(
                            version) + " (member of a CCV)"
                    elif version in orphan_versions:
                        msg = "Skipping delete of version " + str(
                            version) + " (due to keep value)"
                    else:
                        msg = "Skipping delete of version " + str(
                            version) + " (in use)"
                    helpers.log_msg(msg, 'INFO')
                    print msg
                    continue
            else:
                msg = "Version " + str(version) + " is locked"
                helpers.log_msg(msg, 'WARNING')
                continue

            # Delete the view version from the content view
            if not dry_run and not locked:
                try:
                    task_id = helpers.put_json(
                        helpers.KATELLO_API + "content_views/" + str(cvid) +
                        "/remove/",
                        json.dumps({
                            "id": cvid,
                            "content_view_version_ids": delete_id
                        }))['id']

                    # Wait for the task to complete
                    helpers.wait_for_task(task_id, 'clean')

                    # Check if the deletion completed successfully
                    tinfo = helpers.get_task_status(task_id)
                    if tinfo['state'] != 'running' and tinfo[
                            'result'] == 'success':
                        msg = "Removal of content view version OK"
                        helpers.log_msg(msg, 'INFO')
                        print helpers.GREEN + "OK" + helpers.ENDC
                    else:
                        msg = "Failed"
                        helpers.log_msg(msg, 'ERROR')

                except Warning:
                    msg = "Failed to initiate removal"
                    helpers.log_msg(msg, 'WARNING')

                except KeyError:
                    msg = "Failed to initiate removal (KeyError)"
                    helpers.log_msg(msg, 'WARNING')

    # Exit in the case of a dry-run
    if dry_run:
        msg = "Dry run - not actually performing removal"
        helpers.log_msg(msg, 'WARNING')
        sys.exit(2)
Пример #4
0
def cleanup(ver_list, ver_descr, dry_run, runuser, ver_keep, cleanall, ignorefirstpromoted):
    """Clean Content Views"""

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Cleanup content views"

    # Now we have all the info needed, we can actually trigger the cleanup.
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching cleanup criteria
    if not ver_list:
        msg = "No content view versions found matching cleanup criteria"
        helpers.log_msg(msg, 'ERROR')
        sys.exit(1)

    for cvid in sorted(ver_list.keys(),reverse=True):
        # Check if there is a publish/promote already running on this content view
        locked = helpers.check_running_publish(ver_list[cvid], ver_descr[cvid])

        msg = "Cleaning content view '" + str(ver_descr[cvid]) + "'" 
        helpers.log_msg(msg, 'INFO')
        print helpers.HEADER + msg + helpers.ENDC

        # For the given content view we need to find the orphaned versions
        cvinfo = get_content_view_info(cvid)

        # Find the oldest published version
        version_list = []
        version_list_all = []
        for version in cvinfo['versions']:
            if not version['environment_ids']:
                version_list_all.append(float(version['version']))
                continue
            else:
                msg = "Found version " + str(version['version'])
                helpers.log_msg(msg, 'DEBUG')
                # Add the version id to a list
                version_list.append(float(version['version']))

        # Find the oldest 'in use' version id
        if not version_list:
            msg = "No oldest in-use version found"
        else:
            lastver = min(version_list)
            msg = "Oldest in-use version is " + str(lastver)
        helpers.log_msg(msg, 'DEBUG')

        # Find the oldest 'NOT in use' version id
        if not version_list_all:
            msg = "No oldest NOT-in-use version found"
        else:
            msg = "Oldest NOT-in-use version is " + str(min(version_list_all))
        helpers.log_msg(msg, 'DEBUG')

        # Find version to delete (based on keep parameter) if --ignorefirstpromoted
        version_list_all.sort()
        todelete = version_list_all[:(len(version_list_all) - int(ver_keep[cvid]))]
        msg = "Versions to remove if --ignorefirstpromoted: " + str(todelete)
        helpers.log_msg(msg, 'DEBUG')

        for version in cvinfo['versions']:
            # Get composite content views for version
            cvv = get_content_view_version(version['id'])
            # Find versions that are not in any environment and not in any composite content view
            if not version['environment_ids'] and not cvv['composite_content_view_ids']:
                if not locked:
                    msg = "Orphan view version " + str(version['version']) + " found in '" +\
                        str(ver_descr[cvid]) + "'"
                    helpers.log_msg(msg, 'DEBUG')

                    if ignorefirstpromoted:
                        if cleanall:
                            msg = "Removing version " + str(version['version'])
                            helpers.log_msg(msg, 'INFO')
                            print helpers.HEADER + msg + helpers.ENDC
                        else:
                            if float(version['version']) in todelete:
                                # If ignorefirstpromoted delete CV
                                msg = "Removing version " + str(version['version'])
                                helpers.log_msg(msg, 'INFO')
                                print helpers.HEADER + msg + helpers.ENDC
                            else:
                                msg = "Skipping delete of version " + str(version['version']) + " due to --keep value"
                                helpers.log_msg(msg, 'INFO')
                                print msg
                                continue
                    else:
                        if float(version['version']) > float(lastver):
                            # If we have chosen to remove all orphans
                            if cleanall:
                                msg = "Removing version " + str(version['version'])
                                helpers.log_msg(msg, 'INFO')
                                print helpers.HEADER + msg + helpers.ENDC
                            else:
                                msg = "Skipping delete of version " + str(version['version'])
                                helpers.log_msg(msg, 'INFO')
                                print msg
                                continue
                        else:
                            if float(version['version']) < (lastver - float(ver_keep[cvid])):
                                msg = "Removing version " + str(version['version'])
                                helpers.log_msg(msg, 'INFO')
                                print helpers.HEADER + msg + helpers.ENDC
                            else:
                                msg = "Skipping delete of version " + str(version['version']) + " due to --keep value"
                                helpers.log_msg(msg, 'INFO')
                                print msg
                                continue

                # Delete the view version from the content view
                if not dry_run and not locked:
                    try:
                        task = helpers.put_json(
                            helpers.KATELLO_API + "content_views/" + str(cvid) + "/remove/",
                            json.dumps(
                                {
                                    "id": cvid,
                                    "content_view_version_ids": version['id']
                                }
                            )
                        )

                        if id in task:
                            task_id = task['id']

                            # Wait for the task to complete
                            helpers.wait_for_task(task_id,'clean')
    
                            # Check if the deletion completed successfully
                            tinfo = helpers.get_task_status(task_id)
                            if tinfo['state'] != 'running' and tinfo['result'] == 'success':
                                msg = "Removal of content view version OK"
                                helpers.log_msg(msg, 'INFO')
                                print helpers.GREEN + "OK" + helpers.ENDC
                            else:
                                msg = "Failed"
                                helpers.log_msg(msg, 'ERROR')
                        else:
                            msg = "Can't remove content view " + str(cvid)
                            helpers.log_msg(msg, 'INFO')
                            print helpers.HEADER + msg + helpers.ENDC

                    except Warning:
                        msg = "Failed to initiate removal"
                        helpers.log_msg(msg, 'WARNING')

    # Exit in the case of a dry-run
    if dry_run:
        msg = "Dry run - not actually performing removal"
        helpers.log_msg(msg, 'WARNING')
        sys.exit(2)
def promote(target_env, ver_list, ver_descr, ver_version, env_list, prior_list, dry_run, quiet):
    """Promote Content View"""
    target_env_id = env_list[target_env]
    source_env_id = prior_list[target_env_id]

    # Extract the name of the source environment so we can inform the user
    for key, val in env_list.items():
        if val == source_env_id:
            prior_env = key

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Promotion from " + prior_env + " to " + target_env

    # Now we have all the info needed, we can actually trigger the promotion.
    # Loop through each CV with promotable versions
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching promotion criteria
    if not ver_list:
        msg = "No content view versions found matching promotion criteria"
        helpers.log_msg(msg, 'WARNING')
        if helpers.MAILOUT:
            helpers.tf.seek(0)
            output = "{}".format(helpers.tf.read())
            helpers.mailout(helpers.MAILSUBJ_FP, output)
        sys.exit(1)

    # Break repos to promote into batches as configured in config.yml
    cvchunks = [ ver_list.keys()[i:i+helpers.PROMOTEBATCH] for i in range(0, len(ver_list), helpers.PROMOTEBATCH) ]

    # Loop through the smaller subsets of repo id's
    for chunk in cvchunks:
        for cvid in chunk:

            # Check if there is a publish/promote already running on this content view
            locked = helpers.check_running_publish(cvid, ver_descr[cvid])

            if not locked:
                msg = "Promoting '" + str(ver_descr[cvid]) + "' Version " + str(ver_version[cvid]) +\
                    " from " + prior_env + " to " + str(target_env)
                helpers.log_msg(msg, 'INFO')
                print helpers.HEADER + msg + helpers.ENDC

            if not dry_run and not locked:
                try:
                    task_id = helpers.post_json(
                        helpers.KATELLO_API + "content_view_versions/" + str(ver_list[cvid]) +\
                        "/promote/", json.dumps(
                            {
                                "environment_id": target_env_id
                            }
                            ))["id"]
                except Warning:
                    msg = "Failed to initiate promotion of " + str(ver_descr[cvid])
                    helpers.log_msg(msg, 'WARNING')
                else:
                    task_list.append(task_id)
                    ref_list[task_id] = ver_descr[cvid]

        # Exit in the case of a dry-run
        if dry_run:
            msg = "Dry run - not actually performing promotion"
            helpers.log_msg(msg, 'WARNING')
        else:
            # Monitor the status of the promotion tasks
            helpers.watch_tasks(task_list, ref_list, task_name, quiet)

    # Exit in the case of a dry-run
    if dry_run:
        sys.exit(2)
    else:
        return
def cleanup(ver_list, ver_descr, dry_run, runuser, ver_keep, cleanall, ignorefirstpromoted):
    """Clean Content Views"""

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Cleanup content views"

    # Now we have all the info needed, we can actually trigger the cleanup.
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching cleanup criteria
    if not ver_list:
        msg = "No content view versions found matching cleanup criteria"
        helpers.log_msg(msg, 'ERROR')
        sys.exit(1)

    for cvid in ver_list.keys():
        msg = "Cleaning content view '" + str(ver_descr[cvid]) + "'"
        helpers.log_msg(msg, 'INFO')
        print helpers.HEADER + msg + helpers.ENDC

        # Check if there is a publish/promote already running on this content view
        locked = helpers.check_running_publish(ver_list[cvid], ver_descr[cvid])
        if locked:
            continue

        # For the given content view we need to find the orphaned versions
        cvinfo = get_content_view_info(cvid)

        # Find the oldest published version
        version_list = []
        orphan_versions = []
        orphan_dict = {}
        all_versions = []
        ccv_versions = []
        for version in cvinfo['versions']:

            # Check if the version is part of a published view.
            # This is not returned in cvinfo, and we need to see if we are part of a CCV
            version_in_use, version_in_ccv = check_version_views(version['id'])

            # Build a list of ALL version numbers
            all_versions.append(float(version['version']))
            # Add any version numbers that are part of a CCV to a list
            if version_in_ccv:
                ccv_versions.append(float(version['version']))
            if not version['environment_ids']:
                # These are the versions that don't belong to an environment (i.e. orphans)
                # We also cross-check for versions that may be in a CCV here.
                # We add the version name and id into a dictionary so we can delete by id.
                if not version_in_use:
                    orphan_versions.append(float(version['version']))
                    orphan_dict[version['version']] = version['id']
                    continue
            else:
                msg = "Found version " + str(version['version'])
                helpers.log_msg(msg, 'DEBUG')
                # Add the version id to a list
                version_list.append(float(version['version']))

        # Find the oldest 'in use' version id
        if not version_list:
            msg = "No oldest in-use version found"
        else:
            lastver = min(version_list)
            msg = "Oldest in-use version is " + str(lastver)
        helpers.log_msg(msg, 'DEBUG')

        # Find the oldest 'NOT in use' version id
        if not orphan_versions:
            msg = "No oldest NOT-in-use version found"
        else:
            msg = "Oldest NOT-in-use version is " + str(min(orphan_versions))
        helpers.log_msg(msg, 'DEBUG')

        # Find the element position in the all_versions list of the oldest in-use version
        # e.g. vers 102.0 is oldest in-use and is element [5] in the all_versions list
        list_position = [i for i,x in enumerate(all_versions) if x == lastver]
        # Remove the number of views to keep from the element position of the oldest in-use
        # e.g. keep=2 results in an adjusted list element position [3]
        num_to_delete = list_position[0] - int(ver_keep[cvid])
        # Delete from position [0] to the first 'keep' position
        # e.g. first keep element is [3] so list of elements [0, 1, 2] is created
        list_pos_to_delete = [i for i in range(num_to_delete)]

        # Find versions to delete (based on keep parameter)
        # Make sure the version list is in order
        orphan_versions.sort()

        if cleanall:
            # Remove all orphaned versions
            todelete = orphan_versions
        elif ignorefirstpromoted:
            # Remove the last 'keep' elements from the orphans list (from PR #26)
            todelete = orphan_versions[:(len(orphan_versions) - int(ver_keep[cvid]))]
        else:
            todelete = []
            # Remove the element numbers for deletion from the list all versions
            for i in sorted(list_pos_to_delete, reverse=True):
                todelete.append(orphan_versions[i])

        msg = "Versions to remove: " + str(todelete)
        helpers.log_msg(msg, 'DEBUG')

        for version in all_versions:
            if not locked:
                if version in todelete:
                    msg = "Orphan view version " + str(version) + " found in '" +\
                        str(ver_descr[cvid]) + "'"
                    helpers.log_msg(msg, 'DEBUG')

                    # Lookup the version_id from our orphan_dict
                    delete_id = orphan_dict.get(str(version))

                    msg = "Removing version " + str(version)
                    helpers.log_msg(msg, 'INFO')
                    print helpers.HEADER + msg + helpers.ENDC
                else:
                    if version in ccv_versions:
                        msg = "Skipping delete of version " + str(version) + " (member of a CCV)"
                    elif version in orphan_versions:
                        msg = "Skipping delete of version " + str(version) + " (due to keep value)"
                    else:
                        msg = "Skipping delete of version " + str(version) + " (in use)"
                    helpers.log_msg(msg, 'INFO')
                    print msg
                    continue
            else:
                msg = "Version " + str(version) + " is locked"
                helpers.log_msg(msg, 'WARNING')
                continue

            # Delete the view version from the content view
            if not dry_run and not locked:
                try:
                    task_id = helpers.put_json(
                        helpers.KATELLO_API + "content_views/" + str(cvid) + "/remove/",
                        json.dumps(
                            {
                                "id": cvid,
                                "content_view_version_ids": delete_id
                            }
                            ))['id']

                    # Wait for the task to complete
                    helpers.wait_for_task(task_id,'clean')

                    # Check if the deletion completed successfully
                    tinfo = helpers.get_task_status(task_id)
                    if tinfo['state'] != 'running' and tinfo['result'] == 'success':
                        msg = "Removal of content view version OK"
                        helpers.log_msg(msg, 'INFO')
                        print helpers.GREEN + "OK" + helpers.ENDC
                    else:
                        msg = "Failed"
                        helpers.log_msg(msg, 'ERROR')

                except Warning:
                    msg = "Failed to initiate removal"
                    helpers.log_msg(msg, 'WARNING')

                except KeyError:
                    msg = "Failed to initiate removal (KeyError)"
                    helpers.log_msg(msg, 'WARNING')

    # Exit in the case of a dry-run
    if dry_run:
        msg = "Dry run - not actually performing removal"
        helpers.log_msg(msg, 'WARNING')
        sys.exit(2)
def publish(ver_list, ver_descr, ver_version, dry_run, runuser, description, quiet, forcemeta):
    """Publish Content View"""

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Publish content view to Library"

    # Now we have all the info needed, we can actually trigger the publish.
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching publish criteria
    if not ver_list:
        msg = "No content view versions found matching publication criteria"
        helpers.log_msg(msg, 'ERROR')
        if helpers.MAILOUT:
            helpers.tf.seek(0)
            output = "{}".format(helpers.tf.read())
            helpers.mailout(helpers.MAILSUBJ_FP, output)
        sys.exit(1)

    # Break repos to publish into batches as configured in config.yml
    cvchunks = [ ver_list.keys()[i:i+helpers.PUBLISHBATCH] for i in range(0, len(ver_list), helpers.PUBLISHBATCH) ]

    # Loop through the smaller subsets of repo id's
    for chunk in cvchunks:
        for cvid in chunk:

            # Check if there is a publish/promote already running on this content view
            locked = helpers.check_running_publish(ver_list[cvid], ver_descr[cvid])

            if not locked:
                msg = "Publishing '" + str(ver_descr[cvid]) + "' Version " + str(ver_version[cvid]) + ".0"
                helpers.log_msg(msg, 'INFO')
                print helpers.HEADER + msg + helpers.ENDC

            if not dry_run and not locked:
                try:
                    task_id = helpers.post_json(
                        helpers.KATELLO_API + "content_views/" + str(ver_list[cvid]) +\
                        "/publish", json.dumps(
                            {
                                "description": description,
                                "force_yum_metadata_regeneration": str(forcemeta)
                            }
                            ))["id"]
                except Warning:
                    msg = "Failed to initiate publication of " + str(ver_descr[cvid])
                    helpers.log_msg(msg, 'WARNING')
                except KeyError:
                    msg = "Failed to initiate publication of " + str(ver_descr[cvid])
                    helpers.log_msg(msg, 'WARNING')
                else:
                    task_list.append(task_id)
                    ref_list[task_id] = ver_descr[cvid]

        # Notify user in the case of a dry-run
        if dry_run:
            msg = "Dry run - not actually performing publish"
            helpers.log_msg(msg, 'WARNING')
        else:
            # Wait for the tasks to finish
            helpers.watch_tasks(task_list, ref_list, task_name, quiet)

    # Exit in the case of a dry-run
    if dry_run:
        sys.exit(2)
    else:
        return
def publish(ver_list, ver_descr, ver_version, dry_run, runuser, description,
            quiet):
    """Publish Content View"""

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Publish content view to Library"

    # Now we have all the info needed, we can actually trigger the publish.
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching publish criteria
    if not ver_list:
        msg = "No content view versions found matching publication criteria"
        helpers.log_msg(msg, 'ERROR')
        if helpers.MAILOUT:
            helpers.tf.seek(0)
            output = "{}".format(helpers.tf.read())
            helpers.mailout(helpers.MAILSUBJ_FP, output)
        sys.exit(1)

    # Break repos to publish into batches as configured in config.yml
    cvchunks = [
        ver_list.keys()[i:i + helpers.PUBLISHBATCH]
        for i in range(0, len(ver_list), helpers.PUBLISHBATCH)
    ]

    # Loop through the smaller subsets of repo id's
    for chunk in cvchunks:
        for cvid in chunk:

            # Check if there is a publish/promote already running on this content view
            locked = helpers.check_running_publish(ver_list[cvid],
                                                   ver_descr[cvid])

            if not locked:
                msg = "Publishing '" + str(
                    ver_descr[cvid]) + "' Version " + str(
                        ver_version[cvid]) + ".0"
                helpers.log_msg(msg, 'INFO')
                print helpers.HEADER + msg + helpers.ENDC

            if not dry_run and not locked:
                try:
                    task_id = helpers.post_json(
                        helpers.KATELLO_API + "content_views/" + str(ver_list[cvid]) +\
                        "/publish", json.dumps(
                            {
                                "description": description
                            }
                            ))["id"]
                except Warning:
                    msg = "Failed to initiate publication of " + str(
                        ver_descr[cvid])
                    helpers.log_msg(msg, 'WARNING')
                else:
                    task_list.append(task_id)
                    ref_list[task_id] = ver_descr[cvid]

        # Notify user in the case of a dry-run
        if dry_run:
            msg = "Dry run - not actually performing publish"
            helpers.log_msg(msg, 'WARNING')
        else:
            # Wait for the tasks to finish
            helpers.watch_tasks(task_list, ref_list, task_name, quiet)

    # Exit in the case of a dry-run
    if dry_run:
        sys.exit(2)
    else:
        return
def promote(target_env, ver_list, ver_descr, ver_version, env_list, prior_list, dry_run, quiet, forcemeta):
    """Promote Content View"""
    target_env_id = env_list[target_env]
    source_env_id = prior_list[target_env_id]

    # Extract the name of the source environment so we can inform the user
    for key, val in env_list.items():
        if val == source_env_id:
            prior_env = key

    # Set the task name to be displayed in the task monitoring stage
    task_name = "Promotion from " + prior_env + " to " + target_env

    # Now we have all the info needed, we can actually trigger the promotion.
    # Loop through each CV with promotable versions
    task_list = []
    ref_list = {}

    # Catch scenario that no CV versions are found matching promotion criteria
    if not ver_list:
        msg = "No content view versions found matching promotion criteria"
        helpers.log_msg(msg, 'WARNING')
        if helpers.MAILOUT:
            helpers.tf.seek(0)
            output = "{}".format(helpers.tf.read())
            helpers.mailout(helpers.MAILSUBJ_FP, output)
        sys.exit(1)

    # Break repos to promote into batches as configured in config.yml
    cvchunks = [ ver_list.keys()[i:i+helpers.PROMOTEBATCH] for i in range(0, len(ver_list), helpers.PROMOTEBATCH) ]

    # Loop through the smaller subsets of repo id's
    for chunk in cvchunks:
        for cvid in chunk:

            # Check if there is a publish/promote already running on this content view
            locked = helpers.check_running_publish(cvid, ver_descr[cvid])

            if not locked:
                msg = "Promoting '" + str(ver_descr[cvid]) + "' Version " + str(ver_version[cvid]) +\
                    " from " + prior_env + " to " + str(target_env)
                helpers.log_msg(msg, 'INFO')
                print helpers.HEADER + msg + helpers.ENDC

            if not dry_run and not locked:
                try:
                    task_id = helpers.post_json(
                        helpers.KATELLO_API + "content_view_versions/" + str(ver_list[cvid]) +\
                        "/promote/", json.dumps(
                            {
                                "environment_id": target_env_id,
                                "force_yum_metadata_regeneration": str(forcemeta)
                            }
                            ))["id"]
                except Warning:
                    msg = "Failed to initiate promotion of " + str(ver_descr[cvid])
                    helpers.log_msg(msg, 'WARNING')
                else:
                    task_list.append(task_id)
                    ref_list[task_id] = ver_descr[cvid]

        # Exit in the case of a dry-run
        if dry_run:
            msg = "Dry run - not actually performing promotion"
            helpers.log_msg(msg, 'WARNING')
        else:
            # Monitor the status of the promotion tasks
            helpers.watch_tasks(task_list, ref_list, task_name, quiet)

    # Exit in the case of a dry-run
    if dry_run:
        sys.exit(2)
    else:
        return