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
15package rafthttp
16
17import (
18	"bytes"
19	"context"
20	"io"
21	"io/ioutil"
22	"net/http"
23	"time"
24
25	"github.com/coreos/etcd/pkg/httputil"
26	pioutil "github.com/coreos/etcd/pkg/ioutil"
27	"github.com/coreos/etcd/pkg/types"
28	"github.com/coreos/etcd/raft"
29	"github.com/coreos/etcd/snap"
30)
31
32var (
33	// timeout for reading snapshot response body
34	snapResponseReadTimeout = 5 * time.Second
35)
36
37type snapshotSender struct {
38	from, to types.ID
39	cid      types.ID
40
41	tr     *Transport
42	picker *urlPicker
43	status *peerStatus
44	r      Raft
45	errorc chan error
46
47	stopc chan struct{}
48}
49
50func newSnapshotSender(tr *Transport, picker *urlPicker, to types.ID, status *peerStatus) *snapshotSender {
51	return &snapshotSender{
52		from:   tr.ID,
53		to:     to,
54		cid:    tr.ClusterID,
55		tr:     tr,
56		picker: picker,
57		status: status,
58		r:      tr.Raft,
59		errorc: tr.ErrorC,
60		stopc:  make(chan struct{}),
61	}
62}
63
64func (s *snapshotSender) stop() { close(s.stopc) }
65
66func (s *snapshotSender) send(merged snap.Message) {
67	start := time.Now()
68
69	m := merged.Message
70	to := types.ID(m.To).String()
71
72	body := createSnapBody(merged)
73	defer body.Close()
74
75	u := s.picker.pick()
76	req := createPostRequest(u, RaftSnapshotPrefix, body, "application/octet-stream", s.tr.URLs, s.from, s.cid)
77
78	plog.Infof("start to send database snapshot [index: %d, to %s]...", m.Snapshot.Metadata.Index, types.ID(m.To))
79
80	err := s.post(req)
81	defer merged.CloseWithError(err)
82	if err != nil {
83		plog.Warningf("database snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
84
85		// errMemberRemoved is a critical error since a removed member should
86		// always be stopped. So we use reportCriticalError to report it to errorc.
87		if err == errMemberRemoved {
88			reportCriticalError(err, s.errorc)
89		}
90
91		s.picker.unreachable(u)
92		s.status.deactivate(failureType{source: sendSnap, action: "post"}, err.Error())
93		s.r.ReportUnreachable(m.To)
94		// report SnapshotFailure to raft state machine. After raft state
95		// machine knows about it, it would pause a while and retry sending
96		// new snapshot message.
97		s.r.ReportSnapshot(m.To, raft.SnapshotFailure)
98		sentFailures.WithLabelValues(to).Inc()
99		snapshotSendFailures.WithLabelValues(to).Inc()
100		return
101	}
102	s.status.activate()
103	s.r.ReportSnapshot(m.To, raft.SnapshotFinish)
104	plog.Infof("database snapshot [index: %d, to: %s] sent out successfully", m.Snapshot.Metadata.Index, types.ID(m.To))
105
106	sentBytes.WithLabelValues(to).Add(float64(merged.TotalSize))
107
108	snapshotSend.WithLabelValues(to).Inc()
109	snapshotSendSeconds.WithLabelValues(to).Observe(time.Since(start).Seconds())
110}
111
112// post posts the given request.
113// It returns nil when request is sent out and processed successfully.
114func (s *snapshotSender) post(req *http.Request) (err error) {
115	ctx, cancel := context.WithCancel(context.Background())
116	req = req.WithContext(ctx)
117	defer cancel()
118
119	type responseAndError struct {
120		resp *http.Response
121		body []byte
122		err  error
123	}
124	result := make(chan responseAndError, 1)
125
126	go func() {
127		resp, err := s.tr.pipelineRt.RoundTrip(req)
128		if err != nil {
129			result <- responseAndError{resp, nil, err}
130			return
131		}
132
133		// close the response body when timeouts.
134		// prevents from reading the body forever when the other side dies right after
135		// successfully receives the request body.
136		time.AfterFunc(snapResponseReadTimeout, func() { httputil.GracefulClose(resp) })
137		body, err := ioutil.ReadAll(resp.Body)
138		result <- responseAndError{resp, body, err}
139	}()
140
141	select {
142	case <-s.stopc:
143		return errStopped
144	case r := <-result:
145		if r.err != nil {
146			return r.err
147		}
148		return checkPostResponse(r.resp, r.body, req, s.to)
149	}
150}
151
152func createSnapBody(merged snap.Message) io.ReadCloser {
153	buf := new(bytes.Buffer)
154	enc := &messageEncoder{w: buf}
155	// encode raft message
156	if err := enc.encode(&merged.Message); err != nil {
157		plog.Panicf("encode message error (%v)", err)
158	}
159
160	return &pioutil.ReaderAndCloser{
161		Reader: io.MultiReader(buf, merged.ReadCloser),
162		Closer: merged.ReadCloser,
163	}
164}
165