def validate_dockerrun_v2(dockerrun):

    if dockerrun is None:
        raise ValidationError(strings['local.missingdockerrun'])

    elif _get_version(dockerrun) != VERSION_TWO:
        raise ValidationError(strings['local.invaliddockerrunversion'])
示例#2
0
def validate_build_config(build_config):
    if build_config.service_role is not None:
        # Verify that the service role exists in the customers account
        from ebcli.lib.iam import get_roles
        role = build_config.service_role
        validated_role = None
        existing_roles = get_roles()
        for existing_role in existing_roles:
            if role == existing_role['Arn'] or role == existing_role[
                    'RoleName']:
                validated_role = existing_role['Arn']

        if validated_role is None:
            LOG.debug(
                "Role '{0}' not found in retrieved list of roles".format(role))
            raise ValidationError("Role '{0}' does not exist.".format(role))
        build_config.service_role = validated_role
    else:
        io.log_warning(
            "To learn more about creating a service role for CodeBuild, see Docs:"
            " https://docs-aws.amazon.com/codebuild/latest/userguide/setting-up.html#setting-up-service-role"
        )
        raise ValidationError(
            "No service role specified in buildspec; this is a required argument."
        )
        # Fail because the service role is required
    if build_config.image is None:
        #  Fail because the image is required
        raise ValidationError(
            "No image specified in buildspec; this is a required argument.")
def validate_dockerrun_v1(dockerrun, is_used_to_make_dockerfile):
    """
    Validates given Dockerrun.aws.json version, and that if no Dockerfile
    exists, Image.Name and Ports[0].ContainerPort exists.
    :param dockerrun: dict: dictionary representation of Dockerrun.aws.json
    :param is_used_to_make_dockerfile: bool: whether used to make Dockerfile
    :return: None
    """

    if dockerrun is None:
        return

    if _get_version(dockerrun) != VERSION_ONE:
        raise ValidationError(strings['local.invaliddockerrunversion'])

    if not is_used_to_make_dockerfile:
        return

    if IMG_KEY not in dockerrun or IMG_NAME_KEY not in dockerrun[IMG_KEY]:
        raise ValidationError(strings['local.missingdockerrunimage'])

    elif PORTS_KEY not in dockerrun:
        raise ValidationError(strings['local.missingdockerrunports'])

    elif CONTAINER_PORT_KEY not in dockerrun[PORTS_KEY][0]:
        raise ValidationError(strings['local.missingdockerruncontainerport'])
示例#4
0
def delete_app_version_label(app_name, version_label):

    if version_label:
        # check if version_label exists under app_name
        app_versions = elasticbeanstalk.get_application_versions(app_name)['ApplicationVersions']
        #  if the given version label does not exist at all!
        if not any(version_label == app_version['VersionLabel'] for app_version in app_versions):
            raise ValidationError(strings['appversion.delete.notfound'].format(app_name, version_label))

        envs = elasticbeanstalk.get_app_environments(app_name)

        versions_in_use = [(e.version_label, e.name) for e in envs]

        # find all the environments that are using the app version
        used_envs = [version[1] for version in versions_in_use if version[0] == version_label]

        if used_envs:
            raise ValidationError(strings['appversion.delete.deployed'].format(version_label, ','.join(used_envs)))

        try:
            io.validate_action(prompts['appversion.delete.validate'].format(version_label), "y")
            elasticbeanstalk.delete_application_version(app_name, version_label)
            io.echo('Application Version deleted successfully.')
            delete_successful = True
        except ValidationError:
            io.echo('Application Version will not be deleted.')
            delete_successful = False

        return delete_successful
    else:
        raise NotFoundError(strings['appversion.delete.none'])
示例#5
0
def delete_platform_version(platform_version, force=False):
    arn = _version_to_arn(platform_version)

    if not force:
        io.echo(prompts['platformdelete.confirm'].replace(
            '{platform-arn}', arn))
        io.validate_action(prompts['platformdelete.validate'], arn)

    environments = []
    try:
        environments = [
            env for env in elasticbeanstalk.get_environments()
            if env.platform.version == arn
        ]
    except NotFoundError:
        pass

    if len(environments) > 0:
        _, platform_name, platform_version = PlatformVersion.arn_to_platform(
            arn)
        raise ValidationError(strings['platformdeletevalidation.error'].format(
            platform_name, platform_version,
            '\n '.join([env.name for env in environments])))

    response = elasticbeanstalk.delete_platform(arn)
    request_id = response['ResponseMetadata']['RequestId']
    timeout = 10

    commonops.wait_for_success_events(request_id,
                                      timeout_in_minutes=timeout,
                                      platform_arn=arn)
def _validate_preconfig_dockerfile(soln_stk, container_config,
                                   full_docker_path):
    """
    Validates that the Dockerfile found at full_docker_path has the correct
    Docker base image that matches runtime Docker image appropriate for this
    solution stack. For example, the given solution stack:

    64bit Debian jessie v1.2.0 running GlassFish 4.1 Java 8 (Preconfigured - Docker)

    must have

    glassfish-runtime-4.1-jdk8 base image in the Dockerfile.

    :param soln_stk: SolutionStack: the solution stack
    :param container_config: dict: container_config.json as dict
    :param full_docker_path: str: path to the Dockerfile
    :return: bool
    """

    container_info = containerops._get_preconfig_info(soln_stk,
                                                      container_config)
    expected_img = container_info[containerops.RUNTIME_IMG_KEY]
    actual_img = commands._get_base_img(full_docker_path)
    err_msg = (
        'Invalid base Docker img in Dockerfile. Expected {} but got {}'.format(
            expected_img, actual_img))
    if actual_img != expected_img:
        raise ValidationError(err_msg)
示例#7
0
def _fst_match_in_dockerfile(full_docker_path, predicate, not_found_error_msg):
    raw_lines = fileoperations.readlines_from_text_file(full_docker_path)
    stripped_lines = (x.strip() for x in raw_lines)
    try:
        line = next(x for x in stripped_lines if predicate(x))
        return line.split()
    except StopIteration:
        raise ValidationError(not_found_error_msg)
示例#8
0
def delete_app_version_label(app_name, version_label):

    if version_label:
        app_versions = elasticbeanstalk.get_application_versions(
            app_name)['ApplicationVersions']
        if not any(version_label == app_version['VersionLabel']
                   for app_version in app_versions):
            raise ValidationError(strings['appversion.delete.notfound'].format(
                app_name, version_label))

        envs = elasticbeanstalk.get_app_environments(app_name)

        versions_in_use = [(e.version_label, e.name) for e in envs]

        used_envs = [
            version[1] for version in versions_in_use
            if version[0] == version_label
        ]

        if used_envs:
            raise ValidationError(strings['appversion.delete.deployed'].format(
                version_label, ','.join(used_envs)))

        should_delete = io.get_boolean_response(
            text=prompts['appversion.delete.validate'].format(version_label),
            default=True)
        if not should_delete:
            io.echo('Application Version will not be deleted.')
            delete_successful = False
        else:
            elasticbeanstalk.delete_application_version(
                app_name, version_label)
            io.echo('Application Version deleted successfully.')
            delete_successful = True

        return delete_successful
    else:
        raise NotFoundError(strings['appversion.delete.none'])
def get_dockerrun(dockerrun_path):
    """
    Return dict representation of Dockerrun.aws.json in dockerrun_path
    Return None if Dockerrun doesn't exist at that path.
    :param dockerrun_path: str: full path to Dockerrun.aws.json
    :return: dict
    """

    try:
        return fileoperations.get_json_dict(dockerrun_path)
    except ValueError:
        raise ValidationError(strings['local.invalidjson'])
    except IOError:  # Dockerrun.aws.json doesn't exist
        return None
示例#10
0
def get_build_configuration():
    # TODO: Verify this is correct.
    # Values expected in the eb config section in BuildSpec
    service_role_key = 'CodeBuildServiceRole'
    image_key = 'Image'
    compute_key = 'ComputeType'
    timeout_key = 'Timeout'

    # get setting from global if it exists
    cwd = os.getcwd()  # save working directory

    try:
        _traverse_to_project_root()

        build_spec = _get_yaml_dict(buildspec_name)

        # Assert that special beanstalk section exists
        if buildspec_config_header not in build_spec.keys():
            LOG.debug("Buildspec Keys: {0}".format(build_spec.keys()))
            raise ValidationError("Beanstalk configuration header '{0}' is missing from Buildspec file".format(buildspec_config_header))

        build_configuration = BuildConfiguration()
        beanstalk_build_configs = build_spec[buildspec_config_header]
        LOG.debug("EB Config Keys: {0}".format(beanstalk_build_configs.keys()))

        if service_role_key in beanstalk_build_configs.keys():
            build_configuration.service_role = beanstalk_build_configs[service_role_key]

        if image_key in beanstalk_build_configs.keys():
            build_configuration.image = beanstalk_build_configs[image_key]

        if compute_key in beanstalk_build_configs.keys():
            build_configuration.compute_type = beanstalk_build_configs[compute_key]

        if timeout_key in beanstalk_build_configs.keys():
            build_configuration.timeout = beanstalk_build_configs[timeout_key]

    finally:
        os.chdir(cwd)  # move back to working directory

    return build_configuration
示例#11
0
def make_api_call(service_name, operation_name, **operation_options):
    operation = _set_operation(service_name, operation_name)
    aggregated_error_message = []
    max_attempts = 10

    region = _region_name
    if not region:
        region = 'default'

    attempt = 0
    while True:
        attempt += 1
        if attempt > 1:
            LOG.debug('Retrying -- attempt #' + str(attempt))
        delay = _get_delay(attempt)
        time.sleep(delay)
        try:
            LOG.debug('Making api call: (' + service_name + ', ' +
                      operation_name + ') to region: ' + region +
                      ' with args:' + str(operation_options))
            response_data = operation(**operation_options)
            status = response_data['ResponseMetadata']['HTTPStatusCode']
            LOG.debug('API call finished, status = ' + str(status))
            if response_data:
                LOG.debug('Response: ' + str(response_data))

            return response_data

        except botocore.exceptions.ClientError as e:
            _handle_response_code(e.response, attempt,
                                  aggregated_error_message)
        except botocore.parsers.ResponseParserError as e:
            LOG.debug('Botocore could not parse response received')
            if attempt > max_attempts:
                raise MaxRetriesError(
                    'Max retries exceeded for ResponseParserErrors' +
                    os.linesep.join(aggregated_error_message))

            aggregated_error_message.insert(attempt, str(e))
        except botocore.exceptions.NoCredentialsError:
            LOG.debug('No credentials found')
            raise CredentialsError('Operation Denied. You appear to have no'
                                   ' credentials')
        except botocore.exceptions.PartialCredentialsError as e:
            LOG.debug('Credentials incomplete')
            raise CredentialsError(str(e))

        except (botocore.exceptions.ValidationError,
                botocore.exceptions.ParamValidationError) as e:
            raise ValidationError(str(e))

        except botocore.exceptions.BotoCoreError:
            LOG.error('Botocore Error')
            raise

        except IOError as error:
            if hasattr(error.args[0], 'reason') and str(error.args[0].reason) == \
                    '[Errno -2] Name or service not known':
                raise ConnectionError()

            LOG.error('Error while contacting Elastic Beanstalk Service')
            LOG.debug('error:' + str(error))
            raise ServiceError(error)
示例#12
0
def validate_action(output, expected_input):
    result = get_input(output)

    if result != expected_input:
        raise ValidationError(prompts['terminate.nomatch'])