Commit 92afcbbd authored by Vladimir Barsukov's avatar Vladimir Barsukov
Browse files

add quit pool

parent b9d319f8
package zquit
import (
"os"
"os/signal"
"syscall"
"time"
)
type Pool struct {
PostWaitDur time.Duration
items []*ZQuit
}
func NewPool(postWaitDur time.Duration) *Pool {
return &Pool{
PostWaitDur: postWaitDur,
items: make([]*ZQuit, 0),
}
}
func DefaultPool() *Pool {
return NewPool(time.Second)
}
func (p *Pool) Add(z *ZQuit) {
p.items = append(p.items, z)
}
func (p *Pool) PrintStat() {
for _, i := range p.items {
i.PrintStat()
}
}
func (p *Pool) Wait() {
for _, i := range p.items {
i.Wait()
}
}
func (p *Pool) WaitInterruptPrePost(pre func(), post func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
if pre != nil {
pre()
}
p.Wait()
time.Sleep(p.PostWaitDur)
if post != nil {
post()
}
}
func (p *Pool) WaitInterrupt() {
p.WaitInterruptPrePost(nil, nil)
}
......@@ -3,23 +3,38 @@ package zquit
import (
"git.barsukov.pro/barsukov/zgo/zwg"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type ZQuit struct {
Name string
PostWaitDur time.Duration
isQuit bool
wg *zwg.Zwg
}
func New() *ZQuit {
func New(name string, postWaitDur time.Duration) *ZQuit {
return &ZQuit{
Name: name,
PostWaitDur: postWaitDur,
wg: zwg.New(),
}
}
func Default(name ...string) *ZQuit {
if len(name) == 0 {
name = []string{"MAIN"}
}
return New(name[0], time.Second)
}
func (q *ZQuit) Inc() {
q.wg.Inc()
}
......@@ -47,16 +62,16 @@ func (q *ZQuit) Val() int {
}
func (q *ZQuit) WaitInterruptPrePost(pre func(), post func()) {
if pre != nil {
pre()
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
if pre != nil {
pre()
}
q.Wait()
time.Sleep(q.PostWaitDur)
if post != nil {
post()
......@@ -70,6 +85,7 @@ func (q *ZQuit) WaitInterrupt() {
func (q *ZQuit) Middleware(c *gin.Context) {
if q.isQuit {
c.Data(http.StatusServiceUnavailable, "text/plain", []byte("server shutdown"))
c.Abort()
return
}
......@@ -79,6 +95,15 @@ func (q *ZQuit) Middleware(c *gin.Context) {
c.Next()
}
func (q *ZQuit) PrintStat() {
go func() {
for {
<-time.After(time.Second)
log.Printf("Z_QUIT: LOCKS[%s]: %v", q.Name, q.Val())
}
}()
}
func (q *ZQuit) Shutdown() {
q.isQuit = true
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment