| 1 |
// Copyright 2015 The etcd Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package rafthttp |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"net/http" |
| 20 |
"sync" |
| 21 |
"time" |
| 22 |
|
| 23 |
"github.com/coreos/etcd/etcdserver/stats" |
| 24 |
"github.com/coreos/etcd/pkg/logutil" |
| 25 |
"github.com/coreos/etcd/pkg/transport" |
| 26 |
"github.com/coreos/etcd/pkg/types" |
| 27 |
"github.com/coreos/etcd/raft" |
| 28 |
"github.com/coreos/etcd/raft/raftpb" |
| 29 |
"github.com/coreos/etcd/snap" |
| 30 |
|
| 31 |
"github.com/coreos/pkg/capnslog" |
| 32 |
"github.com/xiang90/probing" |
| 33 |
"golang.org/x/time/rate" |
| 34 |
) |
| 35 |
|
| 36 |
var plog = logutil.NewMergeLogger(capnslog.NewPackageLogger("github.com/coreos/etcd", "rafthttp")) |
| 37 |
|
| 38 |
type Raft interface { |
| 39 |
Process(ctx context.Context, m raftpb.Message) error |
| 40 |
IsIDRemoved(id uint64) bool |
| 41 |
ReportUnreachable(id uint64) |
| 42 |
ReportSnapshot(id uint64, status raft.SnapshotStatus) |
| 43 |
} |
| 44 |
|
| 45 |
type Transporter interface { |
| 46 |
// Start starts the given Transporter. |
| 47 |
// Start MUST be called before calling other functions in the interface. |
| 48 |
Start() error |
| 49 |
// Handler returns the HTTP handler of the transporter. |
| 50 |
// A transporter HTTP handler handles the HTTP requests |
| 51 |
// from remote peers. |
| 52 |
// The handler MUST be used to handle RaftPrefix(/raft) |
| 53 |
// endpoint. |
| 54 |
Handler() http.Handler |
| 55 |
// Send sends out the given messages to the remote peers. |
| 56 |
// Each message has a To field, which is an id that maps |
| 57 |
// to an existing peer in the transport. |
| 58 |
// If the id cannot be found in the transport, the message |
| 59 |
// will be ignored. |
| 60 |
Send(m []raftpb.Message) |
| 61 |
// SendSnapshot sends out the given snapshot message to a remote peer. |
| 62 |
// The behavior of SendSnapshot is similar to Send. |
| 63 |
SendSnapshot(m snap.Message) |
| 64 |
// AddRemote adds a remote with given peer urls into the transport. |
| 65 |
// A remote helps newly joined member to catch up the progress of cluster, |
| 66 |
// and will not be used after that. |
| 67 |
// It is the caller's responsibility to ensure the urls are all valid, |
| 68 |
// or it panics. |
| 69 |
AddRemote(id types.ID, urls []string) |
| 70 |
// AddPeer adds a peer with given peer urls into the transport. |
| 71 |
// It is the caller's responsibility to ensure the urls are all valid, |
| 72 |
// or it panics. |
| 73 |
// Peer urls are used to connect to the remote peer. |
| 74 |
AddPeer(id types.ID, urls []string) |
| 75 |
// RemovePeer removes the peer with given id. |
| 76 |
RemovePeer(id types.ID) |
| 77 |
// RemoveAllPeers removes all the existing peers in the transport. |
| 78 |
RemoveAllPeers() |
| 79 |
// UpdatePeer updates the peer urls of the peer with the given id. |
| 80 |
// It is the caller's responsibility to ensure the urls are all valid, |
| 81 |
// or it panics. |
| 82 |
UpdatePeer(id types.ID, urls []string) |
| 83 |
// ActiveSince returns the time that the connection with the peer |
| 84 |
// of the given id becomes active. |
| 85 |
// If the connection is active since peer was added, it returns the adding time. |
| 86 |
// If the connection is currently inactive, it returns zero time. |
| 87 |
ActiveSince(id types.ID) time.Time |
| 88 |
// ActivePeers returns the number of active peers. |
| 89 |
ActivePeers() int |
| 90 |
// Stop closes the connections and stops the transporter. |
| 91 |
Stop() |
| 92 |
} |
| 93 |
|
| 94 |
// Transport implements Transporter interface. It provides the functionality |
| 95 |
// to send raft messages to peers, and receive raft messages from peers. |
| 96 |
// User should call Handler method to get a handler to serve requests |
| 97 |
// received from peerURLs. |
| 98 |
// User needs to call Start before calling other functions, and call |
| 99 |
// Stop when the Transport is no longer used. |
| 100 |
type Transport struct { |
| 101 |
DialTimeout time.Duration // maximum duration before timing out dial of the request |
| 102 |
// DialRetryFrequency defines the frequency of streamReader dial retrial attempts; |
| 103 |
// a distinct rate limiter is created per every peer (default value: 10 events/sec) |
| 104 |
DialRetryFrequency rate.Limit |
| 105 |
|
| 106 |
TLSInfo transport.TLSInfo // TLS information used when creating connection |
| 107 |
|
| 108 |
ID types.ID // local member ID |
| 109 |
URLs types.URLs // local peer URLs |
| 110 |
ClusterID types.ID // raft cluster ID for request validation |
| 111 |
Raft Raft // raft state machine, to which the Transport forwards received messages and reports status |
| 112 |
Snapshotter *snap.Snapshotter |
| 113 |
ServerStats *stats.ServerStats // used to record general transportation statistics |
| 114 |
// used to record transportation statistics with followers when |
| 115 |
// performing as leader in raft protocol |
| 116 |
LeaderStats *stats.LeaderStats |
| 117 |
// ErrorC is used to report detected critical errors, e.g., |
| 118 |
// the member has been permanently removed from the cluster |
| 119 |
// When an error is received from ErrorC, user should stop raft state |
| 120 |
// machine and thus stop the Transport. |
| 121 |
ErrorC chan error |
| 122 |
|
| 123 |
streamRt http.RoundTripper // roundTripper used by streams |
| 124 |
pipelineRt http.RoundTripper // roundTripper used by pipelines |
| 125 |
|
| 126 |
mu sync.RWMutex // protect the remote and peer map |
| 127 |
remotes map[types.ID]*remote // remotes map that helps newly joined member to catch up |
| 128 |
peers map[types.ID]Peer // peers map |
| 129 |
|
| 130 |
prober probing.Prober |
| 131 |
} |
| 132 |
|
| 133 |
func (t *Transport) Start() error { |
| 134 |
var err error |
| 135 |
t.streamRt, err = newStreamRoundTripper(t.TLSInfo, t.DialTimeout) |
| 136 |
if err != nil { |
| 137 |
return err |
| 138 |
} |
| 139 |
t.pipelineRt, err = NewRoundTripper(t.TLSInfo, t.DialTimeout) |
| 140 |
if err != nil { |
| 141 |
return err |
| 142 |
} |
| 143 |
t.remotes = make(map[types.ID]*remote) |
| 144 |
t.peers = make(map[types.ID]Peer) |
| 145 |
t.prober = probing.NewProber(t.pipelineRt) |
| 146 |
|
| 147 |
// If client didn't provide dial retry frequency, use the default |
| 148 |
// (100ms backoff between attempts to create a new stream), |
| 149 |
// so it doesn't bring too much overhead when retry. |
| 150 |
if t.DialRetryFrequency == 0 { |
| 151 |
t.DialRetryFrequency = rate.Every(100 * time.Millisecond) |
| 152 |
} |
| 153 |
return nil |
| 154 |
} |
| 155 |
|
| 156 |
func (t *Transport) Handler() http.Handler { |
| 157 |
pipelineHandler := newPipelineHandler(t, t.Raft, t.ClusterID) |
| 158 |
streamHandler := newStreamHandler(t, t, t.Raft, t.ID, t.ClusterID) |
| 159 |
snapHandler := newSnapshotHandler(t, t.Raft, t.Snapshotter, t.ClusterID) |
| 160 |
mux := http.NewServeMux() |
| 161 |
mux.Handle(RaftPrefix, pipelineHandler) |
| 162 |
mux.Handle(RaftStreamPrefix+"/", streamHandler) |
| 163 |
mux.Handle(RaftSnapshotPrefix, snapHandler) |
| 164 |
mux.Handle(ProbingPrefix, probing.NewHandler()) |
| 165 |
return mux |
| 166 |
} |
| 167 |
|
| 168 |
func (t *Transport) Get(id types.ID) Peer { |
| 169 |
t.mu.RLock() |
| 170 |
defer t.mu.RUnlock() |
| 171 |
return t.peers[id] |
| 172 |
} |
| 173 |
|
| 174 |
func (t *Transport) Send(msgs []raftpb.Message) { |
| 175 |
for _, m := range msgs { |
| 176 |
if m.To == 0 { |
| 177 |
// ignore intentionally dropped message |
| 178 |
continue |
| 179 |
} |
| 180 |
to := types.ID(m.To) |
| 181 |
|
| 182 |
t.mu.RLock() |
| 183 |
p, pok := t.peers[to] |
| 184 |
g, rok := t.remotes[to] |
| 185 |
t.mu.RUnlock() |
| 186 |
|
| 187 |
if pok { |
| 188 |
if m.Type == raftpb.MsgApp { |
| 189 |
t.ServerStats.SendAppendReq(m.Size()) |
| 190 |
} |
| 191 |
p.send(m) |
| 192 |
continue |
| 193 |
} |
| 194 |
|
| 195 |
if rok { |
| 196 |
g.send(m) |
| 197 |
continue |
| 198 |
} |
| 199 |
|
| 200 |
plog.Debugf("ignored message %s (sent to unknown peer %s)", m.Type, to) |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
func (t *Transport) Stop() { |
| 205 |
t.mu.Lock() |
| 206 |
defer t.mu.Unlock() |
| 207 |
for _, r := range t.remotes { |
| 208 |
r.stop() |
| 209 |
} |
| 210 |
for _, p := range t.peers { |
| 211 |
p.stop() |
| 212 |
} |
| 213 |
t.prober.RemoveAll() |
| 214 |
if tr, ok := t.streamRt.(*http.Transport); ok { |
| 215 |
tr.CloseIdleConnections() |
| 216 |
} |
| 217 |
if tr, ok := t.pipelineRt.(*http.Transport); ok { |
| 218 |
tr.CloseIdleConnections() |
| 219 |
} |
| 220 |
t.peers = nil |
| 221 |
t.remotes = nil |
| 222 |
} |
| 223 |
|
| 224 |
// CutPeer drops messages to the specified peer. |
| 225 |
func (t *Transport) CutPeer(id types.ID) { |
| 226 |
t.mu.RLock() |
| 227 |
p, pok := t.peers[id] |
| 228 |
g, gok := t.remotes[id] |
| 229 |
t.mu.RUnlock() |
| 230 |
|
| 231 |
if pok { |
| 232 |
p.(Pausable).Pause() |
| 233 |
} |
| 234 |
if gok { |
| 235 |
g.Pause() |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
// MendPeer recovers the message dropping behavior of the given peer. |
| 240 |
func (t *Transport) MendPeer(id types.ID) { |
| 241 |
t.mu.RLock() |
| 242 |
p, pok := t.peers[id] |
| 243 |
g, gok := t.remotes[id] |
| 244 |
t.mu.RUnlock() |
| 245 |
|
| 246 |
if pok { |
| 247 |
p.(Pausable).Resume() |
| 248 |
} |
| 249 |
if gok { |
| 250 |
g.Resume() |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
func (t *Transport) AddRemote(id types.ID, us []string) { |
| 255 |
t.mu.Lock() |
| 256 |
defer t.mu.Unlock() |
| 257 |
if t.remotes == nil { |
| 258 |
// there's no clean way to shutdown the golang http server |
| 259 |
// (see: https://github.com/golang/go/issues/4674) before |
| 260 |
// stopping the transport; ignore any new connections. |
| 261 |
return |
| 262 |
} |
| 263 |
if _, ok := t.peers[id]; ok { |
| 264 |
return |
| 265 |
} |
| 266 |
if _, ok := t.remotes[id]; ok { |
| 267 |
return |
| 268 |
} |
| 269 |
urls, err := types.NewURLs(us) |
| 270 |
if err != nil { |
| 271 |
plog.Panicf("newURLs %+v should never fail: %+v", us, err) |
| 272 |
} |
| 273 |
t.remotes[id] = startRemote(t, urls, id) |
| 274 |
} |
| 275 |
|
| 276 |
func (t *Transport) AddPeer(id types.ID, us []string) { |
| 277 |
t.mu.Lock() |
| 278 |
defer t.mu.Unlock() |
| 279 |
|
| 280 |
if t.peers == nil { |
| 281 |
panic("transport stopped") |
| 282 |
} |
| 283 |
if _, ok := t.peers[id]; ok { |
| 284 |
return |
| 285 |
} |
| 286 |
urls, err := types.NewURLs(us) |
| 287 |
if err != nil { |
| 288 |
plog.Panicf("newURLs %+v should never fail: %+v", us, err) |
| 289 |
} |
| 290 |
fs := t.LeaderStats.Follower(id.String()) |
| 291 |
t.peers[id] = startPeer(t, urls, id, fs) |
| 292 |
addPeerToProber(t.prober, id.String(), us) |
| 293 |
|
| 294 |
plog.Infof("added peer %s", id) |
| 295 |
} |
| 296 |
|
| 297 |
func (t *Transport) RemovePeer(id types.ID) { |
| 298 |
t.mu.Lock() |
| 299 |
defer t.mu.Unlock() |
| 300 |
t.removePeer(id) |
| 301 |
} |
| 302 |
|
| 303 |
func (t *Transport) RemoveAllPeers() { |
| 304 |
t.mu.Lock() |
| 305 |
defer t.mu.Unlock() |
| 306 |
for id := range t.peers { |
| 307 |
t.removePeer(id) |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
// the caller of this function must have the peers mutex. |
| 312 |
func (t *Transport) removePeer(id types.ID) { |
| 313 |
if peer, ok := t.peers[id]; ok { |
| 314 |
peer.stop() |
| 315 |
} else { |
| 316 |
plog.Panicf("unexpected removal of unknown peer '%d'", id) |
| 317 |
} |
| 318 |
delete(t.peers, id) |
| 319 |
delete(t.LeaderStats.Followers, id.String()) |
| 320 |
t.prober.Remove(id.String()) |
| 321 |
plog.Infof("removed peer %s", id) |
| 322 |
} |
| 323 |
|
| 324 |
func (t *Transport) UpdatePeer(id types.ID, us []string) { |
| 325 |
t.mu.Lock() |
| 326 |
defer t.mu.Unlock() |
| 327 |
// TODO: return error or just panic? |
| 328 |
if _, ok := t.peers[id]; !ok { |
| 329 |
return |
| 330 |
} |
| 331 |
urls, err := types.NewURLs(us) |
| 332 |
if err != nil { |
| 333 |
plog.Panicf("newURLs %+v should never fail: %+v", us, err) |
| 334 |
} |
| 335 |
t.peers[id].update(urls) |
| 336 |
|
| 337 |
t.prober.Remove(id.String()) |
| 338 |
addPeerToProber(t.prober, id.String(), us) |
| 339 |
plog.Infof("updated peer %s", id) |
| 340 |
} |
| 341 |
|
| 342 |
func (t *Transport) ActiveSince(id types.ID) time.Time { |
| 343 |
t.mu.Lock() |
| 344 |
defer t.mu.Unlock() |
| 345 |
if p, ok := t.peers[id]; ok { |
| 346 |
return p.activeSince() |
| 347 |
} |
| 348 |
return time.Time{} |
| 349 |
} |
| 350 |
|
| 351 |
func (t *Transport) SendSnapshot(m snap.Message) { |
| 352 |
t.mu.Lock() |
| 353 |
defer t.mu.Unlock() |
| 354 |
p := t.peers[types.ID(m.To)] |
| 355 |
if p == nil { |
| 356 |
m.CloseWithError(errMemberNotFound) |
| 357 |
return |
| 358 |
} |
| 359 |
p.sendSnap(m) |
| 360 |
} |
| 361 |
|
| 362 |
// Pausable is a testing interface for pausing transport traffic. |
| 363 |
type Pausable interface { |
| 364 |
Pause() |
| 365 |
Resume() |
| 366 |
} |
| 367 |
|
| 368 |
func (t *Transport) Pause() { |
| 369 |
for _, p := range t.peers { |
| 370 |
p.(Pausable).Pause() |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
func (t *Transport) Resume() { |
| 375 |
for _, p := range t.peers { |
| 376 |
p.(Pausable).Resume() |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
// ActivePeers returns a channel that closes when an initial |
| 381 |
// peer connection has been established. Use this to wait until the |
| 382 |
// first peer connection becomes active. |
| 383 |
func (t *Transport) ActivePeers() (cnt int) { |
| 384 |
t.mu.RLock() |
| 385 |
defer t.mu.RUnlock() |
| 386 |
for _, p := range t.peers { |
| 387 |
if !p.activeSince().IsZero() { |
| 388 |
cnt++ |
| 389 |
} |
| 390 |
} |
| 391 |
return cnt |
| 392 |
} |
| 393 |
|
| 394 |
type nopTransporter struct{} |
| 395 |
|
| 396 |
func NewNopTransporter() Transporter { |
| 397 |
return &nopTransporter{} |
| 398 |
} |
| 399 |
|
| 400 |
func (s *nopTransporter) Start() error { return nil } |
| 401 |
func (s *nopTransporter) Handler() http.Handler { return nil } |
| 402 |
func (s *nopTransporter) Send(m []raftpb.Message) {} |
| 403 |
func (s *nopTransporter) SendSnapshot(m snap.Message) {} |
| 404 |
func (s *nopTransporter) AddRemote(id types.ID, us []string) {} |
| 405 |
func (s *nopTransporter) AddPeer(id types.ID, us []string) {} |
| 406 |
func (s *nopTransporter) RemovePeer(id types.ID) {} |
| 407 |
func (s *nopTransporter) RemoveAllPeers() {} |
| 408 |
func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {} |
| 409 |
func (s *nopTransporter) ActiveSince(id types.ID) time.Time { return time.Time{} } |
| 410 |
func (s *nopTransporter) ActivePeers() int { return 0 } |
| 411 |
func (s *nopTransporter) Stop() {} |
| 412 |
func (s *nopTransporter) Pause() {} |
| 413 |
func (s *nopTransporter) Resume() {} |
| 414 |
|
| 415 |
type snapTransporter struct { |
| 416 |
nopTransporter |
| 417 |
snapDoneC chan snap.Message |
| 418 |
snapDir string |
| 419 |
} |
| 420 |
|
| 421 |
func NewSnapTransporter(snapDir string) (Transporter, <-chan snap.Message) { |
| 422 |
ch := make(chan snap.Message, 1) |
| 423 |
tr := &snapTransporter{snapDoneC: ch, snapDir: snapDir} |
| 424 |
return tr, ch |
| 425 |
} |
| 426 |
|
| 427 |
func (s *snapTransporter) SendSnapshot(m snap.Message) { |
| 428 |
ss := snap.New(s.snapDir) |
| 429 |
ss.SaveDBFrom(m.ReadCloser, m.Snapshot.Metadata.Index+1) |
| 430 |
m.CloseWithError(nil) |
| 431 |
s.snapDoneC <- m |
| 432 |
} |