# Path: libcloudforensics/errors.py
# class LCFError(Exception):
# class CredentialsConfigurationError(LCFError):
# class InvalidFileFormatError(LCFError):
# class InvalidNameError(LCFError):
# class ResourceNotFoundError(LCFError):
# class ResourceCreationError(LCFError):
# class ResourceDeletionError(LCFError):
# class InstanceStateChangeError(LCFError):
# class ServiceAccountRemovalError(LCFError):
# class InstanceProfileCreationError(LCFError):
# class OperationFailedError(LCFError):
# class TransferCreationError(LCFError):
# class TransferExecutionError(LCFError):
# class ResourceAlreadyExistsError(LCFError):
#   def __init__(self,
#                message: str,
#                name: str) -> None:
# 
# Path: libcloudforensics/logging_utils.py
# def _GenerateColorSequences() -> List[str]:
#   def __init__(self,
#                colorize: bool = True,
#                random_color: bool = False,
#                **kwargs: str) -> None:
#   def format(self, record: logging.LogRecord) -> str:
# def SetUpLogger(name: str, no_newline: bool = False) -> None:
# def GetLogger(name: str) -> logging.Logger:
# COLOR_SEQS = _GenerateColorSequences()
# RESET_SEQ = '\u001b[0m'
# BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = COLOR_SEQS[8:16]
# BG_RED = '\u001b[41m'  # Red background
# BOLD = '\u001b[1m'  # Bold / bright modifier
# LOG_FORMAT = ('[%(asctime)s] [{0:s}{color:s}%(name)-20s{1:s}] %(levelname)-8s'
#               ' %(message)s')
# LEVEL_COLOR_MAP = {
#     'WARNING': YELLOW,
#     'INFO': WHITE,
#     'DEBUG': BLUE,
#     'CRITICAL': BOLD + BG_RED + WHITE,
#     'ERROR': RED
# }
# class Formatter(logging.Formatter):
# 
# Path: libcloudforensics/providers/aws/internal/common.py
# EC2_SERVICE = 'ec2'
# ACCOUNT_SERVICE = 'sts'
# KMS_SERVICE = 'kms'
# CLOUDTRAIL_SERVICE = 'cloudtrail'
# S3_SERVICE = 's3'
# IAM_SERVICE = 'iam'
# INSTANCE = 'instance'
# VOLUME = 'volume'
# SNAPSHOT = 'snapshot'
# UBUNTU_1804_FILTER = 'ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20200611'  # pylint: disable=line-too-long
# ALINUX2_BASE_FILTER = 'amzn2-ami-hvm-2*-x86_64-gp2'
# def CreateTags(resource: str, tags: Dict[str, str]) -> Dict[str, Any]:
# def GetInstanceTypeByCPU(cpu_cores: int) -> str:
# def ExecuteRequest(client: 'botocore.client.EC2',
#                    func: str,
#                    kwargs: Dict[str, Any]) -> List[Dict[str, Any]]:


import datetime
import json
import os
from typing import TYPE_CHECKING, Optional, Tuple
from libcloudforensics import errors
from libcloudforensics import logging_utils
from libcloudforensics.providers.aws.internal import common
  from libcloudforensics.providers.aws.internal import account  # pylint: disable=cyclic-import
          raise errors.ResourceNotFoundError('Could not locate role with name {0:s} after creation failure due to EntityAlreadyExistsException'
          # pylint: enable=line-too-long
            .format(name), __name__) from exception

        roles = self.client.list_roles(Marker=roles['Marker'])

  def DeleteRole(self, role_name: str) -> None:
    """Delete an IAM role.

    Args:
      role_name (str): The name of the role to delete.
    """
    logger.info('Deleting IAM role {0:s}'.format(role_name))
    try:
      self.client.delete_role(RoleName=role_name)
    except self.client.exceptions.NoSuchEntityException:
      logger.info('IAM role {0:s} did not exist'.format(role_name))

  def AttachPolicyToRole(self, policy_arn: str, role_name: str) -> None:
    """Attaches an IAM policy to an IAM role.

    Args:
      policy_arn (str): The Policy Arn.
      role_name (str): The Role Name.
    """
    logger.info('Attaching policy {0:s} to role {1:s}'
      .format(policy_arn, role_name))
    try:
      self.client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
    except Exception as e:

# Path: libcloudforensics/errors.py
# class LCFError(Exception):
# class CredentialsConfigurationError(LCFError):
# class InvalidFileFormatError(LCFError):
# class InvalidNameError(LCFError):
# class ResourceNotFoundError(LCFError):
# class ResourceCreationError(LCFError):
# class ResourceDeletionError(LCFError):
# class InstanceStateChangeError(LCFError):
# class ServiceAccountRemovalError(LCFError):
# class InstanceProfileCreationError(LCFError):
# class OperationFailedError(LCFError):
# class TransferCreationError(LCFError):
# class TransferExecutionError(LCFError):
# class ResourceAlreadyExistsError(LCFError):
#   def __init__(self,
#                message: str,
#                name: str) -> None:
# 
# Path: libcloudforensics/logging_utils.py
# def _GenerateColorSequences() -> List[str]:
#   def __init__(self,
#                colorize: bool = True,
#                random_color: bool = False,
#                **kwargs: str) -> None:
#   def format(self, record: logging.LogRecord) -> str:
# def SetUpLogger(name: str, no_newline: bool = False) -> None:
# def GetLogger(name: str) -> logging.Logger:
# COLOR_SEQS = _GenerateColorSequences()
# RESET_SEQ = '\u001b[0m'
# BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = COLOR_SEQS[8:16]
# BG_RED = '\u001b[41m'  # Red background
# BOLD = '\u001b[1m'  # Bold / bright modifier
# LOG_FORMAT = ('[%(asctime)s] [{0:s}{color:s}%(name)-20s{1:s}] %(levelname)-8s'
#               ' %(message)s')
# LEVEL_COLOR_MAP = {
#     'WARNING': YELLOW,
#     'INFO': WHITE,
#     'DEBUG': BLUE,
#     'CRITICAL': BOLD + BG_RED + WHITE,
#     'ERROR': RED
# }
# class Formatter(logging.Formatter):
# 
# Path: libcloudforensics/providers/aws/internal/common.py
# EC2_SERVICE = 'ec2'
# ACCOUNT_SERVICE = 'sts'
# KMS_SERVICE = 'kms'
# CLOUDTRAIL_SERVICE = 'cloudtrail'
# S3_SERVICE = 's3'
# IAM_SERVICE = 'iam'
# INSTANCE = 'instance'
# VOLUME = 'volume'
# SNAPSHOT = 'snapshot'
# UBUNTU_1804_FILTER = 'ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20200611'  # pylint: disable=line-too-long
# ALINUX2_BASE_FILTER = 'amzn2-ami-hvm-2*-x86_64-gp2'
# def CreateTags(resource: str, tags: Dict[str, str]) -> Dict[str, Any]:
# def GetInstanceTypeByCPU(cpu_cores: int) -> str:
# def ExecuteRequest(client: 'botocore.client.EC2',
#                    func: str,
#                    kwargs: Dict[str, Any]) -> List[Dict[str, Any]]:


# Path: libcloudforensics/providers/aws/internal/iam.py
import datetime
import json
import os
from typing import TYPE_CHECKING, Optional, Tuple
from libcloudforensics import errors
from libcloudforensics import logging_utils
from libcloudforensics.providers.aws.internal import common
  from libcloudforensics.providers.aws.internal import account  # pylint: disable=cyclic-import

          raise errors.ResourceNotFoundError('Could not locate role with name {0:s} after creation failure due to EntityAlreadyExistsException'
          # pylint: enable=line-too-long
            .format(name), __name__) from exception

        roles = self.client.list_roles(Marker=roles['Marker'])

  def DeleteRole(self, role_name: str) -> None:
    """Delete an IAM role.

    Args:
      role_name (str): The name of the role to delete.
    """
    logger.info('Deleting IAM role {0:s}'.format(role_name))
    try:
      self.client.delete_role(RoleName=role_name)
    except self.client.exceptions.NoSuchEntityException:
      logger.info('IAM role {0:s} did not exist'.format(role_name))

  def AttachPolicyToRole(self, policy_arn: str, role_name: str) -> None:
    """Attaches an IAM policy to an IAM role.

    Args:
      policy_arn (str): The Policy Arn.
      role_name (str): The Role Name.
    """
    logger.info('Attaching policy {0:s} to role {1:s}'
      .format(policy_arn, role_name))
    try:
      self.client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
    except Exception as e:

      raise errors.ResourceNotFoundError(