From f4c1ad199cdd31a454a60e50661db0de1747977a Mon Sep 17 00:00:00 2001
From: sunty <1172534965@qq.com>
Date: 星期五, 17 四月 2020 17:35:26 +0800
Subject: [PATCH] fix last

---
 controllers/swfsControllers.go |  242 ++++++++----------------------------------------
 1 files changed, 41 insertions(+), 201 deletions(-)

diff --git a/controllers/swfsControllers.go b/controllers/swfsControllers.go
index c4c8c38..5e009e0 100644
--- a/controllers/swfsControllers.go
+++ b/controllers/swfsControllers.go
@@ -3,12 +3,13 @@
 import (
 	"fmt"
 	"github.com/gin-gonic/gin"
-	"net/http"
-	"strconv"
 	"strings"
+	"swfs/code"
 	"swfs/config"
+	"swfs/tools/es"
+	"swfs/tools/middleware"
+	"swfs/tools/script"
 	"swfs/util"
-	"sync"
 	"time"
 )
 
@@ -18,220 +19,59 @@
 	Role string `json:"role"`
 }
 
-//淇敼
 func (sc *SeaweedfsController) UpdateSWFSServiceController(c *gin.Context) {
-	oldPeers := GetOldPeers()
-	newPeers := GetNewPeers()
-	UpdatePeers(oldPeers, newPeers)
+	script.ReplaceLineContentBySearch(es.GetNewPeers(), config.Peer, config.Server.ScriptPath, config.StartServerScript)
+	util.ResponseFormat(c, code.Success, config.Server.EsServerIp+"鏇存柊鎴愬姛")
 }
 
+// @Security ApiKeyAuth
+// @Summary 鏂拌妭鐐瑰姞鍏�
+// @Description  鏂拌妭鐐瑰姞鍏�
+// @Accept  json
+// @Produce json
+// @Tags swfs
+// @Param obj body SWFSInfo true "鍔犲叆瑙掕壊鍙傛暟"
+// @Success 200 {string} json "{"code":200, msg:"", success:true}"
+// @Failure 500 {string} json "{"code":500, msg:"", success:false}"
+// @Router /node/api-v/swfs/addSWFSNode [POST]
 func (sc *SeaweedfsController) AddSWFSNodeController(c *gin.Context) {
 	var body SWFSInfo
 	c.BindJSON(&body)
 	role := body.Role
-	nowPeers := GetNowPeersList()
 	if role == "master" {
-		AsMaster(nowPeers)
+		middleware.AsMaster(role)
+		util.ResponseFormat(c, code.AddSuccess, "鍔犲叆鑺傜偣鎴愬姛")
+		return
 	} else if role == "volume" {
-		AsVolume(nowPeers)
+		status := middleware.AsVolume()
+		if status == true {
+			util.ResponseFormat(c, code.AddSuccess, "鍔犲叆鑺傜偣鎴愬姛")
+			return
+		} else {
+			util.ResponseFormat(c, code.AddClusterInfoErr, "褰撳墠杩樻病鏈変富鑺傜偣")
+			return
+		}
+	} else if role == "master+volume" {
+		middleware.AsMaVo(role)
+		util.ResponseFormat(c, code.AddSuccess, "鍔犲叆鑺傜偣鎴愬姛")
 	} else {
+		util.ResponseFormat(c, code.RequestParamError, "閫夋嫨鑺傜偣绫诲瀷閿欒")
 		return
 	}
 
 }
 
-func ReplaceLineContentBySearch(replaceContent string) {
-	resContent := GetNowLineContent("/opt/vasystem/script/seaweedfs_start.sh", "#start_master_server")
-	replaceStr := "sed -ie 's/" + resContent + "/" + replaceContent + "/g' /opt/vasystem/seaweedfs_start.sh"
-	util.RunScript(replaceStr)
-}
-
-func (sc *SeaweedfsController) RestartMasterController(c *gin.Context) {
-	end := "sh /opt/vasystem/script/seaweedfs_stop.sh"
-	start := "sh /opt/vasystem/script/seaweedfs_start.sh"
-	util.RunScript(end)
-	util.RunScript(start)
-}
-
-func UpdateAllNodesScriptArgument(nowPeers []interface{}) {
-	for _, val := range nowPeers {
-		ip := val.(string)
-		url := "http://" + ip + ":7020/node/api-v/swfs/updateSWFSService"
-		http.Get(url)
-	}
-}
-
-func RequestMasterNodesOperation(nowPeers []interface{}) {
-	//fmt.Println("config.Server.CoreBaseUnit", config.Server.CoreBaseUnit)
-	coreBaseUnit, _ := strconv.Atoi(config.Server.CoreBaseUnit)
-	//fmt.Println("nowPeers: ", nowPeers)
-	//fmt.Println("coreBaseUnit: ", coreBaseUnit)
-	UpdateAllNodesScriptArgument(nowPeers)
-	RestartAllMaster(nowPeers, coreBaseUnit)
-}
-
-func RestartServer(ip string, timeOut int) {
-	url := "http://" + ip + ":7020/node/api-v/swfs/restartMaster"
-	http.Get(url)
-	tick := time.Tick(1 * time.Second)
-	for countdown := timeOut; countdown > 0; countdown-- {
-		verificationMasterUrl := "http://" + ip + ":6333"
-		verificationVolume1Url := "http://" + ip + ":6700"
-		verificationVolume2Url := "http://" + ip + ":6701"
-		_, masterErr := http.Get(verificationMasterUrl)
-		_, volume1Err := http.Get(verificationVolume1Url)
-		_, volume2Err := http.Get(verificationVolume2Url)
-		if masterErr == nil && volume1Err == nil && volume2Err == nil {
-			break
-		}
-		<-tick
-	}
-}
-
-func RestartAllMaster(nowPeers []interface{}, coreBaseUnit int) {
-	coreThread := len(nowPeers)/coreBaseUnit + 1
-	masterIp := make([]string, 0)
-	timeOut, _ := strconv.Atoi(config.Server.TimeOut)
-	var waitGroup sync.WaitGroup
-	for i, val := range nowPeers {
-		ip := val.(string)
-		if (i+1)%coreThread == 0 {
-			masterIp = append(masterIp, strings.Split(ip, ":")[0])
-			for i := 0; i < len(masterIp); i++ {
-				go RestartServer(masterIp[i], timeOut)
-				waitGroup.Add(1) //姣忓垱寤轰竴涓猤oroutine锛屽氨鎶婁换鍔¢槦鍒椾腑浠诲姟鐨勬暟閲�+1
-			}
-			waitGroup.Wait() //.Wait()杩欓噷浼氬彂鐢熼樆濉烇紝鐩村埌闃熷垪涓墍鏈夌殑浠诲姟缁撴潫灏变細瑙i櫎闃诲
-			masterIp = make([]string, 0)
-		} else {
-			masterIp = append(masterIp, strings.Split(ip, ":")[0])
-			if len(nowPeers) == i+1 {
-				var waitGroup sync.WaitGroup
-				for i := 0; i < len(masterIp); i++ {
-					go RestartServer(masterIp[i], timeOut)
-					waitGroup.Add(1) //姣忓垱寤轰竴涓猤oroutine锛屽氨鎶婁换鍔¢槦鍒椾腑浠诲姟鐨勬暟閲�+1
-				}
-				waitGroup.Wait() //.Wait()杩欓噷浼氬彂鐢熼樆濉烇紝鐩村埌闃熷垪涓墍鏈夌殑浠诲姟缁撴潫灏变細瑙i櫎闃诲
-				masterIp = make([]string, 0)
-				break
-			}
-		}
-		continue
-	}
-}
-
-func GetOldPeers() string {
-	str := "cat /opt/vasystem/seaweedfs_start.sh | grep peers="
-	peers := strings.Split(util.RunScript(str), "\n")[0]
-	return peers
-}
-
-func GetNowLineContent(filePath string, searchContent string) string {
-	scriptStr := "cat" + filePath + "| grep " + searchContent
-	content := strings.Split(util.RunScript(scriptStr), "\n")[0]
-	return content
-}
-
-func AsVolume(nowPeers []interface{}) {
-	ReplaceLineContentBySearch("start_master_server")
-	fmt.Println(nowPeers)
-}
-
-func AsMaster(nowPeers []interface{}) {
-	AddNewMasterToPeers()
-	RequestMasterNodesOperation(nowPeers)
-}
-
 func (sc *SeaweedfsController) RoleOfVolumeToMasterController(c *gin.Context) {
-	AsMaster(GetNowPeersList())
+	middleware.AsMaster("master+volume")
+	util.ResponseFormat(c, code.Success, "瑙掕壊娣诲姞鎴愬姛")
 }
 
-func GetNowPeersList() []interface{} {
-
-	getUrl := "http://" + config.Server.EsServerIp + ":" + config.Server.EsServerPort + "/" + config.BasicFS.IndexName + "/_search"
-	getJson := `{
-    "query": {
-        "bool": {
-            "filter": [
-                {
-                    "term": {
-						"application":"nodeOperation"
-					}
-                }
-            ]
-        }
-    },
-    "size": 1
-}`
-
-	buf, _ := util.EsReq("POST", getUrl, []byte(getJson))
-	source, _ := util.Sourcelist(buf)
-	//fmt.Println(source)
-	peers := source[0]["peers"].([]interface{})
-	return peers
-}
-
-func GetNewPeers() string {
-
-	getUrl := "http://" + config.Server.EsServerIp + ":" + config.Server.EsServerPort + "/" + config.BasicFS.IndexName + "/_search"
-	getJson := `{
-    "query": {
-        "bool": {
-            "filter": [
-                {
-                    "term": {
-						"application":"nodeOperation"
-					}
-                }
-            ]
-        }
-    },
-    "size": 1
-}`
-
-	buf, _ := util.EsReq("POST", getUrl, []byte(getJson))
-	source, _ := util.Sourcelist(buf)
-	//fmt.Println(source)
-	peers := source[0]["peers"].([]interface{})
-	fmt.Println(peers)
-	p := "peers=" + strings.Replace(strings.Trim(fmt.Sprint(peers), "[]"), " ", ",", -1)
-	return p
-}
-
-func UpdatePeers(oldPeers string, newPeers string) {
-	str := "sed -ie 's/" + oldPeers + "/" + newPeers + "/g' /opt/vasystem/seaweedfs_start.sh"
-	util.RunScript(str)
-}
-
-func AddNewMasterToPeers() (result bool) {
-	peer := config.Server.EsServerIp + ":6333"
-	addUrl := "http://" + config.Server.EsServerIp + ":" + config.Server.EsServerPort + "/" + config.BasicFS.IndexName + "/_update_by_query"
-	addJson := `{
-    "script": {
-        "lang": "painless",
-        "inline": "ctx._source.peers.add(params.newpeer)",
-        "params": {
-            "newpeer": "` + peer + `"
-        }
-    },
-    "query": {
-        "bool": {
-            "filter": [
-                {
-                    "term": {
-                        "application": "nodeOperation"
-                    }
-                }
-            ]
-        }
-    }
-}`
-	buf, _ := util.EsReq("POST", addUrl, []byte(addJson))
-	updateRes, _ := util.SourceUpdated(buf)
-	if updateRes == -1 {
-		result = false
-	} else {
-		result = true
-	}
-	return result
+func (sc *SeaweedfsController) RestartServerController(c *gin.Context) {
+	script.StopServer(config.Server.ScriptPath)
+	script.StartServer(config.Server.ScriptPath)
+	time.Sleep(time.Second * 1)
+	//fmt.Println("GetLocalStartupItem: ", GetLocalStartupItem(config.Server.ScriptPath, StartServerScript))
+	result := strings.Split(middleware.GetLocalStartupItem(config.Server.ScriptPath, config.StartServerScript), "=")[1]
+	fmt.Println("result: ", result)
+	util.ResponseFormat(c, code.Success, result)
 }

--
Gitblit v1.8.0