github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/runtime/k0s/join_nodes.go (about)

     1  // Copyright © 2022 Alibaba Group Holding Ltd.
     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 k0s
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"net"
    21  
    22  	"github.com/pkg/errors"
    23  	"github.com/sirupsen/logrus"
    24  	"golang.org/x/sync/errgroup"
    25  )
    26  
    27  func (k *Runtime) joinNodes(nodes []net.IP) error {
    28  	if len(nodes) == 0 {
    29  		return nil
    30  	}
    31  
    32  	if err := k.initKube(nodes); err != nil {
    33  		return err
    34  	}
    35  
    36  	if err := k.WaitSSHReady(6, nodes...); err != nil {
    37  		return errors.Wrap(err, "join nodes wait for ssh ready time out")
    38  	}
    39  	/**To join a node, following these steps.
    40  	STEP1: send private registry cert and add registry info into node
    41  	STEP2: copy k0s join token
    42  	STEP3: use k0s command to join node with worker role.
    43  	STEP4: join node with token
    44  	STEP5: start the k0sworker.service
    45  	*/
    46  	if err := k.CopyJoinToken(WorkerRole, nodes); err != nil {
    47  		return err
    48  	}
    49  
    50  	cmds := k.JoinCommand(WorkerRole, "")
    51  	if cmds == nil {
    52  		return fmt.Errorf("failed to get join node command")
    53  	}
    54  
    55  	eg, _ := errgroup.WithContext(context.Background())
    56  	for _, node := range nodes {
    57  		node := node
    58  		eg.Go(func() error {
    59  			logrus.Infof("Start to join %s as worker", node)
    60  
    61  			if err := k.infra.CmdAsync(node, nil, cmds...); err != nil {
    62  				return fmt.Errorf("failed to join node %s: %v", node, err)
    63  			}
    64  			logrus.Infof("Succeeded in joining %s as worker", node)
    65  			return nil
    66  		})
    67  	}
    68  	return eg.Wait()
    69  }