安装 守护进程优化 web修改

This commit is contained in:
刘河
2019-02-06 00:35:23 +08:00
parent 74b262503e
commit 7af09a2f4c
28 changed files with 406 additions and 3706 deletions

View File

@@ -1,12 +1,11 @@
package lib
import (
"github.com/astaxie/beego"
"io/ioutil"
"log"
"os"
"os/exec"
"runtime"
"path/filepath"
"strconv"
"strings"
)
@@ -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")
}
}

View File

@@ -3,8 +3,8 @@ package lib
import (
"encoding/csv"
"errors"
"github.com/astaxie/beego"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
@@ -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())
}
@@ -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)
@@ -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)
}
@@ -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)
@@ -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)
@@ -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())
}

View File

@@ -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 {
@@ -44,39 +62,29 @@ 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
}
@@ -84,32 +92,30 @@ func CopyDir(srcPath string, destPath string) error {
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()

View File

@@ -1,9 +1,9 @@
package lib
import (
"github.com/astaxie/beego"
"log"
"os"
"path/filepath"
"runtime"
)
@@ -12,9 +12,9 @@ var Log *log.Logger
func InitLogFile(f string, isStdout bool) {
var prefix string
if !isStdout {
logFile, err := os.OpenFile(beego.AppPath+"/"+f+"_log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
logFile, err := os.OpenFile(filepath.Join(GetLogPath(), f+"_log.txt"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
if err != nil {
log.Fatalln("open file error !")
log.Fatalln("open file error !", err)
}
if runtime.GOOS == "windows" {
prefix = "\r\n"

View File

@@ -6,7 +6,9 @@ import (
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
)
@@ -151,7 +153,6 @@ 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 {
@@ -160,4 +161,60 @@ func FileExists(name string) bool {
}
}
return true
}
}
func GetRunPath() string {
var path string
if path = GetInstallPath(); !FileExists(path) {
return "./"
}
return path
}
func GetInstallPath() string {
var path string
if IsWindows() {
path = `C:\Program Files\nps`
} else {
path = "/etc/nps"
}
return path
}
func GetAppPath() string {
if path, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
return path
}
return os.Args[0]
}
func IsWindows() bool {
if runtime.GOOS == "windows" {
return true
}
return false
}
func GetLogPath() string {
var path string
if IsWindows() {
path = "./"
} else {
path = "/tmp"
}
return path
}
func GetPidPath() string {
var path string
if IsWindows() {
path = "./"
} else {
path = "/tmp"
}
return path
}
func TestTcpPort(port int) bool {
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
defer l.Close()
if err != nil {
return false
}
return true
}