Ejemplo n.º 1
0
def throw_warning(message, resp=None, cr=True):
    """
    Recoverable Warning.
    :param message: Message text
    :param resp: Optional - CloudGenix SDK Response object
    :param cr: Optional - Use (or not) Carriage Returns.
    :return: None
    """
    output = "WARNING: " + str(message)
    if cr:
        output += "\n"
    sys.stderr.write(output)
    if resp is not None:
        output2 = str(cloudgenix.jdout_detailed(resp))
        if cr:
            output2 += "\n"
        sys.stderr.write(output2)
    return
Ejemplo n.º 2
0
def throw_error(message, resp=None, cr=True):
    """
    Non-recoverable error, write message to STDERR and exit or raise exception
    :param message: Message text
    :param resp: Optional - CloudGenix SDK Response object
    :param cr: Optional - Use (or not) Carriage Returns.
    :return: No Return, throws exception.
    """
    output = "ERROR: " + str(message)
    if cr:
        output += "\n"
    sys.stderr.write(output)
    if resp is not None:
        output2 = str(jdout_detailed(resp))
        if cr:
            output2 += "\n"
        sys.stderr.write(output2)
    raise CloudGenixConfigError(message)
Ejemplo n.º 3
0
def throw_warning(message, resp=None, cr=True):
    """
    Recoverable Warning. (taken from cloudgenix_config)
    :param message: Message text
    :param resp: Optional - CloudGenix SDK Response object
    :param cr: Optional - Use (or not) Carriage Returns.
    :return: None
    """
    output = str(message)
    if cr:
        output += "\n"
    print(output)
    if resp is not None:
        output2 = str(cloudgenix.jdout_detailed(resp))
        if cr:
            output2 += "\n"
        print(output2)
    return
Ejemplo n.º 4
0
def throw_error(message, resp=None, cr=True):
    """
    Non-recoverable error, print message and raise exception (taken from cloudgenix_config)
    :param message: Message text
    :param resp: Optional - CloudGenix SDK Response object
    :param cr: Optional - Use (or not) Carriage Returns.
    :return: No Return, throws exception.
    """
    output = str(message)
    output2 = str("")
    if cr:
        output += "\n"
    print(output)
    if resp is not None:
        output2 = str(cloudgenix.jdout_detailed(resp))
        if cr:
            output2 += "\n"
        print(output2)

    if output2:
        print(message + output2)

    sys.exit(1)
Ejemplo n.º 5
0
def go():
    """
    Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site()
    :return: No return
    """

    # Parse arguments
    parser = argparse.ArgumentParser(description="{0} ({1})".format(
        GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION))

    ####
    #
    # Add custom cmdline argparse arguments here
    #
    ####
    custom_group = parser.add_argument_group('custom_args', 'Tag Options')
    custom_group.add_argument("--remove",
                              help="Remove all Serial Tags.",
                              default=False,
                              action="store_true")
    ####
    #
    # End custom cmdline arguments
    #
    ####

    # Standard CloudGenix script switches.
    controller_group = parser.add_argument_group(
        'API', 'These options change how this program connects to the API.')
    controller_group.add_argument(
        "--controller",
        "-C",
        help="Controller URI, ex. https://api.elcapitan.cloudgenix.com",
        default=None)

    login_group = parser.add_argument_group(
        'Login', 'These options allow skipping of interactive login')
    login_group.add_argument(
        "--email",
        "-E",
        help="Use this email as User Name instead of cloudgenix_settings.py "
        "or prompting",
        default=None)
    login_group.add_argument(
        "--password",
        "-PW",
        help="Use this Password instead of cloudgenix_settings.py "
        "or prompting",
        default=None)
    login_group.add_argument("--insecure",
                             "-I",
                             help="Do not verify SSL certificate",
                             action='store_true',
                             default=False)
    login_group.add_argument("--noregion",
                             "-NR",
                             help="Ignore Region-based redirection.",
                             dest='ignore_region',
                             action='store_true',
                             default=False)

    debug_group = parser.add_argument_group(
        'Debug', 'These options enable debugging output')
    debug_group.add_argument("--sdkdebug",
                             "-D",
                             help="Enable SDK Debug output, levels 0-2",
                             type=int,
                             default=0)

    args = vars(parser.parse_args())

    sdk_debuglevel = args["sdkdebug"]

    # Build SDK Constructor
    if args['controller'] and args['insecure']:
        sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False)
    elif args['controller']:
        sdk = cloudgenix.API(controller=args['controller'])
    elif args['insecure']:
        sdk = cloudgenix.API(ssl_verify=False)
    else:
        sdk = cloudgenix.API()

    # check for region ignore
    if args['ignore_region']:
        sdk.ignore_region = True

    # SDK debug, default = 0
    # 0 = logger handlers removed, critical only
    # 1 = logger info messages
    # 2 = logger debug messages.

    if sdk_debuglevel == 1:
        # CG SDK info
        sdk.set_debug(1)
    elif sdk_debuglevel >= 2:
        # CG SDK debug
        sdk.set_debug(2)

    # login logic. Use cmdline if set, use AUTH_TOKEN next, finally user/pass from config file, then prompt.
    # figure out user
    if args["email"]:
        user_email = args["email"]
    elif CLOUDGENIX_USER:
        user_email = CLOUDGENIX_USER
    else:
        user_email = None

    # figure out password
    if args["password"]:
        user_password = args["password"]
    elif CLOUDGENIX_PASSWORD:
        user_password = CLOUDGENIX_PASSWORD
    else:
        user_password = None

    # check for token
    if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["password"]:
        sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN)
        if sdk.tenant_id is None:
            print("AUTH_TOKEN login failure, please check token.")
            sys.exit(1)

    else:
        while sdk.tenant_id is None:
            sdk.interactive.login(user_email, user_password)
            # clear after one failed login, force relogin.
            if not sdk.tenant_id:
                user_email = None
                user_password = None

    ####
    #
    # Do your custom work here, or call custom functions.
    #
    ####

    remove = args['remove']

    if not remove:
        print(
            "Checking all Elements for '#serial' hashtag on Controller with correct serial..."
        )
    else:
        print("Removing all '#serial' hashtags on Controller ports.")

    elements_resp = sdk.get.elements()

    if elements_resp.cgx_status:
        elements_cache = elements_resp.cgx_content.get('items', [])
    else:
        print("ERROR: Unable to read 'elements': {0}".format(
            cloudgenix.jdout_detailed(elements_resp)))
        sys.exit()

    for element in elements_cache:
        element_id = element.get('id')
        element_displayname = element.get('name', element_id)
        print("Checking '{0}'... ".format(element_displayname), end="")

        element_id = element.get('id')
        site = element.get("site_id")
        serial_no = element.get("serial_number")

        if not serial_no:
            print("Error getting Serial Number.")
            continue
        if not site or site == "1":
            print("Not assigned to Site, skipping.")
            continue

        interfaces_resp = sdk.get.interfaces(site, element_id)

        if interfaces_resp.cgx_status:
            interfaces_cache = interfaces_resp.cgx_content.get('items', [])
        else:
            print("Unable to read 'interfaces'. Skipping.")
            continue

        selected_interface = {}
        for interface in interfaces_cache:
            if interface.get('name') in ['controller', 'controller 1']:
                selected_interface = interface
                continue

        if not selected_interface:
            print(
                "Could not find Controller/Controller 1 interface. Skipping.")
            continue

        selected_interface_id = selected_interface.get('id')
        selected_interface_name = selected_interface.get('name')
        serial_hashtag = "serial:{0}".format(serial_no)
        interface_hashtags = extract_tags(selected_interface)

        if remove:
            candidtate_interface_config = remove_tags(selected_interface)

            interface_edit_resp = sdk.put.interfaces(
                site, element_id, selected_interface_id,
                candidtate_interface_config)

            if interface_edit_resp.cgx_status:
                print("Cleaned Serial Hashtags from {0}.".format(
                    selected_interface_name))
            else:
                print("Failed Clean Serial Hashtags: {0}".format(
                    cloudgenix.jdout_detailed(interface_edit_resp)))

        else:  # add/check
            if serial_hashtag in interface_hashtags:
                print("Serial Hashtag Present.")
                continue

            # tag not present, add.
            candidtate_interface_config = put_tags([serial_hashtag],
                                                   selected_interface)

            interface_edit_resp = sdk.put.interfaces(
                site, element_id, selected_interface_id,
                candidtate_interface_config)

            if interface_edit_resp.cgx_status:
                print("Added Serial Hashtag to {0}.".format(
                    selected_interface_name))
            else:
                print("Failed to add Serial Hashtag: {0}".format(
                    cloudgenix.jdout_detailed(interface_edit_resp)))