-
Notifications
You must be signed in to change notification settings - Fork 2k
/
exec.go
85 lines (73 loc) · 2.28 KB
/
exec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
Copyright 2022 cuisongliu@qq.com.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ssh
import (
"context"
"fmt"
"strings"
"golang.org/x/sync/errgroup"
v2 "github.com/labring/sealos/pkg/types/v1beta1"
"github.com/labring/sealos/pkg/utils/logger"
)
type Exec struct {
cluster *v2.Cluster
ipList []string
}
func NewExecCmdFromRoles(cluster *v2.Cluster, roles string) (Exec, error) {
var ipList []string
if roles == "" {
ipList = append(cluster.GetMasterIPAndPortList(), cluster.GetNodeIPAndPortList()...)
} else {
roleList := strings.Split(roles, ",")
for _, role := range roleList {
ipList = append(ipList, cluster.GetIPSByRole(role)...)
}
if len(ipList) == 0 {
return Exec{}, fmt.Errorf("failed to get ipList, please check your roles label")
}
}
logger.Debug("exec from roles ipList is %+v", ipList)
return Exec{cluster: cluster, ipList: ipList}, nil
}
func NewExecCmdFromIPs(cluster *v2.Cluster, ips []string) (Exec, error) {
return Exec{cluster: cluster, ipList: ips}, nil
}
func (e *Exec) RunCmd(cmd string) error {
sshClient := NewSSHByCluster(e.cluster, true)
eg, _ := errgroup.WithContext(context.Background())
for _, ipAddr := range e.ipList {
ip := ipAddr
eg.Go(func() error {
return sshClient.CmdAsync(ip, cmd)
})
}
if err := eg.Wait(); err != nil {
return fmt.Errorf("failed to exec command, err: %v", err)
}
return nil
}
func (e *Exec) RunCopy(srcFilePath, dstFilePath string) error {
sshClient := NewSSHByCluster(e.cluster, true)
eg, _ := errgroup.WithContext(context.Background())
for _, ipAddr := range e.ipList {
ip := ipAddr
eg.Go(func() error {
return sshClient.Copy(ip, srcFilePath, dstFilePath)
})
}
if err := eg.Wait(); err != nil {
return fmt.Errorf("failed to copy command, err: %v", err)
}
logger.Info("transfers files success")
return nil
}