-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathdemo.go
490 lines (427 loc) · 15.6 KB
/
demo.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
// Copyright 2018 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 cli
import (
"context"
gosql "database/sql"
"fmt"
"net/url"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/cli/cliflags"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logflags"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/cockroach/pkg/workload"
"github.com/cockroachdb/cockroach/pkg/workload/histogram"
"github.com/cockroachdb/cockroach/pkg/workload/workloadsql"
"github.com/cockroachdb/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/time/rate"
)
var demoCmd = &cobra.Command{
Use: "demo",
Short: "open a demo sql shell",
Long: `
Start an in-memory, standalone, single-node CockroachDB instance, and open an
interactive SQL prompt to it. Various datasets are available to be preloaded as
subcommands: e.g. "cockroach demo startrek". See --help for a full list.
By default, the 'movr' dataset is pre-loaded. You can also use --empty
to avoid pre-loading a dataset.
cockroach demo attempts to connect to a Cockroach Labs server to obtain a
temporary enterprise license for demoing enterprise features and enable
telemetry back to Cockroach Labs. In order to disable this behavior, set the
environment variable "COCKROACH_SKIP_ENABLING_DIAGNOSTIC_REPORTING" to true.
`,
Example: ` cockroach demo`,
Args: cobra.NoArgs,
RunE: MaybeDecorateGRPCError(func(cmd *cobra.Command, _ []string) error {
return runDemo(cmd, nil /* gen */)
}),
}
const demoOrg = "Cockroach Demo"
const defaultGeneratorName = "movr"
var defaultGenerator workload.Generator
var defaultLocalities = demoLocalityList{
// Default localities for a 3 node cluster
{Tiers: []roachpb.Tier{{Key: "region", Value: "us-east1"}, {Key: "az", Value: "b"}}},
{Tiers: []roachpb.Tier{{Key: "region", Value: "us-east1"}, {Key: "az", Value: "c"}}},
{Tiers: []roachpb.Tier{{Key: "region", Value: "us-east1"}, {Key: "az", Value: "d"}}},
// Default localities for a 6 node cluster
{Tiers: []roachpb.Tier{{Key: "region", Value: "us-west1"}, {Key: "az", Value: "a"}}},
{Tiers: []roachpb.Tier{{Key: "region", Value: "us-west1"}, {Key: "az", Value: "b"}}},
{Tiers: []roachpb.Tier{{Key: "region", Value: "us-west1"}, {Key: "az", Value: "c"}}},
// Default localities for a 9 node cluster
{Tiers: []roachpb.Tier{{Key: "region", Value: "europe-west1"}, {Key: "az", Value: "b"}}},
{Tiers: []roachpb.Tier{{Key: "region", Value: "europe-west1"}, {Key: "az", Value: "c"}}},
{Tiers: []roachpb.Tier{{Key: "region", Value: "europe-west1"}, {Key: "az", Value: "d"}}},
}
func init() {
for _, meta := range workload.Registered() {
gen := meta.New()
if meta.Name == defaultGeneratorName {
// Save the default for use in the top-level 'demo' command
// without argument.
defaultGenerator = gen
}
var genFlags *pflag.FlagSet
if f, ok := gen.(workload.Flagser); ok {
genFlags = f.Flags().FlagSet
}
genDemoCmd := &cobra.Command{
Use: meta.Name,
Short: meta.Description,
Args: cobra.ArbitraryArgs,
RunE: MaybeDecorateGRPCError(func(cmd *cobra.Command, _ []string) error {
return runDemo(cmd, gen)
}),
}
demoCmd.AddCommand(genDemoCmd)
genDemoCmd.Flags().AddFlagSet(genFlags)
}
}
// GetAndApplyLicense is not implemented in order to keep OSS/BSL builds successful.
// The cliccl package sets this function if enterprise features are available to demo.
var GetAndApplyLicense func(dbConn *gosql.DB, clusterID uuid.UUID, org string) (bool, error)
type transientCluster struct {
connURL string
stopper *stop.Stopper
s *server.TestServer
cleanup func()
}
func setupTransientCluster(
ctx context.Context, cmd *cobra.Command, gen workload.Generator,
) (c transientCluster, err error) {
c.cleanup = func() {}
// The user specified some localities for their nodes.
if len(demoCtx.localities) != 0 {
// Error out of localities don't line up with requested node
// count before doing any sort of setup.
if len(demoCtx.localities) != demoCtx.nodes {
return c, errors.Errorf("number of localities specified must equal number of nodes")
}
} else {
demoCtx.localities = make([]roachpb.Locality, demoCtx.nodes)
for i := 0; i < demoCtx.nodes; i++ {
demoCtx.localities[i] = defaultLocalities[i%len(defaultLocalities)]
}
}
// Set up logging. For demo/transient server we use non-standard
// behavior where we avoid file creation if possible.
fl := flagSetForCmd(cmd)
df := fl.Lookup(cliflags.LogDir.Name)
sf := fl.Lookup(logflags.LogToStderrName)
if !df.Changed && !sf.Changed {
// User did not request logging flags; shut down all logging.
// Otherwise, the demo command would cause a cockroach-data
// directory to appear in the current directory just for logs.
_ = df.Value.Set("")
df.Changed = true
_ = sf.Value.Set(log.Severity_NONE.String())
sf.Changed = true
}
c.stopper, err = setupAndInitializeLoggingAndProfiling(ctx, cmd)
if err != nil {
return c, err
}
c.cleanup = func() { c.stopper.Stop(ctx) }
// Create the first transient server. The others will join this one.
args := base.TestServerArgs{
PartOfCluster: true,
Insecure: true,
Stopper: c.stopper,
}
serverFactory := server.TestServerFactory
for i := 0; i < demoCtx.nodes; i++ {
// All the nodes connect to the address of the first server created.
if c.s != nil {
args.JoinAddr = c.s.ServingRPCAddr()
}
if demoCtx.localities != nil {
args.Locality = demoCtx.localities[i]
}
serv := serverFactory.New(args).(*server.TestServer)
if err := serv.Start(args); err != nil {
return c, err
}
// Remember the first server created.
if i == 0 {
c.s = serv
}
}
if demoCtx.nodes < 3 {
// Set up the default zone configuration. We are using an in-memory store
// so we really want to disable replication.
if err := cliDisableReplication(ctx, c.s.Server); err != nil {
return c, err
}
}
// Prepare the URL for use by the SQL shell.
options := url.Values{}
options.Add("sslmode", "disable")
options.Add("application_name", sqlbase.ReportableAppNamePrefix+"cockroach demo")
url := url.URL{
Scheme: "postgres",
User: url.User(security.RootUser),
Host: c.s.ServingSQLAddr(),
RawQuery: options.Encode(),
}
if gen != nil {
url.Path = gen.Meta().Name
}
c.connURL = url.String()
// Start up the update check loop.
// We don't do this in (*server.Server).Start() because we don't want it
// in tests.
if !demoCtx.disableTelemetry {
c.s.PeriodicallyCheckForUpdates(ctx)
}
return c, nil
}
func (c *transientCluster) setupWorkload(ctx context.Context, gen workload.Generator) error {
// Communicate information about license acquisition to services
// that depend on it.
licenseDone := make(chan struct{})
if demoCtx.disableLicenseAcquisition {
close(licenseDone)
} else {
// If we allow telemetry, then also try and get an enterprise license for the demo.
// GetAndApplyLicense will be nil in the pure OSS/BSL build of cockroach.
db, err := gosql.Open("postgres", c.connURL)
if err != nil {
return err
}
// Perform license acquisition asynchronously to avoid delay in cli startup.
go func() {
defer db.Close()
success, err := GetAndApplyLicense(db, c.s.ClusterID(), demoOrg)
if err != nil {
exitWithError("demo", err)
}
if !success {
if demoCtx.geoPartitionedReplicas {
log.Shout(ctx, log.Severity_ERROR,
"license acquisition was unsuccessful.\nNote: enterprise features are needed for --geo-partitioned-replicas.")
exitWithError("demo", errors.New("unable to acquire a license for this demo"))
}
const msg = "\nwarning: unable to acquire demo license - enterprise features are not enabled."
fmt.Fprintln(stderr, msg)
}
close(licenseDone)
}()
}
// If there is a load generator, create its database and load its
// fixture.
if gen != nil {
db, err := gosql.Open("postgres", c.connURL)
if err != nil {
return err
}
defer db.Close()
if _, err := db.Exec(`CREATE DATABASE ` + gen.Meta().Name); err != nil {
return err
}
ctx := context.TODO()
var l workloadsql.InsertsDataLoader
if _, err := workloadsql.Setup(ctx, db, gen, l); err != nil {
return err
}
// If we are requested to prepartition our data spawn a goroutine to do the partitioning.
if demoCtx.geoPartitionedReplicas {
// Wait until the license has been acquired to trigger partitioning.
fmt.Println("#\n# Waiting for license acquisition to complete...")
<-licenseDone
fmt.Println("#\n# Partitioning the demo database, please wait...")
db, err := gosql.Open("postgres", c.connURL)
if err != nil {
return err
}
defer db.Close()
// Based on validation done in setup, we know that this workload has a partitioning step.
if err := gen.(workload.Hookser).Hooks().Partition(db); err != nil {
return errors.Wrapf(err, "partitioning the demo database")
}
}
// Run the workload. This must occur after partitioning the database.
if demoCtx.runWorkload {
if err := c.runWorkload(ctx, gen); err != nil {
return errors.Wrapf(err, "starting background workload")
}
}
}
return nil
}
func (c *transientCluster) runWorkload(ctx context.Context, gen workload.Generator) error {
opser, ok := gen.(workload.Opser)
if !ok {
return errors.Errorf("default dataset %s does not have a workload defined", gen.Meta().Name)
}
// Dummy registry to prove to the Opser.
reg := histogram.NewRegistry(time.Duration(100) * time.Millisecond)
ops, err := opser.Ops([]string{c.connURL}, reg)
if err != nil {
return errors.Wrap(err, "unable to create workload")
}
// Use a light rate limit of 25 queries per second
limiter := rate.NewLimiter(rate.Limit(25), 1)
// Start a goroutine to run each of the workload functions.
for _, workerFn := range ops.WorkerFns {
workloadFun := func(f func(context.Context) error) func(context.Context) {
return func(ctx context.Context) {
for {
// Limit how quickly we can generate work.
if err := limiter.Wait(ctx); err != nil {
// When the limiter throws an error, panic because we don't
// expect any errors from it.
panic(err)
}
if err := f(ctx); err != nil {
// Only log an error and return when the workload function throws
// an error, because errors these errors should be ignored, and
// should not interrupt the rest of the demo.
log.Warningf(ctx, "Error running workload query: %+v\n", err)
return
}
}
}
}
c.stopper.RunWorker(ctx, workloadFun(workerFn))
}
return nil
}
func incrementTelemetryCounters(cmd *cobra.Command) {
if flagSetForCmd(cmd).Lookup(cliflags.DemoNodes.Name).Changed {
incrementDemoCounter(nodes)
}
if demoCtx.localities != nil {
incrementDemoCounter(demoLocality)
}
if demoCtx.runWorkload {
incrementDemoCounter(withLoad)
}
if demoCtx.geoPartitionedReplicas {
incrementDemoCounter(geoPartitionedReplicas)
}
}
func checkDemoConfiguration(
cmd *cobra.Command, gen workload.Generator,
) (workload.Generator, error) {
if gen == nil && !demoCtx.useEmptyDatabase {
// Use a default dataset unless prevented by --empty.
gen = defaultGenerator
}
// Make sure that the user didn't request a workload and an empty database.
if demoCtx.runWorkload && demoCtx.useEmptyDatabase {
return nil, errors.New("cannot run a workload against an empty database")
}
// Make sure the number of nodes is valid.
if demoCtx.nodes <= 0 {
return nil, errors.Newf("--nodes has invalid value (expected positive, got %d)", demoCtx.nodes)
}
demoCtx.disableTelemetry = cluster.TelemetryOptOut()
demoCtx.disableLicenseAcquisition = demoCtx.disableTelemetry || (GetAndApplyLicense == nil)
if demoCtx.geoPartitionedReplicas {
if demoCtx.disableLicenseAcquisition {
return nil, errors.New("enterprise features are needed for this demo (--geo-partitioning-replicas)")
}
// Make sure that the user didn't request to have a topology and an empty database.
if demoCtx.useEmptyDatabase {
return nil, errors.New("cannot setup geo-partitioned replicas topology on an empty database")
}
// Make sure that the Movr database is selected when automatically partitioning.
if gen == nil || gen.Meta().Name != "movr" {
return nil, errors.New("--geo-partitioned-replicas must be used with the Movr dataset")
}
// If the geo-partitioned replicas flag was given and the demo localities have changed, throw an error.
if demoCtx.localities != nil {
return nil, errors.New("--demo-locality cannot be used with --geo-partitioned-replicas")
}
// If the geo-partitioned replicas flag was given and the nodes have changed, throw an error.
if flagSetForCmd(cmd).Lookup(cliflags.DemoNodes.Name).Changed {
if demoCtx.nodes != 9 {
return nil, errors.New("--nodes with a value different from 9 cannot be used with --geo-partitioned-replicas")
}
} else {
const msg = `#
# --geo-partitioned replicas operates on a 9 node cluster.
# The cluster size has been changed from the default to 9 nodes.`
fmt.Println(msg)
demoCtx.nodes = 9
}
// If geo-partition-replicas is requested, make sure the workload has a Partitioning step.
configErr := errors.New(fmt.Sprintf("workload %s is not configured to have a partitioning step", gen.Meta().Name))
hookser, ok := gen.(workload.Hookser)
if !ok {
return nil, configErr
}
if hookser.Hooks().Partition == nil {
return nil, configErr
}
}
return gen, nil
}
func runDemo(cmd *cobra.Command, gen workload.Generator) (err error) {
if gen, err = checkDemoConfiguration(cmd, gen); err != nil {
return err
}
// Record some telemetry about what flags are being used.
incrementTelemetryCounters(cmd)
ctx := context.Background()
c, err := setupTransientCluster(ctx, cmd, gen)
defer c.cleanup()
if err != nil {
return checkAndMaybeShout(err)
}
checkInteractive()
if cliCtx.isInteractive {
fmt.Printf(`#
# Welcome to the CockroachDB demo database!
#
# You are connected to a temporary, in-memory CockroachDB cluster of %d node%s.
`, demoCtx.nodes, util.Pluralize(int64(demoCtx.nodes)))
if demoCtx.disableTelemetry {
fmt.Println("#\n# Telemetry and automatic license acquisition disabled by configuration.")
} else if demoCtx.disableLicenseAcquisition {
fmt.Println("#\n# Enterprise features disabled by OSS-only build.")
} else {
fmt.Println("#\n# This demo session will attempt to enable enterprise features\n" +
"# by acquiring a temporary license from Cockroach Labs in the background.\n" +
"# To disable this behavior, set the environment variable\n" +
"# COCKROACH_SKIP_ENABLING_DIAGNOSTIC_REPORTING=true.")
}
}
if err := c.setupWorkload(ctx, gen); err != nil {
return err
}
if cliCtx.isInteractive {
if gen != nil {
fmt.Printf("#\n# The cluster has been preloaded with the %q dataset\n# (%s).\n",
gen.Meta().Name, gen.Meta().Description)
}
fmt.Printf(`#
# Reminder: your changes to data stored in the demo session will not be saved!
#
# Web UI: %s
#
`, c.s.AdminURL())
}
checkTzDatabaseAvailability(ctx)
conn := makeSQLConn(c.connURL)
defer conn.Close()
return runClient(cmd, conn)
}