forked from sillelien/docker-mysql-backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.sh
executable file
·90 lines (72 loc) · 2.79 KB
/
start.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/bash -x
EXCLUDE_OPT=
PASS_OPT=
export MYSQL_HOST=$MYSQL_PORT_3306_TCP_ADDR
export MYSQL_PORT=$MYSQL_PORT_3306_TCP_PORT
export MYSQL_PASSWORD=$MYSQL_ENV_MYSQL_PASS
export MYSQL_USER=$MYSQL_ENV_MYSQL_USER
export MYSQL_DB=$MYSQL_ENV_ON_CREATE_DB
for i in "$@"; do
case $i in
--exclude=*)
EXCLUDE_OPT="${i#*=}"
shift
;;
*)
# unknown option
;;
esac
done
if [ -n $MYSQL_PASSWORD ]; then
PASS_OPT="--password=${MYSQL_PASSWORD}"
fi
if [ -n $EXCLUDE_OPT ]; then
EXCLUDE_OPT="| grep -Ev (${EXCLUDE_OPT//,/|})"
fi
if [ "$1" == "backup" ]; then
databases=`mysql --user=$MYSQL_USER --host=$MYSQL_HOST --port=$MYSQL_PORT ${PASS_OPT} -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema) ${EXCLUDE_OPT}"`
for db in $databases; do
echo "dumping $db"
mysqldump --force --opt --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER --databases $db ${PASS_OPT} | gzip > "/tmp/$db.gz"
if [ $? == 0 ]; then
aws s3 cp /tmp/$db.gz s3://$S3_BUCKET/$S3_PATH/$db.gz
if [ $? == 0 ]; then
rm /tmp/$db.gz
else
>&2 echo "couldn't transfer $db.gz to S3"
fi
else
>&2 echo "couldn't dump $db"
fi
done
elif [ "$1" == "restore" ]; then
if [ -n "$2" ]; then
archives=$2.gz
else
archives=`aws s3 ls s3://$S3_BUCKET/$S3_PATH/ | awk '{print $4}' ${EXCLUDE_OPT}`
fi
for archive in $archives; do
tmp=/tmp/$archive
echo "restoring $archive"
echo "...transferring"
aws s3 cp s3://$S3_BUCKET/$S3_PATH/$archive $tmp
if [ $? == 0 ]; then
echo "...restoring"
db=`basename --suffix=.gz $archive`
if [ -n $MYSQL_PASSWORD ]; then
yes | mysqladmin --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER --password=$MYSQL_PASSWORD drop $db
mysql --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER --password=$MYSQL_PASSWORD -e "CREATE DATABASE $db CHARACTER SET $RESTORE_DB_CHARSET COLLATE $RESTORE_DB_COLLATION"
gunzip -c $tmp | mysql --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER --password=$MYSQL_PASSWORD $db
else
yes | mysqladmin --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER drop $db
mysql --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER -e "CREATE DATABASE $db CHARACTER SET $RESTORE_DB_CHARSET COLLATE $RESTORE_DB_COLLATION"
gunzip -c $tmp | mysql --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER $db
fi
else
rm $tmp
fi
done
else
>&2 echo "You must provide either backup or restore to run this container"
exit 64
fi