<commit_before>########
# Copyright (c) 2020 Cloudify Platform Ltd. All rights reserved
#
# 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
import shutil
import tempfile
import requests
import traceback

from setuptools import archive_util

from cloudify._compat import unquote
from cloudify.decorators import workflow
from cloudify.manager import get_rest_client
from cloudify.models_states import BlueprintUploadState
from cloudify.exceptions import InvalidBlueprintImport, WorkflowFailed
from cloudify.constants import (CONVENTION_APPLICATION_BLUEPRINT_FILE,
                                SUPPORTED_ARCHIVE_TYPES)

from dsl_parser import constants, tasks
from dsl_parser import utils as dsl_parser_utils
from dsl_parser.exceptions import DSLParsingException


@workflow
def upload(ctx, **kwargs):

    client = get_rest_client()

    # extract the execution parameters
    blueprint_id = kwargs['blueprint_id']
    app_file_name = kwargs['app_file_name']
    url = kwargs['url']
    file_server_root = kwargs['file_server_root']
    validate_only = kwargs['validate_only']

    # Download the archive, one way or the other
    archive_target_path = tempfile.mkdtemp()
    if url:
        # download the blueprint archive from URL using requests:
        if not validate_only:
            client.blueprints.update(
                blueprint_id,
                update_dict={'state': BlueprintUploadState.UPLOADING})
        try:
            with requests.get(url, stream=True, timeout=(5, None)) as resp:
                resp.raise_for_status()
                archive_file_path = os.path.join(archive_target_path,
                                                 os.path.basename(url))
                with open(archive_file_path, 'wb') as f:
                    for chunk in resp.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)

        except requests.exceptions.RequestException as e:
            client.blueprints.update(
                blueprint_id,
                update_dict={'state': BlueprintUploadState.FAILED_UPLOADING,
                             'error': str(e),
                             'error_traceback': traceback.format_exc()})
            remove(archive_target_path)
            raise

        # Upload the downloaded archive to the manager
        if not validate_only:
            client.blueprints.upload_archive(
                blueprint_id,
                archive_path=archive_file_path)

    else:
        # download the blueprint archive using REST<commit_msg>Handle any exception whatsoever, otherwise blueprint stays in 'uploading' state, stuck forever (#2623)<commit_after>########
# Copyright (c) 2020 Cloudify Platform Ltd. All rights reserved
#
# 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
import shutil
import tempfile
import requests
import traceback

from setuptools import archive_util

from cloudify._compat import unquote
from cloudify.decorators import workflow
from cloudify.manager import get_rest_client
from cloudify.models_states import BlueprintUploadState
from cloudify.exceptions import InvalidBlueprintImport, WorkflowFailed
from cloudify.constants import (CONVENTION_APPLICATION_BLUEPRINT_FILE,
                                SUPPORTED_ARCHIVE_TYPES)

from dsl_parser import constants, tasks
from dsl_parser import utils as dsl_parser_utils
from dsl_parser.exceptions import DSLParsingException


@workflow
def upload(ctx, **kwargs):

    client = get_rest_client()

    # extract the execution parameters
    blueprint_id = kwargs['blueprint_id']
    app_file_name = kwargs['app_file_name']
    url = kwargs['url']
    file_server_root = kwargs['file_server_root']
    validate_only = kwargs['validate_only']

    # Download the archive, one way or the other
    archive_target_path = tempfile.mkdtemp()
    if url:
        # download the blueprint archive from URL using requests:
        if not validate_only:
            client.blueprints.update(
                blueprint_id,
                update_dict={'state': BlueprintUploadState.UPLOADING})
        try:
            with requests.get(url, stream=True, timeout=(5, None)) as resp:
                resp.raise_for_status()
                archive_file_path = os.path.join(archive_target_path,
                                                 os.path.basename(url))
                with open(archive_file_path, 'wb') as f:
                    for chunk in resp.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)

        except Exception as e:
            client.blueprints.update(
                blueprint_id,
                update_dict={'state': BlueprintUploadState.FAILED_UPLOADING,
                             'error': str(e),
                             'error_traceback': traceback.format_exc()})
            remove(archive_target_path)
            raise

        # Upload the downloaded archive to the manager
        if not validate_only:
            client.blueprints.upload_archive(
                blueprint_id,
                archive_path=archive_file_path)

    else:
        # download the blueprint archive using REST
{'fraction_non_alphanumeric': 0.06633472534532606, 'fraction_numerical': 0.004818503051718599, 'mean_word_length': 2.5521962350256704, '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': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2267504', 'n_tokens_mistral': 1633, 'n_tokens_neox': 1588, 'n_words': 507}