File: tiproxy.go

package info (click to toggle)
tiup 1.16.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,384 kB
  • sloc: sh: 1,988; makefile: 138; sql: 16
file content (157 lines) | stat: -rw-r--r-- 4,086 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package instance

import (
	"context"
	"encoding/pem"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/BurntSushi/toml"
	"github.com/pingcap/tiup/pkg/cluster/spec"
	"github.com/pingcap/tiup/pkg/crypto"
	"github.com/pingcap/tiup/pkg/utils"
)

// TiProxy represent a ticdc instance.
type TiProxy struct {
	instance
	pds []*PDInstance
	Process
}

var _ Instance = &TiProxy{}

// GenTiProxySessionCerts will create a self-signed certs for TiProxy session migration. NOTE that this cert is directly used by TiDB.
func GenTiProxySessionCerts(dir string) error {
	if _, err := os.Stat(filepath.Join(dir, "tiproxy.crt")); err == nil {
		return nil
	}

	ca, err := crypto.NewCA("tiproxy")
	if err != nil {
		return err
	}
	privKey, err := crypto.NewKeyPair(crypto.KeyTypeRSA, crypto.KeySchemeRSASSAPSSSHA256)
	if err != nil {
		return err
	}
	csr, err := privKey.CSR("tiproxy", "tiproxy", nil, nil)
	if err != nil {
		return err
	}
	cert, err := ca.Sign(csr)
	if err != nil {
		return err
	}
	if err := utils.SaveFileWithBackup(filepath.Join(dir, "tiproxy.key"), privKey.Pem(), ""); err != nil {
		return err
	}
	return utils.SaveFileWithBackup(filepath.Join(dir, "tiproxy.crt"), pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: cert,
	}), "")
}

// NewTiProxy create a TiProxy instance.
func NewTiProxy(shOpt SharedOptions, binPath string, dir, host, configPath string, id int, port int, pds []*PDInstance) *TiProxy {
	if port <= 0 {
		port = 6000
	}
	tiproxy := &TiProxy{
		instance: instance{
			BinPath:    binPath,
			ID:         id,
			Dir:        dir,
			Host:       host,
			Port:       utils.MustGetFreePort(host, port, shOpt.PortOffset),
			StatusPort: utils.MustGetFreePort(host, 3080, shOpt.PortOffset),
			ConfigPath: configPath,
		},
		pds: pds,
	}
	return tiproxy
}

// MetricAddr implements Instance interface.
func (c *TiProxy) MetricAddr() (r MetricAddr) {
	r.Targets = append(r.Targets, utils.JoinHostPort(c.Host, c.StatusPort))
	r.Labels = map[string]string{
		"__metrics_path__": "/api/metrics",
	}
	return
}

// Start implements Instance interface.
func (c *TiProxy) Start(ctx context.Context) error {
	endpoints := pdEndpoints(c.pds, false)

	configPath := filepath.Join(c.Dir, "config", "proxy.toml")
	dir := filepath.Dir(configPath)
	if err := utils.MkdirAll(dir, 0755); err != nil {
		return err
	}

	userConfig, err := unmarshalConfig(c.ConfigPath)
	if err != nil {
		return err
	}
	if userConfig == nil {
		userConfig = make(map[string]any)
	}

	cf, err := os.Create(configPath)
	if err != nil {
		return err
	}

	enc := toml.NewEncoder(cf)
	enc.Indent = ""
	if err := enc.Encode(spec.MergeConfig(userConfig, map[string]any{
		"proxy.pd-addrs":        strings.Join(endpoints, ","),
		"proxy.addr":            utils.JoinHostPort(c.Host, c.Port),
		"proxy.advertise-addr":  AdvertiseHost(c.Host),
		"api.addr":              utils.JoinHostPort(c.Host, c.StatusPort),
		"log.log-file.filename": c.LogFile(),
	})); err != nil {
		return err
	}

	args := []string{
		fmt.Sprintf("--config=%s", configPath),
	}

	c.Process = &process{cmd: PrepareCommand(ctx, c.BinPath, args, nil, c.Dir)}

	logIfErr(c.Process.SetOutputFile(c.LogFile()))
	return c.Process.Start()
}

// Addr return addresses that can be connected by MySQL clients.
func (c *TiProxy) Addr() string {
	return utils.JoinHostPort(AdvertiseHost(c.Host), c.Port)
}

// Component return component name.
func (c *TiProxy) Component() string {
	return "tiproxy"
}

// LogFile return the log file.
func (c *TiProxy) LogFile() string {
	return filepath.Join(c.Dir, "tiproxy.log")
}