Skip to content

Commit

Permalink
安装 守护进程优化 web修改
Browse files Browse the repository at this point in the history
  • Loading branch information
刘河 committed Feb 5, 2019
1 parent 74b2625 commit 7af09a2
Show file tree
Hide file tree
Showing 28 changed files with 405 additions and 3,705 deletions.
18 changes: 11 additions & 7 deletions cmd/nps/nps.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package main
import (
"flag"
"github.com/astaxie/beego"
"github.com/cnlh/nps/server"
"github.com/cnlh/nps/lib"
"github.com/cnlh/nps/server"
_ "github.com/cnlh/nps/web/routers"
"log"
"os"
"path/filepath"
)

const VERSION = "v0.0.13"
Expand All @@ -26,12 +28,13 @@ var (

func main() {
flag.Parse()
var test bool
if len(os.Args) > 1 && os.Args[1] == "test" {
test = true
server.TestServerConfig()
log.Println("test ok, no error")
return
}
lib.InitDaemon("nps")
if *logType == "stdout" || test {
if *logType == "stdout" {
lib.InitLogFile("nps", true)
} else {
lib.InitLogFile("nps", false)
Expand Down Expand Up @@ -61,7 +64,7 @@ func main() {
Flow: &lib.Flow{},
}
c.Cnf.CompressDecode, c.Cnf.CompressEncode = lib.GetCompressType(c.Cnf.Compress)
server.CsvDb.Clients[0] = c
lib.GetCsvDb().Clients[0] = c
task.Client = c
}
if *TcpPort == 0 {
Expand All @@ -75,7 +78,8 @@ func main() {
lib.Println("服务端启动,监听tcp服务端端口:", *TcpPort)
task.Config.CompressDecode, task.Config.CompressEncode = lib.GetCompressType(task.Config.Compress)
if *rpMode != "webServer" {
server.CsvDb.Tasks[0] = task
lib.GetCsvDb().Tasks[0] = task
}
server.StartNewServer(*TcpPort, task, test)
beego.LoadAppConfig("ini", filepath.Join(lib.GetRunPath(), "conf", "app.conf"))
server.StartNewServer(*TcpPort, task)
}
6 changes: 3 additions & 3 deletions conf/app.conf
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
appname = nps

#web管理端口
httpport = 8080
httpport = 8081

#启动模式dev|pro
runmode = dev
Expand All @@ -15,10 +15,10 @@ tcpport=8284
#web api免验证IP地址
authip=127.0.0.1

##http代理端口
##http代理端口,为空则不启动
httpProxyPort=80

##https代理端口
##https代理端口,为空则不启动
httpsProxyPort=

##certFile绝对路径
Expand Down
1 change: 1 addition & 0 deletions conf/clients.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1,ydiigrm4ghu7mym1,,true,,,0,,0,0
1 change: 1 addition & 0 deletions conf/hosts.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a.o.com,127.0.0.1:8081,1,,,测试
4 changes: 4 additions & 0 deletions conf/tasks.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
9001,tunnelServer,123.206.77.88:22,,,,1,0,0,0,1,1,true,测试tcp
53,udpServer,114.114.114.114:53,,,,1,0,0,0,2,1,true,udp
0,socks5Server,,,,,1,0,0,0,3,1,true,socks5
9005,httpProxyServer,,,,,1,0,0,0,4,1,true,
Binary file modified image/web.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 47 additions & 12 deletions lib/daemon.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package lib

import (
"github.com/astaxie/beego"
"io/ioutil"
"log"
"os"
"os/exec"
"runtime"
"path/filepath"
"strconv"
"strings"
)
Expand All @@ -33,39 +32,75 @@ func InitDaemon(f string) {
start(args, f)
os.Exit(0)
case "install":
InstallNps()
if f == "nps" {
InstallNps()
}
os.Exit(0)
case "status":
if status(f) {
log.Printf("%s is running", f)
} else {
log.Printf("%s is not running", f)
}
os.Exit(0)
}
}

func status(f string) bool {
var cmd *exec.Cmd
b, err := ioutil.ReadFile(filepath.Join(GetPidPath(), f+".pid"))
if err == nil {
if !IsWindows() {
cmd = exec.Command("/bin/sh", "-c", "ps -ax | awk '{ print $1 }' | grep "+string(b))
} else {
cmd = exec.Command("tasklist", )
}
out, _ := cmd.Output()
if strings.Index(string(out), string(b)) > -1 {
return true
}
}
return false
}

func start(osArgs []string, f string) {
if status(f) {
log.Printf(" %s is running", f)
return
}
cmd := exec.Command(osArgs[0], osArgs[1:]...)
cmd.Start()
log.Println("执行启动成功")
if cmd.Process.Pid > 0 {
log.Println("start ok , pid:", cmd.Process.Pid, "config path:", GetRunPath())
d1 := []byte(strconv.Itoa(cmd.Process.Pid))
ioutil.WriteFile(beego.AppPath+"/"+f+".pid", d1, 0600)
ioutil.WriteFile(filepath.Join(GetPidPath(), f+".pid"), d1, 0600)
} else {
log.Println("start error")
}
}

func stop(f string, p string) {
if !status(f) {
log.Printf(" %s is not running", f)
return
}
var c *exec.Cmd
var err error
switch runtime.GOOS {
case "windows":
if IsWindows() {
p := strings.Split(p, `\`)
c = exec.Command("taskkill", "/F", "/IM", p[len(p)-1])
case "linux", "darwin":
b, err := ioutil.ReadFile(beego.AppPath + "/" + f + ".pid")
} else {
b, err := ioutil.ReadFile(filepath.Join(GetPidPath(), f+".pid"))
if err == nil {
c = exec.Command("/bin/bash", "-c", `kill -9 `+string(b))
} else {
log.Println("停止服务失败,pid文件不存在")
log.Fatalln("stop error,PID file does not exist")
}
}
err = c.Run()
if err != nil {
log.Println("停止服务失败,", err)
log.Println("stop error,", err)
} else {
log.Println("停止服务成功")
log.Println("stop ok")
}
}
14 changes: 7 additions & 7 deletions lib/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package lib
import (
"encoding/csv"
"errors"
"github.com/astaxie/beego"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -37,7 +37,7 @@ func (s *Csv) Init() {

func (s *Csv) StoreTasksToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/tasks.csv")
csvFile, err := os.Create(filepath.Join(GetRunPath(), "conf", "tasks.csv"))
if err != nil {
Fatalf(err.Error())
}
Expand Down Expand Up @@ -87,7 +87,7 @@ func (s *Csv) openFile(path string) ([][]string, error) {
}

func (s *Csv) LoadTaskFromCsv() {
path := beego.AppPath + "/conf/tasks.csv"
path := filepath.Join(GetRunPath(), "conf", "tasks.csv")
records, err := s.openFile(path)
if err != nil {
Fatalln("配置文件打开错误:", path)
Expand Down Expand Up @@ -186,7 +186,7 @@ func (s *Csv) GetTask(id int) (v *Tunnel, err error) {

func (s *Csv) StoreHostToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/hosts.csv")
csvFile, err := os.Create(filepath.Join(GetRunPath(), "conf", "hosts.csv"))
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -214,7 +214,7 @@ func (s *Csv) StoreHostToCsv() {
}

func (s *Csv) LoadClientFromCsv() {
path := beego.AppPath + "/conf/clients.csv"
path := filepath.Join(GetRunPath(), "conf", "clients.csv")
records, err := s.openFile(path)
if err != nil {
Fatalln("配置文件打开错误:", path)
Expand Down Expand Up @@ -250,7 +250,7 @@ func (s *Csv) LoadClientFromCsv() {
}

func (s *Csv) LoadHostFromCsv() {
path := beego.AppPath + "/conf/hosts.csv"
path := filepath.Join(GetRunPath(), "conf", "hosts.csv")
records, err := s.openFile(path)
if err != nil {
Fatalln("配置文件打开错误:", path)
Expand Down Expand Up @@ -389,7 +389,7 @@ func (s *Csv) GetClient(id int) (v *Client, err error) {
}
func (s *Csv) StoreClientsToCsv() {
// 创建文件
csvFile, err := os.Create(beego.AppPath + "/conf/clients.csv")
csvFile, err := os.Create(filepath.Join(GetRunPath(), "conf", "clients.csv"))
if err != nil {
Fatalln(err.Error())
}
Expand Down
78 changes: 42 additions & 36 deletions lib/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,52 @@ import (
"log"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)

func InstallNps() {
var path string
switch runtime.GOOS {
case "windows":
path = "C:/"
case "linux", "darwin":
path = "/etc/nps/"
}
if err := os.Mkdir(path, 0755); err != nil {
log.Fatalf("创建目录%s失败:%s", path, err.Error())
}
path := GetInstallPath()
MkidrDirAll(path, "conf", "web/static", "web/views")
//复制文件到对应目录
if err := CopyDir("./web", path); err != nil {
if err := CopyDir(filepath.Join(GetAppPath(), "web", "views"), filepath.Join(path, "web", "views")); err != nil {
log.Fatalln(err)
}
if err := CopyDir("./conf", path); err != nil {
if err := CopyDir(filepath.Join(GetAppPath(), "web", "static"), filepath.Join(path, "web", "static")); err != nil {
log.Fatalln(err)
}
if err := CopyDir(filepath.Join(GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
log.Fatalln(err)
}
//linux加入到/etc/init.d

//windows处理
if !IsWindows() {
if _, err := copyFile(filepath.Join(GetAppPath(), "nps"), "/usr/bin/nps"); err != nil {
if _, err := copyFile(filepath.Join(GetAppPath(), "nps"), "/usr/local/bin/nps"); err != nil {
log.Fatalln(err)
} else {
os.Chmod("/usr/local/bin/nps", 0777)
log.Println("Executable files have been copied to", "/usr/local/bin/nps")
}
} else {
os.Chmod("/usr/bin/nps", 0777)
log.Println("Executable files have been copied to", "/usr/bin/nps")
}

//darwin处理
}
log.Println("install ok!")
log.Println("Static files and configuration files in the current directory will be useless")
log.Println("The new configuration file is located in", path, "you can edit them")
if !IsWindows() {
log.Println("You can start with nps test|start|stop|restart|status anywhere")
} else {
log.Println("You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status")
}
}
func MkidrDirAll(path string, v ... string) {
for _, item := range v {
if err := os.MkdirAll(filepath.Join(path, item), 0755); err != nil {
log.Fatalf("Failed to create directory %s error:%s", path, err.Error())
}
}
}

func CopyDir(srcPath string, destPath string) error {
Expand All @@ -44,72 +62,60 @@ func CopyDir(srcPath string, destPath string) error {
return err
} else {
if !srcInfo.IsDir() {
e := errors.New("srcPath不是一个正确的目录!")
fmt.Println(e.Error())
e := errors.New("SrcPath is not the right directory!")
return e
}
}
if destInfo, err := os.Stat(destPath); err != nil {
fmt.Println(err.Error())
return err
} else {
if !destInfo.IsDir() {
e := errors.New("destInfo不是一个正确的目录!")
fmt.Println(e.Error())
e := errors.New("DestInfo is not the right directory!")
return e
}
}
//加上拷贝时间:不用可以去掉
destPath = destPath + "_" + time.Now().Format("20060102150405")

err := filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if !f.IsDir() {
path := strings.Replace(path, "\\", "/", -1)
destNewPath := strings.Replace(path, srcPath, destPath, -1)
fmt.Println("复制文件:" + path + " " + destNewPath)
log.Println("copy file ::" + path + " to " + destNewPath)
copyFile(path, destNewPath)
}
return nil
})
if err != nil {
fmt.Printf(err.Error())
}
return err
}

//生成目录并拷贝文件
func copyFile(src, dest string) (w int64, err error) {
srcFile, err := os.Open(src)
if err != nil {
fmt.Println(err.Error())
return
}
defer srcFile.Close()
//分割path目录
destSplitPathDirs := strings.Split(dest, "/")
destSplitPathDirs := strings.Split(dest, string(filepath.Separator))

//检测时候存在目录
destSplitPath := ""
for index, dir := range destSplitPathDirs {
if index < len(destSplitPathDirs)-1 {
destSplitPath = destSplitPath + dir + "/"
destSplitPath = destSplitPath + dir + string(filepath.Separator)
b, _ := pathExists(destSplitPath)
if b == false {
fmt.Println("创建目录:" + destSplitPath)
log.Println("mkdir:" + destSplitPath)
//创建目录
err := os.Mkdir(destSplitPath, os.ModePerm)
if err != nil {
fmt.Println(err)
log.Fatalln(err)
}
}
}
}
dstFile, err := os.Create(dest)
if err != nil {
fmt.Println(err.Error())
return
}
defer dstFile.Close()
Expand Down
Loading

0 comments on commit 7af09a2

Please sign in to comment.