Explore all UUID Generator open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in UUID Generator

No Popular Releases are available at this moment for UUID Generator

Popular Libraries in UUID Generator

uuid-generator

by furkankahvecii doticonphpdoticon

star image 3 doticon

Pure PHP UUID generator

uuid-generator

by sanikapanika doticonjavadoticon

star image 2 doticon

Generate uuids by just typing uuid to terminal

Trending New libraries in UUID Generator

uuid-generator

by furkankahvecii doticonphpdoticon

star image 3 doticon

Pure PHP UUID generator

uuid-generator

by sanikapanika doticonjavadoticon

star image 2 doticon

Generate uuids by just typing uuid to terminal

Top Authors in UUID Generator

1

sanikapanika

1 Libraries

star icon2

2

furkankahvecii

1 Libraries

star icon3

1

1 Libraries

star icon2

2

1 Libraries

star icon3

Trending Kits in UUID Generator

No Trending Kits are available at this moment for UUID Generator

Trending Discussions on UUID Generator

MySQL + Kubernetes statefulset with defined env variables

How to convert a UUID to a number with less than 40 digits?

Save Variable from a Pre-request script to use in a new Request

YAML/YQ - remove sections that have sub-sections containing a particular attribute match

How can I reference an array when I don't know the name of it?

React Context API context API issues , when adding and removing an items from UI

BLE: How to get correct service UUID and characteristic UUID?

Syntax to manually insert a UUID value in Postgres

QUESTION

MySQL + Kubernetes statefulset with defined env variables

Asked 2022-Mar-08 at 14:56

I'm following Kubernetes's MySQL as a StatefulSet from here. What the tutorial did not cover is how do I specify other environmental variables, like MYSQL_ROOT_PASSWORD, MYSQL_USER and such. I tried doing it myself, but didn't work. Here's the code:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169

and here is my kubectl get all,secret,configmap's result:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194

When I tried to describe the mysql-1 pod, it said that:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195

But when I tried logging in using my defined root password on mysql-0 pod, it works. I have also tried looking a duplicated question here, but the past's tutorial code has changed (FYI, I also tried it too despite the change), so it did not really help. Any help will do! Thanks in advance!

UPDATE I tried adding this:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197

on my mysql and xtrabackup containers, also didn't work, here's the get pods --watch return:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
237

For some reason mysql-1 ran for a while, then stopped.

Logs from mysql-1 pod :

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289

UPDATE

What I have tried again is stripping down a lot of optional code(I think...), and here is the result:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365

From the yaml above, the master pod is running without a problem, but for the slave pods, the process is pretty normal until it ran for a while, then they encountered an error. After that, the state went back to running again. I checked the error from the logs and turned out that they could not authenticate mysql using the user root and the root password that I've set, so they tried authenticating mysql using the user root with no password specified and succeeded. That's weird because I've set the env variables MYSQL_ROOT_PASSWORD already inside the initContainers and the containers themselves, so I tried to exec each of the slave pods. I ran echo $MYSQL_ROOT_PASSWORD and the result is the same as I have specified. So the problem now from the yaml above is the env variable that I've set on the yaml file did not penetrate through the mysql application, but only through the container's environmental system.

ANSWER

Answered 2021-Oct-28 at 03:33

I have solved the problem. Turns out I tweaked some of my first uploaded code because there was a syntax error and typos:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365$MYSQL_ROOT_PASSWORD ==> $(MYSQL_ROOT_PASSWORD) 
366#when calling env var inside command, you have to add the brackets
367
1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365$MYSQL_ROOT_PASSWORD ==> $(MYSQL_ROOT_PASSWORD) 
366#when calling env var inside command, you have to add the brackets
367-uroot -p$MYQSL_ROOT_PASSWORD ==> -u root --password=$(MYSQL_ROOT_PASSWORD)
368
1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365$MYSQL_ROOT_PASSWORD ==> $(MYSQL_ROOT_PASSWORD) 
366#when calling env var inside command, you have to add the brackets
367-uroot -p$MYQSL_ROOT_PASSWORD ==> -u root --password=$(MYSQL_ROOT_PASSWORD)
368START SLAVE USER='root' PASSWORD=$(MYSQL_ROOT_PASSWORD);" || exit 1 ==> START SLAVE;" || exit 1
369

and

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365$MYSQL_ROOT_PASSWORD ==> $(MYSQL_ROOT_PASSWORD) 
366#when calling env var inside command, you have to add the brackets
367-uroot -p$MYQSL_ROOT_PASSWORD ==> -u root --password=$(MYSQL_ROOT_PASSWORD)
368START SLAVE USER='root' PASSWORD=$(MYSQL_ROOT_PASSWORD);" || exit 1 ==> START SLAVE;" || exit 1
369MASTER_PASSWORD=$(MYSQL_ROOT_PASSWORD), \ ==> MASTER_PASSWORD='$(MYSQL_ROOT_PASSWORD)', \
370# have to put ' before and after getting the env value
371

Also, I noticed that the code from mine only works if you removed the livenessProbe and readinessProbe. Somehow, both of them is called before the env var gets loaded, that's why when readinessProbe executes this command:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365$MYSQL_ROOT_PASSWORD ==> $(MYSQL_ROOT_PASSWORD) 
366#when calling env var inside command, you have to add the brackets
367-uroot -p$MYQSL_ROOT_PASSWORD ==> -u root --password=$(MYSQL_ROOT_PASSWORD)
368START SLAVE USER='root' PASSWORD=$(MYSQL_ROOT_PASSWORD);" || exit 1 ==> START SLAVE;" || exit 1
369MASTER_PASSWORD=$(MYSQL_ROOT_PASSWORD), \ ==> MASTER_PASSWORD='$(MYSQL_ROOT_PASSWORD)', \
370# have to put ' before and after getting the env value
371command: ["mysql", "-h", "127.0.0.1", "-u", "root", "--password=$(MYSQL_ROOT_PASSWORD)", "-e", "SELECT 1"]
372

it failed because $(MYSQL_ROOT_PASSWORD)'s value was not found, therefore, resulting this error:

1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4  name: mysql
5spec:
6  selector:
7    matchLabels:
8      app: mysql
9  serviceName: mysql
10  replicas: 3
11  template:
12    metadata:
13      labels:
14        app: mysql
15    spec:
16      initContainers:
17      - name: init-mysql
18        image: mysql:5.7
19        env:
20        - name: MYSQL_ROOT_PASSWORD
21          valueFrom:
22            secretKeyRef:
23              name: mysql-secret
24              key: mysql-root-password
25        command:
26        - bash
27        - "-c"
28        - |
29          set -ex
30          # Generate mysql server-id from pod ordinal index.
31          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
32          ordinal=${BASH_REMATCH[1]}
33          echo [mysqld] > /mnt/conf.d/server-id.cnf
34          # Add an offset to avoid reserved server-id=0 value.
35          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
36          # Copy appropriate conf.d files from config-map to emptyDir.
37          if [[ $ordinal -eq 0 ]]; then
38            cp /mnt/config-map/primary.cnf /mnt/conf.d/
39          else
40            cp /mnt/config-map/replica.cnf /mnt/conf.d/
41          fi          
42        volumeMounts:
43        - name: conf
44          mountPath: /mnt/conf.d
45        - name: config-map
46          mountPath: /mnt/config-map
47      - name: clone-mysql
48        image: gcr.io/google-samples/xtrabackup:1.0
49        command:
50        - bash
51        - "-c"
52        - |
53          set -ex
54          # Skip the clone if data already exists.
55          [[ -d /var/lib/mysql/mysql ]] && exit 0
56          # Skip the clone on primary (ordinal index 0).
57          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
58          ordinal=${BASH_REMATCH[1]}
59          [[ $ordinal -eq 0 ]] && exit 0
60          # Clone data from previous peer.
61          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
62          # Prepare the backup.
63          xtrabackup --prepare --target-dir=/var/lib/mysql          
64        volumeMounts:
65        - name: data
66          mountPath: /var/lib/mysql
67          subPath: mysql
68        - name: conf
69          mountPath: /etc/mysql/conf.d
70      containers:
71      - name: mysql
72        image: mysql:5.7
73        env:
74        - name: MYSQL_ROOT_PASSWORD
75          valueFrom:
76            secretKeyRef:
77              name: mysql-secret
78              key: mysql-root-password
79        ports:
80        - name: mysql
81          containerPort: 3306
82        volumeMounts:
83        - name: data
84          mountPath: /var/lib/mysql
85          subPath: mysql
86        - name: conf
87          mountPath: /etc/mysql/conf.d
88        resources:
89          requests:
90            cpu: 100m
91            memory: 500Mi
92      - name: xtrabackup
93        image: gcr.io/google-samples/xtrabackup:1.0
94        env:
95        - name: MYSQL_ROOT_PASSWORD
96          valueFrom:
97            secretKeyRef:
98              name: mysql-secret
99              key: mysql-root-password
100        ports:
101        - name: xtrabackup
102          containerPort: 3307
103        command:
104        - bash
105        - "-c"
106        - |
107          set -ex
108          cd /var/lib/mysql
109
110          # Determine binlog position of cloned data, if any.
111          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
112            # XtraBackup already generated a partial "CHANGE MASTER TO" query
113            # because we're cloning from an existing replica. (Need to remove the tailing semicolon!)
114            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
115            # Ignore xtrabackup_binlog_info in this case (it's useless).
116            rm -f xtrabackup_slave_info xtrabackup_binlog_info
117          elif [[ -f xtrabackup_binlog_info ]]; then
118            # We're cloning directly from primary. Parse binlog position.
119            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
120            rm -f xtrabackup_binlog_info xtrabackup_slave_info
121            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
122                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
123          fi
124
125          # Check if we need to complete a clone by starting replication.
126          if [[ -f change_master_to.sql.in ]]; then
127            echo "Waiting for mysqld to be ready (accepting connections)"
128            until mysql -h 127.0.0.1 -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1"; do sleep 1; done
129
130            echo "Initializing replication from clone position"
131            mysql -h 127.0.0.1 \
132                  -e "$(<change_master_to.sql.in), \
133                          MASTER_HOST='mysql-0.mysql', \
134                          MASTER_USER='root', \
135                          MASTER_PASSWORD=$MYSQL_ROOT_PASSWORD, \
136                          MASTER_CONNECT_RETRY=10; \
137                        START SLAVE USER='root' PASSWORD=$MYSQL_ROOT_PASSWORD;" || exit 1
138            # In case of container restart, attempt this at-most-once.
139            mv change_master_to.sql.in change_master_to.sql.orig
140          fi
141
142          # Start a server to send backups when requested by peers.
143          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
144            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root --password=$MYSQL_ROOT_PASSWORD"          
145        volumeMounts:
146        - name: data
147          mountPath: /var/lib/mysql
148          subPath: mysql
149        - name: conf
150          mountPath: /etc/mysql/conf.d
151        resources:
152          requests:
153            cpu: 50m
154            memory: 50Mi
155      volumes:
156      - name: conf
157        emptyDir: {}
158      - name: config-map
159        configMap:
160          name: mysql
161  volumeClaimTemplates:
162  - metadata:
163      name: data
164    spec:
165      accessModes: ["ReadWriteOnce"]
166      resources:
167        requests:
168          storage: 10Gi
169NAME                              READY   STATUS                  RESTARTS   AGE
170pod/mysql-0                       2/2     Running                 0          11m
171pod/mysql-1                       1/2     Error                   7          11m
172pod/mysql-2                       0/2     Init:CrashLoopBackOff   6          10m
173
174NAME                         TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)          AGE
175service/kubernetes           ClusterIP      10.245.0.1       <none>           443/TCP          2d23h
176service/mysql                ClusterIP      None             <none>           3306/TCP         43h
177service/mysql-read           ClusterIP      10.245.81.173    <none>           3306/TCP         43h
178
179NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
180deployment.apps/phpmyadmin   1/1     1            1           2d18h
181
182NAME                                    DESIRED   CURRENT   READY   AGE
183replicaset.apps/phpmyadmin-6c57fd98bf   1         1         1       2d18h
184
185NAME                     READY   AGE
186statefulset.apps/mysql   1/3     11m
187
188NAME                         TYPE                                  DATA   AGE
189secret/mysql-pass            Opaque                                1      46h
190secret/mysql-secret          Opaque                                3      2d18h
191
192NAME                         DATA   AGE
193configmap/mysql              4      2d18h
194ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
195  - name: MYSQL_ROOT_HOST
196    value: "%"
197NAME                          READY   STATUS     RESTARTS   AGE
198mysql-0                       0/2     Init:0/2   0          7s
199mysql-0                       0/2     Init:1/2   0          18s
200mysql-0                       0/2     PodInitializing   0          19s
201mysql-0                       2/2     Running           0          20s
202mysql-1                       0/2     Pending           0          0s
203mysql-1                       0/2     Pending           0          0s
204mysql-1                       0/2     Pending           0          8s
205mysql-1                       0/2     Init:0/2          0          8s
206mysql-1                       0/2     Init:1/2          0          26s
207mysql-1                       0/2     Init:1/2          0          27s
208mysql-1                       0/2     PodInitializing   0          34s
209mysql-1                       2/2     Running           0          35s
210mysql-2                       0/2     Pending           0          0s
211mysql-2                       0/2     Pending           0          0s
212mysql-1                       1/2     Error             0          37s
213mysql-1                       1/2     Error             1          38s
214mysql-2                       0/2     Pending           0          3s
215mysql-2                       0/2     Init:0/2          0          3s
216mysql-1                       1/2     CrashLoopBackOff   1          53s
217mysql-1                       1/2     Error              2          54s
218mysql-2                       0/2     Init:1/2           0          21s
219mysql-2                       0/2     Init:Error         0          22s
220mysql-2                       0/2     Init:Error         1          23s
221mysql-2                       0/2     Init:CrashLoopBackOff   1          24s
222mysql-1                       1/2     CrashLoopBackOff        2          64s
223mysql-2                       0/2     Init:Error              2          38s
224mysql-1                       1/2     Error                   3          79s
225mysql-2                       0/2     Init:CrashLoopBackOff   2          50s
226mysql-1                       1/2     CrashLoopBackOff        3          92s
227mysql-2                       0/2     Init:Error              3          62s
228mysql-2                       0/2     Init:CrashLoopBackOff   3          74s
229mysql-1                       1/2     Error                   4          2m1s
230mysql-1                       1/2     CrashLoopBackOff        4          2m11s
231mysql-2                       0/2     Init:Error              4          113s
232mysql-2                       0/2     Init:CrashLoopBackOff   4          2m6s
233mysql-1                       1/2     Error                   5          3m29s
234mysql-1                       1/2     CrashLoopBackOff        5          3m41s
235mysql-2                       0/2     Init:Error              5          3m23s
236mysql-2                       0/2     Init:CrashLoopBackOff   5          3m34s
2372021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2382021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2392021-10-25 03:16:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started.
2402021-10-25T03:16:37.231906Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2412021-10-25T03:16:37.234015Z 0 [Note] mysqld (mysqld 5.7.36) starting as process 1 ...
2422021-10-25T03:16:37.237044Z 0 [Note] InnoDB: PUNCH HOLE support available
2432021-10-25T03:16:37.237196Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2442021-10-25T03:16:37.237263Z 0 [Note] InnoDB: Uses event mutexes
2452021-10-25T03:16:37.237345Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2462021-10-25T03:16:37.237416Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2472021-10-25T03:16:37.237489Z 0 [Note] InnoDB: Using Linux native AIO
2482021-10-25T03:16:37.237792Z 0 [Note] InnoDB: Number of pools: 1
2492021-10-25T03:16:37.238102Z 0 [Note] InnoDB: Using CPU crc32 instructions
2502021-10-25T03:16:37.240179Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2512021-10-25T03:16:37.248111Z 0 [Note] InnoDB: Completed initialization of buffer pool
2522021-10-25T03:16:37.251017Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2532021-10-25T03:16:37.263519Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2542021-10-25T03:16:37.307064Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2552021-10-25T03:16:37.307319Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2562021-10-25T03:16:37.307466Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2572021-10-25T03:16:37.353707Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2582021-10-25T03:16:37.354244Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2592021-10-25T03:16:37.354256Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2602021-10-25T03:16:37.355048Z 0 [Note] InnoDB: Waiting for purge to start
2612021-10-25T03:16:37.406335Z 0 [Note] InnoDB: 5.7.36 started; log sequence number 12660776
2622021-10-25T03:16:37.406850Z 0 [Note] Plugin 'FEDERATED' is disabled.
2632021-10-25T03:16:37.413880Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2642021-10-25T03:16:37.426491Z 0 [Note] InnoDB: Buffer pool(s) load completed at 211025  3:16:37
2652021-10-25T03:16:37.427210Z 0 [Note] Salting uuid generator variables, current_pid: 1, server_start_time: 1635131797, bytes_sent: 0, 
2662021-10-25T03:16:37.427438Z 0 [Note] Generated uuid: 'f6f89137-3541-11ec-84bc-f29710c93c86', server_start_time: 281476611842454, bytes_sent: 94355589700272
2672021-10-25T03:16:37.427554Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: f6f89137-3541-11ec-84bc-f29710c93c86.
2682021-10-25T03:16:38.109098Z 0 [Note] Auto generated SSL certificates are placed in data directory.
2692021-10-25T03:16:38.109327Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2702021-10-25T03:16:38.109395Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2712021-10-25T03:16:38.109907Z 0 [Warning] CA certificate ca.pem is self signed.
2722021-10-25T03:16:38.354105Z 0 [Note] Auto generated RSA key files are placed in data directory.
2732021-10-25T03:16:38.354795Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2742021-10-25T03:16:38.354968Z 0 [Note] IPv6 is available.
2752021-10-25T03:16:38.355039Z 0 [Note]   - '::' resolves to '::';
2762021-10-25T03:16:38.355125Z 0 [Note] Server socket created on IP: '::'.
2772021-10-25T03:16:38.357907Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2782021-10-25T03:16:38.361720Z 0 [Note] Failed to start slave threads for channel ''
2792021-10-25T03:16:38.366691Z 0 [Note] Event Scheduler: Loaded 0 events
2802021-10-25T03:16:38.367135Z 0 [Note] mysqld: ready for connections.
281Version: '5.7.36'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
2822021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2832021-10-25T03:16:39.759020Z 5 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2842021-10-25T03:16:56.006754Z 7 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2852021-10-25T03:17:21.016988Z 9 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2862021-10-25T03:18:03.010443Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2872021-10-25T03:19:30.984929Z 13 [Note] Access denied for user 'root'@'localhost' (using password: NO)
2882021-10-25T03:22:25.011291Z 15 [Note] Access denied for user 'root'@'localhost' (using password: NO)
289apiVersion: apps/v1
290kind: StatefulSet
291metadata:
292  name: mysql
293spec:
294  selector:
295    matchLabels:
296      app: mysql
297  serviceName: mysql
298  replicas: 3
299  template:
300    metadata:
301      labels:
302        app: mysql
303    spec:
304      initContainers:
305      - name: init-mysql
306        image: mysql:5.7
307        env:
308        - name: MYSQL_ROOT_PASSWORD
309          value: admin123
310        command:
311        - bash
312        - "-c"
313        - |
314          set -ex
315          # Generate mysql server-id from pod ordinal index.
316          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
317          ordinal=${BASH_REMATCH[1]}
318          echo [mysqld] > /mnt/conf.d/server-id.cnf
319          # Add an offset to avoid reserved server-id=0 value.
320          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
321          # Copy appropriate conf.d files from config-map to emptyDir.
322          if [[ $ordinal -eq 0 ]]; then
323            cp /mnt/config-map/primary.cnf /mnt/conf.d/
324          else
325            cp /mnt/config-map/replica.cnf /mnt/conf.d/
326          fi          
327        volumeMounts:
328        - name: conf
329          mountPath: /mnt/conf.d
330        - name: config-map
331          mountPath: /mnt/config-map
332      containers:
333      - name: mysql
334        image: mysql:5.7
335        env:
336        - name: MYSQL_ROOT_PASSWORD
337          value: admin123
338        ports:
339        - name: mysql
340          containerPort: 3306
341        volumeMounts:
342        - name: data
343          mountPath: /var/lib/mysql
344          subPath: mysql
345        - name: conf
346          mountPath: /etc/mysql/conf.d
347        resources:
348          requests:
349            cpu: 100m
350            memory: 500Mi
351      volumes:
352      - name: conf
353        emptyDir: {}
354      - name: config-map
355        configMap:
356          name: mysql
357  volumeClaimTemplates:
358  - metadata:
359      name: data
360    spec:
361      accessModes: ["ReadWriteOnce"]
362      resources:
363        requests:
364          storage: 10Gi
365$MYSQL_ROOT_PASSWORD ==> $(MYSQL_ROOT_PASSWORD) 
366#when calling env var inside command, you have to add the brackets
367-uroot -p$MYQSL_ROOT_PASSWORD ==> -u root --password=$(MYSQL_ROOT_PASSWORD)
368START SLAVE USER='root' PASSWORD=$(MYSQL_ROOT_PASSWORD);" || exit 1 ==> START SLAVE;" || exit 1
369MASTER_PASSWORD=$(MYSQL_ROOT_PASSWORD), \ ==> MASTER_PASSWORD='$(MYSQL_ROOT_PASSWORD)', \
370# have to put ' before and after getting the env value
371command: ["mysql", "-h", "127.0.0.1", "-u", "root", "--password=$(MYSQL_ROOT_PASSWORD)", "-e", "SELECT 1"]
3722021-10-25T03:16:39.011694Z 3 [Note] Access denied for user 'root'@'localhost' (using password: NO)
373

If someone has any additional info between livenessProbe, readinessProbe, and env var, please let me know, because my theory might be wrong. CMIIW. :)

Source https://stackoverflow.com/questions/69702207

QUESTION

How to convert a UUID to a number with less than 40 digits?

Asked 2022-Feb-17 at 17:49

I need to convert a UUID (like ffffffff-ffff-ffff-ffff-ffffffffffff) to a number with as least digits as possible. These UUIDs are being generated by com.fasterxml.uuid.impl.TimeBasedGenerator.java.

1package com.fasterxml.uuid.impl;
2
3import java.util.UUID;
4
5import com.fasterxml.uuid.*;
6
7/**
8 * Implementation of UUID generator that uses time/location based generation
9 * method (variant 1).
10 *<p>
11 * As all JUG provided implementations, this generator is fully thread-safe.
12 * Additionally it can also be made externally synchronized with other
13 * instances (even ones running on other JVMs); to do this,
14 * use {@link com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer}
15 * (or equivalent).
16 *
17 * @since 3.0
18 */
19public class TimeBasedGenerator extends NoArgGenerator
20{
21    /*
22    /**********************************************************************
23    /* Configuration
24    /**********************************************************************
25     */
26
27    protected final EthernetAddress _ethernetAddress;
28
29    /**
30     * Object used for synchronizing access to timestamps, to guarantee
31     * that timestamps produced by this generator are unique and monotonically increasings.
32     * Some implementations offer even stronger guarantees, for example that
33     * same guarantee holds between instances running on different JVMs (or
34     * with native code).
35     */
36    protected final UUIDTimer _timer;
37
38    /**
39     * Base values for the second long (last 8 bytes) of UUID to construct
40     */
41    protected final long _uuidL2;
42    
43    /*
44    /**********************************************************************
45    /* Construction
46    /**********************************************************************
47     */
48
49    /**
50     * @param ethAddr Hardware address (802.1) to use for generating
51     *   spatially unique part of UUID. If system has more than one NIC,
52     */
53    
54    public TimeBasedGenerator(EthernetAddress ethAddr, UUIDTimer timer)
55    {
56        byte[] uuidBytes = new byte[16];
57        if (ethAddr == null) {
58            ethAddr = EthernetAddress.constructMulticastAddress();
59        }
60        // initialize baseline with MAC address info
61        _ethernetAddress = ethAddr;
62        _ethernetAddress.toByteArray(uuidBytes, 10);
63        // and add clock sequence
64        int clockSeq = timer.getClockSequence();
65        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE] = (byte) (clockSeq >> 8);
66        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE+1] = (byte) clockSeq;
67        long l2 = UUIDUtil.gatherLong(uuidBytes, 8);
68        _uuidL2 = UUIDUtil.initUUIDSecondLong(l2);
69        _timer = timer;
70    }
71    
72    /*
73    /**********************************************************************
74    /* Access to config
75    /**********************************************************************
76     */
77
78    @Override
79    public UUIDType getType() { return UUIDType.TIME_BASED; }
80
81    public EthernetAddress getEthernetAddress() { return _ethernetAddress; }
82    
83    /*
84    /**********************************************************************
85    /* UUID generation
86    /**********************************************************************
87     */
88    
89    /* As timer is not synchronized (nor _uuidBytes), need to sync; but most
90     * importantly, synchronize on timer which may also be shared between
91     * multiple instances
92     */
93    @Override
94    public UUID generate()
95    {
96        final long rawTimestamp = _timer.getTimestamp();
97        // Time field components are kind of shuffled, need to slice:
98        int clockHi = (int) (rawTimestamp >>> 32);
99        int clockLo = (int) rawTimestamp;
100        // and dice
101        int midhi = (clockHi << 16) | (clockHi >>> 16);
102        // need to squeeze in type (4 MSBs in byte 6, clock hi)
103        midhi &= ~0xF000; // remove high nibble of 6th byte
104        midhi |= 0x1000; // type 1
105        long midhiL = (long) midhi;
106        midhiL = ((midhiL << 32) >>> 32); // to get rid of sign extension
107        // and reconstruct
108        long l1 = (((long) clockLo) << 32) | midhiL;
109        // last detail: must force 2 MSB to be '10'
110        return new UUID(l1, _uuidL2);
111    }
112}
113

I expect that every day at least 12 million UUIDs will be generated on a particular machine. I assume that TimeBasedGenerator will be instatiated once when the program starts and thus will have a constant network address and a constant random generator seed time (value now in the code snipped below).

1package com.fasterxml.uuid.impl;
2
3import java.util.UUID;
4
5import com.fasterxml.uuid.*;
6
7/**
8 * Implementation of UUID generator that uses time/location based generation
9 * method (variant 1).
10 *<p>
11 * As all JUG provided implementations, this generator is fully thread-safe.
12 * Additionally it can also be made externally synchronized with other
13 * instances (even ones running on other JVMs); to do this,
14 * use {@link com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer}
15 * (or equivalent).
16 *
17 * @since 3.0
18 */
19public class TimeBasedGenerator extends NoArgGenerator
20{
21    /*
22    /**********************************************************************
23    /* Configuration
24    /**********************************************************************
25     */
26
27    protected final EthernetAddress _ethernetAddress;
28
29    /**
30     * Object used for synchronizing access to timestamps, to guarantee
31     * that timestamps produced by this generator are unique and monotonically increasings.
32     * Some implementations offer even stronger guarantees, for example that
33     * same guarantee holds between instances running on different JVMs (or
34     * with native code).
35     */
36    protected final UUIDTimer _timer;
37
38    /**
39     * Base values for the second long (last 8 bytes) of UUID to construct
40     */
41    protected final long _uuidL2;
42    
43    /*
44    /**********************************************************************
45    /* Construction
46    /**********************************************************************
47     */
48
49    /**
50     * @param ethAddr Hardware address (802.1) to use for generating
51     *   spatially unique part of UUID. If system has more than one NIC,
52     */
53    
54    public TimeBasedGenerator(EthernetAddress ethAddr, UUIDTimer timer)
55    {
56        byte[] uuidBytes = new byte[16];
57        if (ethAddr == null) {
58            ethAddr = EthernetAddress.constructMulticastAddress();
59        }
60        // initialize baseline with MAC address info
61        _ethernetAddress = ethAddr;
62        _ethernetAddress.toByteArray(uuidBytes, 10);
63        // and add clock sequence
64        int clockSeq = timer.getClockSequence();
65        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE] = (byte) (clockSeq >> 8);
66        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE+1] = (byte) clockSeq;
67        long l2 = UUIDUtil.gatherLong(uuidBytes, 8);
68        _uuidL2 = UUIDUtil.initUUIDSecondLong(l2);
69        _timer = timer;
70    }
71    
72    /*
73    /**********************************************************************
74    /* Access to config
75    /**********************************************************************
76     */
77
78    @Override
79    public UUIDType getType() { return UUIDType.TIME_BASED; }
80
81    public EthernetAddress getEthernetAddress() { return _ethernetAddress; }
82    
83    /*
84    /**********************************************************************
85    /* UUID generation
86    /**********************************************************************
87     */
88    
89    /* As timer is not synchronized (nor _uuidBytes), need to sync; but most
90     * importantly, synchronize on timer which may also be shared between
91     * multiple instances
92     */
93    @Override
94    public UUID generate()
95    {
96        final long rawTimestamp = _timer.getTimestamp();
97        // Time field components are kind of shuffled, need to slice:
98        int clockHi = (int) (rawTimestamp >>> 32);
99        int clockLo = (int) rawTimestamp;
100        // and dice
101        int midhi = (clockHi << 16) | (clockHi >>> 16);
102        // need to squeeze in type (4 MSBs in byte 6, clock hi)
103        midhi &= ~0xF000; // remove high nibble of 6th byte
104        midhi |= 0x1000; // type 1
105        long midhiL = (long) midhi;
106        midhiL = ((midhiL << 32) >>> 32); // to get rid of sign extension
107        // and reconstruct
108        long l1 = (((long) clockLo) << 32) | midhiL;
109        // last detail: must force 2 MSB to be '10'
110        return new UUID(l1, _uuidL2);
111    }
112}
113final long now = 1644575806478L;
114
115final TimeBasedGenerator sut = new TimeBasedGenerator(EthernetAddress.fromInterface(),
116  new UUIDTimer(new Random(now), null));
117

How can I turn a UUID into a number with

a) less than 40 digits and

b) so that duplicate UUIDs occur once in 6 months the earliest?

Failed attempt 1

The simplest way to convert a UUID to a number looks like this:

1package com.fasterxml.uuid.impl;
2
3import java.util.UUID;
4
5import com.fasterxml.uuid.*;
6
7/**
8 * Implementation of UUID generator that uses time/location based generation
9 * method (variant 1).
10 *<p>
11 * As all JUG provided implementations, this generator is fully thread-safe.
12 * Additionally it can also be made externally synchronized with other
13 * instances (even ones running on other JVMs); to do this,
14 * use {@link com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer}
15 * (or equivalent).
16 *
17 * @since 3.0
18 */
19public class TimeBasedGenerator extends NoArgGenerator
20{
21    /*
22    /**********************************************************************
23    /* Configuration
24    /**********************************************************************
25     */
26
27    protected final EthernetAddress _ethernetAddress;
28
29    /**
30     * Object used for synchronizing access to timestamps, to guarantee
31     * that timestamps produced by this generator are unique and monotonically increasings.
32     * Some implementations offer even stronger guarantees, for example that
33     * same guarantee holds between instances running on different JVMs (or
34     * with native code).
35     */
36    protected final UUIDTimer _timer;
37
38    /**
39     * Base values for the second long (last 8 bytes) of UUID to construct
40     */
41    protected final long _uuidL2;
42    
43    /*
44    /**********************************************************************
45    /* Construction
46    /**********************************************************************
47     */
48
49    /**
50     * @param ethAddr Hardware address (802.1) to use for generating
51     *   spatially unique part of UUID. If system has more than one NIC,
52     */
53    
54    public TimeBasedGenerator(EthernetAddress ethAddr, UUIDTimer timer)
55    {
56        byte[] uuidBytes = new byte[16];
57        if (ethAddr == null) {
58            ethAddr = EthernetAddress.constructMulticastAddress();
59        }
60        // initialize baseline with MAC address info
61        _ethernetAddress = ethAddr;
62        _ethernetAddress.toByteArray(uuidBytes, 10);
63        // and add clock sequence
64        int clockSeq = timer.getClockSequence();
65        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE] = (byte) (clockSeq >> 8);
66        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE+1] = (byte) clockSeq;
67        long l2 = UUIDUtil.gatherLong(uuidBytes, 8);
68        _uuidL2 = UUIDUtil.initUUIDSecondLong(l2);
69        _timer = timer;
70    }
71    
72    /*
73    /**********************************************************************
74    /* Access to config
75    /**********************************************************************
76     */
77
78    @Override
79    public UUIDType getType() { return UUIDType.TIME_BASED; }
80
81    public EthernetAddress getEthernetAddress() { return _ethernetAddress; }
82    
83    /*
84    /**********************************************************************
85    /* UUID generation
86    /**********************************************************************
87     */
88    
89    /* As timer is not synchronized (nor _uuidBytes), need to sync; but most
90     * importantly, synchronize on timer which may also be shared between
91     * multiple instances
92     */
93    @Override
94    public UUID generate()
95    {
96        final long rawTimestamp = _timer.getTimestamp();
97        // Time field components are kind of shuffled, need to slice:
98        int clockHi = (int) (rawTimestamp >>> 32);
99        int clockLo = (int) rawTimestamp;
100        // and dice
101        int midhi = (clockHi << 16) | (clockHi >>> 16);
102        // need to squeeze in type (4 MSBs in byte 6, clock hi)
103        midhi &= ~0xF000; // remove high nibble of 6th byte
104        midhi |= 0x1000; // type 1
105        long midhiL = (long) midhi;
106        midhiL = ((midhiL << 32) >>> 32); // to get rid of sign extension
107        // and reconstruct
108        long l1 = (((long) clockLo) << 32) | midhiL;
109        // last detail: must force 2 MSB to be '10'
110        return new UUID(l1, _uuidL2);
111    }
112}
113final long now = 1644575806478L;
114
115final TimeBasedGenerator sut = new TimeBasedGenerator(EthernetAddress.fromInterface(),
116  new UUIDTimer(new Random(now), null));
117import java.math.BigInteger;
118import java.util.function.Function;
119
120public class OldUUIDConverter implements Function<String, BigInteger> {
121    @Override
122    public BigInteger apply(final String uuid) {
123        final String uuidWithoutDashes = uuid.replaceAll("-", "");
124        return new BigInteger(uuidWithoutDashes, 16);
125    }
126}
127

For the largest possible UUID (ffffffff-ffff-ffff-ffff-ffffffffffff) it producees the number

1package com.fasterxml.uuid.impl;
2
3import java.util.UUID;
4
5import com.fasterxml.uuid.*;
6
7/**
8 * Implementation of UUID generator that uses time/location based generation
9 * method (variant 1).
10 *<p>
11 * As all JUG provided implementations, this generator is fully thread-safe.
12 * Additionally it can also be made externally synchronized with other
13 * instances (even ones running on other JVMs); to do this,
14 * use {@link com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer}
15 * (or equivalent).
16 *
17 * @since 3.0
18 */
19public class TimeBasedGenerator extends NoArgGenerator
20{
21    /*
22    /**********************************************************************
23    /* Configuration
24    /**********************************************************************
25     */
26
27    protected final EthernetAddress _ethernetAddress;
28
29    /**
30     * Object used for synchronizing access to timestamps, to guarantee
31     * that timestamps produced by this generator are unique and monotonically increasings.
32     * Some implementations offer even stronger guarantees, for example that
33     * same guarantee holds between instances running on different JVMs (or
34     * with native code).
35     */
36    protected final UUIDTimer _timer;
37
38    /**
39     * Base values for the second long (last 8 bytes) of UUID to construct
40     */
41    protected final long _uuidL2;
42    
43    /*
44    /**********************************************************************
45    /* Construction
46    /**********************************************************************
47     */
48
49    /**
50     * @param ethAddr Hardware address (802.1) to use for generating
51     *   spatially unique part of UUID. If system has more than one NIC,
52     */
53    
54    public TimeBasedGenerator(EthernetAddress ethAddr, UUIDTimer timer)
55    {
56        byte[] uuidBytes = new byte[16];
57        if (ethAddr == null) {
58            ethAddr = EthernetAddress.constructMulticastAddress();
59        }
60        // initialize baseline with MAC address info
61        _ethernetAddress = ethAddr;
62        _ethernetAddress.toByteArray(uuidBytes, 10);
63        // and add clock sequence
64        int clockSeq = timer.getClockSequence();
65        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE] = (byte) (clockSeq >> 8);
66        uuidBytes[UUIDUtil.BYTE_OFFSET_CLOCK_SEQUENCE+1] = (byte) clockSeq;
67        long l2 = UUIDUtil.gatherLong(uuidBytes, 8);
68        _uuidL2 = UUIDUtil.initUUIDSecondLong(l2);
69        _timer = timer;
70    }
71    
72    /*
73    /**********************************************************************
74    /* Access to config
75    /**********************************************************************
76     */
77
78    @Override
79    public UUIDType getType() { return UUIDType.TIME_BASED; }
80
81    public EthernetAddress getEthernetAddress() { return _ethernetAddress; }
82    
83    /*
84    /**********************************************************************
85    /* UUID generation
86    /**********************************************************************
87     */
88    
89    /* As timer is not synchronized (nor _uuidBytes), need to sync; but most
90     * importantly, synchronize on timer which may also be shared between
91     * multiple instances
92     */
93    @Override
94    public UUID generate()
95    {
96        final long rawTimestamp = _timer.getTimestamp();
97        // Time field components are kind of shuffled, need to slice:
98        int clockHi = (int) (rawTimestamp >>> 32);
99        int clockLo = (int) rawTimestamp;
100        // and dice
101        int midhi = (clockHi << 16) | (clockHi >>> 16);
102        // need to squeeze in type (4 MSBs in byte 6, clock hi)
103        midhi &= ~0xF000; // remove high nibble of 6th byte
104        midhi |= 0x1000; // type 1
105        long midhiL = (long) midhi;
106        midhiL = ((midhiL << 32) >>> 32); // to get rid of sign extension
107        // and reconstruct
108        long l1 = (((long) clockLo) << 32) | midhiL;
109        // last detail: must force 2 MSB to be '10'
110        return new UUID(l1, _uuidL2);
111    }
112}
113final long now = 1644575806478L;
114
115final TimeBasedGenerator sut = new TimeBasedGenerator(EthernetAddress.fromInterface(),
116  new UUIDTimer(new Random(now), null));
117import java.math.BigInteger;
118import java.util.function.Function;
119
120public class OldUUIDConverter implements Function<String, BigInteger> {
121    @Override
122    public BigInteger apply(final String uuid) {
123        final String uuidWithoutDashes = uuid.replaceAll("-", "");
124        return new BigInteger(uuidWithoutDashes, 16);
125    }
126}
127340282366920938463463374607431768211455
128^         ^         ^         ^         ^
129

Because we convert the UUID directly, it won't be repeated if the UUID generator does not produce duplicate UUIDs too frequently.

The criterion b) of the above requirement is satisfied. But criterion a) -- the length of the converted number -- is not.

Failed attempt 2

Someone proposed to only take the first 8 digits of the UUID. Thus the criterion a) will be satisfied.

However, the first 8 digits of the UUID repeat too frequently.

I wrote a simple test program:

1package com.fasterxml.uuid.impl;
2
3import java.util.UUID;
4
5import com.fasterxml.uuid.*;
6
7/**
8 * Implementation of UUID generator that uses time/location based generation
9 * method (variant 1).
10 *<p>
11 * As all JUG provided implementations, this generator is fully thread-safe.
12 * Additionally it can also be made externally synchronized with other
13 * instances (even ones running on other JVMs); to do this,
14 * use {@link com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer}
15 * (or equivalent).
16 *
17 * @since 3.0
18 */
19public class TimeBasedGenerator extends NoArgGenerator
20{
21    /*
22    /**********************************************************************
23    /* Configuration
24    /**********************************************************************
25     */
26
27    protected final EthernetAddress _ethernetAddress;
28
29    /**
30     * Object used for synchronizing access to timestamps, to guarantee
31     * that timestamps produced by this generator are unique and monotonically increasings.
32     * Some implementations offer even stronger guarantees, for example that
33     * same guarantee holds between instances running on different JVMs (or
34     * with native code).
35     */
36    protected final UUIDTimer _timer;
37
38    /**
39     * Base values for the second long (last 8 bytes) of UUID to construct
40     */
41    protected final long _uuidL2;
42    
43    /*
44    /**********************************************************************
45    /* Construction
46    /**********************************************************************
47     */
48
49    /**