-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
tenant.go
656 lines (592 loc) · 21.7 KB
/
tenant.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"context"
"crypto/tls"
"net/http"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/blobs"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvtenant"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangefeed"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptprovider"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/multitenant/tenantcostmodel"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/debug"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/contention"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/optionalnodeliveness"
"github.com/cockroachdb/cockroach/pkg/sql/sqlinstance"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
)
// StartTenant starts a stand-alone SQL server against a KV backend.
func StartTenant(
ctx context.Context,
stopper *stop.Stopper,
kvClusterName string, // NB: gone after https://github.com/cockroachdb/cockroach/issues/42519
baseCfg BaseConfig,
sqlCfg SQLConfig,
) (sqlServer *SQLServer, pgAddr string, httpAddr string, _ error) {
err := ApplyTenantLicense()
if err != nil {
return nil, "", "", err
}
args, err := makeTenantSQLServerArgs(stopper, kvClusterName, baseCfg, sqlCfg)
if err != nil {
return nil, "", "", err
}
err = args.ValidateAddrs(ctx)
if err != nil {
return nil, "", "", err
}
args.monitorAndMetrics = newRootSQLMemoryMonitor(monitorAndMetricsOptions{
memoryPoolSize: args.MemoryPoolSize,
histogramWindowInterval: args.HistogramWindowInterval(),
settings: args.Settings,
})
connManager := netutil.MakeServer(
args.stopper,
// The SQL server only uses connManager.ServeWith. The both below
// are unused.
nil, // tlsConfig
nil, // handler
)
// Initialize gRPC server for use on shared port with pg
grpcMain := newGRPCServer(args.rpcContext)
grpcMain.setMode(modeOperational)
// TODO(davidh): Do we need to force this to be false?
baseCfg.SplitListenSQL = false
background := baseCfg.AmbientCtx.AnnotateCtx(context.Background())
// StartListenRPCAndSQL will replace the SQLAddr fields if we choose
// to share the SQL and gRPC port so here, since the tenant config
// expects to have port set on the SQL param we transfer those to
// the base Addr params in order for the RPC to be configured
// correctly.
baseCfg.Addr = baseCfg.SQLAddr
baseCfg.AdvertiseAddr = baseCfg.SQLAdvertiseAddr
pgL, startRPCServer, err := StartListenRPCAndSQL(ctx, background, baseCfg, stopper, grpcMain)
if err != nil {
return nil, "", "", err
}
{
waitQuiesce := func(ctx context.Context) {
<-args.stopper.ShouldQuiesce()
// NB: we can't do this as a Closer because (*Server).ServeWith is
// running in a worker and usually sits on accept(pgL) which unblocks
// only when pgL closes. In other words, pgL needs to close when
// quiescing starts to allow that worker to shut down.
_ = pgL.Close()
}
if err := args.stopper.RunAsyncTask(ctx, "wait-quiesce-pgl", waitQuiesce); err != nil {
waitQuiesce(ctx)
return nil, "", "", err
}
}
serverTLSConfig, err := args.rpcContext.GetUIServerTLSConfig()
if err != nil {
return nil, "", "", err
}
httpL, err := ListenAndUpdateAddrs(ctx, &args.Config.HTTPAddr, &args.Config.HTTPAdvertiseAddr, "http")
if err != nil {
return nil, "", "", err
}
if serverTLSConfig != nil {
httpL = tls.NewListener(httpL, serverTLSConfig)
}
{
waitQuiesce := func(ctx context.Context) {
<-args.stopper.ShouldQuiesce()
_ = httpL.Close()
}
if err := args.stopper.RunAsyncTask(ctx, "wait-quiesce-http", waitQuiesce); err != nil {
waitQuiesce(ctx)
return nil, "", "", err
}
}
pgLAddr := pgL.Addr().String()
httpLAddr := httpL.Addr().String()
args.advertiseAddr = baseCfg.AdvertiseAddr
// The tenantStatusServer needs access to the sqlServer,
// but we also need the same object to set up the sqlServer.
// So construct the tenant status server with a nil sqlServer,
// and then assign it once an SQL server gets created. We are
// going to assume that the tenant status server won't require
// the SQL server object.
tenantStatusServer := newTenantStatusServer(
baseCfg.AmbientCtx, &adminPrivilegeChecker{ie: args.circularInternalExecutor},
args.sessionRegistry, args.contentionRegistry, args.flowScheduler, baseCfg.Settings, nil,
args.rpcContext, args.stopper,
)
args.sqlStatusServer = tenantStatusServer
s, err := newSQLServer(ctx, args)
tenantStatusServer.sqlServer = s
if err != nil {
return nil, "", "", err
}
// TODO(asubiotto): remove this. Right now it is needed to initialize the
// SpanResolver.
s.execCfg.DistSQLPlanner.SetNodeInfo(roachpb.NodeDescriptor{NodeID: 0})
workersCtx := tenantStatusServer.AnnotateCtx(context.Background())
// Register and start gRPC service on pod. This is separate from the
// gRPC + Gateway services configured below.
tenantStatusServer.RegisterService(grpcMain.Server)
startRPCServer(workersCtx)
// Begin configuration of GRPC Gateway
gwMux, gwCtx, conn, err := ConfigureGRPCGateway(
ctx,
workersCtx,
args.AmbientCtx,
tenantStatusServer.rpcCtx,
s.stopper,
grpcMain,
pgLAddr,
)
if err != nil {
return nil, "", "", err
}
if err := tenantStatusServer.RegisterGateway(gwCtx, gwMux, conn); err != nil {
return nil, "", "", err
}
args.recorder.AddNode(
args.registry,
roachpb.NodeDescriptor{},
timeutil.Now().UnixNano(),
pgLAddr, // advertised addr
httpLAddr, // http addr
pgLAddr, // sql addr
)
if err := args.stopper.RunAsyncTask(ctx, "serve-http", func(ctx context.Context) {
mux := http.NewServeMux()
debugServer := debug.NewServer(args.Settings, s.pgServer.HBADebugFn(), s.execCfg.SQLStatusServer)
mux.Handle("/", debugServer)
mux.Handle("/_status/", gwMux)
mux.HandleFunc("/health", func(w http.ResponseWriter, req *http.Request) {
// Return Bad Request if called with arguments.
if err := req.ParseForm(); err != nil || len(req.Form) != 0 {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
})
f := varsHandler{metricSource: args.recorder, st: args.Settings}.handleVars
mux.Handle(statusVars, http.HandlerFunc(f))
ff := loadVarsHandler(ctx, args.runtime)
mux.Handle(loadStatusVars, http.HandlerFunc(ff))
tlsConnManager := netutil.MakeServer(
args.stopper,
serverTLSConfig, // tlsConfig
mux, // handler
)
netutil.FatalIfUnexpected(tlsConnManager.Serve(httpL))
}); err != nil {
return nil, "", "", err
}
const (
socketFile = "" // no unix socket
)
orphanedLeasesTimeThresholdNanos := args.clock.Now().WallTime
// TODO(tbg): the log dir is not configurable at this point
// since it is integrated too tightly with the `./cockroach start` command.
if err := startSampleEnvironment(ctx, sampleEnvironmentCfg{
st: args.Settings,
stopper: args.stopper,
minSampleInterval: base.DefaultMetricsSampleInterval,
goroutineDumpDirName: args.GoroutineDumpDirName,
heapProfileDirName: args.HeapProfileDirName,
runtime: args.runtime,
sessionRegistry: args.sessionRegistry,
}); err != nil {
return nil, "", "", err
}
if err := s.preStart(ctx,
args.stopper,
args.TestingKnobs,
connManager,
pgL,
socketFile,
orphanedLeasesTimeThresholdNanos,
); err != nil {
return nil, "", "", err
}
// This is necessary so the grpc server doesn't error out on heartbeat
// ping when we make pod-to-pod calls, we pass the InstanceID with the
// request to ensure we're dialing the pod we think we are.
//
// The InstanceID subsystem is not available until `preStart`.
args.rpcContext.NodeID.Set(ctx, roachpb.NodeID(s.SQLInstanceID()))
// Register the server's identifiers so that log events are
// decorated with the server's identity. This helps when gathering
// log events from multiple servers into the same log collector.
//
// We do this only here, as the identifiers may not be known before this point.
clusterID := args.rpcContext.ClusterID.Get().String()
log.SetNodeIDs(clusterID, 0 /* nodeID is not known for a SQL-only server. */)
log.SetTenantIDs(args.TenantID.String(), int32(s.SQLInstanceID()))
externalUsageFn := func(ctx context.Context) multitenant.ExternalUsage {
userTimeMillis, _, err := status.GetCPUTime(ctx)
if err != nil {
log.Ops.Errorf(ctx, "unable to get cpu usage: %v", err)
}
return multitenant.ExternalUsage{
CPUSecs: float64(userTimeMillis) * 1e-3,
PGWireEgressBytes: s.pgServer.BytesOut(),
}
}
nextLiveInstanceIDFn := makeNextLiveInstanceIDFn(
ctx,
args.stopper,
s.sqlInstanceProvider,
s.SQLInstanceID(),
)
if err := args.costController.Start(
ctx, args.stopper, s.SQLInstanceID(), s.sqlLivenessSessionID,
externalUsageFn, nextLiveInstanceIDFn,
); err != nil {
return nil, "", "", err
}
if err := s.startServeSQL(ctx,
args.stopper,
s.connManager,
s.pgL,
socketFile); err != nil {
return nil, "", "", err
}
return s, pgLAddr, httpLAddr, nil
}
// Construct a handler responsible for serving the instant values of selected
// load metrics. These include user and system CPU time currently.
func loadVarsHandler(
ctx context.Context, rsr *status.RuntimeStatSampler,
) func(http.ResponseWriter, *http.Request) {
cpuUserNanos := metric.NewGauge(rsr.CPUUserNS.GetMetadata())
cpuSysNanos := metric.NewGauge(rsr.CPUSysNS.GetMetadata())
registry := metric.NewRegistry()
registry.AddMetric(cpuUserNanos)
registry.AddMetric(cpuSysNanos)
return func(w http.ResponseWriter, r *http.Request) {
userTimeMillis, sysTimeMillis, err := status.GetCPUTime(ctx)
if err != nil {
// Just log but don't return an error to match the _status/vars metrics handler.
log.Ops.Errorf(ctx, "unable to get cpu usage: %v", err)
}
// cpuTime.{User,Sys} are in milliseconds, convert to nanoseconds.
utime := userTimeMillis * 1e6
stime := sysTimeMillis * 1e6
cpuUserNanos.Update(utime)
cpuSysNanos.Update(stime)
exporter := metric.MakePrometheusExporter()
exporter.ScrapeRegistry(registry, true)
if err := exporter.PrintAsText(w); err != nil {
log.Errorf(r.Context(), "%v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func makeTenantSQLServerArgs(
stopper *stop.Stopper, kvClusterName string, baseCfg BaseConfig, sqlCfg SQLConfig,
) (sqlServerArgs, error) {
st := baseCfg.Settings
baseCfg.AmbientCtx.AddLogTag("sql", nil)
// TODO(tbg): this is needed so that the RPC heartbeats between the testcluster
// and this tenant work.
//
// TODO(tbg): address this when we introduce the real tenant RPCs in:
// https://github.com/cockroachdb/cockroach/issues/47898
baseCfg.ClusterName = kvClusterName
clock := hlc.NewClock(hlc.UnixNano, time.Duration(baseCfg.MaxOffset))
registry := metric.NewRegistry()
var rpcTestingKnobs rpc.ContextTestingKnobs
if p, ok := baseCfg.TestingKnobs.Server.(*TestingKnobs); ok {
rpcTestingKnobs = p.ContextTestingKnobs
}
rpcContext := rpc.NewContext(rpc.ContextOptions{
TenantID: sqlCfg.TenantID,
AmbientCtx: baseCfg.AmbientCtx,
Config: baseCfg.Config,
Clock: clock,
Stopper: stopper,
Settings: st,
Knobs: rpcTestingKnobs,
})
var dsKnobs kvcoord.ClientTestingKnobs
if dsKnobsP, ok := baseCfg.TestingKnobs.DistSQL.(*kvcoord.ClientTestingKnobs); ok {
dsKnobs = *dsKnobsP
}
rpcRetryOptions := base.DefaultRetryOptions()
tcCfg := kvtenant.ConnectorConfig{
AmbientCtx: baseCfg.AmbientCtx,
RPCContext: rpcContext,
RPCRetryOptions: rpcRetryOptions,
DefaultZoneConfig: &baseCfg.DefaultZoneConfig,
}
tenantConnect, err := kvtenant.Factory.NewConnector(tcCfg, sqlCfg.TenantKVAddrs)
if err != nil {
return sqlServerArgs{}, err
}
resolver := kvtenant.AddressResolver(tenantConnect)
nodeDialer := nodedialer.New(rpcContext, resolver)
provider := kvtenant.TokenBucketProvider(tenantConnect)
if tenantKnobs, ok := baseCfg.TestingKnobs.TenantTestingKnobs.(*sql.TenantTestingKnobs); ok &&
tenantKnobs.OverrideTokenBucketProvider != nil {
provider = tenantKnobs.OverrideTokenBucketProvider(provider)
}
costController, err := NewTenantSideCostController(st, sqlCfg.TenantID, provider)
if err != nil {
return sqlServerArgs{}, err
}
dsCfg := kvcoord.DistSenderConfig{
AmbientCtx: baseCfg.AmbientCtx,
Settings: st,
Clock: clock,
NodeDescs: tenantConnect,
RPCRetryOptions: &rpcRetryOptions,
RPCContext: rpcContext,
NodeDialer: nodeDialer,
RangeDescriptorDB: tenantConnect,
KVInterceptor: costController,
TestingKnobs: dsKnobs,
}
ds := kvcoord.NewDistSender(dsCfg)
var clientKnobs kvcoord.ClientTestingKnobs
if p, ok := baseCfg.TestingKnobs.KVClient.(*kvcoord.ClientTestingKnobs); ok {
clientKnobs = *p
}
txnMetrics := kvcoord.MakeTxnMetrics(baseCfg.HistogramWindowInterval())
registry.AddMetricStruct(txnMetrics)
tcsFactory := kvcoord.NewTxnCoordSenderFactory(
kvcoord.TxnCoordSenderFactoryConfig{
AmbientCtx: baseCfg.AmbientCtx,
Settings: st,
Clock: clock,
Stopper: stopper,
HeartbeatInterval: base.DefaultTxnHeartbeatInterval,
Linearizable: false,
Metrics: txnMetrics,
TestingKnobs: clientKnobs,
},
ds,
)
db := kv.NewDB(baseCfg.AmbientCtx, tcsFactory, clock, stopper)
rangeFeedKnobs, _ := baseCfg.TestingKnobs.RangeFeed.(*rangefeed.TestingKnobs)
rangeFeedFactory, err := rangefeed.NewFactory(stopper, db, rangeFeedKnobs)
if err != nil {
return sqlServerArgs{}, err
}
circularInternalExecutor := &sql.InternalExecutor{}
// Protected timestamps won't be available (at first) in multi-tenant
// clusters.
var protectedTSProvider protectedts.Provider
{
pp, err := ptprovider.New(ptprovider.Config{
DB: db,
InternalExecutor: circularInternalExecutor,
Settings: st,
})
if err != nil {
panic(err)
}
protectedTSProvider = dummyProtectedTSProvider{pp}
}
recorder := status.NewMetricsRecorder(clock, nil, rpcContext, nil, st)
runtime := status.NewRuntimeStatSampler(context.Background(), clock)
registry.AddMetricStruct(runtime)
esb := &externalStorageBuilder{}
externalStorage := func(ctx context.Context, dest roachpb.ExternalStorage) (cloud.
ExternalStorage, error) {
return esb.makeExternalStorage(ctx, dest)
}
externalStorageFromURI := func(ctx context.Context, uri string,
user security.SQLUsername) (cloud.ExternalStorage, error) {
return esb.makeExternalStorageFromURI(ctx, uri, user)
}
var blobClientFactory blobs.BlobClientFactory
if p, ok := baseCfg.TestingKnobs.Server.(*TestingKnobs); ok && p.TenantBlobClientFactory != nil {
blobClientFactory = p.TenantBlobClientFactory
}
esb.init(sqlCfg.ExternalIODirConfig, baseCfg.Settings, blobClientFactory, circularInternalExecutor, db)
// We don't need this for anything except some services that want a gRPC
// server to register against (but they'll never get RPCs at the time of
// writing): the blob service and DistSQL.
dummyRPCServer := rpc.NewServer(rpcContext)
sessionRegistry := sql.NewSessionRegistry()
contentionRegistry := contention.NewRegistry()
flowScheduler := flowinfra.NewFlowScheduler(baseCfg.AmbientCtx, stopper, st)
return sqlServerArgs{
sqlServerOptionalKVArgs: sqlServerOptionalKVArgs{
nodesStatusServer: serverpb.MakeOptionalNodesStatusServer(nil),
nodeLiveness: optionalnodeliveness.MakeContainer(nil),
gossip: gossip.MakeOptionalGossip(nil),
grpcServer: dummyRPCServer,
isMeta1Leaseholder: func(_ context.Context, _ hlc.ClockTimestamp) (bool, error) {
return false, errors.New("isMeta1Leaseholder is not available to secondary tenants")
},
externalStorage: externalStorage,
externalStorageFromURI: externalStorageFromURI,
// Set instance ID to 0 and node ID to nil to indicate
// that the instance ID will be bound later during preStart.
nodeIDContainer: base.NewSQLIDContainer(0, nil),
},
sqlServerOptionalTenantArgs: sqlServerOptionalTenantArgs{
tenantConnect: tenantConnect,
},
SQLConfig: &sqlCfg,
BaseConfig: &baseCfg,
stopper: stopper,
clock: clock,
runtime: runtime,
rpcContext: rpcContext,
nodeDescs: tenantConnect,
systemConfigProvider: tenantConnect,
spanConfigAccessor: tenantConnect,
nodeDialer: nodeDialer,
distSender: ds,
db: db,
registry: registry,
recorder: recorder,
sessionRegistry: sessionRegistry,
contentionRegistry: contentionRegistry,
flowScheduler: flowScheduler,
circularInternalExecutor: circularInternalExecutor,
circularJobRegistry: &jobs.Registry{},
protectedtsProvider: protectedTSProvider,
rangeFeedFactory: rangeFeedFactory,
regionsServer: tenantConnect,
costController: costController,
}, nil
}
func makeNextLiveInstanceIDFn(
serverCtx context.Context,
stopper *stop.Stopper,
sqlInstanceProvider sqlinstance.Provider,
instanceID base.SQLInstanceID,
) multitenant.NextLiveInstanceIDFn {
retrieveNextLiveInstanceID := func(ctx context.Context) base.SQLInstanceID {
instances, err := sqlInstanceProvider.GetAllInstances(ctx)
if err != nil {
log.Infof(ctx, "GetAllInstances failed: %v", err)
// We will try again.
return 0
}
if len(instances) == 0 {
return 0
}
// Find the next ID in circular order.
var minID, nextID base.SQLInstanceID
for i := range instances {
id := instances[i].InstanceID
if minID == 0 || minID > id {
minID = id
}
if id > instanceID && (nextID == 0 || nextID > id) {
nextID = id
}
}
if nextID == 0 {
return minID
}
return nextID
}
// We retrieve the value from the provider every minute.
//
// We report each retrieved value only once; for all other calls we return 0.
// We prefer to not provide a value rather than providing a stale value which
// might cause a bit of unnecessary work on the server side.
//
// TODO(radu): once the provider caches the information (see #69976), we can
// use it directly each time.
const interval = 1 * time.Minute
var mu syncutil.Mutex
var lastRefresh time.Time
var lastValue base.SQLInstanceID
var refreshInProgress bool
serverCtx = logtags.AddTag(serverCtx, "get-next-live-instance-id", nil)
return func(ctx context.Context) base.SQLInstanceID {
mu.Lock()
defer mu.Unlock()
if lastValue != 0 {
v := lastValue
lastValue = 0
return v
}
if now := timeutil.Now(); lastRefresh.Before(now.Add(-interval)) && !refreshInProgress {
lastRefresh = now
refreshInProgress = true
// An error here indicates that the server is shutting down, so we can
// ignore it.
_ = stopper.RunAsyncTask(serverCtx, "get-next-live-instance-id", func(ctx context.Context) {
newValue := retrieveNextLiveInstanceID(ctx)
mu.Lock()
defer mu.Unlock()
lastValue = newValue
refreshInProgress = false
})
}
return 0
}
}
// NewTenantSideCostController is a hook for CCL code which implements the
// controller.
var NewTenantSideCostController = func(
st *cluster.Settings, tenantID roachpb.TenantID, provider kvtenant.TokenBucketProvider,
) (multitenant.TenantSideCostController, error) {
// Return a no-op implementation.
return noopTenantSideCostController{}, nil
}
// ApplyTenantLicense is a hook for CCL code which enables enterprise features
// for the tenant process if the COCKROACH_TENANT_LICENSE environment variable
// is set.
var ApplyTenantLicense = func() error { return nil /* no-op */ }
// noopTenantSideCostController is a no-op implementation of
// TenantSideCostController.
type noopTenantSideCostController struct{}
var _ multitenant.TenantSideCostController = noopTenantSideCostController{}
func (noopTenantSideCostController) Start(
ctx context.Context,
stopper *stop.Stopper,
instanceID base.SQLInstanceID,
sessionID sqlliveness.SessionID,
externalUsageFn multitenant.ExternalUsageFn,
nextLiveInstanceIDFn multitenant.NextLiveInstanceIDFn,
) error {
return nil
}
func (noopTenantSideCostController) OnRequestWait(
ctx context.Context, info tenantcostmodel.RequestInfo,
) error {
return nil
}
func (noopTenantSideCostController) OnResponse(
ctx context.Context, req tenantcostmodel.RequestInfo, resp tenantcostmodel.ResponseInfo,
) {
}