apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  serviceName: mysql
  replicas: 3
  template:
    metadata:
      labels:
        app: mysql
    spec:
      initContainers:
      - name: init-mysql
        image: mysql:5.7
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: XTRABACKUP_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: MYSQL_ROOT_HOST
          value: "%"
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Generate mysql server-id from pod ordinal index.
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          echo [mysqld] > /mnt/conf.d/server-id.cnf
          # Add an offset to avoid reserved server-id=0 value.
          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
          # Copy appropriate conf.d files from config-map to emptyDir.
          if [[ $ordinal -eq 0 ]]; then
            cp /mnt/config-map/master.cnf /mnt/conf.d/
          else
            cp /mnt/config-map/slave.cnf /mnt/conf.d/
          fi
        resources:
          requests:
            cpu: 10m
            memory: 100Mi
        volumeMounts:
        - name: conf
          mountPath: /mnt/conf.d
        - name: config-map
          mountPath: /mnt/config-map
      - name: clone-mysql
        image: gcr.io/google-samples/xtrabackup:1.0
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: XTRABACKUP_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: MYSQL_ROOT_HOST
          value: "%"
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Skip the clone if data already exists.
          [[ -d /var/lib/mysql/mysql ]] && exit 0
          # Skip the clone on master (ordinal index 0).
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          [[ $ordinal -eq 0 ]] && exit 0
          # Clone data from previous peer.
          # mysql-X.mysql.default.svc.cluster.local
          # ncat --recv-only mysql-$(($ordinal-1)).mysql.default.svc.cluster.local. 3307 | xbstream -x -C /var/lib/mysql
          # mysql-0.mysql.default.svc.cluster.local
          ncat --recv-only mysql-0.mysql.default.svc.cluster.local. 3307 | xbstream -x -C /var/lib/mysql
          # Prepare the backup.
          xtrabackup --prepare -u root --password=$MYSQL_ROOT_PASSWORD --target-dir=/var/lib/mysql
        resources:
          requests:
            cpu: 10m
            memory: 100Mi
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
      containers:
      - name: mysql
        image: mysql:5.7
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: XTRABACKUP_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: MYSQL_ROOT_HOST
          value: "%"
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 300m
            memory: 1Gi
        livenessProbe:
          exec:
            command:
            - bash
            - -c
            - mysqladmin -uroot -p"${MYSQL_ROOT_PASSWORD}" ping
          initialDelaySeconds: 65
          periodSeconds: 5
          timeoutSeconds: 2
        readinessProbe:
          exec:
            # Check we can execute queries over TCP (skip-networking is off).
            command:
            - bash
            - -c
            - mysql -h127.0.0.1 -uroot -p"${MYSQL_ROOT_PASSWORD}" -e 'SHOW DATABASES;'
          initialDelaySeconds: 65
          periodSeconds: 5
          timeoutSeconds: 2
      - name: xtrabackup
        image: gcr.io/google-samples/xtrabackup:1.0
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: XTRABACKUP_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql
              key: root_password
        - name: MYSQL_ROOT_HOST
          value: "%"
        ports:
        - name: xtrabackup
          containerPort: 3307
        command:
        - bash
        - "-c"
        - |
          set -ex
          cd /var/lib/mysql

          # Determine binlog position of cloned data, if any.
          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
            # XtraBackup already generated a partial "CHANGE MASTER TO" query
            # because we're cloning from an existing slave. (Need to remove the tailing semicolon!)
            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
            # Ignore xtrabackup_binlog_info in this case (it's useless).
            rm -f xtrabackup_slave_info xtrabackup_binlog_info
          elif [[ -f xtrabackup_binlog_info ]]; then
            # We're cloning directly from master. Parse binlog position.
            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
            rm -f xtrabackup_binlog_info xtrabackup_slave_info
            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
          fi

          echo "Waiting for mysqld to be ready (accepting connections)"
          until mysql -h 127.0.0.1 -u root -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done

          if ! mysql -h 127.0.0.1 \
             -u root -p$MYSQL_ROOT_PASSWORD \
             -e "INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so';
                 INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so';"
          then
              echo "Error code: $? of SQL: SET GLOBAL rpl_semi_sync_master_enabled = 1;"
          else
            echo "Query OK"
          fi

          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          # Copy appropriate conf.d files from config-map to emptyDir.
          if [[ $ordinal -eq 0 ]]; then
            echo "Configure semi-sync replication"
            if ! mysql -h 127.0.0.1 \
                  -u root -p$MYSQL_ROOT_PASSWORD \
                  -e "SET GLOBAL rpl_semi_sync_master_enabled = 1;
                      SET GLOBAL rpl_semi_sync_master_timeout = 10000;"
            then
              echo "Error code: $? of SQL: SET GLOBAL rpl_semi_sync_master_enabled = 1;"
            else
              echo "Query OK"
            fi
          else
            echo "Enable semi-sync replication"
            if ! mysql -h 127.0.0.1 \
                  -u root -p$MYSQL_ROOT_PASSWORD \
                  -e "SET GLOBAL rpl_semi_sync_slave_enabled = 1;
                      STOP SLAVE IO_THREAD;
                      START SLAVE IO_THREAD;"
            then
              echo "error code: $? of sql: SET GLOBAL rpl_semi_sync_slave_enabled = 1;"
            else
              echo "query ok"
            fi
            # In case of container restart, attempt this at-most-once.
            mysql -h 127.0.0.1 \
                  -u root -p$MYSQL_ROOT_PASSWORD \
                  -e "STOP SLAVE; CHANGE MASTER TO \
                          MASTER_HOST='mysql-0.mysql.default.svc.cluster.local', \
                          MASTER_USER='root', \
                          MASTER_PASSWORD='"$MYSQL_ROOT_PASSWORD"', \
                          MASTER_CONNECT_RETRY=10,
                          MASTER_AUTO_POSITION = 1; \
                      START SLAVE;" || exit 1
          fi

          # Check if we need to complete a clone by starting replication.
          if [[ -f change_master_to.sql.in ]]; then
            mv change_master_to.sql.in change_master_to.sql.orig
          fi

          # Start a server to send backups when requested by peers.
          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 40m
            memory: 100Mi
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 32Gi
