Commit 7884dc8b authored by root's avatar root

fmt

parent 3fb8e362
......@@ -8,10 +8,10 @@ import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
clog "github.com/33cn/chain33/common/log"
log "github.com/33cn/chain33/common/log/log15"
"net/http"
"time"
)
func init() {
......@@ -26,7 +26,6 @@ func init() {
var tlog = log.New("main", "main.go")
// @title Golang Gin API
// @version 1.0
// @description An example of gin
......@@ -38,7 +37,7 @@ func main() {
//区域网广播设备
go app.Broadcast()
//节点操作
go app.BityuanJob(time.NewTicker(time.Second*30))
go app.BityuanJob(time.NewTicker(time.Second * 30))
//树莓派内置程序操作
go app.PaiJob(time.NewTicker(time.Second * 50))
//go app.ClearLog(time.NewTicker(time.Hour*1))
......@@ -60,7 +59,7 @@ func main() {
MaxHeaderBytes: maxHeaderBytes,
}
tlog.Info("[info] start http server listening ", "port",endPoint)
tlog.Info("[info] start http server listening ", "port", endPoint)
server.ListenAndServe()
select {}
// If you want Graceful Restart, you need a Unix system and download github.com/fvbock/endless
......
package app
import (
"chain33-pai/service/pai_service"
"chain33-pai/pkg/util"
"chain33-pai/service/pai_service"
"net"
"time"
)
var (
serial string
serial string
runningAddr *net.IPNet
)
func Broadcast() {
func Broadcast() {
var pai pai_service.Pai
send := "hello world"
if serial != "" {
......@@ -25,10 +25,10 @@ func Broadcast() {
}
}
//ip 会变化
ip,err := util.GetLocalIpByName("wlan0")
ip, err := util.GetLocalIpByName("wlan0")
if err != nil || ip == nil {
tlog.Error("broadcast",err)
ip,err = util.GetLocalIpByName("eth0")
tlog.Error("broadcast", err)
ip, err = util.GetLocalIpByName("eth0")
if err != nil {
panic(err)
}
......@@ -46,21 +46,21 @@ func Broadcast() {
}
conn, err := net.DialUDP("udp", &laddr, &raddr)
if err != nil {
tlog.Error("broadcast","net error ",err)
tlog.Error("broadcast", "net error ", err)
panic(err)
}
for {
//ip 会变化
ip,err = util.GetLocalIpByName("wlan0")
ip, err = util.GetLocalIpByName("wlan0")
if err != nil || ip == nil {
tlog.Error("broadcast","err","wlan0 not exists")
ip,err = util.GetLocalIpByName("eth0")
tlog.Error("broadcast", "err", "wlan0 not exists")
ip, err = util.GetLocalIpByName("eth0")
if err != nil {
tlog.Error("broadcast","err","eth0 not exists")
time.Sleep(time.Second*1)
tlog.Error("broadcast", "err", "eth0 not exists")
time.Sleep(time.Second * 1)
continue
}
tlog.Info("broadcast","eth0",ip.IP.String())
tlog.Info("broadcast", "eth0", ip.IP.String())
}
if runningAddr != nil && runningAddr.IP.String() != ip.IP.String() {
......@@ -76,22 +76,22 @@ func Broadcast() {
conn.Close()
conn, err = net.DialUDP("udp", &laddr, &raddr)
if err != nil {
tlog.Error("broadcast","net error ",err)
tlog.Error("broadcast", "net error ", err)
panic(err)
}
tlog.Info("broadcast","oldip",runningAddr.IP.String(),"newip",ip.IP.String())
tlog.Info("broadcast", "oldip", runningAddr.IP.String(), "newip", ip.IP.String())
}
runningAddr = ip
_, err = conn.Write([]byte(send))
if err != nil{
tlog.Error("broadcast ","err",err)
time.Sleep(time.Second*1)
if err != nil {
tlog.Error("broadcast ", "err", err)
time.Sleep(time.Second * 1)
continue
}
tlog.Info("broadcast","ip:",ip.IP.String(),"udp",send)
time.Sleep(time.Second*1)
tlog.Info("broadcast", "ip:", ip.IP.String(), "udp", send)
time.Sleep(time.Second * 1)
}
......
......@@ -7,5 +7,5 @@ type MsgType struct {
}
func Setup() {
JobChan = make(chan MsgType,10)
JobChan = make(chan MsgType, 10)
}
......@@ -2,30 +2,30 @@ package app
import (
"bytes"
"chain33-pai/pkg/chain33"
"chain33-pai/pkg/pai"
"chain33-pai/pkg/setting"
"chain33-pai/pkg/util"
"chain33-pai/service/pai_service"
"encoding/json"
"errors"
"fmt"
"io"
"github.com/33cn/chain33/common/log"
"github.com/33cn/chain33/types"
types2 "github.com/33cn/plugin/plugin/dapp/ticket/types"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"strings"
"time"
"io/ioutil"
"chain33-pai/pkg/util"
"github.com/33cn/chain33/types"
"chain33-pai/service/pai_service"
"encoding/json"
"chain33-pai/pkg/chain33"
types2 "github.com/33cn/plugin/plugin/dapp/ticket/types"
"strconv"
"strings"
"sync"
"chain33-pai/pkg/pai"
"time"
)
var tlog = log.New("pkg","app")
var tlog = log.New("pkg", "app")
type ProcessInfo struct {
PName string `json:"p_name"`
......@@ -35,21 +35,20 @@ type ProcessInfo struct {
}
type updateInfo struct {
Flag bool `json:"flag"` //接口处理完成
Total int64 `json:"total"`
Flag bool `json:"flag"` //接口处理完成
Total int64 `json:"total"`
Current int64 `json:"current"`
}
type Server struct {
Disks []*pai.Disk `json:"disks"`//硬盘信息
NodeProcesssInfo ProcessInfo `json:"node_processs_info"`//节点信息
Error string `json:"error"`//错误信息
Disks []*pai.Disk `json:"disks"` //硬盘信息
NodeProcesssInfo ProcessInfo `json:"node_processs_info"` //节点信息
Error string `json:"error"` //错误信息
}
type BTYDownloadInfo struct {
IsDownload bool
Version string
Version string
}
type BityuanOp struct {
......@@ -60,16 +59,16 @@ type BityuanOp struct {
var paiJobs pai_service.Pai
var BityuanFlag BityuanOp //true表示有任务在占用,禁止其他重复操作
var Bityuan ProcessInfo
var UpdateInfo updateInfo
var NodeError error
var ServerStatus Server
var Bityuan ProcessInfo
var UpdateInfo updateInfo
var NodeError error
var ServerStatus Server
var RebootP bool
func getProcessInfo(keyfile string)string{
func getProcessInfo(keyfile string) string {
var buffer bytes.Buffer //
var buffer_res bytes.Buffer //
lsof := exec.Command("ps","aux")
lsof := exec.Command("ps", "aux")
grep := exec.Command("grep", keyfile)
head := exec.Command("grep", "-v", "grep")
read, write := io.Pipe() // Create a pipe
......@@ -87,50 +86,49 @@ func getProcessInfo(keyfile string)string{
head.Stdout = &buffer_res
head.Start()
head.Wait()
return strings.Replace(buffer_res.String(), "\n", "", -1)
return strings.Replace(buffer_res.String(), "\n", "", -1)
}
func getWalletInfo()error{
func getWalletInfo() error {
rawProcessInfo:=getProcessInfo(setting.BityuanSetting.Name)
tlog.Info("getWalletInfo","wallet",rawProcessInfo)
if rawProcessInfo==""{
rawProcessInfo := getProcessInfo(setting.BityuanSetting.Name)
tlog.Info("getWalletInfo", "wallet", rawProcessInfo)
if rawProcessInfo == "" {
//钱包节点未启动
StartProcess(setting.Chain33Pai.Auto)
var buffer bytes.Buffer
cmd:=exec.Command("find","/media","-name",setting.BityuanSetting.Name)
cmd.Stdout=&buffer
cmd := exec.Command("find", "/media", "-name", setting.BityuanSetting.Name)
cmd.Stdout = &buffer
cmd.Start()
cmd.Wait()
if buffer.String()==""{
if buffer.String() == "" {
tlog.Info("node dose not exist")
return fmt.Errorf("node dose not exist")
}else{
} else {
fmt.Println(buffer.String())
rawProcessInfo=getProcessInfo(setting.BityuanSetting.Name)
if rawProcessInfo==""{
rawProcessInfo = getProcessInfo(setting.BityuanSetting.Name)
if rawProcessInfo == "" {
tlog.Info("node down")
return errors.New("node down")
}
}
}
record:=StrFilter(strings.Split(rawProcessInfo," "),"")
record := StrFilter(strings.Split(rawProcessInfo, " "), "")
{
Bityuan.User=record[0]
Bityuan.Pid=record[1]
Bityuan.Path=record[10]
Bityuan.PName=path.Base(Bityuan.Path)
Bityuan.User = record[0]
Bityuan.Pid = record[1]
Bityuan.Path = record[10]
Bityuan.PName = path.Base(Bityuan.Path)
ServerStatus.NodeProcesssInfo = Bityuan
}
return nil
}
func StrFilter(str []string,filter string)(res []string){
for i:=0;i<len(str);i++{
if str[i]!=filter{
res=append(res,str[i])
func StrFilter(str []string, filter string) (res []string) {
for i := 0; i < len(str); i++ {
if str[i] != filter {
res = append(res, str[i])
}
}
......@@ -138,27 +136,27 @@ func StrFilter(str []string,filter string)(res []string){
}
//corn job for collecting chain33 process info
func BityuanJob(ticker *time.Ticker){
func BityuanJob(ticker *time.Ticker) {
NodeError = getWalletInfo()
for {
select {
case <-ticker.C:
BityuanFlag.Lock.Lock()
if !BityuanFlag.Flag {//有更新,重置等节点重启操作时 禁止运行,防止冲突
if !BityuanFlag.Flag { //有更新,重置等节点重启操作时 禁止运行,防止冲突
//节点未启动 会调用auto启动
NodeError = getWalletInfo()
//解锁钱包
if NodeError == nil {
status ,err := GetWalletStatus()
status, err := GetWalletStatus()
if err != nil {
tlog.Error("GetWalletStatus","err",err)
} else if status != nil && status.IsHasSeed {
if status.IsTicketLock && status.IsWalletLock{
tlog.Error("GetWalletStatus", "err", err)
} else if status != nil && status.IsHasSeed {
if status.IsTicketLock && status.IsWalletLock {
err := Unlock()
if err != nil {
tlog.Error("unlock wallet","err",err)
tlog.Error("unlock wallet", "err", err)
}
}
//if !status.IsAutoMining {
......@@ -178,23 +176,23 @@ func BityuanJob(ticker *time.Ticker){
}
}
func Copy(src,dst string){
cp:=exec.Command("cp","-r",src,dst)
func Copy(src, dst string) {
cp := exec.Command("cp", "-r", src, dst)
cp.Start()
cp.Wait()
}
func StartProcess(scriptsAddr string)(err error){
cmd:=exec.Command(scriptsAddr)
err=cmd.Start()
if err!=nil{
tlog.Info("StartProcess","exec shell err",err)
func StartProcess(scriptsAddr string) (err error) {
cmd := exec.Command(scriptsAddr)
err = cmd.Start()
if err != nil {
tlog.Info("StartProcess", "exec shell err", err)
return
}
err=cmd.Wait()
if err!=nil{
tlog.Info("StartProcess","exec shell err",err)
err = cmd.Wait()
if err != nil {
tlog.Info("StartProcess", "exec shell err", err)
return
}
return
......@@ -203,16 +201,16 @@ func StartProcess(scriptsAddr string)(err error){
var DPercent DownloadPercent
type DownloadPercent struct {
Total int64
Total int64
Current int64
Flag bool
Flag bool
}
func DownLoadFile(url string,file string,ty int32) error {
func DownLoadFile(url string, file string, ty int32) error {
var (
buf = make([]byte, 32*1024)
buf = make([]byte, 32*1024)
)
r,err := http.Get(url)
r, err := http.Get(url)
if err != nil {
return err
}
......@@ -220,11 +218,11 @@ func DownLoadFile(url string,file string,ty int32) error {
r.Body.Close()
}()
f,err := os.Create(file)
f, err := os.Create(file)
if err != nil {
return err
}
defer func(){
defer func() {
f.Close()
}()
if ty == int32(1) {
......@@ -278,9 +276,9 @@ func DownLoadFile(url string,file string,ty int32) error {
func GetAbsPath(key string) string {
str := getProcessInfo(key)
sstr := strings.Split(str,"\n")
sstr := strings.Split(str, "\n")
regstr := util.DeleteExtraSpace(sstr[0])
params := strings.Split(regstr," ")
params := strings.Split(regstr, " ")
if len(params) == 11 {
if params[10] != "" {
return path.Dir(params[10])
......@@ -292,9 +290,9 @@ func GetAbsPath(key string) string {
func GetNodePid(key string) string {
str := getProcessInfo(key)
sstr := strings.Split(str,"\n")
sstr := strings.Split(str, "\n")
regstr := util.DeleteExtraSpace(sstr[0])
params := strings.Split(regstr," ")
params := strings.Split(regstr, " ")
if len(params) == 11 {
if params[1] != "" {
return params[1]
......@@ -304,7 +302,7 @@ func GetNodePid(key string) string {
return ""
}
func SafeCloseNode() (bool,error) {
func SafeCloseNode() (bool, error) {
//var client chain33.PaiClient
//reply,err := client.Close()
//if err != nil {
......@@ -316,60 +314,60 @@ func SafeCloseNode() (bool,error) {
//return true,nil
path := GetAbsPath(setting.BityuanSetting.Name)
if path == "" {
return false,nil
return false, nil
}
close := exec.Command(path+"/"+setting.BityuanSetting.Name+"-cli","close")
close := exec.Command(path+"/"+setting.BityuanSetting.Name+"-cli", "close")
stderr := bytes.NewBuffer(nil)
close.Stderr = stderr
err := close.Start()
if err != nil {
return false,err
return false, err
}
err = close.Wait()
if err != nil {
return false,errors.New(stderr.String())
return false, errors.New(stderr.String())
}
return true,nil
return true, nil
}
func GetPubKey()string{
f,err:=os.Open("/root/.ssh/id_rsa.pub")
if err!=nil{
func GetPubKey() string {
f, err := os.Open("/root/.ssh/id_rsa.pub")
if err != nil {
tlog.Info(err.Error())
}
r,_:=ioutil.ReadAll(f)
r, _ := ioutil.ReadAll(f)
return string(r)
}
func Preprocessing(){//判断密钥对是否存在,存在则删除
func Preprocessing() { //判断密钥对是否存在,存在则删除
_, err := os.Stat("/root/.ssh")
if err == nil || os.IsExist(err){
if err == nil || os.IsExist(err) {
os.RemoveAll("/root/.ssh")
}
}
func cp(src,dst string,){//复制文件并赋予执行权限
cp:=exec.Command("cp","-rf",src,dst)
os.Chmod(src,0755)
func cp(src, dst string) { //复制文件并赋予执行权限
cp := exec.Command("cp", "-rf", src, dst)
os.Chmod(src, 0755)
cp.Run()
}
func MVScripts(src,dst string){//Absolute Path
path,err:=os.Getwd()
err=os.Chdir(src)
if err!=nil{
func MVScripts(src, dst string) { //Absolute Path
path, err := os.Getwd()
err = os.Chdir(src)
if err != nil {
tlog.Info("invalid directory")
}
dir,_:=ioutil.ReadDir("./")
for _,f:=range dir{
if f.IsDir()&&f.Name()=="scripts"{
dir2,_:=ioutil.ReadDir(f.Name()+"/")
dir, _ := ioutil.ReadDir("./")
for _, f := range dir {
if f.IsDir() && f.Name() == "scripts" {
dir2, _ := ioutil.ReadDir(f.Name() + "/")
os.Chdir(f.Name())
for _,s:=range dir2{
if s.Name()==".gitkeep"{
continue
for _, s := range dir2 {
if s.Name() == ".gitkeep" {
continue
}
cp(s.Name(),path+"/"+f.Name()+"/"+s.Name())
cp(s.Name(), path+"/"+f.Name()+"/"+s.Name())
}
}
......@@ -377,77 +375,76 @@ func MVScripts(src,dst string){//Absolute Path
os.Chdir(path)
}
func Unlock() error{
func Unlock() error {
var passwd []byte
f,err:=os.Open(setting.BityuanSetting.Passwd)
if err!=nil{
f, err := os.Open(setting.BityuanSetting.Passwd)
if err != nil {
tlog.Info("password dose not set")
return err
}
passwd,err=ioutil.ReadAll(f)
if err!=nil{
passwd, err = ioutil.ReadAll(f)
if err != nil {
tlog.Info("Read passwd failed")
return err
}
pass := strings.Replace(string(passwd),"\n","",-1)
reply,err :=setting.PaiClient.Unlock(&types.WalletUnLock{
Passwd: string(pass),
pass := strings.Replace(string(passwd), "\n", "", -1)
reply, err := setting.PaiClient.Unlock(&types.WalletUnLock{
Passwd: string(pass),
Timeout: 0,
WalletOrTicket: false,
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
})
if err!=nil {
if err != nil {
tlog.Info("unlock auth failed")
return err
}
if !reply.IsOk {
tlog.Error("unlock auth failed","err",string(reply.Msg))
tlog.Error("unlock auth failed", "err", string(reply.Msg))
}
return nil
}
type clientRequest struct {
Method string `json:"method"`
Params [1]interface{} `json:"params"`
ID uint64 `json:"id"`
}
func AutoOpenTicket() error{
func AutoOpenTicket() error {
params := clientRequest{}
params.ID = 1
params.Method = "ticket.SetAutoMining"
p := [1]interface{}{}
p[0] = types2.MinerFlag{Flag:1}
p[0] = types2.MinerFlag{Flag: 1}
params.Params = p
data,err := json.Marshal(params)
data, err := json.Marshal(params)
if err != nil {
tlog.Error("AutoOpenTicket","marshal",err)
tlog.Error("AutoOpenTicket", "marshal", err)
return err
}
client := &http.Client{}
req ,err := http.NewRequest("POST","http://localhost:8801",bytes.NewReader(data))
req, err := http.NewRequest("POST", "http://localhost:8801", bytes.NewReader(data))
if err != nil {
tlog.Error("AutoOpenTicket","NewRequest",err)
tlog.Error("AutoOpenTicket", "NewRequest", err)
return err
}
resp,err:=client.Do(req)
resp, err := client.Do(req)
if err != nil {
tlog.Error("AutoOpenTicket","NewRequest do",err)
tlog.Error("AutoOpenTicket", "NewRequest do", err)
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
tlog.Error("AutoOpenTicket","read",err)
tlog.Error("AutoOpenTicket", "read", err)
return err
}
tlog.Info("AutoOpenTicket","err",string(body))
tlog.Info("AutoOpenTicket", "err", string(body))
return nil
}
func GetWalletStatus() (*types.WalletStatus,error) {
func GetWalletStatus() (*types.WalletStatus, error) {
var p chain33.PaiClient
return p.GetWalletStatus()
}
......@@ -464,61 +461,61 @@ func PaiJob(tick *time.Ticker) {
}
type PaiProcessInfo struct {
Pid int32
Pid int32
Stime int64
Cmd string
Cmd string
}
func AutoSSHClean() error {
pai,err := getAutoSSHProcessInfo()
pai, err := getAutoSSHProcessInfo()
if err != nil {
return err
}
tlog.Info("getAutoSSHProcessInfo","pai",*pai)
tlog.Info("getAutoSSHProcessInfo", "pai", *pai)
if pai.Stime > 0 && (time.Now().Unix()-pai.Stime) > 72 * 3600 && pai.Pid > 0 {
if pai.Stime > 0 && (time.Now().Unix()-pai.Stime) > 72*3600 && pai.Pid > 0 {
err := KillAutoSsh(pai.Pid)
if err != nil {
tlog.Error("KillAutoSsh","err",err)
tlog.Error("KillAutoSsh", "err", err)
return err
}
tlog.Info("KillAutoSsh Success","pid",pai.Pid)
tlog.Info("KillAutoSsh Success", "pid", pai.Pid)
}
return nil
}
func KillAutoSsh(pid int32) error {
ps := fmt.Sprintf("%d",pid)
cmd := exec.Command("kill",ps)
ps := fmt.Sprintf("%d", pid)
cmd := exec.Command("kill", ps)
return cmd.Run()
}
func getAutoSSHProcessInfo() (*PaiProcessInfo,error) {
func getAutoSSHProcessInfo() (*PaiProcessInfo, error) {
var pai PaiProcessInfo
var buf bytes.Buffer
cmd := exec.Command("bash","-c","ps -eo pid,lstart,cmd |grep autossh | grep -v grep")
cmd := exec.Command("bash", "-c", "ps -eo pid,lstart,cmd |grep autossh | grep -v grep")
cmd.Stdout = &buf
err := cmd.Run()
if err != nil {
tlog.Error("getAutoSSHProcessInfo cmd","err",err)
return nil,err
tlog.Error("getAutoSSHProcessInfo cmd", "err", err)
return nil, err
}
trimBuf := strings.Trim(buf.String()," ")
list := strings.Split(trimBuf," ")
trimBuf := strings.Trim(buf.String(), " ")
list := strings.Split(trimBuf, " ")
if len(list) < 7 {
return nil, errors.New("ps return exception")
}
lstart := list[1]+" "+list[2]+" "+ list[3]+" "+ list[4]+" "+list[5]
location , _ := time.LoadLocation("Local")
tt,err := time.ParseInLocation(time.ANSIC,lstart,location)
lstart := list[1] + " " + list[2] + " " + list[3] + " " + list[4] + " " + list[5]
location, _ := time.LoadLocation("Local")
tt, err := time.ParseInLocation(time.ANSIC, lstart, location)
if err != nil {
tlog.Error("getAutoSSHProcessInfo","err",err)
return nil,err
tlog.Error("getAutoSSHProcessInfo", "err", err)
return nil, err
}
start := tt.Unix()
p ,_ := strconv.Atoi(list[0])
p, _ := strconv.Atoi(list[0])
pai.Pid = int32(p)
pai.Stime = start
......@@ -526,26 +523,26 @@ func getAutoSSHProcessInfo() (*PaiProcessInfo,error) {
}
func AutoUpdate() {
if RebootP {//重启pai
if RebootP { //重启pai
err := KillPai()
if err != nil {
tlog.Error("kill pai","err",err)
tlog.Error("kill pai", "err", err)
} else {
err := StartProcess(setting.Chain33Pai.Start)
if err != nil {
tlog.Error("restart pai fail","err",err)
tlog.Error("restart pai fail", "err", err)
} else {
tlog.Info("kill restart pai success ")
}
}
} else {
if !DPercent.Flag {//没有其他任务占用
if !DPercent.Flag { //没有其他任务占用
DPercent.Flag = true
err := AutoUpdatePai()
if err != nil {
tlog.Error("autoupdatepai","err",err)
tlog.Error("autoupdatepai", "err", err)
}
tlog.Info("autoupdatepai","err",GetVersion())
tlog.Info("autoupdatepai", "err", GetVersion())
DPercent.Flag = false
}
}
......@@ -556,7 +553,7 @@ func AutoUpdatePai() error {
version := util.VersionCompare(GetVersion())
//检查最新版本号online数据库
var pai pai_service.Pai
latest,err := pai.GetPaiLatestVersion(int32(2))
latest, err := pai.GetPaiLatestVersion(int32(2))
if err != nil {
return err
}
......@@ -566,36 +563,36 @@ func AutoUpdatePai() error {
return nil
}
name := setting.Chain33Pai.Name+"_"+latest+".tar.gz"
url := setting.Chain33Pai.DownloadUrl+ name
name := setting.Chain33Pai.Name + "_" + latest + ".tar.gz"
url := setting.Chain33Pai.DownloadUrl + name
//oss下载更新包
err = DownLoadFile(url,name,int32(2))
err = DownLoadFile(url, name, int32(2))
if err != nil {
return err
}
var serr bytes.Buffer
//解压缩文件
tar := exec.Command("tar","-xvf",name,"-C","../")
tar := exec.Command("tar", "-xvf", name, "-C", "../")
tar.Stdout = &serr
err = tar.Start()
if err != nil {
tlog.Error("tar","err",err)
tlog.Error("tar", "err", err)
return err
}
err = tar.Wait()
if err != nil {
tlog.Error("tar2","err",serr.String())
tlog.Error("tar2", "err", serr.String())
return err
}
remove := exec.Command("rm","-rf",name)
remove := exec.Command("rm", "-rf", name)
err = remove.Start()
if err != nil {
tlog.Error("rm ","err",err)
tlog.Error("rm ", "err", err)
return err
}
err = remove.Wait()
if err != nil {
tlog.Error("rm wait","err",err)
tlog.Error("rm wait", "err", err)
return err
}
RebootP = true
......@@ -605,80 +602,80 @@ func AutoUpdatePai() error {
func KillPai() error {
err := StartProcess(setting.Chain33Pai.StopPai)
if err != nil {
tlog.Error("stop chain33 pai ","err",err)
tlog.Error("stop chain33 pai ", "err", err)
}
return nil
}
func UploadInfo(tick * time.Ticker) {
func UploadInfo(tick *time.Ticker) {
for {
select {
case <- tick.C:
select {
case <-tick.C:
uploadInfo()
}
}
}
//上传基本信息
func uploadInfo() error {
params:=make(map[string]string)
params := make(map[string]string)
params["version"] = GetVersion()
var pai pai_service.Pai
err := pai.SetPai()
if err != nil {
tlog.Error("SetPai","err",err)
tlog.Error("SetPai", "err", err)
return err
}
jpai,_ := json.Marshal(pai)
jpai, _ := json.Marshal(pai)
params["addr"] = pai.Serial
params["info"] = string(jpai)
data,err := json.Marshal(params)
data, err := json.Marshal(params)
client := &http.Client{}
req ,err := http.NewRequest("POST",setting.Chain33Pai.UploadVersionUrl,bytes.NewReader(data))
req, err := http.NewRequest("POST", setting.Chain33Pai.UploadVersionUrl, bytes.NewReader(data))
if err != nil {
tlog.Error("uploadInfo","NewRequest",err)
tlog.Error("uploadInfo", "NewRequest", err)
return err
}
resp,err:=client.Do(req)
resp, err := client.Do(req)
if err != nil {
tlog.Error("uploadInfo","NewRequest do",err)
tlog.Error("uploadInfo", "NewRequest do", err)
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
tlog.Error("uploadInfo","read",err)
tlog.Error("uploadInfo", "read", err)
return err
}
tlog.Info("uploadInfo","result",string(body))
tlog.Info("uploadInfo", "result", string(body))
return nil
}
func uploadVersion() error {
client := &http.Client{}
params:=make(map[string]interface{})
params := make(map[string]interface{})
params["version"] = GetVersion()
data,err := json.Marshal(params)
data, err := json.Marshal(params)
if err != nil {
tlog.Error("uploadVersion","marshal",err)
tlog.Error("uploadVersion", "marshal", err)
return err
}
req ,err := http.NewRequest("POST",setting.Chain33Pai.UploadVersionUrl,bytes.NewReader(data))
req, err := http.NewRequest("POST", setting.Chain33Pai.UploadVersionUrl, bytes.NewReader(data))
if err != nil {
tlog.Error("uploadVersion","NewRequest",err)
tlog.Error("uploadVersion", "NewRequest", err)
return err
}
resp,err:=client.Do(req)
resp, err := client.Do(req)
if err != nil {
tlog.Error("uploadVersion","NewRequest do",err)
tlog.Error("uploadVersion", "NewRequest do", err)
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
tlog.Error("uploadVersion","read",err)
tlog.Error("uploadVersion", "read", err)
return err
}
tlog.Info("uploadversion","version",string(body))
tlog.Info("uploadversion", "version", string(body))
return nil
}
......@@ -692,91 +689,91 @@ func updateBityuan640() error {
plantime := int64(1585828800)
nowtime := time.Now().Unix()
if nowtime < plantime {
tlog.Error("waiting plantime to update","nowtime",nowtime)
tlog.Error("waiting plantime to update", "nowtime", nowtime)
BityuanFlag.Flag = false
return errors.New("waiting plantime to update")
}
update := GetNodeUpdateStatus()
if update {
tlog.Info("updateBityuan640 is updating","update",update)
tlog.Info("updateBityuan640 is updating", "update", update)
BityuanFlag.Flag = false
return nil
}
var pai chain33.PaiClient
v ,err:= pai.Version()
v, err := pai.Version()
if err != nil {
tlog.Error("get version ","err",err)
tlog.Error("get version ", "err", err)
BityuanFlag.Flag = false
return err
}
if strings.Contains(v.App,"6.4.2") {
tlog.Info("bityuan do not need update","version",v.App)
if strings.Contains(v.App, "6.4.2") {
tlog.Info("bityuan do not need update", "version", v.App)
BityuanFlag.Flag = false
return nil
}
stderr := bytes.NewBuffer(nil)
absPath := GetAbsPath(setting.BityuanSetting.Name)+"/"
name := setting.BityuanSetting.Name+"_6.4.2.tar.gz"
url := setting.Chain33Pai.DownloadUrl+ name
tlog.Info("UpdateNode","dir",name)
tlog.Info("UpdateNode","path",absPath)
err = DownLoadFile(url,name,int32(1))
if err != nil {
tlog.Error("updateBityuan640","err",err)
absPath := GetAbsPath(setting.BityuanSetting.Name) + "/"
name := setting.BityuanSetting.Name + "_6.4.2.tar.gz"
url := setting.Chain33Pai.DownloadUrl + name
tlog.Info("UpdateNode", "dir", name)
tlog.Info("UpdateNode", "path", absPath)
err = DownLoadFile(url, name, int32(1))
if err != nil {
tlog.Error("updateBityuan640", "err", err)
BityuanFlag.Flag = false
return err
}
dirs := strings.Split(absPath,"wallet-bty")
dirs := strings.Split(absPath, "wallet-bty")
if len(dirs) != 2 {
tlog.Error("updateBityuan640","err",err)
tlog.Error("updateBityuan640", "err", err)
BityuanFlag.Flag = false
return err
}
//解压缩文件
tar := exec.Command("tar","-xvf",name ,"-C",dirs[0])
tar := exec.Command("tar", "-xvf", name, "-C", dirs[0])
tar.Stderr = stderr
err = tar.Start()
if err != nil {
tlog.Error("tar","err",err)
tlog.Error("tar", "err", err)
BityuanFlag.Flag = false
return err
}
err = tar.Wait()
if err != nil {
tlog.Error("tar","err",stderr.String())
tlog.Error("tar", "err", stderr.String())
BityuanFlag.Flag = false
return err
}
t,err := SafeCloseNode()
t, err := SafeCloseNode()
if err != nil || !t {
tlog.Error("updateBityuan640 close node","err",err)
tlog.Error("updateBityuan640 close node", "err", err)
BityuanFlag.Flag = false
return err
}
//其他模块可能没有即时关闭,在高速刷盘的情形下
time.Sleep(time.Second * 2)
remove := exec.Command("rm","-rf",name)
remove := exec.Command("rm", "-rf", name)
remove.Stderr = stderr
err = remove.Start()
if err != nil {
tlog.Error("rm","err",stderr.String())
tlog.Error("rm", "err", stderr.String())
BityuanFlag.Flag = false
return err
}
err = remove.Wait()
if err != nil {
tlog.Error("rm","err",stderr.String())
tlog.Error("rm", "err", stderr.String())
BityuanFlag.Flag = false
return err
}
err=StartProcess(setting.Chain33Pai.Auto)
if err!=nil{
tlog.Error("updateBityuan640","auto.sh error ",err)
err = StartProcess(setting.Chain33Pai.Auto)
if err != nil {
tlog.Error("updateBityuan640", "auto.sh error ", err)
BityuanFlag.Flag = false
return err
}
tlog.Info("updateBityuan640 success please waiting hours","version","6.3.2->6.4.2")
tlog.Info("updateBityuan640 success please waiting hours", "version", "6.3.2->6.4.2")
BityuanFlag.Flag = false
return nil
}
......@@ -789,11 +786,10 @@ func GetNodeUpdateStatus() bool {
return false
}
//程序运行 + 端口没开启
if strings.Contains(buf.String(),"v7-bityuan") && !strings.Contains(buf.String(),":8801") && strings.Contains(buf.String(),":6060") {
if strings.Contains(buf.String(), "v7-bityuan") && !strings.Contains(buf.String(), ":8801") && strings.Contains(buf.String(), ":6060") {
return true
} else if !strings.Contains(buf.String(),"v7-bityuan") {
} else if !strings.Contains(buf.String(), "v7-bityuan") {
return false
}
return false
}
package app
import (
"time"
"chain33-pai/pkg/setting"
"bytes"
"os/exec"
"fmt"
"chain33-pai/pkg/setting"
"chain33-pai/service/pai_service"
"errors"
"fmt"
"os"
"os/exec"
"time"
)
var (
......@@ -17,8 +17,8 @@ var (
func RaspberryChan() {
for {
if value,ok := <- JobChan; ok {
tlog.Info("raspberrychan","msg",value)
if value, ok := <-JobChan; ok {
tlog.Info("raspberrychan", "msg", value)
if value.Name == "" {
continue
}
......@@ -30,37 +30,37 @@ func RaspberryChan() {
case "ROLLBACK":
err := rollback()
if err == nil {
tlog.Info("rollback success","err",nil)
tlog.Info("rollback success", "err", nil)
} else {
tlog.Error("rollback fail ","err",err)
tlog.Error("rollback fail ", "err", err)
}
case "BACKUP":
err := backup()
if err == nil {
tlog.Info("backup success","err",nil)
tlog.Info("backup success", "err", nil)
} else {
tlog.Error("backup fail ","err",err)
tlog.Error("backup fail ", "err", err)
}
case "RECOVER":
err := recoverNode()
if err == nil {
tlog.Info("recover success","err",nil)
tlog.Info("recover success", "err", nil)
} else {
tlog.Error("recover fail ","err",err)
tlog.Error("recover fail ", "err", err)
}
case "DELETEBACKUP":
err := deleteBackup()
if err == nil {
tlog.Info("deleteBackup success","err",nil)
tlog.Info("deleteBackup success", "err", nil)
} else {
tlog.Error("deleteBackup fail ","err",err)
tlog.Error("deleteBackup fail ", "err", err)
}
case "RESTART":
err := restartNode()
if err == nil {
tlog.Info("deleteBackup success","err",nil)
tlog.Info("deleteBackup success", "err", nil)
} else {
tlog.Error("deleteBackup fail ","err",err)
tlog.Error("deleteBackup fail ", "err", err)
}
}
......@@ -69,26 +69,25 @@ func RaspberryChan() {
}
}
func rollback() error {
BityuanFlag.Lock.Lock()
defer BityuanFlag.Lock.Unlock()
BityuanFlag.Flag = true
_,err := SafeCloseNode()
_, err := SafeCloseNode()
if err != nil {
BityuanFlag.Flag = false
BityuanFlag.Flag = false
return err
}
var pai pai_service.Pai
err = pai.SetPai()
if err != nil {
tlog.Error("SetPai","err",err)
BityuanFlag.Flag = false
tlog.Error("SetPai", "err", err)
BityuanFlag.Flag = false
return err
}
if pai.LocalLastHeight == 0 {
tlog.Error("LocalLastHeight","height",pai.LocalLastHeight)
BityuanFlag.Flag = false
tlog.Error("LocalLastHeight", "height", pai.LocalLastHeight)
BityuanFlag.Flag = false
return err
}
rollheight := pai.LocalLastHeight - 1000
......@@ -97,25 +96,25 @@ func rollback() error {
}
isrun := MakeSureBtyIsNotRun()
if isrun {
BityuanFlag.Flag = false
BityuanFlag.Flag = false
return errors.New("bty is running")
}
tlog.Info("rollback start","height",pai.LocalLastHeight,"rollbackheight",rollheight)
tlog.Info("rollback start", "height", pai.LocalLastHeight, "rollbackheight", rollheight)
var buf bytes.Buffer
if btyPath == "" {
tlog.Error("GetAbsPath","err","btyPath not exists")
BityuanFlag.Flag = false
tlog.Error("GetAbsPath", "err", "btyPath not exists")
BityuanFlag.Flag = false
return err
}
cmd := exec.Command(btyPath+"/"+setting.BityuanSetting.Name, "-rollback",fmt.Sprintf("%d",rollheight))
cmd := exec.Command(btyPath+"/"+setting.BityuanSetting.Name, "-rollback", fmt.Sprintf("%d", rollheight))
cmd.Stdout = &buf
err = cmd.Run()
if err != nil {
BityuanFlag.Flag = false
BityuanFlag.Flag = false
return err
}
tlog.Info("rollback end","height",pai.LocalLastHeight,"rollbackheight",rollheight)
BityuanFlag.Flag = false
tlog.Info("rollback end", "height", pai.LocalLastHeight, "rollbackheight", rollheight)
BityuanFlag.Flag = false
return nil
}
......@@ -126,10 +125,10 @@ func backup() error {
return errors.New("env err")
}
BityuanFlag.Flag = true
ok,err := SafeCloseNode()
if err != nil {
ok, err := SafeCloseNode()
if err != nil {
BityuanFlag.Flag = false
tlog.Error("SafeCloseNode","err",err)
tlog.Error("SafeCloseNode", "err", err)
return err
}
if !ok {
......@@ -138,11 +137,11 @@ func backup() error {
}
isrun := MakeSureBtyIsNotRun()
if isrun {
BityuanFlag.Flag = false
BityuanFlag.Flag = false
return errors.New("bty is running")
}
err = deleteBackup()
if err != nil && err != errors.New("backup file not exists"){
if err != nil && err != errors.New("backup file not exists") {
BityuanFlag.Flag = false
return err
}
......@@ -150,7 +149,7 @@ func backup() error {
if err != nil {
return err
}
BityuanFlag.Flag = false
BityuanFlag.Flag = false
StartProcess(setting.Chain33Pai.Auto)
return nil
}
......@@ -158,13 +157,13 @@ func backup() error {
func SafeBackup() error {
s := time.Now()
defer func() {
tlog.Info("SafeBackup","cost",time.Since(s))
tlog.Info("SafeBackup", "cost", time.Since(s))
}()
var buf bytes.Buffer
backup := exec.Command("cp","-r",btyPath+"/datadir",btyPath+"/datadir_backup")
backup := exec.Command("cp", "-r", btyPath+"/datadir", btyPath+"/datadir_backup")
backup.Stderr = &buf
if err := backup.Run();err != nil {
tlog.Error("SafeBackup","err",buf.String())
if err := backup.Run(); err != nil {
tlog.Error("SafeBackup", "err", buf.String())
return err
}
return nil
......@@ -174,10 +173,10 @@ func recoverNode() error {
BityuanFlag.Lock.Lock()
defer BityuanFlag.Lock.Unlock()
if btyPath == "" {
tlog.Error("btyPath empty","err","node not exists")
tlog.Error("btyPath empty", "err", "node not exists")
return errors.New("node not exists")
}
_,err := SafeCloseNode()
_, err := SafeCloseNode()
if err != nil {
return err
}
......@@ -186,23 +185,23 @@ func recoverNode() error {
return errors.New("bty is running")
}
backupPath := btyPath + "/datadir_backup"
if _,err := os.Stat(backupPath);err != nil {
if _, err := os.Stat(backupPath); err != nil {
if os.IsNotExist(err) {
tlog.Error("backup file not exists","err",backupPath)
tlog.Error("backup file not exists", "err", backupPath)
return errors.New("backup file not exists")
}
}
remove := exec.Command("rm","-rf",btyPath+"/datadir")
remove := exec.Command("rm", "-rf", btyPath+"/datadir")
err = remove.Run()
if err != nil {
tlog.Error("rm -rf datadir","err",err)
tlog.Error("rm -rf datadir", "err", err)
return err
}
recover := exec.Command("cp","-r",backupPath,btyPath+"/datadir")
recover := exec.Command("cp", "-r", backupPath, btyPath+"/datadir")
err = recover.Run()
if err != nil {
tlog.Error("cp -r datadir_backup datadir","err",err)
tlog.Error("cp -r datadir_backup datadir", "err", err)
return err
}
StartProcess(setting.Chain33Pai.Auto)
......@@ -212,33 +211,32 @@ func recoverNode() error {
func deleteBackup() error {
s := time.Now()
defer func() {
tlog.Info("deleteBackup","cost",time.Since(s))
tlog.Info("deleteBackup", "cost", time.Since(s))
}()
backupPath := btyPath + "/datadir_backup"
if _,err := os.Stat(backupPath);err != nil {
if _, err := os.Stat(backupPath); err != nil {
if os.IsNotExist(err) {
tlog.Error("backup file not exists","err",backupPath)
tlog.Error("backup file not exists", "err", backupPath)
return nil
}
}
remove := exec.Command("rm","-rf",backupPath)
remove := exec.Command("rm", "-rf", backupPath)
err := remove.Run()
if err != nil {
tlog.Error("rm -rf datadir_backup","err",err)
tlog.Error("rm -rf datadir_backup", "err", err)
return err
}
return nil
}
func restartNode() error {
BityuanFlag.Lock.Lock()
defer BityuanFlag.Lock.Unlock()
if btyPath == "" {
tlog.Error("btyPath empty","err","node not exists")
tlog.Error("btyPath empty", "err", "node not exists")
return errors.New("node not exists")
}
_,err := SafeCloseNode()
_, err := SafeCloseNode()
if err != nil {
return err
}
......@@ -247,13 +245,13 @@ func restartNode() error {
return errors.New("bty is running")
}
StartProcess(setting.Chain33Pai.Auto)
return nil
return nil
}
func MakeSureBtyIsNotRun() bool {
s := time.Now()
defer func() {
tlog.Info("MakeSureBtyIsNotRun","cost",time.Since(s))
tlog.Info("MakeSureBtyIsNotRun", "cost", time.Since(s))
}()
num := 0
for {
......@@ -265,7 +263,7 @@ func MakeSureBtyIsNotRun() bool {
return false
}
num++
time.Sleep(time.Second*1)
time.Sleep(time.Second * 1)
}
return true
}
\ No newline at end of file
}
......@@ -8,7 +8,7 @@ var (
func GetVersion() string {
if GitCommit != "" {
return version+"-"+GitCommit
return version + "-" + GitCommit
}
return version
}
......@@ -2,57 +2,55 @@ package chain33
import (
"context"
"google.golang.org/grpc"
"github.com/33cn/chain33/types"
"google.golang.org/grpc"
)
type PaiClient struct {
}
var (
paiClient types.Chain33Client
paiClient types.Chain33Client
paiNetgrpcAddr = "localhost:8802"
)
func init() {
maxReceLimit := grpc.WithMaxMsgSize(30*1024*1024)
conn, err := grpc.Dial(paiNetgrpcAddr, grpc.WithInsecure(),maxReceLimit)
maxReceLimit := grpc.WithMaxMsgSize(30 * 1024 * 1024)
conn, err := grpc.Dial(paiNetgrpcAddr, grpc.WithInsecure(), maxReceLimit)
if err != nil {
panic(err)
}
paiClient = types.NewChain33Client(conn)
}
func (p *PaiClient) GetWalletStatus() (*types.WalletStatus,error) {
return paiClient.GetWalletStatus(context.Background(),&types.ReqNil{})
func (p *PaiClient) GetWalletStatus() (*types.WalletStatus, error) {
return paiClient.GetWalletStatus(context.Background(), &types.ReqNil{})
}
func (p *PaiClient) GetPeerInfo() (*types.PeerList,error) {
return paiClient.GetPeerInfo(context.Background(),&types.P2PGetPeerReq{})
func (p *PaiClient) GetPeerInfo() (*types.PeerList, error) {
return paiClient.GetPeerInfo(context.Background(), &types.P2PGetPeerReq{})
}
func (p *PaiClient) IsNtpClockSync() (*types.Reply,error) {
return paiClient.IsNtpClockSync(context.Background(),&types.ReqNil{})
func (p *PaiClient) IsNtpClockSync() (*types.Reply, error) {
return paiClient.IsNtpClockSync(context.Background(), &types.ReqNil{})
}
func (p *PaiClient) GetNetInfo() (*types.NodeNetInfo,error) {
return paiClient.NetInfo(context.Background(),&types.P2PGetNetInfoReq{})
func (p *PaiClient) GetNetInfo() (*types.NodeNetInfo, error) {
return paiClient.NetInfo(context.Background(), &types.P2PGetNetInfoReq{})
}
func (p *PaiClient) Version()(*types.VersionInfo,error){
return paiClient.Version(context.Background(),&types.ReqNil{})
func (p *PaiClient) Version() (*types.VersionInfo, error) {
return paiClient.Version(context.Background(), &types.ReqNil{})
}
func (p *PaiClient) Close() (*types.Reply,error) {
return paiClient.CloseQueue(context.Background(),&types.ReqNil{})
func (p *PaiClient) Close() (*types.Reply, error) {
return paiClient.CloseQueue(context.Background(), &types.ReqNil{})
}
func (p *PaiClient) Unlock(lock *types.WalletUnLock)(*types.Reply,error){
return paiClient.UnLock(context.Background(),lock)
func (p *PaiClient) Unlock(lock *types.WalletUnLock) (*types.Reply, error) {
return paiClient.UnLock(context.Background(), lock)
}
func (p *PaiClient) IsSync() (*types.Reply,error) {
return paiClient.IsSync(context.Background(),&types.ReqNil{})
func (p *PaiClient) IsSync() (*types.Reply, error) {
return paiClient.IsSync(context.Background(), &types.ReqNil{})
}
......@@ -5,21 +5,21 @@ const (
ERROR = 500
INVALID_PARAMS = 400
NETWORK_ERROR = 5004
NODE_ERROR = 5000
SUCCESS_RUNNING= 5002
ENV_ERROR = 5001
DOWNLOAD_ERROR = 5005
TAR_XVF_ERROR = 5006
CP_ERROR = 5007
RM_ERROR = 5008
MV_ERROR = 5009
TRY_LATER = 5010
DF_ERROR = 5011
VERSION_UPDATE_ERROR = 5012
NO_JOB = 5013
UNDONE = 5014
ERROR_AUTH = 5015
NETWORK_ERROR = 5004
NODE_ERROR = 5000
SUCCESS_RUNNING = 5002
ENV_ERROR = 5001
DOWNLOAD_ERROR = 5005
TAR_XVF_ERROR = 5006
CP_ERROR = 5007
RM_ERROR = 5008
MV_ERROR = 5009
TRY_LATER = 5010
DF_ERROR = 5011
VERSION_UPDATE_ERROR = 5012
NO_JOB = 5013
UNDONE = 5014
ERROR_AUTH = 5015
ERROR_EXIST_TAG = 10001
ERROR_EXIST_TAG_FAIL = 10002
ERROR_NOT_EXIST_TAG = 10003
......
......@@ -4,14 +4,14 @@ var MsgFlags = map[int]string{
SUCCESS: "ok",
ERROR: "fail",
INVALID_PARAMS: "请求参数错误",
DOWNLOAD_ERROR: "下载出错",
TAR_XVF_ERROR: "解压文件出错",
CP_ERROR: "拷贝文件出错",
RM_ERROR: "删除文件出错",
MV_ERROR: "移动文件出错",
TRY_LATER: "其他任务进行中,稍后再试",
DF_ERROR: "df命令执行异常",
VERSION_UPDATE_ERROR: "版本更新异常,请检查当前版本和更新版本",
DOWNLOAD_ERROR: "下载出错",
TAR_XVF_ERROR: "解压文件出错",
CP_ERROR: "拷贝文件出错",
RM_ERROR: "删除文件出错",
MV_ERROR: "移动文件出错",
TRY_LATER: "其他任务进行中,稍后再试",
DF_ERROR: "df命令执行异常",
VERSION_UPDATE_ERROR: "版本更新异常,请检查当前版本和更新版本",
ERROR_EXIST_TAG: "已存在该标签名称",
ERROR_EXIST_TAG_FAIL: "获取已存在标签失败",
ERROR_NOT_EXIST_TAG: "该标签不存在",
......
package logging
import (
"fmt"
"chain33-pai/pkg/file"
"fmt"
"log"
"os"
"path/filepath"
......
package pai
import (
"os/exec"
"io/ioutil"
"strings"
"bytes"
"chain33-pai/pkg/util"
"github.com/33cn/chain33/common/log"
"bytes"
"io/ioutil"
"os/exec"
"strings"
)
var tlog = log.New("pkg","pai")
var tlog = log.New("pkg", "pai")
func MonitorServer() ([]*Disk,error) {
func MonitorServer() ([]*Disk, error) {
//获取硬盘情况
cmd := exec.Command("df","-T")
cmd := exec.Command("df", "-T")
stdout, err := cmd.StdoutPipe()
err = cmd.Start()
if err != nil {
tlog.Info("MonitorServer","df -T start " ,err)
return nil,err
tlog.Info("MonitorServer", "df -T start ", err)
return nil, err
}
content, err := ioutil.ReadAll(stdout)
if err != nil {
tlog.Info("MonitorServer","ioutil readd err",err)
return nil,err
tlog.Info("MonitorServer", "ioutil readd err", err)
return nil, err
}
err = cmd.Wait()
if err != nil {
tlog.Info("MonitorServer","df -T end" ,err)
return nil,err
tlog.Info("MonitorServer", "df -T end", err)
return nil, err
}
tlog.Info("MonitorServer","content",string(content))
list := strings.Split(string(content),"\n")
tempDisk := make([]*Disk,0)
for _,v := range list {
c := strings.Contains(v,"/dev/sd")
tlog.Info("MonitorServer", "content", string(content))
list := strings.Split(string(content), "\n")
tempDisk := make([]*Disk, 0)
for _, v := range list {
c := strings.Contains(v, "/dev/sd")
if c {
tempD := &Disk{}
params := strings.Split(util.DeleteExtraSpace(v)," ")
params := strings.Split(util.DeleteExtraSpace(v), " ")
if len(params) == 7 {
tempD.Filesystem = params[0]
tempD.Type = params[1]
tempD.SizeK = params[2]
tempD.Use = params[5]
tempDisk = append(tempDisk,tempD)
tempDisk = append(tempDisk, tempD)
} else {
break
}
}
}
return tempDisk,nil
return tempDisk, nil
}
func FindAbsPath(name string) string {
var buffer bytes.Buffer
cmd:=exec.Command("find","/media","-name",name)
cmd.Stdout=&buffer
cmd := exec.Command("find", "/media", "-name", name)
cmd.Stdout = &buffer
cmd.Start()
cmd.Wait()
if buffer.String() == "" {
tlog.Error("FindAbsPath","ERR","node path not exists")
tlog.Error("FindAbsPath", "ERR", "node path not exists")
return ""
}
pathlist := strings.Split(buffer.String(),"\n")
pathlist := strings.Split(buffer.String(), "\n")
return pathlist[0]
}
\ No newline at end of file
}
......@@ -2,7 +2,7 @@ package pai
type Disk struct {
Filesystem string `json:"filesystem"`
Type string `json:"type"`//硬盘格式
SizeK string `json:"size_k"`//硬盘大小
Use string `json:"use"`
Type string `json:"type"` //硬盘格式
SizeK string `json:"size_k"` //硬盘大小
Use string `json:"use"`
}
package setting
import (
"log"
"time"
"os/exec"
"chain33-pai/pkg/chain33"
"github.com/go-ini/ini"
"github.com/33cn/chain33/types"
"github.com/go-ini/ini"
"log"
"os/exec"
"time"
)
var PaiClient *chain33.PaiClient
......@@ -63,40 +62,42 @@ type Redis struct {
MaxActive int
IdleTimeout time.Duration
}
var RedisSetting = &Redis{}
type Bityuan struct {
Path string
Path string
Name string
GitPath string
Passwd string
Version string
GitPath string
Passwd string
Version string
VersionPath string
}
var BityuanSetting=&Bityuan{}
var BityuanSetting = &Bityuan{}
type Chain33_pai struct {
Name string
Path string
Auto string
Start string
StartUp string
Scripts string
DownloadUrl string
VersionUrl string
FeedBackUrl string
IsCompleteUrl string
FeedBackNosshUrl string
IsCompleteNosshUrl string
RaspberryServer string
StopPai string
UploadVersionUrl string
UploadTestUrl string
Name string
Path string
Auto string
Start string
StartUp string
Scripts string
DownloadUrl string
VersionUrl string
FeedBackUrl string
IsCompleteUrl string
FeedBackNosshUrl string
IsCompleteNosshUrl string
RaspberryServer string
StopPai string
UploadVersionUrl string
UploadTestUrl string
}
var Chain33Pai=&Chain33_pai{}
var Chain33Pai = &Chain33_pai{}
var LogSetting=&types.Log{}
var LogSetting = &types.Log{}
var cfg *ini.File
......@@ -110,10 +111,10 @@ func Setup() {
mapTo("app", AppSetting)
mapTo("redis", RedisSetting)
mapTo("server", ServerSetting)
mapTo("chain33-pai",Chain33Pai)
mapTo("bityuan",BityuanSetting)
mapTo("chain33-pai", Chain33Pai)
mapTo("bityuan", BityuanSetting)
mapTo("database", DatabaseSetting)
mapTo("log",LogSetting)
mapTo("log", LogSetting)
AppSetting.ImageMaxSize = AppSetting.ImageMaxSize * 1024 * 1024
ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
......@@ -121,20 +122,20 @@ func Setup() {
}
func FreshVersion(){
version,err:=PaiClient.Version()
if err!=nil{
auto:=exec.Command(Chain33Pai.Auto)
err=auto.Start()
if err != nil {
log.Fatalf("start node failed,need to start manually")
}
err=auto.Wait()
if err != nil {
log.Fatalf("start node failed,need to start manually")
}
func FreshVersion() {
version, err := PaiClient.Version()
if err != nil {
auto := exec.Command(Chain33Pai.Auto)
err = auto.Start()
if err != nil {
log.Fatalf("start node failed,need to start manually")
}
err = auto.Wait()
if err != nil {
log.Fatalf("start node failed,need to start manually")
}
BityuanSetting.Version=version.App
}
BityuanSetting.Version = version.App
}
// mapTo map section
......
package util
import (
"github.com/unknwon/com"
"github.com/gin-gonic/gin"
"github.com/unknwon/com"
"chain33-pai/pkg/setting"
)
......
......@@ -2,12 +2,12 @@ package util
import (
"chain33-pai/pkg/setting"
"net"
"errors"
"net/http"
"io/ioutil"
"strings"
"net"
"net/http"
"regexp"
"strings"
)
// Setup Initialize the util
......@@ -31,10 +31,10 @@ func GetLocalIP() (ipv4 *net.IPNet, err error) {
// 取第一个非lo的网卡IP
for _, addr = range addrs {
// 这个网络地址是IP地址: ipv4, ipv6
if ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback(){
if ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback() {
// 跳过IPV6
if ipNet.IP.To4() != nil{
ipv4 = ipNet// 192.168.1.1
if ipNet.IP.To4() != nil {
ipv4 = ipNet // 192.168.1.1
return
}
}
......@@ -46,48 +46,47 @@ func GetLocalIP() (ipv4 *net.IPNet, err error) {
func GetLocalIpByName(name string) (ipv4 *net.IPNet, err error) {
if name == "" {
return nil,errors.New("name not empty")
return nil, errors.New("name not empty")
}
inter,err := net.InterfaceByName(name)
inter, err := net.InterfaceByName(name)
if err != nil {
return nil,err
return nil, err
}
var (
addrs []net.Addr
ipNet *net.IPNet // IP地址
isIpNet bool
)
if addrs,err = inter.Addrs(); err != nil {
return nil,err
if addrs, err = inter.Addrs(); err != nil {
return nil, err
}
for _, addr := range addrs {
if ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback(){
if ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback() {
// 跳过IPV6
if ipNet.IP.To4() != nil{
ipv4 = ipNet// 192.168.1.1
if ipNet.IP.To4() != nil {
ipv4 = ipNet // 192.168.1.1
return
}
}
}
return nil,nil
return nil, nil
}
func GetExternal() (string,error) {
func GetExternal() (string, error) {
resp, err := http.Get("http://myexternalip.com/raw")
if err != nil {
return "",err
return "", err
}
defer resp.Body.Close()
content,_ := ioutil.ReadAll(resp.Body)
return string(content),nil
content, _ := ioutil.ReadAll(resp.Body)
return string(content), nil
}
//两个以上空格替换成一个空格
func DeleteExtraSpace(s string) string {
//删除字符串中的多余空格,有多个空格时,仅保留一个空格
s1 := strings.Replace(s, " ", " ", -1) //替换tab为空格
s1 := strings.Replace(s, " ", " ", -1) //替换tab为空格
regstr := "\\s{2,}" //两个及两个以上空格的正则表达式
reg, _ := regexp.Compile(regstr) //编译正则表达式
s2 := make([]byte, len(s1)) //定义字符数组切片
......@@ -129,4 +128,3 @@ func VersionCompare(version string) string {
}
return string(vo)
}
package api
import (
"net/http"
"github.com/astaxie/beego/validation"
"github.com/gin-gonic/gin"
"chain33-pai/pkg/app"
"chain33-pai/pkg/e"
"chain33-pai/pkg/util"
"chain33-pai/service/auth_service"
)
type auth struct {
Username string `valid:"Required; MaxSize(50)"`
Password string `valid:"Required; MaxSize(50)"`
}
// @Summary Get Auth
// @Produce json
// @Param username query string true "userName"
// @Param password query string true "password"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /auth [get]
func GetAuth(c *gin.Context) {
appG := app.Gin{C: c}
valid := validation.Validation{}
username := c.Query("username")
password := c.Query("password")
a := auth{Username: username, Password: password}
ok, _ := valid.Valid(&a)
if !ok {
app.MarkErrors(valid.Errors)
appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
return
}
authService := auth_service.Auth{Username: username, Password: password}
isExist, err := authService.Check()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, nil)
return
}
if !isExist {
appG.Response(http.StatusUnauthorized, e.ERROR_AUTH, nil)
return
}
token, err := util.GenerateToken(username, password)
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
"token": token,
})
}
package v1
import (
"fmt"
"os"
"log"
"path"
"reflect"
"io/ioutil"
"os/exec"
"net/http"
"encoding/json"
"chain33-pai/pkg/e"
"bytes"
"chain33-pai/pkg/app"
"chain33-pai/pkg/chain33"
"chain33-pai/pkg/e"
"chain33-pai/pkg/setting"
"github.com/gin-gonic/gin"
"chain33-pai/service/pai_service"
"bytes"
"chain33-pai/pkg/chain33"
"encoding/json"
"fmt"
"github.com/33cn/chain33/types"
"github.com/gin-gonic/gin"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"reflect"
"strconv"
"strings"
"time"
"strconv"
)
var flag bool//判断是否正在更新
var flag bool //判断是否正在更新
func ResetWallet(c *gin.Context) {
appG := app.Gin{C: c}
app.BityuanFlag.Lock.Lock()
defer app.BityuanFlag.Lock.Unlock()
if app.BityuanFlag.Flag {
appG.Response(http.StatusOK, e.TRY_LATER,"other job is busy,please try later")
appG.Response(http.StatusOK, e.TRY_LATER, "other job is busy,please try later")
return
}
app.BityuanFlag.Flag = true
if app.NodeError!=nil{
if app.NodeError != nil {
tlog.Error(app.NodeError.Error())
appG.Response(http.StatusOK, e.NODE_ERROR,"node internal error,could not start node")
appG.Response(http.StatusOK, e.NODE_ERROR, "node internal error,could not start node")
app.BityuanFlag.Flag = false
return
}
t,err := app.SafeCloseNode()
t, err := app.SafeCloseNode()
if err != nil || !t {
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK,e.NODE_ERROR,err)
appG.Response(http.StatusOK, e.NODE_ERROR, err)
return
}
err=os.RemoveAll(fmt.Sprintf("%s/wallet",path.Dir(app.Bityuan.Path)))
if err!=nil{
appG.Response(http.StatusOK, e.NODE_ERROR, "fail to remove wallet")
tlog.Error("ResetWallet","remove error",err)
err = os.RemoveAll(fmt.Sprintf("%s/wallet", path.Dir(app.Bityuan.Path)))
if err != nil {
appG.Response(http.StatusOK, e.NODE_ERROR, "fail to remove wallet")
tlog.Error("ResetWallet", "remove error", err)
app.BityuanFlag.Flag = false
return
}
err=app.StartProcess(setting.Chain33Pai.Auto)
if err!=nil{
appG.Response(http.StatusOK, e.NODE_ERROR,"fail to restart node")
tlog.Error("ResetWallet","auto.sh error ",err)
err = app.StartProcess(setting.Chain33Pai.Auto)
if err != nil {
appG.Response(http.StatusOK, e.NODE_ERROR, "fail to restart node")
tlog.Error("ResetWallet", "auto.sh error ", err)
app.BityuanFlag.Flag = false
return
}
appG.Response(http.StatusOK, e.SUCCESS,"reset complete")
appG.Response(http.StatusOK, e.SUCCESS, "reset complete")
app.BityuanFlag.Flag = false
}
//钱包更新,只替换执行文件和配置文件
//具体更新逻辑不再代码实现
//oss下载包打包要保持执行权限
func UpdateNodeNew(c *gin.Context){
func UpdateNodeNew(c *gin.Context) {
appG := app.Gin{C: c}
app.BityuanFlag.Lock.Lock()
defer app.BityuanFlag.Lock.Unlock()
if app.BityuanFlag.Flag {
appG.Response(http.StatusOK,e.SUCCESS_RUNNING,"node is updating")
appG.Response(http.StatusOK, e.SUCCESS_RUNNING, "node is updating")
return
}
if app.NodeError!=nil{
appG.Response(http.StatusOK, e.NODE_ERROR,"node internal error,could not start node")
if app.NodeError != nil {
appG.Response(http.StatusOK, e.NODE_ERROR, "node internal error,could not start node")
return
}
absPath := app.GetAbsPath(setting.BityuanSetting.Name)+"/"
pwd,err := os.Getwd()
absPath := app.GetAbsPath(setting.BityuanSetting.Name) + "/"
pwd, err := os.Getwd()
if err != nil {
appG.Response(http.StatusOK, e.ERROR,"get pwd err")
appG.Response(http.StatusOK, e.ERROR, "get pwd err")
return
}
pwd = pwd + "/"
......@@ -91,39 +92,39 @@ func UpdateNodeNew(c *gin.Context){
setting.FreshVersion()
var pai pai_service.Pai
latestVersion,err := pai.GetPaiLatestVersion(int32(1))
latestVersion, err := pai.GetPaiLatestVersion(int32(1))
if err != nil {
appG.Response(http.StatusOK, e.NODE_ERROR,"get online version err")
appG.Response(http.StatusOK, e.NODE_ERROR, "get online version err")
app.BityuanFlag.Flag = false
//app.UpdateInfo.Flag = true
return
}
if latestVersion==setting.BityuanSetting.Version{
if latestVersion == setting.BityuanSetting.Version {
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK,e.SUCCESS,"current version is latest")
appG.Response(http.StatusOK, e.SUCCESS, "current version is latest")
return
}
if latestVersion==""{
if latestVersion == "" {
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK,e.NETWORK_ERROR,"network error,please checkout your network then try again")
appG.Response(http.StatusOK, e.NETWORK_ERROR, "network error,please checkout your network then try again")
return
}
stderr := bytes.NewBuffer(nil)
name := setting.BityuanSetting.Name+"_"+latestVersion+".tar.gz"
url := setting.Chain33Pai.DownloadUrl+ name
tlog.Info("UpdateNode","dir",setting.BityuanSetting.Name+"_"+latestVersion)
tlog.Info("UpdateNode","path",absPath)
err = app.DownLoadFile(url,name,int32(1))
name := setting.BityuanSetting.Name + "_" + latestVersion + ".tar.gz"
url := setting.Chain33Pai.DownloadUrl + name
tlog.Info("UpdateNode", "dir", setting.BityuanSetting.Name+"_"+latestVersion)
tlog.Info("UpdateNode", "path", absPath)
err = app.DownLoadFile(url, name, int32(1))
if err != nil {
appG.Response(http.StatusOK, e.DOWNLOAD_ERROR, err)
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
return
}
dirs := strings.Split(absPath,"wallet-bty")
dirs := strings.Split(absPath, "wallet-bty")
if len(dirs) != 2 {
appG.Response(http.StatusOK, e.ERROR, err)
//app.UpdateInfo.Flag = true
......@@ -131,11 +132,11 @@ func UpdateNodeNew(c *gin.Context){
return
}
//解压缩文件
tar := exec.Command("tar","-xvf",name ,"-C",dirs[0])
tar := exec.Command("tar", "-xvf", name, "-C", dirs[0])
tar.Stderr = stderr
err = tar.Start()
if err != nil {
tlog.Error("tar","err",err)
tlog.Error("tar", "err", err)
appG.Response(http.StatusOK, e.TAR_XVF_ERROR, err)
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
......@@ -143,22 +144,22 @@ func UpdateNodeNew(c *gin.Context){
}
err = tar.Wait()
if err != nil {
tlog.Error("tar","err",stderr.String())
tlog.Error("tar", "err", stderr.String())
appG.Response(http.StatusOK, e.TAR_XVF_ERROR, stderr.String())
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
return
}
t,err := app.SafeCloseNode()
t, err := app.SafeCloseNode()
if err != nil || !t {
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK,e.NODE_ERROR,err)
appG.Response(http.StatusOK, e.NODE_ERROR, err)
return
}
time.Sleep(time.Second*2)
remove := exec.Command("rm","-rf",setting.BityuanSetting.Name+"_"+latestVersion,name)
time.Sleep(time.Second * 2)
remove := exec.Command("rm", "-rf", setting.BityuanSetting.Name+"_"+latestVersion, name)
remove.Stderr = stderr
err = remove.Start()
if err != nil {
......@@ -174,308 +175,308 @@ func UpdateNodeNew(c *gin.Context){
app.BityuanFlag.Flag = false
return
}
err=app.StartProcess(setting.Chain33Pai.Auto)
if err!=nil{
appG.Response(http.StatusOK, e.NODE_ERROR,"fail to restart node")
tlog.Error("UpdateNodeNew","auto.sh error ",err)
err = app.StartProcess(setting.Chain33Pai.Auto)
if err != nil {
appG.Response(http.StatusOK, e.NODE_ERROR, "fail to restart node")
tlog.Error("UpdateNodeNew", "auto.sh error ", err)
//app.UpdateInfo.Flag = true
app.BityuanFlag.Flag = false
return
}
app.BityuanFlag.Flag = false
//app.UpdateInfo.Flag = true
appG.Response(http.StatusOK,e.SUCCESS,"update job ok")
appG.Response(http.StatusOK, e.SUCCESS, "update job ok")
}
//重置节点只需要删除datadir 然后重启节点
func ResetNode(c* gin.Context){
func ResetNode(c *gin.Context) {
appG := app.Gin{C: c}
app.BityuanFlag.Lock.Lock()
defer app.BityuanFlag.Lock.Unlock()
if app.BityuanFlag.Flag {
appG.Response(http.StatusOK, e.TRY_LATER,"other job is busy,please try later")
appG.Response(http.StatusOK, e.TRY_LATER, "other job is busy,please try later")
return
}
app.BityuanFlag.Flag = true
_,err := app.SafeCloseNode()
_, err := app.SafeCloseNode()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,"node err")
appG.Response(http.StatusOK, e.NODE_ERROR, "node err")
app.BityuanFlag.Flag = false
return
}
err = os.RemoveAll(fmt.Sprintf("%s/datadir",path.Dir(app.Bityuan.Path)))
err = os.RemoveAll(fmt.Sprintf("%s/datadir", path.Dir(app.Bityuan.Path)))
if err != nil {
app.BityuanFlag.Flag = false
tlog.Error("ResetNode","remove datadir err",err)
appG.Response(http.StatusOK, e.RM_ERROR,"remove datadir err")
tlog.Error("ResetNode", "remove datadir err", err)
appG.Response(http.StatusOK, e.RM_ERROR, "remove datadir err")
return
}
err=app.StartProcess(setting.Chain33Pai.Auto)
err = app.StartProcess(setting.Chain33Pai.Auto)
if err != nil {
tlog.Error("ResetNode","start node err",err)
tlog.Error("ResetNode", "start node err", err)
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK, e.NODE_ERROR,"start auto sh err")
appG.Response(http.StatusOK, e.NODE_ERROR, "start auto sh err")
return
}
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK,e.SUCCESS,"reset job ok")
appG.Response(http.StatusOK, e.SUCCESS, "reset job ok")
}
func UpdateDetail(c* gin.Context){
func UpdateDetail(c *gin.Context) {
appG := app.Gin{C: c}
appG.Response(http.StatusOK,e.SUCCESS,gin.H{
"total":app.UpdateInfo.Total,
"current":app.UpdateInfo.Current,
appG.Response(http.StatusOK, e.SUCCESS, gin.H{
"total": app.UpdateInfo.Total,
"current": app.UpdateInfo.Current,
})
}
//get current version and latest version
func Version(c* gin.Context){
func Version(c *gin.Context) {
appG := app.Gin{C: c}
setting.FreshVersion()
//latestVersion:=app.GetLatestVersion()
var pai pai_service.Pai
//1 bityuan 2 chain33-pai
latestVersion,err := pai.GetPaiLatestVersion(int32(1))
latestVersion, err := pai.GetPaiLatestVersion(int32(1))
if latestVersion=="" || err != nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"network error,please try again")
if latestVersion == "" || err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "network error,please try again")
return
}
appG.Response(http.StatusOK,e.SUCCESS,gin.H{
"current":setting.BityuanSetting.Version,
"latest" :latestVersion,
appG.Response(http.StatusOK, e.SUCCESS, gin.H{
"current": setting.BityuanSetting.Version,
"latest": latestVersion,
})
}
func NodeInfo(c *gin.Context){
appG:=app.Gin{C:c}
func NodeInfo(c *gin.Context) {
appG := app.Gin{C: c}
var client chain33.PaiClient
_,err := client.Version()
_, err := client.Version()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,"node down")
appG.Response(http.StatusOK, e.NODE_ERROR, "node down")
return
}
appG.Response(http.StatusOK,e.SUCCESS,"node is running")
appG.Response(http.StatusOK, e.SUCCESS, "node is running")
}
func RestartNode(c* gin.Context){
appG:=app.Gin{C:c}
func RestartNode(c *gin.Context) {
appG := app.Gin{C: c}
app.BityuanFlag.Flag = true
_,err := app.SafeCloseNode()
_, err := app.SafeCloseNode()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,"node err")
appG.Response(http.StatusOK, e.NODE_ERROR, "node err")
app.BityuanFlag.Flag = false
return
}
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK,e.SUCCESS,"node close safe")
appG.Response(http.StatusOK, e.SUCCESS, "node close safe")
}
func CloseNode(c* gin.Context){
appG:=app.Gin{C:c}
func CloseNode(c *gin.Context) {
appG := app.Gin{C: c}
app.BityuanFlag.Flag = true
_,err := app.SafeCloseNode()
_, err := app.SafeCloseNode()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,"node err")
appG.Response(http.StatusOK, e.NODE_ERROR, "node err")
app.BityuanFlag.Flag = false
return
}
//防止其他模块未关闭
//time.Sleep(time.Second * 2)
if !app.MakeSureBtyIsNotRun() {
appG.Response(http.StatusOK,e.NODE_ERROR,"node stop err")
appG.Response(http.StatusOK, e.NODE_ERROR, "node stop err")
app.BityuanFlag.Flag = false
return
}
appG.Response(http.StatusOK,e.SUCCESS,"node close safe")
appG.Response(http.StatusOK, e.SUCCESS, "node close safe")
}
//反馈信息
func FeedBack(c *gin.Context){
appG:=app.Gin{C:c}
app.Preprocessing()
ssh_keygen:=exec.Command(fmt.Sprintf("%s%sssh-keygen.sh",setting.Chain33Pai.Path,setting.Chain33Pai.Scripts))
err:=ssh_keygen.Start()
if err!=nil{
appG.Response(http.StatusOK,e.ENV_ERROR,nil)
log.Println(err)
return
}
err=ssh_keygen.Wait()
if err!=nil{
appG.Response(http.StatusOK,e.ENV_ERROR,nil)
log.Println(err)
return
}
local_keyPair:=make(map[string]string)
results:=make(map[string]string)
keyPairStream,_:=ioutil.ReadAll(appG.C.Request.Body)
err=json.Unmarshal(keyPairStream,&local_keyPair)
if err!=nil{
appG.Response(http.StatusOK,e.INVALID_PARAMS,nil)
log.Println(err)
return
}
local_keyPair["public"]=app.GetPubKey()
keyPairStream,_=json.Marshal(local_keyPair)
resp,err:=http.Post(setting.Chain33Pai.FeedBackUrl,"application/json",bytes.NewReader(keyPairStream))
if err!=nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络错误")
log.Println(err)
return
}
keyPairStream,_=ioutil.ReadAll(resp.Body)
//log.Println(string(keyPairStream))
err=json.Unmarshal(keyPairStream,&results)
if err!=nil{
appG.Response(http.StatusOK,e.ENV_ERROR,"系统错误")
func FeedBack(c *gin.Context) {
appG := app.Gin{C: c}
app.Preprocessing()
ssh_keygen := exec.Command(fmt.Sprintf("%s%sssh-keygen.sh", setting.Chain33Pai.Path, setting.Chain33Pai.Scripts))
err := ssh_keygen.Start()
if err != nil {
appG.Response(http.StatusOK, e.ENV_ERROR, nil)
log.Println(err)
return
}
err = ssh_keygen.Wait()
if err != nil {
appG.Response(http.StatusOK, e.ENV_ERROR, nil)
log.Println(err)
return
}
local_keyPair := make(map[string]string)
results := make(map[string]string)
keyPairStream, _ := ioutil.ReadAll(appG.C.Request.Body)
err = json.Unmarshal(keyPairStream, &local_keyPair)
if err != nil {
appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
log.Println(err)
return
}
local_keyPair["public"] = app.GetPubKey()
keyPairStream, _ = json.Marshal(local_keyPair)
resp, err := http.Post(setting.Chain33Pai.FeedBackUrl, "application/json", bytes.NewReader(keyPairStream))
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络错误")
log.Println(err)
return
}
keyPairStream, _ = ioutil.ReadAll(resp.Body)
//log.Println(string(keyPairStream))
err = json.Unmarshal(keyPairStream, &results)
if err != nil {
appG.Response(http.StatusOK, e.ENV_ERROR, "系统错误")
log.Println(err)
return
}
if results["code"] == "200" {
setting.ReverseTunnelPort = results["port"]
//log.Println(results)
ssh := exec.Command(fmt.Sprintf("%s%sautosshdaemon.sh", setting.Chain33Pai.Path, setting.Chain33Pai.Scripts), results["daemon"], results["port"], setting.Chain33Pai.RaspberryServer)
//log.Println(ssh.String())
err = ssh.Run()
if err != nil {
log.Println(err)
appG.Response(http.StatusOK, e.ENV_ERROR, nil)
return
}
if results["code"]=="200"{
setting.ReverseTunnelPort=results["port"]
//log.Println(results)
ssh := exec.Command(fmt.Sprintf("%s%sautosshdaemon.sh",setting.Chain33Pai.Path,setting.Chain33Pai.Scripts),results["daemon"],results["port"], setting.Chain33Pai.RaspberryServer)
//log.Println(ssh.String())
err=ssh.Run()
if err!=nil{
log.Println(err)
appG.Response(http.StatusOK,e.ENV_ERROR,nil)
return
}
appG.Response(http.StatusOK,e.SUCCESS,nil)
return
}
appG.Response(http.StatusOK,e.NETWORK_ERROR,nil)
appG.Response(http.StatusOK, e.SUCCESS, nil)
return
}
appG.Response(http.StatusOK, e.NETWORK_ERROR, nil)
}
//反馈信息
func FeedBackWithoutSSH(c *gin.Context){
appG:=app.Gin{C:c}
local_keyPair:=make(map[string]string)
results:=make(map[string]string)
keyPairStream,_:=ioutil.ReadAll(appG.C.Request.Body)
err:=json.Unmarshal(keyPairStream,&local_keyPair)
if err!=nil{
appG.Response(http.StatusOK,e.INVALID_PARAMS,nil)
func FeedBackWithoutSSH(c *gin.Context) {
appG := app.Gin{C: c}
local_keyPair := make(map[string]string)
results := make(map[string]string)
keyPairStream, _ := ioutil.ReadAll(appG.C.Request.Body)
err := json.Unmarshal(keyPairStream, &local_keyPair)
if err != nil {
appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
log.Println(err)
return
}
keyPairStream,_=json.Marshal(local_keyPair)
resp,err:=http.Post(setting.Chain33Pai.FeedBackNosshUrl,"application/json",bytes.NewReader(keyPairStream))
if err!=nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络错误")
keyPairStream, _ = json.Marshal(local_keyPair)
resp, err := http.Post(setting.Chain33Pai.FeedBackNosshUrl, "application/json", bytes.NewReader(keyPairStream))
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络错误")
log.Println(err)
return
}
keyPairStream,_=ioutil.ReadAll(resp.Body)
keyPairStream, _ = ioutil.ReadAll(resp.Body)
log.Println(string(keyPairStream))
err=json.Unmarshal(keyPairStream,&results)
if err!=nil{
appG.Response(http.StatusOK,e.ENV_ERROR,"系统错误")
err = json.Unmarshal(keyPairStream, &results)
if err != nil {
appG.Response(http.StatusOK, e.ENV_ERROR, "系统错误")
log.Println(err)
return
}
if results["code"]=="200"{
appG.Response(http.StatusOK,e.SUCCESS,nil)
if results["code"] == "200" {
appG.Response(http.StatusOK, e.SUCCESS, nil)
return
}
appG.Response(http.StatusOK,e.NETWORK_ERROR,nil)
appG.Response(http.StatusOK, e.NETWORK_ERROR, nil)
}
func FeedBackStatusWithoutSSH(c *gin.Context){
appG:=app.Gin{C:c}
func FeedBackStatusWithoutSSH(c *gin.Context) {
appG := app.Gin{C: c}
results := make(map[string]interface{})
var pai pai_service.Pai
pai.GetConfig()
results["addr"] = pai.Serial
keyPairStream,_ :=json.Marshal(results)
keyPairStream, _ := json.Marshal(results)
resp,err:=http.Post(setting.Chain33Pai.IsCompleteNosshUrl,"application/json",bytes.NewReader(keyPairStream))
if err!=nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络错误")
resp, err := http.Post(setting.Chain33Pai.IsCompleteNosshUrl, "application/json", bytes.NewReader(keyPairStream))
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络错误")
log.Println(err)
return
}
data,_ :=ioutil.ReadAll(resp.Body)
err=json.Unmarshal(data,&results)
if err!=nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络错误")
data, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(data, &results)
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络错误")
log.Println(err)
return
}
if results["code"]==float64(e.UNDONE){
appG.Response(http.StatusOK,e.UNDONE,"未解决")
if results["code"] == float64(e.UNDONE) {
appG.Response(http.StatusOK, e.UNDONE, "未解决")
return
}
if results["msg"]=="ok"{
appG.Response(http.StatusOK,e.SUCCESS,nil)
if results["msg"] == "ok" {
appG.Response(http.StatusOK, e.SUCCESS, nil)
return
}
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络出错")
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络出错")
log.Println(results)
}
func FeedBackStatus(c *gin.Context){
appG:=app.Gin{C:c}
results:=make(map[string]interface{})
func FeedBackStatus(c *gin.Context) {
appG := app.Gin{C: c}
results := make(map[string]interface{})
//results_port:=make(map[string]interface{})
results["port"]=setting.ReverseTunnelPort
results["port"] = setting.ReverseTunnelPort
if results["port"]==""{
appG.Response(http.StatusOK,e.NO_JOB,"没有反馈记录")
if results["port"] == "" {
appG.Response(http.StatusOK, e.NO_JOB, "没有反馈记录")
return
}
data,_:=json.Marshal(&results)
resp,err:=http.Post(setting.Chain33Pai.IsCompleteUrl,"application/json",bytes.NewReader(data))
if err!=nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络错误")
data, _ := json.Marshal(&results)
resp, err := http.Post(setting.Chain33Pai.IsCompleteUrl, "application/json", bytes.NewReader(data))
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络错误")
log.Println(err)
return
}
data,_=ioutil.ReadAll(resp.Body)
err=json.Unmarshal(data,&results)
if err!=nil{
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络错误")
data, _ = ioutil.ReadAll(resp.Body)
err = json.Unmarshal(data, &results)
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络错误")
log.Println(err)
return
}
fmt.Println(reflect.TypeOf(e.UNDONE))
if results["code"]==float64(e.UNDONE){
appG.Response(http.StatusOK,e.UNDONE,"未解决")
if results["code"] == float64(e.UNDONE) {
appG.Response(http.StatusOK, e.UNDONE, "未解决")
return
}
if results["msg"]=="ok"{
appG.Response(http.StatusOK,e.SUCCESS,nil)
breakConn:=exec.Command(fmt.Sprintf("%s%sautossh.sh",setting.Chain33Pai.Path,setting.Chain33Pai.Scripts))
err:=breakConn.Start()
if err!=nil{
if results["msg"] == "ok" {
appG.Response(http.StatusOK, e.SUCCESS, nil)
breakConn := exec.Command(fmt.Sprintf("%s%sautossh.sh", setting.Chain33Pai.Path, setting.Chain33Pai.Scripts))
err := breakConn.Start()
if err != nil {
return
}
err=breakConn.Wait()
err = breakConn.Wait()
return
}
appG.Response(http.StatusOK,e.NETWORK_ERROR,"网络出错")
appG.Response(http.StatusOK, e.NETWORK_ERROR, "网络出错")
log.Println(results)
}
func EscrowPasswd(c *gin.Context){
func EscrowPasswd(c *gin.Context) {
type Password struct {
Password string `json:"password" binding:"required"`
}
var passwd Password
appG:=app.Gin{C:c}
err:=appG.C.ShouldBindJSON(&passwd)
if err!=nil{
appG.Response(http.StatusOK,e.INVALID_PARAMS,nil)
appG := app.Gin{C: c}
err := appG.C.ShouldBindJSON(&passwd)
if err != nil {
appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
tlog.Info("invalid params")
return
}
r,errs:=setting.PaiClient.Unlock(&types.WalletUnLock{
r, errs := setting.PaiClient.Unlock(&types.WalletUnLock{
Passwd: passwd.Password,
Timeout: 0,
WalletOrTicket: false,
......@@ -483,60 +484,61 @@ func EscrowPasswd(c *gin.Context){
XXX_unrecognized: nil,
XXX_sizecache: 0,
})
if errs!=nil{
appG.Response(http.StatusOK,e.NODE_ERROR,nil)
tlog.Info("节点故障",err)
if errs != nil {
appG.Response(http.StatusOK, e.NODE_ERROR, nil)
tlog.Info("节点故障", err)
return
}//覆盖原有密码
if !r.IsOk{
appG.Response(http.StatusOK,e.ERROR_AUTH,r.Msg)
tlog.Info("Auth Faild","password",passwd.Password)
} //覆盖原有密码
if !r.IsOk {
appG.Response(http.StatusOK, e.ERROR_AUTH, r.Msg)
tlog.Info("Auth Faild", "password", passwd.Password)
return
}
f,err:=os.OpenFile(setting.BityuanSetting.Passwd,os.O_WRONLY|os.O_TRUNC|os.O_CREATE,0666)
f, err := os.OpenFile(setting.BityuanSetting.Passwd, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
defer f.Close()
if err!=nil{
appG.Response(http.StatusOK,e.ENV_ERROR,nil)
if err != nil {
appG.Response(http.StatusOK, e.ENV_ERROR, nil)
tlog.Info(err.Error())
return
}
f.WriteString(passwd.Password)
appG.Response(http.StatusOK,e.SUCCESS,nil)
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
//如果bityuan进程开启 端口没开启 默认认为是在版本内部升级过程中 确定是否还在版本更新中 status false 表示已同步完成 true 表示还在版本同步中
func UpdateNodeStatus(c *gin.Context){
appG:=app.Gin{C:c}
func UpdateNodeStatus(c *gin.Context) {
appG := app.Gin{C: c}
var update bool
var buf bytes.Buffer
cmd := exec.Command("netstat", "-tunlp")
cmd.Stdout = &buf
err := cmd.Run()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,nil)
appG.Response(http.StatusOK, e.NODE_ERROR, nil)
return
}
//程序运行 + 端口没开启
if strings.Contains(buf.String(),"v7-bityuan") && !strings.Contains(buf.String(),":8801") {
if strings.Contains(buf.String(), "v7-bityuan") && !strings.Contains(buf.String(), ":8801") {
update = true
} else if !strings.Contains(buf.String(),"v7-bityuan") {
appG.Response(http.StatusOK,e.NODE_ERROR,nil)
} else if !strings.Contains(buf.String(), "v7-bityuan") {
appG.Response(http.StatusOK, e.NODE_ERROR, nil)
return
}
appG.Response(http.StatusOK,e.SUCCESS,gin.H{
"status":update,
appG.Response(http.StatusOK, e.SUCCESS, gin.H{
"status": update,
})
}
func PoweroffPai(c *gin.Context) {
appG:=app.Gin{C:c}
appG := app.Gin{C: c}
app.BityuanFlag.Lock.Lock()
defer app.BityuanFlag.Lock.Unlock()
app.BityuanFlag.Flag = true
_,err := app.SafeCloseNode()
_, err := app.SafeCloseNode()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,err)
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK, e.NODE_ERROR, err)
app.BityuanFlag.Flag = false
return
}
var buf bytes.Buffer
......@@ -544,117 +546,117 @@ func PoweroffPai(c *gin.Context) {
cmd.Stdout = &buf
err = cmd.Run()
if err != nil {
appG.Response(http.StatusOK,e.NODE_ERROR,err)
app.BityuanFlag.Flag = false
appG.Response(http.StatusOK, e.NODE_ERROR, err)
app.BityuanFlag.Flag = false
return
}
appG.Response(http.StatusOK,e.SUCCESS,"pai restarted")
appG.Response(http.StatusOK, e.SUCCESS, "pai restarted")
}
func Test(c *gin.Context) {
appG:=app.Gin{C:c}
report ,_:= ioutil.ReadAll(appG.C.Request.Body)
tlog.Info("test","report",string(report))
appG := app.Gin{C: c}
report, _ := ioutil.ReadAll(appG.C.Request.Body)
tlog.Info("test", "report", string(report))
client := &http.Client{}
params:=make(map[string]interface{})
params := make(map[string]interface{})
params["report"] = string(report)
data,_ := json.Marshal(params)
req ,_ := http.NewRequest("post",setting.Chain33Pai.UploadTestUrl,bytes.NewReader(data))
resp,_:=client.Do(req)
data, _ := json.Marshal(params)
req, _ := http.NewRequest("post", setting.Chain33Pai.UploadTestUrl, bytes.NewReader(data))
resp, _ := client.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
tlog.Info("uploadtest","report",string(body))
appG.Response(http.StatusOK,e.SUCCESS,"")
tlog.Info("uploadtest", "report", string(body))
appG.Response(http.StatusOK, e.SUCCESS, "")
}
func Rollback(c *gin.Context) {
appG:=app.Gin{C:c}
app.JobChan <- app.MsgType{Name:"ROLLBACK"}
appG.Response(http.StatusOK,e.SUCCESS,"bityuan rollback")
appG := app.Gin{C: c}
app.JobChan <- app.MsgType{Name: "ROLLBACK"}
appG.Response(http.StatusOK, e.SUCCESS, "bityuan rollback")
}
func NodeBackup(c *gin.Context) {
appG:=app.Gin{C:c}
appG := app.Gin{C: c}
var pai pai_service.Pai
err := pai.GetDiskUseage()
if err != nil {
tlog.Error("GetDiskUseage","err",err)
appG.Response(http.StatusOK,e.ENV_ERROR,"get diskuseage err")
tlog.Error("GetDiskUseage", "err", err)
appG.Response(http.StatusOK, e.ENV_ERROR, "get diskuseage err")
return
}
if len(pai.Disks) == 0 {
tlog.Error("disk ","err","disk not find")
appG.Response(http.StatusOK,e.ENV_ERROR,"disk not find")
tlog.Error("disk ", "err", "disk not find")
appG.Response(http.StatusOK, e.ENV_ERROR, "disk not find")
return
}
tlog.Info("disk info","ssd",pai.Disks[0])
tlog.Info("disk info", "ssd", pai.Disks[0])
p := pai.Disks[0].Use
ps := strings.Split(p,"%")
pint,_ := strconv.Atoi(ps[0])
if pint * 2 > 80 {
tlog.Error("disk space ","err","space not enough to backup")
appG.Response(http.StatusOK,e.ENV_ERROR,"disk space not enough")
ps := strings.Split(p, "%")
pint, _ := strconv.Atoi(ps[0])
if pint*2 > 80 {
tlog.Error("disk space ", "err", "space not enough to backup")
appG.Response(http.StatusOK, e.ENV_ERROR, "disk space not enough")
return
}
app.JobChan <- app.MsgType{Name:"BACKUP"}
appG.Response(http.StatusOK,e.SUCCESS,"bityuan ready to backup")
app.JobChan <- app.MsgType{Name: "BACKUP"}
appG.Response(http.StatusOK, e.SUCCESS, "bityuan ready to backup")
}
func CheckBackup(c *gin.Context) {
appG:=app.Gin{C:c}
appG := app.Gin{C: c}
path := app.GetAbsPath(setting.BityuanSetting.Name)
backupPath := path + "/datadir_backup"
if _,err := os.Stat(backupPath);err != nil {
tlog.Info("CheckBackup","err",err)
if _, err := os.Stat(backupPath); err != nil {
tlog.Info("CheckBackup", "err", err)
if os.IsNotExist(err) {
tlog.Error("CheckBackup file not exists","err",backupPath)
appG.Response(http.StatusOK,e.ERROR,false)
tlog.Error("CheckBackup file not exists", "err", backupPath)
appG.Response(http.StatusOK, e.ERROR, false)
return
}
}
appG.Response(http.StatusOK,e.SUCCESS,true)
appG.Response(http.StatusOK, e.SUCCESS, true)
}
func NodeRecover(c *gin.Context) {
appG:=app.Gin{C:c}
appG := app.Gin{C: c}
var pai pai_service.Pai
err := pai.GetDiskUseage()
if err != nil {
tlog.Error("GetDiskUseage","err",err)
appG.Response(http.StatusOK,e.ENV_ERROR,"get diskuseage err")
tlog.Error("GetDiskUseage", "err", err)
appG.Response(http.StatusOK, e.ENV_ERROR, "get diskuseage err")
return
}
if len(pai.Disks) == 0 {
tlog.Error("disk ","err","disk not find")
appG.Response(http.StatusOK,e.ENV_ERROR,"disk not find")
tlog.Error("disk ", "err", "disk not find")
appG.Response(http.StatusOK, e.ENV_ERROR, "disk not find")
return
}
tlog.Info("disk info","ssd",pai.Disks[0])
tlog.Info("disk info", "ssd", pai.Disks[0])
p := pai.Disks[0].Use
ps := strings.Split(p,"%")
pint,_ := strconv.Atoi(ps[0])
ps := strings.Split(p, "%")
pint, _ := strconv.Atoi(ps[0])
if pint > 90 {
tlog.Error("disk ","err","disk space not enough")
tlog.Error("disk ", "err", "disk space not enough")
//app.JobChan <- app.MsgType{Name:"DELETEBACKUP"}
}
app.JobChan <- app.MsgType{Name:"RECOVER"}
appG.Response(http.StatusOK,e.SUCCESS,"bityuan ready to recover")
app.JobChan <- app.MsgType{Name: "RECOVER"}
appG.Response(http.StatusOK, e.SUCCESS, "bityuan ready to recover")
}
func DelBackup(c *gin.Context) {
appG:=app.Gin{C:c}
appG := app.Gin{C: c}
var pai pai_service.Pai
err := pai.GetDiskUseage()
if err != nil {
tlog.Error("GetDiskUseage","err",err)
appG.Response(http.StatusOK,e.ENV_ERROR,"get diskuseage err")
tlog.Error("GetDiskUseage", "err", err)
appG.Response(http.StatusOK, e.ENV_ERROR, "get diskuseage err")
return
}
if len(pai.Disks) == 0 {
tlog.Error("disk ","err","disk not find")
appG.Response(http.StatusOK,e.ENV_ERROR,"disk not find")
tlog.Error("disk ", "err", "disk not find")
appG.Response(http.StatusOK, e.ENV_ERROR, "disk not find")
return
}
tlog.Info("disk info","ssd",pai.Disks[0])
app.JobChan <- app.MsgType{Name:"DELETEBACKUP"}
appG.Response(http.StatusOK,e.ENV_ERROR,"del backup")
}
\ No newline at end of file
tlog.Info("disk info", "ssd", pai.Disks[0])
app.JobChan <- app.MsgType{Name: "DELETEBACKUP"}
appG.Response(http.StatusOK, e.ENV_ERROR, "del backup")
}
package v1
import (
"os"
"net/http"
"chain33-pai/pkg/e"
"chain33-pai/pkg/app"
"github.com/gin-gonic/gin"
"chain33-pai/service/pai_service"
"chain33-pai/pkg/e"
"chain33-pai/pkg/pai"
"chain33-pai/pkg/setting"
"os/exec"
log "github.com/33cn/chain33/common/log/log15"
"chain33-pai/pkg/util"
"chain33-pai/pkg/pai"
"chain33-pai/service/pai_service"
log "github.com/33cn/chain33/common/log/log15"
"github.com/gin-gonic/gin"
"net/http"
"os"
"os/exec"
)
var tlog = log.New("api", "v1")
......@@ -40,18 +40,18 @@ func GetDevstatus(c *gin.Context) {
//获取chain33-pai程序版本
func GetPaiVersion(c *gin.Context) {
appG := app.Gin{C:c}
appG := app.Gin{C: c}
version := app.GetVersion()
var pai pai_service.Pai
latest,err := pai.GetPaiLatestVersion(int32(2))
latest, err := pai.GetPaiLatestVersion(int32(2))
if err != nil {
appG.Response(http.StatusOK, e.NETWORK_ERROR, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, gin.H{
"current":version,
"latest":latest,
"current": version,
"latest": latest,
})
}
......@@ -59,7 +59,7 @@ func GetPaiVersion(c *gin.Context) {
//具体更新逻辑写在代码 更新迭代比较麻烦 改为下面new方法
//下载地址阿里云oss地址 固定ip格式+/+chain33-pai+x.x.x+.tar.gz
func UpdatePai(c *gin.Context) {
appG := app.Gin{C:c}
appG := app.Gin{C: c}
if app.DPercent.Flag {
appG.Response(http.StatusOK, e.DOWNLOAD_ERROR, "正在升级中,不要重复点击")
return
......@@ -83,7 +83,7 @@ func UpdatePai(c *gin.Context) {
}
//检查版本号是否存在于online数据库
var pai pai_service.Pai
latest,err := pai.GetPaiLatestVersion(int32(2))
latest, err := pai.GetPaiLatestVersion(int32(2))
if err != nil {
appG.Response(http.StatusOK, e.DOWNLOAD_ERROR, err)
app.DPercent.Flag = false
......@@ -96,102 +96,102 @@ func UpdatePai(c *gin.Context) {
app.DPercent.Flag = false
return
}
name := setting.Chain33Pai.Name+"_"+req.Version+".tar.gz"
url := setting.Chain33Pai.DownloadUrl+ name
name := setting.Chain33Pai.Name + "_" + req.Version + ".tar.gz"
url := setting.Chain33Pai.DownloadUrl + name
//oss下载更新包
err = app.DownLoadFile(url,name,int32(2))
err = app.DownLoadFile(url, name, int32(2))
if err != nil {
appG.Response(http.StatusOK, e.DOWNLOAD_ERROR, err)
app.DPercent.Flag = false
return
}
//解压缩文件
tar := exec.Command("tar","-xvf",name)
tar := exec.Command("tar", "-xvf", name)
err = tar.Start()
if err != nil {
tlog.Error("tar","err",err)
tlog.Error("tar", "err", err)
appG.Response(http.StatusOK, e.TAR_XVF_ERROR, err)
app.DPercent.Flag = false
return
}
err = tar.Wait()
if err != nil {
tlog.Error("tar","err",err)
tlog.Error("tar", "err", err)
appG.Response(http.StatusOK, e.TAR_XVF_ERROR, err)
app.DPercent.Flag = false
return
}
//备份原文件 确保没有alias 关联
bak := exec.Command("cp",setting.Chain33Pai.Name,setting.Chain33Pai.Name+".bak")
bak := exec.Command("cp", setting.Chain33Pai.Name, setting.Chain33Pai.Name+".bak")
err = bak.Start()
if err != nil {
tlog.Error("bak","err",err)
tlog.Error("bak", "err", err)
appG.Response(http.StatusOK, e.CP_ERROR, err)
app.DPercent.Flag = false
return
}
err = bak.Wait()
if err != nil {
tlog.Error("bak","err",err)
tlog.Error("bak", "err", err)
appG.Response(http.StatusOK, e.CP_ERROR, err)
app.DPercent.Flag = false
return
}
//备份配置文件
bakconf := exec.Command("cp","conf/app.ini","conf/app.ini.bak")
bakconf := exec.Command("cp", "conf/app.ini", "conf/app.ini.bak")
err = bakconf.Start()
if err != nil {
tlog.Error("bakconf","err",err)
tlog.Error("bakconf", "err", err)
appG.Response(http.StatusOK, e.CP_ERROR, err)
app.DPercent.Flag = false
return
}
err = bakconf.Wait()
if err != nil {
tlog.Error("bakconf","err",err)
tlog.Error("bakconf", "err", err)
appG.Response(http.StatusOK, e.CP_ERROR, err)
app.DPercent.Flag = false
return
}
//替换原执行文件
mv := exec.Command("mv",setting.Chain33Pai.Name+"_"+req.Version+"/"+setting.Chain33Pai.Name,".")
mv := exec.Command("mv", setting.Chain33Pai.Name+"_"+req.Version+"/"+setting.Chain33Pai.Name, ".")
err = mv.Start()
if err != nil {
tlog.Error("mv","err",err)
tlog.Error("mv", "err", err)
appG.Response(http.StatusOK, e.MV_ERROR, err)
app.DPercent.Flag = false
return
}
err = mv.Wait()
if err != nil {
tlog.Error("mv","err",err)
tlog.Error("mv", "err", err)
appG.Response(http.StatusOK, e.MV_ERROR, err)
app.DPercent.Flag = false
return
}
//替换配置文件
mvconf := exec.Command("mv",setting.Chain33Pai.Name+"_"+req.Version+"/conf/app.ini","conf")
mvconf := exec.Command("mv", setting.Chain33Pai.Name+"_"+req.Version+"/conf/app.ini", "conf")
err = mvconf.Start()
if err != nil {
tlog.Error("mvconf","err",err)
tlog.Error("mvconf", "err", err)
appG.Response(http.StatusOK, e.MV_ERROR, err)
app.DPercent.Flag = false
return
}
err = mvconf.Wait()
if err != nil {
tlog.Error("mvconf","err",err)
tlog.Error("mvconf", "err", err)
appG.Response(http.StatusOK, e.MV_ERROR, err)
app.DPercent.Flag = false
return
}
os.RemoveAll("scripts")
os.Mkdir("scripts",0600)
os.RemoveAll("scripts")
os.Mkdir("scripts", 0600)
//删除temp文件夹
//替换原执行文件
app.MVScripts(setting.Chain33Pai.Name+"_"+req.Version,".")
app.MVScripts(setting.Chain33Pai.Name+"_"+req.Version, ".")
remove := exec.Command("rm","-rf",setting.Chain33Pai.Name+"_"+req.Version,name)
remove := exec.Command("rm", "-rf", setting.Chain33Pai.Name+"_"+req.Version, name)
err = remove.Start()
if err != nil {
appG.Response(http.StatusOK, e.RM_ERROR, err)
......@@ -212,7 +212,7 @@ func UpdatePai(c *gin.Context) {
//忽略req.Version 对比自己版本和最新版本 直接更新覆盖最新版本
//下载地址阿里云oss地址 固定ip格式+/+chain33-pai+x.x.x+.tar.gz
func UpdatePaiNew(c *gin.Context) {
appG := app.Gin{C:c}
appG := app.Gin{C: c}
if app.DPercent.Flag {
appG.Response(http.StatusOK, e.DOWNLOAD_ERROR, "正在升级中,不要重复点击")
return
......@@ -238,18 +238,17 @@ func UpdatePaiNew(c *gin.Context) {
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
func GetDPercent(c *gin.Context) {
appG := app.Gin{C:c}
appG := app.Gin{C: c}
appG.Response(http.StatusOK, e.SUCCESS, gin.H{
"total":app.DPercent.Total,
"current":app.DPercent.Current,
"total": app.DPercent.Total,
"current": app.DPercent.Current,
})
}
func GetExternal(c *gin.Context) {
appG := app.Gin{C:c}
ip,err := util.GetExternal()
appG := app.Gin{C: c}
ip, err := util.GetExternal()
if err != nil {
appG.Response(http.StatusOK, e.ERROR, "get external ip err")
return
......@@ -258,12 +257,12 @@ func GetExternal(c *gin.Context) {
}
func GetServerStatus(c *gin.Context) {
appG := app.Gin{C:c}
disks,err := pai.MonitorServer()
appG := app.Gin{C: c}
disks, err := pai.MonitorServer()
if err != nil {
appG.Response(http.StatusOK, e.ERROR, err)
return
}
app.ServerStatus.Disks = disks
appG.Response(http.StatusOK, e.SUCCESS, app.ServerStatus)
}
\ No newline at end of file
}
package routers
import (
"github.com/gin-gonic/gin"
_ "chain33-pai/docs"
"chain33-pai/routers/api/v1"
"github.com/gin-gonic/gin"
"net/http"
)
// InitRouter initialize routing information
func InitRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(Cors())
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(Cors())
apiv1 := r.Group("/pai")
//获取树莓派基本信息
apiv1.POST("/devdetail",v1.GetDevdetail)
apiv1.POST("/devdetail", v1.GetDevdetail)
//获取树莓派基本信息
apiv1.POST("/resetwallet",v1.ResetWallet)
apiv1.POST("/resetwallet", v1.ResetWallet)
//更新bityuan节点 下载替换 重启
apiv1.POST("/updatenode",v1.UpdateNodeNew)
apiv1.POST("/updatenode", v1.UpdateNodeNew)
//检查节点是否还在更新同步 节点6.4.0大版本更新可能需要十几个小时 故加此接口
apiv1.POST("/nodeupdate",v1.UpdateNodeStatus)
apiv1.POST("/devstatus",v1.GetDevstatus)
apiv1.POST("/updatedetail",v1.UpdateDetail)
apiv1.POST("/version",v1.Version)
apiv1.POST("/reset",v1.ResetNode)
apiv1.POST("/nodeinfo",v1.NodeInfo)
apiv1.POST("/nodeupdate", v1.UpdateNodeStatus)
apiv1.POST("/devstatus", v1.GetDevstatus)
apiv1.POST("/updatedetail", v1.UpdateDetail)
apiv1.POST("/version", v1.Version)
apiv1.POST("/reset", v1.ResetNode)
apiv1.POST("/nodeinfo", v1.NodeInfo)
//本程序版本
apiv1.POST("/paiversion",v1.GetPaiVersion)
apiv1.POST("/paiversion", v1.GetPaiVersion)
//本程序下载新版本
apiv1.POST("/updatepai",v1.UpdatePaiNew)
apiv1.POST("/updatepai", v1.UpdatePaiNew)
//获取下载进度
apiv1.POST("/dpercent",v1.GetDPercent)
apiv1.POST("/dpercent", v1.GetDPercent)
//获取外网ip
apiv1.POST("/external",v1.GetExternal)
apiv1.POST("/external", v1.GetExternal)
//服务器状态
apiv1.POST("/serverstatus",v1.GetServerStatus)
apiv1.POST("/serverstatus", v1.GetServerStatus)
//反馈信息
apiv1.POST("/feedback",v1.FeedBackWithoutSSH)
apiv1.POST("/feedback", v1.FeedBackWithoutSSH)
//反馈处理进度
apiv1.POST("/iscomplete",v1.FeedBackStatusWithoutSSH)
apiv1.POST("/iscomplete", v1.FeedBackStatusWithoutSSH)
//反馈信息
apiv1.POST("/feedback1",v1.FeedBack)
apiv1.POST("/feedback1", v1.FeedBack)
//反馈处理进度
apiv1.POST("/iscomplete1",v1.FeedBackStatus)
apiv1.POST("/escrowpassword",v1.EscrowPasswd)
apiv1.POST("/iscomplete1", v1.FeedBackStatus)
apiv1.POST("/escrowpassword", v1.EscrowPasswd)
//pai更新完成用户手动重启设备
//apiv1.POST("/isreboot",v1.IsReBoot)
//重启节点
apiv1.POST("/restartnode",v1.RestartNode)
apiv1.POST("/restartnode", v1.RestartNode)
//安全关闭节点,不会再重启 除非是重启树莓派
apiv1.POST("/closenode",v1.CloseNode)
apiv1.POST("/closenode", v1.CloseNode)
//sudo poweroff
apiv1.POST("/poweroff",v1.PoweroffPai)
apiv1.POST("/poweroff", v1.PoweroffPai)
//test
apiv1.POST("/test",v1.Test)
apiv1.POST("/test", v1.Test)
//回滚1000区块
apiv1.POST("/rollback",v1.Rollback)
apiv1.POST("/rollback", v1.Rollback)
//一键备份 40g
apiv1.POST("/nodebackup",v1.NodeBackup)
apiv1.POST("/nodebackup", v1.NodeBackup)
//一键恢复 针对不同步 并且 回滚多次还不同步的情况下拿最近的备份恢复
apiv1.POST("/noderecover",v1.NodeRecover)
apiv1.POST("/noderecover", v1.NodeRecover)
//删除备份
apiv1.POST("/delbackup",v1.DelBackup)
apiv1.POST("/delbackup", v1.DelBackup)
//是否备份
apiv1.POST("/isbackup",v1.CheckBackup)
apiv1.POST("/isbackup", v1.CheckBackup)
return r
}
......
package pai_service
import (
"os/exec"
"io"
"strings"
"bufio"
"bytes"
"chain33-pai/pkg/chain33"
"github.com/33cn/chain33/types"
"chain33-pai/pkg/pai"
"chain33-pai/pkg/setting"
"encoding/json"
"errors"
log "github.com/33cn/chain33/common/log/log15"
"net/http"
"bytes"
"github.com/33cn/chain33/types"
"io"
"io/ioutil"
"encoding/json"
"chain33-pai/pkg/setting"
"chain33-pai/pkg/pai"
"net/http"
"os"
"errors"
"os/exec"
"strconv"
"strings"
)
var (
pai_serial string
tlog = log.New("service", "pai_Service")
tlog = log.New("service", "pai_Service")
)
//在网络通畅的情况下 ENum 每30s +1 20=>restart 40 => rollback 60 =>recover
type Pai struct {
Hardware string `json:"hardware"`
Revision string `json:"revision"`
Revision string `json:"revision"`
Serial string `json:"serial"`
//PeerList *types.PeerList
LocalLastHeight int64 `json:"local_last_height"`
LastHeight int64 `json:"last_height"`
IsNtpSync bool `json:"is_ntp_sync"`
WalletStatus *types.WalletStatus `json:"wallet_status"`
NetInfo *types.NodeNetInfo `json:"net_info"`
BtyVersion *types.VersionInfo `json:"bty_version"`
Err string `json:"err"`
Arch string `json:"arch"`
Disks []*pai.Disk
IsBackup bool `json:"is_backup"`
ENum int64 `json:"e_num"`
LocalLastHeight int64 `json:"local_last_height"`
LastHeight int64 `json:"last_height"`
IsNtpSync bool `json:"is_ntp_sync"`
WalletStatus *types.WalletStatus `json:"wallet_status"`
NetInfo *types.NodeNetInfo `json:"net_info"`
BtyVersion *types.VersionInfo `json:"bty_version"`
Err string `json:"err"`
Arch string `json:"arch"`
Disks []*pai.Disk
IsBackup bool `json:"is_backup"`
ENum int64 `json:"e_num"`
LocalLastHeight2 int64 `json:"local_last_height_2"`
ProLevel int64 `json:"pro_level"`
Temp int64 `json:"temp"`
ProLevel int64 `json:"pro_level"`
Temp int64 `json:"temp"`
}
type ReqUpdatePai struct {
......@@ -69,13 +69,13 @@ func (p *Pai) SetPaiEnv() error {
cmd.Stdout = &buf
cmd.Run()
arch := buf.String()
p.Arch = strings.Replace(arch,"\n","",-1)
p.Arch = strings.Replace(arch, "\n", "", -1)
return nil
}
func (p *Pai) GetBtyVersion() error {
client := &chain33.PaiClient{}
v,err := client.Version()
v, err := client.Version()
if err != nil {
p.Err = err.Error()
return err
......@@ -91,12 +91,12 @@ func (p *Pai) GetConfig() bool {
if p.Serial != "" {
return true
}
config ,err := getPaiConfig("cat","/proc/cpuinfo")
config, err := getPaiConfig("cat", "/proc/cpuinfo")
if err != nil {
p.Err = err.Error()
return false
}
if _,ok := config["serial"];ok {
if _, ok := config["serial"]; ok {
p.Serial = config["serial"]
p.Hardware = config["hardware"]
p.Revision = config["revision"]
......@@ -107,14 +107,14 @@ func (p *Pai) GetConfig() bool {
func (p *Pai) GetDevstatus() error {
client := &chain33.PaiClient{}
peerinfo,err := client.GetPeerInfo()
peerinfo, err := client.GetPeerInfo()
if err != nil {
tlog.Error("GetDevstatus peerinfo ","err",err)
tlog.Error("GetDevstatus peerinfo ", "err", err)
p.Err = err.Error()
return err
}
for _,v := range peerinfo.Peers {
for _, v := range peerinfo.Peers {
if p.LastHeight < v.Header.Height {
p.LastHeight = v.Header.Height
}
......@@ -122,31 +122,31 @@ func (p *Pai) GetDevstatus() error {
p.LocalLastHeight = v.Header.Height
}
}
sync ,err := client.IsNtpClockSync()
sync, err := client.IsNtpClockSync()
if err != nil {
p.Err = err.Error()
tlog.Error("GetDevstatus IsNtpClockSync"," err",err)
tlog.Error("GetDevstatus IsNtpClockSync", " err", err)
return err
}
p.IsNtpSync = sync.IsOk
netinfo,err := client.GetNetInfo()
netinfo, err := client.GetNetInfo()
if err != nil {
p.Err = err.Error()
tlog.Error("GetDevstatus GetNetInfo"," err",err)
tlog.Error("GetDevstatus GetNetInfo", " err", err)
return err
}
p.NetInfo = netinfo
walletstatus,err := client.GetWalletStatus()
walletstatus, err := client.GetWalletStatus()
if err != nil {
p.Err = err.Error()
tlog.Error("GetDevstatus GetWalletStatus ","err",err)
tlog.Error("GetDevstatus GetWalletStatus ", "err", err)
return err
}
p.WalletStatus = walletstatus
return nil
}
func getPaiConfig(command string ,arg ...string) (config map[string]string,err error) {
func getPaiConfig(command string, arg ...string) (config map[string]string, err error) {
//获取操作系统版本信息
list := make(map[string]string, 0)
......@@ -154,20 +154,20 @@ func getPaiConfig(command string ,arg ...string) (config map[string]string,err e
stdout, err := cmd.StdoutPipe()
//tlog.Info(stdout)
if err != nil {
tlog.Info("getPaiConfig",err)
return nil,err
tlog.Info("getPaiConfig", err)
return nil, err
}
defer stdout.Close()
if err := cmd.Start(); err != nil {
tlog.Info("getPaiConfig",err)
return nil,err
tlog.Info("getPaiConfig", err)
return nil, err
}
rd := bufio.NewReader(stdout)
for {
line, err := rd.ReadString('\n')
if err!=nil || io.EOF==err{
if err != nil || io.EOF == err {
break
}else{
} else {
//tlog.Info("line", line)
l := strings.Split(line, ":")
......@@ -188,33 +188,33 @@ func getPaiConfig(command string ,arg ...string) (config map[string]string,err e
return list, nil
}
func (p *Pai) GetPaiLatestVersion(t int32) (string,error) {
func (p *Pai) GetPaiLatestVersion(t int32) (string, error) {
data := make(map[string]interface{})
data["type"] = t
bytesData, _ := json.Marshal(data)
resp, err := http.Post(setting.Chain33Pai.VersionUrl,"application/json", bytes.NewReader(bytesData))
resp, err := http.Post(setting.Chain33Pai.VersionUrl, "application/json", bytes.NewReader(bytesData))
if err != nil {
return "",err
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "",err
return "", err
}
type res struct {
Code int64
Msg string
Msg string
Data string
}
var r res
err = json.Unmarshal(body,&r)
err = json.Unmarshal(body, &r)
if err != nil {
return "",err
return "", err
}
return r.Data,nil
return r.Data, nil
}
func (p *Pai) GetDiskUseage() error {
disks,err := pai.MonitorServer()
disks, err := pai.MonitorServer()
if err != nil {
return err
}
......@@ -227,14 +227,14 @@ func (p *Pai) GetDiskUseage() error {
func (p *Pai) CheckBackup() error {
path := pai.FindAbsPath("wallet-bty")
if path == "" {
tlog.Error("IsBackup","path","node not exists")
tlog.Error("IsBackup", "path", "node not exists")
//p.IsBackup = false
return errors.New("node not exists")
}
backupPath := path + "/datadir_backup"
if _,err := os.Stat(backupPath);err != nil {
if _, err := os.Stat(backupPath); err != nil {
if os.IsNotExist(err) {
tlog.Error("backup file not exists","err",backupPath)
tlog.Error("backup file not exists", "err", backupPath)
p.IsBackup = false
return errors.New("backup file not exists")
}
......@@ -245,16 +245,16 @@ func (p *Pai) CheckBackup() error {
func (p *Pai) GetTemp() error {
var b bytes.Buffer
cmd := exec.Command("cat","/sys/class/thermal/thermal_zone0/temp")
cmd := exec.Command("cat", "/sys/class/thermal/thermal_zone0/temp")
cmd.Stdout = &b
err := cmd.Run()
if err != nil {
return err
}
list := strings.Split(b.String(),"\n")
list := strings.Split(b.String(), "\n")
if list[0] != "" {
temp,_ := strconv.Atoi(list[0])
temp, _ := strconv.Atoi(list[0])
p.Temp = int64(temp)
}
return nil
}
\ No newline at end of file
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment