package metrics

import (
	"archive/tar"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/DataDog/zstd"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/api/types/image"
	"github.com/docker/go-connections/nat"
	"github.com/onsi/gomega"
	"github.com/pingcap/errors"
	"github.com/pingcap/log"
	"github.com/prometheus/common/model"
	"go.uber.org/zap"

	"github.com/pingcap-inc/clinic/pkg/db_docker/db/impl"
)

const (
	vmVersion = "latest"

	timeout  = time.Second * 120
	interval = time.Second * 1
)

// TODO: use configurable port
func StartVmDocker() error {
	//for {
	//	//VmPort++
	//	if !impl.IsPortAvailable(8400) {
	//		return startVM(VmPort)
	//	}
	//	log.Info("port is not available, try another one", zap.Uint16("port", VmPort))
	//}

	storeImageName := fmt.Sprintf("victoriametrics/vmstorage:%s", vmVersion)
	err := startVMComponent(storeImageName, []uint16{8400, 8401}, nil)
	if err != nil {
		panic(err)
	}

	insertImageName := fmt.Sprintf("victoriametrics/vminsert:%s", vmVersion)
	err = startVMComponent(insertImageName, []uint16{VmInsert}, []string{"--storageNode=vmstorage:8400"})
	if err != nil {
		panic(err)
	}

	selectImageName := fmt.Sprintf("victoriametrics/vmselect:%s", vmVersion)
	err = startVMComponent(selectImageName, []uint16{VmSelect}, []string{"--storageNode=vmstorage:8401"})
	if err != nil {
		panic(err)
	}

	for !isVmReady(VmInsert) {
		log.Info("waiting for vm", zap.String("version", vmVersion), zap.Uint16("port", VmInsert))
		time.Sleep(time.Millisecond * 500)
	}

	for !isVmReady(VmSelect) {
		log.Info("waiting for vm", zap.String("version", vmVersion), zap.Uint16("port", VmSelect))
		time.Sleep(time.Millisecond * 500)
	}

	return nil
}

// imageName := fmt.Sprintf("victoriametrics/vmstorage:%s", vmVersion)
func startVMComponent(imageName string, ports []uint16, cmd []string) error {
	ctx := context.Background()
	cli, err := impl.GetDockerClient()
	if err != nil {
		return err
	}

	images, err := cli.ImageList(ctx, image.ListOptions{
		All: false,
		Filters: filters.NewArgs(filters.KeyValuePair{
			Key:   "reference",
			Value: imageName,
		}),
	})
	if err != nil {
		return err
	}

	if len(images) < 1 {
		log.Info("image not found, pull image", zap.String("version", vmVersion), zap.Uint16s("ports", ports))
		out, err := cli.ImagePull(ctx, imageName, image.PullOptions{})
		if err != nil {
			return nil
		}
		log.Info("pull image done", zap.String("version", vmVersion), zap.Uint16s("ports", ports))
		_, _ = io.Copy(os.Stdout, out)
	}

	hostConfig := &container.HostConfig{
		//PortBindings: nat.PortMap{
		//	"8400/tcp": []nat.PortBinding{
		//		{
		//			HostIP:   "127.0.0.1",
		//			HostPort: fmt.Sprintf("%d", port),
		//		},
		//	},
		//	"8401/tcp": []nat.PortBinding{
		//		{
		//			HostIP:   "127.0.0.1",
		//			HostPort: fmt.Sprintf("%d", port),
		//		},
		//	},
		//},
	}

	portMap := make(map[nat.Port][]nat.PortBinding)
	exposedPorts := map[nat.Port]struct{}{}

	for _, port := range ports {
		portMap[nat.Port(fmt.Sprintf("%d/tcp", port))] = []nat.PortBinding{
			{
				HostIP:   "127.0.0.1",
				HostPort: fmt.Sprintf("%d", port),
			},
		}
		exposedPorts[nat.Port(fmt.Sprintf("%d/%s", port, "tcp"))] = struct{}{}
	}

	hostConfig.PortBindings = portMap

	var containerName string
	switch {
	case strings.Contains(imageName, "vmstorage"):
		containerName = "vmstorage"
	case strings.Contains(imageName, "vmselect"):
		hostConfig.Links = []string{"vmstorage:vmstorage"}
		containerName = "vmselect"
	case strings.Contains(imageName, "vminsert"):
		hostConfig.Links = []string{"vmstorage:vmstorage"}
		containerName = "vminsert"
	}

	cfg := &container.Config{
		Image:        imageName,
		Labels:       map[string]string{dockerLabelKey: dockerLabelValue},
		ExposedPorts: exposedPorts,
	}

	// exposedPorts := map[nat.Port]struct{}{}

	if len(cmd) > 0 {
		cfg.Cmd = cmd
	}

	resp, err := cli.ContainerCreate(ctx, cfg, hostConfig, nil, nil, containerName)
	if err != nil {
		return err
	}

	err = cli.ContainerStart(ctx, resp.ID, container.StartOptions{})
	if err != nil {
		return err
	}

	//for !isVmReady(port) {
	//	log.Info("waiting for vm", zap.String("version", vmVersion), zap.Uint16("port", port))
	//	time.Sleep(time.Millisecond * 500)
	//}

	return nil
}

func isVmReady(port uint16) bool {
	req, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/health", port), nil)
	if err != nil {
		log.Warn("waiting for vm", zap.Error(err))
		return false
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Warn("waiting for vm", zap.Error(err))
		return false
	}
	defer resp.Body.Close()

	return resp.StatusCode == http.StatusOK
}

var (
	VmSelect         = uint16(8481)
	VmInsert         = uint16(8480)
	dockerLabelKey   = "component"
	dockerLabelValue = "clinic-test-docker"
)

func StopAllVmDocker() {
	fmt.Println("release all importer docker")
	ctx := context.Background()
	cli, err := impl.GetDockerClient()
	if err != nil {
		log.Warn("failed to get the client", zap.Error(err))
	}
	cs, err := cli.ContainerList(ctx, container.ListOptions{
		Filters: filters.NewArgs(filters.KeyValuePair{
			Key:   "label",
			Value: fmt.Sprintf("%s=%s", dockerLabelKey, dockerLabelValue),
		}),
	})
	if err != nil {
		log.Warn("failed to get the client", zap.Error(err))
	}
	fmt.Println("> Clean Metric Docker")
	for _, item := range cs {
		fmt.Printf("removing container %s\n", item.ID)
		_ = cli.ContainerRemove(ctx, item.ID, container.RemoveOptions{Force: true})
	}
	fmt.Println("> Clean successful")
}

type PromQueryResponse struct {
	Status string          `json:"status"`
	Data   PromQueryResult `json:"data"`
}

type PromQueryResult struct {
	ResultType string       `json:"resultType"`
	Result     model.Matrix `json:"result"`
}

func MockPromResponse(filepath string, timestamp int64, compressed bool) ([]byte, error) {
	ss := make([]*model.SampleStream, 0)
	for k := 0; k < 100; k++ {
		sp := make([]model.SamplePair, 0)
		for i := 0; i < 100; i++ {
			if timestamp == 0 {
				timestamp = time.Now().Unix()
			}
			sp = append(sp, model.SamplePair{
				Timestamp: model.Time(timestamp),
				Value:     model.SampleValue(i),
			})
		}

		stream := model.SampleStream{
			Metric: map[model.LabelName]model.LabelValue{
				"instance": model.LabelValue(filepath),
				"id":       model.LabelValue(fmt.Sprintf("%s-%d", filepath, k)),
				"filepath": model.LabelValue(filepath),
			},
			Values: sp,
		}

		ss = append(ss, &stream)
	}

	resp := PromQueryResponse{
		Status: "success",
		Data: PromQueryResult{
			ResultType: "matrix",
			Result:     ss,
		},
	}

	if !compressed {
		return json.Marshal(resp)
	}

	data, err := json.Marshal(resp)
	if err != nil {
		return nil, err
	}

	return zstd.Compress(nil, data)
}

func NewTarReader(filepath string, timestamp int64, compressed bool, hostName string) (*tar.Reader, error) {
	promData, err := MockPromResponse(filepath, timestamp, compressed)
	if err != nil {
		return nil, err
	}

	fileName := "monitor/metrics"
	if hostName != "" {
		fileName += "/" + hostName + "/"
	} else {
		fileName += "/"
	}
	var buf bytes.Buffer
	tw := tar.NewWriter(&buf)

	for i := 0; i < 15; i++ {
		hdr := &tar.Header{
			Name: fmt.Sprintf("%s%d.json", fileName, i),
			Mode: 0o600,
			Size: int64(len(promData)),
		}
		if err := tw.WriteHeader(hdr); err != nil {
			log.Error("write header failed", zap.Error(err))
			return nil, err
		}
		if _, err := tw.Write(promData); err != nil {
			log.Error("write failed", zap.Error(err))
			return nil, err
		}
	}
	if err := tw.Close(); err != nil {
		log.Error("close failed", zap.Error(err))
		return nil, err
	}

	return tar.NewReader(&buf), nil
}

func NewTar(filepath string, timestamp int64, compressed bool, hostName string) (string, error) {
	promData, err := MockPromResponse(filepath, timestamp, compressed)
	if err != nil {
		return "", err
	}

	fileName := "monitor/metrics"
	if hostName != "" {
		fileName += "/" + hostName + "/"
	} else {
		fileName += "/"
	}
	file, err := os.CreateTemp("", "")
	if err != nil {
		return "", err
	}
	defer func() {
		_ = file.Close()
		_ = os.Remove(file.Name())
	}()

	tw := tar.NewWriter(file)

	clusterData := []byte(clusterJSON)

	hdr := &tar.Header{
		Name: "cluster.json",
		Mode: 0o600,
		Size: int64(len(clusterData)),
	}

	if err := tw.WriteHeader(hdr); err != nil {
		log.Error("write cluster json header failed", zap.Error(err))
		return "", err
	}
	if _, err := tw.Write(clusterData); err != nil {
		log.Error("write cluster json failed", zap.Error(err))
		return "", err
	}

	for i := 0; i < 15; i++ {
		hdr := &tar.Header{
			Name: fmt.Sprintf("%s%d.json", fileName, i),
			Mode: 0o600,
			Size: int64(len(promData)),
		}
		if err := tw.WriteHeader(hdr); err != nil {
			log.Error("write header failed", zap.Error(err))
			return "", err
		}
		if _, err := tw.Write(promData); err != nil {
			log.Error("write failed", zap.Error(err))
			return "", err
		}
	}

	if err := tw.Flush(); err != nil {
		log.Error("flush tar writer failed", zap.Error(err))
		return "", err
	}

	_ = tw.Close()

	if _, err := file.Seek(0, 0); err != nil {
		log.Error("reset file pointer failed", zap.Error(err))
		return "", err
	}

	zstdFile, err := os.CreateTemp("", "")
	if err != nil {
		log.Error("new zstd file failed", zap.Error(err))
		return "", err
	}
	defer func() {
		if err := zstdFile.Close(); err != nil {
			log.Error("zstdFile close failed", zap.Error(err))
		}
	}()

	writer := zstd.NewWriter(zstdFile)
	defer func() {
		if err := writer.Close(); err != nil {
			log.Error("zstd file writer close failed", zap.Error(err))
		}
	}()
	if _, err := io.Copy(writer, file); err != nil {
		log.Error("copy file to zstd file failed", zap.Error(err))
		return "", err
	}
	_ = writer.Flush()

	return zstdFile.Name(), nil
}

type QueryOption struct {
	Query    string
	StatTime int64
	EndTime  int64
}

func QueryEventually(host string, port uint16, opt QueryOption, orgID uint, g *gomega.WithT) model.Matrix {
	var response model.Matrix
	g.Eventually(func() bool {
		result, err := Query(host, port, opt, orgID)
		g.Expect(err).To(gomega.Succeed())
		if result.Len() == 0 {
			return false
		}

		response = result
		return true
	}, timeout, interval).Should(gomega.BeTrue())

	return response
}

func Query(host string, port uint16, option QueryOption, orgID uint) (model.Matrix, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("http://%s:%d/select/%d/prometheus/api/v1/query", host, port, orgID), nil)
	if err != nil {
		return nil, err
	}

	q := req.URL.Query()

	if option.StatTime == 0 {
		option.StatTime = time.Now().Unix() - 3600
	}

	if option.EndTime == 0 {
		option.EndTime = time.Now().Unix()
	}

	if option.EndTime < option.StatTime {
		return nil, errors.Errorf("invalid timerange, start=%d, end=%d", option.StatTime, option.EndTime)
	}

	q.Add("query", fmt.Sprintf("%s[%ds]", option.Query, (option.EndTime-option.StatTime)))
	// q.Add("start", fmt.Sprintf("%d", option.StatTime))
	// q.Add("end", fmt.Sprintf("%d", option.EndTime))
	req.URL.RawQuery = q.Encode()

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, errors.Errorf("query data failed. query=%s, msg=%v", option.Query, resp.Status)
	}

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var presp PromQueryResponse
	err = json.Unmarshal(data, &presp)
	if err != nil {
		return nil, err
	}

	return presp.Data.Result, nil
}

const clusterJSON = `{
  "cluster_name": "saos-htap-tidb-cluster-prod",
  "cluster_id": 6860009869741753344,
  "deploy_type": "tiup-cluster",
  "session": "fLGjP8sRcNz",
  "begin_time": "2021-11-25T12:16:19+08:00",
  "end_time": "2021-11-25T14:16:19+08:00",
  "collectors": [
    "system",
    "monitor",
    "log",
    "config"
  ],
  "topology": {
    "version": "v4.0.15",
    "attributes": {
      "tiup-cluster": {
        "GlobalOptions": {
          "User": "tidb",
          "Group": "",
          "SSHPort": 22,
          "SSHType": "builtin",
          "TLSEnabled": false,
          "DeployDir": "/chj/app/tidb/deploy",
          "DataDir": "/chj/app/tidb/data",
          "LogDir": "",
          "ResourceControl": {
            "MemoryLimit": "",
            "CPUQuota": "",
            "IOReadBandwidthMax": "",
            "IOWriteBandwidthMax": "",
            "LimitCORE": ""
          },
          "OS": "linux",
          "Arch": "amd64",
          "Custom": null
        },
        "MonitoredOptions": {
          "NodeExporterPort": 9100,
          "BlackboxExporterPort": 9115,
          "DeployDir": "/chj/app/tidb/monitored/monitored-9100",
          "DataDir": "/chj/app/tidb/monitored/monitored-9100/data",
          "LogDir": "/chj/app/tidb/monitored/monitored-9100/log",
          "NumaNode": "",
          "ResourceControl": {
            "MemoryLimit": "",
            "CPUQuota": "",
            "IOReadBandwidthMax": "",
            "IOWriteBandwidthMax": "",
            "LimitCORE": ""
          }
        },
        "ServerConfigs": {
          "TiDB": {
            "binlog.enable": false,
            "binlog.ignore-error": false,
            "log.slow-threshold": 2000,
            "mem-quota-query": 2147483648,
            "oom-action": "log",
            "tmp-storage-path": "/chj/app/tidb/data/tmp"
          },
          "TiKV": {
            "readpool.storage.use-unified-pool": false,
            "readpool.coprocessor.use-unified-pool": true
          },
          "PD": {
            "schedule.leader-schedule-limit": 4,
            "schedule.region-schedule-limit": 2048,
            "schedule.replica-schedule-limit": 64
          },
          "TiFlash": {
            "logger.level": "info"
          },
          "TiFlashLearner": {
            "log-level": "info"
          },
          "Pump": {
            
          },
          "Drainer": {
            
          },
          "CDC": {
            
          }
        },
        "TiDBServers": [
          {
            "Host": "172.21.49.83",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 4000,
            "StatusPort": 10080,
            "DeployDir": "/chj/app/tidb/deploy/tidb-4000",
            "LogDir": "/chj/app/tidb/deploy/tidb-4000/log",
            "NumaNode": "",
            "Config": {
              "log.level": "info",
              "log.slow-query-file": "tidb_slow_query.log"
            },
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.49.84",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 4000,
            "StatusPort": 10080,
            "DeployDir": "/chj/app/tidb/deploy/tidb-4000",
            "LogDir": "/chj/app/tidb/deploy/tidb-4000/log",
            "NumaNode": "",
            "Config": {
              "log.level": "info",
              "log.slow-query-file": "tidb_slow_query.log"
            },
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.49.165",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 4000,
            "StatusPort": 10080,
            "DeployDir": "/chj/app/tidb/deploy/tidb-4000",
            "LogDir": "/chj/app/tidb/deploy/tidb-4000/log",
            "NumaNode": "",
            "Config": {
              "log.level": "info",
              "log.slow-query-file": "tidb_slow_query.log"
            },
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.49.82",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 4000,
            "StatusPort": 10080,
            "DeployDir": "/chj/app/tidb/deploy/tidb-4000",
            "LogDir": "/chj/app/tidb/deploy/tidb-4000/log",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          }
        ],
        "TiKVServers": [
          {
            "Host": "172.21.58.64",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.65",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.66",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.84",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.85",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.86",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.62.184",
            "ListenHost": "",
            "AdvertiseAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 20160,
            "StatusPort": 20180,
            "AdvertiseStatusAddr": "",
            "DeployDir": "/chj/app/tidb/deploy/tikv-20160",
            "DataDir": "/chj/app/tidb/data/tikv-20160",
            "LogDir": "/chj/app/tidb/deploy/tikv-20160/log",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          }
        ],
        "TiFlashServers": [
          {
            "Host": "172.21.58.87",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "TCPPort": 9000,
            "HTTPPort": 8123,
            "FlashServicePort": 3930,
            "FlashProxyPort": 20170,
            "FlashProxyStatusPort": 20292,
            "StatusPort": 8234,
            "DeployDir": "/chj/app/tidb/deploy/tiflash-9000",
            "DataDir": "/chj/app/data/tiflash-9000",
            "LogDir": "/chj/app/tidb/deploy/tiflash-9000/log",
            "TmpDir": "",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "LearnerConfig": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.88",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "TCPPort": 9000,
            "HTTPPort": 8123,
            "FlashServicePort": 3930,
            "FlashProxyPort": 20170,
            "FlashProxyStatusPort": 20292,
            "StatusPort": 8234,
            "DeployDir": "/chj/app/tidb/deploy/tiflash-9000",
            "DataDir": "/chj/app/data/tiflash-9000",
            "LogDir": "/chj/app/tidb/deploy/tiflash-9000/log",
            "TmpDir": "",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "LearnerConfig": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.62.242",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "TCPPort": 9000,
            "HTTPPort": 8123,
            "FlashServicePort": 3930,
            "FlashProxyPort": 20170,
            "FlashProxyStatusPort": 20292,
            "StatusPort": 8234,
            "DeployDir": "/chj/app/tidb/deploy/tiflash-9000",
            "DataDir": "/chj/app/data/tiflash-9000",
            "LogDir": "/chj/app/tidb/deploy/tiflash-9000/log",
            "TmpDir": "",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "LearnerConfig": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.62.193",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "TCPPort": 9000,
            "HTTPPort": 8123,
            "FlashServicePort": 3930,
            "FlashProxyPort": 20170,
            "FlashProxyStatusPort": 20292,
            "StatusPort": 8234,
            "DeployDir": "/chj/app/tidb/deploy/tiflash-9000",
            "DataDir": "/chj/app/data/tiflash-9000",
            "LogDir": "/chj/app/tidb/deploy/tiflash-9000/log",
            "TmpDir": "",
            "Offline": false,
            "NumaNode": "",
            "Config": null,
            "LearnerConfig": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          }
        ],
        "PDServers": [
          {
            "Host": "172.21.49.82",
            "ListenHost": "",
            "AdvertiseClientAddr": "",
            "AdvertisePeerAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Name": "pd-1",
            "ClientPort": 2379,
            "PeerPort": 2380,
            "DeployDir": "/chj/app/tidb/deploy/pd-2379",
            "DataDir": "/chj/app/tidb/data/pd-2379",
            "LogDir": "/chj/app/tidb/deploy/pd-2379/log",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.49.83",
            "ListenHost": "",
            "AdvertiseClientAddr": "",
            "AdvertisePeerAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Name": "pd-2",
            "ClientPort": 2379,
            "PeerPort": 2380,
            "DeployDir": "/chj/app/tidb/deploy/pd-2379",
            "DataDir": "/chj/app/tidb/data/pd-2379",
            "LogDir": "/chj/app/tidb/deploy/pd-2379/log",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.49.84",
            "ListenHost": "",
            "AdvertiseClientAddr": "",
            "AdvertisePeerAddr": "",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Name": "pd-3",
            "ClientPort": 2379,
            "PeerPort": 2380,
            "DeployDir": "/chj/app/tidb/deploy/pd-2379",
            "DataDir": "/chj/app/tidb/data/pd-2379",
            "LogDir": "/chj/app/tidb/deploy/pd-2379/log",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          }
        ],
        "PumpServers": null,
        "Drainers": null,
        "CDCServers": [
          {
            "Host": "172.21.58.64",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 8300,
            "DeployDir": "/chj/app/tidb/deploy/cdc-8300",
            "DataDir": "/chj/app/tidb/data/cdc-8300",
            "LogDir": "/chj/app/tidb/deploy/cdc-8300/log",
            "Offline": false,
            "GCTTL": 86400,
            "TZ": "",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.65",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 8300,
            "DeployDir": "/chj/app/tidb/deploy/cdc-8300",
            "DataDir": "/chj/app/tidb/data/cdc-8300",
            "LogDir": "/chj/app/tidb/deploy/cdc-8300/log",
            "Offline": false,
            "GCTTL": 86400,
            "TZ": "",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          },
          {
            "Host": "172.21.58.66",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 8300,
            "DeployDir": "/chj/app/tidb/deploy/cdc-8300",
            "DataDir": "/chj/app/tidb/data/cdc-8300",
            "LogDir": "/chj/app/tidb/deploy/cdc-8300/log",
            "Offline": false,
            "GCTTL": 86400,
            "TZ": "",
            "NumaNode": "",
            "Config": null,
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux"
          }
        ],
        "TiSparkMasters": null,
        "TiSparkWorkers": null,
        "Monitors": [
          {
            "Host": "172.21.49.86",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 9090,
            "NgPort": 0,
            "DeployDir": "/chj/app/tidb/deploy/prometheus-8249",
            "DataDir": "/chj/app/tidb/data/prometheus-8249",
            "LogDir": "/chj/app/tidb/deploy/prometheus-8249/log",
            "NumaNode": "",
            "RemoteConfig": {
              "RemoteWrite": null,
              "RemoteRead": null
            },
            "ExternalAlertmanagers": [],
            "Retention": "",
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux",
            "RuleDir": ""
          }
        ],
        "Grafanas": [
          {
            "Host": "172.21.49.86",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "Port": 3000,
            "DeployDir": "/chj/app/tidb/deploy/grafana-3000",
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux",
            "DashboardDir": "",
            "Username": "admin",
            "Password": "admin",
            "AnonymousEnable": false,
            "RootURL": "",
            "Domain": "",
            "DefaultTheme": "",
            "OrgName": "",
            "OrgRole": ""
          }
        ],
        "Alertmanagers": [
          {
            "Host": "172.21.49.86",
            "SSHPort": 22,
            "Imported": false,
            "Patched": false,
            "IgnoreExporter": false,
            "WebPort": 9093,
            "ClusterPort": 9094,
            "DeployDir": "/chj/app/tidb/deploy/alertmanager-9093",
            "DataDir": "/chj/app/tidb/data/alertmanager-9093",
            "LogDir": "/chj/app/tidb/deploy/alertmanager-9093/log",
            "NumaNode": "",
            "ResourceControl": {
              "MemoryLimit": "",
              "CPUQuota": "",
              "IOReadBandwidthMax": "",
              "IOWriteBandwidthMax": "",
              "LimitCORE": ""
            },
            "Arch": "amd64",
            "OS": "linux",
            "ConfigFilePath": ""
          }
        ]
      },
      "last_ops_ver": "1.6.1 tiup\nGo Version: go1.17.2\nGit Ref: v1.6.1\nGitHash: 1f6ca2b18e5c96c075efb4c08084d6dc8659050b"
    },
    "pd": [
      {
        "host": "172.16.5.137",
        "port": 2379,
        "status_port": 2379,
        "ssh_port": 22,
        "attributes": {
          "imported": false,
          "log_dir": "/chj/app/tidb/deploy/pd-2379/log",
          "os": "linux",
          "data_dir": "/chj/app/tidb/data/pd-2379",
          "config": null,
          "arch": "amd64",
          "name": "pd-1",
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/pd-2379"
        }
      },
      {
        "host": "172.21.49.83",
        "port": 2379,
        "status_port": 2379,
        "ssh_port": 22,
        "attributes": {
          "name": "pd-2",
          "imported": false,
          "patched": false,
          "os": "linux",
          "arch": "amd64",
          "deploy_dir": "/chj/app/tidb/deploy/pd-2379",
          "data_dir": "/chj/app/tidb/data/pd-2379",
          "log_dir": "/chj/app/tidb/deploy/pd-2379/log",
          "config": null
        }
      },
      {
        "host": "172.21.49.84",
        "port": 2379,
        "status_port": 2379,
        "ssh_port": 22,
        "attributes": {
          "imported": false,
          "deploy_dir": "/chj/app/tidb/deploy/pd-2379",
          "data_dir": "/chj/app/tidb/data/pd-2379",
          "config": null,
          "os": "linux",
          "name": "pd-3",
          "patched": false,
          "log_dir": "/chj/app/tidb/deploy/pd-2379/log",
          "arch": "amd64"
        }
      }
    ],
    "tikv": [
      {
        "host": "172.21.58.64",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160",
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log",
          "config": null,
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false
        }
      },
      {
        "host": "172.21.58.65",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "config": null,
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160",
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log"
        }
      },
      {
        "host": "172.21.58.66",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160",
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log",
          "config": null
        }
      },
      {
        "host": "172.21.58.84",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log",
          "config": null,
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160"
        }
      },
      {
        "host": "172.21.58.85",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "config": null,
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160",
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log"
        }
      },
      {
        "host": "172.21.58.86",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160",
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log",
          "config": null,
          "os": "linux"
        }
      },
      {
        "host": "172.21.62.184",
        "port": 20160,
        "status_port": 20180,
        "ssh_port": 22,
        "attributes": {
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tikv-20160",
          "data_dir": "/chj/app/tidb/data/tikv-20160",
          "log_dir": "/chj/app/tidb/deploy/tikv-20160/log",
          "config": null
        }
      }
    ],
    "tidb": [
      {
        "host": "172.16.5.137",
        "port": 4000,
        "status_port": 10080,
        "ssh_port": 22,
        "attributes": {
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tidb-4000",
          "log_dir": "/chj/app/tidb/deploy/tidb-4000/log",
          "config": {
            "log.slow-query-file": "tidb_slow_query.log",
            "log.level": "info"
          },
          "os": "linux",
          "arch": "amd64"
        }
      },
      {
        "host": "172.21.49.84",
        "port": 4000,
        "status_port": 10080,
        "ssh_port": 22,
        "attributes": {
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tidb-4000",
          "log_dir": "/chj/app/tidb/deploy/tidb-4000/log",
          "config": {
            "log.level": "info",
            "log.slow-query-file": "tidb_slow_query.log"
          }
        }
      },
      {
        "host": "172.21.49.165",
        "port": 4000,
        "status_port": 10080,
        "ssh_port": 22,
        "attributes": {
          "config": {
            "log.level": "info",
            "log.slow-query-file": "tidb_slow_query.log"
          },
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tidb-4000",
          "log_dir": "/chj/app/tidb/deploy/tidb-4000/log"
        }
      },
      {
        "host": "172.21.49.82",
        "port": 4000,
        "status_port": 10080,
        "ssh_port": 22,
        "attributes": {
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tidb-4000",
          "log_dir": "/chj/app/tidb/deploy/tidb-4000/log",
          "config": null,
          "os": "linux"
        }
      }
    ],
    "tiflash": [
      {
        "host": "172.21.58.87",
        "port": 9000,
        "status_port": 20292,
        "ssh_port": 22,
        "attributes": {
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tiflash-9000",
          "log_dir": "/chj/app/tidb/deploy/tiflash-9000/log",
          "config": null,
          "os": "linux"
        }
      },
      {
        "host": "172.21.58.88",
        "port": 9000,
        "status_port": 20292,
        "ssh_port": 22,
        "attributes": {
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tiflash-9000",
          "log_dir": "/chj/app/tidb/deploy/tiflash-9000/log",
          "config": null,
          "os": "linux"
        }
      },
      {
        "host": "172.21.62.242",
        "port": 9000,
        "status_port": 20292,
        "ssh_port": 22,
        "attributes": {
          "os": "linux",
          "arch": "amd64",
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tiflash-9000",
          "log_dir": "/chj/app/tidb/deploy/tiflash-9000/log",
          "config": null
        }
      },
      {
        "host": "172.21.62.193",
        "port": 9000,
        "status_port": 20292,
        "ssh_port": 22,
        "attributes": {
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/tiflash-9000",
          "log_dir": "/chj/app/tidb/deploy/tiflash-9000/log",
          "config": null,
          "os": "linux",
          "arch": "amd64"
        }
      }
    ],
    "ticdc": [
      {
        "host": "172.21.58.64",
        "port": 8300,
        "status_port": 0,
        "ssh_port": 22,
        "attributes": {
          "log_dir": "/chj/app/tidb/deploy/cdc-8300/log",
          "gc-ttl": 86400,
          "tz": "",
          "deploy_dir": "/chj/app/tidb/deploy/cdc-8300",
          "patched": false,
          "config": null,
          "os": "linux",
          "arch": "amd64",
          "imported": false
        }
      },
      {
        "host": "172.21.58.65",
        "port": 8300,
        "status_port": 0,
        "ssh_port": 22,
        "attributes": {
          "gc-ttl": 86400,
          "log_dir": "/chj/app/tidb/deploy/cdc-8300/log",
          "os": "linux",
          "deploy_dir": "/chj/app/tidb/deploy/cdc-8300",
          "config": null,
          "arch": "amd64",
          "tz": "",
          "imported": false,
          "patched": false
        }
      },
      {
        "host": "172.21.58.66",
        "port": 8300,
        "status_port": 0,
        "ssh_port": 22,
        "attributes": {
          "imported": false,
          "deploy_dir": "/chj/app/tidb/deploy/cdc-8300",
          "log_dir": "/chj/app/tidb/deploy/cdc-8300/log",
          "gc-ttl": 86400,
          "patched": false,
          "config": null,
          "os": "linux",
          "arch": "amd64",
          "tz": ""
        }
      }
    ],
    "monitors": [
      {
        "host": "172.21.49.86",
        "port": 9090,
        "status_port": 0,
        "ssh_port": 22,
        "attributes": {
          "imported": false,
          "patched": false,
          "deploy_dir": "/chj/app/tidb/deploy/prometheus-8249",
          "log_dir": "/chj/app/tidb/deploy/prometheus-8249/log",
          "data_dir": "/chj/app/tidb/data/prometheus-8249",
          "os": "linux",
          "arch": "amd64"
        }
      }
    ]
  }
}`
