<commit_before># Copyright (C) GRyCAP - I3M - UPV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os.path
import docker
import scar.logger as logger
from scar.providers.aws.ecr import ECR
from scar.utils import FileUtils, SupervisorUtils
from scar.providers.aws.functioncode import create_function_config


class ContainerImage:

    _CACHE_DIR = '/var/tmp/scar_cache'

    @staticmethod
    def get_asset_name(function_info):
        arch = function_info.get('architectures', ['x86_64'])[0]
        arch = '' if arch == 'x86_64' else "-%s" % arch
        alpine = '-alpine' if function_info.get('container').get('alpine') else ''
        return 'supervisor%s%s.zip' % (alpine, arch)

    @staticmethod
    def delete_ecr_image(resources_info):
        """Delete the ECR repository created in _create_ecr_image function."""
        ecr_cli = ECR(resources_info)
        repo_name = resources_info.get('lambda').get('name')
        if ecr_cli.get_repository_uri(repo_name):
            logger.info('Deleting ECR repo: %s' % repo_name)
            ecr_cli.delete_repository(repo_name)

    @staticmethod
    def get_supervisor_zip(resources_info, supervisor_version):
        """Get from cache or download supervisor zip."""
        asset_name = ContainerImage.get_asset_name(resources_info.get('lambda'))
        supervisor_path = FileUtils.join_paths(ContainerImage._CACHE_DIR, supervisor_version)
        supervisor_zip_path = FileUtils.join_paths(supervisor_path, asset_name)
        if os.path.isfile(supervisor_zip_path):
            return supervisor_zip_path
        else:
            if not os.path.exists(supervisor_path):
                os.makedirs(supervisor_path)
            return SupervisorUtils.download_supervisor_asset(
                supervisor_version,
                asset_name,
                supervisor_zip_path
            )

    @staticmethod
    def create_ecr_image(resources_info, supervisor_version):
        """Creates an ECR image using the user provided image adding the supervisor tools."""
        # If the user set an already prepared image return the image name
        image_name = ContainerImage._ecr_image_name_prepared(resources_info.get('lambda').get('container'))
        if image_name:
            return image_name

        tmp_folder = FileUtils.create_tmp_dir()

        # Create function config file
        FileUtils.write_yaml(FileUtils.join_paths(tmp_folder.name, "function_config.yaml"),<commit_msg>Improve code<commit_after># Copyright (C) GRyCAP - I3M - UPV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os.path
import docker
import scar.logger as logger
from scar.providers.aws.ecr import ECR
from scar.utils import FileUtils, SupervisorUtils
from scar.providers.aws.functioncode import create_function_config


class ContainerImage:

    _CACHE_DIR = '/var/tmp/scar_cache'

    @staticmethod
    def get_asset_name(function_info):
        arch = function_info.get('architectures', ['x86_64'])[0]
        arch = '' if arch == 'x86_64' else "-%s" % arch
        alpine = '-alpine' if function_info.get('container').get('alpine') else ''
        return 'supervisor%s%s.zip' % (alpine, arch)

    @staticmethod
    def delete_ecr_image(resources_info):
        """Delete the ECR repository created in _create_ecr_image function."""
        ecr_cli = ECR(resources_info)
        repo_name = resources_info.get('lambda').get('name')
        if ecr_cli.get_repository_uri(repo_name):
            logger.info('Deleting ECR repo: %s' % repo_name)
            ecr_cli.delete_repository(repo_name)

    @staticmethod
    def is_supervisor_zip_cached(asset_name, supervisor_version):
        """Check if specified supervisor asset is cached."""
        supervisor_path = FileUtils.join_paths(ContainerImage._CACHE_DIR, supervisor_version)
        supervisor_zip_path = FileUtils.join_paths(supervisor_path, asset_name)
        if os.path.isfile(supervisor_zip_path):
            return supervisor_zip_path
        elif not os.path.exists(supervisor_path):
            os.makedirs(supervisor_path)
        return None

    @staticmethod
    def get_supervisor_zip(resources_info, supervisor_version):
        """Get from cache or download supervisor zip."""
        asset_name = ContainerImage.get_asset_name(resources_info.get('lambda'))
        supervisor_zip_path = ContainerImage.is_supervisor_zip_cached(asset_name, supervisor_version)
        if supervisor_zip_path:
            # It is cached, do not download again
            return supervisor_zip_path
        else:
            return SupervisorUtils.download_supervisor_asset(
                supervisor_version,
                asset_name,
                supervisor_zip_path
            )

    @staticmethod
    def create_ecr_image(resources_info, supervisor_version):
        """Creates an ECR image using the user provided image adding the supervisor tools."""
        # If the user set an already prepared image return the image name
        image_name = ContainerImage._ecr_image_name_prepared(resources_info.get('lambda').get('container'))
        if image_name:
            return image_name

        tmp_folder = FileUtils.create_tmp_dir()

        # Create function config file
        FileUtils.write_yaml(FileUtils.join_paths(tmp_folder.name, "function_config.yaml"),
{'fraction_non_alphanumeric': 0.08264462809917356, 'fraction_numerical': 0.004450095359186269, 'mean_word_length': 3.3161865569272977, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7303353', 'n_tokens_mistral': 1800, 'n_tokens_neox': 1735, 'n_words': 487}