cheliequan
2023-05-24 ab70148fc0213a4523d976099a18e438cb2ed067
更新代码
1个文件已删除
1个文件已添加
6个文件已修改
442 ■■■■ 已修改文件
go.sum 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/cluster/cluster.go 101 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/k8s/create.go 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/k8s/delete.go 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/main.go 153 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/rancher/ranche.go 110 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/rancher/rancher.go 60 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/util/util.go 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
go.sum
@@ -160,12 +160,6 @@
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rancher/client-go v1.5.1 h1:RqwrSLR+sgaXTC/0nraGDDB58fFySWuMyANCpxdXN2I=
github.com/rancher/client-go v1.25.4-rancher1 h1:9MlBC8QbgngUkhNzMR8rZmmCIj6WNRHFOnYiwC2Kty4=
github.com/rancher/go-rancher v0.1.0 h1:YIKWwe5giu2WICfyCcGqX+m4XTRbMpA8vzLxl1Kwb7w=
github.com/rancher/go-rancher v0.1.0/go.mod h1:7oQvGNiJsGvrUgB+7AH8bmdzuR0uhULfwKb43Ht0hUk=
github.com/rancherio/go-rancher v0.1.0 h1:rwAwhMXyNdA82hglnWxKwkoAvQ8UKo0i0SudM1mTYfY=
github.com/rancherio/go-rancher v0.1.0/go.mod h1:VXd0Uc4WrlOE85WC4Syk7rY+VNPxBhHXoTgcB1Gquo0=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk=
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
src/cluster/cluster.go
@@ -1,16 +1,14 @@
package cluster
import (
    "_/E_/git/aps_deploy/src/util"
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "os"
    "strings"
    "../util"
    "basic.com/aps/aps_deploy.git/src/util"
)
type Cluster struct {
@@ -200,7 +198,7 @@
// Deploy Kubernetes roles on a node using SSH
func Deployk8sRolesOnNode(nodeIP, sshUsername, sshPassword, remoteSSHCommand string, sshPort int, roles []string) error {
    rancherAgentInstalled, err := isRancherAgentInstalled(nodeIP, sshUsername, sshPassword, sshPort)
    rancherAgentInstalled, err := IsRancherAgentInstalled(nodeIP, sshUsername, sshPassword, sshPort)
    if err == nil {
        return nil
    }
@@ -220,18 +218,18 @@
            }
        }
        _, err := sshExec(nodeIP, sshUsername, sshPassword, remoteSSHCommand, sshPort)
        _, err := util.SSHExec(nodeIP, sshUsername, sshPassword, remoteSSHCommand, sshPort)
        if err != nil {
            return fmt.Errorf("failed to deploy Kubernetes roles on the remote server: %v", err)
        }
        return nil
    }
    return nil
}
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 := sshExec(ip, username, password, checkRancherCommand, sshPort)
    _, err := util.SSHExec(ip, username, password, checkRancherCommand, sshPort)
    if err != nil {
        // 如果执行命令出错,则说明Rancher未安装或发生其他错误
        return false, fmt.Errorf("failed to check Rancher installation: %v", err)
@@ -243,7 +241,7 @@
func IsRancherAgentInstalled(ip, username, password string, sshPort int) (bool, error) {
    // 检查Rancher容器是否已运行
    checkRancherCommand := "sudo docker ps --format '{{.Image}}' | grep -q rancher/rancher-agent:v2.5."
    _, err := sshExec(ip, username, password, checkRancherCommand, sshPort)
    _, err := util.SSHExec(ip, username, password, checkRancherCommand, sshPort)
    if err != nil {
        // 如果执行命令出错,则说明Rancher未安装或发生其他错误
        return false, fmt.Errorf("failed to check Rancher installation: %v", err)
@@ -285,91 +283,4 @@
    fmt.Printf("Cluster created: ID=%s, Name=%s\n", responseBody.ID, responseBody.Name)
    return nil
}
func main() {
    clusterName := "kubernetus"
    nodes := []Node{
        {
            ClusterName: clusterName,
            Roles:       []string{"etcd", "controlplane", "worker"},
            IP:          "192.168.20.189",
            SSHUsername: "basic",
            SSHPassword: "123",
            SSHPort:     22,
        },
        {
            ClusterName: clusterName,
            Roles:       []string{"worker"},
            IP:          "192.168.20.10",
            SSHUsername: "basic",
            SSHPassword: "123",
            SSHPort:     22,
        },
        {
            ClusterName: clusterName,
            Roles:       []string{"worker"},
            IP:          "192.168.20.115",
            SSHUsername: "basic",
            SSHPassword: "alien123",
            SSHPort:     22,
        },
        // Add more nodes here if needed
    }
    // Create the cluster
    // Rancher configuration
    /*rancherConfig := RancherConfig{
        RancherURL:  "https://192.168.20.119:8443",
        BearerToken: "token-nnrsc:w68zdt8s47fnpjd5xqdl5hhzpz4j2d56kt5nx49nsswcbpdzc28kh5",
    }*/
    rancherConfig := RancherConfig{
        RancherURL:  "https://192.168.20.189:8443",
        BearerToken: "token-t4cdf:h7zhmbvbzdvd9mmjw8zmt8rh4m7rl5gtqpqljlhl9tlr2z26j9lf4l",
    }
    //    Deploy clusterId
    clusterID, err := GetClusterID(rancherConfig.RancherURL, rancherConfig.BearerToken, clusterName)
    if err != nil {
        log.Fatal(err)
        err = CreateCluster(rancherConfig, clusterName)
        if err != nil {
            log.Fatalf("Failed to create cluster: %v", err)
        }
        fmt.Printf("Cluster created: %s\n", clusterName)
        clusterID, err = GetClusterID(rancherConfig.RancherURL, rancherConfig.BearerToken, clusterName)
        if err != nil {
            log.Fatal(err)
        }
    }
    fmt.Println(clusterID)
    //    Deploy nodeCommand
    nodeCommand, err := GetNodeCommand(rancherConfig.RancherURL, rancherConfig.BearerToken, clusterID)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(nodeCommand)
    for _, node := range nodes {
        //Deploy Docker on each node
        err = util.InstallDocker(node.IP, node.SSHUsername, node.SSHPassword, node.SSHPort)
        if err != nil {
            log.Fatal(err)
        }
        // Deploy Kubectl on each node
        err = util.InstallKubectl(node.IP, node.SSHUsername, node.SSHPassword, node.SSHPort)
        if err != nil {
            log.Fatal(err)
        }
        // Deploy Kubernetes roles on each node
        err = Deployk8sRolesOnNode(node.IP, node.SSHUsername, node.SSHPassword, nodeCommand, node.SSHPort, node.Roles)
        if err != nil {
            log.Fatal(err)
        }
    }
    os.Exit(0)
}
src/k8s/create.go
@@ -8,7 +8,7 @@
    "math/rand"
    "path/filepath"
    "../util"
    "basic.com/aps/aps_deploy.git/src/util"
    appsv1 "k8s.io/api/apps/v1"
    apiv1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/api/errors"
src/k8s/delete.go
@@ -6,7 +6,7 @@
    "fmt"
    "path/filepath"
    "../util"
    "basic.com/aps/aps_deploy.git/src/util"
    "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
src/main/main.go
@@ -8,11 +8,13 @@
    "path/filepath"
    "time"
    "../util"
    "basic.com/aps/aps_deploy.git/src/cluster"
    "basic.com/aps/aps_deploy.git/src/rancher"
    "basic.com/aps/aps_deploy.git/src/util"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "../k8s"
    "basic.com/aps/aps_deploy.git/src/k8s"
)
var (
@@ -22,10 +24,143 @@
    namespaces          = []string{"guangsheng", "geruimi", "tongsheng"}
)
type Node struct {
    ClusterName string   `json:"clusterName"`
    Roles       []string `json:"roles"`
    IP          string   `json:"ip"`
    SSHUsername string   `json:"sshUsername"`
    SSHPassword string   `json:"sshPassword"`
    SSHPort     int      `json:"sshPort"`
}
func rancher_install_test() {
    nodes := []Node{
        {
            Roles:       []string{"etcd", "controlplane", "worker"},
            IP:          "192.168.20.189",
            SSHUsername: "basic",
            SSHPassword: "123",
            SSHPort:     22,
        },
        {
            Roles:       []string{"worker"},
            IP:          "192.168.20.10",
            SSHUsername: "basic",
            SSHPassword: "123",
            SSHPort:     22,
        },
        {
            Roles:       []string{"worker"},
            IP:          "192.168.20.115",
            SSHUsername: "basic",
            SSHPassword: "alien123",
            SSHPort:     22,
        },
        // Add more nodes here if needed
    }
    //install rancher on master node
    err := rancher.InstallDockerAndRancher(nodes[0].IP, nodes[0].SSHUsername, nodes[0].SSHPassword, nodes[0].SSHPort)
    if err != nil {
        log.Fatalf("Failed to install Rancher: %v", err)
    }
    os.Exit(0)
}
func cluster_test() {
    clusterName := "kubernetus"
    nodes := []Node{
        {
            ClusterName: clusterName,
            Roles:       []string{"etcd", "controlplane", "worker"},
            IP:          "192.168.20.189",
            SSHUsername: "basic",
            SSHPassword: "123",
            SSHPort:     22,
        },
        {
            ClusterName: clusterName,
            Roles:       []string{"worker"},
            IP:          "192.168.20.10",
            SSHUsername: "basic",
            SSHPassword: "123",
            SSHPort:     22,
        },
        {
            ClusterName: clusterName,
            Roles:       []string{"worker"},
            IP:          "192.168.20.115",
            SSHUsername: "basic",
            SSHPassword: "alien123",
            SSHPort:     22,
        },
        // Add more nodes here if needed
    }
    // Create the cluster
    // Rancher configuration
    /*rancherConfig := RancherConfig{
        RancherURL:  "https://192.168.20.119:8443",
        BearerToken: "token-nnrsc:w68zdt8s47fnpjd5xqdl5hhzpz4j2d56kt5nx49nsswcbpdzc28kh5",
    }*/
    rancherConfig := rancher.RancherConfig{
        RancherURL:  "https://192.168.20.189:8443",
        BearerToken: "token-t4cdf:h7zhmbvbzdvd9mmjw8zmt8rh4m7rl5gtqpqljlhl9tlr2z26j9lf4l",
    }
    //    Deploy clusterId
    clusterID, err := cluster.GetClusterID(rancherConfig.RancherURL, rancherConfig.BearerToken, clusterName)
    if err != nil {
        log.Fatal(err)
        err = cluster.CreateCluster(rancherConfig, clusterName)
        if err != nil {
            log.Fatalf("Failed to create cluster: %v", err)
        }
        fmt.Printf("Cluster created: %s\n", clusterName)
        clusterID, err = cluster.GetClusterID(rancherConfig.RancherURL, rancherConfig.BearerToken, clusterName)
        if err != nil {
            log.Fatal(err)
        }
    }
    fmt.Println(clusterID)
    //    Deploy nodeCommand
    nodeCommand, err := cluster.GetNodeCommand(rancherConfig.RancherURL, rancherConfig.BearerToken, clusterID)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(nodeCommand)
    for _, node := range nodes {
        //Deploy Docker on each node
        err = util.InstallDocker(node.IP, node.SSHUsername, node.SSHPassword, node.SSHPort)
        if err != nil {
            log.Fatal(err)
        }
        // Deploy Kubectl on each node
        err = util.InstallKubectl(node.IP, node.SSHUsername, node.SSHPassword, node.SSHPort)
        if err != nil {
            log.Fatal(err)
        }
        // Deploy Kubernetes roles on each node
        err = cluster.Deployk8sRolesOnNode(node.IP, node.SSHUsername, node.SSHPassword, nodeCommand, node.SSHPort, node.Roles)
        if err != nil {
            log.Fatal(err)
        }
    }
    os.Exit(0)
}
func main() {
    createCmd := flag.NewFlagSet("create", flag.ExitOnError)
    deleteCmd := flag.NewFlagSet("delete", flag.ExitOnError)
    testCmd := flag.NewFlagSet("test", flag.ExitOnError)
    clusterCmd := flag.NewFlagSet("cluster", flag.ExitOnError)
    rancherInstallCmd := flag.NewFlagSet("rancher_install", flag.ExitOnError)
    createNamespace := createCmd.String("ns", "", "Namespace name")
    createDeployment := createCmd.String("deployment", "", "Deployment name")
@@ -36,7 +171,7 @@
    deleteService := deleteCmd.String("service", "", "Service name")
    if len(os.Args) < 2 {
        fmt.Println("create/delete/test command is required")
        fmt.Println("create/delete/test/cluster/rancher_install command is required")
        os.Exit(1)
    }
@@ -47,6 +182,10 @@
        deleteCmd.Parse(os.Args[2:])
    case "test":
        testCmd.Parse(os.Args[2:])
    case "cluster":
        clusterCmd.Parse(os.Args[2:])
    case "rancher_install":
        rancherInstallCmd.Parse(os.Args[2:])
    default:
        flag.PrintDefaults()
        os.Exit(1)
@@ -144,4 +283,12 @@
        fmt.Println("Resources deleted.")
    }
    if clusterCmd.Parsed() {
        cluster_test()
    }
    if rancherInstallCmd.Parsed() {
        rancher_install_test()
    }
}
src/rancher/ranche.go
File was deleted
src/rancher/rancher.go
New file
@@ -0,0 +1,60 @@
package rancher
import (
    "fmt"
    "basic.com/aps/aps_deploy.git/src/util"
)
type RancherConfig struct {
    RancherURL  string `json:"rancherURL"`
    BearerToken string `json:"bearerToken"`
}
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
}
src/util/util.go
@@ -100,7 +100,7 @@
func InstallDocker(nodeIP, sshUsername, sshPassword string, sshPort int) error {
    // 检查Docker是否已安装
    checkCommand := "which docker"
    _, err := sshExec(nodeIP, sshUsername, sshPassword, checkCommand, sshPort)
    _, err := SSHExec(nodeIP, sshUsername, sshPassword, checkCommand, sshPort)
    if err == nil {
        fmt.Println("Docker is already installed on the remote server.")
        return nil
@@ -108,7 +108,7 @@
    // 安装Docker
    installCommand := "sudo curl -fsSL https://get.docker.com -o get-docker.sh && sudo sh get-docker.sh"
    _, err = sshExec(nodeIP, sshUsername, sshPassword, installCommand, sshPort)
    _, err = SSHExec(nodeIP, sshUsername, sshPassword, installCommand, sshPort)
    if err != nil {
        return fmt.Errorf("failed to install Docker on the remote server: %v", err)
    }
@@ -129,7 +129,7 @@
func InstallKubectl(nodeIP, sshUsername, sshPassword string, sshPort int) error {
    // 检查kubectl是否已安装
    checkCommand := "which kubectl"
    _, err := sshExec(nodeIP, sshUsername, sshPassword, checkCommand, sshPort)
    _, err := SSHExec(nodeIP, sshUsername, sshPassword, checkCommand, sshPort)
    if err == nil {
        fmt.Println("kubectl is already installed on the remote server.")
        return nil
@@ -137,7 +137,7 @@
    // 安装kubectl
    installCommand := "sudo curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && sudo chmod +x kubectl && sudo mv kubectl /usr/local/bin/"
    _, err = sshExec(nodeIP, sshUsername, sshPassword, installCommand, sshPort)
    _, err = SSHExec(nodeIP, sshUsername, sshPassword, installCommand, sshPort)
    if err != nil {
        return fmt.Errorf("failed to install kubectl on the remote server: %v", err)
    }