本文整理汇总了Golang中github.com/cockroachdb/cockroach/util/randutil.RandBytes函数的典型用法代码示例。如果您正苦于以下问题:Golang RandBytes函数的具体用法?Golang RandBytes怎么用?Golang RandBytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RandBytes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: fillRange
// fillRange writes keys with the given prefix and associated values
// until bytes bytes have been written or the given range has split.
func fillRange(store *storage.Store, rangeID roachpb.RangeID, prefix roachpb.Key, bytes int64, t *testing.T) {
src := rand.New(rand.NewSource(0))
for {
var ms engine.MVCCStats
if err := engine.MVCCGetRangeStats(store.Engine(), rangeID, &ms); err != nil {
t.Fatal(err)
}
keyBytes, valBytes := ms.KeyBytes, ms.ValBytes
if keyBytes+valBytes >= bytes {
return
}
key := append(append([]byte(nil), prefix...), randutil.RandBytes(src, 100)...)
key = keys.MakeNonColumnKey(key)
val := randutil.RandBytes(src, int(src.Int31n(1<<8)))
pArgs := putArgs(key, val)
_, err := client.SendWrappedWith(store, nil, roachpb.Header{
RangeID: rangeID,
}, &pArgs)
// When the split occurs in the background, our writes may start failing.
// We know we can stop writing when this happens.
if _, ok := err.(*roachpb.RangeKeyMismatchError); ok {
return
} else if err != nil {
t.Fatal(err)
}
}
}
示例2: fillTestRange
func fillTestRange(t testing.TB, rep *Replica, size int) {
src := rand.New(rand.NewSource(0))
for i := 0; i < snapSize/(keySize+valSize); i++ {
key := keys.MakeRowSentinelKey(randutil.RandBytes(src, keySize))
val := randutil.RandBytes(src, valSize)
pArgs := putArgs(key, val)
if _, pErr := client.SendWrappedWith(rep, nil, roachpb.Header{
RangeID: rangeID,
}, &pArgs); pErr != nil {
t.Fatal(pErr)
}
}
}
示例3: writeRandomDataToRange
func writeRandomDataToRange(t testing.TB, store *storage.Store, rangeID roachpb.RangeID, keyPrefix []byte) {
src := rand.New(rand.NewSource(0))
for i := 0; i < 100; i++ {
key := append([]byte(nil), keyPrefix...)
key = append(key, randutil.RandBytes(src, int(src.Int31n(1<<7)))...)
key = keys.MakeNonColumnKey(key)
val := randutil.RandBytes(src, int(src.Int31n(1<<8)))
pArgs := putArgs(key, val)
if _, pErr := client.SendWrappedWith(rg1(store), nil, roachpb.Header{
RangeID: rangeID,
}, &pArgs); pErr != nil {
t.Fatal(pErr)
}
}
}
示例4: runMVCCConditionalPut
func runMVCCConditionalPut(emk engineMaker, valueSize int, createFirst bool, b *testing.B) {
rng, _ := randutil.NewPseudoRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
eng, stopper := emk(b, fmt.Sprintf("cput_%d", valueSize))
defer stopper.Stop()
b.SetBytes(int64(valueSize))
var expected *roachpb.Value
if createFirst {
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := makeTS(timeutil.Now().UnixNano(), 0)
if err := MVCCPut(context.Background(), eng, nil, key, ts, value, nil); err != nil {
b.Fatalf("failed put: %s", err)
}
}
expected = &value
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := makeTS(timeutil.Now().UnixNano(), 0)
if err := MVCCConditionalPut(context.Background(), eng, nil, key, ts, value, expected, nil); err != nil {
b.Fatalf("failed put: %s", err)
}
}
b.StopTimer()
}
示例5: runMVCCConditionalPut
func runMVCCConditionalPut(valueSize int, createFirst bool, b *testing.B) {
rng, _ := randutil.NewPseudoRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
stopper := stop.NewStopper()
defer stopper.Stop()
rocksdb := NewInMem(roachpb.Attributes{}, testCacheSize, stopper)
b.SetBytes(int64(valueSize))
var expected *roachpb.Value
if createFirst {
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := makeTS(timeutil.Now().UnixNano(), 0)
if err := MVCCPut(rocksdb, nil, key, ts, value, nil); err != nil {
b.Fatalf("failed put: %s", err)
}
}
expected = &value
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := makeTS(timeutil.Now().UnixNano(), 0)
if err := MVCCConditionalPut(rocksdb, nil, key, ts, value, expected, nil); err != nil {
b.Fatalf("failed put: %s", err)
}
}
b.StopTimer()
}
示例6: BenchmarkMVCCPutDelete_RocksDB
func BenchmarkMVCCPutDelete_RocksDB(b *testing.B) {
const cacheSize = 1 << 30 // 1 GB
rocksdb, stopper := setupMVCCInMemRocksDB(b, "put_delete")
defer stopper.Stop()
r := rand.New(rand.NewSource(int64(timeutil.Now().UnixNano())))
value := roachpb.MakeValueFromBytes(randutil.RandBytes(r, 10))
zeroTS := roachpb.ZeroTimestamp
var blockNum int64
for i := 0; i < b.N; i++ {
blockID := r.Int63()
blockNum++
key := encoding.EncodeVarintAscending(nil, blockID)
key = encoding.EncodeVarintAscending(key, blockNum)
if err := MVCCPut(context.Background(), rocksdb, nil, key, zeroTS, value, nil /* txn */); err != nil {
b.Fatal(err)
}
if err := MVCCDelete(context.Background(), rocksdb, nil, key, zeroTS, nil /* txn */); err != nil {
b.Fatal(err)
}
}
}
示例7: TestApproximateSize
func TestApproximateSize(t *testing.T) {
defer leaktest.AfterTest(t)
runWithAllEngines(func(engine Engine, t *testing.T) {
var (
count = 10000
keys = make([]proto.EncodedKey, count)
values = make([][]byte, count) // Random values to prevent compression
rand, _ = randutil.NewPseudoRand()
valueLen = 10
)
for i := 0; i < count; i++ {
keys[i] = []byte(fmt.Sprintf("key%8d", i))
values[i] = randutil.RandBytes(rand, valueLen)
}
insertKeysAndValues(keys, values, engine, t)
if err := engine.Flush(); err != nil {
t.Fatalf("Error flushing InMem: %s", err)
}
sizePerRecord := (len([]byte(keys[0])) + valueLen)
verifyApproximateSize(keys, engine, sizePerRecord, 0.15, t)
verifyApproximateSize(keys[:count/2], engine, sizePerRecord, 0.15, t)
verifyApproximateSize(keys[:count/4], engine, sizePerRecord, 0.15, t)
}, t)
}
示例8: BenchmarkMVCCPutDelete
func BenchmarkMVCCPutDelete(b *testing.B) {
const cacheSize = 1 << 30 // 1 GB
stopper := stop.NewStopper()
rocksdb := NewInMem(roachpb.Attributes{}, cacheSize, stopper)
defer stopper.Stop()
r := rand.New(rand.NewSource(int64(timeutil.Now().UnixNano())))
value := roachpb.MakeValueFromBytes(randutil.RandBytes(r, 10))
zeroTS := roachpb.ZeroTimestamp
var blockNum int64
for i := 0; i < b.N; i++ {
blockID := r.Int63()
blockNum++
key := encoding.EncodeVarintAscending(nil, blockID)
key = encoding.EncodeVarintAscending(key, blockNum)
if err := MVCCPut(rocksdb, nil, key, zeroTS, value, nil /* txn */); err != nil {
b.Fatal(err)
}
if err := MVCCDelete(rocksdb, nil, key, zeroTS, nil /* txn */); err != nil {
b.Fatal(err)
}
}
}
示例9: TestRandBytes
func TestRandBytes(t *testing.T) {
rand, _ := randutil.NewPseudoRand()
for i := 0; i < 100; i++ {
x := randutil.RandBytes(rand, i)
if len(x) != i {
t.Errorf("got array with unexpected length: %d (expected %d)", len(x), i)
}
}
}
示例10: fillRange
// fillRange writes keys with the given prefix and associated values
// until bytes bytes have been written.
func fillRange(store *storage.Store, rangeID roachpb.RangeID, prefix roachpb.Key, bytes int64, t *testing.T) {
src := rand.New(rand.NewSource(0))
for {
var ms engine.MVCCStats
if err := engine.MVCCGetRangeStats(store.Engine(), rangeID, &ms); err != nil {
t.Fatal(err)
}
keyBytes, valBytes := ms.KeyBytes, ms.ValBytes
if keyBytes+valBytes >= bytes {
return
}
key := append(append([]byte(nil), prefix...), randutil.RandBytes(src, 100)...)
val := randutil.RandBytes(src, int(src.Int31n(1<<8)))
pArgs := putArgs(key, val, rangeID, store.StoreID())
if _, err := client.SendWrapped(store, nil, &pArgs); err != nil {
t.Fatal(err)
}
}
}
示例11: startTestWriter
// startTestWriter creates a writer which initiates a sequence of
// transactions, each which writes up to 10 times to random keys with
// random values. If not nil, txnChannel is written to non-blockingly
// every time a new transaction starts.
func startTestWriter(db *client.DB, i int64, valBytes int32, wg *sync.WaitGroup, retries *int32,
txnChannel chan struct{}, done <-chan struct{}, t *testing.T) {
src := rand.New(rand.NewSource(i))
defer func() {
if wg != nil {
wg.Done()
}
}()
for j := 0; ; j++ {
select {
case <-done:
return
default:
first := true
err := db.Txn(func(txn *client.Txn) error {
if first && txnChannel != nil {
select {
case txnChannel <- struct{}{}:
default:
}
} else if !first && retries != nil {
atomic.AddInt32(retries, 1)
}
first = false
for j := 0; j <= int(src.Int31n(10)); j++ {
key := randutil.RandBytes(src, 10)
val := randutil.RandBytes(src, int(src.Int31n(valBytes)))
if err := txn.Put(key, val); err != nil {
log.Infof("experienced an error in routine %d: %s", i, err)
return err
}
}
return nil
})
if err != nil {
t.Error(err)
} else {
time.Sleep(1 * time.Millisecond)
}
}
}
}
示例12: fillTestRange
func fillTestRange(t testing.TB, rep *Replica, size int64) {
src := rand.New(rand.NewSource(0))
for i := int64(0); i < size/int64(keySize+valSize); i++ {
key := keys.MakeRowSentinelKey(randutil.RandBytes(src, keySize))
val := randutil.RandBytes(src, valSize)
pArgs := putArgs(key, val)
if _, pErr := client.SendWrappedWith(rep, nil, roachpb.Header{
RangeID: rangeID,
}, &pArgs); pErr != nil {
t.Fatal(pErr)
}
}
rep.mu.Lock()
after := rep.mu.state.Stats.Total()
rep.mu.Unlock()
if after < size {
t.Fatalf("range not full after filling: wrote %d, but range at %d", size, after)
}
}
示例13: fillRange
// fillRange writes keys with the given prefix and associated values
// until bytes bytes have been written.
func fillRange(store *storage.Store, rangeID proto.RangeID, prefix proto.Key, bytes int64, t *testing.T) {
src := rand.New(rand.NewSource(0))
for {
var ms engine.MVCCStats
if err := engine.MVCCGetRangeStats(store.Engine(), rangeID, &ms); err != nil {
t.Fatal(err)
}
keyBytes, valBytes := ms.KeyBytes, ms.ValBytes
if keyBytes+valBytes >= bytes {
return
}
key := append(append([]byte(nil), prefix...), randutil.RandBytes(src, 100)...)
val := randutil.RandBytes(src, int(src.Int31n(1<<8)))
pArgs := putArgs(key, val, rangeID, store.StoreID())
pArgs.Timestamp = store.Clock().Now()
if _, err := store.ExecuteCmd(context.Background(), &pArgs); err != nil {
t.Fatal(err)
}
}
}
示例14: setupMVCCScanData
// setupMVCCData writes up to numVersions values at each of numKeys
// keys. The number of versions written for each key is chosen
// randomly according to a uniform distribution. Each successive
// version is written starting at 5ns and then in 5ns increments. This
// allows scans at various times, starting at t=5ns, and continuing to
// t=5ns*(numVersions+1). A version for each key will be read on every
// such scan, but the dynamics of the scan will change depending on
// the historical timestamp. Earlier timestamps mean scans which must
// skip more historical versions; later timestamps mean scans which
// skip fewer.
//
// The creation of the rocksdb database is time consuming, especially
// for larger numbers of versions. The database is persisted between
// runs and stored in the current directory as
// "mvcc_scan_<versions>_<keys>_<valueBytes>".
func setupMVCCScanData(numVersions, numKeys, valueBytes int, b *testing.B) (*RocksDB, *stop.Stopper) {
loc := fmt.Sprintf("mvcc_scan_%d_%d_%d", numVersions, numKeys, valueBytes)
exists := true
if _, err := os.Stat(loc); os.IsNotExist(err) {
exists = false
}
const cacheSize = 8 << 30 // 8 GB
stopper := stop.NewStopper()
rocksdb := NewRocksDB(roachpb.Attributes{}, loc, cacheSize, stopper)
if err := rocksdb.Open(); err != nil {
b.Fatalf("could not create new rocksdb db instance at %s: %v", loc, err)
}
if exists {
return rocksdb, stopper
}
log.Infof("creating mvcc data: %s", loc)
rng, _ := randutil.NewPseudoRand()
keys := make([]roachpb.Key, numKeys)
nvs := make([]int, numKeys)
for t := 1; t <= numVersions; t++ {
walltime := int64(5 * t)
ts := makeTS(walltime, 0)
batch := rocksdb.NewBatch()
for i := 0; i < numKeys; i++ {
if t == 1 {
keys[i] = roachpb.Key(encoding.EncodeUvarint([]byte("key-"), uint64(i)))
nvs[i] = rand.Intn(numVersions) + 1
}
// Only write values if this iteration is less than the random
// number of versions chosen for this key.
if t <= nvs[i] {
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueBytes))
value.InitChecksum(keys[i])
if err := MVCCPut(batch, nil, keys[i], ts, value, nil); err != nil {
b.Fatal(err)
}
}
}
if err := batch.Commit(); err != nil {
b.Fatal(err)
}
batch.Close()
}
rocksdb.CompactRange(nil, nil)
return rocksdb, stopper
}
示例15: TestPut
// TestPut starts up an N node cluster and runs N workers that write
// to independent keys.
func TestPut(t *testing.T) {
l := localcluster.Create(*numNodes, stopper)
l.Start()
defer l.Stop()
db, dbStopper := makeDBClient(t, l, 0)
defer dbStopper.Stop()
if err := configutil.SetDefaultRangeMaxBytes(db, *rangeMaxBytes); err != nil {
t.Fatal(err)
}
checkRangeReplication(t, l, 20*time.Second)
errs := make(chan error, *numNodes)
start := time.Now()
deadline := start.Add(*duration)
var count int64
for i := 0; i < *numNodes; i++ {
go func() {
r, _ := randutil.NewPseudoRand()
value := randutil.RandBytes(r, 8192)
for time.Now().Before(deadline) {
k := atomic.AddInt64(&count, 1)
v := value[:r.Intn(len(value))]
if err := db.Put(fmt.Sprintf("%08d", k), v); err != nil {
errs <- err
return
}
}
errs <- nil
}()
}
for i := 0; i < *numNodes; {
select {
case <-stopper:
t.Fatalf("interrupted")
case err := <-errs:
if err != nil {
t.Fatal(err)
}
i++
case <-time.After(1 * time.Second):
// Periodically print out progress so that we know the test is still
// running.
log.Infof("%d", atomic.LoadInt64(&count))
}
}
elapsed := time.Since(start)
log.Infof("%d %.1f/sec", count, float64(count)/elapsed.Seconds())
}