1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2025-01-23 17:53:23 +02:00

106 lines
2.1 KiB
Go
Raw Normal View History

2015-04-08 15:43:59 -07:00
package server
import (
"io"
2015-04-29 19:57:43 -07:00
"strconv"
2015-04-08 15:43:59 -07:00
"github.com/drone/drone/pkg/bus"
2015-04-08 15:43:59 -07:00
2015-05-22 11:37:40 -07:00
log "github.com/drone/drone/Godeps/_workspace/src/github.com/Sirupsen/logrus"
"github.com/drone/drone/Godeps/_workspace/src/github.com/gin-gonic/gin"
"github.com/drone/drone/Godeps/_workspace/src/github.com/manucorporat/sse"
"github.com/drone/drone/pkg/docker"
2015-04-08 15:43:59 -07:00
)
// GetRepoEvents will upgrade the connection to a Websocket and will stream
// event updates to the browser.
func GetRepoEvents(c *gin.Context) {
bus_ := ToBus(c)
repo := ToRepo(c)
c.Writer.Header().Set("Content-Type", "text/event-stream")
2015-04-24 17:06:46 -07:00
eventc := make(chan *bus.Event, 1)
bus_.Subscribe(eventc)
2015-04-08 15:43:59 -07:00
defer func() {
bus_.Unsubscribe(eventc)
close(eventc)
log.Infof("closed event stream")
2015-04-08 15:43:59 -07:00
}()
c.Stream(func(w io.Writer) bool {
select {
case event := <-eventc:
if event == nil {
log.Infof("nil event received")
return false
}
if event.Kind == bus.EventRepo &&
event.Name == repo.FullName {
sse.Encode(w, sse.Event{
Event: "message",
Data: string(event.Msg),
})
}
case <-c.Writer.CloseNotify():
return false
}
return true
})
2015-04-08 15:43:59 -07:00
}
2015-04-29 19:57:43 -07:00
func GetStream(c *gin.Context) {
store := ToDatastore(c)
2015-04-29 19:57:43 -07:00
repo := ToRepo(c)
2015-05-06 00:56:06 -07:00
runner := ToRunner(c)
commitseq, _ := strconv.Atoi(c.Params.ByName("build"))
2015-06-18 17:36:52 -07:00
jobnum, _ := strconv.Atoi(c.Params.ByName("number"))
2015-04-29 19:57:43 -07:00
c.Writer.Header().Set("Content-Type", "text/event-stream")
2015-05-06 00:56:06 -07:00
build, err := store.BuildNumber(repo, commitseq)
if err != nil {
c.Fail(404, err)
return
}
job, err := store.JobNumber(build, jobnum)
if err != nil {
c.Fail(404, err)
return
}
2015-09-08 18:55:03 -07:00
rc, err := runner.Logs(job)
if err != nil {
c.Fail(404, err)
return
2015-04-29 19:57:43 -07:00
}
defer func() {
rc.Close()
}()
2015-05-06 00:56:06 -07:00
go func() {
<-c.Writer.CloseNotify()
rc.Close()
2015-05-06 00:56:06 -07:00
}()
rw := &StreamWriter{c.Writer, 0}
2015-05-06 00:56:06 -07:00
docker.StdCopy(rw, rw, rc)
}
2015-05-06 00:56:06 -07:00
type StreamWriter struct {
writer gin.ResponseWriter
count int
2015-04-29 19:57:43 -07:00
}
func (w *StreamWriter) Write(data []byte) (int, error) {
var err = sse.Encode(w.writer, sse.Event{
Id: strconv.Itoa(w.count),
Event: "message",
Data: string(data),
2015-04-08 15:43:59 -07:00
})
w.writer.Flush()
w.count += len(data)
return len(data), err
2015-04-08 15:43:59 -07:00
}