t1
sunty
2020-03-24 c14fefa2903a54298666e1d11df0c5013c51429d
main.go
@@ -2,10 +2,13 @@
import (
   "bytes"
   "encoding/json"
   "errors"
   "fmt"
   "io/ioutil"
   "net/http"
   "os/exec"
   "strings"
   "time"
)
@@ -13,6 +16,7 @@
   oldPeers := GetOldPeers()
   fmt.Println("oldPeers: ", oldPeers)
   //AddNewMasterToPeers()
   newPeers := GetNewPeers()
   fmt.Println("newPeers: ", newPeers)
   UpdatePeers(oldPeers, newPeers)
@@ -44,9 +48,13 @@
    "size": 1
}`
   getRes, _ := EsReq("POST", getUrl, []byte(getJson))
   fmt.Println(getRes)
   return ""
   buf, _ := EsReq("POST", getUrl, []byte(getJson))
   source, _ := 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) {
@@ -95,3 +103,81 @@
   }
   return body, nil
}
func Sourcelist(buf []byte) (sources []map[string]interface{}, err error) {
   var info interface{}
   json.Unmarshal(buf, &info)
   out, ok := info.(map[string]interface{})
   if !ok {
      return nil, errors.New("http response interface can not change map[string]interface{}")
   }
   middle, ok := out["hits"].(map[string]interface{})
   if !ok {
      return nil, errors.New("first hits change error!")
   }
   for _, in := range middle["hits"].([]interface{}) {
      tmpbuf, ok := in.(map[string]interface{})
      if !ok {
         fmt.Println("change to source error!")
         continue
      }
      source, ok := tmpbuf["_source"].(map[string]interface{})
      if !ok {
         fmt.Println("change _source error!")
         continue
      }
      sources = append(sources, source)
   }
   return sources, nil
}
func AddNewMasterToPeers() (result bool) {
   peer := "192.168.5.22:6333"
   addUrl := "http://192.168.20.10:9200/basicfs/_update_by_query"
   addJson := `{
    "script": {
        "lang": "painless",
        "inline": "ctx._source.peers.add(params.newpeer)",
        "params": {
            "newpeer": "` + peer + `"
        }
    },
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "application": "nodeOperation"
                    }
                }
            ]
        }
    }
}`
   buf, _ := EsReq("POST", addUrl, []byte(addJson))
   updateRes, _ := SourceUpdated(buf)
   if updateRes == -1 {
      result = false
   } else {
      result = true
   }
   return result
}
func SourceUpdated(buf []byte) (total int, err error) {
   var info interface{}
   json.Unmarshal(buf, &info)
   out, ok := info.(map[string]interface{})
   if !ok {
      return -1, errors.New("http response interface can not change map[string]interface{}")
   }
   middle, ok := out["updated"].(float64)
   if !ok {
      return -1, errors.New("first total change error!")
   }
   total = int(middle)
   return total, nil
}