-
Notifications
You must be signed in to change notification settings - Fork 155
/
fetcher.go
188 lines (169 loc) · 6.03 KB
/
fetcher.go
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
// Copyright 2019 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package segfetcher
import (
"context"
"math/rand"
"net"
"time"
"github.com/scionproto/scion/pkg/log"
"github.com/scionproto/scion/pkg/private/serrors"
seg "github.com/scionproto/scion/pkg/segment"
"github.com/scionproto/scion/private/pathdb"
"github.com/scionproto/scion/private/segment/segfetcher/internal/metrics"
"github.com/scionproto/scion/private/segment/seghandler"
)
const (
minQueryInterval = 2 * time.Second
expirationLeadTime = 2 * time.Minute
)
// errors for metrics classification.
var (
errFetch = serrors.New("fetching failed")
errDB = serrors.New("error with the db")
)
// ReplyHandler handles replies.
type ReplyHandler interface {
Handle(ctx context.Context, recs seghandler.Segments,
server net.Addr) *seghandler.ProcessedResult
}
// NewFetcherMetrics exposes the metrics constructor.
//
// XXX(roosd): This should be translated to the new metrics approach.
func NewFetcherMetrics(ns string) metrics.Fetcher {
return metrics.NewFetcher(ns)
}
// Fetcher fetches, verifies and stores segments for a path segment request.
type Fetcher struct {
Resolver Resolver
Requester Requester
ReplyHandler ReplyHandler
PathDB pathdb.DB
// QueryInterval specifies after how much time segments should be
// refetched at the remote server.
QueryInterval time.Duration
Metrics metrics.Fetcher
}
// Fetch loads the requested segments from the path DB or requests them from a remote path server.
func (f *Fetcher) Fetch(ctx context.Context, reqs Requests, refresh bool) (Segments, error) {
// Load local and cached segments from DB
loadedSegs, fetchReqs, err := f.Resolver.Resolve(ctx, reqs, refresh)
if err != nil {
return Segments{}, serrors.Wrap(errDB, err)
}
if len(fetchReqs) == 0 {
return loadedSegs, nil
}
// Forward and cache any requests that were not local / cached
fetchedSegs, err := f.Request(ctx, fetchReqs)
if err != nil {
err = serrors.Wrap(errFetch, err)
}
return append(loadedSegs, fetchedSegs...), err
}
func (f *Fetcher) Request(ctx context.Context, reqs Requests) (Segments, error) {
// Pass shorter context for requesting, such that we can reply even if a
// request hangs.
earlyCtx, cancel := earlyContext(ctx, 500*time.Millisecond)
defer cancel()
replies := f.Requester.Request(earlyCtx, reqs)
return f.waitOnProcessed(ctx, replies)
}
func (f *Fetcher) waitOnProcessed(ctx context.Context,
replies <-chan ReplyOrErr) (Segments, error) {
var segs Segments
logger := log.FromCtx(ctx)
for reply := range replies {
// TODO(lukedirtwalker): Should we do this in go routines?
labels := metrics.RequestLabels{Result: metrics.ErrNotClassified}
if reply.Err != nil {
if serrors.IsTimeout(reply.Err) {
labels.Result = metrics.ErrTimeout
}
f.Metrics.SegRequests(labels).Inc()
continue
}
if len(reply.Segments) == 0 {
f.Metrics.SegRequests(labels.WithResult(metrics.OkSuccess)).Inc()
continue
}
r := f.ReplyHandler.Handle(ctx, replyToRecs(reply.Segments), reply.Peer)
if err := r.Err(); err != nil {
f.Metrics.SegRequests(labels.WithResult(metrics.ErrProcess)).Inc()
return segs, serrors.WrapStr("processing reply", err)
}
if len(r.VerificationErrors()) > 0 {
log.FromCtx(ctx).Info("Errors during verification of segments/revocations",
"number", len(r.VerificationErrors()))
log.FromCtx(ctx).Debug("Error during verification of segments/revocations",
"errors", r.VerificationErrors().ToError())
}
segs = append(segs, Segments(r.Stats().VerifiedSegs)...)
nextQuery := f.nextQuery(segs)
_, err := f.PathDB.InsertNextQuery(ctx, reply.Req.Src, reply.Req.Dst, nextQuery)
if err != nil {
logger.Info("NextQuery insertion failed", "err", err)
}
f.Metrics.SegRequests(labels.WithResult(metrics.OkSuccess)).Inc()
}
return segs, nil
}
// nextQuery decides the next time a query should be issued based on the
// received segments.
func (f *Fetcher) nextQuery(segs Segments) time.Time {
// Determine the lead time for the latest segment expiration.
// We want to request new segments before the last one has expired.
expirationLead := maxSegmentExpiry(segs).Add(-expirationLeadTime)
return f.nearestNextQueryTime(time.Now(), expirationLead)
}
// nearestNextQueryTime finds the nearest next query time in the interval spanned
// by the minimum and the configured query interval.
func (f *Fetcher) nearestNextQueryTime(now, nextQuery time.Time) time.Time {
// Adding +-10% random jitter
jitterPercent := time.Duration(rand.Intn(20) - 10)
if earliest := now.Add(minQueryInterval); nextQuery.Before(earliest) {
jitter := minQueryInterval * jitterPercent / 100
return earliest.Add(jitter)
}
if latest := now.Add(f.QueryInterval); nextQuery.After(latest) {
jitter := f.QueryInterval * jitterPercent / 100
return latest.Add(jitter)
}
return nextQuery
}
func earlyContext(ctx context.Context, leadTime time.Duration) (context.Context, func()) {
if deadline, ok := ctx.Deadline(); ok {
// Only use early deadline if it is satisfiable and far enough in the
// future. Cutting the request time too short is worse than timing
// out during verification.
if withLead := deadline.Add(-leadTime); time.Until(withLead) > leadTime {
return context.WithDeadline(ctx, withLead)
}
}
return ctx, func() {}
}
func maxSegmentExpiry(segs Segments) time.Time {
var max time.Time
for _, seg := range segs {
if exp := seg.Segment.MinExpiry(); exp.After(max) {
max = exp
}
}
return max
}
func replyToRecs(reply []*seg.Meta) seghandler.Segments {
return seghandler.Segments{
Segs: reply,
}
}