sunty
2020-04-10 04c7a106e80800a62db8515a7452f2fc1b73693b
add swag code respformat a lot code about server
1个文件已添加
6个文件已修改
182 ■■■■■ 已修改文件
code/code.go 24 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
config/config.go 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/swfsControllers.go 120 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
go.mod 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
main.go 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/router.go 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
util/util.go 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
code/code.go
New file
@@ -0,0 +1,24 @@
package code
import "net/http"
// Code 错误输出数据结构
type Code struct {
    Status  int    `json:"status"`  // HTTP 状态
    Success bool   `json:"success"` // 成功或者失败
    Message string `json:"msg"`     // 描述信息
}
var (
    LicenseExpired = &Code{http.StatusForbidden, false, "license expired"}
    // Success 请求处理成功
    Success       = &Code{http.StatusOK, true, "请求处理成功"}
    AddSuccess    = &Code{http.StatusOK, true, "计入成功"}
    UpdateSuccess = &Code{http.StatusOK, true, "更新成功"}
    UpdateFail    = &Code{http.StatusBadRequest, false, "更新失败"}
    DelSuccess    = &Code{http.StatusOK, true, "删除成功"}
    // RequestParamError 请求参数错误
    RequestParamError  = &Code{http.StatusBadRequest, false, "请求参数有误"}
    CreateFirstNodeErr = &Code{http.StatusInternalServerError, false, "创建节点失败!"}
    AddClusterInfoErr  = &Code{http.StatusInternalServerError, false, "加入节点失败!"}
)
config/config.go
@@ -10,6 +10,7 @@
    EsServerPort string `mapstructure: "esServerPort"`
    CoreBaseUnit string `mapstructure: "coreBaseUnit"`
    TimeOut      string `mapstructure: "timeOut"`
    ScriptPath   string `mapstructure: scriptPath`
}
type elastic struct {
controllers/swfsControllers.go
@@ -6,10 +6,18 @@
    "net/http"
    "strconv"
    "strings"
    "swfs/code"
    "swfs/config"
    "swfs/util"
    "sync"
    "time"
)
const (
    StartServerScript   = "seaweedfs_start.sh"
    StopServerScript    = "seaweedfs_stop.sh"
    StartScriptAsVolume = "option=1"
    StartScriptAsMaster = "option=2"
)
type SeaweedfsController struct{}
@@ -18,13 +26,23 @@
    Role string `json:"role"`
}
//修改
func (sc *SeaweedfsController) UpdateSWFSServiceController(c *gin.Context) {
    oldPeers := GetOldPeers()
    oldPeers := GetOldPeers(config.Server.ScriptPath, StartServerScript)
    newPeers := GetNewPeers()
    UpdatePeers(oldPeers, newPeers)
    UpdatePeers(config.Server.ScriptPath, StartServerScript, oldPeers, newPeers)
    ReplaceLineContentBySearch(StartScriptAsVolume, config.Server.ScriptPath, StartServerScript)
}
// @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)
@@ -32,27 +50,47 @@
    nowPeers := GetNowPeersList()
    if role == "master" {
        AsMaster(nowPeers)
        util.ResponseFormat(c, code.AddSuccess, "加入节点成功")
        return
    } else if role == "volume" {
        AsVolume(nowPeers)
        util.ResponseFormat(c, code.AddSuccess, "加入节点成功")
        return
    } 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) RoleOfVolumeToMasterController(c *gin.Context) {
    AsMaster(GetNowPeersList())
}
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)
    StopServer(config.Server.ScriptPath)
    time.Sleep(time.Second * 1)
    StartServer(config.Server.ScriptPath)
}
//启动服务
func StartServer(scriptPath string) {
    util.RunScript("sh " + scriptPath + StartServerScript)
}
//停止服务
func StopServer(scriptPath string) {
    util.RunScript("sh " + scriptPath + StopServerScript)
}
//根据搜索内容替换整行内容
func ReplaceLineContentBySearch(replaceContent string, scriptPath string, scriptFile string) {
    resContent := GetNowLineContent(scriptPath+"/"+scriptFile, "option=")
    replaceStr := "sed -ie 's/" + resContent + "/" + replaceContent + "/g' " + scriptPath + "/" + scriptFile
    util.RunScript(replaceStr)
}
//更新所有节点的脚本参数
func UpdateAllNodesScriptArgument(nowPeers []interface{}) {
    for _, val := range nowPeers {
        ip := val.(string)
@@ -61,15 +99,17 @@
    }
}
//请求作为主节点操作流程
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)
    RestartAllServer(nowPeers, coreBaseUnit)
}
//重启其他节点服务并验证
func RestartServer(ip string, timeOut int) {
    url := "http://" + ip + ":7020/node/api-v/swfs/restartMaster"
    http.Get(url)
@@ -88,7 +128,8 @@
    }
}
func RestartAllMaster(nowPeers []interface{}, coreBaseUnit int) {
//构建重启流程
func RestartAllServer(nowPeers []interface{}, coreBaseUnit int) {
    coreThread := len(nowPeers)/coreBaseUnit + 1
    masterIp := make([]string, 0)
    timeOut, _ := strconv.Atoi(config.Server.TimeOut)
@@ -120,34 +161,30 @@
    }
}
func GetOldPeers() string {
    str := "cat /opt/vasystem/seaweedfs_start.sh | grep peers="
    peers := strings.Split(util.RunScript(str), "\n")[0]
    return peers
//获取本地以使用集群表单
func GetOldPeers(scriptPath string, scriptFile string) string {
    return GetNowLineContent(scriptPath+"/"+scriptFile, "peers=")
}
//获取查找内容当前行内容
func GetNowLineContent(filePath string, searchContent string) string {
    scriptStr := "cat" + filePath + "| grep " + searchContent
    content := strings.Split(util.RunScript(scriptStr), "\n")[0]
    return content
    return strings.Split(util.RunScript(scriptStr), "\n")[0]
}
//作为数据节点加入
func AsVolume(nowPeers []interface{}) {
    ReplaceLineContentBySearch("start_master_server")
    fmt.Println(nowPeers)
    ReplaceLineContentBySearch(StartScriptAsVolume, config.Server.ScriptPath, StartServerScript)
}
//作为主节点加入(默认包含数据节点)
func AsMaster(nowPeers []interface{}) {
    AddNewMasterToPeers()
    RequestMasterNodesOperation(nowPeers)
}
func (sc *SeaweedfsController) RoleOfVolumeToMasterController(c *gin.Context) {
    AsMaster(GetNowPeersList())
}
//获取当前集群列表
func GetNowPeersList() []interface{} {
    getUrl := "http://" + config.Server.EsServerIp + ":" + config.Server.EsServerPort + "/" + config.BasicFS.IndexName + "/_search"
    getJson := `{
    "query": {
@@ -166,43 +203,24 @@
    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)
    peers := GetNowPeersList()
    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"
//更新本地集群列表
func UpdatePeers(scriptPath string, scriptFile string, oldPeers string, newPeers string) {
    str := "sed -ie 's/" + oldPeers + "/" + newPeers + "/g' " + scriptPath + "/" + scriptFile
    util.RunScript(str)
}
//向集群加入新的master
func AddNewMasterToPeers() (result bool) {
    peer := config.Server.EsServerIp + ":6333"
    addUrl := "http://" + config.Server.EsServerIp + ":" + config.Server.EsServerPort + "/" + config.BasicFS.IndexName + "/_update_by_query"
go.mod
@@ -1,8 +1,11 @@
module test
module swfs
go 1.12
require (
    github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc
    github.com/gin-gonic/gin v1.6.1
    github.com/spf13/viper v1.6.2
    github.com/swaggo/gin-swagger v1.2.0
    github.com/swaggo/swag v1.5.1
)
main.go
@@ -2,7 +2,8 @@
import (
    "flag"
    "test/config"
    "swfs/config"
    "swfs/router"
)
var env = flag.String("pro", "pro", "read storage info")
@@ -12,5 +13,6 @@
}
func main() {
    r := router.NewRouter()
    r.Run("0.0.0.0:7020")
}
router/router.go
@@ -2,20 +2,28 @@
import (
    "github.com/gin-gonic/gin"
    "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
    "swfs/controllers"
    _ "swfs/docs"
)
func NewRouter() *gin.Engine {
    r := gin.Default()
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    swfsController := new(controllers.SeaweedfsController)
    urlPrefix := "/node/api-v"
    swfsApi := r.Group(urlPrefix + "/swfs")
    {
        swfsApi.GET("/addNode", swfsController.AddSWFSNodeController)
        swfsApi.POST("/addSWFSNode", swfsController.AddSWFSNodeController)
        swfsApi.GET("/updateSWFSService", swfsController.UpdateSWFSServiceController)
        swfsApi.GET("/restartMaster", swfsController.RestartMasterController)
        swfsApi.GET("roleOfVolumeToMaster", swfsController.RoleOfVolumeToMasterController)
    }
    // 文件 上传
    r.Static("static", "./static") // 静态文件
    //外部访问swagger.json
    r.StaticFile("/swagger.json", "./docs/swagger.json")
    return r
}
util/util.go
@@ -5,9 +5,11 @@
    "encoding/json"
    "errors"
    "fmt"
    "github.com/gin-gonic/gin"
    "io/ioutil"
    "net/http"
    "os/exec"
    "swfs/code"
    "time"
)
@@ -98,3 +100,17 @@
    total = int(middle)
    return total, nil
}
// ResponseFormat 返回数据格式化
func ResponseFormat(c *gin.Context, respStatus *code.Code, data interface{}) {
    if respStatus == nil {
        respStatus = code.RequestParamError
    }
    c.JSON(respStatus.Status, gin.H{
        "code":    respStatus.Status,
        "success": respStatus.Success,
        "msg":     respStatus.Message,
        "data":    data,
    })
    return
}