Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[chore] Migrate from math/rand to math/rand/v2 #34685

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ linters-settings:
desc: "Use 'errors' or 'fmt' instead of github.com/pkg/errors"
- pkg: github.com/hashicorp/go-multierror
desc: "Use go.uber.org/multierr instead of github.com/hashicorp/go-multierror"
- pkg: "math/rand$"
desc: "Use math/rand/v2 instead of math/rand"
# Add a different guard rule so that we can ignore tests.
ignore-in-test:
deny:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package store

import (
"encoding/hex"
"math/rand"
"math/rand/v2"
"testing"
"time"

Expand Down Expand Up @@ -146,7 +146,7 @@ func TestStoreConcurrency(t *testing.T) {
}

go accessor(func() {
key := NewKey(pcommon.TraceID([16]byte{byte(rand.Intn(32))}), pcommon.SpanID([8]byte{1, 2, 3}))
key := NewKey(pcommon.TraceID([16]byte{byte(rand.IntN(32))}), pcommon.SpanID([8]byte{1, 2, 3}))

_, err := s.UpsertEdge(key, func(e *Edge) {
e.ClientService = hex.EncodeToString(key.tid[:])
Expand Down
7 changes: 3 additions & 4 deletions examples/demo/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"context"
"fmt"
"log"
"math/rand"
"math/rand/v2"
"net/http"
"os"
"time"
Expand Down Expand Up @@ -150,16 +150,15 @@ func main() {
)

defaultCtx := baggage.ContextWithBaggage(context.Background(), bag)
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
startTime := time.Now()
ctx, span := tracer.Start(defaultCtx, "ExecuteRequest")
makeRequest(ctx)
span.End()
latencyMs := float64(time.Since(startTime)) / 1e6
nr := int(rng.Int31n(7))
nr := int(rand.Int32N(7))
for i := 0; i < nr; i++ {
randLineLength := rng.Int63n(999)
randLineLength := rand.Int64N(999)
lineCounts.Add(ctx, 1, metric.WithAttributes(commonLabels...))
lineLengths.Record(ctx, randLineLength, metric.WithAttributes(commonLabels...))
fmt.Printf("#%d: LineLength: %dBy\n", i, randLineLength)
Expand Down
14 changes: 6 additions & 8 deletions examples/demo/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ package main
import (
"context"
"log"
"math/rand"
"math/rand/v2"
"net/http"
"os"
"time"
Expand All @@ -29,8 +29,6 @@ import (
"go.opentelemetry.io/otel/trace"
)

var rng = rand.New(rand.NewSource(time.Now().UnixNano()))

// Initializes an OTLP exporter, and configures the corresponding trace and
// metric providers.
func initProvider() func() {
Expand Down Expand Up @@ -125,15 +123,15 @@ func main() {

switch modulus := time.Now().Unix() % 5; modulus {
case 0:
sleep = rng.Int63n(2000)
sleep = rand.Int64N(2000)
case 1:
sleep = rng.Int63n(15)
sleep = rand.Int64N(15)
case 2:
sleep = rng.Int63n(917)
sleep = rand.Int64N(917)
case 3:
sleep = rng.Int63n(87)
sleep = rand.Int64N(87)
case 4:
sleep = rng.Int63n(1173)
sleep = rand.Int64N(1173)
}
time.Sleep(time.Duration(sleep) * time.Millisecond)
ctx := req.Context()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"compress/zlib"
"fmt"
"io"
"math/rand"
"math/rand/v2"
"sync"
"testing"
"time"
Expand Down Expand Up @@ -77,7 +77,7 @@ func createRandomString(length int) string {

b := make([]byte, length)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
b[i] = letterBytes[rand.IntN(len(letterBytes))]
}

return string(b)
Expand Down Expand Up @@ -118,16 +118,13 @@ func BenchmarkGzipCompressor_1Mb(b *testing.B) {
func benchmarkCompressor(b *testing.B, format string, length int) {
b.Helper()

source := rand.NewSource(time.Now().UnixMilli())
genRand := rand.New(source)

compressor, err := compress.NewCompressor(format)
require.NoError(b, err, "Must not error when given a valid format")
require.NotNil(b, compressor, "Must have a valid compressor")

data := make([]byte, length)
for i := 0; i < length; i++ {
data[i] = byte(genRand.Int31())
data[i] = byte(rand.Int32())
}
b.ReportAllocs()
b.ResetTimer()
Expand Down Expand Up @@ -188,12 +185,9 @@ func concurrentCompressFunc(t *testing.T) {
go func() {
defer wg.Done()

source := rand.NewSource(time.Now().UnixMilli())
genRand := rand.New(source)

data := make([]byte, dataLength)
for i := 0; i < dataLength; i++ {
data[i] = byte(genRand.Int31())
data[i] = byte(rand.Int32())
}

result, localErr := compressFunc(data)
Expand Down
4 changes: 2 additions & 2 deletions exporter/awss3exporter/s3_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"compress/gzip"
"context"
"fmt"
"math/rand"
"math/rand/v2"
"strconv"
"time"

Expand Down Expand Up @@ -37,7 +37,7 @@ func getTimeKey(time time.Time, partition string) string {
}

func randomInRange(low, hi int) int {
return low + rand.Intn(hi-low)
return low + rand.IntN(hi-low)
}

func getS3Key(time time.Time, keyPrefix string, partition string, filePrefix string, metadata string, fileFormat string, compression configcompression.Type) string {
Expand Down
6 changes: 2 additions & 4 deletions exporter/azuredataexplorerexporter/adx_exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package azuredataexplorerexporter // import "github.com/open-telemetry/opentelem
import (
"context"
"io"
"math/rand"
"math/rand/v2"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -163,9 +163,7 @@ func TestIngestedDataRecordCount(t *testing.T) {
ingestOptions: ingestOptions,
logger: logger,
}
source := rand.NewSource(time.Now().UTC().UnixNano())
genRand := rand.New(source)
recordstoingest := genRand.Intn(20)
recordstoingest := rand.IntN(20)
err := adxDataProducer.metricsDataPusher(context.Background(), createMetricsData(recordstoingest))
ingestedrecordsactual := ingestor.Records()
assert.Equal(t, recordstoingest, len(ingestedrecordsactual), "Number of metrics created should match number of records ingested")
Expand Down
6 changes: 2 additions & 4 deletions exporter/clickhouseexporter/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ package clickhouseexporter
import (
"context"
"fmt"
"math/rand"
"strconv"
"testing"
"time"
Expand All @@ -19,6 +18,7 @@ import (
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
"go.opentelemetry.io/collector/pdata/pmetric"
"golang.org/x/exp/rand"
)

func TestIntegration(t *testing.T) {
Expand Down Expand Up @@ -608,7 +608,5 @@ func verifySummaryMetric(t *testing.T, db *sqlx.DB) {
}

func randPort() string {
rs := rand.NewSource(time.Now().Unix())
r := rand.New(rs)
return strconv.Itoa(r.Intn(999) + 9000)
return strconv.Itoa(rand.Intn(999) + 9000)
}
4 changes: 2 additions & 2 deletions exporter/datasetexporter/logs_exporter_stress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"context"
"encoding/json"
"fmt"
"math/rand"
"math/rand/v2"
"net/http"
"net/http/httptest"
"strings"
Expand Down Expand Up @@ -111,7 +111,7 @@ func TestConsumeLogsManyLogsShouldSucceed(t *testing.T) {
log.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))
log.Body().SetStr(key)
log.Attributes().PutStr("key", key)
log.Attributes().PutStr("p1", strings.Repeat("A", rand.Intn(2000)))
log.Attributes().PutStr("p1", strings.Repeat("A", rand.IntN(2000)))
expectedKeys[key] = 1
}
err = logs.ConsumeLogs(context.Background(), batch)
Expand Down
10 changes: 5 additions & 5 deletions exporter/loadbalancingexporter/log_exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package loadbalancingexporter // import "github.com/open-telemetry/opentelemetry

import (
"context"
"math/rand"
"math/rand/v2"
"sync"
"time"

Expand Down Expand Up @@ -135,9 +135,9 @@ func traceIDFromLogs(ld plog.Logs) pcommon.TraceID {
}

func random() pcommon.TraceID {
v1 := uint8(rand.Intn(256))
v2 := uint8(rand.Intn(256))
v3 := uint8(rand.Intn(256))
v4 := uint8(rand.Intn(256))
v1 := uint8(rand.IntN(256))
v2 := uint8(rand.IntN(256))
v3 := uint8(rand.IntN(256))
v4 := uint8(rand.IntN(256))
return [16]byte{v1, v2, v3, v4}
}
14 changes: 7 additions & 7 deletions exporter/loadbalancingexporter/metrics_exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"context"
"errors"
"fmt"
"math/rand"
"math/rand/v2"
"net"
"os"
"path/filepath"
Expand Down Expand Up @@ -876,13 +876,13 @@ func TestRollingUpdatesWhenConsumeMetrics(t *testing.T) {
func randomMetrics(t require.TestingT, rmCount int, smCount int, mCount int, dpCount int) pmetric.Metrics {
md := pmetric.NewMetrics()

timeStamp := pcommon.Timestamp(rand.Intn(256))
value := int64(rand.Intn(256))
timeStamp := pcommon.Timestamp(rand.IntN(256))
value := int64(rand.IntN(256))

for i := 0; i < rmCount; i++ {
rm := md.ResourceMetrics().AppendEmpty()
err := rm.Resource().Attributes().FromRaw(map[string]any{
conventions.AttributeServiceName: fmt.Sprintf("service-%d", rand.Intn(512)),
conventions.AttributeServiceName: fmt.Sprintf("service-%d", rand.IntN(512)),
})
require.NoError(t, err)

Expand All @@ -892,13 +892,13 @@ func randomMetrics(t require.TestingT, rmCount int, smCount int, mCount int, dpC
scope.SetName("MyTestInstrument")
scope.SetVersion("1.2.3")
err = scope.Attributes().FromRaw(map[string]any{
"scope.key": fmt.Sprintf("scope-%d", rand.Intn(512)),
"scope.key": fmt.Sprintf("scope-%d", rand.IntN(512)),
})
require.NoError(t, err)

for k := 0; k < mCount; k++ {
m := sm.Metrics().AppendEmpty()
m.SetName(fmt.Sprintf("metric.%d.test", rand.Intn(512)))
m.SetName(fmt.Sprintf("metric.%d.test", rand.IntN(512)))

sum := m.SetEmptySum()
sum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
Expand All @@ -914,7 +914,7 @@ func randomMetrics(t require.TestingT, rmCount int, smCount int, mCount int, dpC
value += 15

err = dp.Attributes().FromRaw(map[string]any{
"datapoint.key": fmt.Sprintf("dp-%d", rand.Intn(512)),
"datapoint.key": fmt.Sprintf("dp-%d", rand.IntN(512)),
})
require.NoError(t, err)
}
Expand Down
10 changes: 5 additions & 5 deletions exporter/loadbalancingexporter/trace_exporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"context"
"errors"
"fmt"
"math/rand"
"math/rand/v2"
"net"
"path/filepath"
"sync"
Expand Down Expand Up @@ -680,10 +680,10 @@ func BenchmarkConsumeTraces_10E1000T(b *testing.B) {
}

func randomTraces() ptrace.Traces {
v1 := uint8(rand.Intn(256))
v2 := uint8(rand.Intn(256))
v3 := uint8(rand.Intn(256))
v4 := uint8(rand.Intn(256))
v1 := uint8(rand.IntN(256))
v2 := uint8(rand.IntN(256))
v3 := uint8(rand.IntN(256))
v4 := uint8(rand.IntN(256))
traces := ptrace.NewTraces()
appendSimpleTraceWithID(traces.ResourceSpans().AppendEmpty(), [16]byte{v1, v2, v3, v4})
return traces
Expand Down
4 changes: 2 additions & 2 deletions exporter/mezmoexporter/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
package mezmoexporter

import (
"math/rand"
"math/rand/v2"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -51,7 +51,7 @@ const letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
b[i] = letters[rand.IntN(len(letters))]
}
return string(b)
}
13 changes: 6 additions & 7 deletions exporter/otelarrowexporter/internal/arrow/bestofn.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package arrow // import "github.com/open-telemetry/opentelemetry-collector-contr

import (
"context"
"math/rand"
"math/rand/v2"
"runtime"
"sort"
"time"
Expand Down Expand Up @@ -85,8 +85,8 @@ func (lp *bestOfNPrioritizer) downgrade(ctx context.Context) {
}
}

func (lp *bestOfNPrioritizer) sendOne(item writeItem, rnd *rand.Rand, tmp []streamSorter) {
stream := lp.streamFor(item, rnd, tmp)
func (lp *bestOfNPrioritizer) sendOne(item writeItem, tmp []streamSorter) {
stream := lp.streamFor(item, tmp)
writeCh := stream.toWrite
select {
case writeCh <- item:
Expand All @@ -100,13 +100,12 @@ func (lp *bestOfNPrioritizer) sendOne(item writeItem, rnd *rand.Rand, tmp []stre

func (lp *bestOfNPrioritizer) run() {
tmp := make([]streamSorter, len(lp.state))
rnd := rand.New(rand.NewSource(rand.Int63()))
for {
select {
case <-lp.done:
return
case item := <-lp.input:
lp.sendOne(item, rnd, tmp)
lp.sendOne(item, tmp)
}
}
}
Expand Down Expand Up @@ -135,15 +134,15 @@ func (lp *bestOfNPrioritizer) nextWriter() streamWriter {
}
}

func (lp *bestOfNPrioritizer) streamFor(_ writeItem, rnd *rand.Rand, tmp []streamSorter) *streamWorkState {
func (lp *bestOfNPrioritizer) streamFor(_ writeItem, tmp []streamSorter) *streamWorkState {
// Place all streams into the temporary slice.
for idx, item := range lp.state {
tmp[idx].work = item
}
// Select numChoices at random by shifting the selection into the start
// of the temporary slice.
for i := 0; i < lp.numChoices; i++ {
pick := rnd.Intn(lp.numChoices - i)
pick := rand.IntN(lp.numChoices - i)
tmp[i], tmp[i+pick] = tmp[i+pick], tmp[i]
}
for i := 0; i < lp.numChoices; i++ {
Expand Down
Loading
Loading