├── .actrc ├── .dockerignore ├── .github ├── actions │ └── test │ │ └── action.yml └── workflows │ ├── deploy.yml │ ├── dockerhub-description.yml │ └── test.yml ├── .gitignore ├── .secrets.example ├── CHANGELOG.md ├── Dockerfile ├── Dockerfile.mysql57 ├── LICENSE.txt ├── README.md ├── automysqlbackup ├── defaults ├── docker-compose.build.yml ├── docker-compose.yml ├── my.cnf ├── start.sh └── test ├── test.sh └── testdb-init.sql /.actrc: -------------------------------------------------------------------------------- 1 | -P ubuntu-latest=catthehacker/ubuntu:act-latest 2 | --secret-file .secrets -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .* 2 | *.txt 3 | *.md 4 | docker-compose*.yml 5 | /test/ -------------------------------------------------------------------------------- /.github/actions/test/action.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | inputs: 4 | mysql-version: 5 | required: true 6 | dockerfile: 7 | required: true 8 | 9 | runs: 10 | using: "composite" 11 | steps: 12 | - name: Build and export to docker 13 | uses: docker/build-push-action@v3 14 | with: 15 | context: . 16 | file: ${{ inputs.dockerfile }} 17 | load: true 18 | tags: automysqlbackup:test-${{ inputs.mysql-version }} 19 | 20 | - name: Set up the environment 21 | run: | 22 | echo ::notice::Starting MySQL ${{ inputs.mysql-version }} 23 | docker network create dbtest 24 | docker run --name test-mysql \ 25 | --network dbtest \ 26 | --env MYSQL_ROOT_PASSWORD=my-secret-pw \ 27 | --volume "$(pwd)/test/testdb-init.sql:/docker-entrypoint-initdb.d/testdb-init.sql" \ 28 | --health-cmd 'mysql --database=testdb --password=my-secret-pw --execute="SELECT count(*) > 0 FROM test_table;" --skip-column-names -B' \ 29 | --health-interval 30s \ 30 | --health-retries 5 \ 31 | --health-timeout 10s \ 32 | --detach mysql:${{ inputs.mysql-version }} 33 | timeout 100s bash -c 'while [ $(docker inspect --format="{{.State.Health.Status}}" test-mysql) != 'healthy' ]; do docker inspect --format="{{.State.Health.Status}}" test-mysql; sleep 1; done' || { echo "::error::MySQL server start up failure" && exit 1; } 34 | echo ::notice::MySQL ${{ inputs.mysql-version }} started 35 | shell: bash 36 | 37 | - name: Test backups from root 38 | run: | 39 | DIR="${{ runner.temp }}/automysqlbackup-root" 40 | sudo mkdir -p $DIR 41 | docker run --name automysqlbackup \ 42 | --rm \ 43 | --network dbtest \ 44 | --volume "$DIR:/backup" \ 45 | --env DBHOST=test-mysql \ 46 | --env DBNAMES=all \ 47 | --env USERNAME=root \ 48 | --env PASSWORD=my-secret-pw \ 49 | --env DBNAMES=all \ 50 | --env DBEXCLUDE="performance_schema information_schema" \ 51 | --env IGNORE_TABLES="testdb.ignoretable" \ 52 | automysqlbackup:test-${{ inputs.mysql-version }} 53 | 54 | sudo ./test/test.sh $DIR 55 | shell: bash 56 | 57 | - name: Test backups from the regular user 58 | run: | 59 | DIR="${{ runner.temp }}/automysqlbackup-user" 60 | mkdir -p $DIR 61 | docker run --name automysqlbackup \ 62 | --rm \ 63 | --network dbtest \ 64 | --volume "$DIR:/backup" \ 65 | --env DBHOST=test-mysql \ 66 | --env DBNAMES=all \ 67 | --env USERNAME=root \ 68 | --env PASSWORD=my-secret-pw \ 69 | --env DBNAMES=all \ 70 | --env DBEXCLUDE="performance_schema information_schema" \ 71 | --env IGNORE_TABLES="testdb.ignoretable" \ 72 | --env USER_ID="$(id -u)" \ 73 | --env GROUP_ID="$(id -g)" \ 74 | automysqlbackup:test-${{ inputs.mysql-version }} 75 | 76 | ./test/test.sh $DIR 77 | shell: bash 78 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: "0 0 * * 0" # rebuild once a week 4 | release: 5 | types: 6 | - published 7 | 8 | jobs: 9 | deploy: 10 | name: Deploy latest full release 11 | 12 | strategy: 13 | matrix: 14 | variant: 15 | - dockerfile: Dockerfile 16 | mysql-version: "8.0" 17 | platforms: linux/amd64 18 | latest: true 19 | - dockerfile: Dockerfile.mysql57 20 | mysql-version: "5.7" 21 | platforms: linux/amd64 22 | 23 | runs-on: ubuntu-latest 24 | 25 | steps: 26 | - name: Fetch the latest release 27 | uses: octokit/request-action@v2.x 28 | id: get_latest_release 29 | with: 30 | route: GET /repos/{owner}/{repo}/releases/latest 31 | owner: selim13 32 | repo: docker-automysqlbackup 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | 36 | - name: Checkout all tags 37 | uses: actions/checkout@v3 38 | with: 39 | fetch-depth: 0 40 | 41 | - name: Switch to the latest relese tag 42 | id: latest-release 43 | run: | 44 | LATEST_RELEASE_TAG="${{ fromJSON(steps.get_latest_release.outputs.data).tag_name }}" 45 | git checkout $LATEST_RELEASE_VERSION 46 | echo "::set-output name=latest-release::$(echo $LATEST_RELEASE_TAG | sed 's/^v//')" 47 | 48 | - name: Set up QEMU 49 | uses: docker/setup-qemu-action@v1 50 | 51 | - name: Set up Docker Buildx 52 | id: buildx 53 | uses: docker/setup-buildx-action@v2 54 | 55 | - name: Inspect Buildx 56 | run: | 57 | echo "Name: ${{ steps.buildx.outputs.name }}" 58 | echo "Endpoint: ${{ steps.buildx.outputs.endpoint }}" 59 | echo "Status: ${{ steps.buildx.outputs.status }}" 60 | echo "Flags: ${{ steps.buildx.outputs.flags }}" 61 | echo "Platforms: ${{ steps.buildx.outputs.platforms }}" 62 | 63 | - name: Test the image 64 | uses: ./.github/actions/test 65 | with: 66 | mysql-version: ${{ matrix.variant.mysql-version }} 67 | dockerfile: ${{ matrix.variant.dockerfile }} 68 | 69 | - name: Login to Github Container Registry 70 | uses: docker/login-action@v1 71 | with: 72 | registry: ghcr.io 73 | username: ${{ github.actor }} 74 | password: ${{ secrets.GITHUB_TOKEN }} 75 | 76 | - name: Login to Docker Hub 77 | uses: docker/login-action@v1 78 | with: 79 | username: ${{ secrets.DOCKERHUB_USERNAME }} 80 | password: ${{ secrets.DOCKERHUB_TOKEN }} 81 | 82 | - name: Build and push the image 83 | if: matrix.variant.latest != true 84 | uses: docker/build-push-action@v3 85 | with: 86 | context: . 87 | file: ${{ matrix.variant.dockerfile }} 88 | platforms: ${{ matrix.variant.platforms }} 89 | push: true 90 | tags: | 91 | ghcr.io/${{ github.repository }}:${{ steps.latest-release.outputs.latest-release }}-mysql${{ matrix.variant.mysql-version }} 92 | ${{ secrets.DOCKERHUB_REPOSITORY }}:${{ steps.latest-release.outputs.latest-release }}-mysql${{ matrix.variant.mysql-version }} 93 | cache-from: type=gha 94 | cache-to: type=gha,mode=max 95 | 96 | - name: Build and push the image with the latest tags 97 | if: matrix.variant.latest == true 98 | uses: docker/build-push-action@v3 99 | with: 100 | context: . 101 | file: ${{ matrix.variant.dockerfile }} 102 | platforms: ${{ matrix.variant.platforms }} 103 | push: true 104 | tags: | 105 | ghcr.io/${{ github.repository }}:latest 106 | ghcr.io/${{ github.repository }}:${{ steps.latest-release.outputs.latest-release }} 107 | ghcr.io/${{ github.repository }}:${{ steps.latest-release.outputs.latest-release }}-mysql${{ matrix.variant.mysql-version }} 108 | ${{ secrets.DOCKERHUB_REPOSITORY }}:latest 109 | ${{ secrets.DOCKERHUB_REPOSITORY }}:${{ steps.latest-release.outputs.latest-release }} 110 | ${{ secrets.DOCKERHUB_REPOSITORY }}:${{ steps.latest-release.outputs.latest-release }}-mysql${{ matrix.variant.mysql-version }} 111 | cache-from: type=gha 112 | cache-to: type=gha,mode=max 113 | -------------------------------------------------------------------------------- /.github/workflows/dockerhub-description.yml: -------------------------------------------------------------------------------- 1 | name: Update Docker Hub Description 2 | on: 3 | push: 4 | branches: 5 | - master 6 | paths: 7 | - README.md 8 | - .github/workflows/dockerhub-description.yml 9 | 10 | jobs: 11 | update-hub-description: 12 | name: Update Docker Hub Description 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v3 16 | 17 | - name: Docker Hub Description 18 | uses: peter-evans/dockerhub-description@v3 19 | with: 20 | username: ${{ secrets.DOCKERHUB_USERNAME }} 21 | password: ${{ secrets.DOCKERHUB_TOKEN }} 22 | repository: ${{ secrets.DOCKERHUB_REPOSITORY }} 23 | short-description: ${{ github.event.repository.description }} 24 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | tags-ignore: 4 | - "v*" # exclude releases 5 | 6 | jobs: 7 | test: 8 | name: Build and test the image 9 | 10 | strategy: 11 | matrix: 12 | variant: 13 | - dockerfile: Dockerfile 14 | mysql-version: "8.0" 15 | - dockerfile: Dockerfile.mysql57 16 | mysql-version: "5.7" 17 | 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | 23 | - name: Set up Docker Buildx 24 | uses: docker/setup-buildx-action@v2 25 | 26 | - name: Test the image 27 | uses: ./.github/actions/test 28 | with: 29 | mysql-version: ${{ matrix.variant.mysql-version }} 30 | dockerfile: ${{ matrix.variant.dockerfile }} 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .secrets -------------------------------------------------------------------------------- /.secrets.example: -------------------------------------------------------------------------------- 1 | GITHUB_TOKEN= 2 | DOCKERHUB_USERNAME= 3 | DOCKERHUB_TOKEN= 4 | DOCKERHUB_REPOSITORY=selim13/automysqlbackup -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## 2.7.0 4 | - Run automysqlbackup process as a user with specified `USER_ID` and `GROUP_ID`. 5 | 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build 2 | FROM golang:1.12 as builder 3 | 4 | RUN go get -d -v github.com/odise/go-cron \ 5 | && cd /go/src/github.com/robfig/cron \ 6 | && git checkout tags/v1.2.0 \ 7 | && cd /go/src/github.com/odise/go-cron \ 8 | && CGO_ENABLED=0 GOOS=linux go build -o go-cron bin/go-cron.go 9 | 10 | # Package 11 | FROM debian:bullseye-slim 12 | LABEL maintainer="selim013@gmail.com" 13 | 14 | RUN apt-get update && apt-get install -y --no-install-recommends gnupg dirmngr bzip2 && rm -rf /var/lib/apt/lists/* 15 | 16 | # add gosu for easy step-down from root 17 | # https://github.com/tianon/gosu/releases 18 | ENV GOSU_VERSION 1.14 19 | RUN set -eux; \ 20 | key='B42F6819007F00F88E364FD4036A9C25BF357DD4'; \ 21 | savedAptMark="$(apt-mark showmanual)"; \ 22 | apt-get update; \ 23 | apt-get install -y --no-install-recommends ca-certificates wget; \ 24 | rm -rf /var/lib/apt/lists/*; \ 25 | dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \ 26 | wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \ 27 | wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \ 28 | export GNUPGHOME="$(mktemp -d)"; \ 29 | (gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" \ 30 | || gpg --batch --keyserver keys.openpgp.org --recv-keys "$key" \ 31 | || gpg --batch --keyserver hkp://pgp.mit.edu:80 --recv-keys "$key"); \ 32 | gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \ 33 | gpgconf --kill all; \ 34 | rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \ 35 | apt-mark auto '.*' > /dev/null; \ 36 | [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \ 37 | apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ 38 | chmod +x /usr/local/bin/gosu; \ 39 | gosu --version; \ 40 | gosu nobody true 41 | 42 | RUN set -uex; \ 43 | # gpg: key 3A79BD29: public key "MySQL Release Engineering " imported 44 | key='859BE8D7C586F538430B19C2467B942D3A79BD29'; \ 45 | export GNUPGHOME="$(mktemp -d)"; \ 46 | (gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" \ 47 | || gpg --batch --keyserver keys.openpgp.org --recv-keys "$key" \ 48 | || gpg --batch --keyserver hkp://pgp.mit.edu:80 --recv-keys "$key"); \ 49 | gpg --batch --export "$key" > /etc/apt/trusted.gpg.d/mysql.gpg; \ 50 | gpgconf --kill all; \ 51 | rm -rf "$GNUPGHOME"; \ 52 | apt-key list > /dev/null 53 | 54 | ENV MYSQL_MAJOR 8.0 55 | 56 | RUN echo "deb http://repo.mysql.com/apt/debian/ bullseye mysql-${MYSQL_MAJOR}" > /etc/apt/sources.list.d/mysql.list 57 | 58 | RUN apt-get update \ 59 | && apt-get install -y mysql-community-client-core \ 60 | && rm -rf /var/lib/apt/lists/* 61 | 62 | RUN mkdir -p /etc/default /etc/mysql 63 | 64 | COPY --from=builder /go/src/github.com/odise/go-cron/go-cron /usr/local/bin/ 65 | COPY automysqlbackup start.sh /usr/local/bin/ 66 | COPY my.cnf /etc/mysql/ 67 | 68 | RUN chmod +x /usr/local/bin/go-cron \ 69 | /usr/local/bin/automysqlbackup \ 70 | /usr/local/bin/start.sh 71 | 72 | RUN groupadd --system automysqlbackup --gid=1000 && useradd --system --uid=1000 --gid automysqlbackup automysqlbackup 73 | 74 | WORKDIR /backup 75 | 76 | ENV USERNAME= \ 77 | PASSWORD= \ 78 | DBHOST=localhost \ 79 | DBNAMES=all \ 80 | DBPORT=3306 \ 81 | BACKUPDIR="/backup" \ 82 | MDBNAMES= \ 83 | DBEXCLUDE="" \ 84 | IGNORE_TABLES="" \ 85 | CREATE_DATABASE=yes \ 86 | SEPDIR=yes \ 87 | DOWEEKLY=6 \ 88 | COMP=gzip \ 89 | COMMCOMP=no \ 90 | LATEST=no \ 91 | MAX_ALLOWED_PACKET= \ 92 | SOCKET= \ 93 | PREBACKUP= \ 94 | POSTBACKUP= \ 95 | ROUTINES=yes \ 96 | EXTRA_OPTS= \ 97 | CRON_SCHEDULE= \ 98 | USER_ID=1 \ 99 | GROUP_ID= 100 | 101 | CMD ["start.sh"] 102 | -------------------------------------------------------------------------------- /Dockerfile.mysql57: -------------------------------------------------------------------------------- 1 | # Build 2 | FROM golang:1.12 as builder 3 | 4 | RUN go get -d -v github.com/odise/go-cron \ 5 | && cd /go/src/github.com/robfig/cron \ 6 | && git checkout tags/v1.2.0 \ 7 | && cd /go/src/github.com/odise/go-cron \ 8 | && CGO_ENABLED=0 GOOS=linux go build -o go-cron bin/go-cron.go 9 | 10 | # Package 11 | FROM debian:buster-slim 12 | LABEL maintainer="selim013@gmail.com" 13 | 14 | RUN apt-get update && apt-get install -y --no-install-recommends gnupg dirmngr bzip2 && rm -rf /var/lib/apt/lists/* 15 | 16 | # add gosu for easy step-down from root 17 | # https://github.com/tianon/gosu/releases 18 | ENV GOSU_VERSION 1.14 19 | RUN set -eux; \ 20 | key='B42F6819007F00F88E364FD4036A9C25BF357DD4'; \ 21 | savedAptMark="$(apt-mark showmanual)"; \ 22 | apt-get update; \ 23 | apt-get install -y --no-install-recommends ca-certificates wget; \ 24 | rm -rf /var/lib/apt/lists/*; \ 25 | dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \ 26 | wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \ 27 | wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \ 28 | export GNUPGHOME="$(mktemp -d)"; \ 29 | (gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" \ 30 | || gpg --batch --keyserver keys.openpgp.org --recv-keys "$key" \ 31 | || gpg --batch --keyserver hkp://pgp.mit.edu:80 --recv-keys "$key"); \ 32 | gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \ 33 | gpgconf --kill all; \ 34 | rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \ 35 | apt-mark auto '.*' > /dev/null; \ 36 | [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \ 37 | apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ 38 | chmod +x /usr/local/bin/gosu; \ 39 | gosu --version; \ 40 | gosu nobody true 41 | 42 | RUN set -uex; \ 43 | # gpg: key 3A79BD29: public key "MySQL Release Engineering " imported 44 | key='859BE8D7C586F538430B19C2467B942D3A79BD29'; \ 45 | export GNUPGHOME="$(mktemp -d)"; \ 46 | (gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" \ 47 | || gpg --batch --keyserver keys.openpgp.org --recv-keys "$key" \ 48 | || gpg --batch --keyserver hkp://pgp.mit.edu:80 --recv-keys "$key"); \ 49 | gpg --batch --export "$key" > /etc/apt/trusted.gpg.d/mysql.gpg; \ 50 | gpgconf --kill all; \ 51 | rm -rf "$GNUPGHOME"; \ 52 | apt-key list > /dev/null 53 | 54 | ENV MYSQL_MAJOR 5.7 55 | 56 | RUN echo "deb http://repo.mysql.com/apt/debian/ buster mysql-${MYSQL_MAJOR}" > /etc/apt/sources.list.d/mysql.list 57 | 58 | RUN apt-get update \ 59 | && apt-get install -y mysql-community-client \ 60 | && rm -rf /var/lib/apt/lists/* 61 | 62 | RUN mkdir -p /etc/default /etc/mysql 63 | 64 | COPY --from=builder /go/src/github.com/odise/go-cron/go-cron /usr/local/bin/ 65 | COPY automysqlbackup start.sh /usr/local/bin/ 66 | 67 | RUN chmod +x /usr/local/bin/go-cron \ 68 | /usr/local/bin/automysqlbackup \ 69 | /usr/local/bin/start.sh 70 | 71 | RUN groupadd --system automysqlbackup --gid=1000 && useradd --system --uid=1000 --gid automysqlbackup automysqlbackup 72 | 73 | WORKDIR /backup 74 | 75 | ENV USERNAME= \ 76 | PASSWORD= \ 77 | DBHOST=localhost \ 78 | DBNAMES=all \ 79 | DBPORT=3306 \ 80 | BACKUPDIR="/backup" \ 81 | MDBNAMES= \ 82 | DBEXCLUDE="" \ 83 | IGNORE_TABLES="" \ 84 | CREATE_DATABASE=yes \ 85 | SEPDIR=yes \ 86 | DOWEEKLY=6 \ 87 | COMP=gzip \ 88 | COMMCOMP=no \ 89 | LATEST=no \ 90 | MAX_ALLOWED_PACKET= \ 91 | SOCKET= \ 92 | PREBACKUP= \ 93 | POSTBACKUP= \ 94 | ROUTINES=yes \ 95 | EXTRA_OPTS= \ 96 | CRON_SCHEDULE= \ 97 | USER_ID=1 \ 98 | GROUP_ID= 99 | 100 | CMD ["start.sh"] 101 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Docker AutoMySQLBackup 2 | 3 | A lightweight image for creating and managing scheduled MySQL backups. 4 | Runs a slightly modified [AutoMySQLBackup](https://sourceforge.net/projects/automysqlbackup/) utility. 5 | 6 | ## Supported tags and respective `Dockerfile` links 7 | 8 | - [`2.7.0 2.7.0-mysql8.0 latest` (_Dockerfile_)](https://github.com/selim13/docker-automysqlbackup/blob/v2.7.0/Dockerfile), main image with mysql8 client 9 | - [`2.7.0-mysql5.7` (_Dockerfile_)](https://github.com/selim13/docker-automysqlbackup/blob/v2.7.0/Dockerfile.mysql57), version with mysql5.7 client 10 | 11 | ## Version 12 | 13 | This image uses AutoMySQLBackup 2.5 from Debian Linux source repository as a base, branched at `2.6+debian.4-1` tag. 14 | Original source can be cloned from `git://anonscm.debian.org/users/zigo/automysqlbackup.git` or taken at the 15 | appropriate [Debian package](https://packages.debian.org/sid/automysqlbackup) page. 16 | 17 | Custom modifications: 18 | 19 | - passed logging to stdout/stderr 20 | - removed error logs mailing code 21 | - made default configuration more suitable for docker container 22 | 23 | # Image usage 24 | 25 | Let's create a bridge network and start a MySQL container as an example. 26 | 27 | ```console 28 | docker network create dbtest 29 | docker run --name some-mysql --network dbtest \ 30 | -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest 31 | ``` 32 | 33 | For the basic one-shot backup, you can run a container like this: 34 | 35 | ```console 36 | docker run --network dbtest \ 37 | -v '/var/lib/automysqlbackup:/backup' \ 38 | -e DBHOST=some-mysql \ 39 | -e DBNAMES=all \ 40 | -e USERNAME=root \ 41 | -e PASSWORD=my-secret-pw \ 42 | -e DBNAMES=all \ 43 | automysqlbackup:2.7.0 44 | ``` 45 | 46 | Container will create dumps of all datebases from MySQL inside `/var/lib/automysqlbackup` directory and exit. 47 | 48 | To run container in a scheduled mode, populate `CRON_SCHEDULE` environment variable with a cron expression. 49 | 50 | ```console 51 | docker run --network dbtest \ 52 | -v '/var/lib/automysqlbackup:/backup' \ 53 | -e DBHOST=some-mysql \ 54 | -e DBNAMES=all \ 55 | -e USERNAME=root \ 56 | -e PASSWORD=my-secret-pw \ 57 | -e DBNAMES=all \ 58 | -e CRON_SCHEDULE="0 0 * * *" \ 59 | automysqlbackup:2.7.0 60 | ``` 61 | 62 | Instead of passing environment variables though docker, you can also mount a file with their declarations 63 | as volume. See `defaults` file in this image's git repository for the example. 64 | 65 | ```console 66 | docker run --network dbtest \ 67 | -v '/var/lib/automysqlbackup:/backup' \ 68 | -v '/etc/default/automysqlbackup:/etc/default/automysqlbackup:ro' \ 69 | automysqlbackup:2.7.0 70 | ``` 71 | 72 | # Usage with docker-compose 73 | 74 | For the example of using this image with docker-compose, see [docker-compose.yml](https://github.com/selim13/docker-automysqlbackup/blob/master/docker-compose.yml) file in the image's repository. 75 | 76 | Quick tips: 77 | 78 | - You can call `automysqlbackup` binary directly for the manual backup: `docker-compose exec mysqlbackup automysqlbackup` 79 | - Use only YAML dictionary for passing CRON_SCHEDULE environment variable `CRON_SCHEDULE: "0 0 * * *"` 80 | as YAML sequence `- CRON_SCHEDULE="0 * * * *"` will preserve quotes breaking go-cron (Issue #1). 81 | 82 | ## Environment variables 83 | 84 | - **CRON_SCHEDULE**\ 85 | If set to cron expression, container will start a cron daemon for scheduled backups. 86 | 87 | - **USERNAME**\ 88 | Username to access the MySQL server. 89 | 90 | - **PASSWORD**\ 91 | Password to access the MySQL server. 92 | 93 | - **DBHOST**\ 94 | Host name (or IP address) of MySQL server. 95 | 96 | - **DBPORT**\ 97 | Port of MySQL server. 98 | 99 | - **DBNAMES**\ 100 | List of space separated database names for Daily/Weekly Backup. Set to `all` for all databases.\ 101 | Default value: `all` 102 | 103 | - **BACKUPDIR**\ 104 | Backup directory location. 105 | Folders inside this one will be created (daily, weekly, etc.), and the subfolders will be database names.\ 106 | Default value: `/backup` 107 | 108 | - **MDBNAMES**\ 109 | List of space separated database names for Monthly Backups.\ 110 | Will mirror DBNAMES if DBNAMES set to `all`. 111 | 112 | - **DBEXCLUDE**\ 113 | List of DBNAMES to **exclude** if DBNAMES are set to all (must be in " quotes). 114 | 115 | - **IGNORE_TABLES**\ 116 | List of space separated table names in a format of `db_name.tbl_name` to exclude from backup (must be in " quotes). 117 | 118 | - **CREATE_DATABASE**\ 119 | Include CREATE DATABASE in backup?\ 120 | Default value: `yes` 121 | 122 | - **SEPDIR**\ 123 | Separate backup directory and file for each DB? (yes or no).\ 124 | Default value: `yes` 125 | 126 | - **DOWEEKLY**\ 127 | Which day do you want weekly backups? (1 to 7 where 1 is Monday).\ 128 | Default value: `6` 129 | 130 | - **COMP**\ 131 | Choose Compression type. (gzip or bzip2)\ 132 | Default value: `gzip` 133 | 134 | - **COMMCOMP**\ 135 | Compress communications between backup server and MySQL server?\ 136 | Default value: `no` 137 | 138 | - **LATEST**\ 139 | Additionally keep a copy of the most recent backup in a seperate directory.\ 140 | Default value: `no` 141 | 142 | - **MAX_ALLOWED_PACKET**\ 143 | The maximum size of the buffer for client/server communication. e.g. 16MB (maximum is 1GB) 144 | 145 | - **SOCKET**\ 146 | For connections to localhost. Sometimes the Unix socket file must be specified. 147 | 148 | - **PREBACKUP**\ 149 | Command to run before backups 150 | 151 | - **POSTBACKUP**\ 152 | Command run after backups 153 | 154 | - **ROUTINES**\ 155 | Backup of stored procedures and routines\ 156 | Default value: `yes` 157 | 158 | - **EXTRA_OPTS**\ 159 | Pass any arbitrary flags to mysqldump, e.g. `--single-transaction`. 160 | 161 | - **USER_ID** 162 | Run the backup process from the specified user id. Allows matching backup files permissions with the host's user.\ 163 | Default value: `1` (root). 164 | 165 | - **GROUP_ID** 166 | Run the backup process from the specified group id. Allows matching backup files permissions with the host's group.\ 167 | If empty, matches USER_ID. 168 | 169 | ## Docker Secrets 170 | 171 | As an alternative to passing sensitive information via environment variables, `_FILE` may be appended to some of the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. In particular, this can be used to load passwords from Docker secrets stored in `/run/secrets/` files. For example: 172 | 173 | ```console 174 | docker run --name automysqlbackup -e USERNAME=root -e PASSWORD_FILE=/run/secrets/mysql_root_password automysqlbackup 175 | ``` 176 | 177 | Currently, this is only supported for `USERNAME` and `PASSWORD`. 178 | 179 | ## FAQ 180 | 181 | - **Will you add support for AutoMySQLBackup 3?**\ 182 | No. AutoMySQLBackup 3 was a complete rewrite of the script with much higher 183 | complexity but was abandoned in 2011 before it released. There are multiple 184 | repositories which try to support it by fixing bugs and ensuring compatibility 185 | with newer MySQL versions but I don't have time to track changes in those 186 | to properly support docker image. 187 | 188 | - **Can you add CONFIG\_\* option**\ 189 | Those options appeared in AutoMySQLBackup 3. See the above question. 190 | 191 | ## License 192 | 193 | Similar to the original automysqlbackup script, all sources for this image 194 | are licensed under [GPL-2.0](./LICENSE.txt). 195 | -------------------------------------------------------------------------------- /automysqlbackup: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # MySQL Backup Script 4 | # VER. 2.5 - http://sourceforge.net/projects/automysqlbackup/ 5 | # Copyright (c) 2002-2003 wipe_out@lycos.co.uk 6 | # 7 | # This program is free software; you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation; either version 2 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program; if not, write to the Free Software 19 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 20 | # 21 | #===================================================================== 22 | #===================================================================== 23 | # Set the following variables to your system needs 24 | # (Detailed instructions below variables) 25 | #===================================================================== 26 | 27 | if [ -f /etc/default/automysqlbackup ] ; then 28 | . /etc/default/automysqlbackup 29 | fi 30 | 31 | #===================================================================== 32 | # Options documantation 33 | #===================================================================== 34 | # Set USERNAME and PASSWORD of a user that has at least SELECT permission 35 | # to ALL databases. 36 | # 37 | # Set the DBHOST option to the server you wish to backup, leave the 38 | # default to backup "this server".(to backup multiple servers make 39 | # copies of this file and set the options for that server) 40 | # 41 | # Put in the list of DBNAMES(Databases)to be backed up. If you would like 42 | # to backup ALL DBs on the server set DBNAMES="all".(if set to "all" then 43 | # any new DBs will automatically be backed up without needing to modify 44 | # this backup script when a new DB is created). 45 | # 46 | # If the DB you want to backup has a space in the name replace the space 47 | # with a % e.g. "data base" will become "data%base" 48 | # NOTE: Spaces in DB names may not work correctly when SEPDIR=no. 49 | # 50 | # You can change the backup storage location from /backups to anything 51 | # you like by using the BACKUPDIR setting.. 52 | # 53 | # The MAILCONTENT and MAILADDR options and pretty self explanitory, use 54 | # these to have the backup log mailed to you at any email address or multiple 55 | # email addresses in a space seperated list. 56 | # (If you set mail content to "log" you will require access to the "mail" program 57 | # on your server. If you set this to "files" you will have to have mutt installed 58 | # on your server. If you set it to "stdout" it will log to the screen if run from 59 | # the console or to the cron job owner if run through cron. If you set it to "quiet" 60 | # logs will only be mailed if there are errors reported. ) 61 | # 62 | # MAXATTSIZE sets the largest allowed email attachments total (all backup files) you 63 | # want the script to send. This is the size before it is encoded to be sent as an email 64 | # so if your mail server will allow a maximum mail size of 5MB I would suggest setting 65 | # MAXATTSIZE to be 25% smaller than that so a setting of 4000 would probably be fine. 66 | # 67 | # Finally copy automysqlbackup.sh to anywhere on your server and make sure 68 | # to set executable permission. You can also copy the script to 69 | # /etc/cron.daily to have it execute automatically every night or simply 70 | # place a symlink in /etc/cron.daily to the file if you wish to keep it 71 | # somwhere else. 72 | # NOTE:On Debian copy the file with no extention for it to be run 73 | # by cron e.g just name the file "automysqlbackup" 74 | # 75 | # Thats it.. 76 | # 77 | # 78 | # === Advanced options doc's === 79 | # 80 | # The list of MDBNAMES is the DB's to be backed up only monthly. You should 81 | # always include "mysql" in this list to backup your user/password 82 | # information along with any other DBs that you only feel need to 83 | # be backed up monthly. (if using a hosted server then you should 84 | # probably remove "mysql" as your provider will be backing this up) 85 | # NOTE: If DBNAMES="all" then MDBNAMES has no effect as all DBs will be backed 86 | # up anyway. 87 | # 88 | # If you set DBNAMES="all" you can configure the option DBEXCLUDE. Other 89 | # wise this option will not be used. 90 | # This option can be used if you want to backup all dbs, but you want 91 | # exclude some of them. (eg. a db is to big). 92 | # 93 | # Set CREATE_DATABASE to "yes" (the default) if you want your SQL-Dump to create 94 | # a database with the same name as the original database when restoring. 95 | # Saying "no" here will allow your to specify the database name you want to 96 | # restore your dump into, making a copy of the database by using the dump 97 | # created with automysqlbackup. 98 | # NOTE: Not used if SEPDIR=no 99 | # 100 | # The SEPDIR option allows you to choose to have all DBs backed up to 101 | # a single file (fast restore of entire server in case of crash) or to 102 | # seperate directories for each DB (each DB can be restored seperately 103 | # in case of single DB corruption or loss). 104 | # 105 | # To set the day of the week that you would like the weekly backup to happen 106 | # set the DOWEEKLY setting, this can be a value from 1 to 7 where 1 is Monday, 107 | # The default is 6 which means that weekly backups are done on a Saturday. 108 | # 109 | # COMP is used to choose the copmression used, options are gzip or bzip2. 110 | # bzip2 will produce slightly smaller files but is more processor intensive so 111 | # may take longer to complete. 112 | # 113 | # COMMCOMP is used to enable or diable mysql client to server compression, so 114 | # it is useful to save bandwidth when backing up a remote MySQL server over 115 | # the network. 116 | # 117 | # LATEST is to store an additional copy of the latest backup to a standard 118 | # location so it can be downloaded bt thrid party scripts. 119 | # 120 | # If the DB's being backed up make use of large BLOB fields then you may need 121 | # to increase the MAX_ALLOWED_PACKET setting, for example 16MB.. 122 | # 123 | # When connecting to localhost as the DB server (DBHOST=localhost) sometimes 124 | # the system can have issues locating the socket file.. This can now be set 125 | # using the SOCKET parameter.. An example may be SOCKET=/private/tmp/mysql.sock 126 | # 127 | # Use PREBACKUP and POSTBACKUP to specify Per and Post backup commands 128 | # or scripts to perform tasks either before or after the backup process. 129 | # 130 | # 131 | #===================================================================== 132 | # Backup Rotation.. 133 | #===================================================================== 134 | # 135 | # Daily Backups are rotated weekly.. 136 | # Weekly Backups are run by default on Saturday Morning when 137 | # cron.daily scripts are run...Can be changed with DOWEEKLY setting.. 138 | # Weekly Backups are rotated on a 5 week cycle.. 139 | # Monthly Backups are run on the 1st of the month.. 140 | # Monthly Backups are NOT rotated automatically... 141 | # It may be a good idea to copy Monthly backups offline or to another 142 | # server.. 143 | # 144 | #===================================================================== 145 | # Please Note!! 146 | #===================================================================== 147 | # 148 | # I take no resposibility for any data loss or corruption when using 149 | # this script.. 150 | # This script will not help in the event of a hard drive crash. If a 151 | # copy of the backup has not be stored offline or on another PC.. 152 | # You should copy your backups offline regularly for best protection. 153 | # 154 | # Happy backing up... 155 | # 156 | #===================================================================== 157 | # Restoring 158 | #===================================================================== 159 | # Firstly you will need to uncompress the backup file. 160 | # eg. 161 | # gunzip file.gz (or bunzip2 file.bz2) 162 | # 163 | # Next you will need to use the mysql client to restore the DB from the 164 | # sql file. 165 | # eg. 166 | # mysql --user=username --pass=password --host=dbserver database < /path/file.sql 167 | # or 168 | # mysql --user=username --pass=password --host=dbserver -e "source /path/file.sql" database 169 | # 170 | # NOTE: Make sure you use "<" and not ">" in the above command because 171 | # you are piping the file.sql to mysql and not the other way around. 172 | # 173 | # Lets hope you never have to use this.. :) 174 | # 175 | #===================================================================== 176 | # Change Log 177 | #===================================================================== 178 | # 179 | # VER 2.5 - (2006-01-15) 180 | # Added support for setting MAXIMUM_PACKET_SIZE and SOCKET parameters (suggested by Yvo van Doorn) 181 | # VER 2.4 - (2006-01-23) 182 | # Fixed bug where weekly backups were not being rotated. (Fix by wolf02) 183 | # Added hour an min to backup filename for the case where backups are taken multiple 184 | # times in a day. NOTE This is not complete support for mutiple executions of the script 185 | # in a single day. 186 | # Added MAILCONTENT="quiet" option, see docs for details. (requested by snowsam) 187 | # Updated path statment for compatibility with OSX. 188 | # Added "LATEST" to additionally store the last backup to a standard location. (request by Grant29) 189 | # VER 2.3 - (2005-11-07) 190 | # Better error handling and notification of errors (a long time coming) 191 | # Compression on Backup server to MySQL server communications. 192 | # VER 2.2 - (2004-12-05) 193 | # Changed from using depricated "-N" to "--skip-column-names". 194 | # Added ability to have compressed backup's emailed out. (code from Thomas Heiserowski) 195 | # Added maximum attachment size setting. 196 | # VER 2.1 - (2004-11-04) 197 | # Fixed a bug in daily rotation when not using gzip compression. (Fix by Rob Rosenfeld) 198 | # VER 2.0 - (2004-07-28) 199 | # Switched to using IO redirection instead of pipeing the output to the logfile. 200 | # Added choice of compression of backups being gzip of bzip2. 201 | # Switched to using functions to facilitate more functionality. 202 | # Added option of either gzip or bzip2 compression. 203 | # VER 1.10 - (2004-07-17) 204 | # Another fix for spaces in the paths (fix by Thomas von Eyben) 205 | # Fixed bug when using PREBACKUP and POSTBACKUP commands containing many arguments. 206 | # VER 1.9 - (2004-05-25) 207 | # Small bug fix to handle spaces in LOGFILE path which contains spaces (reported by Thomas von Eyben) 208 | # Updated docs to mention that Log email can be sent to multiple email addresses. 209 | # VER 1.8 - (2004-05-01) 210 | # Added option to make backups restorable to alternate database names 211 | # meaning that a copy of the database can be created (Based on patch by Rene Hoffmann) 212 | # Seperated options into standard and advanced. 213 | # Removed " from single file dump DBMANES because it caused an error but 214 | # this means that if DB's have spaces in the name they will not dump when SEPDIR=no. 215 | # Added -p option to mkdir commands to create multiple subdirs without error. 216 | # Added disk usage and location to the bottom of the backup report. 217 | # VER 1.7 - (2004-04-22) 218 | # Fixed an issue where weelky backups would only work correctly if server 219 | # locale was set to English (issue reported by Tom Ingberg) 220 | # used "eval" for "rm" commands to try and resolve rotation issues. 221 | # Changed name of status log so multiple scripts can be run at the same time. 222 | # VER 1.6 - (2004-03-14) 223 | # Added PREBACKUP and POSTBACKUP command functions. (patch by markpustjens) 224 | # Added support for backing up DB's with Spaces in the name. 225 | # (patch by markpustjens) 226 | # VER 1.5 - (2004-02-24) 227 | # Added the ability to exclude DB's when the "all" option is used. 228 | # (Patch by kampftitan) 229 | # VER 1.4 - (2004-02-02) 230 | # Project moved to Sourceforge.net 231 | # VER 1.3 - (2003-09-25) 232 | # Added support for backing up "all" databases on the server without 233 | # having to list each one seperately in the configuration. 234 | # Added DB restore instructions. 235 | # VER 1.2 - (2003-03-16) 236 | # Added server name to the backup log so logs from multiple servers 237 | # can be easily identified. 238 | # VER 1.1 - (2003-03-13) 239 | # Small Bug fix in monthly report. (Thanks Stoyanski) 240 | # Added option to email log to any email address. (Inspired by Stoyanski) 241 | # Changed Standard file name to .sh extention. 242 | # Option are set using yes and no rather than 1 or 0. 243 | # VER 1.0 - (2003-01-30) 244 | # Added the ability to have all databases backup to a single dump 245 | # file or seperate directory and file for each database. 246 | # Output is better for log keeping. 247 | # VER 0.6 - (2003-01-22) 248 | # Bug fix for daily directory (Added in VER 0.5) rotation. 249 | # VER 0.5 - (2003-01-20) 250 | # Added "daily" directory for daily backups for neatness (suggestion by Jason) 251 | # Added DBHOST option to allow backing up a remote server (Suggestion by Jason) 252 | # Added "--quote-names" option to mysqldump command. 253 | # Bug fix for handling the last and first of the year week rotation. 254 | # VER 0.4 - (2002-11-06) 255 | # Added the abaility for the script to create its own directory structure. 256 | # VER 0.3 - (2002-10-01) 257 | # Changed Naming of Weekly backups so they will show in order. 258 | # VER 0.2 - (2002-09-27) 259 | # Corrected weekly rotation logic to handle weeks 0 - 10 260 | # VER 0.1 - (2002-09-21) 261 | # Initial Release 262 | # 263 | #===================================================================== 264 | #===================================================================== 265 | #===================================================================== 266 | # 267 | # Should not need to be modified from here down!! 268 | # 269 | #===================================================================== 270 | #===================================================================== 271 | #===================================================================== 272 | PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/mysql/bin 273 | DATE=`date +%Y-%m-%d_%Hh%Mm` # Datestamp e.g 2002-09-21 274 | DOW=`date +%A` # Day of the week e.g. Monday 275 | DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday 276 | DOM=`date +%d` # Date of the Month e.g. 27 277 | M=`date +%B` # Month e.g January 278 | W=`date +%V` # Week Number e.g 37 279 | VER=2.5 # Version Number 280 | LOGFILE=/dev/stdout # Logfile Name 281 | LOGERR=/dev/stderr # Logfile Name 282 | BACKUPFILES="" 283 | OPT="--quote-names --events" # OPT string for use with mysqldump ( see man mysqldump ) 284 | 285 | # Add --compress mysqldump option to $OPT 286 | if [ "$COMMCOMP" = "yes" ]; 287 | then 288 | OPT="$OPT --compress" 289 | fi 290 | 291 | # Add --routines mysqldum option to ${OPT} 292 | if [ "${ROUTINES}" = "yes" ]; 293 | then 294 | OPT="${OPT} --routines" 295 | fi 296 | 297 | # Add --compress mysqldump option to $OPT 298 | if [ "$MAX_ALLOWED_PACKET" ]; 299 | then 300 | OPT="$OPT --max_allowed_packet=$MAX_ALLOWED_PACKET" 301 | fi 302 | 303 | # Pass extra options for mysqldump 304 | if [ "$EXTRA_OPTS" ] 305 | then 306 | OPT="$OPT $EXTRA_OPTS" 307 | fi 308 | 309 | # Create required directories 310 | if [ ! -e "$BACKUPDIR" ] # Check Backup Directory exists. 311 | then 312 | mkdir -p "$BACKUPDIR" 313 | fi 314 | 315 | 316 | chmod o-x ${BACKUPDIR} 317 | chmod o-r ${BACKUPDIR} 318 | 319 | if [ ! -e "$BACKUPDIR/daily" ] # Check Daily Directory exists. 320 | then 321 | mkdir -p "$BACKUPDIR/daily" 322 | fi 323 | 324 | if [ ! -e "$BACKUPDIR/weekly" ] # Check Weekly Directory exists. 325 | then 326 | mkdir -p "$BACKUPDIR/weekly" 327 | fi 328 | 329 | if [ ! -e "$BACKUPDIR/monthly" ] # Check Monthly Directory exists. 330 | then 331 | mkdir -p "$BACKUPDIR/monthly" 332 | fi 333 | 334 | if [ "$LATEST" = "yes" ] 335 | then 336 | if [ ! -e "$BACKUPDIR/latest" ] # Check Latest Directory exists. 337 | then 338 | mkdir -p "$BACKUPDIR/latest" 339 | fi 340 | rm -f "$BACKUPDIR"/latest/* 341 | fi 342 | 343 | # IO redirection for logging. 344 | exec 6>&1 # Link file descriptor #6 with stdout. 345 | # Saves stdout. 346 | exec > $LOGFILE # stdout replaced with file $LOGFILE. 347 | exec 7>&2 # Link file descriptor #7 with stderr. 348 | # Saves stderr. 349 | exec 2> $LOGERR # stderr replaced with file $LOGERR. 350 | 351 | 352 | # Functions 353 | 354 | # Database dump function 355 | dbdump () { 356 | touch $2 357 | chmod 600 $2 358 | if [ $1 = "information_schema" -o $1 = "mysql" ] ; then 359 | NEWOPT="--skip-opt ${OPT}" 360 | else 361 | NEWOPT="--opt $OPT" 362 | fi 363 | 364 | if [ -z "${USERNAME}" -o -z "${PASSWORD}" ] ; then 365 | mysqldump --defaults-file=/etc/mysql/debian.cnf $NEWOPT $1 > $2 366 | else 367 | mysqldump --user=$USERNAME --password="$PASSWORD" --host=$DBHOST --port=$DBPORT $NEWOPT $1 > $2 368 | fi 369 | return 0 370 | } 371 | 372 | # Compression function plus latest copy 373 | SUFFIX="" 374 | compression () { 375 | if [ "$COMP" = "gzip" ]; then 376 | gzip -f "$1" 377 | echo 378 | echo Backup Information for "$1" 379 | gzip -l "$1.gz" 380 | SUFFIX=".gz" 381 | elif [ "$COMP" = "bzip2" ]; then 382 | echo Compression information for "$1.bz2" 383 | bzip2 -f -v $1 2>&1 384 | SUFFIX=".bz2" 385 | else 386 | echo "No compression option set, check advanced settings" 387 | fi 388 | if [ "$LATEST" = "yes" ]; then 389 | cp $1$SUFFIX "$BACKUPDIR/latest/" 390 | fi 391 | return 0 392 | } 393 | 394 | 395 | # Run command before we begin 396 | if [ "$PREBACKUP" ] 397 | then 398 | echo ====================================================================== 399 | echo "Prebackup command output." 400 | echo 401 | $PREBACKUP 402 | echo 403 | echo ====================================================================== 404 | echo 405 | fi 406 | 407 | 408 | if [ "$SEPDIR" = "yes" ]; then # Check if CREATE DATABSE should be included in Dump 409 | if [ "$CREATE_DATABASE" = "no" ]; then 410 | OPT="$OPT --no-create-db" 411 | else 412 | OPT="$OPT --databases" 413 | fi 414 | else 415 | OPT="$OPT --databases" 416 | fi 417 | 418 | # Hostname for LOG information 419 | if [ "$DBHOST" = "localhost" ]; then 420 | HOST=`hostname` 421 | if [ "$SOCKET" ]; then 422 | OPT="$OPT --socket=$SOCKET" 423 | fi 424 | else 425 | HOST=$DBHOST 426 | fi 427 | 428 | for ignore in $IGNORE_TABLES 429 | do 430 | OPT="$OPT --ignore-table=$ignore" 431 | done 432 | 433 | # If backing up all DBs on the server 434 | if [ "$DBNAMES" = "all" ]; then 435 | if [ -z "${USERNAME}" -o -z "${PASSWORD}" ] ; then 436 | DBNAMES="`mysql --defaults-file=/etc/mysql/debian.cnf --batch --skip-column-names -e "show databases"| sed 's/ /%/g'`" 437 | else 438 | DBNAMES="`mysql --user=$USERNAME --password="$PASSWORD" --host=$DBHOST --port=$DBPORT --batch --skip-column-names -e "show databases"| sed 's/ /%/g'`" 439 | fi 440 | 441 | # If DBs are excluded 442 | for exclude in $DBEXCLUDE 443 | do 444 | DBNAMES=`echo $DBNAMES | sed "s/\b$exclude\b//g"` 445 | done 446 | 447 | MDBNAMES=$DBNAMES 448 | fi 449 | 450 | echo ====================================================================== 451 | echo AutoMySQLBackup VER $VER 452 | echo http://sourceforge.net/projects/automysqlbackup/ 453 | echo 454 | echo Backup of Database Server - $HOST 455 | echo ====================================================================== 456 | 457 | # Test is seperate DB backups are required 458 | if [ "$SEPDIR" = "yes" ]; then 459 | echo Backup Start Time `date` 460 | echo ====================================================================== 461 | # Monthly Full Backup of all Databases 462 | if [ "$DOM" = "01" ]; then 463 | for MDB in $MDBNAMES 464 | do 465 | 466 | # Prepare $DB for using 467 | MDB="`echo $MDB | sed 's/%/ /g'`" 468 | 469 | if [ ! -e "$BACKUPDIR/monthly/$MDB" ] # Check Monthly DB Directory exists. 470 | then 471 | mkdir -p "$BACKUPDIR/monthly/$MDB" 472 | fi 473 | echo Monthly Backup of $MDB... 474 | dbdump "$MDB" "$BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql" 475 | compression "$BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql" 476 | BACKUPFILES="$BACKUPFILES $BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql$SUFFIX" 477 | echo ---------------------------------------------------------------------- 478 | done 479 | fi 480 | 481 | for DB in $DBNAMES 482 | do 483 | # Prepare $DB for using 484 | DB="`echo $DB | sed 's/%/ /g'`" 485 | 486 | # Create Seperate directory for each DB 487 | if [ ! -e "$BACKUPDIR/daily/$DB" ] # Check Daily DB Directory exists. 488 | then 489 | mkdir -p "$BACKUPDIR/daily/$DB" 490 | fi 491 | 492 | if [ ! -e "$BACKUPDIR/weekly/$DB" ] # Check Weekly DB Directory exists. 493 | then 494 | mkdir -p "$BACKUPDIR/weekly/$DB" 495 | fi 496 | 497 | # Weekly Backup 498 | if [ "$DNOW" = "$DOWEEKLY" ]; then 499 | echo Weekly Backup of Database \( $DB \) 500 | echo Rotating 5 weeks Backups... 501 | if [ "$W" -le 05 ];then 502 | REMW=`expr 48 + $W` 503 | elif [ "$W" -lt 15 ];then 504 | REMW=0`expr $W - 5` 505 | else 506 | REMW=`expr $W - 5` 507 | fi 508 | rm -fv "$BACKUPDIR/weekly/$DB/${DB}_week.$REMW".* 509 | echo 510 | dbdump "$DB" "$BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql" 511 | compression "$BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql" 512 | BACKUPFILES="$BACKUPFILES $BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql$SUFFIX" 513 | echo ---------------------------------------------------------------------- 514 | 515 | # Daily Backup 516 | else 517 | echo Daily Backup of Database \( $DB \) 518 | echo Rotating last weeks Backup... 519 | rm -fv "$BACKUPDIR/daily/$DB"/*."$DOW".sql* 520 | echo 521 | dbdump "$DB" "$BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql" 522 | compression "$BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql" 523 | BACKUPFILES="$BACKUPFILES $BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql$SUFFIX" 524 | echo ---------------------------------------------------------------------- 525 | fi 526 | done 527 | echo Backup End `date` 528 | echo ====================================================================== 529 | 530 | 531 | else # One backup file for all DBs 532 | echo Backup Start `date` 533 | echo ====================================================================== 534 | # Monthly Full Backup of all Databases 535 | if [ "$DOM" = "01" ]; then 536 | echo Monthly full Backup of \( $MDBNAMES \)... 537 | dbdump "$MDBNAMES" "$BACKUPDIR/monthly/$DATE.$M.all-databases.sql" 538 | compression "$BACKUPDIR/monthly/$DATE.$M.all-databases.sql" 539 | BACKUPFILES="$BACKUPFILES $BACKUPDIR/monthly/$DATE.$M.all-databases.sql$SUFFIX" 540 | echo ---------------------------------------------------------------------- 541 | fi 542 | 543 | # Weekly Backup 544 | if [ "$DNOW" = "$DOWEEKLY" ]; then 545 | echo Weekly Backup of Databases \( $DBNAMES \) 546 | echo 547 | echo Rotating 5 weeks Backups... 548 | if [ "$W" -le 05 ];then 549 | REMW=`expr 48 + $W` 550 | elif [ "$W" -lt 15 ];then 551 | REMW=0`expr $W - 5` 552 | else 553 | REMW=`expr $W - 5` 554 | fi 555 | rm -fv "$BACKUPDIR/weekly/week.$REMW".* 556 | echo 557 | dbdump "$DBNAMES" "$BACKUPDIR/weekly/week.$W.$DATE.sql" 558 | compression "$BACKUPDIR/weekly/week.$W.$DATE.sql" 559 | BACKUPFILES="$BACKUPFILES $BACKUPDIR/weekly/week.$W.$DATE.sql$SUFFIX" 560 | echo ---------------------------------------------------------------------- 561 | 562 | # Daily Backup 563 | else 564 | echo Daily Backup of Databases \( $DBNAMES \) 565 | echo 566 | echo Rotating last weeks Backup... 567 | rm -fv "$BACKUPDIR"/daily/*."$DOW.sql".* 568 | echo 569 | dbdump "$DBNAMES" "$BACKUPDIR/daily/$DATE.$DOW.sql" 570 | compression "$BACKUPDIR/daily/$DATE.$DOW.sql" 571 | BACKUPFILES="$BACKUPFILES $BACKUPDIR/daily/$DATE.$DOW.sql$SUFFIX" 572 | echo ---------------------------------------------------------------------- 573 | fi 574 | echo Backup End Time `date` 575 | echo ====================================================================== 576 | fi 577 | echo Total disk space used for backup storage.. 578 | echo Size - Location 579 | echo `du -hs "$BACKUPDIR"` 580 | echo 581 | echo ====================================================================== 582 | echo If you find AutoMySQLBackup valuable please make a donation at 583 | echo http://sourceforge.net/project/project_donations.php?group_id=101066 584 | echo ====================================================================== 585 | 586 | # Run command when we're done 587 | if [ "$POSTBACKUP" ] 588 | then 589 | echo ====================================================================== 590 | echo "Postbackup command output." 591 | echo 592 | $POSTBACKUP 593 | echo 594 | echo ====================================================================== 595 | fi 596 | 597 | #Clean up IO redirection 598 | exec 1>&6 6>&- # Restore stdout and close file descriptor #6. 599 | exec 1>&7 7>&- # Restore stdout and close file descriptor #7. 600 | -------------------------------------------------------------------------------- /defaults: -------------------------------------------------------------------------------- 1 | # By default, the Debian version of automysqlbackup will use: 2 | # mysqldump --defaults-file=/etc/mysql/debian.cnf 3 | # but you might want to overwrite with a specific user & pass. 4 | # To do this, simply edit bellow. 5 | 6 | # Username to access the MySQL server e.g. dbuser 7 | USERNAME=root 8 | 9 | # Username to access the MySQL server e.g. password 10 | PASSWORD=my-secret-pw 11 | 12 | # Host name (or IP address) of MySQL server e.g localhost 13 | DBHOST=some-mysql 14 | 15 | # Port of MySQL server 16 | DBPORT=3306 17 | 18 | # List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3" 19 | # Note that it's absolutely normal that the db named "mysql" is not in this 20 | # list, as it's added later by the script. See the MDBNAMES directives below 21 | # in this file (advanced options). 22 | # This is ONLY a convenient default, if you don't like it, don't complain 23 | # and write your own. 24 | # The following is a quick hack that will find the names of the databases by 25 | # reading the mysql folder content. Feel free to replace by something else. 26 | # DBNAMES=`find /var/lib/mysql -mindepth 1 -maxdepth 1 -type d | cut -d'/' -f5 | grep -v ^mysql\$ | tr \\\r\\\n ,\ ` 27 | # This one does a list of dbs using a MySQL statement. 28 | DBNAMES=`mysql --user=$USERNAME --password=$PASSWORD --host=$DBHOST --execute="SHOW DATABASES" | awk '{print $1}' | grep -v ^Database$ | grep -v ^mysql$ | grep -v ^performance_schema$ | grep -v ^information_schema$ | tr \\\r\\\n ,\ ` 29 | 30 | # Backup directory location e.g /backups 31 | # Folders inside this one will be created (daily, weekly, etc.), and the 32 | # subfolders will be database names. Note that backups will be owned by 33 | # root, with Unix rights 0600. 34 | BACKUPDIR="/backup" 35 | 36 | # Mail setup 37 | # What would you like to be mailed to you? 38 | # - log : send only log file 39 | # - files : send log file and sql files as attachments (see docs) 40 | # - stdout : will simply output the log to the screen if run manually. 41 | # - quiet : Only send logs if an error occurs to the MAILADDR. 42 | MAILCONTENT="quiet" 43 | 44 | # Set the maximum allowed email size in k. (4000 = approx 5MB email [see 45 | # docs]) 46 | MAXATTSIZE="4000" 47 | 48 | # Email Address to send mail to? (user@domain.com) 49 | MAILADDR="root" 50 | 51 | # ============================================================ 52 | # === ADVANCED OPTIONS ( Read the doc's below for details )=== 53 | #============================================================= 54 | 55 | # List of DBBNAMES for Monthly Backups. 56 | MDBNAMES="mysql $DBNAMES" 57 | 58 | # List of DBNAMES to EXLUCDE if DBNAMES are set to all (must be in " quotes) 59 | DBEXCLUDE="" 60 | 61 | # List of space separated table names in a format of db_name.tbl_name 62 | # to exclude from backup (must be in " quotes). 63 | IGNORE_TABLES="" 64 | 65 | # Include CREATE DATABASE in backup? 66 | CREATE_DATABASE=yes 67 | 68 | # Separate backup directory and file for each DB? (yes or no) 69 | SEPDIR=yes 70 | 71 | # Which day do you want weekly backups? (1 to 7 where 1 is Monday) 72 | DOWEEKLY=6 73 | 74 | # Choose Compression type. (gzip or bzip2) 75 | COMP=gzip 76 | 77 | # Compress communications between backup server and MySQL server? 78 | COMMCOMP=no 79 | 80 | # Additionally keep a copy of the most recent backup in a seperate 81 | # directory. 82 | LATEST=no 83 | 84 | # The maximum size of the buffer for client/server communication. e.g. 16MB 85 | # (maximum is 1GB) 86 | MAX_ALLOWED_PACKET= 87 | 88 | # For connections to localhost. Sometimes the Unix socket file must be 89 | # specified. 90 | SOCKET= 91 | 92 | # Command to run before backups (uncomment to use) 93 | #PREBACKUP="/etc/mysql-backup-pre" 94 | 95 | # Command run after backups (uncomment to use) 96 | #POSTBACKUP="/etc/mysql-backup-post" 97 | 98 | # Backup of stored procedures and routines (comment to remove) 99 | ROUTINES=yes 100 | -------------------------------------------------------------------------------- /docker-compose.build.yml: -------------------------------------------------------------------------------- 1 | version: "2.4" 2 | 3 | volumes: 4 | mysql-data: {} 5 | mysql-backups-data: {} 6 | 7 | services: 8 | mysql: 9 | image: mysql:8.0 10 | volumes: 11 | - "mysql-data:/var/lib/mysql" 12 | environment: 13 | MYSQL_ROOT_PASSWORD: "my-secret-pw" 14 | 15 | mysqlbackup: 16 | build: . 17 | volumes: 18 | - "./backup:/backup" 19 | environment: 20 | USERNAME: root 21 | PASSWORD: "my-secret-pw" 22 | DBHOST: mysql 23 | DBEXCLUDE: "performance_schema information_schema" 24 | #CRON_SCHEDULE: "* * * * *" 25 | EXTRA_OPTS: "--single-transaction" 26 | USER_ID: 1000 27 | GROUP_ID: 1000 28 | depends_on: 29 | - mysql 30 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "2.4" 2 | 3 | volumes: 4 | mysql-data: {} 5 | mysql-backups-data: {} 6 | 7 | services: 8 | mysql: 9 | image: mysql:8.0 10 | volumes: 11 | - "mysql-data:/var/lib/mysql" 12 | environment: 13 | MYSQL_ROOT_PASSWORD: "my-secret-pw" 14 | 15 | mysqlbackup: 16 | image: selim13/automysqlbackup:2.6-9 17 | volumes: 18 | - "mysql-backups-data:/backup" 19 | environment: 20 | USERNAME: root 21 | PASSWORD: "my-secret-pw" 22 | DBHOST: mysql 23 | DBEXCLUDE: "performance_schema information_schema" 24 | CRON_SCHEDULE: "0 0 * * *" 25 | EXTRA_OPTS: "--single-transaction" 26 | depends_on: 27 | - mysql 28 | -------------------------------------------------------------------------------- /my.cnf: -------------------------------------------------------------------------------- 1 | [mysqldump] 2 | column-statistics=0 -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | # usage: file_env VAR [DEFAULT] 6 | # ie: file_env 'XYZ_DB_PASSWORD' 'example' 7 | # (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of 8 | # "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature) 9 | file_env() { 10 | local var="$1" 11 | local fileVar="${var}_FILE" 12 | local def="${2:-}" 13 | if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then 14 | echo >&2 "error: both $var and $fileVar are set (but are exclusive)" 15 | exit 1 16 | fi 17 | local val="$def" 18 | if [ "${!var:-}" ]; then 19 | val="${!var}" 20 | elif [ "${!fileVar:-}" ]; then 21 | val="$(< "${!fileVar}")" 22 | fi 23 | export "$var"="$val" 24 | unset "$fileVar" 25 | } 26 | 27 | # Get PASSWORD from PASSWORD_FILE if available 28 | file_env 'PASSWORD' 29 | 30 | # Get USERNAME from USERNAME_FILE if availabile 31 | file_env 'USERNAME' 32 | 33 | # Select user to run the process 34 | user="root" 35 | if [ "$USER_ID" ] && [ "$USER_ID" != "1" ]; then 36 | usermod --uid $USER_ID automysqlbackup > /dev/null 37 | groupmod --gid $USER_ID automysqlbackup 38 | 39 | # make sure we can write to stdout and stderr as user 40 | chown --dereference automysqlbackup "/proc/$$/fd/1" "/proc/$$/fd/2" || : 41 | # ignore errors thanks to https://github.com/docker-library/mongo/issues/149 42 | 43 | user="automysqlbackup" 44 | fi 45 | 46 | # Select group to run the process 47 | group="$user" 48 | if [ "$GROUP_ID" ]; then 49 | if [ "$GROUP_ID" == "1" ]; then 50 | group="root" 51 | else 52 | groupmod -g $GROUP_ID automysqlbackup 53 | group="automysqlbackup" 54 | fi 55 | fi 56 | 57 | if [ "${CRON_SCHEDULE}" ]; then 58 | exec gosu $user:$group go-cron -s "0 ${CRON_SCHEDULE}" -- automysqlbackup 59 | else 60 | exec gosu $user:$group bash /usr/local/bin/automysqlbackup 61 | fi 62 | -------------------------------------------------------------------------------- /test/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | BACKUPS_DIR="$1" 4 | 5 | DBFILE=$(sudo find $BACKUPS_DIR -type f -size +1b -name '*testdb*.gz') 6 | 7 | [ "$DBFILE" != "" ] || { echo "::error::Backups not created" && exit 1; } 8 | zgrep ignoretable "$DBFILE" && { echo "::error::Ignored table found in the backup" && exit 1; } || true -------------------------------------------------------------------------------- /test/testdb-init.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE testdb; 2 | 3 | USE testdb; 4 | 5 | CREATE TABLE test_table ( 6 | id INT AUTO_INCREMENT PRIMARY KEY, 7 | name VARCHAR(255) NOT NULL 8 | ) ENGINE=INNODB; 9 | 10 | INSERT INTO test_table(name) VALUES ('Hello world!'); 11 | INSERT INTO test_table(name) VALUES ('Hello world!'); 12 | INSERT INTO test_table(name) VALUES ('Hello world!'); --------------------------------------------------------------------------------