feat/muzan
Evan Chen 2021-11-12 23:09:32 +08:00 committed by Evan
parent 56841cc8be
commit 2ecac19807
14 changed files with 224 additions and 6026 deletions

View File

@ -36,7 +36,7 @@ func init() {
flag.StringVar(&flagAction, "c", "", "cmd to apply") flag.StringVar(&flagAction, "c", "", "cmd to apply")
flag.StringVar(&flagLogFile, "log", "", "log to file") flag.StringVar(&flagLogFile, "log", "", "log to file")
flag.StringVar(&flagAllow, "allow", "", "IPs to allow, blank to allow all") flag.StringVar(&flagAllow, "allow", "", "IPs to allow, blank to allow all")
flag.StringVar(&flagBind, "bind", "0.0.0.0:8000", "address to bind") flag.StringVar(&flagBind, "bind", "127.0.0.1:8000", "address to bind")
flag.BoolVar(&flagNoReconfig, "static", false, "disable config api") flag.BoolVar(&flagNoReconfig, "static", false, "disable config api")
flag.BoolVar(&flagVer, "v", false, "show version") flag.BoolVar(&flagVer, "v", false, "show version")
flag.Usage = func() { flag.Usage = func() {

View File

@ -8,6 +8,7 @@ import (
"html/template" "html/template"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -17,8 +18,9 @@ import (
"kumoly.io/tools/configui/public" "kumoly.io/tools/configui/public"
) )
var UNIX_SHELL = "/usr/bin/sh" const UNIX_SHELL = "/usr/bin/sh"
var WIN_SHELL = "C:\\Windows\\System32\\cmd" const WIN_SHELL = "C:\\Windows\\System32\\cmd"
const DARWIN_SHELL = "/bin/bash"
const version = "v0.1.12" const version = "v0.1.12"
@ -35,13 +37,12 @@ var Ext2Mode map[string]string = map[string]string{
} }
type Action struct { type Action struct {
Name string `json:"name"` Name string `json:"name"`
Cmd string `json:"cmd"` Cmd string `json:"cmd"`
Dir string `json:"dir"` Dir string `json:"dir"`
Args []string `json:"args"`
Envs []string `json:"envs"`
run chan struct{} `json:"-"` run chan struct{} `json:"-"`
pid int
} }
type Integration struct { type Integration struct {
@ -56,6 +57,7 @@ type ConfigUI struct {
Prod bool `json:"production"` Prod bool `json:"production"`
BaseUrl string `json:"base_url"` BaseUrl string `json:"base_url"`
ConfigPath string `json:"config_path"` ConfigPath string `json:"config_path"`
SHELL string `json:"shell"`
NoReconfig bool `json:"no_reconfig"` NoReconfig bool `json:"no_reconfig"`
AllowIP string `json:"allow_ip"` AllowIP string `json:"allow_ip"`
@ -75,7 +77,8 @@ type ConfigUI struct {
LogLevel klog.Llevel `json:"log_level"` LogLevel klog.Llevel `json:"log_level"`
// Running commands // Running commands
Onitachi map[string]*Oni `json:"-"` Onitachi []*Oni `json:"onitachi"`
oniIndex map[string]int `json:"-"`
TmplFS embed.FS `json:"-"` TmplFS embed.FS `json:"-"`
tmpl *engine.Engine tmpl *engine.Engine
@ -98,9 +101,43 @@ func New() *ConfigUI {
"normal": func(name string) string { "normal": func(name string) string {
return strings.ReplaceAll(name, " ", "-") return strings.ReplaceAll(name, " ", "-")
}, },
"state_class": func(state State) string {
switch state {
case STARTED:
return "is-success"
case ERROR:
return "is-danger"
case ENDED:
return "has-background-grey-light"
default:
return ""
}
},
"state_icon": func(state State) string {
switch state {
case STARTED:
return "play_arrow"
case ERROR:
return "error"
case ENDED:
return "stop"
default:
return "pending"
}
},
}).ParseFS(tmplFS, "templates/*.tmpl", "templates/**/*.tmpl")) }).ParseFS(tmplFS, "templates/*.tmpl", "templates/**/*.tmpl"))
sh := ""
switch runtime.GOOS {
case "darwin":
sh = DARWIN_SHELL
case "windows":
sh = WIN_SHELL
default:
sh = UNIX_SHELL
}
return &ConfigUI{ return &ConfigUI{
fileIndex: map[string]int{}, fileIndex: map[string]int{},
SHELL: sh,
Prod: true, Prod: true,
AppName: "ConfigUI", AppName: "ConfigUI",
BaseUrl: "/", BaseUrl: "/",
@ -112,7 +149,7 @@ func New() *ConfigUI {
cmdTimeout: time.Second * 10, cmdTimeout: time.Second * 10,
LogLevel: klog.Lerror | klog.Linfo, LogLevel: klog.Lerror | klog.Linfo,
log: klog.Sub("ConfigUI"), log: klog.Sub("ConfigUI"),
Onitachi: make(map[string]*Oni), oniIndex: make(map[string]int),
} }
} }
@ -155,6 +192,28 @@ func (cui *ConfigUI) LoadConfig(confstr string) error {
} }
} }
// construct oni
for _, o := range tmpConf.Onitachi {
if o.Cmd == "" {
continue
}
if o.Name == "" {
o.Name = o.Cmd
}
// update if exist
j, ok := cui.oniIndex[o.Name]
if ok {
cui.Onitachi[j].Cmd = o.Cmd
cui.Onitachi[j].Args = o.Args
cui.Onitachi[j].Envs = o.Envs
cui.Onitachi[j].Dir = o.Dir
cui.Onitachi[j].Policy = o.Policy
} else {
cui.oniIndex[o.Name] = len(cui.Onitachi)
cui.Onitachi = append(cui.Onitachi, o)
}
}
// copy // copy
cui.configLock.Lock() cui.configLock.Lock()
defer cui.configLock.Unlock() defer cui.configLock.Unlock()
@ -167,6 +226,7 @@ func (cui *ConfigUI) LoadConfig(confstr string) error {
cui.HideConfig = tmpConf.HideConfig cui.HideConfig = tmpConf.HideConfig
cui.NoReconfig = tmpConf.NoReconfig cui.NoReconfig = tmpConf.NoReconfig
cui.ResultBellow = tmpConf.ResultBellow cui.ResultBellow = tmpConf.ResultBellow
cui.SHELL = tmpConf.SHELL
cui.Actions = tmpConf.Actions cui.Actions = tmpConf.Actions
for i := range cui.Actions { for i := range cui.Actions {

View File

@ -13,9 +13,9 @@ var ErrorOniHasNoPID = ksrv.Error{
} }
var ErrorOniNotStarted = ksrv.Error{ var ErrorOniNotStarted = ksrv.Error{
Code: http.StatusConflict, Code: http.StatusConflict,
ID: "ErrorOniNotStarted", ID: "ErrorOniNotStarted",
Message: "oni hasn't start", Tmpl: "%s hasn't start",
} }
var ErrorOniHasStarted = ksrv.Error{ var ErrorOniHasStarted = ksrv.Error{
@ -25,9 +25,9 @@ var ErrorOniHasStarted = ksrv.Error{
} }
var ErrorOniNotFound = ksrv.Error{ var ErrorOniNotFound = ksrv.Error{
Code: http.StatusNotFound, Code: http.StatusNotFound,
ID: "ErrorOniNotFound", ID: "ErrorOniNotFound",
Message: "oni not found", Tmpl: "%s not found",
} }
var ErrorOniNotValid = ksrv.Error{ var ErrorOniNotValid = ksrv.Error{

View File

@ -58,7 +58,7 @@ func (f *File) Write(data []byte) error {
return os.WriteFile(f.Path, data, info.Mode()) return os.WriteFile(f.Path, data, info.Mode())
} }
func (f *File) Do(CmdTimeout time.Duration) (string, error) { func (f *File) Do(CmdTimeout time.Duration, report chan int) (string, error) {
if f.Cmd == "" { if f.Cmd == "" {
return "", nil return "", nil
} }
@ -80,9 +80,9 @@ func (f *File) Do(CmdTimeout time.Duration) (string, error) {
// prepare cmd // prepare cmd
cmd := &exec.Cmd{} cmd := &exec.Cmd{}
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
cmd = exec.Command(WIN_SHELL, "/c", f.Cmd) cmd = exec.Command(f.owner.SHELL, "/c", f.Cmd)
} else { } else {
cmd = exec.Command(UNIX_SHELL, "-c", f.Cmd) cmd = exec.Command(f.owner.SHELL, "-c", f.Cmd)
} }
f.owner.log.Info("DO: ", f.Cmd) f.owner.log.Info("DO: ", f.Cmd)
done := make(chan string, 1) done := make(chan string, 1)
@ -96,6 +96,7 @@ func (f *File) Do(CmdTimeout time.Duration) (string, error) {
} }
go func() { go func() {
f.pid = cmd.Process.Pid f.pid = cmd.Process.Pid
report <- cmd.Process.Pid
cmd.Wait() cmd.Wait()
done <- b.String() done <- b.String()
}() }()

1
go.mod
View File

@ -10,4 +10,5 @@ require (
require ( require (
github.com/mattn/go-isatty v0.0.14 // indirect github.com/mattn/go-isatty v0.0.14 // indirect
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b // indirect golang.org/x/sys v0.0.0-20211103235746-7861aae1554b // indirect
kumoly.io/lib/stat v0.0.1 // indirect
) )

2
go.sum
View File

@ -10,3 +10,5 @@ kumoly.io/lib/ksrv v0.0.1 h1:JfWwJ9GeiTtDfGoeG7YxJwsckralbhsLKEPLQb20Uzo=
kumoly.io/lib/ksrv v0.0.1/go.mod h1:ykHXeAPjNvA5jEZo5rp32edzkugLf0e+2pspct3FOFQ= kumoly.io/lib/ksrv v0.0.1/go.mod h1:ykHXeAPjNvA5jEZo5rp32edzkugLf0e+2pspct3FOFQ=
kumoly.io/lib/ksrv v0.0.2-0.20211112060911-0d61b343a298 h1:0raqoIXmNpD6s1SrJbieAyIIkDyhe+aqfaXvx8wenrI= kumoly.io/lib/ksrv v0.0.2-0.20211112060911-0d61b343a298 h1:0raqoIXmNpD6s1SrJbieAyIIkDyhe+aqfaXvx8wenrI=
kumoly.io/lib/ksrv v0.0.2-0.20211112060911-0d61b343a298/go.mod h1:pwd+NspxnoxPJAETRY2V4i2qZc+orKLxvWzGUBiqBW8= kumoly.io/lib/ksrv v0.0.2-0.20211112060911-0d61b343a298/go.mod h1:pwd+NspxnoxPJAETRY2V4i2qZc+orKLxvWzGUBiqBW8=
kumoly.io/lib/stat v0.0.1 h1:Ck596El7Ixk7GZyzQq/86F1YCl7iYffHmzEdFx1sSRM=
kumoly.io/lib/stat v0.0.1/go.mod h1:zqMV9q4TC94VGbpDn/mGBTwRNWBVWlVg1taLlCBAWc8=

View File

@ -121,7 +121,7 @@ func (cui *ConfigUI) Apply(w http.ResponseWriter, r *http.Request) {
ksrv.Response(w, 404, []byte("file not found")) ksrv.Response(w, 404, []byte("file not found"))
return return
} }
result, err := file.Do(cui.cmdTimeout) result, err := file.Do(cui.cmdTimeout, make(chan int))
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -141,23 +141,20 @@ func (cui *ConfigUI) DoAction(w http.ResponseWriter, r *http.Request) {
case cui.Actions[i].run <- struct{}{}: case cui.Actions[i].run <- struct{}{}:
defer func() { <-cui.Actions[i].run }() defer func() { <-cui.Actions[i].run }()
default: default:
panic(fmt.Errorf("another task of %s is running with", name)) panic(fmt.Errorf("another task of %s is running with pid: %d", name, v.pid))
} }
oni, ok := cui.Onitachi[name] file := &File{Name: name, Cmd: v.Cmd, owner: cui}
if !ok { pid := make(chan int)
oni = NewOni(name, cui) go func() {
oni.Cmd = cui.Actions[i].Cmd cui.Actions[i].pid = <-pid
oni.Args = cui.Actions[i].Args }()
oni.Envs = cui.Actions[i].Envs result, err := file.Do(cui.cmdTimeout, pid)
oni.Dir = cui.Actions[i].Dir
cui.Onitachi[name] = oni
}
err := oni.Start()
if err != nil { if err != nil {
panic(err) panic(err)
} }
w.Write([]byte("ok")) w.Write([]byte(result))
return return
} }
} }
@ -199,8 +196,8 @@ func (cui *ConfigUI) Download(w http.ResponseWriter, r *http.Request) {
panic(err) panic(err)
} }
w.Header().Set( w.Header().Set(
"Content-Disposition", ` "Content-Disposition",
attachment; filename="`+cui.AppName+`.json"`, `attachment; filename="`+cui.AppName+`.json"`,
) )
w.Write(data) w.Write(data)
return return
@ -263,6 +260,53 @@ func (cui *ConfigUI) GetConfig(w http.ResponseWriter, r *http.Request) {
w.Write(data) w.Write(data)
} }
func (cui *ConfigUI) GetRunning(w http.ResponseWriter, r *http.Request) { func (cui *ConfigUI) GetOni(w http.ResponseWriter, r *http.Request) {
ksrv.JSON(w, cui.Onitachi) name := r.URL.Query().Get("name")
if name == "" {
ksrv.JSON(w, cui.Onitachi)
return
}
i, ok := cui.oniIndex[name]
if !ok {
panic(ErrorOniNotFound.New(name))
}
oni := cui.Onitachi[i]
ksrv.JSON(w, oni)
}
func (cui *ConfigUI) OniStart(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
i, ok := cui.oniIndex[name]
if !ok {
panic(ErrorOniNotFound.New(name))
}
oni := cui.Onitachi[i]
switch oni.State {
case "":
oni.Init(cui)
case STARTED:
panic(ErrorOniHasStarted)
}
err := oni.Start()
if err != nil {
panic(err)
}
w.Write([]byte("ok"))
}
func (cui *ConfigUI) OniStop(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
i, ok := cui.oniIndex[name]
if !ok {
panic(ErrorOniNotFound.New(name))
}
oni := cui.Onitachi[i]
switch oni.State {
case STARTED:
oni.Stop()
default:
panic(ErrorOniNotStarted.New(name))
}
oni.Start()
w.Write([]byte("ok"))
} }

View File

@ -42,33 +42,30 @@ type Oni struct {
Error string `json:"error"` Error string `json:"error"`
ManStop bool `json:"manual_stop"` ManStop bool `json:"manual_stop"`
parent *ConfigUI parent *ConfigUI
cmd *exec.Cmd cmd *exec.Cmd
start chan struct{} running chan struct{}
buff bytes.Buffer buff bytes.Buffer
log io.Writer log io.Writer
listeners []io.Writer listeners []io.Writer
} }
func NewOni(name string, cui *ConfigUI) *Oni { func (oni *Oni) Init(cui *ConfigUI) error {
var err error var err error
oni := &Oni{ oni.parent = cui
Policy: NO, oni.running = make(chan struct{}, 1)
State: READY, oni.listeners = make([]io.Writer, 0)
parent: cui, oni.StateChange(READY)
start: make(chan struct{}, 1),
listeners: make([]io.Writer, 0),
}
if cui.LogPath != "" { if cui.LogPath != "" {
logpath := filepath.Join(filepath.Dir(cui.LogPath), name+".log") logpath := filepath.Join(filepath.Dir(cui.LogPath), oni.Name+".log")
oni.LogFile = logpath oni.LogFile = logpath
oni.log, err = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) oni.log, err = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil { if err != nil {
panic(err) return err
} }
} }
return oni return err
} }
func (oni *Oni) Start() error { func (oni *Oni) Start() error {
@ -76,7 +73,7 @@ func (oni *Oni) Start() error {
return ErrorOniNotValid return ErrorOniNotValid
} }
select { select {
case oni.start <- struct{}{}: case oni.running <- struct{}{}:
defer func() { defer func() {
err := recover() err := recover()
if err != nil { if err != nil {
@ -105,7 +102,7 @@ func (oni *Oni) Start() error {
} }
go oni.read() go oni.read()
oni.PID = cmd.Process.Pid oni.PID = cmd.Process.Pid
oni.State = STARTED oni.StateChange(STARTED)
go func() { go func() {
oni.end(cmd.Wait()) oni.end(cmd.Wait())
}() }()
@ -122,13 +119,13 @@ func (oni *Oni) Stop() error {
func (oni *Oni) end(v interface{}) { func (oni *Oni) end(v interface{}) {
if v == nil { if v == nil {
oni.State = ENDED oni.StateChange(ENDED)
} else { } else {
oni.Error = fmt.Sprint(v) oni.Error = fmt.Sprint(v)
oni.State = ERROR oni.StateChange(ERROR)
} }
if len(oni.start) == 1 { if len(oni.running) == 1 {
<-oni.start <-oni.running
} }
} }
@ -144,3 +141,12 @@ func (oni *Oni) read() {
} }
}() }()
} }
func (oni *Oni) StateChange(state State) {
oni.State = state
// for i := range oni.parent.Actions {
// if oni.parent.Actions[i].Name == oni.Name {
// oni.parent.Actions[i].State = state
// }
// }
}

5961
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -17,10 +17,6 @@
"dependencies": { "dependencies": {
"@creativebulma/bulma-tooltip": "^1.2.0", "@creativebulma/bulma-tooltip": "^1.2.0",
"bulma": "^0.9.3", "bulma": "^0.9.3",
"prismjs": "^1.25.0",
"sass": "^1.43.2" "sass": "^1.43.2"
},
"devDependencies": {
"parcel": "^2.0.0"
} }
} }

View File

@ -5,6 +5,7 @@ import (
"strings" "strings"
"kumoly.io/lib/ksrv" "kumoly.io/lib/ksrv"
"kumoly.io/lib/stat"
) )
func (cui *ConfigUI) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (cui *ConfigUI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@ -98,9 +99,30 @@ func (cui *ConfigUI) mux() *http.ServeMux {
w.WriteHeader(404) w.WriteHeader(404)
} }
}) })
cuiR.HandleFunc("/api/running", func(w http.ResponseWriter, r *http.Request) { cuiR.HandleFunc("/api/profile", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" { if r.Method == "GET" {
cui.GetRunning(w, r) ksrv.JSON(w, stat.GetProfile())
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/oni", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
cui.GetOni(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/oni/start", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
cui.OniStart(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/oni/stop", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
cui.OniStart(w, r)
} else { } else {
w.WriteHeader(404) w.WriteHeader(404)
} }

7
templates/action.tmpl Normal file
View File

@ -0,0 +1,7 @@
{{define "action"}}
{{template "base/header" .}}
{{template "components/error" .}}
{{template "base/footer" .}}
{{end}}

View File

@ -14,6 +14,7 @@
</div> </div>
<div id="navbarBasicExample" class="navbar-menu"> <div id="navbarBasicExample" class="navbar-menu">
{{/*
<div class="navbar-start"> <div class="navbar-start">
{{if .Actions}} {{if .Actions}}
<a class="navbar-item"> <a class="navbar-item">
@ -27,7 +28,6 @@
{{end}} {{end}}
</div> </div>
{{/*
<div class="navbar-end"> <div class="navbar-end">
<div class="navbar-item"> <div class="navbar-item">
<div class="buttons"> <div class="buttons">
@ -44,6 +44,7 @@
</div> </div>
</nav> </nav>
{{/* not having pages
<script> <script>
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
@ -70,5 +71,6 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}); });
*/}}
</script> </script>
{{end}} {{end}}

View File

@ -14,6 +14,24 @@
</li> </li>
{{ end }} {{ end }}
</ul> </ul>
{{/* {{if .Actions}}
<p class="menu-label">
Actions
</p>
<ul class="menu-list">
{{- range .Actions -}}
<li>
<a class="button has-tooltip-arrow {{.State|state_class}}" id="actbtn-{{.Name|normal}}"
data-tooltip="{{.Cmd}}" onclick="toolDoAction('{{.Name}}')">
<span>{{- .Name -}}</span>
<span class="icon is-small"><span class="material-icons">
{{.State|state_icon}}
</span></span>
</a>
</li>
{{- end -}}
</ul>
{{end}} */}}
{{if not .HideConfig}} {{if not .HideConfig}}
<p class="menu-label"> <p class="menu-label">
System System