Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pdms: support primary/transfer api for scheduling and tso #8157

Merged
merged 37 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
7fa19d3
check primary
HuSharp May 9, 2024
1f13fa2
make test happy
HuSharp May 9, 2024
af995cc
address comment and add test
HuSharp May 9, 2024
8d36be5
only trigger by updating
HuSharp May 9, 2024
2433f0c
change log
HuSharp May 10, 2024
dd72b9c
address comment
HuSharp May 10, 2024
a39300e
change to name
HuSharp May 13, 2024
51708b5
make test happy
HuSharp May 13, 2024
c6d2bc3
address comment and change some comments
HuSharp May 14, 2024
a4c5c29
add more test
HuSharp May 14, 2024
4d0598f
merge master
HuSharp May 21, 2024
6ac311f
Merge branch 'master' into support_transfer_primary2
HuSharp May 30, 2024
510b92a
Merge branch 'master' into support_transfer_primary2
HuSharp Jun 13, 2024
b235bc1
address comment and add more comment
HuSharp Jul 1, 2024
f659782
add more comment
HuSharp Jul 1, 2024
32b0b5f
Merge branch 'master' into support_transfer_primary2
HuSharp Jul 2, 2024
dbc5447
Merge branch 'master' into support_transfer_primary2
HuSharp Jul 2, 2024
204ffd5
address comment
HuSharp Jul 3, 2024
ec8e737
remove redundant wait
HuSharp Jul 4, 2024
9e3b798
Merge branch 'master' into support_transfer_primary2
ti-chi-bot[bot] Jul 8, 2024
e53844e
Merge branch 'master' into support_transfer_primary2
ti-chi-bot[bot] Jul 8, 2024
cc82e7b
Merge branch 'master' into support_transfer_primary2
ti-chi-bot[bot] Jul 9, 2024
19ce9d8
Merge branch 'master' into support_transfer_primary2
ti-chi-bot[bot] Jul 9, 2024
4c7f8ac
changed by name
HuSharp Jul 25, 2024
36b5a82
refine code
HuSharp Jul 25, 2024
ea8d9e3
address comment
HuSharp Jul 30, 2024
ffb7b1b
refine code
HuSharp Jul 31, 2024
379b1f6
merge master
HuSharp Aug 5, 2024
d9bffb8
Merge branch 'master' into support_transfer_primary2
HuSharp Aug 12, 2024
d037a6a
remove delete
HuSharp Aug 12, 2024
e711fd9
refine purpose and lease
HuSharp Aug 12, 2024
d999c7f
merge master
HuSharp Aug 12, 2024
7f0a426
refine code
HuSharp Aug 12, 2024
d810ed1
address comment
HuSharp Aug 12, 2024
43830ec
non-essential exported
HuSharp Aug 13, 2024
2d9a3b0
refine check name
HuSharp Aug 13, 2024
c1da5b5
Merge branch 'master' into support_transfer_primary2
ti-chi-bot[bot] Aug 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions client/http/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,11 @@ func MicroServicePrimary(service string) string {
return fmt.Sprintf("%s/primary/%s", microServicePrefix, service)
}

// MicroServicePrimaryTransfer returns the path of PD HTTP API to transfer the primary of microservice.
func MicroServicePrimaryTransfer(service string) string {
return fmt.Sprintf("%s/primary/transfer/%s", microServicePrefix, service)
}

// GetUpdateKeyspaceConfigURL returns the path of PD HTTP API to update keyspace config.
func GetUpdateKeyspaceConfigURL(keyspaceName string) string {
return fmt.Sprintf(KeyspaceConfig, keyspaceName)
Expand Down
17 changes: 17 additions & 0 deletions client/http/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
/* Micro Service interfaces */
GetMicroServiceMembers(context.Context, string) ([]MicroServiceMember, error)
GetMicroServicePrimary(context.Context, string) (string, error)
TransferMicroServicePrimary(context.Context, string, string) error
DeleteOperators(context.Context) error

/* Keyspace interface */
Expand Down Expand Up @@ -908,6 +909,22 @@
return primary, err
}

func (c *client) TransferMicroServicePrimary(ctx context.Context, service, newPrimary string) error {
reqData, err := json.Marshal(struct {
NewPrimary string `json:"new_primary"`
}{
NewPrimary: newPrimary,
})
if err != nil {
return errors.Trace(err)

Check warning on line 919 in client/http/interface.go

View check run for this annotation

Codecov / codecov/patch

client/http/interface.go#L919

Added line #L919 was not covered by tests
}
return c.request(ctx, newRequestInfo().
WithName(transferMicroServicePrimaryName).
WithURI(MicroServicePrimaryTransfer(service)).
WithMethod(http.MethodPost).
WithBody(reqData))
}

// GetPDVersion gets the release version of the PD binary.
func (c *client) GetPDVersion(ctx context.Context) (string, error) {
var ver struct {
Expand Down
1 change: 1 addition & 0 deletions client/http/request_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const (
getMinResolvedTSByStoresIDsName = "GetMinResolvedTSByStoresIDs"
getMicroServiceMembersName = "GetMicroServiceMembers"
getMicroServicePrimaryName = "GetMicroServicePrimary"
transferMicroServicePrimaryName = "TransferMicroServicePrimary"
getPDVersionName = "GetPDVersion"
resetTSName = "ResetTS"
resetBaseAllocIDName = "ResetBaseAllocID"
Expand Down
3 changes: 3 additions & 0 deletions cmd/pd-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ func NewTSOServiceCommand() *cobra.Command {
Short: "Run the TSO service",
Run: tso.CreateServerWrapper,
}
cmd.Flags().StringP("name", "", "", "human-readable name for this TSO member")
cmd.Flags().BoolP("version", "V", false, "print version information and exit")
cmd.Flags().StringP("config", "", "", "config file")
cmd.Flags().StringP("backend-endpoints", "", "", "url for etcd client")
Expand All @@ -114,6 +115,7 @@ func NewSchedulingServiceCommand() *cobra.Command {
Short: "Run the scheduling service",
Run: scheduling.CreateServerWrapper,
}
cmd.Flags().StringP("name", "", "", "human-readable name for this Scheduling member")
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
cmd.Flags().BoolP("version", "V", false, "print version information and exit")
cmd.Flags().StringP("config", "", "", "config file")
cmd.Flags().StringP("backend-endpoints", "", "", "url for etcd client")
Expand All @@ -134,6 +136,7 @@ func NewResourceManagerServiceCommand() *cobra.Command {
Short: "Run the resource manager service",
Run: resource_manager.CreateServerWrapper,
}
cmd.Flags().StringP("name", "", "", "human-readable name for this resource management member")
cmd.Flags().BoolP("version", "V", false, "print version information and exit")
cmd.Flags().StringP("config", "", "", "config file")
cmd.Flags().StringP("backend-endpoints", "", "", "url for etcd client")
Expand Down
23 changes: 23 additions & 0 deletions pkg/election/leadership.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@
leaderKey string
leaderValue string

leaderWatch atomic.Bool
HuSharp marked this conversation as resolved.
Show resolved Hide resolved

keepAliveCtx context.Context
keepAliveCancelFunc context.CancelFunc
keepAliveCancelFuncLock syncutil.Mutex
Expand All @@ -72,6 +74,10 @@
campaignTimes []time.Time
}

func (ls *Leadership) GetLeaderValue() string {
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
return ls.leaderValue

Check warning on line 78 in pkg/election/leadership.go

View check run for this annotation

Codecov / codecov/patch

pkg/election/leadership.go#L77-L78

Added lines #L77 - L78 were not covered by tests
}

// NewLeadership creates a new Leadership.
func NewLeadership(client *clientv3.Client, leaderKey, purpose string) *Leadership {
leadership := &Leadership{
Expand Down Expand Up @@ -113,6 +119,16 @@
return ls.leaderKey
}

// SetLeaderWatch sets the leader watch flag.
func (ls *Leadership) SetLeaderWatch(val bool) {
ls.leaderWatch.Store(val)
}

// IsLeader gets the leader watch flag.
func (ls *Leadership) IsLeader() bool {
return ls.leaderWatch.Load()
}

// GetCampaignTimesNum is used to get the campaign times of the leader within `campaignTimesRecordTimeout`.
func (ls *Leadership) GetCampaignTimesNum() int {
if ls == nil {
Expand Down Expand Up @@ -375,6 +391,12 @@
zap.Int64("revision", wresp.Header.Revision), zap.String("leader-key", ls.leaderKey), zap.String("purpose", ls.purpose))
return
}
// only API update the leader key to transfer the primary will meet
if ev.Type == mvccpb.PUT && ls.IsLeader() {
log.Info("[PrimaryWatch] current leadership is updated",
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
zap.Int64("revision", wresp.Header.Revision), zap.String("leader-key", ls.leaderKey), zap.String("purpose", ls.purpose))
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
return
}
}
revision = wresp.Header.Revision + 1
}
Expand All @@ -393,4 +415,5 @@
}
ls.keepAliveCancelFuncLock.Unlock()
ls.getLease().Close()
ls.SetLeaderWatch(false)
}
66 changes: 62 additions & 4 deletions pkg/mcs/discovery/discover.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@
package discovery

import (
"math/rand"
"strconv"
"time"

"github.com/pingcap/errors"
"github.com/pingcap/log"
"github.com/tikv/pd/pkg/errs"
"github.com/tikv/pd/pkg/mcs/utils"
"github.com/tikv/pd/pkg/storage/endpoint"
"github.com/tikv/pd/pkg/storage/kv"
"github.com/tikv/pd/pkg/utils/etcdutil"
"go.etcd.io/etcd/clientv3"
Expand All @@ -45,14 +48,14 @@
}

// GetMSMembers returns all the members of the specified service name.
func GetMSMembers(name string, client *clientv3.Client) ([]ServiceRegistryEntry, error) {
switch name {
func GetMSMembers(serviceName string, client *clientv3.Client) ([]ServiceRegistryEntry, error) {
switch serviceName {
case utils.TSOServiceName, utils.SchedulingServiceName, utils.ResourceManagerServiceName:
clusterID, err := etcdutil.GetClusterID(client, utils.ClusterIDPath)
if err != nil {
return nil, err
}
servicePath := ServicePath(strconv.FormatUint(clusterID, 10), name)
servicePath := ServicePath(strconv.FormatUint(clusterID, 10), serviceName)
resps, err := kv.NewSlowLogTxn(client).Then(clientv3.OpGet(servicePath, clientv3.WithPrefix())).Commit()
if err != nil {
return nil, errs.ErrEtcdKVGet.Wrap(err).GenWithStackByCause()
Expand All @@ -75,5 +78,60 @@
return entries, nil
}

return nil, errors.Errorf("unknown service name %s", name)
return nil, errors.Errorf("unknown service name %s", serviceName)

Check warning on line 81 in pkg/mcs/discovery/discover.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/discovery/discover.go#L81

Added line #L81 was not covered by tests
}

// TransferPrimary transfers the primary of the specified service.
func TransferPrimary(client *clientv3.Client, serviceName, oldPrimary, newPrimary string, keyspaceGroupID uint32) error {
log.Info("transfer primary", zap.String("service", serviceName), zap.String("from", oldPrimary), zap.String("to", newPrimary))
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
entries, err := GetMSMembers(serviceName, client)
if err != nil {
return err

Check warning on line 89 in pkg/mcs/discovery/discover.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/discovery/discover.go#L89

Added line #L89 was not covered by tests
}

// Do nothing when I am the only member of cluster.
if len(entries) == 1 {
return errors.New("no valid secondary to transfer primary")

Check warning on line 94 in pkg/mcs/discovery/discover.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/discovery/discover.go#L94

Added line #L94 was not covered by tests
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
}

var primaryIDs []string
var secondaryValues []string
for _, member := range entries {
if (newPrimary == "" && member.ServiceAddr != oldPrimary) || (newPrimary != "" && member.Name == newPrimary) {
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
primaryIDs = append(primaryIDs, member.ServiceAddr)
if string(member.MemberValue) == "" {
return errors.New("member value is empty")

Check warning on line 103 in pkg/mcs/discovery/discover.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/discovery/discover.go#L103

Added line #L103 was not covered by tests
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
}
secondaryValues = append(secondaryValues, string(member.MemberValue))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

secondaryValues sounds strange.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed to memberValues

}
}
if len(primaryIDs) == 0 {
return errors.New("no valid secondary to transfer primary")
}

r := rand.New(rand.NewSource(time.Now().UnixNano()))
nextPrimaryID := r.Intn(len(primaryIDs))

clusterID, err := etcdutil.GetClusterID(client, utils.ClusterIDPath)
if err != nil {
return errors.Errorf("failed to get cluster ID: %v", err)

Check warning on line 117 in pkg/mcs/discovery/discover.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/discovery/discover.go#L117

Added line #L117 was not covered by tests
}

var primaryKey string
switch serviceName {
case utils.SchedulingServiceName:
primaryKey = endpoint.SchedulingPrimaryPath(clusterID)
case utils.TSOServiceName:
tsoRootPath := endpoint.TSOSvcRootPath(clusterID)
primaryKey = endpoint.KeyspaceGroupPrimaryPath(tsoRootPath, keyspaceGroupID)
}

// update primary key to notify old primary server.
putResp, err := kv.NewSlowLogTxn(client).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the transaction takes a long time here, will it be possible to make the lease expire unexpectedly?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We give lease 3 seconds.

  • If this transaction takes a long time will only have the effect of causing the transfer primary to start very slowly, which will also be reflected by the api take a long time to execute it.
  • If you mean that the grant lease was not updated due to a large transaction failure, then the primary will be re-selected after a timeout. You can checked in TestTransferPrimaryWhileLeaseExpired

https://github.com/tikv/pd/pull/8157/files#diff-5a1f6bff4bb6b99fcd2f7bf4edc37aa937e8c51eafa41acc0aabd7aa1a1d1da6R267

Then(clientv3.OpPut(primaryKey, secondaryValues[nextPrimaryID])).
Commit()
if err != nil || !putResp.Succeeded {
return errors.Errorf("failed to write primary flag for %s", serviceName)

Check warning on line 134 in pkg/mcs/discovery/discover.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/discovery/discover.go#L134

Added line #L134 was not covered by tests
}
return nil
}
2 changes: 2 additions & 0 deletions pkg/mcs/discovery/registry_entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@ import (

// ServiceRegistryEntry is the registry entry of a service
type ServiceRegistryEntry struct {
Name string `json:"name"`
ServiceAddr string `json:"service-addr"`
Version string `json:"version"`
GitHash string `json:"git-hash"`
DeployPath string `json:"deploy-path"`
StartTimestamp int64 `json:"start-timestamp"`
MemberValue []byte `json:"member-value"`
}

// Serialize this service registry entry
Expand Down
1 change: 1 addition & 0 deletions pkg/mcs/resourcemanager/server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ func (c *Config) Parse(flagSet *pflag.FlagSet) error {
}

// Ignore the error check here
configutil.AdjustCommandLineString(flagSet, &c.Name, "name")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@niubell PTAL, thx!

configutil.AdjustCommandLineString(flagSet, &c.Log.Level, "log-level")
configutil.AdjustCommandLineString(flagSet, &c.Log.File.Filename, "log-file")
configutil.AdjustCommandLineString(flagSet, &c.Metric.PushAddress, "metrics-addr")
Expand Down
4 changes: 3 additions & 1 deletion pkg/mcs/resourcemanager/server/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,18 @@ func NewTestServer(ctx context.Context, re *require.Assertions, cfg *Config) (*S
// GenerateConfig generates a new config with the given options.
func GenerateConfig(c *Config) (*Config, error) {
arguments := []string{
"--name=" + c.Name,
"--listen-addr=" + c.ListenAddr,
"--advertise-listen-addr=" + c.AdvertiseListenAddr,
"--backend-endpoints=" + c.BackendEndpoints,
}

flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.StringP("name", "", "", "human-readable name for this resource manager member")
flagSet.BoolP("version", "V", false, "print version information and exit")
flagSet.StringP("config", "", "", "config file")
flagSet.StringP("backend-endpoints", "", "", "url for etcd client")
flagSet.StringP("listen-addr", "", "", "listen address for tso service")
flagSet.StringP("listen-addr", "", "", "listen address for resource manager service")
flagSet.StringP("advertise-listen-addr", "", "", "advertise urls for listen address (default '${listen-addr}')")
flagSet.StringP("cacert", "", "", "path of file that contains list of trusted TLS CAs")
flagSet.StringP("cert", "", "", "path of file that contains X509 certificate in PEM format")
Expand Down
1 change: 1 addition & 0 deletions pkg/mcs/scheduling/server/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ func (c *Config) Parse(flagSet *pflag.FlagSet) error {
}

// Ignore the error check here
configutil.AdjustCommandLineString(flagSet, &c.Name, "name")
configutil.AdjustCommandLineString(flagSet, &c.Log.Level, "log-level")
configutil.AdjustCommandLineString(flagSet, &c.Log.File.Filename, "log-file")
configutil.AdjustCommandLineString(flagSet, &c.Metric.PushAddress, "metrics-addr")
Expand Down
58 changes: 58 additions & 0 deletions pkg/mcs/scheduling/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"github.com/tikv/pd/pkg/storage/endpoint"
"github.com/tikv/pd/pkg/storage/kv"
"github.com/tikv/pd/pkg/utils/apiutil"
"github.com/tikv/pd/pkg/utils/etcdutil"
"github.com/tikv/pd/pkg/utils/grpcutil"
"github.com/tikv/pd/pkg/utils/logutil"
"github.com/tikv/pd/pkg/utils/memberutil"
Expand Down Expand Up @@ -128,6 +129,10 @@
return s.cfg.BackendEndpoints
}

func (s *Server) GetParticipant() *member.Participant {
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
return s.participant

Check warning on line 133 in pkg/mcs/scheduling/server/server.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/scheduling/server/server.go#L132-L133

Added lines #L132 - L133 were not covered by tests
}

// SetLogLevel sets log level.
func (s *Server) SetLogLevel(level string) error {
if !logutil.IsLevelLegal(level) {
Expand Down Expand Up @@ -243,6 +248,18 @@
log.Info("the scheduling primary has changed, try to re-campaign a primary")
}

// To make sure the expected leader(if exist) and primary are on the same server.
expectedPrimary := utils.GetExpectedPrimary(s.GetClient(), s.participant.GetLeaderPath())
if expectedPrimary != "" && expectedPrimary != s.participant.MemberValue() {
log.Info("skip campaigning of scheduling primary and check later",
zap.String("server-name", s.Name()),
zap.String("target-primary-id", expectedPrimary),
zap.Uint64("member-id", s.participant.ID()),
zap.String("cur-memberValue", s.participant.MemberValue()))
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
time.Sleep(200 * time.Millisecond)
continue
}

s.campaignLeader()
}
}
Expand Down Expand Up @@ -290,6 +307,9 @@
member.ServiceMemberGauge.WithLabelValues(serviceName).Set(1)
log.Info("scheduling primary is ready to serve", zap.String("scheduling-primary-name", s.participant.Name()))

exitPrimary := make(chan struct{})
go s.primaryWatch(ctx, exitPrimary)

leaderTicker := time.NewTicker(utils.LeaderTickInterval)
defer leaderTicker.Stop()

Expand All @@ -304,6 +324,42 @@
// Server is closed and it should return nil.
log.Info("server is closed")
return
case <-exitPrimary:
log.Info("no longer a primary because primary have been updated, the scheduling primary will step down")
return
}
}
}

func (s *Server) primaryWatch(ctx context.Context, exitPrimary chan struct{}) {
resp, err := etcdutil.EtcdKVGet(s.participant.GetLeadership().GetClient(), s.participant.GetLeaderPath())
if err != nil || resp == nil || len(resp.Kvs) == 0 {
log.Error("scheduling primary getting the primary meets error", errs.ZapError(err))
return

Check warning on line 338 in pkg/mcs/scheduling/server/server.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/scheduling/server/server.go#L337-L338

Added lines #L337 - L338 were not covered by tests
}
log.Info("scheduling primary start to watch the primary", zap.Stringer("scheduling-primary", s.participant.GetLeader()))
// Watch will keep looping and never return unless the primary has changed.
s.participant.GetLeadership().SetLeaderWatch(true)
s.participant.GetLeadership().Watch(s.serverLoopCtx, resp.Kvs[0].ModRevision+1)
HuSharp marked this conversation as resolved.
Show resolved Hide resolved
s.participant.GetLeadership().SetLeaderWatch(false)

// only API update primary will set the expected leader
curPrimary, err := etcdutil.GetValue(s.participant.Client(), s.participant.GetLeaderPath())
if err != nil {
log.Error("scheduling primary getting the leader meets error", errs.ZapError(err))
return
}
// only trigger by updating primary
if curPrimary != nil && resp.Kvs[0].Value != nil && string(curPrimary) != string(resp.Kvs[0].Value) {
utils.SetExpectedPrimary(s.participant.Client(), s.participant.GetLeaderPath())

s.participant.UnsetLeader()
defer log.Info("scheduling primary exit the primary watch loop")
select {
case <-ctx.Done():
return

Check warning on line 360 in pkg/mcs/scheduling/server/server.go

View check run for this annotation

Codecov / codecov/patch

pkg/mcs/scheduling/server/server.go#L359-L360

Added lines #L359 - L360 were not covered by tests
case exitPrimary <- struct{}{}:
return
}
}
}
Expand Down Expand Up @@ -425,6 +481,7 @@
GitHash: versioninfo.PDGitHash,
DeployPath: deployPath,
StartTimestamp: s.StartTimestamp(),
Name: s.Name(),
}
uniqueName := s.cfg.GetAdvertiseListenAddr()
uniqueID := memberutil.GenerateUniqueID(uniqueName)
Expand All @@ -436,6 +493,7 @@
ListenUrls: []string{s.cfg.GetAdvertiseListenAddr()},
}
s.participant.InitInfo(p, endpoint.SchedulingSvcRootPath(s.clusterID), utils.PrimaryKey, "primary election")
s.serviceID.MemberValue = []byte(s.participant.MemberValue())

s.service = &Service{Server: s}
s.AddServiceReadyCallback(s.startCluster)
Expand Down
2 changes: 2 additions & 0 deletions pkg/mcs/scheduling/server/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ func NewTestServer(ctx context.Context, re *require.Assertions, cfg *config.Conf
// GenerateConfig generates a new config with the given options.
func GenerateConfig(c *config.Config) (*config.Config, error) {
arguments := []string{
"--name=" + c.Name,
"--listen-addr=" + c.ListenAddr,
"--advertise-listen-addr=" + c.AdvertiseListenAddr,
"--backend-endpoints=" + c.BackendEndpoints,
}

flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.StringP("name", "", "", "human-readable name for this scheduling member")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we need a default name?

Copy link
Member Author

@HuSharp HuSharp May 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default name set by this code, which is like TSO-localhost

func (c *Config) Adjust(meta *toml.MetaData) error {
configMetaData := configutil.NewConfigMetadata(meta)
if err := configMetaData.CheckUndecoded(); err != nil {
c.WarningMsgs = append(c.WarningMsgs, err.Error())
}
if c.Name == "" {
hostname, err := os.Hostname()
if err != nil {
return err
}
configutil.AdjustString(&c.Name, fmt.Sprintf("%s-%s", defaultName, hostname))

And your commented snippet is for testing to avoid using the same name for the same machine for local testing, I used addr here

pd/tests/testutil.go

Lines 87 to 88 in 51708b5

cfg.Name = cfg.ListenAddr
cfg, err := tso.GenerateConfig(cfg)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got

flagSet.BoolP("version", "V", false, "print version information and exit")
flagSet.StringP("config", "", "", "config file")
flagSet.StringP("backend-endpoints", "", "", "url for etcd client")
Expand Down
Loading