데이터 엔지니어( 실습 정리 )

데이터 저장 정책에 따른 저장 환경 별 데이터 삭제 스크립트 모음

세용용용용 2024. 10. 16. 18:09

1. 로컬 데이터 삭제 스크립트( local_data_rm.sh )

#!/usr/bin/bash

# 인자 두개인지 확인
if [ "$#" -ne 2 ]; then
        echo "Usage: $0 <로컬 경로> <보존 기간>"
        exit 1
fi

rm_path=$1
preservation_period=$2

find ${rm_path} -type d -mtime +${preservation_period} -exec rm -rf {} +
find ${rm_path} -type f -mtime +${preservation_period} -exec rm -rf {} +

 

 

2. hdfs 데이터 삭제 스크립트( hdfs_data_rm.sh )

#!/usr/bin/bash

# 인자 두개인지 확인
if [ "$#" -ne 2 ]; then
        echo "Usage: $0 <하둡 경로> <보존 기간>"
        exit 1
fi

rm_path=$1
preservation_period=$2

hdfs dfs -ls -R ${rm_path} | awk -v date="$(date -d "${preservation_period} days ago" +%Y-%m-%d)" '$6 < date {print $8}' | xargs -r hdfs dfs -rm -r

 

 

3. hive 데이터 삭제 스크립트( hive_warehouse_rm.sh )

#!/usr/bin/bash

# 인자 두개인지 확인
if [ "$#" -ne 4 ]; then
        echo "Usage: $0 <배치 날짜> <hive 테이블 명> <보존 기간> <파티션 명>"
        exit 1
fi


rm_table_name=$2
preservation_period=$3
partition_name=$4

rm_date=$(date -d "$1 -${preservation_period} days" +%Y%m%d)
# 삭제할 파티션 목록 가져옴
hive_rm_partitions=$(hive -e "select distinct ${partition_name} from ${rm_table_name} where ${partition_name} < ${rm_date}")

for partition in $hive_rm_partitions;
do
        echo "삭제 파티션: ${partition_name}=${partition}"
        hive -e "alter table ${rm_table_name} drop if exists partition (${partition_name}='${partition}')"
done

 

 

4. Aws S3 데이터 삭제 스크립트( Aws_S3_rm.sh )

#!/usr/bin/bash

# 인자 두개인지 확인
if [ "$#" -ne 3 ]; then
        echo "Usage: $0 <배치 날짜> <aws 버킷> <보존 기간>"
        exit 1
fi

batch_date=$1
s3_path=$2
preservation_period=$3

rm_date=$(date -d "${batch_date} - ${preservation_period} days" +%Y%m%d)

s3_path="s3://${s3_path}"
aws s3 ls "${s3_path}" --recursive | while read -r line;
do
        file_size=$(echo ${line} | awk '{print $3}')
        if [ ${file_size} -gt 0 ]; then
                file_path=$(echo ${line} | awk '{print $4}')
                file_date=$(echo ${line} | awk '{print $1}' | sed 's/-//g')

                # 보존 정책 보다 작은 경우 제거
                if [ ${file_date} -lt ${rm_date} ]; then
                        echo "삭제파일 ${file_path}"
                        aws s3 rm ${s3_path}/${file_path}
                fi
        fi
done

 

삭제 확인

 

 

해당 스크립트를 통해 저장 환경 별 데이터를 보관할 수 있습니다!!!