-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
demo.go
358 lines (314 loc) · 11.2 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
// 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/pkg/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".
`,
Example: ` cockroach demo`,
Args: cobra.NoArgs,
RunE: MaybeDecorateGRPCError(func(cmd *cobra.Command, _ []string) error {
return runDemo(cmd, nil /* gen */)
}),
}
const demoOrg = "Cockroach Labs - Production Testing"
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)
func setupTransientServers(
cmd *cobra.Command, gen workload.Generator,
) (connURL string, adminURL string, cleanup func(), err error) {
cleanup = func() {}
ctx := context.Background()
if demoCtx.nodes <= 0 {
return "", "", cleanup, errors.Errorf("must have a positive number of nodes")
}
// 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 "", "", cleanup, 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.
df := cmd.Flags().Lookup(cliflags.LogDir.Name)
sf := cmd.Flags().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
}
stopper, err := setupAndInitializeLoggingAndProfiling(ctx, cmd)
if err != nil {
return connURL, adminURL, cleanup, err
}
cleanup = func() { stopper.Stop(ctx) }
// Create the first transient server. The others will join this one.
args := base.TestServerArgs{
PartOfCluster: true,
Insecure: true,
Stopper: stopper,
}
serverFactory := server.TestServerFactory
var s *server.TestServer
for i := 0; i < demoCtx.nodes; i++ {
// All the nodes connect to the address of the first server created.
if s != nil {
args.JoinAddr = 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 connURL, adminURL, cleanup, err
}
// Remember the first server created.
if i == 0 {
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, s.Server); err != nil {
return ``, ``, cleanup, 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: s.ServingSQLAddr(),
RawQuery: options.Encode(),
}
if gen != nil {
url.Path = gen.Meta().Name
}
urlStr := 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 !cluster.TelemetryOptOut() {
s.PeriodicallyCheckForUpdates(ctx)
// 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.
if GetAndApplyLicense != nil {
db, err := gosql.Open("postgres", urlStr)
if err != nil {
return ``, ``, cleanup, err
}
// Perform license acquisition asynchronously to avoid delay in cli startup.
go func() {
defer db.Close()
success, err := GetAndApplyLicense(db, s.ClusterID(), demoOrg)
// TODO (rohany): How to report this error and exit when license
// acquisition is performed asynchronously?
if err != nil {
panic(err)
}
if !success {
msg := "Unable to acquire demo license. Enterprise features are not enabled in this session.\n"
fmt.Fprint(stderr, msg)
}
}()
}
}
// If there is a load generator, create its database and load its
// fixture.
if gen != nil {
db, err := gosql.Open("postgres", urlStr)
if err != nil {
return ``, ``, cleanup, err
}
defer db.Close()
if _, err := db.Exec(`CREATE DATABASE ` + gen.Meta().Name); err != nil {
return ``, ``, cleanup, err
}
ctx := context.TODO()
var l workloadsql.InsertsDataLoader
if _, err := workloadsql.Setup(ctx, db, gen, l); err != nil {
return ``, ``, cleanup, err
}
if demoCtx.runWorkload {
if err := runWorkload(ctx, gen, urlStr, stopper); err != nil {
return ``, ``, cleanup, err
}
}
}
return urlStr, s.AdminURL(), cleanup, nil
}
func runWorkload(
ctx context.Context, gen workload.Generator, dbURL string, stopper *stop.Stopper,
) 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{dbURL}, 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
}
}
}
}
stopper.RunWorker(ctx, workloadFun(workerFn))
}
return nil
}
func runDemo(cmd *cobra.Command, gen 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 errors.New("cannot run a workload against an empty database")
}
connURL, adminURL, cleanup, err := setupTransientServers(cmd, gen)
defer 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 gen != nil {
fmt.Printf("# The cluster has been preloaded with the %q dataset\n# (%s).\n",
gen.Meta().Name, gen.Meta().Description)
}
fmt.Printf(`#
# Your changes will not be saved!
#
# Web UI: %s
#
`, adminURL)
}
checkTzDatabaseAvailability(context.Background())
conn := makeSQLConn(connURL)
defer conn.Close()
return runClient(cmd, conn)
}