def test_create_iam_user(self):
        """Test create_iam_user
        """
        treadmill_aws.iamclient.get_user.side_effect = exc.NotFoundError('x')
        treadmill_aws.iamclient.get_role.side_effect = exc.NotFoundError('x')

        iam_conn = mock.MagicMock()
        iam_conn.create_user.return_value = {
            'User': {
                'Arn': 'arn:aws:iam::236968667438:user/r',
                'CreateDate': datetime.datetime(2018, 5, 15, 19, 10, 52,
                                                915000),
                'Path': '/',
                'UserId': 'ABCDFEFGABCDEFG',
                'UserName': '******'
            }
        }

        result = usermanager.create_iam_user(iam_conn,
                                             user_name='foo',
                                             policy='xxx')

        iam_conn.create_user.assert_called_with(UserName='******', Path='/')
        iam_conn.create_role.assert_called_with(
            RoleName='foo', Path='/', AssumeRolePolicyDocument='"xxx"')
Beispiel #2
0
def attach_role_policy(iam_conn, role_name, policy_arn):
    """Attach role policies"""
    try:
        return iam_conn.attach_role_policy(RoleName=role_name,
                                           PolicyArn=policy_arn)
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #3
0
def delete_role(iam_conn, role_name):
    """Delete IAM role.
    """
    try:
        return iam_conn.delete_role(RoleName=role_name)
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #4
0
def update_assume_role_policy(iam_conn, role_name, policy_document):
    """Update assume role policy."""
    try:
        iam_conn.update_assume_role_policy(RoleName=role_name,
                                           PolicyDocument=policy_document)
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #5
0
 def get(self, job_id):
     """Return Treadmill cron configuration."""
     job = impl.get(job_id)
     if not job:
         raise exc.NotFoundError(
             'job does not exist: {}'.format(job_id))
     return job
Beispiel #6
0
def delete_user(iam_conn, user_name):
    """Delete IAM user.
    """
    try:
        return iam_conn.delete_user(UserName=user_name)
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #7
0
 def get(self, instance_id):
     """Return Treadmill instance configuration."""
     instance = impl.get(instance_id)
     if not instance:
         raise exc.NotFoundError(
             'Instance does not exist: {}'.format(instance_id))
     return instance
Beispiel #8
0
def update_job(scheduler, job_id, job_name, func, func_kwargs, trigger_args):
    """Update an existing job/model.
    """
    _LOGGER.debug(
        'job_id: %s, job_name: %s, func: %s, func_kwargs: %r, trigger_args: '
        '%r', job_id, job_name, func, func_kwargs, trigger_args)

    job = get_job(scheduler, job_id)
    if not job:
        raise exc.NotFoundError('{} does not exist'.format(job_id))

    is_paused = _is_paused(job)

    _LOGGER.info('Updating job %s', job_id)
    job = scheduler.add_job(func,
                            trigger='cron',
                            id=job_id,
                            name=job_name,
                            replace_existing=True,
                            misfire_grace_time=ONE_DAY_IN_SECS,
                            kwargs=func_kwargs,
                            **trigger_args)

    if is_paused:
        job.pause()

    return job
Beispiel #9
0
 def get(self, instance_id):
     """Return Treadmill instance state."""
     state = impl.get(instance_id)
     if state is None:
         raise exc.NotFoundError(
             'Instance does not exist: {}'.format(instance_id))
     return state
Beispiel #10
0
def attach_user_policy(iam_conn, user_name, policy_arn):
    """Attach user policies"""
    try:
        return iam_conn.attach_user_policy(UserName=user_name,
                                           PolicyArn=policy_arn)
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #11
0
def get_user(iam_conn, user_name):
    """Get IAM user information.
    """
    try:
        return iam_conn.get_user(UserName=user_name)['User']
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #12
0
def update_role(iam_conn, role_name, max_session_duration):
    """Update IAM role.
    """
    try:
        response = iam_conn.update_role(
            RoleName=role_name, MaxSessionDuration=max_session_duration)
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))
Beispiel #13
0
 def get(self, app_name):
     """Return trace information of a Treadmill application.
     """
     trace_info = impl.get(app_name)
     if trace_info is None:
         raise exc.NotFoundError(
             'No trace information available for {}'.format(app_name))
     return trace_info
Beispiel #14
0
def delete_images(ec2_conn, ids=None, tags=None, owners=None, name=None):
    """Delete (unregister) AMI images."""
    images = list_images(
        ec2_conn, ids=ids, tags=tags, owners=owners, name=name
    )

    if not images:
        if ids:
            raise exc.NotFoundError('No image id {} found.'.format(ids))
        if tags:
            raise exc.NotFoundError('No image tagged {} found.'.format(tags))
        if name:
            raise exc.NotFoundError('No image named {} found.'.format(name))

    for image in images:
        _LOGGER.info('deleting image: %s', image['ImageId'])
        ec2_conn.deregister_image(ImageId=image['ImageId'])
Beispiel #15
0
 def get(rsrc_id):
     """Get instance configuration."""
     try:
         tkt_info = os.path.join(self._info_dir, rsrc_id)
         _LOGGER.info('Processing: %s', tkt_info)
         with open(tkt_info) as f:
             return json.loads(f.read())
     except FileNotFoundError:
         raise exc.NotFoundError(rsrc_id)
Beispiel #16
0
def get_image(ec2_conn, ids=None, tags=None, owners=None, name=None):
    """Get single image matching criteria.

    If more than one image match, raise exception NonUniqueError.
    """
    images = list_images(
        ec2_conn, ids=ids, tags=tags, owners=owners, name=name
    )

    if not images:
        if ids:
            raise exc.NotFoundError('No image id {} found.'.format(ids))
        if tags:
            raise exc.NotFoundError('No image tagged {} found.'.format(tags))
        if name:
            raise exc.NotFoundError('No image named {} found.'.format(name))

    image = images.pop(0)
    if images:
        raise aws.NotUniqueError()

    return image
Beispiel #17
0
def _explain(inst_id):
    """Explain application placement"""
    with lc.LogContext(_LOGGER, inst_id):
        start = time.time()
        ro_scheduler = get_readonly_scheduler()
        _LOGGER.info('ro_scheduler was ready in %s secs', time.time() - start)

        try:
            instance = ro_scheduler.cell.apps[inst_id]
        except KeyError:
            raise exc.NotFoundError(inst_id)

        if instance.server:
            raise exc.FoundError('instance {} is already placed on {}'.format(
                inst_id, instance.server))

        return reports.explain_placement(ro_scheduler.cell, instance,
                                         'servers')
Beispiel #18
0
def get_instance(ec2_conn, ids=None, tags=None, hostnames=None, state=None):
    """Get single instance matching criteria.

    If more than one image match, raise exception NonUniqueError.
    """
    instances = list_instances(ec2_conn,
                               ids=ids,
                               tags=tags,
                               hostnames=hostnames,
                               state=state)

    if not instances:
        raise exc.NotFoundError(
            'No instance with hostname {} found.'.format(hostnames))
    elif len(instances) > 1:
        raise aws.NotUniqueError()

    return instances.pop(0)
Beispiel #19
0
def list_snapshots(ec2_conn, name=None, ids=None, tags=None):
    """List Snapshots."""

    filters = []

    if name:
        filters.append({'Name': 'tag:Name', 'Values': [name]})

    if ids:
        filters.append({'Name': 'snapshot-id', 'Values': ids})

    if tags and not filters:
        filters = aws.build_tags_filter(tags)

    response = ec2_conn.describe_snapshots(Filters=filters)
    if response['Snapshots']:
        return response['Snapshots']
    else:
        raise exc.NotFoundError('No snapshot match criteria.')
    def test_create_iam_role(self):
        """Test create_iam_user
        """
        treadmill_aws.iamclient.get_role.side_effect = exc.NotFoundError('x')

        iam_conn = mock.MagicMock()
        iam_conn.create_role.return_value = {
            'Role': {
                'Arn': 'arn:aws:iam::236968667438:role/xxx',
                'Path': '/',
                'RoleId': 'ABSDEFGABCDEFG',
                'RoleName': 'xxx',
                'AssumeRolePolicyDocument': {
                    'Version':
                    '2012-10-17',
                    'Statement': [{
                        'Action': 'sts:AssumeRole',
                        'Effect': 'Allow',
                        'Principal': {
                            'AWS': 'arn:aws:iam::12345:root'
                        }
                    }]
                }
            }
        }

        result = usermanager.create_iam_role(
            iam_conn,
            role_name='xxx',
            policy={'foo': 'bar'},
        )

        iam_conn.create_role.assert_called_with(
            RoleName='xxx',
            Path='/',
            AssumeRolePolicyDocument='{"foo": "bar"}')
Beispiel #21
0
 def _check_resource(cgroup, data):
     """Validate cgroup stats resource."""
     if not data:
         raise exc.NotFoundError('Cgroup does not exist: {}'.format(cgroup))
Beispiel #22
0
def get_role(iam_conn, role_name):
    """Return role by name."""
    try:
        return iam_conn.get_role(RoleName=role_name)['Role']
    except iam_conn.exceptions.NoSuchEntityException as err:
        raise exc.NotFoundError(str(err))