-
Notifications
You must be signed in to change notification settings - Fork 453
/
common.go
441 lines (390 loc) · 14.2 KB
/
common.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package placement
import (
"errors"
"fmt"
"net/http"
"path"
"strings"
"time"
clusterclient "github.com/m3db/m3/src/cluster/client"
"github.com/m3db/m3/src/cluster/generated/proto/placementpb"
"github.com/m3db/m3/src/cluster/placement"
"github.com/m3db/m3/src/cluster/placement/algo"
"github.com/m3db/m3/src/cluster/services"
"github.com/m3db/m3/src/cluster/shard"
"github.com/m3db/m3/src/cmd/services/m3query/config"
"github.com/m3db/m3/src/query/api/v1/handler"
"github.com/m3db/m3/src/query/util/logging"
xhttp "github.com/m3db/m3/src/x/net/http"
"github.com/gorilla/mux"
)
const (
// ServicesPathName is the services part of the API path.
ServicesPathName = "services"
// PlacementPathName is the placement part of the API path.
PlacementPathName = "placement"
m3AggregatorPlacementNamespace = "/placement"
)
var (
// M3DBServicePlacementPathName is the M3DB service placement API path.
M3DBServicePlacementPathName = path.Join(ServicesPathName, handler.M3DBServiceName, PlacementPathName)
// M3AggServicePlacementPathName is the M3Agg service placement API path.
M3AggServicePlacementPathName = path.Join(ServicesPathName, handler.M3AggregatorServiceName, PlacementPathName)
// M3CoordinatorServicePlacementPathName is the M3Coordinator service placement API path.
M3CoordinatorServicePlacementPathName = path.Join(ServicesPathName, handler.M3CoordinatorServiceName, PlacementPathName)
errUnableToParseService = errors.New("unable to parse service")
)
// HandlerOptions is the options struct for the handler.
type HandlerOptions struct {
// This is used by other placement Handlers
// nolint: structcheck
ClusterClient clusterclient.Client
Config config.Configuration
M3AggServiceOptions *handler.M3AggServiceOptions
}
// NewHandlerOptions is the constructor function for HandlerOptions.
func NewHandlerOptions(
client clusterclient.Client,
cfg config.Configuration,
m3AggOpts *handler.M3AggServiceOptions,
) HandlerOptions {
return HandlerOptions{
ClusterClient: client,
Config: cfg,
M3AggServiceOptions: m3AggOpts,
}
}
// Handler represents a generic handler for placement endpoints.
type Handler struct {
HandlerOptions
// nolint: structcheck
nowFn func() time.Time
}
// Service gets a placement service from m3cluster client
func Service(
clusterClient clusterclient.Client,
opts handler.ServiceOptions,
now time.Time,
validationFn placement.ValidateFn,
) (placement.Service, error) {
ps, _, err := ServiceWithAlgo(clusterClient, opts, now, validationFn)
return ps, err
}
// ServiceWithAlgo gets a placement service from m3cluster client and
// additionally returns an algorithm instance for callers that need fine-grained
// control over placement updates.
func ServiceWithAlgo(
clusterClient clusterclient.Client,
opts handler.ServiceOptions,
now time.Time,
validationFn placement.ValidateFn,
) (placement.Service, placement.Algorithm, error) {
overrides := services.NewOverrideOptions()
switch opts.ServiceName {
case handler.M3AggregatorServiceName:
overrides = overrides.
SetNamespaceOptions(
overrides.NamespaceOptions().
SetPlacementNamespace(m3AggregatorPlacementNamespace),
)
}
cs, err := clusterClient.Services(overrides)
if err != nil {
return nil, nil, err
}
if err := opts.Validate(); err != nil {
return nil, nil, err
}
if !handler.IsAllowedService(opts.ServiceName) {
return nil, nil, fmt.Errorf(
"invalid service name: %s, must be one of: %v",
opts.ServiceName, handler.AllowedServices())
}
sid := opts.ServiceID()
pOpts := placement.NewOptions().
SetValidZone(opts.ServiceZone).
SetIsSharded(true).
SetDryrun(opts.DryRun)
switch opts.ServiceName {
case handler.M3CoordinatorServiceName:
pOpts = pOpts.
SetIsSharded(false)
case handler.M3AggregatorServiceName:
var (
maxAggregationWindowSize = opts.M3Agg.MaxAggregationWindowSize
warmupDuration = opts.M3Agg.WarmupDuration
// For now these are not configurable, but we include them to
// make the code match r2admin for ease of debugging / migration.
placementCutoverOpts = m3aggregatorPlacementOpts{}
)
pOpts = pOpts.
// M3Agg expects a mirrored and staged placement.
SetIsMirrored(true).
SetIsStaged(true).
// placementCutover controls when the new placement will begin to be considered
// the new placement. Since we're trying to do goal-based placement, we set it
// such that it takes effect immediately.
SetPlacementCutoverNanosFn(newPlacementCutoverNanosFn(
now, placementCutoverOpts)).
// shardCutover controls when the clients (who have received the new placement)
// will begin dual-writing to the new shards. We could set it to take effect
// immediately, but right now we use the same logic as r2admin for consistency.
SetShardCutoverNanosFn(newShardCutoverNanosFn(
now, maxAggregationWindowSize, warmupDuration, placementCutoverOpts)).
// Cutoffs control when Leaving shards stop receiving writes.
SetShardCutoffNanosFn(newShardCutOffNanosFn(
now, maxAggregationWindowSize, warmupDuration, placementCutoverOpts)).
SetIsShardCutoverFn(newShardCutOverValidationFn(now)).
SetIsShardCutoffFn(newShardCutOffValidationFn(now, maxAggregationWindowSize))
}
if validationFn != nil {
pOpts = pOpts.SetValidateFnBeforeUpdate(validationFn)
}
ps, err := cs.PlacementService(sid, pOpts)
if err != nil {
return nil, nil, err
}
alg := algo.NewAlgorithm(pOpts)
return ps, alg, nil
}
// ConvertInstancesProto converts a slice of protobuf `Instance`s to `placement.Instance`s
func ConvertInstancesProto(instancesProto []*placementpb.Instance) ([]placement.Instance, error) {
res := make([]placement.Instance, 0, len(instancesProto))
for _, instanceProto := range instancesProto {
shards, err := shard.NewShardsFromProto(instanceProto.Shards)
if err != nil {
return nil, err
}
instance := placement.NewInstance().
SetEndpoint(instanceProto.Endpoint).
SetHostname(instanceProto.Hostname).
SetID(instanceProto.Id).
SetPort(instanceProto.Port).
SetIsolationGroup(instanceProto.IsolationGroup).
SetShards(shards).
SetShardSetID(instanceProto.ShardSetId).
SetWeight(instanceProto.Weight).
SetZone(instanceProto.Zone)
res = append(res, instance)
}
return res, nil
}
// RegisterRoutes registers the placement routes
func RegisterRoutes(r *mux.Router, opts HandlerOptions) {
// Init
var (
initHandler = NewInitHandler(opts)
deprecatedInitFn = applyDeprecatedMiddleware(initHandler.ServeHTTP)
initFn = applyMiddleware(initHandler.ServeHTTP)
)
r.HandleFunc(DeprecatedM3DBInitURL, deprecatedInitFn).Methods(InitHTTPMethod)
r.HandleFunc(M3DBInitURL, initFn).Methods(InitHTTPMethod)
r.HandleFunc(M3AggInitURL, initFn).Methods(InitHTTPMethod)
r.HandleFunc(M3CoordinatorInitURL, initFn).Methods(InitHTTPMethod)
// Get
var (
getHandler = NewGetHandler(opts)
deprecatedGetFn = applyDeprecatedMiddleware(getHandler.ServeHTTP)
getFn = applyMiddleware(getHandler.ServeHTTP)
)
r.HandleFunc(DeprecatedM3DBGetURL, deprecatedGetFn).Methods(GetHTTPMethod)
r.HandleFunc(M3DBGetURL, getFn).Methods(GetHTTPMethod)
r.HandleFunc(M3AggGetURL, getFn).Methods(GetHTTPMethod)
r.HandleFunc(M3CoordinatorGetURL, getFn).Methods(GetHTTPMethod)
// Delete all
var (
deleteAllHandler = NewDeleteAllHandler(opts)
deprecatedDeleteAllFn = applyDeprecatedMiddleware(deleteAllHandler.ServeHTTP)
deleteAllFn = applyMiddleware(deleteAllHandler.ServeHTTP)
)
r.HandleFunc(DeprecatedM3DBDeleteAllURL, deprecatedDeleteAllFn).Methods(DeleteAllHTTPMethod)
r.HandleFunc(M3DBDeleteAllURL, deleteAllFn).Methods(DeleteAllHTTPMethod)
r.HandleFunc(M3AggDeleteAllURL, deleteAllFn).Methods(DeleteAllHTTPMethod)
r.HandleFunc(M3CoordinatorDeleteAllURL, getFn).Methods(GetHTTPMethod)
// Add
var (
addHandler = NewAddHandler(opts)
deprecatedAddFn = applyDeprecatedMiddleware(addHandler.ServeHTTP)
addFn = applyMiddleware(addHandler.ServeHTTP)
)
r.HandleFunc(DeprecatedM3DBAddURL, deprecatedAddFn).Methods(AddHTTPMethod)
r.HandleFunc(M3DBAddURL, addFn).Methods(AddHTTPMethod)
r.HandleFunc(M3AggAddURL, addFn).Methods(AddHTTPMethod)
r.HandleFunc(M3CoordinatorAddURL, getFn).Methods(GetHTTPMethod)
// Delete
var (
deleteHandler = NewDeleteHandler(opts)
deprecatedDeleteFn = applyDeprecatedMiddleware(deleteHandler.ServeHTTP)
deleteFn = applyMiddleware(deleteHandler.ServeHTTP)
)
r.HandleFunc(DeprecatedM3DBDeleteURL, deprecatedDeleteFn).Methods(DeleteHTTPMethod)
r.HandleFunc(M3DBDeleteURL, deleteFn).Methods(DeleteHTTPMethod)
r.HandleFunc(M3AggDeleteURL, deleteFn).Methods(DeleteHTTPMethod)
r.HandleFunc(M3CoordinatorDeleteURL, getFn).Methods(GetHTTPMethod)
// Replace
var (
replaceHandler = NewReplaceHandler(opts)
replaceFn = applyMiddleware(replaceHandler.ServeHTTP)
)
r.HandleFunc(M3DBReplaceURL, replaceFn).Methods(ReplaceHTTPMethod)
r.HandleFunc(M3AggReplaceURL, replaceFn).Methods(ReplaceHTTPMethod)
r.HandleFunc(M3CoordinatorReplaceURL, replaceFn).Methods(ReplaceHTTPMethod)
}
func newPlacementCutoverNanosFn(
now time.Time, cutoverOpts m3aggregatorPlacementOpts) placement.TimeNanosFn {
return func() int64 {
return placementCutoverTime(now, cutoverOpts).UnixNano()
}
}
func placementCutoverTime(
now time.Time, opts m3aggregatorPlacementOpts) time.Time {
return now.
Add(opts.maxPositiveSkew).
Add(opts.maxNegativeSkew).
Add(opts.propagationDelay)
}
func newShardCutOffNanosFn(
now time.Time,
maxAggregationWindowSize,
warmup time.Duration,
cutoverOpts m3aggregatorPlacementOpts) placement.TimeNanosFn {
return newShardCutoverNanosFn(
now, maxAggregationWindowSize, warmup, cutoverOpts)
}
func newShardCutoverNanosFn(
now time.Time,
maxAggregationWindowSize,
warmUpDuration time.Duration,
cutoverOpts m3aggregatorPlacementOpts) placement.TimeNanosFn {
return func() int64 {
var (
windowSize = maxAggregationWindowSize
cutover = placementCutoverTime(now, cutoverOpts).Add(warmUpDuration)
truncated = cutover.Truncate(windowSize)
)
if truncated.Before(cutover) {
return truncated.Add(windowSize).UnixNano()
}
return truncated.UnixNano()
}
}
func newShardCutOverValidationFn(now time.Time) placement.ShardValidateFn {
return func(s shard.Shard) error {
switch s.State() {
case shard.Initializing:
if s.CutoverNanos() > now.UnixNano() {
return fmt.Errorf("could not mark shard %d available before cutover time %v", s.ID(), time.Unix(0, s.CutoverNanos()))
}
return nil
default:
return fmt.Errorf("could not mark shard %d available, invalid state %s", s.ID(), s.State().String())
}
}
}
func newShardCutOffValidationFn(now time.Time, maxAggregationWindowSize time.Duration) placement.ShardValidateFn {
return func(s shard.Shard) error {
switch s.State() {
case shard.Leaving:
if s.CutoffNanos() > now.UnixNano()-maxAggregationWindowSize.Nanoseconds() {
return fmt.Errorf("could not return leaving shard %d with cutoff time %v, max aggregation window %v",
s.ID(), time.Unix(0, s.CutoffNanos()), maxAggregationWindowSize)
}
return nil
default:
return fmt.Errorf("could not mark shard %d available, invalid state %s", s.ID(), s.State().String())
}
}
}
type m3aggregatorPlacementOpts struct {
maxPositiveSkew time.Duration
maxNegativeSkew time.Duration
propagationDelay time.Duration
}
type unsafeAddError struct {
hosts string
}
func (e unsafeAddError) Error() string {
return fmt.Sprintf("instances [%s] do not have all shards available", e.hosts)
}
func validateAllAvailable(p placement.Placement) error {
badInsts := []string{}
for _, inst := range p.Instances() {
if !inst.IsAvailable() {
badInsts = append(badInsts, inst.ID())
}
}
if len(badInsts) > 0 {
return unsafeAddError{
hosts: strings.Join(badInsts, ","),
}
}
return nil
}
func applyMiddleware(
f func(serviceName string, w http.ResponseWriter, r *http.Request),
) func(w http.ResponseWriter, r *http.Request) {
return logging.WithResponseTimeAndPanicErrorLoggingFunc(
parseServiceMiddleware(f),
).ServeHTTP
}
func applyDeprecatedMiddleware(
f func(serviceName string, w http.ResponseWriter, r *http.Request),
) func(w http.ResponseWriter, r *http.Request) {
return logging.WithResponseTimeAndPanicErrorLoggingFunc(
func(w http.ResponseWriter, r *http.Request) {
f(handler.M3DBServiceName, w, r)
},
).ServeHTTP
}
func parseServiceMiddleware(
next func(serviceName string, w http.ResponseWriter, r *http.Request),
) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
serviceName, err := parseServiceFromRequest(r)
if err != nil {
xhttp.Error(w, err, http.StatusBadRequest)
return
}
next(serviceName, w, r)
}
}
func parseServiceFromRequest(r *http.Request) (string, error) {
path := r.URL.Path
components := strings.Split(path, "/")
for i, c := range components {
if c == "services" && i+1 < len(components) {
service := components[i+1]
if handler.IsAllowedService(service) {
return service, nil
}
return "", fmt.Errorf("unknown service: %s", service)
}
}
return "", errUnableToParseService
}
func isStateless(serviceName string) bool {
switch serviceName {
case handler.M3CoordinatorServiceName:
return true
}
return false
}