apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: starcoin
  namespace: starcoin-barnard
  labels:
    app: starcoin
    network: barnard
spec:
  selector:
    matchLabels:
      app: starcoin
  serviceName: starcoin-svc
  replicas: 6
  template:
    metadata:
      name: starcoin
      labels:
        app: starcoin
        network: barnard
    spec:
      nodeSelector:
        starcoin/node-pool: seed-pool
      containers:
      - name: starcoin
        image: starcoin/starcoin:1.11.7-rc
        imagePullPolicy: Always
        command:
          - bash
          - -c
        args:
          -
            rm -rf /sc-data/barnard/starcoin.ipc /sc-data/barnard/starcoindb/db/starcoindb/LOCK;
            id=$(echo -e $POD_NAME|awk -F'-' '{print $2}') && IFS='; ' read -r -a node_keys <<< $NODE_KEYS &&
            node_key=${node_keys[$id]};
            if [ ! -z $node_key ]; then
              node_key_flag="--node-key ${node_key}";
            fi;
            /starcoin/starcoin -n barnard --discover-local true --min-peers-to-propagate 512 --max-peers-to-propagate 1024 --max-outgoing-peers 512 --max-incoming-peers 512 -d /sc-data $node_key_flag;
            ret=$?;
            db_corruption="SST file is ahead of WALs";
            if [ $ret -ne 0 ]; then
              error_message=$(tail -n 10 /sc-data/barnard/starcoin.log);
              echo "Try to handle error.";
              if [[ "$error_message" =~ .*"$db_corruption".* ]]; then
                echo "the db is corruption, try to remove rocksdb log file.";
                find /sc-data/barnard/starcoindb/db/starcoindb/ -name "*.log" -type f -exec mv '{}' '{}.bak' \;;
              fi;
            fi;

        ports:
          - containerPort: 9840
            hostPort: 9840
        volumeMounts:
        - name: starcoin-volume
          mountPath: /sc-data
        env:
          - name: POD_NAME
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: NODE_KEYS
            valueFrom:
              secretKeyRef:
                name: node-keys
                key: node-keys
        livenessProbe:
          tcpSocket:
            port: 9840
          initialDelaySeconds: 10
          periodSeconds: 5
          timeoutSeconds: 2
          failureThreshold: 3
          successThreshold: 1
        readinessProbe:
          exec:
            command:
              - sh
              - -c
              - >-
                 /starcoin/starcoin -n barnard -d /sc-data node sync status|grep Synchronized
          initialDelaySeconds: 10
          periodSeconds: 5
          timeoutSeconds: 2
          failureThreshold: 3
          successThreshold: 1
  volumeClaimTemplates:
  - metadata:
      name: starcoin-volume
      namespace: starcoin-barnard
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 50Gi
