From fea217048591823280a888b6c26f68558e51dded Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期五, 12 一月 2024 15:17:53 +0800
Subject: [PATCH] 增加admin_grpc环境变量

---
 src/cluster/cluster.go |  231 ++++++++++++++++++++++++++++++---------------------------
 1 files changed, 123 insertions(+), 108 deletions(-)

diff --git a/src/cluster/cluster.go b/src/cluster/cluster.go
index 4245064..1012b5b 100644
--- a/src/cluster/cluster.go
+++ b/src/cluster/cluster.go
@@ -1,16 +1,18 @@
 package cluster
 
 import (
-	"_/E_/git/aps_deploy/src/util"
 	"bytes"
 	"encoding/json"
 	"fmt"
+	"io/ioutil"
 	"log"
 	"net/http"
 	"os"
+	"path/filepath"
 	"strings"
 
-	"../util"
+	"basic.com/aps/aps_deploy.git/src/rancher"
+	"basic.com/aps/aps_deploy.git/src/util"
 )
 
 type Cluster struct {
@@ -20,6 +22,12 @@
 
 type ClustersResponse struct {
 	Data []Cluster `json:"data"`
+}
+
+type KubectlConfigResponse struct {
+	BaseType string `json:"baseType"`
+	Config   string `json:"config"`
+	Type     string `json:"type"`
 }
 
 type RegistrationTokenResponse struct {
@@ -112,7 +120,7 @@
 
 	req, err := http.NewRequest("GET", url, nil)
 	if err != nil {
-		return "", fmt.Errorf("failed to create cluster list request: %v", err)
+		return "", fmt.Errorf("failed to get cluster list request: %v", err)
 	}
 
 	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
@@ -147,6 +155,101 @@
 	return "", fmt.Errorf("cluster '%s' not found", clusterName)
 }
 
+func GetClusters(serverURL, bearerToken string) ([]string, error) {
+
+	url := fmt.Sprintf("%s/v3/clusters", serverURL)
+
+	req, err := http.NewRequest("GET", url, nil)
+	if err != nil {
+		return nil, fmt.Errorf("failed to get cluster list request: %v", err)
+	}
+
+	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
+
+	client := util.CreateHTTPClient()
+
+	resp, err := client.Do(req)
+	if err != nil {
+		return nil, fmt.Errorf("failed to get cluster list: %v", err)
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("failed to get cluster list: unexpected status code %d", resp.StatusCode)
+	}
+
+	// Parse the API response
+	var clustersResponse ClustersResponse
+	err = json.NewDecoder(resp.Body).Decode(&clustersResponse)
+
+	log.Println("3333333333333333333333333")
+	log.Printf("%v", resp.Body)
+	if err != nil {
+		return nil, fmt.Errorf("failed to decode cluster list response: %v", err)
+	}
+
+	var clusters = make([]string, 0)
+	// Print cluster names
+	for _, cluster := range clustersResponse.Data {
+		clusters = append(clusters, cluster.ID)
+		fmt.Printf("Cluster ID: %s, Name: %s\n", cluster.ID, cluster.Name)
+	}
+
+	return clusters, nil
+}
+
+func GetKubectlConfig(serverURL, bearerToken, clusterName string) (string, error) {
+
+	url := fmt.Sprintf("%s/v3/clusters/%s?action=generateKubeconfig", serverURL, clusterName)
+
+	req, err := http.NewRequest("POST", url, nil)
+	if err != nil {
+		return "", fmt.Errorf("failed to get cluster list request: %v", err)
+	}
+
+	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Accept", "application/json")
+
+	client := util.CreateHTTPClient()
+
+	resp, err := client.Do(req)
+	if err != nil {
+		return "", fmt.Errorf("failed to get cluster list: %v", err)
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("failed to get cluster list: unexpected status code %d", resp.StatusCode)
+	}
+
+	// Parse the API response
+	var kubectlConfig KubectlConfigResponse
+	err = json.NewDecoder(resp.Body).Decode(&kubectlConfig)
+
+	if err != nil {
+		return "", fmt.Errorf("failed to decode cluster list response: %v", err)
+	}
+
+	// 淇濆瓨 kubeconfig 鍒版枃浠�
+	homeDir, err := os.UserHomeDir()
+	if err != nil {
+		log.Fatalf("Failed to get home directory: %v", err)
+	}
+	kubeconfigDir := filepath.Join(homeDir, ".kube", clusterName)
+	err = os.MkdirAll(kubeconfigDir, 0700)
+	if err != nil {
+		log.Fatalf("Failed to create .kube directory: %v", err)
+	}
+	kubeconfigPath := filepath.Join(kubeconfigDir, "config")
+	err = ioutil.WriteFile(kubeconfigPath, []byte(kubectlConfig.Config), 0600)
+	if err != nil {
+		log.Fatalf("Failed to save kubeconfig: %v", err)
+	}
+
+	return kubectlConfig.Config, nil
+}
+
 type Node struct {
 	ClusterName string   `json:"clusterName"`
 	Roles       []string `json:"roles"`
@@ -154,11 +257,6 @@
 	SSHUsername string   `json:"sshUsername"`
 	SSHPassword string   `json:"sshPassword"`
 	SSHPort     int      `json:"sshPort"`
-}
-
-type RancherConfig struct {
-	RancherURL  string `json:"rancherURL"`
-	BearerToken string `json:"bearerToken"`
 }
 
 type ClusterCreateRequest struct {
@@ -200,7 +298,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 +318,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) {
 	// 妫�鏌ancher瀹瑰櫒鏄惁宸茶繍琛�
 	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 +341,7 @@
 func IsRancherAgentInstalled(ip, username, password string, sshPort int) (bool, error) {
 	// 妫�鏌ancher瀹瑰櫒鏄惁宸茶繍琛�
 	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)
@@ -252,124 +350,41 @@
 	return true, nil
 }
 
-func CreateCluster(rancherConfig RancherConfig, clusterName string) error {
+func CreateCluster(rancherClusterConfig rancher.RancherClusterConfig, clusterName string) (string, error) {
 	requestBody := createClusterData(clusterName)
+	fmt.Println(rancherClusterConfig.RancherURL)
 
-	url := fmt.Sprintf("%s/v3/clusters", rancherConfig.RancherURL)
+	url := fmt.Sprintf("%s/v3/clusters", rancherClusterConfig.RancherURL)
+	fmt.Println("url:    ", url)
+	fmt.Println("body:    ", requestBody)
 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
 	if err != nil {
-		return fmt.Errorf("Failed to create HTTP request: %v", err)
+		return "", fmt.Errorf("Failed to create HTTP request: %v", err)
 	}
 
-	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", rancherConfig.BearerToken))
+	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", rancherClusterConfig.BearerToken))
 	req.Header.Set("Content-Type", "application/json")
 
 	client := util.CreateHTTPClient()
 
 	resp, err := client.Do(req)
 	if err != nil {
-		return fmt.Errorf("Failed to send HTTP request: %v", err)
+		return "", fmt.Errorf("Failed to send HTTP request: %v", err)
 	}
 	defer resp.Body.Close()
 
 	if resp.StatusCode != http.StatusCreated {
-		return fmt.Errorf("Failed to create cluster, status code: %d", resp.StatusCode)
+		fmt.Println("1111111111111111111111111111    ", resp)
+		return "", fmt.Errorf("Failed to create cluster, status code: %d", resp.StatusCode)
 	}
 
 	var responseBody ClusterCreateResponse
 	err = json.NewDecoder(resp.Body).Decode(&responseBody)
 	if err != nil {
-		return fmt.Errorf("Failed to decode response body: %v", err)
+		return "", fmt.Errorf("Failed to decode response body: %v", err)
 	}
 
 	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)
+	return responseBody.ID, nil
 }

--
Gitblit v1.8.0