github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/dbs/cmd/config/config_test.go (about)

     1  // Copyright 2020 WHTCORPS INC, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package config
    15  
    16  import (
    17  	"encoding/json"
    18  	"os"
    19  	"os/user"
    20  	"path/filepath"
    21  	"runtime"
    22  	"testing"
    23  
    24  	"github.com/BurntSushi/toml"
    25  	tracing "github.com/uber/jaeger-client-go/config"
    26  	"github.com/whtcorpsinc/BerolinaSQL/allegrosql"
    27  	. "github.com/whtcorpsinc/check"
    28  	zaplog "github.com/whtcorpsinc/log"
    29  	"github.com/whtcorpsinc/milevadb/soliton/logutil"
    30  )
    31  
    32  var _ = SerialSuites(&testConfigSuite{})
    33  
    34  type testConfigSuite struct{}
    35  
    36  func TestT(t *testing.T) {
    37  	CustomVerboseFlag = true
    38  	TestingT(t)
    39  }
    40  
    41  func (s *testConfigSuite) TestNullableBoolUnmarshal(c *C) {
    42  	var nb = nullableBool{false, false}
    43  	data, err := json.Marshal(nb)
    44  	c.Assert(err, IsNil)
    45  	err = json.Unmarshal(data, &nb)
    46  	c.Assert(err, IsNil)
    47  	c.Assert(nb, Equals, nbUnset)
    48  
    49  	nb = nullableBool{true, false}
    50  	data, err = json.Marshal(nb)
    51  	c.Assert(err, IsNil)
    52  	err = json.Unmarshal(data, &nb)
    53  	c.Assert(err, IsNil)
    54  	c.Assert(nb, Equals, nbFalse)
    55  
    56  	nb = nullableBool{true, true}
    57  	data, err = json.Marshal(nb)
    58  	c.Assert(err, IsNil)
    59  	err = json.Unmarshal(data, &nb)
    60  	c.Assert(err, IsNil)
    61  	c.Assert(nb, Equals, nbTrue)
    62  
    63  	// Test for UnmarshalText
    64  	var log Log
    65  	_, err = toml.Decode("enable-error-stack = true", &log)
    66  	c.Assert(err, IsNil)
    67  	c.Assert(log.EnableErrorStack, Equals, nbTrue)
    68  
    69  	_, err = toml.Decode("enable-error-stack = \"\"", &log)
    70  	c.Assert(err, IsNil)
    71  	c.Assert(log.EnableErrorStack, Equals, nbUnset)
    72  
    73  	_, err = toml.Decode("enable-error-stack = 1", &log)
    74  	c.Assert(err, ErrorMatches, "Invalid value for bool type: 1")
    75  	c.Assert(log.EnableErrorStack, Equals, nbUnset)
    76  
    77  	// Test for UnmarshalJSON
    78  	err = json.Unmarshal([]byte("{\"enable-timestamp\":false}"), &log)
    79  	c.Assert(err, IsNil)
    80  	c.Assert(log.EnableTimestamp, Equals, nbFalse)
    81  
    82  	err = json.Unmarshal([]byte("{\"disable-timestamp\":null}"), &log)
    83  	c.Assert(err, IsNil)
    84  	c.Assert(log.DisableTimestamp, Equals, nbUnset)
    85  }
    86  
    87  func (s *testConfigSuite) TestLogConfig(c *C) {
    88  	var conf Config
    89  	configFile := "log_config.toml"
    90  	_, localFile, _, _ := runtime.Caller(0)
    91  	configFile = filepath.Join(filepath.Dir(localFile), configFile)
    92  
    93  	f, err := os.Create(configFile)
    94  	c.Assert(err, IsNil)
    95  	defer func() {
    96  		c.Assert(f.Close(), IsNil)
    97  		c.Assert(os.Remove(configFile), IsNil)
    98  	}()
    99  
   100  	var testLoad = func(confStr string, expectedEnableErrorStack, expectedDisableErrorStack, expectedEnableTimestamp, expectedDisableTimestamp nullableBool, resultedDisableTimestamp, resultedDisableErrorVerbose bool, valid Checker) {
   101  		conf = defaultConf
   102  		_, err = f.WriteString(confStr)
   103  		c.Assert(err, IsNil)
   104  		c.Assert(conf.Load(configFile), IsNil)
   105  		c.Assert(conf.Valid(), valid)
   106  		c.Assert(conf.Log.EnableErrorStack, Equals, expectedEnableErrorStack)
   107  		c.Assert(conf.Log.DisableErrorStack, Equals, expectedDisableErrorStack)
   108  		c.Assert(conf.Log.EnableTimestamp, Equals, expectedEnableTimestamp)
   109  		c.Assert(conf.Log.DisableTimestamp, Equals, expectedDisableTimestamp)
   110  		c.Assert(conf.Log.ToLogConfig(), DeepEquals, logutil.NewLogConfig("info", "text", "milevadb-slow.log", conf.Log.File, resultedDisableTimestamp, func(config *zaplog.Config) { config.DisableErrorVerbose = resultedDisableErrorVerbose }))
   111  		f.Truncate(0)
   112  		f.Seek(0, 0)
   113  	}
   114  
   115  	testLoad(`
   116  [Log]
   117  `, nbUnset, nbUnset, nbUnset, nbUnset, false, true, IsNil)
   118  
   119  	testLoad(`
   120  [Log]
   121  enable-timestamp = false
   122  `, nbUnset, nbUnset, nbFalse, nbUnset, true, true, IsNil)
   123  
   124  	testLoad(`
   125  [Log]
   126  enable-timestamp = true
   127  disable-timestamp = false
   128  `, nbUnset, nbUnset, nbTrue, nbFalse, false, true, IsNil)
   129  
   130  	testLoad(`
   131  [Log]
   132  enable-timestamp = false
   133  disable-timestamp = true
   134  `, nbUnset, nbUnset, nbFalse, nbTrue, true, true, IsNil)
   135  
   136  	testLoad(`
   137  [Log]
   138  enable-timestamp = true
   139  disable-timestamp = true
   140  `, nbUnset, nbUnset, nbTrue, nbUnset, false, true, IsNil)
   141  
   142  	testLoad(`
   143  [Log]
   144  enable-error-stack = false
   145  disable-error-stack = false
   146  `, nbFalse, nbUnset, nbUnset, nbUnset, false, true, IsNil)
   147  
   148  }
   149  
   150  func (s *testConfigSuite) TestConfig(c *C) {
   151  	conf := new(Config)
   152  	conf.TempStoragePath = tempStorageDirName
   153  	conf.Binlog.Enable = true
   154  	conf.Binlog.IgnoreError = true
   155  	conf.Binlog.Strategy = "hash"
   156  	conf.Performance.TxnTotalSizeLimit = 1000
   157  	conf.EinsteinDBClient.CommitTimeout = "10s"
   158  	conf.EinsteinDBClient.RegionCacheTTL = 600
   159  	conf.Log.EnableSlowLog = logutil.DefaultMilevaDBEnableSlowLog
   160  	configFile := "config.toml"
   161  	_, localFile, _, _ := runtime.Caller(0)
   162  	configFile = filepath.Join(filepath.Dir(localFile), configFile)
   163  
   164  	f, err := os.Create(configFile)
   165  	c.Assert(err, IsNil)
   166  
   167  	// Make sure the server refuses to start if there's an unrecognized configuration option
   168  	_, err = f.WriteString(`
   169  unrecognized-option-test = true
   170  `)
   171  	c.Assert(err, IsNil)
   172  	c.Assert(f.Sync(), IsNil)
   173  
   174  	c.Assert(conf.Load(configFile), ErrorMatches, "(?:.|\n)*invalid configuration option(?:.|\n)*")
   175  	c.Assert(conf.MaxServerConnections, Equals, uint32(0))
   176  
   177  	f.Truncate(0)
   178  	f.Seek(0, 0)
   179  
   180  	_, err = f.WriteString(`
   181  token-limit = 0
   182  enable-causet-dagger = true
   183  alter-primary-key = true
   184  delay-clean-causet-dagger = 5
   185  split-region-max-num=10000
   186  enable-batch-dml = true
   187  server-version = "test_version"
   188  repair-mode = true
   189  max-server-connections = 200
   190  mem-quota-query = 10000
   191  nested-loop-join-cache-capacity = 100
   192  max-index-length = 3080
   193  skip-register-to-dashboard = true
   194  deprecate-integer-display-length = true
   195  [performance]
   196  txn-total-size-limit=2000
   197  [einsteindb-client]
   198  commit-timeout="41s"
   199  enable-async-commit=true
   200  async-commit-keys-limit=123
   201  max-batch-size=128
   202  region-cache-ttl=6000
   203  causetstore-limit=0
   204  ttl-refreshed-txn-size=8192
   205  [stmt-summary]
   206  enable=false
   207  enable-internal-query=true
   208  max-stmt-count=1000
   209  max-allegrosql-length=1024
   210  refresh-interval=100
   211  history-size=100
   212  [experimental]
   213  [isolation-read]
   214  engines = ["tiflash"]
   215  [labels]
   216  foo= "bar"
   217  group= "abc"
   218  [security]
   219  spilled-file-encryption-method = "plaintext"
   220  `)
   221  
   222  	c.Assert(err, IsNil)
   223  	c.Assert(f.Sync(), IsNil)
   224  
   225  	c.Assert(conf.Load(configFile), IsNil)
   226  
   227  	c.Assert(conf.ServerVersion, Equals, "test_version")
   228  	c.Assert(allegrosql.ServerVersion, Equals, conf.ServerVersion)
   229  	// Test that the original value will not be clear by load the config file that does not contain the option.
   230  	c.Assert(conf.Binlog.Enable, Equals, true)
   231  	c.Assert(conf.Binlog.Strategy, Equals, "hash")
   232  
   233  	// Test that the value will be overwritten by the config file.
   234  	c.Assert(conf.Performance.TxnTotalSizeLimit, Equals, uint64(2000))
   235  	c.Assert(conf.AlterPrimaryKey, Equals, true)
   236  
   237  	c.Assert(conf.EinsteinDBClient.CommitTimeout, Equals, "41s")
   238  	c.Assert(conf.EinsteinDBClient.EnableAsyncCommit, Equals, true)
   239  	c.Assert(conf.EinsteinDBClient.AsyncCommitKeysLimit, Equals, uint(123))
   240  	c.Assert(conf.EinsteinDBClient.MaxBatchSize, Equals, uint(128))
   241  	c.Assert(conf.EinsteinDBClient.RegionCacheTTL, Equals, uint(6000))
   242  	c.Assert(conf.EinsteinDBClient.StoreLimit, Equals, int64(0))
   243  	c.Assert(conf.EinsteinDBClient.TTLRefreshedTxnSize, Equals, int64(8192))
   244  	c.Assert(conf.TokenLimit, Equals, uint(1000))
   245  	c.Assert(conf.EnableTableLock, IsTrue)
   246  	c.Assert(conf.DelayCleanTableLock, Equals, uint64(5))
   247  	c.Assert(conf.SplitRegionMaxNum, Equals, uint64(10000))
   248  	c.Assert(conf.StmtSummary.Enable, Equals, false)
   249  	c.Assert(conf.StmtSummary.EnableInternalQuery, Equals, true)
   250  	c.Assert(conf.StmtSummary.MaxStmtCount, Equals, uint(1000))
   251  	c.Assert(conf.StmtSummary.MaxALLEGROSQLLength, Equals, uint(1024))
   252  	c.Assert(conf.StmtSummary.RefreshInterval, Equals, 100)
   253  	c.Assert(conf.StmtSummary.HistorySize, Equals, 100)
   254  	c.Assert(conf.EnableBatchDML, Equals, true)
   255  	c.Assert(conf.RepairMode, Equals, true)
   256  	c.Assert(conf.MaxServerConnections, Equals, uint32(200))
   257  	c.Assert(conf.MemQuotaQuery, Equals, int64(10000))
   258  	c.Assert(conf.NestedLoopJoinCacheCapacity, Equals, int64(100))
   259  	c.Assert(conf.IsolationRead.Engines, DeepEquals, []string{"tiflash"})
   260  	c.Assert(conf.MaxIndexLength, Equals, 3080)
   261  	c.Assert(conf.SkipRegisterToDashboard, Equals, true)
   262  	c.Assert(len(conf.Labels), Equals, 2)
   263  	c.Assert(conf.Labels["foo"], Equals, "bar")
   264  	c.Assert(conf.Labels["group"], Equals, "abc")
   265  	c.Assert(conf.Security.SpilledFileEncryptionMethod, Equals, SpilledFileEncryptionMethodPlaintext)
   266  	c.Assert(conf.DeprecateIntegerDisplayWidth, Equals, true)
   267  
   268  	_, err = f.WriteString(`
   269  [log.file]
   270  log-rotate = true`)
   271  	c.Assert(err, IsNil)
   272  	err = conf.Load(configFile)
   273  	tmp := err.(*ErrConfigValidationFailed)
   274  	c.Assert(isAllDeprecatedConfigItems(tmp.UndecodedItems), IsTrue)
   275  
   276  	// Test telemetry config default value and whether it will be overwritten.
   277  	conf = NewConfig()
   278  	f.Truncate(0)
   279  	f.Seek(0, 0)
   280  	c.Assert(f.Sync(), IsNil)
   281  	c.Assert(conf.Load(configFile), IsNil)
   282  	c.Assert(conf.EnableTelemetry, Equals, true)
   283  
   284  	_, err = f.WriteString(`
   285  enable-causet-dagger = true
   286  `)
   287  	c.Assert(err, IsNil)
   288  	c.Assert(f.Sync(), IsNil)
   289  	c.Assert(conf.Load(configFile), IsNil)
   290  	c.Assert(conf.EnableTelemetry, Equals, true)
   291  
   292  	_, err = f.WriteString(`
   293  enable-telemetry = false
   294  `)
   295  	c.Assert(err, IsNil)
   296  	c.Assert(f.Sync(), IsNil)
   297  	c.Assert(conf.Load(configFile), IsNil)
   298  	c.Assert(conf.EnableTelemetry, Equals, false)
   299  
   300  	_, err = f.WriteString(`
   301  [security]
   302  spilled-file-encryption-method = "aes128-ctr"
   303  `)
   304  	c.Assert(err, IsNil)
   305  	c.Assert(f.Sync(), IsNil)
   306  	c.Assert(conf.Load(configFile), IsNil)
   307  	c.Assert(conf.Security.SpilledFileEncryptionMethod, Equals, SpilledFileEncryptionMethodAES128CTR)
   308  
   309  	c.Assert(f.Close(), IsNil)
   310  	c.Assert(os.Remove(configFile), IsNil)
   311  
   312  	configFile = filepath.Join(filepath.Dir(localFile), "config.toml.example")
   313  	c.Assert(conf.Load(configFile), IsNil)
   314  
   315  	// Make sure the example config is the same as default config.
   316  	c.Assert(conf, DeepEquals, GetGlobalConfig())
   317  
   318  	// Test for log config.
   319  	c.Assert(conf.Log.ToLogConfig(), DeepEquals, logutil.NewLogConfig("info", "text", "milevadb-slow.log", conf.Log.File, false, func(config *zaplog.Config) { config.DisableErrorVerbose = conf.Log.getDisableErrorStack() }))
   320  
   321  	// Test for tracing config.
   322  	tracingConf := &tracing.Configuration{
   323  		Disabled: true,
   324  		Reporter: &tracing.ReporterConfig{},
   325  		Sampler:  &tracing.SamplerConfig{Type: "const", Param: 1.0},
   326  	}
   327  	c.Assert(tracingConf, DeepEquals, conf.OpenTracing.ToTracingConfig())
   328  
   329  	// Test for TLS config.
   330  	certFile := "cert.pem"
   331  	certFile = filepath.Join(filepath.Dir(localFile), certFile)
   332  	f, err = os.Create(certFile)
   333  	c.Assert(err, IsNil)
   334  	_, err = f.WriteString(`-----BEGIN CERTIFICATE-----
   335  MIIC+jCCAeKgAwIBAgIRALsvlisKJzXtiwKcv7toreswDQYJKoZIhvcNAQELBQAw
   336  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xOTAzMTMwNzExNDhaFw0yMDAzMTIwNzEx
   337  NDhaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
   338  ggEKAoIBAQDECyY5cZ4SccQdk4XCgENwOLsE92uZvutBcYHk8ndIpxuxQnmS/2af
   339  JxWlduKgauuLlwRYrzwvmUQumzB0LIJIwZN37KMeepTv+cf1Iv0U1Tw2PyXa7jD1
   340  VxccI7lHxqObYrnLdZ1AOG2SyWoJp/g6jZqbdGnYAbBxbZXYv9FyA6h0FksDysEP
   341  62zu5YwtRcmhob7L5Wezq0/eV/2U1WdbGGWMCUs2LKQav4TP7Kaopk+MAl9UpSoc
   342  arl+NGxs39TsvrxQvT7k/W6g7mo0rOc5PEc6Zho2+E8JjnEYCdGKmMW/Bea6V1yc
   343  ShMe79lwN7ISCw3e7GZhZGM2XFTjvhH/AgMBAAGjSzBJMA4GA1UdDwEB/wQEAwIF
   344  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBQGA1UdEQQNMAuC
   345  CWxvY2FsaG9zdDANBgkqhkiG9w0BAQsFAAOCAQEAK+pS76DxAbQBdbpyqt0Xi1QY
   346  SnWxFEFepP3pHC28oy8fzHiys9fwMvJwgMgLcwyB9GUhMZ/xsO2ehutWbzYCCRmV
   347  4einEx9Ipr26i2txzZPphqXNkV+ZhPeQK54fWrzAkRq4qKNyoYfvhldZ+uTuKNiS
   348  If0KbvbS6qDfimA+m0m6n5yDzc5tPl+kgKyeivSyqeG7T9m40gvCLAMgI7iTFhIZ
   349  BvUPi88z3wGa8rmhn9dOvkwauLFU5i5dqoz6m9HXmaEKzAAigGzgU8vFIDelt/Dxxgu
   350  c933WW1E0hCtvuGxWFIFtoJMQoyH0Pl4ACmY/6CokCCZKDInrFIDelhhf3MGRjkkw==
   351  -----END CERTIFICATE-----
   352  `)
   353  	c.Assert(err, IsNil)
   354  	c.Assert(f.Close(), IsNil)
   355  
   356  	keyFile := "key.pem"
   357  	keyFile = filepath.Join(filepath.Dir(localFile), keyFile)
   358  	f, err = os.Create(keyFile)
   359  	c.Assert(err, IsNil)
   360  	_, err = f.WriteString(`-----BEGIN RSA PRIVATE KEY-----
   361  MIIEowIBAAKCAQEAxAsmOXGeEnHEHZOFwoBDcDi7BFIDelrmb7rQXGB5PJ3SKcbsUJ5
   362  ekv9mnycVpXbioGrri5cEWK88L5lELpswdCyCSMGTd+yjHnqU7/nH9SL9FNU8Nj8l
   363  2u4w9VcXHCO5R8ajm2K5y3WdQDhtkslqCaf4Oo2am3Rp2AGwcW2V2L/RcgOodBZL
   364  A8rBD+ts7uWMLUXJoaG+y+Vns6tP3lf9lNVnWxhljAlLNiykGr+Ez+ymqKZPjAJf
   365  VKUqHGq5fjRsbN/U7L68UL0+5P1uoO5qNKznOTxHOmYaNvhPCY5xGAnRipjFvwXm
   366  uldcnEoTHu/ZcDeyEgsN3uxmYWRjNlxU474R/wIDAQABAoIBAGyZAIOxvK7a9pir
   367  r90e0DzKME9//8sbR5bpGduJtSo558051b7oXCCttgAC62eR0wlwjqfR6rUzYeGv
   368  dhfk0AcdtGMqYvHvVbHZ3DqfNzLjLIegU4gDintd0x9zap+oGdlpxyI99O4uVASM
   369  LoFK2ucUqiCTTE6sIOG0ot1+5LcS9xlygmmBfl8Q+6dG1D+vtPlU4J1kQ1MZV/JI
   370  01Mbea4iiUKD9qrbxfsMiu52u/J3MMoWJHsvAA/LpOp2Ua6pUECluZECslxYSnJJ
   371  IyjeGYxAIfXj81bqBk3RpemlX7YAxMbn6noZPQ6KUzS4IT2clrG10boCBdUNK1pN
   372  WjVOEoECgYEA0/aP1wvrC3sZtHmURHv1El0vmaZocmH3sdwUfrW5cMqqhOosax6d
   373  5iKAJQ1cAL6ZivIB4WJ3X8mlfMOaHPOQxqdudPui0sMHQehT2NBl/gwX9wXMwxXl
   374  t+ebqK5DSSbVuJQS45sSdYPQvrMVDB/owHHjfdeOk1EwmqxHv1r338UCgYEA7MXk
   375  IIF+LETxkw4QqbEPzwJ8kVRjkU3jmlEClOatTe+RQJxanErgMiGi9NZMM+Vm5GjC
   376  5kzAuNgMDuD/NAWyzPzWd+mbeG/2IHYf44OiK1TmnFHkTc0JW7s4tUQgDMQccheR
   377  EgA3UDGU9aevUoUDUhpeXxBdtnf66qw0e1cSovMCgYBLJdg7UsNjT6J+ZLhXS2dI
   378  unb8z42qN+d8TF2LytvTDFdGRku3MqSiicrK2CCtNuXy5/gYszNFZ5VfVW3XI9dJ
   379  RuUXXnuMo454JGlNrhzq49i/QHQnGiVWfSunsxix363YAc9smHcD6NbiNVWZ9dos
   380  GHSiEgE/Y4KK49eQFS1aTQKBgQC+xzznTC+j7/FOcjjO4hJA1FoWp46Kl93ai4eu
   381  /qeJcozxKIqCAHrhKeUprjo8Xo0nYZoZAqMOzVX57yTyf9zv+pG8kQhqZJxGz6cm
   382  JPxYOdKPBhUU8y6lMReiRsAkSSg6be7AOFhZT3oc7f4AWZixYPnFU2SFIDel+GnkRXA
   383  hApKLQKBgHUG+SjrxQjiFipE52YNGFLzbMR6Uga4baACW05uGPpao/+MkCGRAidL
   384  d/8eU66iPNt/23iVAbqkF8mRpCxC0+O5HRqTEzgrlWKabXfmhYqIVjq+tkonJ0NU
   385  xkNuJ2BlEGkwWLiRbKy1lNBBFUXKuhh3L/EIY10WTnr3TQzeL6H1
   386  -----END RSA PRIVATE KEY-----
   387  `)
   388  	c.Assert(err, IsNil)
   389  	c.Assert(f.Close(), IsNil)
   390  
   391  	conf.Security.ClusterSSLCA = certFile
   392  	conf.Security.ClusterSSLCert = certFile
   393  	conf.Security.ClusterSSLKey = keyFile
   394  	tlsConfig, err := conf.Security.ToTLSConfig()
   395  	c.Assert(err, IsNil)
   396  	c.Assert(tlsConfig, NotNil)
   397  
   398  	// Note that on windows, we can't Remove a file if the file is not closed.
   399  	// The behavior is different on linux, we can always Remove a file even
   400  	// if it's open. The OS maintains a reference count for open/close, the file
   401  	// is recycled when the reference count drops to 0.
   402  	c.Assert(os.Remove(certFile), IsNil)
   403  	c.Assert(os.Remove(keyFile), IsNil)
   404  }
   405  
   406  func (s *testConfigSuite) TestOOMCausetActionValid(c *C) {
   407  	c1 := NewConfig()
   408  	tests := []struct {
   409  		oomCausetAction string
   410  		valid           bool
   411  	}{
   412  		{"log", true},
   413  		{"Log", true},
   414  		{"Cancel", true},
   415  		{"cANceL", true},
   416  		{"quit", false},
   417  	}
   418  	for _, tt := range tests {
   419  		c1.OOMCausetAction = tt.oomCausetAction
   420  		c.Assert(c1.Valid() == nil, Equals, tt.valid)
   421  	}
   422  }
   423  
   424  func (s *testConfigSuite) TestTxnTotalSizeLimitValid(c *C) {
   425  	conf := NewConfig()
   426  	tests := []struct {
   427  		limit uint64
   428  		valid bool
   429  	}{
   430  		{4 << 10, true},
   431  		{10 << 30, true},
   432  		{10<<30 + 1, false},
   433  	}
   434  
   435  	for _, tt := range tests {
   436  		conf.Performance.TxnTotalSizeLimit = tt.limit
   437  		c.Assert(conf.Valid() == nil, Equals, tt.valid)
   438  	}
   439  }
   440  
   441  func (s *testConfigSuite) TestPrepareCausetCacheValid(c *C) {
   442  	conf := NewConfig()
   443  	tests := map[PreparedCausetCache]bool{
   444  		{Enabled: true, Capacity: 0}:                        false,
   445  		{Enabled: true, Capacity: 2}:                        true,
   446  		{Enabled: true, MemoryGuardRatio: -0.1}:             false,
   447  		{Enabled: true, MemoryGuardRatio: 2.2}:              false,
   448  		{Enabled: true, Capacity: 2, MemoryGuardRatio: 0.5}: true,
   449  	}
   450  	for testCase, res := range tests {
   451  		conf.PreparedCausetCache = testCase
   452  		c.Assert(conf.Valid() == nil, Equals, res)
   453  	}
   454  }
   455  
   456  func (s *testConfigSuite) TestMaxIndexLength(c *C) {
   457  	conf := NewConfig()
   458  	checkValid := func(indexLen int, shouldBeValid bool) {
   459  		conf.MaxIndexLength = indexLen
   460  		c.Assert(conf.Valid() == nil, Equals, shouldBeValid)
   461  	}
   462  	checkValid(DefMaxIndexLength, true)
   463  	checkValid(DefMaxIndexLength-1, false)
   464  	checkValid(DefMaxOfMaxIndexLength, true)
   465  	checkValid(DefMaxOfMaxIndexLength+1, false)
   466  }
   467  
   468  func (s *testConfigSuite) TestParsePath(c *C) {
   469  	etcdAddrs, disableGC, err := ParsePath("einsteindb://node1:2379,node2:2379")
   470  	c.Assert(err, IsNil)
   471  	c.Assert(etcdAddrs, DeepEquals, []string{"node1:2379", "node2:2379"})
   472  	c.Assert(disableGC, IsFalse)
   473  
   474  	_, _, err = ParsePath("einsteindb://node1:2379")
   475  	c.Assert(err, IsNil)
   476  	_, disableGC, err = ParsePath("einsteindb://node1:2379?disableGC=true")
   477  	c.Assert(err, IsNil)
   478  	c.Assert(disableGC, IsTrue)
   479  }
   480  
   481  func (s *testConfigSuite) TestEncodeDefTempStorageDir(c *C) {
   482  	tests := []struct {
   483  		host       string
   484  		statusHost string
   485  		port       uint
   486  		statusPort uint
   487  		expect     string
   488  	}{
   489  		{"0.0.0.0", "0.0.0.0", 4000, 10080, "MC4wLjAuMDo0MDAwLzAuMC4wLjA6MTAwODA="},
   490  		{"127.0.0.1", "127.16.5.1", 4000, 10080, "MTI3LjAuMC4xOjQwMDAvMTI3LjE2LjUuMToxMDA4MA=="},
   491  		{"127.0.0.1", "127.16.5.1", 4000, 15532, "MTI3LjAuMC4xOjQwMDAvMTI3LjE2LjUuMToxNTUzMg=="},
   492  	}
   493  
   494  	var osUID string
   495  	currentUser, err := user.Current()
   496  	if err != nil {
   497  		osUID = ""
   498  	} else {
   499  		osUID = currentUser.Uid
   500  	}
   501  
   502  	dirPrefix := filepath.Join(os.TemFIDelir(), osUID+"_milevadb")
   503  	for _, test := range tests {
   504  		tempStorageDir := encodeDefTempStorageDir(os.TemFIDelir(), test.host, test.statusHost, test.port, test.statusPort)
   505  		c.Assert(tempStorageDir, Equals, filepath.Join(dirPrefix, test.expect, "tmp-storage"))
   506  	}
   507  }
   508  
   509  func (s *testConfigSuite) TestModifyThroughLDFlags(c *C) {
   510  	tests := []struct {
   511  		Edition               string
   512  		CheckBeforeDropLDFlag string
   513  		EnableTelemetry       bool
   514  		CheckTableBeforeDrop  bool
   515  	}{
   516  		{"Community", "None", true, false},
   517  		{"Community", "1", true, true},
   518  		{"Enterprise", "None", false, false},
   519  		{"Enterprise", "1", false, true},
   520  	}
   521  
   522  	originalEnableTelemetry := defaultConf.EnableTelemetry
   523  	originalCheckTableBeforeDrop := CheckTableBeforeDrop
   524  	originalGlobalConfig := GetGlobalConfig()
   525  
   526  	for _, test := range tests {
   527  		defaultConf.EnableTelemetry = true
   528  		CheckTableBeforeDrop = false
   529  
   530  		initByLDFlags(test.Edition, test.CheckBeforeDropLDFlag)
   531  
   532  		conf := GetGlobalConfig()
   533  		c.Assert(conf.EnableTelemetry, Equals, test.EnableTelemetry)
   534  		c.Assert(defaultConf.EnableTelemetry, Equals, test.EnableTelemetry)
   535  		c.Assert(CheckTableBeforeDrop, Equals, test.CheckTableBeforeDrop)
   536  	}
   537  
   538  	defaultConf.EnableTelemetry = originalEnableTelemetry
   539  	CheckTableBeforeDrop = originalCheckTableBeforeDrop
   540  	StoreGlobalConfig(originalGlobalConfig)
   541  }
   542  
   543  func (s *testConfigSuite) TestSecurityValid(c *C) {
   544  	c1 := NewConfig()
   545  	tests := []struct {
   546  		spilledFileEncryptionMethod string
   547  		valid                       bool
   548  	}{
   549  		{"", false},
   550  		{"Plaintext", true},
   551  		{"plaintext123", false},
   552  		{"aes256-ctr", false},
   553  		{"aes128-ctr", true},
   554  	}
   555  	for _, tt := range tests {
   556  		c1.Security.SpilledFileEncryptionMethod = tt.spilledFileEncryptionMethod
   557  		c.Assert(c1.Valid() == nil, Equals, tt.valid)
   558  	}
   559  }