Commit cfa24f9d authored by wei.xuan's avatar wei.xuan

Merge branch '1106' into 'master'

fix:fix redial

See merge request !7
parents ecf22296 33aa7847
...@@ -6,4 +6,7 @@ majora-cli ...@@ -6,4 +6,7 @@ majora-cli
bin bin
nohup.out nohup.out
release release
./majora ./majora
\ No newline at end of file *.log
majora.log
std.log
\ No newline at end of file
...@@ -3,7 +3,7 @@ export PATH := $(GOPATH)/bin:$(PATH) ...@@ -3,7 +3,7 @@ export PATH := $(GOPATH)/bin:$(PATH)
export GO111MODULE=on export GO111MODULE=on
LDFLAGS := -s -w LDFLAGS := -s -w
DATE=$(shell date +"%Y-%m-%d") DATE=$(shell date +"%Y-%m-%d")
version=v0.0.3 version=latest
BUILDINFO := -X main.Version=$(version) -X main.Date=$(DATE) BUILDINFO := -X main.Version=$(version) -X main.Date=$(DATE)
os-archs=darwin:amd64 darwin:arm64 freebsd:386 freebsd:amd64 linux:386 linux:amd64 linux:arm linux:arm64 windows:386 windows:amd64 linux:mips64 linux:mips64le os-archs=darwin:amd64 darwin:arm64 freebsd:386 freebsd:amd64 linux:386 linux:amd64 linux:arm linux:arm64 windows:386 windows:amd64 linux:mips64 linux:mips64le
......
...@@ -55,12 +55,12 @@ func init() { ...@@ -55,12 +55,12 @@ func init() {
func initial(cfg *model.Configure) { func initial(cfg *model.Configure) {
if cfg.LogLevel > 0 { if cfg.LogLevel > 0 {
_ = getty.SetLoggerCallerDisable()
_ = getty.SetLoggerLevel(getty.LoggerLevel(cfg.LogLevel - 1)) _ = getty.SetLoggerLevel(getty.LoggerLevel(cfg.LogLevel - 1))
_ = getty.Online(cfg.LogPath)
} }
addr := fmt.Sprintf("127.0.0.1:%d", cfg.PprofPort)
if cfg.PprofPort > 0 { if cfg.PprofPort > 0 {
go func() { go func() {
addr := fmt.Sprintf("127.0.0.1:%d", cfg.PprofPort)
getty.GetLogger().Infof("enable pprof: %s", addr) getty.GetLogger().Infof("enable pprof: %s", addr)
log.Fatal(http.ListenAndServe(addr, nil)) log.Fatal(http.ListenAndServe(addr, nil))
}() }()
...@@ -75,12 +75,6 @@ func initial(cfg *model.Configure) { ...@@ -75,12 +75,6 @@ func initial(cfg *model.Configure) {
} }
getty.GetLogger().Infof("use custom dns server %s", dnsServer) getty.GetLogger().Infof("use custom dns server %s", dnsServer)
} }
//if !cfg.DisableUpdate {
// if _, err := infra.Update("majora", Version); err != nil {
// getty.GetLogger().Errorf("check update error %+s", err.Error())
// }
//}
} }
func parseFromCmd(cfg *model.Configure) { func parseFromCmd(cfg *model.Configure) {
...@@ -102,11 +96,13 @@ func cli() { ...@@ -102,11 +96,13 @@ func cli() {
parseFromCmd(cfg) parseFromCmd(cfg)
} }
initial(cfg) initial(cfg)
runtime.GOMAXPROCS(runtime.NumCPU() * 2)
getty.GetLogger().Infof("current Version %s, build at %s", Version, Date) debug.SetGCPercent(200)
getty.GetLogger().Infof("hostinfo os:%s, arch:%s", runtime.GOOS, runtime.GOARCH) getty.GetLogger().Warnf("cpu count %d proc %d", runtime.NumCPU(), runtime.NumCPU()*2)
getty.GetLogger().Warnf("current Version %s, build at %s", Version, Date)
getty.GetLogger().Warnf("hostinfo os:%s, arch:%s", runtime.GOOS, runtime.GOARCH)
cfgInfo, _ := json.Marshal(cfg) cfgInfo, _ := json.Marshal(cfg)
getty.GetLogger().Infof("config info:%s", string(cfgInfo)) getty.GetLogger().Warnf("config info:%s", string(cfgInfo))
client.NewClientWithConf(cfg) client.NewClientWithConf(cfg)
} }
...@@ -116,10 +112,6 @@ func main() { ...@@ -116,10 +112,6 @@ func main() {
fmt.Println(Version) fmt.Println(Version)
os.Exit(0) os.Exit(0)
} }
runtime.GOMAXPROCS(runtime.NumCPU() * 2)
debug.SetGCPercent(200)
getty.GetLogger().Warnf("cpu count %d,proc %d", runtime.NumCPU(), runtime.NumCPU()*2)
sigs := make(chan os.Signal, 1) sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
...@@ -129,6 +121,6 @@ func main() { ...@@ -129,6 +121,6 @@ func main() {
select { select {
case <-sigs: case <-sigs:
time.Sleep(time.Second * 3) time.Sleep(time.Second * 3)
getty.GetLogger().Info("main process exit...") getty.GetLogger().Warn("main process exit...")
} }
} }
...@@ -14,7 +14,6 @@ type MajoraEventListener struct { ...@@ -14,7 +14,6 @@ type MajoraEventListener struct {
} }
func (m *MajoraEventListener) OnOpen(session getty.Session) error { func (m *MajoraEventListener) OnOpen(session getty.Session) error {
getty.GetLogger().Infof("connect to nathost %s success ...", m.client.config.TunnelAddr)
packet := protocol.TypeRegister.CreatePacket() packet := protocol.TypeRegister.CreatePacket()
packet.Extra = m.client.config.ClientID packet.Extra = m.client.config.ClientID
extraMap := make(map[string]string, 1) extraMap := make(map[string]string, 1)
...@@ -24,20 +23,17 @@ func (m *MajoraEventListener) OnOpen(session getty.Session) error { ...@@ -24,20 +23,17 @@ func (m *MajoraEventListener) OnOpen(session getty.Session) error {
getty.GetLogger().Errorf("register to server error %+v", err) getty.GetLogger().Errorf("register to server error %+v", err)
return err return err
} }
getty.GetLogger().Infof("[OnOpen] registe to %s success", m.client.config.TunnelAddr) getty.GetLogger().Warnf("[OnOpen] registe to %s success", m.client.config.TunnelAddr)
return nil return nil
} }
func (m *MajoraEventListener) OnClose(session getty.Session) { func (m *MajoraEventListener) OnClose(session getty.Session) {
getty.GetLogger().Infof("OnClose->%v,clean local session...", session.IsClosed()) getty.GetLogger().Errorf("OnClose->%v,clean local session...", session.IsClosed())
m.client.CloseAll(session) m.client.CloseAll(session)
} }
func (m *MajoraEventListener) OnError(session getty.Session, err error) { func (m *MajoraEventListener) OnError(session getty.Session, err error) {
getty.GetLogger().Errorf("OnError %s", err.Error()) getty.GetLogger().Errorf("OnError %s", err.Error())
//if errors.Is(err, common.ErrInvalidMagic) {
// session.Close()
//}
m.client.CloseAll(session) m.client.CloseAll(session)
} }
......
...@@ -91,5 +91,5 @@ func (client *Client) Redial(session getty.Session) { ...@@ -91,5 +91,5 @@ func (client *Client) Redial(session getty.Session) {
client.CloseAll(session) client.CloseAll(session)
getty.GetLogger().Warnf("=================redial->wait %v ==============", client.config.Redial.WaitTime) getty.GetLogger().Warnf("=================redial->wait %v ==============", client.config.Redial.WaitTime)
time.Sleep(client.config.Redial.WaitTime) time.Sleep(client.config.Redial.WaitTime)
infra.Redial(client.config) infra.Redial(client.config, session)
} }
#!/bin/bash
CURDIR=$(cd $(dirname "$0");pwd)
CONF=$CURDIR/majora.ini
chmod +x majora
echo "$CURDIR"/majora -conf "$CONF"
exec "$CURDIR"/majora -conf "$CONF"
\ No newline at end of file
...@@ -10,6 +10,7 @@ disable_update = false ...@@ -10,6 +10,7 @@ disable_update = false
log_level = 1 log_level = 1
reconn_interval = 5s reconn_interval = 5s
;client_id = ;client_id =
log_path = "./majora.log"
[extra] [extra]
account = superman account = superman
......
...@@ -9,6 +9,7 @@ disable_update = false ...@@ -9,6 +9,7 @@ disable_update = false
log_level = 2 log_level = 2
reconn_interval = 5s reconn_interval = 5s
;client_id = ;client_id =
log_path = /root/majora.log
[extra] [extra]
account = superman account = superman
......
[Unit]
Description=majora client
After=network.target
[Service]
Type=simple
User=root
Restart=always
RestartSec=5s
ExecStart=/root/majora -conf /root/majora.ini
ExecReload=/root/majora -conf /root/majora.ini
LimitNOFILE=1048576
[Install]
WantedBy=multi-user.target
\ No newline at end of file
#!/usr/bin/env bash #!/usr/bin/env bash
. /etc/profile rm -fr /usr/lib/systemd/system/majora.service
. /root/.bash_profile
# create link
ln -s /root/majora.service /usr/lib/systemd/system/majora.service
echo 'shutdown majora-cli server' systemctl daemon-reload
now_dir=`pwd`
cd `dirname $0` echo "restart..."
script_dir=`pwd`
function getPid(){ systemctl restart majora.service
echo `ps -ef | grep "majora" | grep ".ini" | grep -v "grep" | grep -v "startup.sh" | awk '{print $2}'`
}
remote_pid=`getPid`
echo remote_pid:${remote_pid} systemctl status majora.service
if [[ -n "${remote_pid}" ]] ;then
echo kill pid ${remote_pid}
kill -9 ${remote_pid}
fi
echo "start majora-cli server"
sleep 2
remote_pid=`getPid`
if [[ -n "${remote_pid}" ]] ;then
# 被supervisor自动守护
exit 0
fi
std_log=../log
if [[ ! -d ${std_log} ]] ;then
mkdir ${std_log}
fi
nohup bash exec.sh >> std.log 2>&1 &
sleep 2
remote_pid=`getPid`
echo "remote pid:${remote_pid}"
\ No newline at end of file
#!/usr/bin/env bash
wget https://oss.virjar.com/majora/bin/latest/majora-cli_latest_linux_amd64.tar.gz -O majora-cli.tar.gz
tar -zxvf majora-cli.tar.gz
rm -fr majora
rm -fr exec.sh
rm -fr start.sh
rm -fr majora.ini
rm -fr majora.service
rm -fr majora-dev.ini
mv -f majora-cli*/* .
rm -fr /usr/lib/systemd/system/majora.service
# create link
ln -s /root/majora.service /usr/lib/systemd/system/majora.service
systemctl daemon-reload
echo "restart..."
systemctl restart majora.service
systemctl status majora.service
...@@ -3,15 +3,13 @@ module virjar.com/majora-go ...@@ -3,15 +3,13 @@ module virjar.com/majora-go
go 1.17 go 1.17
require ( require (
github.com/adamweixuan/getty v1.8.2 github.com/adamweixuan/getty v1.8.4
github.com/adamweixuan/gostnops v1.11.20-0.20211029124314-3f0589fceea6 github.com/adamweixuan/gostnops v1.11.20-0.20211029124314-3f0589fceea6
github.com/blang/semver/v4 v4.0.0
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
gopkg.in/ini.v1 v1.63.2 gopkg.in/ini.v1 v1.63.2
) )
require ( require (
github.com/golang/snappy v0.0.4 // indirect
github.com/gorilla/websocket v1.4.2 // indirect github.com/gorilla/websocket v1.4.2 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
go.uber.org/atomic v1.9.0 // indirect go.uber.org/atomic v1.9.0 // indirect
......
github.com/adamweixuan/getty v1.8.2 h1:y/0KmxLPo0QiErZRr4xBlcsVHmXkuTXTs/EIPZyar1s= github.com/adamweixuan/getty v1.8.4 h1:YhHVYwrSqky3cMrPV5/dfHUwrhc9XB7emobVXTe1wY4=
github.com/adamweixuan/getty v1.8.2/go.mod h1:JFfNdX0dvMtvPiF7LEfU4X8OLJYao5BGTHS9cf4kng8= github.com/adamweixuan/getty v1.8.4/go.mod h1:+P0Afn1ky1/4q96pjJmR6GssmVYXN+2dZ/0BxkIDpGo=
github.com/adamweixuan/gostnops v1.11.20-0.20211029124314-3f0589fceea6 h1:UGMsACjkGfNRKCz5U8ijtkpKL8o/25rGHxTV1adWjak= github.com/adamweixuan/gostnops v1.11.20-0.20211029124314-3f0589fceea6 h1:UGMsACjkGfNRKCz5U8ijtkpKL8o/25rGHxTV1adWjak=
github.com/adamweixuan/gostnops v1.11.20-0.20211029124314-3f0589fceea6/go.mod h1:zZYjPhU2+ujyEOWWE0l1pEdf5H4CyfiMG//rSpNjwcQ= github.com/adamweixuan/gostnops v1.11.20-0.20211029124314-3f0589fceea6/go.mod h1:zZYjPhU2+ujyEOWWE0l1pEdf5H4CyfiMG//rSpNjwcQ=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM=
github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
......
package infra
import (
"crypto/tls"
"net/http"
"time"
"github.com/adamweixuan/getty"
)
// 网络检测
var (
httpcli *http.Client
)
const (
defTimeout = time.Second * 10
baiduUrl = "https://www.baidu.com"
)
func init() {
httpcli = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
Timeout: defTimeout,
}
}
func Ping(url string) bool {
resp, err := httpcli.Head(url)
if err != nil {
getty.GetLogger().Warnf("ping %s with error %+v", url, err)
return false
}
defer resp.Body.Close()
getty.GetLogger().Warnf("ping %s status code %d", url, resp.StatusCode)
return resp.StatusCode == http.StatusOK
}
func PingBaidu() bool {
return Ping(baiduUrl)
}
package infra
import (
"testing"
)
func TestPing(t *testing.T) {
type args struct {
url string
}
tests := []struct {
name string
args args
want bool
}{
{
name: "baidu",
args: args{url: "https://www.baidu.com"},
want: true,
},
{
name: "google",
args: args{url: "https://www.taobao.com"},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Ping(tt.args.url); got != tt.want {
t.Errorf("Ping() = %v, want %v", got, tt.want)
}
})
}
}
...@@ -19,6 +19,7 @@ func Restart() { ...@@ -19,6 +19,7 @@ func Restart() {
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
getty.GetLogger().Errorf("Restart error %+v", err) getty.GetLogger().Errorf("Restart error %+v", err)
} }
} }
func RestartBySignal(signal chan struct{}) { func RestartBySignal(signal chan struct{}) {
......
...@@ -3,6 +3,7 @@ package infra ...@@ -3,6 +3,7 @@ package infra
import ( import (
"os/exec" "os/exec"
"runtime" "runtime"
"time"
"github.com/adamweixuan/getty" "github.com/adamweixuan/getty"
"virjar.com/majora-go/model" "virjar.com/majora-go/model"
...@@ -13,16 +14,34 @@ const ( ...@@ -13,16 +14,34 @@ const (
cmdUnix = "-c" cmdUnix = "-c"
) )
func Redial(cfg *model.Configure) { func Redial(cfg *model.Configure, session getty.Session) {
getty.GetLogger().Warnf("[redial] start, session status:%s", session.Stat())
status := command(cfg)
getty.GetLogger().Warnf("[redial] end:%v, session status: %s", status, session.Stat())
pingBaidu := PingBaidu()
getty.GetLogger().Warnf("[redial] net check: %v", pingBaidu)
if !pingBaidu {
getty.GetLogger().Warnf("[redial] net check fail,redial...")
Redial(cfg, session)
}
}
func command(cfg *model.Configure) bool {
defer func(start time.Time) {
getty.GetLogger().Warnf("[redial] cost %v", time.Since(start))
}(time.Now())
execPath := cfg.Redial.ExecPath execPath := cfg.Redial.ExecPath
if len(execPath) == 0 { if len(execPath) == 0 {
getty.GetLogger().Warn("redial exec file is empty") getty.GetLogger().Warn("[redial] exec file is empty")
return return true
} }
command := cfg.Redial.Command command := cfg.Redial.Command
if len(command) == 0 { if len(command) == 0 {
getty.GetLogger().Warn("redial command is empty") getty.GetLogger().Warn("[redial] command is empty")
return return true
} }
args := cmdUnix args := cmdUnix
...@@ -34,7 +53,8 @@ func Redial(cfg *model.Configure) { ...@@ -34,7 +53,8 @@ func Redial(cfg *model.Configure) {
output, err := cmd.Output() output, err := cmd.Output()
if err != nil { if err != nil {
getty.GetLogger().Errorf("[redial] Execute Shell:%s failed with error:%s", command, err.Error()) getty.GetLogger().Errorf("[redial] Execute Shell:%s failed with error:%s", command, err.Error())
return return false
} }
getty.GetLogger().Warnf("[redial] redial success %+v resp:%s", cmd, string(output)) getty.GetLogger().Warnf("[redial] success %+v resp:%s", cmd, string(output))
return true
} }
package infra
import (
"testing"
"virjar.com/majora-go/model"
)
func TestRedial(t *testing.T) {
conf := model.InitConf("/Users/weixuan/code/gcode/majora-go/conf/majora.ini")
redial(conf)
}
package infra package infra
import ( //// getBinary 下载二进制
"errors" //func getBinary(name, os, arch, version string) (io.ReadCloser, error) {
"fmt" // fileName := fmt.Sprintf(common.VersionTpl, name, version, os, arch)
"io" // if os == "windows" {
"io/ioutil" // fileName += ".exe"
"net/http" // }
"os" // url := common.UpdateServer + common.UpdateBinaryPath + fileName
"runtime" // getty.GetLogger().Debugf("getBinary url %s, filename %s", url, fileName)
"strings" //
// body, err := http.DefaultClient.Get(url)
"github.com/adamweixuan/getty" // if err != nil {
"github.com/blang/semver/v4" // return nil, err
"virjar.com/majora-go/common" // }
) // return body.Body, nil
//}
// getBinary 下载二进制 //
func getBinary(name, os, arch, version string) (io.ReadCloser, error) { //func downloadFile(name, os, arch, version string, f *os.File) error {
fileName := fmt.Sprintf(common.VersionTpl, name, version, os, arch) // binary, err := getBinary(name, os, arch, version)
if os == "windows" { // if err != nil {
fileName += ".exe" // return err
} // }
url := common.UpdateServer + common.UpdateBinaryPath + fileName //
getty.GetLogger().Debugf("getBinary url %s, filename %s", url, fileName) // defer func(binary io.ReadCloser) {
// _ = binary.Close()
body, err := http.DefaultClient.Get(url) // }(binary)
if err != nil { //
return nil, err // body, err := ioutil.ReadAll(binary)
} //
return body.Body, nil // if err != nil {
} // return err
// }
func downloadFile(name, os, arch, version string, f *os.File) error { //
binary, err := getBinary(name, os, arch, version) // cnt, err := f.Write(body)
if err != nil { // if err != nil {
return err // return err
} // }
//
defer func(binary io.ReadCloser) { // if cnt != len(body) {
_ = binary.Close() // return errors.New("write to file is not enough")
}(binary) // }
// return nil
body, err := ioutil.ReadAll(binary) //}
//
if err != nil { //func rename(src, dst string) error {
return err // if err := os.Chmod(src, common.DefaultMode); err != nil {
} // return err
// }
cnt, err := f.Write(body) //
if err != nil { // if err := os.Rename(src, dst); err != nil {
return err // return err
} // }
// getty.GetLogger().Debugf("rename %s to %s", src, dst)
if cnt != len(body) { // return nil
return errors.New("write to file is not enough") //}
} //
return nil //func UpdateCore(name, latestVer, targetFile string) (bool, error) {
} // tf, err := ioutil.TempFile("", "")
// if err != nil {
func rename(src, dst string) error { // getty.GetLogger().Debugf("UpdateCore TempFile with error %s", err.Error())
if err := os.Chmod(src, common.DefaultMode); err != nil { // return false, err
return err // }
} //
// if err := downloadFile(name, runtime.GOOS, runtime.GOARCH, latestVer, tf); err != nil {
if err := os.Rename(src, dst); err != nil { // getty.GetLogger().Debugf("UpdateCore downloadFile with error %s", err.Error())
return err // return false, err
} // }
getty.GetLogger().Debugf("rename %s to %s", src, dst) //
return nil // if err := tf.Close(); err != nil {
} // getty.GetLogger().Debugf("UpdateCore tf close with error %s", err.Error())
// return false, err
func UpdateCore(name, latestVer, targetFile string) (bool, error) { // }
tf, err := ioutil.TempFile("", "") //
if err != nil { // if err := rename(tf.Name(), targetFile); err != nil {
getty.GetLogger().Debugf("UpdateCore TempFile with error %s", err.Error()) // return false, err
return false, err // }
} // Restart()
// return true, nil
if err := downloadFile(name, runtime.GOOS, runtime.GOARCH, latestVer, tf); err != nil { //}
getty.GetLogger().Debugf("UpdateCore downloadFile with error %s", err.Error()) //
return false, err //func getLatestVersion() (string, error) {
} // url := common.UpdateServer + common.UpdateBinaryPath + common.Latest
// getty.GetLogger().Debugf("getLatestVersion from %s", url)
if err := tf.Close(); err != nil { // resp, err := http.DefaultClient.Get(url) //nolint:bodyclose
getty.GetLogger().Debugf("UpdateCore tf close with error %s", err.Error()) // if err != nil || resp == nil {
return false, err // return "", err
} // }
//
if err := rename(tf.Name(), targetFile); err != nil { // defer func(Body io.ReadCloser) {
return false, err // _ = Body.Close()
} // }(resp.Body)
Restart() //
return true, nil // if resp.StatusCode != http.StatusOK {
} // getty.GetLogger().Errorf("get latest version with error %s->%d", url, resp.StatusCode)
// return "", nil
func getLatestVersion() (string, error) { // }
url := common.UpdateServer + common.UpdateBinaryPath + common.Latest //
getty.GetLogger().Debugf("getLatestVersion from %s", url) // bytes, err := ioutil.ReadAll(resp.Body)
resp, err := http.DefaultClient.Get(url) //nolint:bodyclose // if err != nil {
if err != nil || resp == nil { // return "", err
return "", err // }
} //
// return strings.ReplaceAll(string(bytes), "\n", ""), nil
defer func(Body io.ReadCloser) { //}
_ = Body.Close() //
}(resp.Body) //func needUpdate(curVer string) (bool, string) {
// if len(curVer) == 0 {
if resp.StatusCode != http.StatusOK { // return false, ""
getty.GetLogger().Errorf("get latest version with error %s->%d", url, resp.StatusCode) // }
return "", nil // latestVer, err := getLatestVersion()
} // if err != nil {
// getty.GetLogger().Errorf("getLatestVersion with error %s", err.Error())
bytes, err := ioutil.ReadAll(resp.Body) // return false, ""
if err != nil { // }
return "", err //
} // if len(latestVer) == 0 {
// getty.GetLogger().Errorf("getLatestVersion with empty")
return strings.ReplaceAll(string(bytes), "\n", ""), nil // return false, ""
} // }
//
func needUpdate(curVer string) (bool, string) { // if curVer[0] == 'v' || curVer[0] == 'V' {
if len(curVer) == 0 { // curVer = curVer[1:]
return false, "" // }
} //
latestVer, err := getLatestVersion() // latest := latestVer
if err != nil { // if latestVer[0] == 'v' || latestVer[0] == 'V' {
getty.GetLogger().Errorf("getLatestVersion with error %s", err.Error()) // latest = latest[1:]
return false, "" // }
} // cur, _ := semver.Make(curVer)
// next, _ := semver.Make(latest)
if len(latestVer) == 0 { // getty.GetLogger().Debugf("curVer %s->cur %s, latestVer %s->next %s", curVer, cur, latest, next)
getty.GetLogger().Errorf("getLatestVersion with empty") //
return false, "" // return cur.Compare(next) < 0, latestVer
} //}
//
if curVer[0] == 'v' || curVer[0] == 'V' { //// Update update to the latest version
curVer = curVer[1:] //func Update(name, curVer string) (bool, error) {
} // defer func() {
// if err := recover(); err != nil {
latest := latestVer // getty.GetLogger().Errorf("Update with error %+v", err)
if latestVer[0] == 'v' || latestVer[0] == 'V' { // }
latest = latest[1:] // }()
} //
cur, _ := semver.Make(curVer) // // get current exec path
next, _ := semver.Make(latest) // executable, err := os.Executable()
getty.GetLogger().Debugf("curVer %s->cur %s, latestVer %s->next %s", curVer, cur, latest, next) // if err != nil {
// return false, err
return cur.Compare(next) < 0, latestVer // }
} //
// getty.GetLogger().Debugf("current exec info %s", executable)
// Update update to the latest version //
func Update(name, curVer string) (bool, error) { // // check has new version
defer func() { // needUpdate, latestVer := needUpdate(curVer)
if err := recover(); err != nil { // getty.GetLogger().Debugf("curVer %s, latestVer %s, need update %v", curVer, latestVer, needUpdate)
getty.GetLogger().Errorf("Update with error %+v", err) // if !needUpdate {
} // getty.GetLogger().Debugf("no need update ...")
}() // return false, nil
// }
// get current exec path // updateStatus, err := UpdateCore(name, latestVer, executable)
executable, err := os.Executable() // if err != nil {
if err != nil { // getty.GetLogger().Errorf("update to latest version with error %s", err)
return false, err // return false, err
} // }
// getty.GetLogger().Infof("update from %s to %s with success %v", curVer, latestVer, updateStatus)
getty.GetLogger().Debugf("current exec info %s", executable) // return updateStatus, nil
//}
// check has new version
needUpdate, latestVer := needUpdate(curVer)
getty.GetLogger().Debugf("curVer %s, latestVer %s, need update %v", curVer, latestVer, needUpdate)
if !needUpdate {
getty.GetLogger().Debugf("no need update ...")
return false, nil
}
updateStatus, err := UpdateCore(name, latestVer, executable)
if err != nil {
getty.GetLogger().Errorf("update to latest version with error %s", err)
return false, err
}
getty.GetLogger().Infof("update from %s to %s with success %v", curVer, latestVer, updateStatus)
return updateStatus, nil
}
...@@ -29,6 +29,7 @@ type Configure struct { ...@@ -29,6 +29,7 @@ type Configure struct {
LocalAddr string `ini:"local_ip" json:"local_ip"` LocalAddr string `ini:"local_ip" json:"local_ip"`
ReconnInterval time.Duration `ini:"reconn_interval" json:"reconn_interval"` ReconnInterval time.Duration `ini:"reconn_interval" json:"reconn_interval"`
ClientID string `ini:"client_id" json:"client_id"` ClientID string `ini:"client_id" json:"client_id"`
LogPath string `ini:"log_path" json:"log_path"`
Extra Extra `ini:"extra" json:"extra"` Extra Extra `ini:"extra" json:"extra"`
Redial Redial `ini:"redial" json:"redial"` Redial Redial `ini:"redial" json:"redial"`
......
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