-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
197 lines (187 loc) · 4.69 KB
/
Copy pathserver.go
File metadata and controls
197 lines (187 loc) · 4.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package balanceServer
import (
"context"
"encoding/binary"
"errors"
"fmt"
"github.com/buffge/consistentHash"
"golang.org/x/sync/errgroup"
"log"
"net/http"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
)
var (
errUpstreamNotExist = errors.New("upstream not exist")
)
type Server struct {
c context.Context
cancel context.CancelFunc
httpSrv *http.Server // http 服务
reqTimes atomic.Uint64 // 总请求次数
consistent *consistentHash.ConsistentHash // 轮询一致性
upstreamSet map[string]*Upstream // 后端服务器set
monitorInterval, monitorTimeout time.Duration // 监控间隔,超时时间
monitorFlag atomic.Bool // 监控标记
mu sync.RWMutex // 读写锁 修改后端时使用
}
func NewServer(addr string) *Server {
ctx, cancel := context.WithCancel(context.TODO())
s := &Server{
c: ctx,
cancel: cancel,
consistent: consistentHash.New(),
upstreamSet: make(map[string]*Upstream, 8),
mu: sync.RWMutex{},
monitorInterval: time.Second * 5,
monitorTimeout: time.Second * 5,
}
httpSrv := &http.Server{
Addr: addr,
Handler: s,
}
s.httpSrv = httpSrv
return s
}
// Start 启动服务
func (s *Server) Start() error {
g, c := errgroup.WithContext(s.c)
g.Go(func() error { // http 服务
err := s.httpSrv.ListenAndServe()
return err
})
g.Go(func() error { // 监控服务
return s.Monitor()
})
g.Go(func() error { // 服务平滑关闭
<-c.Done()
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*5)
defer cancel()
err := s.httpSrv.Shutdown(ctx)
return err
})
sigExitC := make(chan os.Signal, 1)
signal.Notify(sigExitC, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
g.Go(func() error { // 等待手动关闭或信号关闭
for {
select {
case <-c.Done():
return c.Err()
case _ = <-sigExitC:
_ = s.Stop()
}
}
})
if err := g.Wait(); err != nil && !errors.Is(err, context.Canceled) {
return err
}
return nil
}
// Stop 停止服务
func (s *Server) Stop() error {
s.cancel()
return nil
}
func (s *Server) AddUpstream(baseUrl string) error {
u, err := NewUpstream(baseUrl)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if err = s.consistent.AddNode(u); err != nil {
return err
}
s.upstreamSet[baseUrl] = u
return nil
}
func (s *Server) RemoveUpstream(baseUrl string) error {
u, exist := s.upstreamSet[baseUrl]
if !exist {
return errUpstreamNotExist
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.upstreamSet, baseUrl)
s.consistent.RemoveNode(u.Key())
return nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.reqTimes.Add(1)
t := s.reqTimes.Load()
u := s.consistent.GetNode(u642bytes(t))
if u == nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
upstream := u.(*Upstream)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*30)
defer cancel()
req := r.Clone(r.Context()).WithContext(ctx)
upstream.Proxy(w, req)
}
// Monitor 监控
func (s *Server) Monitor() error {
defer func() {
if r := recover(); r != nil {
log.Println("monitor recover", r)
}
}()
for {
select {
case <-s.c.Done():
return nil
default:
}
time.Sleep(s.monitorInterval)
if !s.monitorFlag.CompareAndSwap(false, true) {
continue
}
c, cancel := context.WithTimeout(s.c, s.monitorTimeout)
g, ctx := errgroup.WithContext(c)
upstreams := make([]*Upstream, 0, len(s.upstreamSet))
s.mu.RLock()
for _, upstream := range s.upstreamSet {
upstreams = append(upstreams, upstream)
}
s.mu.RUnlock()
for _, v := range upstreams {
upstream := v
g.Go(func() (innerErr error) {
defer func() {
if r := recover(); r != nil {
innerErr = errors.New(fmt.Sprint(r))
return
}
}()
if err := upstream.LiveCheck(ctx); err != nil {
if upstream.disabled {
return
}
upstream.disabled = true
log.Println("upstream live check failed,removed", string(upstream.Key()), err)
s.consistent.RemoveNode(upstream.Key())
return
}
if upstream.disabled {
log.Println("upstream live check success,enabled", string(upstream.Key()))
upstream.disabled = false
_ = s.consistent.AddNode(upstream)
}
return
})
}
if err := g.Wait(); err != nil {
log.Println("monitor errGroup recover", err)
}
s.monitorFlag.Store(false)
cancel()
}
}
func u642bytes(val uint64) []byte {
return binary.LittleEndian.AppendUint64(make([]byte, 0, 8), val)
}