diff --git a/server/server.go b/server/server.go index 74f09b2bdb020..daaa6ff3aa81b 100644 --- a/server/server.go +++ b/server/server.go @@ -59,6 +59,7 @@ import ( "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/sys/linux" + "github.com/pingcap/tidb/util/timeutil" "go.uber.org/zap" "google.golang.org/grpc" ) @@ -209,6 +210,7 @@ func NewServer(cfg *config.Config, driver IDriver) (*Server, error) { stopListenerCh: make(chan struct{}, 1), } s.loadTLSCertificates() + setSystemTimeZoneVariable() s.capability = defaultCapability if s.tlsConfig != nil { @@ -622,6 +624,18 @@ func (s *Server) kickIdleConnection() { } } +func setSystemTimeZoneVariable() { + tz, err := timeutil.GetSystemTZ() + if err != nil { + logutil.BgLogger().Error( + "Error getting SystemTZ, use default value instead", + zap.Error(err), + zap.String("default system_time_zone", variable.SysVars["system_time_zone"].Value)) + return + } + variable.SysVars["system_time_zone"].Value = tz +} + // Server error codes. const ( codeUnknownFieldType = 1 diff --git a/server/tidb_test.go b/server/tidb_test.go index 26c16c46a4d0c..4f787990754e8 100644 --- a/server/tidb_test.go +++ b/server/tidb_test.go @@ -37,6 +37,7 @@ import ( "github.com/pingcap/tidb/metrics" "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/store/mockstore" + "github.com/pingcap/tidb/util/testkit" ) type TidbTestSuite struct { @@ -293,6 +294,19 @@ func registerTLSConfig(configName string, caCertPath string, clientCertPath stri return nil } +func (ts *TidbTestSuite) TestSystemTimeZone(c *C) { + tk := testkit.NewTestKit(c, ts.store) + cfg := config.NewConfig() + cfg.Port = 4002 + cfg.Status.ReportStatus = false + server, err := NewServer(cfg, ts.tidbdrv) + c.Assert(err, IsNil) + defer server.Close() + + tz1 := tk.MustQuery("select variable_value from mysql.tidb where variable_name = 'system_tz'").Rows() + tk.MustQuery("select @@system_time_zone").Check(tz1) +} + func (ts *TidbTestSuite) TestTLS(c *C) { // Generate valid TLS certificates. caCert, caKey, err := generateCert(0, "TiDB CA", nil, nil, "/tmp/ca-key.pem", "/tmp/ca-cert.pem") diff --git a/util/timeutil/time.go b/util/timeutil/time.go index 6b00468c625a4..d2e3c134a1208 100644 --- a/util/timeutil/time.go +++ b/util/timeutil/time.go @@ -117,6 +117,14 @@ func SetSystemTZ(name string) { }) } +// GetSystemTZ gets the value of systemTZ, an error is returned if systemTZ is not properly set. +func GetSystemTZ() (string, error) { + if systemTZ == "System" || systemTZ == "" { + return "", fmt.Errorf("variable `systemTZ` is not properly set") + } + return systemTZ, nil +} + // getLoc first trying to load location from a cache map. If nothing found in such map, then call // `time.LoadLocation` to get a timezone location. After trying both way, an error will be returned // if valid Location is not found.