cheliequan
2023-05-31 d3a63ffbec643f7a2746dfe2db2313492ef163af
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
package rancher
 
import (
    "fmt"
 
    "basic.com/aps/aps_deploy.git/src/util"
)
 
 
type Node struct {
    Roles       []string `json:"roles"`
    IP          string   `json:"ip"`
    SSHUsername string   `json:"sshUsername"`
    SSHPassword string   `json:"sshPassword"`
    SSHPort     int      `json:"sshPort"`
}
 
 
type RancherClusterConfig struct {
    RancherURL  string `json:"rancherURL"`
    BearerToken string `json:"bearerToken"`
    ClusterName string   `mapstructure:"ClusterName"`
    Nodes       []Node   `mapstructure:"Nodes"`
}
 
 
func isRancherInstalled(ip, username, password string, sshPort int) (bool, error) {
    // 检查Rancher容器是否已运行
    checkRancherCommand := "sudo docker ps --format '{{.Image}}' | grep -q rancher/rancher:v2.5.17"
    _, err := util.SSHExec(ip, username, password, checkRancherCommand, sshPort)
    if err != nil {
        // 如果执行命令出错,则说明Rancher未安装或发生其他错误
        return false, fmt.Errorf("failed to check Rancher installation: %v", err)
    }
 
    return true, nil
}
 
func InstallRancher(ip, username, password string, sshPort int) error {
    rancherInstalled, err := isRancherInstalled(ip, username, password, sshPort)
    if err == nil {
        return nil
    }
 
    if !rancherInstalled {
        // 安装Rancher命令
        rancherCommand := "sudo docker run --privileged  -d --restart=unless-stopped -p 8081:80 -p 8443:443  -v /opt/rancher:/var/lib/rancher registry.cn-hangzhou.aliyuncs.com/rancher/rancher:v2.5.17"
        _, err = util.SSHExec(ip, username, password, rancherCommand, sshPort)
        if err != nil {
            return fmt.Errorf("failed to install Rancher: %v", err)
        }
    } else {
        fmt.Println("Rancher is already installed on the remote server.")
    }
 
    return nil
}
 
func InstallDockerAndRancher(ip, username, password string, sshPort int) error {
    // 安装Docker命令
    err := util.InstallDocker(ip, username, password, sshPort)
    if err != nil {
        return err
    }
 
    // 安装Rancher命令
    err = InstallRancher(ip, username, password, sshPort)
    if err != nil {
        return err
    }
 
    return nil
}