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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
|
// Copyright 2023 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 spec
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/pingcap/tiup/pkg/cluster/ctxt"
"github.com/pingcap/tiup/pkg/cluster/template/scripts"
"github.com/pingcap/tiup/pkg/meta"
"github.com/pingcap/tiup/pkg/utils"
"github.com/prometheus/common/expfmt"
)
func proxyUptimeByHost(host string, port int, timeout time.Duration, tlsCfg *tls.Config) time.Duration {
if timeout < time.Second {
timeout = statusQueryTimeout
}
scheme := "http"
if tlsCfg != nil {
scheme = "https"
}
url := fmt.Sprintf("%s://%s/api/metrics", scheme, utils.JoinHostPort(host, port))
client := utils.NewHTTPClient(timeout, tlsCfg)
body, err := client.Get(context.TODO(), url)
if err != nil || body == nil {
return 0
}
var parser expfmt.TextParser
reader := bytes.NewReader(body)
mf, err := parser.TextToMetricFamilies(reader)
if err != nil {
return 0
}
now := time.Now()
for k, v := range mf {
if k == promMetricStartTimeSeconds {
ms := v.GetMetric()
if len(ms) >= 1 {
startTime := ms[0].Gauge.GetValue()
return now.Sub(time.Unix(int64(startTime), 0))
}
return 0
}
}
return 0
}
// TiProxySpec represents the TiProxy topology specification in topology.yaml
type TiProxySpec struct {
Host string `yaml:"host"`
ManageHost string `yaml:"manage_host,omitempty" validate:"manage_host:editable"`
SSHPort int `yaml:"ssh_port,omitempty" validate:"ssh_port:editable"`
Port int `yaml:"port" default:"6000"`
StatusPort int `yaml:"status_port" default:"3080"`
DeployDir string `yaml:"deploy_dir,omitempty"`
NumaNode string `yaml:"numa_node,omitempty" validate:"numa_node:editable"`
Config map[string]any `yaml:"config,omitempty" validate:"config:ignore"`
Arch string `yaml:"arch,omitempty"`
OS string `yaml:"os,omitempty"`
}
// Role returns the component role of the instance
func (s *TiProxySpec) Role() string {
return ComponentTiProxy
}
// SSH returns the host and SSH port of the instance
func (s *TiProxySpec) SSH() (string, int) {
return s.Host, s.SSHPort
}
// GetMainPort returns the main port of the instance
func (s *TiProxySpec) GetMainPort() int {
return s.Port
}
// GetManageHost returns the manage host of the instance
func (s *TiProxySpec) GetManageHost() string {
if s.ManageHost != "" {
return s.ManageHost
}
return s.Host
}
// IsImported returns if the node is imported from TiDB-Ansible
func (s *TiProxySpec) IsImported() bool {
return false
}
// IgnoreMonitorAgent returns if the node does not have monitor agents available
func (s *TiProxySpec) IgnoreMonitorAgent() bool {
return false
}
// TiProxyComponent represents TiProxy component.
type TiProxyComponent struct{ Topology *Specification }
// Name implements Component interface.
func (c *TiProxyComponent) Name() string {
return ComponentTiProxy
}
// Role implements Component interface.
func (c *TiProxyComponent) Role() string {
return ComponentTiProxy
}
// Source implements Component interface.
func (c *TiProxyComponent) Source() string {
return ComponentTiProxy
}
// CalculateVersion implements the Component interface
func (c *TiProxyComponent) CalculateVersion(clusterVersion string) string {
version := c.Topology.ComponentVersions.TiProxy
if version == "" {
// always not follow global version
// because tiproxy version is different from clusterVersion
// but "nightly" is effective
if clusterVersion == "nightly" {
version = clusterVersion
}
}
return version
}
// SetVersion implements Component interface.
func (c *TiProxyComponent) SetVersion(version string) {
c.Topology.ComponentVersions.TiProxy = version
}
// Instances implements Component interface.
func (c *TiProxyComponent) Instances() []Instance {
ins := make([]Instance, 0, len(c.Topology.TiProxyServers))
for _, s := range c.Topology.TiProxyServers {
instance := &TiProxyInstance{BaseInstance{
InstanceSpec: s,
Name: c.Name(),
Host: s.Host,
ManageHost: s.ManageHost,
ListenHost: c.Topology.BaseTopo().GlobalOptions.ListenHost,
Port: s.Port,
SSHP: s.SSHPort,
NumaNode: s.NumaNode,
NumaCores: "",
Ports: []int{
s.Port,
s.StatusPort,
},
Dirs: []string{
s.DeployDir,
},
StatusFn: func(_ context.Context, timeout time.Duration, tlsCfg *tls.Config, _ ...string) string {
return statusByHost(s.Host, s.StatusPort, "/api/debug/health", timeout, tlsCfg)
},
UptimeFn: func(_ context.Context, timeout time.Duration, tlsCfg *tls.Config) time.Duration {
return proxyUptimeByHost(s.Host, s.StatusPort, timeout, tlsCfg)
},
Component: c,
}, c.Topology}
ins = append(ins, instance)
}
return ins
}
// TiProxyInstance represent the TiProxy instance.
type TiProxyInstance struct {
BaseInstance
topo Topology
}
// ScaleConfig deploy temporary config on scaling
func (i *TiProxyInstance) ScaleConfig(
ctx context.Context,
e ctxt.Executor,
topo Topology,
clusterName,
clusterVersion,
user string,
paths meta.DirPaths,
) error {
s := i.topo
defer func() {
i.topo = s
}()
i.topo = mustBeClusterTopo(topo)
return i.InitConfig(ctx, e, clusterName, clusterVersion, user, paths)
}
func (i *TiProxyInstance) checkConfig(
cfg map[string]any,
paths meta.DirPaths,
) map[string]any {
topo := i.topo.(*Specification)
spec := i.InstanceSpec.(*TiProxySpec)
if cfg == nil {
cfg = make(map[string]any)
}
pds := []string{}
for _, pdspec := range topo.PDServers {
pds = append(pds, utils.JoinHostPort(pdspec.Host, pdspec.ClientPort))
}
cfg["proxy.pd-addrs"] = strings.Join(pds, ",")
cfg["proxy.addr"] = utils.JoinHostPort(i.GetListenHost(), i.GetPort())
cfg["proxy.advertise-addr"] = spec.Host
cfg["api.addr"] = utils.JoinHostPort(i.GetListenHost(), spec.StatusPort)
cfg["log.log-file.filename"] = filepath.Join(paths.Log, "tiproxy.log")
return cfg
}
// InitConfig implements Instance interface.
func (i *TiProxyInstance) InitConfig(
ctx context.Context,
e ctxt.Executor,
clusterName,
clusterVersion,
deployUser string,
paths meta.DirPaths,
) error {
topo := i.topo.(*Specification)
if err := i.BaseInstance.InitConfig(ctx, e, topo.GlobalOptions, deployUser, paths); err != nil {
return err
}
spec := i.InstanceSpec.(*TiProxySpec)
globalConfig := topo.ServerConfigs.TiProxy
instanceConfig := i.checkConfig(spec.Config, paths)
cfg := &scripts.TiProxyScript{
DeployDir: paths.Deploy,
NumaNode: spec.NumaNode,
}
fp := filepath.Join(paths.Cache, fmt.Sprintf("run_tiproxy_%s_%d.sh", i.GetHost(), i.GetPort()))
if err := cfg.ConfigToFile(fp); err != nil {
return err
}
dst := filepath.Join(paths.Deploy, "scripts", "run_tiproxy.sh")
if err := e.Transfer(ctx, fp, dst, false, 0, false); err != nil {
return err
}
if _, _, err := e.Execute(ctx, "chmod +x "+dst, false); err != nil {
return err
}
var err error
instanceConfig, err = i.setTLSConfig(ctx, topo.GlobalOptions.TLSEnabled, instanceConfig, paths)
if err != nil {
return err
}
return i.MergeServerConfig(ctx, e, globalConfig, instanceConfig, paths)
}
// setTLSConfig set TLS Config to support enable/disable TLS
func (i *TiProxyInstance) setTLSConfig(ctx context.Context, enableTLS bool, configs map[string]any, paths meta.DirPaths) (map[string]any, error) {
if configs == nil {
configs = make(map[string]any)
}
if enableTLS {
configs["security.cluster-tls.ca"] = fmt.Sprintf("%s/tls/%s", paths.Deploy, TLSCACert)
configs["security.cluster-tls.cert"] = fmt.Sprintf("%s/tls/%s.crt", paths.Deploy, i.Role())
configs["security.cluster-tls.key"] = fmt.Sprintf("%s/tls/%s.pem", paths.Deploy, i.Role())
configs["security.server-http-tls.ca"] = fmt.Sprintf("%s/tls/%s", paths.Deploy, TLSCACert)
configs["security.server-http-tls.cert"] = fmt.Sprintf("%s/tls/%s.crt", paths.Deploy, i.Role())
configs["security.server-http-tls.key"] = fmt.Sprintf("%s/tls/%s.pem", paths.Deploy, i.Role())
configs["security.server-http-tls.skip-ca"] = true
configs["security.sql-tls.ca"] = fmt.Sprintf("%s/tls/%s", paths.Deploy, TLSCACert)
configs["security.sql-tls.cert"] = fmt.Sprintf("%s/tls/%s.crt", paths.Deploy, i.Role())
configs["security.sql-tls.key"] = fmt.Sprintf("%s/tls/%s.pem", paths.Deploy, i.Role())
} else {
// drainer tls config list
tlsConfigs := []string{
"security.cluster-tls.ca",
"security.cluster-tls.cert",
"security.cluster-tls.key",
"security.server-tls.ca",
"security.server-tls.cert",
"security.server-tls.key",
"security.server-tls.skip-ca",
"security.server-http-tls.ca",
"security.server-http-tls.cert",
"security.server-http-tls.key",
"security.server-http-tls.skip-ca",
"security.sql-tls.ca",
"security.sql-tls.cert",
"security.sql-tls.key",
}
// delete TLS configs
for _, config := range tlsConfigs {
delete(configs, config)
}
}
return configs, nil
}
// GetAddr return the address of this TiProxy instance
func (i *TiProxyInstance) GetAddr() string {
return utils.JoinHostPort(i.GetHost(), i.GetPort())
}
var _ RollingUpdateInstance = &TiProxyInstance{}
// PreRestart implements RollingUpdateInstance interface.
func (i *TiProxyInstance) PreRestart(ctx context.Context, topo Topology, apiTimeoutSeconds int, tlsCfg *tls.Config, updcfg *UpdateConfig) error {
return nil
}
// PostRestart implements RollingUpdateInstance interface.
func (i *TiProxyInstance) PostRestart(ctx context.Context, topo Topology, tlsCfg *tls.Config, updcfg *UpdateConfig) error {
return nil
}
|