def show_emsfilter() -> None:
    """Show EMS Filter"""

    substep("EMS Filter")
    print("======================")
    try:
        for emsfilter in EmsFilter.get_collection():
            print("=====")
            print("Filter Name = %s" % emsfilter.name)
            for filterrule in EmsFilterRule.get_collection(emsfilter.name):
                print("Rule:-")
                print("Index:- %s" % filterrule.index)
                try:
                    ruleindex = EmsFilterRule.find(emsfilter.name,
                                                   index=filterrule.index)
                    pprint.pprint(ruleindex.index)
                    pprint.pprint(ruleindex.message_criteria.name_pattern)
                    pprint.pprint(ruleindex.message_criteria.severities)
                    pprint.pprint(ruleindex.message_criteria.snmp_trap_types)
                    pprint.pprint(ruleindex.type)
                except RuntimeError as err:
                    print("Exception: ", err)
    except NetAppRestError as error:
        print("Error:- " % error.http_err_response.http_response.text)
        print("Exception caught :" + str(error))
def test_cert_auth(parsed_args: argparse.Namespace, temp_path: str) -> None:
    """Verify our account can connect with a cert and no user/pass. After uploading
    and creating a user account, it can take some time before authentication works.
    In my testing, I've seen it take about 10 seconds. The while loop here tries
    to paper over that.
    """

    substep("List the volumes using a connection with cert-based auth")
    cert_conn = HostConnection(
        parsed_args.cluster,
        cert="%s/cert_user.cert" % temp_path,
        key="%s/cert_user.key" % temp_path,
        verify=False,
    )
    with cert_conn:
        tries = 0
        while True:
            try:
                logging.info([vol.name for vol in Volume.get_collection()])
                logging.debug("Succeeded on try %s", tries)
                break
            except NetAppRestError as err:
                resp = err.http_err_response
                if resp is None or resp.http_response.status_code == 401:
                    tries += 1
                    if tries > 60:
                        logging.error(
                            "Not able to authenticate within 60 tries")
                        raise
                    time.sleep(1)
                else:
                    raise
def show_current_cluster_image():
    """Verify our current software status"""

    step("Show the packages")
    substep("Show the current cluster image")
    software = Software()
    software.get()
    print("Current software package:", software)

    substep("Show the available software packages")
    print("Available software packages:", list(SoftwarePackage.get_collection()))
    return software
def show_emsevents() -> None:
    """Show EMS Events"""

    substep("EMS Events")
    print("======================")
    try:
        emsevent = EmsEvent.get_collection()
        for emsevent in EmsEvent.get_collection():
            print("=====")
            pprint.pprint(emsevent.to_dict())
    except NetAppRestError as error:
        print("Error:- " % error.http_err_response.http_response.text)
        print("Exception caught :" + str(error))
def show_emsdestination() -> None:
    """Show EMS Config"""

    substep("EMS Destination")
    print("======================")
    try:
        emsdestination = EmsDestination.get_collection()
        for emsdestination in EmsDestination.get_collection():
            print("=====")
            pprint.pprint(emsdestination.to_dict())
    except NetAppRestError as error:
        print("Error:- " % error.http_err_response.http_response.text)
        print("Exception caught :" + str(error))
def show_account() -> None:
    """Lists Accounts"""

    substep("List Accounts")
    print("======================")
    try:
        for account in Account.get_collection():
            print("=====")
            print("Account Name = %s" % account.name)
            print("Account Owner Name = %s" % account.owner.name)
            print("Account Owner UUID = %s" % account.owner.uuid)
    except NetAppRestError as error:
        print("Exception caught :" + str(error))
def show_emsconfig() -> None:
    """Show EMS Config"""

    substep("EMS Config")
    print("======================")
    try:
        emsconfig = EmsConfig()
        emsconfig.get()
        print("EmsConfig Name = %s" % emsconfig)
        print("Mail Server = %s" % emsconfig.mail_server)
        print("Mail From = %s" % emsconfig.mail_from)
    except NetAppRestError as error:
        print("Error:- " % error.http_err_response.http_response.text)
        print("Exception caught :" + str(error))
def sign_domain(my_ca: SecurityCertificate, temp_path: str,
                parsed_args: argparse.Namespace) -> SecurityCertificate:
    """Generate a signing request and have it signed by the CA we just installed"""

    subject = ("/C=US/ST=PA/L=Pittsburgh/O=%s/OU=BestPart/CN=%s" %
               (parsed_args.organization, parsed_args.cert_account))

    substep("Generate the private key")
    run_cmd("openssl genrsa -out %s/cert_user.key 2048" % temp_path)

    substep("Generate the certificate signing request")
    run_cmd("openssl req -sha256 -new -nodes -key %s/cert_user.key"
            ' -subj "%s" -out %s/cert_user.csr' %
            (temp_path, subject, temp_path))

    substep("Sign the CSR with our root CA")
    with open("%s/cert_user.csr" % temp_path) as signing_request_file:
        response = my_ca.sign(
            body={"signing_request": signing_request_file.read()})

    substep("Create a cert object from the response")
    cert = SecurityCertificate.from_dict(response.http_response.json())
    logging.info(cert)
    with open("%s/cert_user.cert" % temp_path, "w") as cert_file:
        cert_file.write(cert.public_certificate)
    return cert
def delete_account():
    """Delete the User"""

    step("Delete the limited account and role")
    show_account()
    accname = input(
        "Enter the name of the Account that needs to be deleted:- ")
    try:
        account = Account.find(name=accname)
    except NetAppRestError as error:
        print("Exception caught :" + str(error))

    substep("Delete our %s account" % accname)
    try:
        account.delete()
    except NetAppRestError as error:
        print("Exception caught :" + str(error))
def update_account():
    """Module to update the account details with new role"""

    step("Update the account with new roles")
    show_account()
    accname = input(
        "Enter the name of the Account that needs to be updated with the new role:- "
    )
    try:
        account = Account.find(name=accname)
    except NetAppRestError as error:
        print("Exception caught :" + str(error))

    print("======================")
    substep("Create the new role")
    rolename = input("Enter the name of the Role to be created:- ")
    privpath = input(
        "Enter the name of the Command Directoey PATH [eg: /api/storage/volume]:- "
    )
    pathaccess = input(
        "Enter the Access for the Command Directory PATH [none/all/readonly]:- "
    )
    role = Role(
        name=rolename,
        privileges=[
            RolePrivilege(access=pathaccess, path=privpath),
        ],
    )
    try:
        role.post()
    except NetAppRestError as error:
        print("Exception caught :" + str(error))
    print("New role created: %s" % rolename)

    substep("Assign the test account to the test role")
    account.role = role
    try:
        account.patch()
    except NetAppRestError as error:
        print("Exception caught :" + str(error))
    print("======================")
    print("Account updated with the new role: %s" % account)
def enable_cert_auth(parsed_args: argparse.Namespace) -> Account:
    """Install the client cert as a client-ca and enable cert auth """

    account = Account.find(name=parsed_args.cert_account)
    if account is None:
        substep("Create an account that uses cert auth")
        account = Account(
            name="cert_user",
            applications=[
                AccountApplication(application="http",
                                   authentication_methods=["cert"])
            ],
        )
        account.post()
    else:
        http_application = [
            a for a in account.applications if a.application == "http"
        ]
        if http_application and "cert" in http_application[
                0].authentication_methods:
            substep("The %s account is already cert-enabled")
        else:
            substep("Modifying the %s account for cert authentication" %
                    account.name)
            if http_application:
                http_application[0].authentication_methods.append("cert")
            else:
                http_application = AccountApplication(
                    application="http",
                    authentication_methods=["cert"],
                )
                account.applications.append(http_application)
            account.patch()
    return account
def download_new_cluster_image(parsed_args: argparse.Namespace):
    """Start our HTTP server and tell ONTAP to start downloading the new image"""

    step("Download a new software package")
    substep("Start an HTTP server to serve the file")
    image_server = Thread(target=serve_image_download, args=(parsed_args,))
    image_server.start()

    substep("Have ONTAP download the package")
    local_ip = socket.gethostbyname(socket.gethostname())
    url = "http://%s:%s/%s" % (local_ip, parsed_args.port, parsed_args.image_path)
    download_package = SoftwarePackageDownload(url=url)
    download_package.post(poll_timeout=1200, poll_interval=60)
    image_server.join()

    substep("Show the new package")
    packages = list(SoftwarePackage.get_collection())
    print("Available software packages:", packages)
    return packages[0]
def install_cert(parsed_args: argparse.Namespace) -> SecurityCertificate:
    """Create and install a new root cert"""

    common_name = "%sCA" % parsed_args.organization
    cert = SecurityCertificate.find(common_name=common_name, type="root_ca")
    if cert is None:
        substep("Create a new root CA in ONTAP for %s" %
                parsed_args.organization)
        cert = SecurityCertificate(
            type="root_ca",
            common_name=common_name,
            expiry_time="3652days",
        )
        cert.post(hydrate=True)
    else:
        substep("Using existing root CA for %s" % parsed_args.organization)

    substep("Show the installed root CA")
    logging.info(cert)
    return cert
def create_account():
    """Create an account and a role and assign the account to the role.
    """

    step("Create an account and the role.")

    substep("Create the test account")
    print("======================")
    accname = input("Enter the name of the Account to be created:- ")
    accpwd = getpass.getpass()
    accapp = input(
        "Enter the Application type for the Account [http/snmp/ontapi/ssh/rsh/telnet]:- "
    )
    accauth = input(
        "Enter the Athentication Method for the Account [password/domain/nsswitch]:- "
    )
    account = Account(
        name=accname,
        password=accpwd,
        applications=[
            AccountApplication(application=accapp,
                               authentication_methods=[accauth])
        ],
    )

    try:
        account.post(hydrate=True)
    except NetAppRestError as error:
        print("Error:- " % error.http_err_response.http_response.text)
        print("Exception caught :" + str(error))
    print("New account created: %s" % account.name)
    print("======================")
    substep("Create the test role")
    rolename = input("Enter the name of the Role to be created:- ")
    privpath = input(
        "Enter the name of the Command Directoey PATH [eg: /api/storage/volume]:- "
    )
    pathaccess = input(
        "Enter the Access for the Command Directory PATH [none/all/readonly]:- "
    )
    role = Role(
        name=rolename,
        privileges=[
            RolePrivilege(access=pathaccess, path=privpath),
        ],
    )
    try:
        role.post()
    except NetAppRestError as error:
        print("Exception caught :" + str(error))

    print("New role created: %s" % rolename)

    substep("Assign the test account to the test role")
    account.role = role
    try:
        account.patch()
    except NetAppRestError as error:
        print("Exception caught :" + str(error))
    print("======================")
    print("Account assigned to role: %s" % account)

    return account, role