本文整理汇总了Golang中github.com/cockroachdb/cockroach/pkg/internal/client.NewDB函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDB函数的具体用法?Golang NewDB怎么用?Golang NewDB使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDB函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: MakeDBClient
// MakeDBClient creates a kv client for use in cli tools.
func MakeDBClient() (*client.DB, *stop.Stopper, error) {
conn, stopper, err := getGRPCConn()
if err != nil {
return nil, nil, err
}
return client.NewDB(client.NewSender(conn)), stopper, nil
}
开发者ID:BramGruneir,项目名称:cockroach,代码行数:8,代码来源:kv.go
示例2: TestTxnAbandonCount
func TestTxnAbandonCount(t *testing.T) {
defer leaktest.AfterTest(t)()
manual, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
value := []byte("value")
db := client.NewDB(sender)
// Test abandoned transaction by making the client timeout ridiculously short. We also set
// the sender to heartbeat very frequently, because the heartbeat detects and tears down
// abandoned transactions.
sender.heartbeatInterval = 2 * time.Millisecond
sender.clientTimeout = 1 * time.Millisecond
if err := db.Txn(context.TODO(), func(txn *client.Txn) error {
key := []byte("key-abandon")
if err := txn.SetIsolation(enginepb.SNAPSHOT); err != nil {
return err
}
if err := txn.Put(key, value); err != nil {
return err
}
manual.Increment(int64(sender.clientTimeout + sender.heartbeatInterval*2))
checkTxnMetrics(t, sender, "abandon txn", 0, 0, 1, 0, 0)
return nil
}); !testutils.IsError(err, "writing transaction timed out") {
t.Fatalf("unexpected error: %v", err)
}
}
开发者ID:hvaara,项目名称:cockroach,代码行数:32,代码来源:txn_coord_sender_test.go
示例3: TestTxnAbortCount
func TestTxnAbortCount(t *testing.T) {
defer leaktest.AfterTest(t)()
_, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
value := []byte("value")
db := client.NewDB(sender)
intentionalErrText := "intentional error to cause abort"
// Test aborted transaction.
if err := db.Txn(context.TODO(), func(txn *client.Txn) error {
key := []byte("key-abort")
if err := txn.SetIsolation(enginepb.SNAPSHOT); err != nil {
return err
}
if err := txn.Put(key, value); err != nil {
t.Fatal(err)
}
return errors.New(intentionalErrText)
}); !testutils.IsError(err, intentionalErrText) {
t.Fatalf("unexpected error: %v", err)
}
teardownHeartbeats(sender)
checkTxnMetrics(t, sender, "abort txn", 0, 0, 0, 1, 0)
}
开发者ID:hvaara,项目名称:cockroach,代码行数:28,代码来源:txn_coord_sender_test.go
示例4: NewClient
// NewClient implements the Cluster interface.
func (f *Farmer) NewClient(ctx context.Context, t testing.TB, i int) *client.DB {
conn, err := f.RPCContext.GRPCDial(f.Addr(ctx, i, base.DefaultPort))
if err != nil {
t.Fatal(err)
}
return client.NewDB(client.NewSender(conn))
}
开发者ID:jmptrader,项目名称:cockroach,代码行数:8,代码来源:farmer.go
示例5: createTestNode
// createTestNode creates an rpc server using the specified address,
// gossip instance, KV database and a node using the specified slice
// of engines. The server, clock and node are returned. If gossipBS is
// not nil, the gossip bootstrap address is set to gossipBS.
func createTestNode(
addr net.Addr, engines []engine.Engine, gossipBS net.Addr, t *testing.T,
) (*grpc.Server, net.Addr, *hlc.Clock, *Node, *stop.Stopper) {
cfg := storage.StoreConfig{}
stopper := stop.NewStopper()
cfg.Clock = hlc.NewClock(hlc.UnixNano)
nodeRPCContext := rpc.NewContext(log.AmbientContext{}, nodeTestBaseContext, cfg.Clock, stopper)
cfg.ScanInterval = 10 * time.Hour
cfg.ConsistencyCheckInterval = 10 * time.Hour
grpcServer := rpc.NewServer(nodeRPCContext)
serverCfg := makeTestConfig()
cfg.Gossip = gossip.NewTest(
0,
nodeRPCContext,
grpcServer,
serverCfg.GossipBootstrapResolvers,
stopper,
metric.NewRegistry(),
)
ln, err := netutil.ListenAndServeGRPC(stopper, grpcServer, addr)
if err != nil {
t.Fatal(err)
}
if gossipBS != nil {
// Handle possibility of a :0 port specification.
if gossipBS.Network() == addr.Network() && gossipBS.String() == addr.String() {
gossipBS = ln.Addr()
}
r, err := resolver.NewResolverFromAddress(gossipBS)
if err != nil {
t.Fatalf("bad gossip address %s: %s", gossipBS, err)
}
cfg.Gossip.SetResolvers([]resolver.Resolver{r})
cfg.Gossip.Start(ln.Addr())
}
retryOpts := base.DefaultRetryOptions()
retryOpts.Closer = stopper.ShouldQuiesce()
distSender := kv.NewDistSender(kv.DistSenderConfig{
Clock: cfg.Clock,
RPCContext: nodeRPCContext,
RPCRetryOptions: &retryOpts,
}, cfg.Gossip)
cfg.AmbientCtx.Tracer = tracing.NewTracer()
sender := kv.NewTxnCoordSender(
cfg.AmbientCtx,
distSender,
cfg.Clock,
false,
stopper,
kv.MakeTxnMetrics(metric.TestSampleInterval),
)
cfg.DB = client.NewDB(sender)
cfg.Transport = storage.NewDummyRaftTransport()
cfg.MetricsSampleInterval = metric.TestSampleInterval
node := NewNode(cfg, status.NewMetricsRecorder(cfg.Clock), metric.NewRegistry(), stopper,
kv.MakeTxnMetrics(metric.TestSampleInterval), sql.MakeEventLogger(nil))
roachpb.RegisterInternalServer(grpcServer, node)
return grpcServer, ln.Addr(), cfg.Clock, node, stopper
}
开发者ID:knz,项目名称:cockroach,代码行数:64,代码来源:node_test.go
示例6: NewClient
// NewClient implements the Cluster interface.
func (f *Farmer) NewClient(ctx context.Context, i int) (*client.DB, error) {
conn, err := f.RPCContext.GRPCDial(f.Addr(ctx, i, base.DefaultPort))
if err != nil {
return nil, err
}
return client.NewDB(client.NewSender(conn)), nil
}
开发者ID:BramGruneir,项目名称:cockroach,代码行数:8,代码来源:farmer.go
示例7: TestTxnCommit
// Test a normal transaction. This and the other metrics tests below use real KV operations,
// because it took far too much mucking with TxnCoordSender internals to mock out the sender
// function as other tests do.
func TestTxnCommit(t *testing.T) {
defer leaktest.AfterTest(t)()
_, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
value := []byte("value")
db := client.NewDB(sender)
// Test normal commit.
if err := db.Txn(context.TODO(), func(txn *client.Txn) error {
key := []byte("key-commit")
if err := txn.SetIsolation(enginepb.SNAPSHOT); err != nil {
return err
}
if err := txn.Put(key, value); err != nil {
return err
}
if err := txn.CommitOrCleanup(); err != nil {
return err
}
return nil
}); err != nil {
t.Fatal(err)
}
teardownHeartbeats(sender)
checkTxnMetrics(t, sender, "commit txn", 1, 0 /* not 1PC */, 0, 0, 0)
}
开发者ID:hvaara,项目名称:cockroach,代码行数:33,代码来源:txn_coord_sender_test.go
示例8: newKVNative
func newKVNative(b *testing.B) kvInterface {
enableTracing := tracing.Disable()
s, _, _ := serverutils.StartServer(b, base.TestServerArgs{})
// TestServer.DB() returns the TxnCoordSender wrapped client. But that isn't
// a fair comparison with SQL as we want these client requests to be sent
// over the network.
sender, err := client.NewSender(
rpc.NewContext(log.AmbientContext{}, &base.Config{
User: security.NodeUser,
SSLCA: filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCACert),
SSLCert: filepath.Join(security.EmbeddedCertsDir, "node.crt"),
SSLCertKey: filepath.Join(security.EmbeddedCertsDir, "node.key"),
}, nil, s.Stopper()),
s.ServingAddr())
if err != nil {
b.Fatal(err)
}
return &kvNative{
db: client.NewDB(sender),
doneFn: func() {
s.Stopper().Stop()
enableTracing()
},
}
}
开发者ID:knz,项目名称:cockroach,代码行数:27,代码来源:kv_test.go
示例9: makeClient
func (c *Cluster) makeClient(nodeIdx int) *client.DB {
sender, err := client.NewSender(c.rpcCtx, c.RPCAddr(nodeIdx))
if err != nil {
log.Fatalf(context.Background(), "failed to initialize KV client: %s", err)
}
return client.NewDB(sender)
}
开发者ID:knz,项目名称:cockroach,代码行数:7,代码来源:localcluster.go
示例10: NewClient
// NewClient implements the Cluster interface.
func (f *Farmer) NewClient(t *testing.T, i int) (*client.DB, *stop.Stopper) {
stopper := stop.NewStopper()
rpcContext := rpc.NewContext(log.AmbientContext{}, &base.Config{
Insecure: true,
User: security.NodeUser,
}, nil, stopper)
sender, err := client.NewSender(rpcContext, f.Addr(i, base.DefaultPort))
if err != nil {
t.Fatal(err)
}
return client.NewDB(sender), stopper
}
开发者ID:knz,项目名称:cockroach,代码行数:13,代码来源:farmer.go
示例11: TestInconsistentReads
// TestInconsistentReads tests that the methods that generate inconsistent reads
// generate outgoing requests with an INCONSISTENT read consistency.
func TestInconsistentReads(t *testing.T) {
defer leaktest.AfterTest(t)()
// Mock out DistSender's sender function to check the read consistency for
// outgoing BatchRequests and return an empty reply.
var senderFn client.SenderFunc
senderFn = func(_ context.Context, ba roachpb.BatchRequest) (*roachpb.BatchResponse, *roachpb.Error) {
if ba.ReadConsistency != roachpb.INCONSISTENT {
return nil, roachpb.NewErrorf("BatchRequest has unexpected ReadConsistency %s",
ba.ReadConsistency)
}
return ba.CreateReply(), nil
}
db := client.NewDB(senderFn)
ctx := context.TODO()
prepInconsistent := func() *client.Batch {
b := &client.Batch{}
b.Header.ReadConsistency = roachpb.INCONSISTENT
return b
}
// Perform inconsistent reads through the mocked sender function.
{
key := roachpb.Key([]byte("key"))
b := prepInconsistent()
b.Get(key)
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
}
{
b := prepInconsistent()
key1 := roachpb.Key([]byte("key1"))
key2 := roachpb.Key([]byte("key2"))
b.Scan(key1, key2)
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
}
{
key := roachpb.Key([]byte("key"))
b := &client.Batch{}
b.Header.ReadConsistency = roachpb.INCONSISTENT
b.Get(key)
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
}
}
开发者ID:hvaara,项目名称:cockroach,代码行数:54,代码来源:client_test.go
示例12: createTestClientForUser
func createTestClientForUser(t *testing.T, stopper *stop.Stopper, addr, user string) *client.DB {
var ctx base.Config
ctx.InitDefaults()
ctx.User = user
ctx.SSLCA = filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCACert)
ctx.SSLCert = filepath.Join(security.EmbeddedCertsDir, fmt.Sprintf("%s.crt", user))
ctx.SSLCertKey = filepath.Join(security.EmbeddedCertsDir, fmt.Sprintf("%s.key", user))
sender, err := client.NewSender(rpc.NewContext(log.AmbientContext{}, &ctx, nil, stopper), addr)
if err != nil {
t.Fatal(err)
}
return client.NewDB(sender)
}
开发者ID:knz,项目名称:cockroach,代码行数:13,代码来源:db_test.go
示例13: NewClient
// NewClient implements the Cluster interface.
func (l *LocalCluster) NewClient(t *testing.T, i int) (*roachClient.DB, *stop.Stopper) {
stopper := stop.NewStopper()
rpcContext := rpc.NewContext(log.AmbientContext{}, &base.Config{
User: security.NodeUser,
SSLCA: filepath.Join(l.CertsDir, security.EmbeddedCACert),
SSLCert: filepath.Join(l.CertsDir, security.EmbeddedNodeCert),
SSLCertKey: filepath.Join(l.CertsDir, security.EmbeddedNodeKey),
}, hlc.NewClock(hlc.UnixNano, 0), stopper)
conn, err := rpcContext.GRPCDial(l.Nodes[i].Addr(DefaultTCP).String())
if err != nil {
t.Fatal(err)
}
return roachClient.NewDB(roachClient.NewSender(conn)), stopper
}
开发者ID:hvaara,项目名称:cockroach,代码行数:15,代码来源:localcluster.go
示例14: createTestClientForUser
func createTestClientForUser(
t *testing.T, s serverutils.TestServerInterface, user string,
) *client.DB {
var ctx base.Config
ctx.InitDefaults()
ctx.User = user
ctx.SSLCA = filepath.Join(security.EmbeddedCertsDir, security.EmbeddedCACert)
ctx.SSLCert = filepath.Join(security.EmbeddedCertsDir, fmt.Sprintf("%s.crt", user))
ctx.SSLCertKey = filepath.Join(security.EmbeddedCertsDir, fmt.Sprintf("%s.key", user))
conn, err := rpc.NewContext(log.AmbientContext{}, &ctx, s.Clock(), s.Stopper()).GRPCDial(s.ServingAddr())
if err != nil {
t.Fatal(err)
}
return client.NewDB(client.NewSender(conn))
}
开发者ID:hvaara,项目名称:cockroach,代码行数:15,代码来源:db_test.go
示例15: TestTxnOnePhaseCommit
// TestTxnOnePhaseCommit verifies that 1PC metric tracking works.
func TestTxnOnePhaseCommit(t *testing.T) {
defer leaktest.AfterTest(t)()
_, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
value := []byte("value")
db := client.NewDB(sender)
if err := db.Txn(context.TODO(), func(txn *client.Txn) error {
key := []byte("key-commit")
b := txn.NewBatch()
b.Put(key, value)
return txn.CommitInBatch(b)
}); err != nil {
t.Fatal(err)
}
teardownHeartbeats(sender)
checkTxnMetrics(t, sender, "commit 1PC txn", 1, 1 /* 1PC */, 0, 0, 0)
}
开发者ID:hvaara,项目名称:cockroach,代码行数:19,代码来源:txn_coord_sender_test.go
示例16: TestTxnDurations
func TestTxnDurations(t *testing.T) {
defer leaktest.AfterTest(t)()
manual, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
db := client.NewDB(sender)
const puts = 10
const incr int64 = 1000
for i := 0; i < puts; i++ {
key := roachpb.Key(fmt.Sprintf("key-txn-durations-%d", i))
if err := db.Txn(context.TODO(), func(txn *client.Txn) error {
if err := txn.SetIsolation(enginepb.SNAPSHOT); err != nil {
return err
}
if err := txn.Put(key, []byte("val")); err != nil {
return err
}
manual.Increment(incr)
return nil
}); err != nil {
t.Fatal(err)
}
}
teardownHeartbeats(sender)
checkTxnMetrics(t, sender, "txn durations", puts, 0, 0, 0, 0)
hist := sender.metrics.Durations
// The clock is a bit odd in these tests, so I can't test the mean without
// introducing spurious errors or being overly lax.
//
// TODO(cdo): look into cause of variance.
if a, e := hist.TotalCount(), int64(puts); a != e {
t.Fatalf("durations %d != expected %d", a, e)
}
// Metrics lose fidelity, so we can't compare incr directly.
if min, thresh := hist.Min(), incr-10; min < thresh {
t.Fatalf("min %d < %d", min, thresh)
}
}
开发者ID:hvaara,项目名称:cockroach,代码行数:43,代码来源:txn_coord_sender_test.go
示例17: newKVNative
func newKVNative(b *testing.B) kvInterface {
enableTracing := tracing.Disable()
s, _, _ := serverutils.StartServer(b, base.TestServerArgs{})
// TestServer.KVClient() returns the TxnCoordSender wrapped client. But that
// isn't a fair comparison with SQL as we want these client requests to be
// sent over the network.
rpcContext := s.RPCContext()
conn, err := rpcContext.GRPCDial(s.ServingAddr())
if err != nil {
b.Fatal(err)
}
return &kvNative{
db: client.NewDB(client.NewSender(conn)),
doneFn: func() {
s.Stopper().Stop()
enableTracing()
},
}
}
开发者ID:hvaara,项目名称:cockroach,代码行数:22,代码来源:kv_test.go
示例18: makeDBClient
func makeDBClient() (*client.DB, *stop.Stopper, error) {
stopper := stop.NewStopper()
cfg := &base.Config{
User: security.NodeUser,
SSLCA: baseCfg.SSLCA,
SSLCert: baseCfg.SSLCert,
SSLCertKey: baseCfg.SSLCertKey,
Insecure: baseCfg.Insecure,
}
addr, err := addrWithDefaultHost(baseCfg.Addr)
if err != nil {
return nil, nil, err
}
sender, err := client.NewSender(
rpc.NewContext(log.AmbientContext{}, cfg, nil, stopper),
addr,
)
if err != nil {
stopper.Stop()
return nil, nil, errors.Wrap(err, "failed to initialize KV client")
}
return client.NewDB(sender), stopper, nil
}
开发者ID:knz,项目名称:cockroach,代码行数:23,代码来源:kv.go
示例19: TestTxnRestartCount
func TestTxnRestartCount(t *testing.T) {
defer leaktest.AfterTest(t)()
_, sender, cleanupFn := setupMetricsTest(t)
defer cleanupFn()
key := []byte("key-restart")
value := []byte("value")
db := client.NewDB(sender)
// Start a transaction and do a GET. This forces a timestamp to be chosen for the transaction.
txn := client.NewTxn(context.Background(), *db)
if _, err := txn.Get(key); err != nil {
t.Fatal(err)
}
// Outside of the transaction, read the same key as was read within the transaction. This
// means that future attempts to write will increase the timestamp.
if _, err := db.Get(context.TODO(), key); err != nil {
t.Fatal(err)
}
// This put will lay down an intent, txn timestamp will increase beyond original.
if err := txn.Put(key, value); err != nil {
t.Fatal(err)
}
if !txn.Proto.OrigTimestamp.Less(txn.Proto.Timestamp) {
t.Errorf("expected timestamp to increase: %s", txn.Proto)
}
// Commit (should cause restart metric to increase).
err := txn.CommitOrCleanup()
assertTransactionRetryError(t, err)
teardownHeartbeats(sender)
checkTxnMetrics(t, sender, "restart txn", 0, 0, 0, 1, 1)
}
开发者ID:hvaara,项目名称:cockroach,代码行数:36,代码来源:txn_coord_sender_test.go
示例20: bootstrapCluster
// bootstrapCluster bootstraps a multiple stores using the provided
// engines and cluster ID. The first bootstrapped store contains a
// single range spanning all keys. Initial range lookup metadata is
// populated for the range. Returns the cluster ID.
func bootstrapCluster(engines []engine.Engine, txnMetrics kv.TxnMetrics) (uuid.UUID, error) {
clusterID := uuid.MakeV4()
stopper := stop.NewStopper()
defer stopper.Stop()
cfg := storage.StoreConfig{}
cfg.ScanInterval = 10 * time.Minute
cfg.MetricsSampleInterval = time.Duration(math.MaxInt64)
cfg.ConsistencyCheckInterval = 10 * time.Minute
cfg.Clock = hlc.NewClock(hlc.UnixNano)
cfg.AmbientCtx.Tracer = tracing.NewTracer()
// Create a KV DB with a local sender.
stores := storage.NewStores(cfg.AmbientCtx, cfg.Clock)
sender := kv.NewTxnCoordSender(cfg.AmbientCtx, stores, cfg.Clock, false, stopper, txnMetrics)
cfg.DB = client.NewDB(sender)
cfg.Transport = storage.NewDummyRaftTransport()
for i, eng := range engines {
sIdent := roachpb.StoreIdent{
ClusterID: clusterID,
NodeID: FirstNodeID,
StoreID: roachpb.StoreID(i + 1),
}
// The bootstrapping store will not connect to other nodes so its
// StoreConfig doesn't really matter.
s := storage.NewStore(cfg, eng, &roachpb.NodeDescriptor{NodeID: FirstNodeID})
// Verify the store isn't already part of a cluster.
if s.Ident.ClusterID != *uuid.EmptyUUID {
return uuid.UUID{}, errors.Errorf("storage engine already belongs to a cluster (%s)", s.Ident.ClusterID)
}
// Bootstrap store to persist the store ident.
if err := s.Bootstrap(sIdent); err != nil {
return uuid.UUID{}, err
}
// Create first range, writing directly to engine. Note this does
// not create the range, just its data. Only do this if this is the
// first store.
if i == 0 {
initialValues := GetBootstrapSchema().GetInitialValues()
if err := s.BootstrapRange(initialValues); err != nil {
return uuid.UUID{}, err
}
}
if err := s.Start(context.Background(), stopper); err != nil {
return uuid.UUID{}, err
}
stores.AddStore(s)
ctx := context.TODO()
// Initialize node and store ids. Only initialize the node once.
if i == 0 {
if nodeID, err := allocateNodeID(ctx, cfg.DB); nodeID != sIdent.NodeID || err != nil {
return uuid.UUID{}, errors.Errorf("expected to initialize node id allocator to %d, got %d: %s",
sIdent.NodeID, nodeID, err)
}
}
if storeID, err := allocateStoreIDs(ctx, sIdent.NodeID, 1, cfg.DB); storeID != sIdent.StoreID || err != nil {
return uuid.UUID{}, errors.Errorf("expected to initialize store id allocator to %d, got %d: %s",
sIdent.StoreID, storeID, err)
}
}
return clusterID, nil
}
开发者ID:knz,项目名称:cockroach,代码行数:70,代码来源:node.go
注:本文中的github.com/cockroachdb/cockroach/pkg/internal/client.NewDB函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论