Skip to content

Commit

Permalink
Added --status. Fixed: cross-compile issues; launch bugs on win
Browse files Browse the repository at this point in the history
  • Loading branch information
Karmenzind committed Dec 20, 2023
1 parent e36a8d5 commit a3e481a
Show file tree
Hide file tree
Showing 11 changed files with 122 additions and 54 deletions.
5 changes: 4 additions & 1 deletion .github/workflows/release-tags.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ jobs:
with:
go-version: '1.21.x'
# cache-dependency-path: go.sum

- name: Install system dependencies
run: sudo apt-get install -y gcc-mingw-w64-x86-64

- name: Install dependencies
run: go mod tidy
Expand All @@ -49,7 +52,7 @@ jobs:
uses: softprops/action-gh-release@v1
# if: startsWith(github.ref, 'refs/tags/')
with:
name: test-${{ steps.version.outputs.version }}
# name: test-${{ steps.version.outputs.version }}
# body_path: ${{ github.workspace }}-CHANGELOG.txt
body: ${{steps.build_changelog.outputs.changelog}}
fail_on_unmatched_files: true
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@

## 特性

- 单文件运行,多平台兼容,无需安装任何依赖
- 单文件运行,多平台兼容,无需安装任何依赖。Windows运行截图:

![](https://raw.githubusercontent.com/Karmenzind/i/master/kd/win_terminal.png)

> 理论上可兼容[所有平台/架构](https://gist.github.com/asukakenji/f15ba7e588ac42795f421b48b8aede63),但我只有Linux/Win可测试,欢迎使用其他平台的朋友试用反馈
Expand Down
61 changes: 46 additions & 15 deletions cmd/kd.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
"syscall"

Expand Down Expand Up @@ -44,34 +45,53 @@ var um = map[string]string{
"update": "check and update kd client 更新kd的可执行文件",
"generate-config": "generate config sample 生成配置文件,Linux/Mac默认地址为~/.config/kd.toml,Win为~\\kd.toml",
"edit-config": "edit configuration file with the default editor 用默认编辑器打开配置文件",
"status": "show running status 展示运行信息",
}

func KillDaemonIfRunning() error {
p, err := daemon.FindServerProcess()
if err == nil && p == nil {
d.EchoOkay("未发现守护进程,无需停止")
return nil
var trySysKill bool
if err == nil {
if p == nil {
d.EchoOkay("未发现守护进程,无需停止")
return nil
} else if runtime.GOOS != "windows" {
zap.S().Infof("Found running daemon PID: %d,", p.Pid)
errSig := p.SendSignal(syscall.SIGINT)
if errSig != nil {
zap.S().Warnf("Failed to stop PID %d with syscall.SIGINT: %s", p.Pid, errSig)
trySysKill = true
}
} else {
trySysKill = true
}
} else {
zap.S().Warnf("[process] Failed to find daemon: %s", err)
trySysKill = true
}
if err != nil {
pidStr := strconv.Itoa(int(p.Pid))

if trySysKill {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("taskkill", "/im", "kd", "/T", "/F")
cmd = exec.Command("taskkill", "/F", "/T", "/PID", pidStr)
// cmd = exec.Command("taskkill", "/im", "kd", "/T", "/F")
case "linux":
cmd = exec.Command("killall", "kd")
cmd = exec.Command("kill", "-9", pidStr)
// cmd = exec.Command("killall", "kd")
}
err = cmd.Run()
output, err := cmd.Output()
zap.S().Infof("Executed '%s'. Output %s", cmd, output)
if err != nil {
zap.S().Warnf("Failed to kill daemon with system command: %s", err)
zap.S().Warnf("Failed to kill daemon with system command. Error: %s", output, err)
}
}
err = p.SendSignal(syscall.SIGINT)
if err != nil {
return err
if err == nil {
zap.S().Info("Terminated daemon process.")
d.EchoOkay("守护进程已经停止")
}
zap.S().Info("Terminated daemon process.")
d.EchoOkay("守护进程已经停止")
return nil
return err
}

// -----------------------------------------------------------------------------
Expand Down Expand Up @@ -164,6 +184,16 @@ func flagEditConfig(*cli.Context, bool) error {
return err
}

func flagStatus(*cli.Context, bool) error {
di := internal.GetDaemonInfo()
d.EchoRun("运行和相关配置信息如下:")
fmt.Printf(" Daemon端口:%s\n", di.Port)
fmt.Printf(" Daemon PID:%d\n", di.PID)
fmt.Printf(" 配置文件地址:%s\n", config.CONFIG_PATH)
fmt.Printf(" 数据文件目录:%s\n", cache.CACHE_ROOT_PATH)
return nil
}

func main() {
config.InitConfig()
cfg := config.Cfg
Expand Down Expand Up @@ -213,10 +243,11 @@ func main() {
&cli.BoolFlag{Name: "update", DisableDefaultText: true, Action: flagUpdate, Usage: um["update"]},
&cli.BoolFlag{Name: "generate-config", DisableDefaultText: true, Action: flagGenerateConfig, Usage: um["generate-config"]},
&cli.BoolFlag{Name: "edit-config", DisableDefaultText: true, Action: flagEditConfig, Usage: um["edit-config"]},
&cli.BoolFlag{Name: "status", DisableDefaultText: true, Action: flagStatus, Usage: um["status"]},
},
Action: func(cCtx *cli.Context) error {
// 除了--text外,其他的BoolFlag都当subcommand用
for _, flag := range []string{"init", "server", "daemon", "stop", "update", "generate-config", "edit-config"} {
for _, flag := range []string{"init", "server", "daemon", "stop", "update", "generate-config", "edit-config", "status"} {
if cCtx.Bool(flag) {
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (c *Config) CheckAndApply() (err error) {
c.Logging.Level = strings.ToLower(c.Logging.Level)
if c.Logging.Level == "warning" {
c.Logging.Level = "warn"
} else if !str.InSlice(c.Logging.Level, []string{"debug", "info", "panic", "fatal"}) {
} else if !str.InSlice(c.Logging.Level, []string{"debug", "info", "warn", "panic", "fatal"}) {
return fmt.Errorf("[logging.level] 不支持的日志等级:%s", c.Logging.Level)

}
Expand Down Expand Up @@ -87,7 +87,7 @@ func parseConfig() (err error) {
Cfg.ModTime = fileinfo.ModTime().Unix()
err = configor.New(&configor.Config{ErrorOnUnmatchedKeys: false}).Load(&Cfg, p)
} else {
// 配有配置文件,部分默认值处理
// 没有配置文件,部分默认值处理
err = configor.New(&configor.Config{ErrorOnUnmatchedKeys: false}).Load(&Cfg)
switch runtime.GOOS {
case "darwin": //MacOS
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ require (
github.com/kyokomi/emoji/v2 v2.2.12
github.com/mattn/go-sqlite3 v1.14.18
github.com/shirou/gopsutil/v3 v3.23.11
github.com/ugorji/go/codec v1.2.12
github.com/urfave/cli/v2 v2.26.0
go.uber.org/zap v1.26.0
golang.org/x/term v0.15.0
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFA
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/urfave/cli/v2 v2.26.0 h1:3f3AMg3HpThFNT4I++TKOejZO8yU55t3JnnSr4S4QEI=
github.com/urfave/cli/v2 v2.26.0/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8=
Expand Down
15 changes: 12 additions & 3 deletions internal/daemon/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"runtime"
"time"

"github.com/Karmenzind/kd/internal/cache"
Expand Down Expand Up @@ -93,14 +94,18 @@ func updateDataZip() {
// continue
// }

applyTempDB(dbPath, tempDBPath)
err = applyTempDB(dbPath, tempDBPath)
if err != nil {
zap.S().Warnf("Failed: %s", err)
continue
}

// success
os.WriteFile(tsFile, []byte(fmt.Sprint(time.Now().Unix())), os.ModePerm)

ticker.Stop()
// TODO 以消息通知形式
zap.S().Infof("DB文件发生改变,进程主动退出")
zap.S().Info("DB文件发生改变,进程主动退出")
fmt.Println("DB文件发生改变,进程主动退出")
os.Exit(0)
break
Expand Down Expand Up @@ -158,7 +163,11 @@ func decompressDBZip(tempDBPath, zipPath string) (err error) {
func applyTempDB(dbPath, tempDBPath string) error {
var err error
now := time.Now()
// cache.LiteDB.Close()
if runtime.GOOS == "windows" {
cache.LiteDB.Close()
zap.S().Info("Waiting for 3 sec...")
time.Sleep(3*time.Second)
}
backupPath := fmt.Sprintf("%s.backup.%d-%d-%d", dbPath, now.Year(), now.Month(), now.Day())
err = os.Rename(dbPath, backupPath)
if err != nil {
Expand Down
64 changes: 38 additions & 26 deletions internal/daemon/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package daemon
import (
"fmt"
"os/exec"
"runtime"
"strings"
"time"

Expand All @@ -13,6 +14,20 @@ import (
"go.uber.org/zap"
)

func getKdPIDs() {
var cmd *exec.Cmd

switch runtime.GOOS {
case "windows":
cmd = exec.Command("taskkill", "/NH", "/FO", "csv")
}
output, err := cmd.Output()
if err != nil {
_ = err
}
strings.Split(string(output), "\n")
}

func ServerIsRunning() bool {
p, _ := FindServerProcess()
return p != nil
Expand All @@ -24,11 +39,9 @@ func FindServerProcess() (*process.Process, error) {
return nil, err
}
for _, p := range processes {
n, err := p.Name()
if err != nil {
return nil, err
}
if n == "kd" {
// XXX err
n, _ := p.Name()
if n == "kd" || (runtime.GOOS == "windows" && n == "kd.exe") {
cmd, _ := p.Cmdline()
if strings.Contains(cmd, " --server") {
zap.S().Debugf("Found process %+v Cmd: %s", p, cmd)
Expand All @@ -40,37 +53,36 @@ func FindServerProcess() (*process.Process, error) {
}

func StartDaemonProcess() error {
kdpath, err := pkg.GetExecutablePath()
kdpath, err := pkg.GetExecutablePath()
if err != nil {
zap.S().Errorf("Failed to get current file path: %s", err)
return err
}
zap.S().Debugf("Got executable path %s", kdpath)
zap.S().Debugf("Got executable path %s", kdpath)

cmd := exec.Command(kdpath, "--server")
err = cmd.Start()
if err != nil {
zap.S().Errorf("Failed to start daemon with system command: %s", err)
return err
}
var p *process.Process
for i := 0; i < 3; i++ {
time.Sleep(time.Second)
p, err_ := FindServerProcess()
if err_ != nil {
zap.S().Warnf("Failed finding daemon process: %s", err_)
}
if p != nil {
zap.S().Infof("Started daemon process.")
d.EchoOkay(fmt.Sprintf("成功启动守护进程,PID:%d", p.Pid))
return nil
}
d.EchoRun("正在检查运行结果,稍等...")
}
if p == nil {
err = fmt.Errorf("启动失败,请重试。如果多次启动失败,请创建Issue并提交日志文件")
return err
}
var p *process.Process
for i := 0; i < 3; i++ {
time.Sleep(time.Second)
p, err_ := FindServerProcess()
if err_ != nil {
zap.S().Warnf("Failed finding daemon process: %s", err_)
}
if p != nil {
zap.S().Infof("Started daemon process.")
d.EchoOkay(fmt.Sprintf("成功启动守护进程,PID:%d", p.Pid))
return nil
}
d.EchoRun("正在检查运行结果,稍等...")
}
if p == nil {
err = fmt.Errorf("启动失败,请重试。如果多次启动失败,请创建Issue并提交日志文件")
return err
}
return nil
}

7 changes: 5 additions & 2 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"

"github.com/Karmenzind/kd/config"
Expand All @@ -16,9 +17,11 @@ func buildLogger(logCfg *config.LoggerConfig, options ...zap.Option) (*zap.Logge
if logCfg.Path == "" {
u, err := user.Current()
if err != nil {
f = fmt.Sprintf("%s/kd.log", os.TempDir())
f = filepath.Join(os.TempDir(), "kd.log")
} else {
f = fmt.Sprintf("%s/kd_%s.log", os.TempDir(), strings.ReplaceAll(u.Username, " ", "_"))
name := strings.ReplaceAll(u.Username, " ", "_")
name = strings.ReplaceAll(name, "\\", "_")
f = filepath.Join(os.TempDir(), fmt.Sprintf("kd_%s.log", name))
}
} else {
f = logCfg.Path
Expand Down
2 changes: 2 additions & 0 deletions plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
## wip
- 测试win/mac的DB初始化情况

- powershell命令改成当前用户范围

## short-term
- 多source直接嵌套进列表
- 加上变形(addtional pattern
Expand Down
11 changes: 10 additions & 1 deletion scripts/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,16 @@ do_build() {
local os=$1
local arch=$2
local targetfile=$3
GOOS=$os GOARCH=$arch go build -o ${targetfile} -ldflags="-s -w" -tags urfave_cli_no_docs cmd/kd.go

local cgo=0 cc=

if [[ $os == "windows" ]]; then
local cgo=1 cc=x86_64-w64-mingw32-gcc
# cc=i686-w64-mingw32-gcc
# local buildopts=-buildmode=c-shared
fi

GOOS=$os GOARCH=$arch CGO_ENABLED=$cgo CC=$cc go build ${buildopts} -o ${targetfile} -ldflags="-s -w" -tags urfave_cli_no_docs cmd/kd.go
echo " Finished -> ${targetfile}"
}

Expand Down

0 comments on commit a3e481a

Please sign in to comment.