예제 #1
0
파일: __init__.py 프로젝트: JGoutin/accelpy
    def _checksum_verify(cls, checksum_list, data, filename):
        """
        Verify SHA256 checksum

        Args:
            checksum_list (bytes): List of checksum. Should have one
                line per file formatted as "digest filename".
            data (bytes): Data to verify.
            filename (str): Name of file to verify

        Raises:
            accelpy.exceptions.RuntimeException: Invalid Checksum.
        """
        # Get file checksum in checksum file
        for line in checksum_list.decode().splitlines():
            if filename in line:
                checksum = line.split(' ')[0].strip()
                break
        else:
            # Should never raise
            raise RuntimeException(
                f'Unable to update {cls._name()}: No checksum found')

        # Lazy import package that are required only on install
        from hashlib import sha256

        # Verify checksum
        sha = sha256()
        sha.update(data)
        if sha.hexdigest() != checksum:
            raise RuntimeException(
                f'Unable to update {cls._name()}: Invalid checksum')
예제 #2
0
파일: __init__.py 프로젝트: JGoutin/accelpy
    def _download(cls, url):
        """
        Download from URL and handles exceptions.

        Args:
            url (str): URL

        Returns:
            requests.Response: Response.

        Raises:
            accelpy.exceptions.RuntimeException: HTTP Error.
        """
        # Lazy import: Only used on update
        from requests import get
        from requests.exceptions import HTTPError

        response = get(url)

        try:
            response.raise_for_status()
        except HTTPError as error:
            raise RuntimeException(
                f'Unable to update {cls._name()}: {str(error)}')

        return response
예제 #3
0
    def delete(self):
        """
        Delete application definition on Accelize web service.
        """
        if not self._configuration_id:
            raise RuntimeException(
                'Can only delete an application loaded with "from_id"')

        accelize_ws_session.request(
            f'/auth/objects/productconfiguration/{self._configuration_id}/',
            method='delete')
예제 #4
0
파일: __init__.py 프로젝트: iRomi14/accelpy
    def state_list(self):
        """
         list resources within the Terraform state.

        Returns:
            list of str: List of resources.
        """
        result = self._exec('state', 'list', pipe_stdout=True, check=False)

        if result.returncode:
            # Error because no state file, return empty list
            if not self._has_state():
                return []

            # Other errors: Raise
            raise RuntimeException(result.stderr)

        # No errors, return state
        return result.stdout.strip().splitlines()
예제 #5
0
파일: __init__.py 프로젝트: JGoutin/accelpy
    def _gpg_verify(cls, data, signature):
        """
        Verify GPG signature with HashiCorp public key.

        Args:
            data (bytes): Data to verify.
            signature (bytes): Signature against verify data.

        Raises:
            accelpy.exceptions.RuntimeException: Invalid signature.

        References:
            https://www.hashicorp.com/security.html
        """
        # Import HashiCorp GPG public key
        call(
            ('gpg', '--import', join(dirname(__file__), 'gpg_public_key.asc')),
            pipe_stdout=True)

        # Lazy import package that are required only on install
        from tempfile import TemporaryDirectory

        # Verify signature
        with TemporaryDirectory() as tmp:

            data_path = join(tmp, 'data')
            with open(data_path, 'wb') as data_file:
                data_file.write(data)

            signature_path = join(tmp, 'data.sig')
            with open(signature_path, 'wb') as signature_file:
                signature_file.write(signature)

            gpg_valid = call(('gpg', '--verify', signature_path, data_path),
                             pipe_stdout=True,
                             check=False)

        if gpg_valid.returncode:
            raise RuntimeException(
                f'Unable to update {cls._name()}: Invalid signature')
예제 #6
0
파일: __init__.py 프로젝트: iRomi14/accelpy
    def apply(self, quiet=False, retries=10, delay=1.0):
        """
        Builds or changes infrastructure.

        Args:
            quiet (bool): If True, hide outputs.
            retries (int): Number of time to retries to apply the configuration.
                Apply is retried only on a specified set of known retryable
                errors.
            delay (float): Delay to wait between retries
        """
        self._init()

        failures = 0
        args = ['apply', '-no-color', '-auto-approve', '-input=false']
        if isfile(join(self._config_dir, 'tfplan')):
            # Use "tfplan" if any
            args.append('tfplan')

        while True:
            try:
                self._exec(*args, pipe_stdout=quiet)
                break
            except RuntimeException as exception:
                if failures > retries:
                    raise RuntimeException(
                        f'Unable to apply after {retries} retries\n\n'
                        f'{str(exception)}')

                for retryable_error in (
                        "Error requesting spot instances: "
                        "InvalidSubnetID.NotFound: "
                        "No default subnet for availability zone: 'null'",
                        'Error while waiting for spot request',):
                    if retryable_error in str(exception):
                        break
                else:
                    raise
                failures += 1
                sleep(delay)
예제 #7
0
 def _exec(*args, **_):
     """
     Fake calls that raise exceptions on "apply"
     """
     if 'apply' in args:
         raise RuntimeException(exception_message)