Skip to content

Commit e39a360

Browse files
authored
feat: add auto shutdown (#2)
* feat: add auto shutdown Signed-off-by: cbluebird <crk2778355976@163.com> * feat: add gracefully shutting down Signed-off-by: cbluebird <crk2778355976@163.com> * bugfix: fix the graceful shutdown and http close Signed-off-by: cbluebird <crk2778355976@163.com> * bugfix: move http close after err check Signed-off-by: cbluebird <crk2778355976@163.com> --------- Signed-off-by: cbluebird <crk2778355976@163.com>
1 parent 67780e7 commit e39a360

File tree

5 files changed

+102
-6
lines changed

5 files changed

+102
-6
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
wst
22
**/*.local
3+
.idea

go.work.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
golang.org/x/crypto v0.30.0 h1:RwoQn3GkWiMkzlX562cLB7OxWvjH1L8xutO2WoJcRoY=
12
golang.org/x/crypto v0.30.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
3+
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
24
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
5+
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
36
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
7+
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
48
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=

server/healthy.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"log"
8+
"net/http"
9+
"os"
10+
"sync/atomic"
11+
"time"
12+
)
13+
14+
var (
15+
interval = os.Getenv("AUTO_SHUTDOWN_INTERVAL")
16+
serviceTarget = os.Getenv("AUTO_SHUTDOWN_SERVICE_URL")
17+
jwtToken = os.Getenv("JWT_TOKEN")
18+
)
19+
20+
var ActiveNum int32 = 0
21+
22+
func HealthyCheck(ctx context.Context) {
23+
shutdownDuration, _ := time.ParseDuration(interval)
24+
ticker := time.NewTicker(1 * time.Minute)
25+
defer ticker.Stop()
26+
27+
zeroDuration := 0 * time.Minute
28+
for {
29+
select {
30+
case <-ticker.C:
31+
if atomic.LoadInt32(&ActiveNum) == 0 {
32+
zeroDuration += 1 * time.Minute
33+
if zeroDuration >= shutdownDuration {
34+
sendShutdownRequest()
35+
}
36+
} else {
37+
zeroDuration = 0
38+
}
39+
case <-ctx.Done():
40+
return
41+
}
42+
}
43+
}
44+
45+
func sendShutdownRequest() {
46+
url := serviceTarget + "/opsrequest"
47+
data := map[string]string{
48+
"operation": "shutdown",
49+
"jwt_token": jwtToken,
50+
}
51+
jsonData, _ := json.Marshal(data)
52+
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
53+
if err != nil {
54+
log.Println("error:fail to send shutdown request", err)
55+
}
56+
defer resp.Body.Close()
57+
}

server/main.go

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,50 @@
11
package main
22

3-
import "os"
3+
import (
4+
"context"
5+
"log"
6+
"os"
7+
"os/signal"
8+
"sync"
9+
"syscall"
10+
)
411

512
var (
613
listen = os.Getenv("LISTEN")
714
target = os.Getenv("TARGET")
15+
flag = os.Getenv("ENABLE_AUTO_SHUTDOWN")
816
)
917

1018
func main() {
19+
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
20+
defer cancel()
21+
22+
var wg sync.WaitGroup
23+
24+
if flag == "true" {
25+
wg.Add(1)
26+
go func() {
27+
defer wg.Done()
28+
HealthyCheck(ctx)
29+
}()
30+
}
31+
1132
if listen == "" || target == "" {
1233
panic("LISTEN or TARGET is not set")
1334
}
14-
_ = NewServer(
15-
listen,
16-
"/",
17-
NewHandler(target),
18-
).Serve()
35+
36+
go func() {
37+
err := NewServer(
38+
listen,
39+
"/",
40+
NewHandler(target),
41+
).Serve()
42+
if err != nil {
43+
log.Fatalf("Failed to ws serve: %v", err)
44+
}
45+
}()
46+
47+
<-ctx.Done()
48+
log.Println("Shutting down gracefully")
49+
wg.Wait()
1950
}

server/wsh.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"net"
88
"net/http"
99
"sync"
10+
"sync/atomic"
1011
"time"
1112

1213
"golang.org/x/net/websocket"
@@ -95,7 +96,9 @@ func (h *Handler) putBuffer(buffer *[]byte) {
9596
}
9697

9798
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
99+
atomic.AddInt32(&ActiveNum, 1)
98100
h.wsServer.ServeHTTP(w, req)
101+
atomic.AddInt32(&ActiveNum, -1)
99102
}
100103

101104
var pingCodec = websocket.Codec{

0 commit comments

Comments
 (0)