守护进程 负载均衡

This commit is contained in:
刘河
2019-02-03 00:54:43 +08:00
parent 662a799f02
commit da899fd3db
20 changed files with 341 additions and 129 deletions

View File

@@ -7,7 +7,6 @@ import (
"errors"
"github.com/golang/snappy"
"io"
"log"
"net"
"net/http"
"net/url"
@@ -99,7 +98,7 @@ func (s *SnappyConn) Write(b []byte) (n int, err error) {
n = len(b)
if s.crypt {
if b, err = AesEncrypt(b, []byte(cryptKey)); err != nil {
log.Println("encode crypt error:", err)
Println("encode crypt error:", err)
return
}
}
@@ -125,7 +124,7 @@ func (s *SnappyConn) Read(b []byte) (n int, err error) {
var bs []byte
if s.crypt {
if bs, err = AesDecrypt(buf[:n], []byte(cryptKey)); err != nil {
log.Println("decode crypt error:", err)
Println("decode crypt error:", err)
return
}
} else {
@@ -170,9 +169,13 @@ func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.
return
}
if hostPortURL.Opaque == "443" { //https访问
address = r.Host + ":443"
if strings.Index(r.Host, ":") == -1 { //host不带端口 默认80
address = r.Host + ":443"
} else {
address = r.Host
}
} else { //http访问
if strings.Index(hostPortURL.Host, ":") == -1 { //host不带端口 默认80
if strings.Index(r.Host, ":") == -1 { //host不带端口 默认80
address = r.Host + ":80"
} else {
address = r.Host

69
utils/daemon.go Normal file
View File

@@ -0,0 +1,69 @@
package utils
import (
"github.com/astaxie/beego"
"io/ioutil"
"log"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
)
func InitDaemon(f string) {
if len(os.Args) < 2 {
return
}
var args []string
args = append(args, os.Args[0])
if len(os.Args) >= 2 {
args = append(args, os.Args[2:]...)
}
args = append(args, "-log=file")
switch os.Args[1] {
case "start":
start(args, f)
os.Exit(0)
case "stop":
stop(f, args[0])
os.Exit(0)
case "restart":
stop(f, args[0])
start(args, f)
os.Exit(0)
}
}
func start(osArgs []string, f string) {
cmd := exec.Command(osArgs[0], osArgs[1:]...)
cmd.Start()
log.Println("执行启动成功")
if cmd.Process.Pid > 0 {
d1 := []byte(strconv.Itoa(cmd.Process.Pid))
ioutil.WriteFile(beego.AppPath+"/proxy_"+f+".pid", d1, 0600)
}
}
func stop(f string, p string) {
var c *exec.Cmd
var err error
switch runtime.GOOS {
case "windows":
p := strings.Split(p, `\`)
c = exec.Command("taskkill", "/F", "/IM", p[len(p)-1])
case "linux", "darwin":
b, err := ioutil.ReadFile(beego.AppPath + "/proxy_" + f + ".pid")
if err == nil {
c = exec.Command("/bin/bash", "-c", `kill -9 `+string(b))
} else {
log.Println("停止服务失败,pid文件不存在")
}
}
err = c.Run()
if err != nil {
log.Println("停止服务失败,", err)
} else {
log.Println("停止服务成功")
}
}

View File

@@ -4,7 +4,6 @@ import (
"encoding/csv"
"errors"
"github.com/astaxie/beego"
"log"
"os"
"strconv"
"strings"
@@ -40,7 +39,7 @@ func (s *Csv) StoreTasksToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/tasks.csv")
if err != nil {
log.Fatalf(err.Error())
Fatalf(err.Error())
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
@@ -63,7 +62,7 @@ func (s *Csv) StoreTasksToCsv() {
}
err := writer.Write(record)
if err != nil {
log.Fatalf(err.Error())
Fatalf(err.Error())
}
}
writer.Flush()
@@ -91,7 +90,7 @@ func (s *Csv) LoadTaskFromCsv() {
path := beego.AppPath + "/conf/tasks.csv"
records, err := s.openFile(path)
if err != nil {
log.Fatal("配置文件打开错误:", path)
Fatalln("配置文件打开错误:", path)
}
var tasks []*Tunnel
// 将每一行数据保存到内存slice中
@@ -218,7 +217,7 @@ func (s *Csv) LoadClientFromCsv() {
path := beego.AppPath + "/conf/clients.csv"
records, err := s.openFile(path)
if err != nil {
log.Fatal("配置文件打开错误:", path)
Fatalln("配置文件打开错误:", path)
}
var clients []*Client
// 将每一行数据保存到内存slice中
@@ -254,7 +253,7 @@ func (s *Csv) LoadHostFromCsv() {
path := beego.AppPath + "/conf/hosts.csv"
records, err := s.openFile(path)
if err != nil {
log.Fatal("配置文件打开错误:", path)
Fatalln("配置文件打开错误:", path)
}
var hosts []*Host
// 将每一行数据保存到内存slice中
@@ -392,7 +391,7 @@ func (s *Csv) StoreClientsToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/clients.csv")
if err != nil {
log.Fatalf(err.Error())
Fatalln(err.Error())
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
@@ -411,7 +410,7 @@ func (s *Csv) StoreClientsToCsv() {
}
err := writer.Write(record)
if err != nil {
log.Fatalf(err.Error())
Fatalln(err.Error())
}
}
writer.Flush()

View File

@@ -2,6 +2,7 @@ package utils
import (
"net"
"strings"
"sync"
)
@@ -101,6 +102,23 @@ type Host struct {
Flow *Flow
Client *Client
Remark string //备注
NowIndex int
TargetArr []string
sync.RWMutex
}
func (s *Host) GetRandomTarget() string {
if s.TargetArr == nil {
s.TargetArr = strings.Split(s.Target, "\n")
}
s.Lock()
defer s.Unlock()
if s.NowIndex >= len(s.TargetArr)-1 {
s.NowIndex = 0
} else {
s.NowIndex++
}
return s.TargetArr[s.NowIndex]
}
//深拷贝Config

45
utils/log.go Normal file
View File

@@ -0,0 +1,45 @@
package utils
import (
"github.com/astaxie/beego"
"log"
"os"
"runtime"
)
var Log *log.Logger
func InitLogFile(f string, isStdout bool) {
var prefix string
if !isStdout {
logFile, err := os.OpenFile(beego.AppPath+"/proxy_"+f+"_log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
if err != nil {
log.Fatalln("open file error !")
}
if runtime.GOOS == "windows" {
prefix = "\r\n"
}
Log = log.New(logFile, prefix, log.Ldate|log.Ltime)
} else {
Log = log.New(os.Stdout, "", log.Ldate|log.Ltime)
}
}
func Println(v ...interface{}) {
Log.Println(v ...)
}
func Fatalln(v ...interface{}) {
Log.SetPrefix("error ")
Log.Fatalln(v ...)
Log.SetPrefix("")
}
func Fatalf(format string, v ...interface{}) {
Log.SetPrefix("error ")
Log.Fatalf(format, v...)
Log.SetPrefix("")
}
func Printf(format string, v ...interface{}) {
Log.Printf(format, v...)
}

View File

@@ -1,23 +0,0 @@
package utils
import (
"log"
"testing"
)
var rate = NewRate(100 * 1024)
func TestRate_Get(t *testing.T) {
rate.Start()
for i := 0; i < 5; i++ {
go test(i)
}
test(5)
}
func test(i int) {
for {
rate.Get(64 * 1024)
log.Println("get ok", i)
}
}

View File

@@ -3,7 +3,6 @@ package utils
import (
"encoding/base64"
"io/ioutil"
"log"
"net"
"net/http"
"os"
@@ -38,7 +37,6 @@ WWW-Authenticate: Basic realm="easyProxy"
`
)
//判断压缩方式
func GetCompressType(compress string) (int, int) {
switch compress {
@@ -47,7 +45,7 @@ func GetCompressType(compress string) (int, int) {
case "snappy":
return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
default:
log.Fatalln("数据压缩格式错误")
Fatalln("数据压缩格式错误")
}
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
}
@@ -127,7 +125,6 @@ func Getverifyval(vkey string) string {
return Md5(vkey)
}
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
if host != "" {
r.Host = host
@@ -153,3 +150,14 @@ func ReadAllFromFile(filePath string) ([]byte, error) {
}
return ioutil.ReadAll(f)
}
// FileExists reports whether the named file or directory exists.
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}