apiVersion: batch/v1
kind: Job
metadata:
  name: {{ .identity }}
  labels:
    app.kubernetes.io/instance: db
    app.kubernetes.io/component: tidb-initializer
spec:
  backoffLimit: 1000
  template:
    metadata:
      labels:
        app.kubernetes.io/instance: db
        app.kubernetes.io/component: tidb-initializer
      annotations:
        iam.amazonaws.com/role: {{ .assumeRoleArn }}
    spec:
      restartPolicy: OnFailure
      initContainers:
      # Before proceeding to initialize TiDB, we wait for the TiDB host:port is
      # open. This avoids unnecessary pod restarts which may result in a very long
      # restart delay (10s, 20s, .., 5 mins).
      # https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
      - name: wait
        image: "busybox:1.31.1"
        imagePullPolicy: "IfNotPresent"
        command:
        - sh
        - -c
        - |
          trap exit TERM # because we don't use dumb-init
          host={{ .tidbHost }}
          port=4000
          while true; do
            nc -zv -w 3 "$host" "$port"
            if [ $? -eq 0 ]; then
              break
            else
              echo "info: failed to connect to $host:$port, sleep 1 second then retry"
              sleep 1
            fi
          done
          echo "info: successfully connected to $host:$port, able to initialize TiDB now"
      containers:
      - name: mysql-client
        image: {{ .image }}
        imagePullPolicy: "IfNotPresent"
        args:
        - python
        - -c
        - |
          import os, MySQLdb
          sql="""
          CREATE USER dbaas_root@'%%' IDENTIFIED BY '%s';
          GRANT ALL ON *.* TO 'dbaas_root'@'%%';
          CREATE USER dbaas_shell@'%%' IDENTIFIED BY '%s';
          GRANT ALL ON *.* TO 'dbaas_shell'@'%%';
          revoke super on *.* from 'dbaas_shell'@'%%';
          ALTER USER 'root'@'%%' IDENTIFIED BY '%s';
          revoke super on *.* from 'root'@'%%';
          FLUSH PRIVILEGES;
          """ % (os.environ.get('DBAAS_PASSWORD'), os.environ.get('DBAAS_SHELL_PASSWORD'), os.environ.get('ROOT_PASSWORD'))
          # import sys; sys.stdout.flush(); print(sql)
          conn = MySQLdb.connect(host='{{.tidbHost}}', port=4000, user='root')
          for line in sql.splitlines():
              if line == '':
                  continue
              conn.cursor().execute(line)
              conn.commit()
        env:
        - name: AWS_DEFAULT_REGION
          value: "{{ .region }}"
        - name: KMS_ENCRYPTED_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: "{{ .passwordSecretName }}"
              key: root
        - name: KMS_ENCRYPTED_DBAAS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: "{{ .passwordSecretName }}"
              key: dbaas
        - name: KMS_ENCRYPTED_DBAAS_SHELL_PASSWORD
          valueFrom:
            secretKeyRef:
              name: "{{ .passwordSecretName }}"
              key: dbaas_shell

