apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  serviceName: mysql
  replicas: 2
  template:
    metadata:
      labels:
        app: mysql
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
                - key: "app"
                  operator: In
                  values:
                  - mysql
            topologyKey: "kubernetes.io/hostname"
      initContainers:
      - name: init-mysql
        image: mysql:8
        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.
          cp /mnt/config-map/server.cnf /mnt/conf.d/
          cp /mnt/config-map/configure-slave.sh /mnt/script/
        volumeMounts:
        - name: conf
          mountPath: /mnt/conf.d
        - name: script
          mountPath: /mnt/script
        - name: config-map
          mountPath: /mnt/config-map
      containers:
      - name: mysql
        image: mysql:8
        env:
        - name: MYSQL_ALLOW_EMPTY_PASSWORD
          value: "1"
        ports:
        - name: mysql
          containerPort: 3306
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        - name: script
          mountPath: /script
        resources:
          requests:
            cpu: 500m
            memory: 1Gi
        livenessProbe:
          exec:
            command: ["mysqladmin", "ping"]
          initialDelaySeconds: 999
          periodSeconds: 10
          timeoutSeconds: 50
        readinessProbe:
          exec:
            # Check we can execute queries over TCP (skip-networking is off).
            command: ["mysql", "-h", "127.0.0.1", "-e", "SELECT 1"]
          initialDelaySeconds: 5
          periodSeconds: 2
          timeoutSeconds: 1
        lifecycle:
          postStart:
            exec:
              command: ["/bin/bash", "/script/configure-slave.sh", "run"]
      volumes:
      - name: conf
        emptyDir: {}
      - name: script
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
      - name: data
        persistentVolumeClaim:
          claimName: mysql-pv-claim
