-
Notifications
You must be signed in to change notification settings - Fork 269
/
server_config.go
352 lines (312 loc) · 11 KB
/
server_config.go
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
346
347
348
349
350
351
352
// 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 config
import (
"encoding/json"
"fmt"
"math"
"net"
"regexp"
"strings"
"sync/atomic"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/log"
cerror "github.com/pingcap/tiflow/pkg/errors"
"github.com/pingcap/tiflow/pkg/security"
"go.uber.org/zap"
)
const (
// clusterIDMaxLen is the max length of cdc server cluster id
clusterIDMaxLen = 128
// DefaultSortDir is the default value of sort-dir, it will be a subordinate directory of data-dir.
DefaultSortDir = "/tmp/sorter"
// DefaultRedoDir is a subordinate directory path of data-dir.
DefaultRedoDir = "/tmp/redo"
// DebugConfigurationItem is the name of debug configurations
DebugConfigurationItem = "debug"
// DefaultChangefeedMemoryQuota is the default memory quota for each changefeed.
DefaultChangefeedMemoryQuota = 1024 * 1024 * 1024 // 1GB.
// DisableMemoryLimit is the default max memory percentage for TiCDC server.
// 0 means no memory limit.
DisableMemoryLimit = 0
)
var (
clusterIDRe = regexp.MustCompile(`^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$`)
// ReservedClusterIDs contains a list of reserved cluster id,
// these words are the part of old cdc etcd key prefix
// like: /tidb/cdc/owner
ReservedClusterIDs = []string{
"owner", "capture", "task",
"changefeed", "job", "meta",
}
)
func init() {
StoreGlobalServerConfig(GetDefaultServerConfig())
}
// SecurityConfig represents security config for server
type SecurityConfig = security.Credential
// LogFileConfig represents log file config for server
type LogFileConfig struct {
MaxSize int `toml:"max-size" json:"max-size"`
MaxDays int `toml:"max-days" json:"max-days"`
MaxBackups int `toml:"max-backups" json:"max-backups"`
}
// LogConfig represents log config for server
type LogConfig struct {
File *LogFileConfig `toml:"file" json:"file"`
InternalErrOutput string `toml:"error-output" json:"error-output"`
}
var defaultServerConfig = &ServerConfig{
Addr: "127.0.0.1:8300",
AdvertiseAddr: "",
LogFile: "",
LogLevel: "info",
Log: &LogConfig{
File: &LogFileConfig{
MaxSize: 300,
MaxDays: 0,
MaxBackups: 0,
},
InternalErrOutput: "stderr",
},
DataDir: "",
GcTTL: 24 * 60 * 60, // 24H
TZ: "System",
// The default election-timeout in PD is 3s and minimum session TTL is 5s,
// which is calculated by `math.Ceil(3 * election-timeout / 2)`, we choose
// default capture session ttl to 10s to increase robust to PD jitter,
// however it will decrease RTO when single TiCDC node error happens.
CaptureSessionTTL: 10,
OwnerFlushInterval: TomlDuration(50 * time.Millisecond),
ProcessorFlushInterval: TomlDuration(50 * time.Millisecond),
Sorter: &SorterConfig{
SortDir: DefaultSortDir,
CacheSizeInMB: 128, // By default use 128M memory as sorter cache.
MaxMemoryPercentage: 10, // Deprecated.
},
Security: &SecurityConfig{},
KVClient: &KVClientConfig{
WorkerConcurrent: 8,
WorkerPoolSize: 0, // 0 will use NumCPU() * 2
RegionScanLimit: 40,
// The default TiKV region election timeout is [10s, 20s],
// Use 1 minute to cover region leader missing.
RegionRetryDuration: TomlDuration(time.Minute),
},
Debug: &DebugConfig{
DB: &DBConfig{
Count: 8,
// Following configs are optimized for write/read throughput.
// Users should not change them.
Concurrency: 128,
MaxOpenFiles: 10000,
BlockSize: 65536,
WriterBufferSize: 8388608,
Compression: "snappy",
WriteL0PauseTrigger: math.MaxInt32,
CompactionL0Trigger: 160,
CompactionDeletionThreshold: 10485760,
CompactionPeriod: 1800,
IteratorMaxAliveDuration: 10000,
IteratorSlowReadDuration: 256,
},
Messages: defaultMessageConfig.Clone(),
Scheduler: NewDefaultSchedulerConfig(),
EnableKVConnectBackOff: false,
Puller: &PullerConfig{
EnableResolvedTsStuckDetection: false,
ResolvedTsStuckInterval: TomlDuration(5 * time.Minute),
},
},
ClusterID: "default",
GcTunerMemoryThreshold: DisableMemoryLimit,
}
// ServerConfig represents a config for server
type ServerConfig struct {
Addr string `toml:"addr" json:"addr"`
AdvertiseAddr string `toml:"advertise-addr" json:"advertise-addr"`
LogFile string `toml:"log-file" json:"log-file"`
LogLevel string `toml:"log-level" json:"log-level"`
Log *LogConfig `toml:"log" json:"log"`
DataDir string `toml:"data-dir" json:"data-dir"`
GcTTL int64 `toml:"gc-ttl" json:"gc-ttl"`
TZ string `toml:"tz" json:"tz"`
CaptureSessionTTL int `toml:"capture-session-ttl" json:"capture-session-ttl"`
OwnerFlushInterval TomlDuration `toml:"owner-flush-interval" json:"owner-flush-interval"`
ProcessorFlushInterval TomlDuration `toml:"processor-flush-interval" json:"processor-flush-interval"`
Sorter *SorterConfig `toml:"sorter" json:"sorter"`
Security *SecurityConfig `toml:"security" json:"security"`
// DEPRECATED: after using pull based sink, this config is useless.
// Because we do not control the memory usage by table anymore.
PerTableMemoryQuota uint64 `toml:"per-table-memory-quota" json:"per-table-memory-quota"`
KVClient *KVClientConfig `toml:"kv-client" json:"kv-client"`
Debug *DebugConfig `toml:"debug" json:"debug"`
ClusterID string `toml:"cluster-id" json:"cluster-id"`
// Deprecated: we don't use this field anymore.
MaxMemoryPercentage int `toml:"max-memory-percentage" json:"max-memory-percentage"`
GcTunerMemoryThreshold uint64 `toml:"gc-tuner-memory-threshold" json:"gc-tuner-memory-threshold"`
}
// Marshal returns the json marshal format of a ServerConfig
func (c *ServerConfig) Marshal() (string, error) {
cfg, err := json.Marshal(c)
if err != nil {
return "", cerror.WrapError(cerror.ErrEncodeFailed, errors.Annotatef(err, "Unmarshal data: %v", c))
}
return string(cfg), nil
}
// Unmarshal unmarshals into *ServerConfig from json marshal byte slice
func (c *ServerConfig) Unmarshal(data []byte) error {
err := json.Unmarshal(data, c)
if err != nil {
return cerror.WrapError(cerror.ErrDecodeFailed, err)
}
return nil
}
// String implements the Stringer interface
func (c *ServerConfig) String() string {
s, _ := c.Marshal()
return s
}
// Clone clones a replication
func (c *ServerConfig) Clone() *ServerConfig {
str, err := c.Marshal()
if err != nil {
log.Panic("failed to marshal replica config",
zap.Error(cerror.WrapError(cerror.ErrDecodeFailed, err)))
}
clone := new(ServerConfig)
err = clone.Unmarshal([]byte(str))
if err != nil {
log.Panic("failed to unmarshal replica config",
zap.Error(cerror.WrapError(cerror.ErrDecodeFailed, err)))
}
return clone
}
// ValidateAndAdjust validates and adjusts the server configuration
func (c *ServerConfig) ValidateAndAdjust() error {
if !isValidClusterID(c.ClusterID) {
return cerror.ErrInvalidServerOption.GenWithStack(fmt.Sprintf("bad cluster-id"+
"please match the pattern \"^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$\", and not the list of"+
" following reserved world: %s"+
"eg, \"simple-cluster-id\"", strings.Join(ReservedClusterIDs, ",")))
}
if c.Addr == "" {
return cerror.ErrInvalidServerOption.GenWithStack("empty address")
}
if c.AdvertiseAddr == "" {
c.AdvertiseAddr = c.Addr
}
// Advertise address must be specified.
if idx := strings.LastIndex(c.AdvertiseAddr, ":"); idx >= 0 {
ip := net.ParseIP(c.AdvertiseAddr[:idx])
// Skip nil as it could be a domain name.
if ip != nil && ip.IsUnspecified() {
return cerror.ErrInvalidServerOption.GenWithStack("advertise address must be specified as a valid IP")
}
} else {
return cerror.ErrInvalidServerOption.GenWithStack("advertise address or address does not contain a port")
}
if c.GcTTL == 0 {
return cerror.ErrInvalidServerOption.GenWithStack("empty GC TTL is not allowed")
}
// 5s is minimum lease ttl in etcd(PD)
if c.CaptureSessionTTL < 5 {
log.Warn("capture session ttl too small, set to default value 10s")
c.CaptureSessionTTL = 10
}
if c.Security != nil && c.Security.IsTLSEnabled() {
var err error
_, err = c.Security.ToTLSConfig()
if err != nil {
return errors.Annotate(err, "invalidate TLS config")
}
_, err = c.Security.ToGRPCDialOption()
if err != nil {
return errors.Annotate(err, "invalidate TLS config")
}
}
defaultCfg := GetDefaultServerConfig()
if c.Sorter == nil {
c.Sorter = defaultCfg.Sorter
}
c.Sorter.SortDir = DefaultSortDir
err := c.Sorter.ValidateAndAdjust()
if err != nil {
return err
}
if c.KVClient == nil {
c.KVClient = defaultCfg.KVClient
}
if err = c.KVClient.ValidateAndAdjust(); err != nil {
return errors.Trace(err)
}
if c.Debug == nil {
c.Debug = defaultCfg.Debug
}
if err = c.Debug.ValidateAndAdjust(); err != nil {
return errors.Trace(err)
}
return nil
}
// GetDefaultServerConfig returns the default server config
func GetDefaultServerConfig() *ServerConfig {
return defaultServerConfig.Clone()
}
var globalServerConfig atomic.Value
// GetGlobalServerConfig returns the global configuration for this server.
// It should store configuration from command line and configuration file.
// Other parts of the system can read the global configuration use this function.
func GetGlobalServerConfig() *ServerConfig {
return globalServerConfig.Load().(*ServerConfig)
}
// StoreGlobalServerConfig stores a new config to the globalServerConfig. It mostly uses in the test to avoid some data races.
func StoreGlobalServerConfig(config *ServerConfig) {
globalServerConfig.Store(config)
}
// TomlDuration is a duration with a custom json decoder and toml decoder
type TomlDuration time.Duration
// UnmarshalText is the toml decoder
func (d *TomlDuration) UnmarshalText(text []byte) error {
stdDuration, err := time.ParseDuration(string(text))
if err != nil {
return err
}
*d = TomlDuration(stdDuration)
return nil
}
// UnmarshalJSON is the json decoder
func (d *TomlDuration) UnmarshalJSON(b []byte) error {
var stdDuration time.Duration
if err := json.Unmarshal(b, &stdDuration); err != nil {
return err
}
*d = TomlDuration(stdDuration)
return nil
}
// isValidClusterID returns true if the cluster ID matches
// the pattern "^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$", length no more than `clusterIDMaxLen`,
// eg, "simple-cluster-id".
func isValidClusterID(clusterID string) bool {
valid := clusterID != "" && len(clusterID) <= clusterIDMaxLen &&
clusterIDRe.MatchString(clusterID)
if !valid {
return false
}
for _, reserved := range ReservedClusterIDs {
if reserved == clusterID {
return false
}
}
return true
}