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

     1  // Copyright © 2021 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 exec
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"net"
    21  
    22  	v2 "github.com/sealerio/sealer/types/api/v2"
    23  	"github.com/sealerio/sealer/utils/ssh"
    24  
    25  	"golang.org/x/sync/errgroup"
    26  )
    27  
    28  type Exec struct {
    29  	cluster *v2.Cluster
    30  	ipList  []net.IP
    31  }
    32  
    33  func NewExecCmd(cluster *v2.Cluster, ipList []net.IP) Exec {
    34  	return Exec{cluster: cluster, ipList: ipList}
    35  }
    36  
    37  func (e *Exec) RunCmd(cmd string) error {
    38  	eg, _ := errgroup.WithContext(context.Background())
    39  	for _, ipAddr := range e.ipList {
    40  		ip := ipAddr
    41  		eg.Go(func() error {
    42  			sshClient, sshErr := ssh.NewStdoutSSHClient(ip, e.cluster)
    43  			if sshErr != nil {
    44  				return sshErr
    45  			}
    46  			err := sshClient.CmdAsync(ip, nil, cmd)
    47  			if err != nil {
    48  				return err
    49  			}
    50  			return nil
    51  		})
    52  	}
    53  	if err := eg.Wait(); err != nil {
    54  		return fmt.Errorf("failed to exec command (%s): %v", cmd, err)
    55  	}
    56  	return nil
    57  }