etcdserver/server.go
func (s *EtcdServer) TransferLeadership() error {
	if !s.isLeader() {
		if lg := s.getLogger(); lg != nil {
			lg.Info(
				"skipped leadership transfer; local server is not leader",
				zap.String("local-member-id", s.ID().String()),
				zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
			)
		} else {
			plog.Printf("skipped leadership transfer for stopping non-leader member")
		}
		return nil
	}

	if !s.isMultiNode() {
		if lg := s.getLogger(); lg != nil {
			lg.Info(
				"skipped leadership transfer; it's a single-node cluster",
				zap.String("local-member-id", s.ID().String()),
				zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
			)
		} else {
			plog.Printf("skipped leadership transfer for single member cluster")
		}
		return nil
	}

	transferee, ok := longestConnected(s.r.transport, s.cluster.MemberIDs())
	if !ok {
		return ErrUnhealthy
	}

	tm := s.Cfg.ReqTimeout()
	ctx, cancel := context.WithTimeout(s.ctx, tm)
	err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
	cancel()
	return err
}
func (s *EtcdServer) TransferLeadership() error {
	if !s.isLeader() {
		if lg := s.getLogger(); lg != nil {
			lg.Info(
				"skipped leadership transfer; local server is not leader",
				zap.String("local-member-id", s.ID().String()),
				zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
			)
		} else {
			plog.Printf("skipped leadership transfer for stopping non-leader member")
		}
		return nil
	}

	if !s.isMultiNode() {
		if lg := s.getLogger(); lg != nil {
			lg.Info(
				"skipped leadership transfer; it's a single-node cluster",
				zap.String("local-member-id", s.ID().String()),
				zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
			)
		} else {
			plog.Printf("skipped leadership transfer for single member cluster")
		}
		return nil
	}

	transferee, ok := longestConnected(s.r.transport, s.cluster.MemberIDs())
	if !ok {
		return ErrUnhealthy
	}

	tm := s.Cfg.ReqTimeout()
	ctx, cancel := context.WithTimeout(s.ctx, tm)
	err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
	cancel()
	return err
}
// TransferLeadership transfers the leader to the chosen transferee.