github.com/matrixorigin/matrixone@v1.2.0/pkg/cnservice/types.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cnservice
    16  
    17  import (
    18  	"context"
    19  	"runtime"
    20  	"strings"
    21  	"sync"
    22  	"sync/atomic"
    23  	"time"
    24  
    25  	"github.com/matrixorigin/matrixone/pkg/bootstrap"
    26  	"github.com/matrixorigin/matrixone/pkg/clusterservice"
    27  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    28  	"github.com/matrixorigin/matrixone/pkg/common/morpc"
    29  	moruntime "github.com/matrixorigin/matrixone/pkg/common/runtime"
    30  	"github.com/matrixorigin/matrixone/pkg/common/stopper"
    31  	"github.com/matrixorigin/matrixone/pkg/config"
    32  	"github.com/matrixorigin/matrixone/pkg/defines"
    33  	"github.com/matrixorigin/matrixone/pkg/fileservice"
    34  	"github.com/matrixorigin/matrixone/pkg/frontend"
    35  	"github.com/matrixorigin/matrixone/pkg/gossip"
    36  	"github.com/matrixorigin/matrixone/pkg/incrservice"
    37  	"github.com/matrixorigin/matrixone/pkg/lockservice"
    38  	"github.com/matrixorigin/matrixone/pkg/logservice"
    39  	logservicepb "github.com/matrixorigin/matrixone/pkg/pb/logservice"
    40  	"github.com/matrixorigin/matrixone/pkg/pb/metadata"
    41  	"github.com/matrixorigin/matrixone/pkg/pb/txn"
    42  	"github.com/matrixorigin/matrixone/pkg/queryservice"
    43  	qclient "github.com/matrixorigin/matrixone/pkg/queryservice/client"
    44  	"github.com/matrixorigin/matrixone/pkg/taskservice"
    45  	"github.com/matrixorigin/matrixone/pkg/txn/client"
    46  	"github.com/matrixorigin/matrixone/pkg/txn/rpc"
    47  	"github.com/matrixorigin/matrixone/pkg/udf"
    48  	"github.com/matrixorigin/matrixone/pkg/udf/pythonservice"
    49  	"github.com/matrixorigin/matrixone/pkg/util"
    50  	"github.com/matrixorigin/matrixone/pkg/util/address"
    51  	"github.com/matrixorigin/matrixone/pkg/util/executor"
    52  	"github.com/matrixorigin/matrixone/pkg/util/toml"
    53  	"github.com/matrixorigin/matrixone/pkg/vm/engine"
    54  	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/options"
    55  	"go.uber.org/zap"
    56  )
    57  
    58  var (
    59  	defaultListenAddress             = "127.0.0.1:6002"
    60  	defaultQueryServiceListenAddress = "0.0.0.0:19998"
    61  	// defaultTxnIsolation     = txn.TxnIsolation_SI
    62  	defaultTxnMode             = txn.TxnMode_Pessimistic
    63  	maxForMaxPreparedStmtCount = 1000000
    64  
    65  	// Service ports related.
    66  	defaultServiceHost = "127.0.0.1"
    67  )
    68  
    69  type Service interface {
    70  	Start() error
    71  	Close() error
    72  	// ID returns UUID of the service.
    73  	ID() string
    74  	GetTaskRunner() taskservice.TaskRunner
    75  	GetTaskService() (taskservice.TaskService, bool)
    76  	GetSQLExecutor() executor.SQLExecutor
    77  	GetBootstrapService() bootstrap.Service
    78  }
    79  
    80  type EngineType string
    81  
    82  const (
    83  	EngineDistributedTAE       EngineType = "distributed-tae"
    84  	EngineMemory               EngineType = "memory"
    85  	EngineNonDistributedMemory EngineType = "non-distributed-memory"
    86  	// ReservedTasks equals how many task must run background.
    87  	// 1 for metric StorageUsage
    88  	// 1 for trace ETLMerge
    89  	ReservedTasks = 2
    90  )
    91  
    92  // Config cn service
    93  type Config struct {
    94  	// UUID cn store uuid
    95  	UUID string `toml:"uuid"`
    96  	// Role cn node role, [AP|TP]
    97  	Role string `toml:"role"`
    98  
    99  	// ListenAddress listening address for receiving external requests
   100  	ListenAddress string `toml:"listen-address"`
   101  	// ServiceAddress service address for communication, if this address is not set, use
   102  	// ListenAddress as the communication address.
   103  	ServiceAddress string `toml:"service-address"`
   104  	// SQLAddress service address for receiving external sql client
   105  	SQLAddress string `toml:"sql-address"`
   106  
   107  	// PortBase is the base port for the service. We reserve reservedPorts for
   108  	// the service to start internal server inside it.
   109  	//
   110  	// TODO(volgariver6): The value of this field is also used to determine the version
   111  	// of MO. If it is not set, we use the old listen-address/service-address fields, and
   112  	// if it is set, we use the new policy to distribute the ports to all services.
   113  	PortBase int `toml:"port-base" user_setting:"basic"`
   114  	// ServiceHost is the host name/IP for the service address of RPC request. There is
   115  	// no port value in it.
   116  	ServiceHost string `toml:"service-host" user_setting:"basic"`
   117  
   118  	// FileService file service configuration
   119  
   120  	Engine struct {
   121  		Type     EngineType           `toml:"type"`
   122  		Logstore options.LogstoreType `toml:"logstore"`
   123  	}
   124  
   125  	// parameters for cn-server related buffer.
   126  	ReadBufferSize  int
   127  	WriteBufferSize int
   128  
   129  	// Pipeline configuration
   130  	Pipeline struct {
   131  		// HostSize is the memory limit
   132  		HostSize int64 `toml:"host-size"`
   133  		// GuestSize is the memory limit for one query
   134  		GuestSize int64 `toml:"guest-size"`
   135  		// BatchRows is the batch rows limit for one batch
   136  		BatchRows int64 `toml:"batch-rows"`
   137  		// BatchSize is the memory limit for one batch
   138  		BatchSize int64 `toml:"batch-size"`
   139  	}
   140  
   141  	// Frontend parameters for the frontend
   142  	Frontend config.FrontendParameters `toml:"frontend"`
   143  
   144  	// HAKeeper configuration
   145  	HAKeeper struct {
   146  		// HeatbeatInterval heartbeat interval to send message to hakeeper. Default is 1s
   147  		HeatbeatInterval toml.Duration `toml:"hakeeper-heartbeat-interval"`
   148  		// HeatbeatTimeout heartbeat request timeout. Default is 500ms
   149  		HeatbeatTimeout toml.Duration `toml:"hakeeper-heartbeat-timeout"`
   150  		// DiscoveryTimeout discovery HAKeeper service timeout. Default is 30s
   151  		DiscoveryTimeout toml.Duration `toml:"hakeeper-discovery-timeout"`
   152  		// ClientConfig hakeeper client configuration
   153  		ClientConfig logservice.HAKeeperClientConfig
   154  	}
   155  
   156  	// TaskRunner configuration
   157  	TaskRunner struct {
   158  		QueryLimit        int           `toml:"task-query-limit"`
   159  		Parallelism       int           `toml:"task-parallelism"`
   160  		MaxWaitTasks      int           `toml:"task-max-wait-tasks"`
   161  		FetchInterval     toml.Duration `toml:"task-fetch-interval"`
   162  		FetchTimeout      toml.Duration `toml:"task-fetch-timeout"`
   163  		RetryInterval     toml.Duration `toml:"task-retry-interval"`
   164  		HeartbeatInterval toml.Duration `toml:"task-heartbeat-interval"`
   165  		HeartbeatTimeout  toml.Duration `toml:"task-heartbeat-timeout"`
   166  	}
   167  
   168  	// RPC rpc config used to build txn sender
   169  	RPC rpc.Config `toml:"rpc"`
   170  
   171  	// Cluster configuration
   172  	Cluster struct {
   173  		// RefreshInterval refresh cluster info from hakeeper interval
   174  		RefreshInterval toml.Duration `toml:"refresh-interval"`
   175  	}
   176  
   177  	// LockService lockservice
   178  	LockService lockservice.Config `toml:"lockservice"`
   179  
   180  	// Txn txn config
   181  	Txn struct {
   182  		// Isolation txn isolation. SI or RC
   183  		// when Isolation is not set. we will set SI when Mode is optimistic, RC when Mode is pessimistic
   184  		Isolation string `toml:"isolation" user_setting:"advanced"`
   185  		// Mode txn mode. optimistic or pessimistic, default is pessimistic
   186  		Mode string `toml:"mode" user_setting:"advanced"`
   187  		// EnableSacrificingFreshness In Push Mode, the transaction is not guaranteed
   188  		// to see the latest commit data, and the latest Logtail commit timestamp received
   189  		// by the current CN + 1 is used as the start time of the transaction. But it will
   190  		// ensure that the transactions of the same database connection can see the writes
   191  		// of the previous committed transactions.
   192  		// -1: disable
   193  		//	0: auto config based on txn mode
   194  		//  1: enable
   195  		EnableSacrificingFreshness int `toml:"enable-sacrificing-freshness"`
   196  		// EnableCNBasedConsistency ensure that all the transactions on a CN can read
   197  		// the writes of the previous committed transaction
   198  		// -1: disable
   199  		//	0: auto config based on txn mode
   200  		//  1: enable
   201  		EnableCNBasedConsistency int `toml:"enable-cn-based-consistency"`
   202  		// EnableRefreshExpressionIn RC mode, in the event of a conflict, the later transaction
   203  		// needs to see the latest data after the previous transaction commits. At this time we
   204  		// need to re-read the data, re-read the latest data, and re-compute the expression. This
   205  		// feature was turned off in 0.8 and is not supported for now. The replacement solution is
   206  		// to return a retry error and let the whole computation re-execute.
   207  		// -1: disable
   208  		//	0: auto config based on txn mode
   209  		//  1: enable
   210  		EnableRefreshExpression int `toml:"enable-refresh-expression"`
   211  		// EnableLeakCheck enable txn leak check
   212  		// -1: disable
   213  		//	0: auto config based on txn mode
   214  		//  1: enable
   215  		EnableLeakCheck int `toml:"enable-leak-check"`
   216  		// MaxActiveAges a txn max active duration
   217  		MaxActiveAges toml.Duration `toml:"max-active-ages"`
   218  		// EnableCheckRCInvalidError this config is used to check and find RC bugs in pessimistic mode.
   219  		// Will remove it later version.
   220  		EnableCheckRCInvalidError bool `toml:"enable-check-rc-invalid-error"`
   221  		// Limit flow control of transaction creation, maximum number of transactions per second. Default
   222  		// is unlimited.
   223  		Limit int `toml:"limit-per-second"`
   224  		// MaxActive is the count of max active txn in current cn.  If reached max value, the txn
   225  		// is added to a FIFO queue. Default is unlimited.
   226  		MaxActive int `toml:"max-active"`
   227  		// NormalStateNoWait is the config to control if it waits for the transaction client
   228  		// to be normal state. If the value is false, it waits until the transaction client to be
   229  		// normal state; if the value is true, it does not wait and just return an error to the
   230  		// client. Default value is false.
   231  		NormalStateNoWait bool `toml:"normal-state-no-wait"`
   232  		//PKDedupCount check whether primary key in transaction's workspace is duplicated if the count of pk
   233  		// is less than PKDedupCount when txn commits. Default value is 0 , which means don't do deduplication.
   234  		PkDedupCount int `toml:"pk-dedup-count"`
   235  
   236  		// Trace trace
   237  		Trace struct {
   238  			BufferSize    int           `toml:"buffer-size"`
   239  			FlushBytes    toml.ByteSize `toml:"flush-bytes"`
   240  			FlushDuration toml.Duration `toml:"force-flush-duration"`
   241  			Dir           string        `toml:"dir"`
   242  			Enable        bool          `toml:"enable"`
   243  			Tables        []uint64      `toml:"tables"`
   244  		} `toml:"trace"`
   245  	} `toml:"txn"`
   246  
   247  	// AutoIncrement auto increment config
   248  	AutoIncrement incrservice.Config `toml:"auto-increment"`
   249  
   250  	// QueryServiceConfig is the config for query service.
   251  	QueryServiceConfig queryservice.Config `toml:"query-service"`
   252  
   253  	// PrimaryKeyCheck
   254  	PrimaryKeyCheck bool `toml:"primary-key-check"`
   255  
   256  	// MaxPreparedStmtCount
   257  	MaxPreparedStmtCount int `toml:"max_prepared_stmt_count"`
   258  
   259  	// InitWorkState is the initial work state for CN. Valid values are:
   260  	// "working", "draining" and "drained".
   261  	InitWorkState string `toml:"init-work-state"`
   262  
   263  	PythonUdfClient pythonservice.ClientConfig `toml:"python-udf-client"`
   264  
   265  	// LogtailUpdateStatsThreshold is the number that logtail entries received
   266  	// to trigger stats updating.
   267  	LogtailUpdateStatsThreshold int `toml:"logtail-update-stats-threshold"`
   268  
   269  	// Whether to automatically upgrade when system startup
   270  	AutomaticUpgrade       bool `toml:"auto-upgrade"`
   271  	UpgradeTenantBatchSize int  `toml:"upgrade-tenant-batch"`
   272  }
   273  
   274  func (c *Config) Validate() error {
   275  	foundMachineHost := ""
   276  	if c.UUID == "" {
   277  		panic("missing cn store UUID")
   278  	}
   279  	if c.ListenAddress == "" {
   280  		c.ListenAddress = defaultListenAddress
   281  	}
   282  	if c.ServiceAddress == "" {
   283  		c.ServiceAddress = c.ListenAddress
   284  	} else {
   285  		foundMachineHost = strings.Split(c.ServiceAddress, ":")[0]
   286  	}
   287  	if c.Role == "" {
   288  		c.Role = metadata.CNRole_TP.String()
   289  	}
   290  	if c.HAKeeper.DiscoveryTimeout.Duration == 0 {
   291  		c.HAKeeper.DiscoveryTimeout.Duration = time.Second * 30
   292  	}
   293  	if c.HAKeeper.HeatbeatInterval.Duration == 0 {
   294  		c.HAKeeper.HeatbeatInterval.Duration = time.Second
   295  	}
   296  	if c.HAKeeper.HeatbeatTimeout.Duration == 0 {
   297  		c.HAKeeper.HeatbeatTimeout.Duration = time.Second * 3
   298  	}
   299  	if c.TaskRunner.Parallelism == 0 {
   300  		c.TaskRunner.Parallelism = runtime.NumCPU() / 16
   301  		if c.TaskRunner.Parallelism <= ReservedTasks {
   302  			c.TaskRunner.Parallelism = 1 + ReservedTasks
   303  		}
   304  	}
   305  	if c.TaskRunner.FetchInterval.Duration == 0 {
   306  		c.TaskRunner.FetchInterval.Duration = time.Second * 10
   307  	}
   308  	if c.TaskRunner.FetchTimeout.Duration == 0 {
   309  		c.TaskRunner.FetchTimeout.Duration = time.Second * 10
   310  	}
   311  	if c.TaskRunner.HeartbeatInterval.Duration == 0 {
   312  		c.TaskRunner.HeartbeatInterval.Duration = time.Second * 5
   313  	}
   314  	if c.TaskRunner.MaxWaitTasks == 0 {
   315  		c.TaskRunner.MaxWaitTasks = 256
   316  	}
   317  	if c.TaskRunner.QueryLimit == 0 {
   318  		c.TaskRunner.QueryLimit = c.TaskRunner.Parallelism
   319  	}
   320  	if c.TaskRunner.RetryInterval.Duration == 0 {
   321  		c.TaskRunner.RetryInterval.Duration = time.Second
   322  	}
   323  	if c.Engine.Type == "" {
   324  		c.Engine.Type = EngineDistributedTAE
   325  	}
   326  	if c.Engine.Logstore == "" {
   327  		c.Engine.Logstore = options.LogstoreLogservice
   328  	}
   329  	if c.Cluster.RefreshInterval.Duration == 0 {
   330  		c.Cluster.RefreshInterval.Duration = time.Second * 10
   331  	}
   332  
   333  	if c.Txn.Mode == "" {
   334  		c.Txn.Mode = defaultTxnMode.String()
   335  	}
   336  	if !txn.ValidTxnMode(c.Txn.Mode) {
   337  		return moerr.NewBadDBNoCtx("not support txn mode: " + c.Txn.Mode)
   338  	}
   339  
   340  	if c.Txn.Isolation == "" {
   341  		if txn.GetTxnMode(c.Txn.Mode) == txn.TxnMode_Pessimistic {
   342  			c.Txn.Isolation = txn.TxnIsolation_RC.String()
   343  		} else {
   344  			c.Txn.Isolation = txn.TxnIsolation_SI.String()
   345  		}
   346  	}
   347  	if !txn.ValidTxnIsolation(c.Txn.Isolation) {
   348  		return moerr.NewBadDBNoCtx("not support txn isolation: " + c.Txn.Isolation)
   349  	}
   350  
   351  	// Fix txn mode various config, simply override
   352  	if txn.GetTxnMode(c.Txn.Mode) == txn.TxnMode_Pessimistic {
   353  		if c.Txn.EnableSacrificingFreshness == 0 {
   354  			c.Txn.EnableSacrificingFreshness = 1
   355  		}
   356  		if c.Txn.EnableCNBasedConsistency == 0 {
   357  			c.Txn.EnableCNBasedConsistency = -1
   358  		}
   359  		// We don't support the following now, so always disable
   360  		c.Txn.EnableRefreshExpression = -1
   361  		if c.Txn.EnableLeakCheck == 0 {
   362  			c.Txn.EnableLeakCheck = -1
   363  		}
   364  	} else {
   365  		if c.Txn.EnableSacrificingFreshness == 0 {
   366  			c.Txn.EnableSacrificingFreshness = 1
   367  		}
   368  		if c.Txn.EnableCNBasedConsistency == 0 {
   369  			c.Txn.EnableCNBasedConsistency = 1
   370  		}
   371  		// We don't support the following now, so always disable
   372  		c.Txn.EnableRefreshExpression = -1
   373  		if c.Txn.EnableLeakCheck == 0 {
   374  			c.Txn.EnableLeakCheck = -1
   375  		}
   376  	}
   377  
   378  	if c.Txn.MaxActiveAges.Duration == 0 {
   379  		c.Txn.MaxActiveAges.Duration = time.Minute * 2
   380  	}
   381  	if c.Txn.MaxActive == 0 {
   382  		c.Txn.MaxActive = runtime.NumCPU() * 4
   383  	}
   384  	c.LockService.ServiceID = c.UUID
   385  	c.LockService.Validate()
   386  
   387  	// pessimistic mode implies primary key check
   388  	if txn.GetTxnMode(c.Txn.Mode) == txn.TxnMode_Pessimistic || c.PrimaryKeyCheck {
   389  		config.CNPrimaryCheck = true
   390  	} else {
   391  		config.CNPrimaryCheck = false
   392  	}
   393  
   394  	if c.MaxPreparedStmtCount > 0 {
   395  		if c.MaxPreparedStmtCount > maxForMaxPreparedStmtCount {
   396  			frontend.MaxPrepareNumberInOneSession = maxForMaxPreparedStmtCount
   397  		} else {
   398  			frontend.MaxPrepareNumberInOneSession = c.MaxPreparedStmtCount
   399  		}
   400  	} else {
   401  		frontend.MaxPrepareNumberInOneSession = 100000
   402  	}
   403  	c.QueryServiceConfig.Adjust(foundMachineHost, defaultQueryServiceListenAddress)
   404  
   405  	if c.PortBase != 0 {
   406  		if c.ServiceHost == "" {
   407  			c.ServiceHost = defaultServiceHost
   408  		}
   409  	}
   410  
   411  	if !metadata.ValidStateString(c.InitWorkState) {
   412  		c.InitWorkState = metadata.WorkState_Working.String()
   413  	}
   414  
   415  	// TODO: remove this if rc is stable
   416  	moruntime.ProcessLevelRuntime().SetGlobalVariables(moruntime.EnableCheckInvalidRCErrors,
   417  		c.Txn.EnableCheckRCInvalidError)
   418  	return nil
   419  }
   420  
   421  // SetDefaultValue setups the default of the config.
   422  // most of the code are copied from the Validate.
   423  // But, the Validate may change some global variables that the SetDefaultValue does not need.
   424  // So, need a different function.
   425  func (c *Config) SetDefaultValue() {
   426  	foundMachineHost := ""
   427  	if c.ListenAddress == "" {
   428  		c.ListenAddress = defaultListenAddress
   429  	}
   430  	if c.ServiceAddress == "" {
   431  		c.ServiceAddress = c.ListenAddress
   432  	} else {
   433  		foundMachineHost = strings.Split(c.ServiceAddress, ":")[0]
   434  	}
   435  	if c.Role == "" {
   436  		c.Role = metadata.CNRole_TP.String()
   437  	}
   438  	if c.HAKeeper.DiscoveryTimeout.Duration == 0 {
   439  		c.HAKeeper.DiscoveryTimeout.Duration = time.Second * 30
   440  	}
   441  	if c.HAKeeper.HeatbeatInterval.Duration == 0 {
   442  		c.HAKeeper.HeatbeatInterval.Duration = time.Second
   443  	}
   444  	if c.HAKeeper.HeatbeatTimeout.Duration == 0 {
   445  		c.HAKeeper.HeatbeatTimeout.Duration = time.Second * 3
   446  	}
   447  	if c.TaskRunner.Parallelism == 0 {
   448  		c.TaskRunner.Parallelism = runtime.NumCPU() / 16
   449  		if c.TaskRunner.Parallelism <= ReservedTasks {
   450  			c.TaskRunner.Parallelism = 1 + ReservedTasks
   451  		}
   452  	}
   453  	if c.TaskRunner.FetchInterval.Duration == 0 {
   454  		c.TaskRunner.FetchInterval.Duration = time.Second * 10
   455  	}
   456  	if c.TaskRunner.FetchTimeout.Duration == 0 {
   457  		c.TaskRunner.FetchTimeout.Duration = time.Second * 10
   458  	}
   459  	if c.TaskRunner.HeartbeatInterval.Duration == 0 {
   460  		c.TaskRunner.HeartbeatInterval.Duration = time.Second * 5
   461  	}
   462  	if c.TaskRunner.MaxWaitTasks == 0 {
   463  		c.TaskRunner.MaxWaitTasks = 256
   464  	}
   465  	if c.TaskRunner.QueryLimit == 0 {
   466  		c.TaskRunner.QueryLimit = c.TaskRunner.Parallelism
   467  	}
   468  	if c.TaskRunner.RetryInterval.Duration == 0 {
   469  		c.TaskRunner.RetryInterval.Duration = time.Second
   470  	}
   471  	if c.Engine.Type == "" {
   472  		c.Engine.Type = EngineDistributedTAE
   473  	}
   474  	if c.Engine.Logstore == "" {
   475  		c.Engine.Logstore = options.LogstoreLogservice
   476  	}
   477  	if c.Cluster.RefreshInterval.Duration == 0 {
   478  		c.Cluster.RefreshInterval.Duration = time.Second * 10
   479  	}
   480  
   481  	if c.Txn.Mode == "" {
   482  		c.Txn.Mode = defaultTxnMode.String()
   483  	}
   484  
   485  	if c.Txn.Isolation == "" {
   486  		if txn.GetTxnMode(c.Txn.Mode) == txn.TxnMode_Pessimistic {
   487  			c.Txn.Isolation = txn.TxnIsolation_RC.String()
   488  		} else {
   489  			c.Txn.Isolation = txn.TxnIsolation_SI.String()
   490  		}
   491  	}
   492  	// Fix txn mode various config, simply override
   493  	if txn.GetTxnMode(c.Txn.Mode) == txn.TxnMode_Pessimistic {
   494  		if c.Txn.EnableSacrificingFreshness == 0 {
   495  			c.Txn.EnableSacrificingFreshness = 1
   496  		}
   497  		if c.Txn.EnableCNBasedConsistency == 0 {
   498  			c.Txn.EnableCNBasedConsistency = -1
   499  		}
   500  		// We don't support the following now, so always disable
   501  		c.Txn.EnableRefreshExpression = -1
   502  		if c.Txn.EnableLeakCheck == 0 {
   503  			c.Txn.EnableLeakCheck = -1
   504  		}
   505  	} else {
   506  		if c.Txn.EnableSacrificingFreshness == 0 {
   507  			c.Txn.EnableSacrificingFreshness = 1
   508  		}
   509  		if c.Txn.EnableCNBasedConsistency == 0 {
   510  			c.Txn.EnableCNBasedConsistency = 1
   511  		}
   512  		// We don't support the following now, so always disable
   513  		c.Txn.EnableRefreshExpression = -1
   514  		if c.Txn.EnableLeakCheck == 0 {
   515  			c.Txn.EnableLeakCheck = -1
   516  		}
   517  	}
   518  
   519  	if c.Txn.MaxActiveAges.Duration == 0 {
   520  		c.Txn.MaxActiveAges.Duration = time.Minute * 2
   521  	}
   522  	if c.Txn.MaxActive == 0 {
   523  		c.Txn.MaxActive = runtime.NumCPU() * 4
   524  	}
   525  	c.Txn.NormalStateNoWait = false
   526  	c.LockService.ServiceID = "temp"
   527  	c.LockService.Validate()
   528  	c.LockService.ServiceID = c.UUID
   529  
   530  	c.QueryServiceConfig.Adjust(foundMachineHost, defaultQueryServiceListenAddress)
   531  
   532  	if c.PortBase != 0 {
   533  		if c.ServiceHost == "" {
   534  			c.ServiceHost = defaultServiceHost
   535  		}
   536  	}
   537  
   538  	if !metadata.ValidStateString(c.InitWorkState) {
   539  		c.InitWorkState = metadata.WorkState_Working.String()
   540  	}
   541  
   542  	if c.UpgradeTenantBatchSize <= 0 {
   543  		c.UpgradeTenantBatchSize = 16
   544  	} else if c.UpgradeTenantBatchSize >= 32 {
   545  		c.UpgradeTenantBatchSize = 32
   546  	}
   547  
   548  	c.Frontend.SetDefaultValues()
   549  }
   550  
   551  func (s *service) getLockServiceConfig() lockservice.Config {
   552  	s.cfg.LockService.ServiceID = s.cfg.UUID
   553  	s.cfg.LockService.RPC = s.cfg.RPC
   554  	s.cfg.LockService.ListenAddress = s.lockServiceListenAddr()
   555  	s.cfg.LockService.TxnIterFunc = func(f func([]byte) bool) {
   556  		tc := s._txnClient
   557  		if tc == nil {
   558  			return
   559  		}
   560  
   561  		tc.IterTxns(func(to client.TxnOverview) bool {
   562  			return f(to.Meta.ID)
   563  		})
   564  	}
   565  	return s.cfg.LockService
   566  }
   567  
   568  type service struct {
   569  	metadata       metadata.CNStore
   570  	cfg            *Config
   571  	responsePool   *sync.Pool
   572  	logger         *zap.Logger
   573  	server         morpc.RPCServer
   574  	requestHandler func(ctx context.Context,
   575  		cnAddr string,
   576  		message morpc.Message,
   577  		cs morpc.ClientSession,
   578  		engine engine.Engine,
   579  		fService fileservice.FileService,
   580  		lockService lockservice.LockService,
   581  		queryClient qclient.QueryClient,
   582  		hakeeper logservice.CNHAKeeperClient,
   583  		udfService udf.Service,
   584  		cli client.TxnClient,
   585  		aicm *defines.AutoIncrCacheManager,
   586  		messageAcquirer func() morpc.Message) error
   587  	cancelMoServerFunc     context.CancelFunc
   588  	mo                     *frontend.MOServer
   589  	initHakeeperClientOnce sync.Once
   590  	_hakeeperClient        logservice.CNHAKeeperClient
   591  	hakeeperConnected      chan struct{}
   592  	initTxnSenderOnce      sync.Once
   593  	_txnSender             rpc.TxnSender
   594  	initTxnClientOnce      sync.Once
   595  	_txnClient             client.TxnClient
   596  	timestampWaiter        client.TimestampWaiter
   597  	storeEngine            engine.Engine
   598  	metadataFS             fileservice.ReplaceableFileService
   599  	etlFS                  fileservice.FileService
   600  	fileService            fileservice.FileService
   601  	pu                     *config.ParameterUnit
   602  	moCluster              clusterservice.MOCluster
   603  	lockService            lockservice.LockService
   604  	sqlExecutor            executor.SQLExecutor
   605  	sessionMgr             *queryservice.SessionManager
   606  	// queryService is used to handle query request from other CN service.
   607  	queryService queryservice.QueryService
   608  	// queryClient is used to send query request to other CN services.
   609  	queryClient qclient.QueryClient
   610  	// udfService is used to handle non-sql udf
   611  	udfService       udf.Service
   612  	bootstrapService bootstrap.Service
   613  
   614  	stopper *stopper.Stopper
   615  	aicm    *defines.AutoIncrCacheManager
   616  
   617  	task struct {
   618  		sync.RWMutex
   619  		holder         taskservice.TaskServiceHolder
   620  		runner         taskservice.TaskRunner
   621  		storageFactory taskservice.TaskStorageFactory
   622  	}
   623  
   624  	addressMgr address.AddressManager
   625  	gossipNode *gossip.Node
   626  	config     *util.ConfigData
   627  
   628  	options struct {
   629  		bootstrapOptions []bootstrap.Option
   630  		traceDataPath    string
   631  	}
   632  
   633  	// pipelines record running pipelines in the service, used for monitoring.
   634  	pipelines struct {
   635  		// counter recording the total number of running pipelines,
   636  		// details are not recorded for simplicity as suggested by @nnsgmsone
   637  		counter atomic.Int64
   638  	}
   639  }
   640  
   641  func dumpCnConfig(cfg Config) (map[string]*logservicepb.ConfigItem, error) {
   642  	defCfg := Config{}
   643  	defCfg.SetDefaultValue()
   644  	return util.DumpConfig(cfg, defCfg)
   645  }