def daemon_encrypt()

in VMEncryption/main/handle.py [0:0]


def daemon_encrypt():
    # Ensure the same configuration is executed only once
    # If the previous enable failed, we do not have retry logic here.
    # TODO Remount all
    encryption_marker = EncryptionMarkConfig(logger, encryption_environment)
    if encryption_marker.config_file_exists():
        logger.log("encryption is marked.")

    """
    search for the bek volume, then mount it:)
    """
    disk_util = DiskUtil(hutil, DistroPatcher, logger, encryption_environment)

    encryption_config = EncryptionConfig(encryption_environment, logger)
    bek_passphrase_file = None
    """
    try to find the attached bek volume, and use the file to mount the crypted volumes,
    and if the passphrase file is found, then we will re-use it for the future.
    """
    bek_util = BekUtil(disk_util, logger)
    if encryption_config.config_file_exists():
        bek_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)

    if bek_passphrase_file is None:
        hutil.do_exit(exit_code=CommonVariables.passphrase_file_not_found,
                      operation='EnableEncryption',
                      status=CommonVariables.extension_error_status,
                      code=CommonVariables.passphrase_file_not_found,
                      message='Passphrase file not found.')

    executor = CommandExecutor(logger)
    is_not_in_stripped_os = bool(executor.Execute("mountpoint /oldroot"))
    volume_type = encryption_config.get_volume_type().lower()

    if (volume_type == CommonVariables.VolumeTypeData.lower() or volume_type == CommonVariables.VolumeTypeAll.lower()) and \
       is_not_in_stripped_os:
        try:
            while not daemon_encrypt_data_volumes(encryption_marker=encryption_marker,
                                                  encryption_config=encryption_config,
                                                  disk_util=disk_util,
                                                  bek_util=bek_util,
                                                  bek_passphrase_file=bek_passphrase_file):
                logger.log("Calling daemon_encrypt_data_volumes again")
        except Exception as e:
            message = "Failed to encrypt data volumes with error: {0}, stack trace: {1}".format(e, traceback.format_exc())
            logger.log(msg=message, level=CommonVariables.ErrorLevel)
            hutil.do_exit(exit_code=CommonVariables.encryption_failed,
                          operation='EnableEncryptionDataVolumes',
                          status=CommonVariables.extension_error_status,
                          code=CommonVariables.encryption_failed,
                          message=message)
        else:
            hutil.do_status_report(operation='EnableEncryptionDataVolumes',
                                   status=CommonVariables.extension_success_status,
                                   status_code=str(CommonVariables.success),
                                   message='Encryption succeeded for data volumes')
            disk_util.log_lsblk_output()
            mount_encrypted_disks(disk_util, bek_util, bek_passphrase_file, encryption_config)

    if volume_type == CommonVariables.VolumeTypeOS.lower() or \
       volume_type == CommonVariables.VolumeTypeAll.lower():
        # import OSEncryption here instead of at the top because it relies
        # on pre-req packages being installed (specifically, python-six on Ubuntu)
        distro_name = DistroPatcher.distro_info[0]
        distro_version = DistroPatcher.distro_info[1]

        os_encryption = None

        if (((distro_name == 'redhat' and distro_version == '7.3') or
             (distro_name == 'redhat' and distro_version == '7.4') or
             (distro_name == 'redhat' and distro_version == '7.5') or
             (distro_name == 'redhat' and distro_version == '7.6') or
             (distro_name == 'redhat' and distro_version == '7.7')) and
           (disk_util.is_os_disk_lvm() or os.path.exists('/volumes.lvm'))):
            from oscrypto.rhel_72_lvm import RHEL72LVMEncryptionStateMachine
            os_encryption = RHEL72LVMEncryptionStateMachine(hutil=hutil,
                                                            distro_patcher=DistroPatcher,
                                                            logger=logger,
                                                            encryption_environment=encryption_environment)
        elif (((distro_name == 'centos' and distro_version == '7.3.1611') or
              (distro_name == 'centos' and distro_version.startswith('7.4')) or
              (distro_name == 'centos' and distro_version.startswith('7.5')) or
              (distro_name == 'centos' and distro_version.startswith('7.6')) or
              (distro_name == 'centos' and distro_version.startswith('7.7'))) and
              (disk_util.is_os_disk_lvm() or os.path.exists('/volumes.lvm'))):
            from oscrypto.rhel_72_lvm import RHEL72LVMEncryptionStateMachine
            os_encryption = RHEL72LVMEncryptionStateMachine(hutil=hutil,
                                                            distro_patcher=DistroPatcher,
                                                            logger=logger,
                                                            encryption_environment=encryption_environment)
        elif ((distro_name == 'redhat' and distro_version == '7.2') or
              (distro_name == 'redhat' and distro_version == '7.3') or
              (distro_name == 'redhat' and distro_version == '7.4') or
              (distro_name == 'redhat' and distro_version == '7.5') or
              (distro_name == 'redhat' and distro_version == '7.6') or
              (distro_name == 'redhat' and distro_version == '7.7') or
              (distro_name == 'centos' and distro_version.startswith('7.7')) or
              (distro_name == 'centos' and distro_version.startswith('7.6')) or
              (distro_name == 'centos' and distro_version.startswith('7.5')) or
              (distro_name == 'centos' and distro_version.startswith('7.4')) or
              (distro_name == 'centos' and distro_version == '7.3.1611') or
              (distro_name == 'centos' and distro_version == '7.2.1511')):
            from oscrypto.rhel_72 import RHEL72EncryptionStateMachine
            os_encryption = RHEL72EncryptionStateMachine(hutil=hutil,
                                                         distro_patcher=DistroPatcher,
                                                         logger=logger,
                                                         encryption_environment=encryption_environment)
        elif distro_name == 'redhat' and distro_version == '6.8':
            from oscrypto.rhel_68 import RHEL68EncryptionStateMachine
            os_encryption = RHEL68EncryptionStateMachine(hutil=hutil,
                                                         distro_patcher=DistroPatcher,
                                                         logger=logger,
                                                         encryption_environment=encryption_environment)
        elif distro_name == 'centos' and (distro_version == '6.8' or distro_version == '6.9'):
            from oscrypto.centos_68 import CentOS68EncryptionStateMachine
            os_encryption = CentOS68EncryptionStateMachine(hutil=hutil,
                                                           distro_patcher=DistroPatcher,
                                                           logger=logger,
                                                           encryption_environment=encryption_environment)
        elif distro_name == 'Ubuntu' and distro_version in ['16.04', '18.04']:
            from oscrypto.ubuntu_1604 import Ubuntu1604EncryptionStateMachine
            os_encryption = Ubuntu1604EncryptionStateMachine(hutil=hutil,
                                                             distro_patcher=DistroPatcher,
                                                             logger=logger,
                                                             encryption_environment=encryption_environment)
        elif distro_name == 'Ubuntu' and distro_version == '14.04':
            from oscrypto.ubuntu_1404 import Ubuntu1404EncryptionStateMachine
            os_encryption = Ubuntu1404EncryptionStateMachine(hutil=hutil,
                                                             distro_patcher=DistroPatcher,
                                                             logger=logger,
                                                             encryption_environment=encryption_environment)
        else:
            message = "OS volume encryption is not supported on {0} {1}".format(distro_name,
                                                                                distro_version)
            logger.log(msg=message, level=CommonVariables.ErrorLevel)
            hutil.do_exit(exit_code=CommonVariables.encryption_failed,
                          operation='EnableEncryptionOSVolume',
                          status=CommonVariables.extension_error_status,
                          code=CommonVariables.encryption_failed,
                          message=message)

        try:
            os_encryption.start_encryption()

            if not os_encryption.state == 'completed':
                raise Exception("did not reach completed state")
            else:
                encryption_marker.clear_config()

        except Exception as e:
            message = "Failed to encrypt OS volume with error: {0}, stack trace: {1}, machine state: {2}".format(e,
                                                                                                                 traceback.format_exc(),
                                                                                                                 os_encryption.state)
            logger.log(msg=message, level=CommonVariables.ErrorLevel)
            hutil.do_exit(exit_code=CommonVariables.encryption_failed,
                          operation='EnableEncryptionOSVolume',
                          status=CommonVariables.extension_error_status,
                          code=CommonVariables.encryption_failed,
                          message=message)

        message = ''
        if volume_type == CommonVariables.VolumeTypeAll.lower():
            message = 'Encryption succeeded for all volumes'
        else:
            message = 'Encryption succeeded for OS volume'

        logger.log(msg=message)
        hutil.do_status_report(operation='EnableEncryptionOSVolume',
                               status=CommonVariables.extension_success_status,
                               status_code=str(CommonVariables.success),
                               message=message)