log is ok to see in the web

master
codeskyblue 8 years ago
parent 5be7f800ce
commit 494f65c727

2
Godeps/Godeps.json generated

@ -5,7 +5,7 @@
"Deps": [
{
"ImportPath": "github.com/codeskyblue/kexec",
"Rev": "b7e1983cb3267c8862794eacf39b14386dfa441f"
"Rev": "098ccba5e5e7e676f3631983c5ea931a3592871f"
},
{
"ImportPath": "github.com/go-yaml/yaml",

@ -0,0 +1,98 @@
package main
import (
"bytes"
"log"
"sync"
"time"
)
type BroadcastString struct {
writers map[chan string]bool
mu sync.Mutex
}
func NewBroadcastString() *BroadcastString {
return &BroadcastString{
writers: make(map[chan string]bool, 0),
}
}
func (b *BroadcastString) WriteMessage(message string) {
b.mu.Lock()
defer b.mu.Unlock()
for c := range b.writers {
select {
case c <- message:
case <-time.After(500 * time.Millisecond):
log.Println("channel closed, remove from queue")
delete(b.writers, c)
}
}
}
func (b *BroadcastString) AddListener(c chan string) chan string {
b.mu.Lock()
defer b.mu.Unlock()
if c == nil {
c = make(chan string, 0)
}
b.writers[c] = true
return c
}
type BufferBroadcast struct {
bs *BroadcastString
maxSize int
buf *bytes.Buffer
mu sync.Mutex
}
func NewBufferBroadcast(size int) *BufferBroadcast {
if size <= 0 {
size = 4 * 1024 // 4K
}
return &BufferBroadcast{
maxSize: size,
bs: NewBroadcastString(),
buf: bytes.NewBuffer(nil), // buffer.NewRing(buffer.New(size)),
}
}
func (b *BufferBroadcast) Write(data []byte) (n int, err error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.buf.Len() >= b.maxSize*2 {
b.buf = bytes.NewBuffer(b.buf.Bytes()[b.buf.Len()-b.maxSize : b.buf.Len()])
}
b.bs.WriteMessage(string(data))
return b.buf.Write(data)
}
func (b *BufferBroadcast) Reset() {
b.buf.Reset()
}
func (b *BufferBroadcast) AddHookFunc(wf func(string) error) chan error {
b.mu.Lock()
defer b.mu.Unlock()
c := b.bs.AddListener(nil)
errC := make(chan error, 1)
go func() {
data := b.buf.Bytes()
// data, _ := ioutil.ReadAll(b.buf)
if err := wf(string(data)); err != nil {
errC <- err
return
}
for msg := range c {
err := wf(msg)
if err != nil {
errC <- err
break
}
}
}()
return errC
}

@ -0,0 +1,43 @@
package main
import (
"sync"
"testing"
)
func TestBroadcast(t *testing.T) {
bs := NewBroadcastString()
bs.WriteMessage("hello")
c1 := bs.AddListener(nil)
go func() {
bs.WriteMessage("world")
}()
message := <-c1
if message != "world" {
t.Fatalf("expect message world, but got %s", message)
}
c2 := bs.AddListener(nil)
go func() {
bs.WriteMessage("tab")
}()
// test write multi
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
message = <-c2
if message != "tab" {
t.Errorf("expect tab, but got %s", message)
}
wg.Done()
}()
go func() {
message = <-c1
if message != "tab" {
t.Errorf("expect tab, but got %s", message)
}
wg.Done()
}()
wg.Wait()
}

@ -17,6 +17,7 @@ package main
import (
"errors"
"fmt"
"io"
"log"
"os"
"sync"
@ -122,6 +123,9 @@ type Process struct {
*FSM `json:"-"`
Program `json:"program"`
cmd *kexec.KCommand
Stdout *BufferBroadcast
Stderr *BufferBroadcast
Output *BufferBroadcast
stopC chan syscall.Signal
retryLeft int
Status string `json:"status"`
@ -131,6 +135,8 @@ func (p *Process) buildCommand() *kexec.KCommand {
cmd := kexec.CommandString(p.Command) // Not tested here, I think it should work
// cmd := kexec.Command(p.Command[0], p.Command[1:]...)
cmd.Dir = p.Dir
cmd.Stdout = io.MultiWriter(p.Stdout, p.Output)
cmd.Stderr = io.MultiWriter(p.Stderr, p.Output)
cmd.Env = append(os.Environ(), p.Environ...)
return cmd
}
@ -155,9 +161,14 @@ func (p *Process) stopCommand() {
if p.cmd == nil {
return
}
p.cmd.Terminate(syscall.SIGKILL)
p.cmd.Terminate(syscall.SIGTERM)
select {
case <-GoFunc(p.cmd.Wait):
case <-time.After(3 * time.Second): // TODO: add 3s to config
p.cmd.Terminate(syscall.SIGKILL)
}
p.cmd.Wait() // This is OK, because Signal KILL will definitely work
p.cmd = nil
time.Sleep(200 * time.Millisecond)
p.SetState(Stopped)
}
@ -167,9 +178,11 @@ func (p *Process) IsRunning() bool {
func (p *Process) startCommand() {
p.stopCommand()
p.Stdout.Reset()
p.Stderr.Reset()
p.Output.Reset()
log.Println("start cmd:", p.Name, p.Command)
p.cmd = kexec.CommandString(p.Command)
p.cmd.Stdout = os.Stdout
p.cmd = p.buildCommand()
p.SetState(Running)
go func() {
@ -194,12 +207,16 @@ func (p *Process) startCommand() {
}
func NewProcess(pg Program) *Process {
outputBufferSize := 4 * 1024 // 4K
pr := &Process{
FSM: NewFSM(Stopped),
Program: pg,
stopC: make(chan syscall.Signal),
retryLeft: pg.StartRetries,
Status: string(Stopped),
Output: NewBufferBroadcast(outputBufferSize),
Stdout: NewBufferBroadcast(outputBufferSize),
Stderr: NewBufferBroadcast(outputBufferSize),
}
pr.StateChange = func(_, newStatus FSMState) {
pr.Status = string(newStatus)

@ -19,5 +19,5 @@ body {
}
.realtime-log {
height: 15em;
height: 50em;
}

@ -191,11 +191,11 @@
backdrop: 'static',
})
});
$("#modalTailf").modal({
show: true,
// keyboard: false,
// backdrop: 'static',
})
// $("#modalTailf").modal({
// // show: true,
// // keyboard: false,
// // backdrop: 'static',
// })
});
</script>
</body>

@ -126,6 +126,7 @@ var vm = new Vue({
W.wsLog = newWebsocket("/ws/logs/" + name, {
onopen: function(evt) {
that.log.content = "";
that.log.line_count = 0;
},
onmessage: function(evt) {
that.log.content += evt.data;
@ -138,6 +139,7 @@ var vm = new Vue({
}
}
});
this.log.follow = true;
$("#modalTailf").modal({
show: true,
keyboard: true,

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 codeskyblue
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.

@ -37,3 +37,9 @@ example2: see more [examples](examples)
p.Start()
p.Terminate(syscall.SIGKILL)
}
## PS
This lib also support you call `Wait()` twice, which is not support by `os/exec`
## LICENSE
[MIT](LICENSE)

@ -1,7 +1,53 @@
package kexec
import "os/exec"
import (
"errors"
"os/exec"
"sync"
)
type KCommand struct {
*exec.Cmd
errChs []chan error
err error
finished bool
once sync.Once
mu sync.Mutex
}
func (c *KCommand) Run() error {
if err := c.Start(); err != nil {
return err
}
return c.Wait()
}
func (k *KCommand) Wait() error {
if k.Process == nil {
return errors.New("exec: not started")
}
k.once.Do(func() {
if k.errChs == nil {
k.errChs = make([]chan error, 0)
}
go func() {
k.err = k.Cmd.Wait()
k.mu.Lock()
k.finished = true
for _, errC := range k.errChs {
errC <- k.err
}
k.mu.Unlock()
}()
})
k.mu.Lock()
if k.finished {
k.mu.Unlock()
return k.err
}
errC := make(chan error, 1)
k.errChs = append(k.errChs, errC)
k.mu.Unlock()
return <-errC
}

@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
@ -26,8 +27,9 @@ type Supervisor struct {
pgs []*Program
pgMap map[string]*Program
procMap map[string]*Process
eventCs map[chan string]bool
mu sync.Mutex
mu sync.Mutex
eventB *BroadcastString
}
func (s *Supervisor) programPath() string {
@ -45,27 +47,45 @@ func (s *Supervisor) newProcess(pg Program) *Process {
}
func (s *Supervisor) broadcastEvent(event string) {
s.mu.Lock()
defer s.mu.Unlock()
for c := range s.eventCs {
select {
case c <- event:
case <-time.After(500 * time.Millisecond):
log.Println("Chan closed, remove from queue")
delete(s.eventCs, c)
}
}
s.eventB.WriteMessage(event)
}
func (s *Supervisor) addStatusChangeListener(c chan string) {
s.mu.Lock()
defer s.mu.Unlock()
s.eventCs[c] = true
s.eventB.AddListener(c)
}
// Send Stop signal and wait program stops
func (s *Supervisor) stopAndWait(name string) error {
p, ok := s.procMap[name]
if !ok {
return errors.New("No such program")
}
if !p.IsRunning() {
return nil
}
c := make(chan string, 0)
defer func() { close(c) }()
s.addStatusChangeListener(c)
p.Operate(StopEvent)
for {
select {
case <-c:
if !p.IsRunning() {
return nil
}
case <-time.After(1 * time.Second): // In case some event not catched
if !p.IsRunning() {
return nil
}
}
}
}
func (s *Supervisor) addOrUpdateProgram(pg Program) error {
defer s.broadcastEvent(pg.Name + " add or update")
if err := pg.Check(); err != nil {
return err
}
origPg, ok := s.pgMap[pg.Name]
if ok {
if !reflect.DeepEqual(origPg, &pg) {
@ -73,10 +93,7 @@ func (s *Supervisor) addOrUpdateProgram(pg Program) error {
origProc := s.procMap[pg.Name]
isRunning := origProc.IsRunning()
go func() {
origProc.Operate(StopEvent)
// TODO: wait state change
time.Sleep(2 * time.Second)
s.stopAndWait(origProc.Name)
newProc := s.newProcess(pg)
s.procMap[pg.Name] = newProc
@ -91,7 +108,7 @@ func (s *Supervisor) addOrUpdateProgram(pg Program) error {
s.procMap[pg.Name] = s.newProcess(pg)
log.Println("Add:", pg.Name)
}
return s.saveDB()
return nil // s.saveDB()
}
// Check
@ -222,6 +239,7 @@ func (s *Supervisor) hAddProgram(w http.ResponseWriter, r *http.Request) {
"error": err.Error(),
})
} else {
s.saveDB()
data, _ = json.Marshal(map[string]interface{}{
"status": 0,
})
@ -280,8 +298,6 @@ func (s *Supervisor) wsEvents(w http.ResponseWriter, r *http.Request) {
ch := make(chan string, 0)
s.addStatusChangeListener(ch)
// s.eventCs[ch] = true
// s.eventCs = append(s.eventCs, ch)
go func() {
for message := range ch {
// Question: type 1 ?
@ -307,6 +323,12 @@ func (s *Supervisor) wsEvents(w http.ResponseWriter, r *http.Request) {
func (s *Supervisor) wsLog(w http.ResponseWriter, r *http.Request) {
name := mux.Vars(r)["name"]
log.Println(name)
proc, ok := s.procMap[name]
if !ok {
log.Println("No such process")
// TODO: raise error here?
return
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
@ -314,15 +336,10 @@ func (s *Supervisor) wsLog(w http.ResponseWriter, r *http.Request) {
return
}
defer c.Close()
n := 0
for {
n += 1
err := c.WriteMessage(1, []byte(strconv.Itoa(n)+" "+time.Now().Format(http.TimeFormat)+"Hello\n"))
if err != nil {
break
}
time.Sleep(500 * time.Millisecond)
}
<-proc.Output.AddHookFunc(func(message string) error {
return c.WriteMessage(1, []byte(message))
})
}
func (s *Supervisor) catchExitSignal() {
@ -346,7 +363,8 @@ func init() {
ConfigDir: defaultConfigDir,
pgMap: make(map[string]*Program, 0),
procMap: make(map[string]*Process, 0),
eventCs: make(map[chan string]bool),
// eventCs: make(map[chan string]bool),
eventB: NewBroadcastString(),
}
if err := suv.loadDB(); err != nil {
log.Fatal(err)

Loading…
Cancel
Save