Skip to content

Commit

Permalink
Fix ASAN bug with emptyAttributes.
Browse files Browse the repository at this point in the history
If mutliple instantiations of a Resources struct are happening
in parallel, they can end up modifying the same underlying resource.
  • Loading branch information
jaredjenkins committed Aug 4, 2023
1 parent f67ecb3 commit eb02f96
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 4 additions & 5 deletions sdk/resource/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ type Resource struct {
}

var (
emptyResource Resource
defaultResource *Resource
defaultResourceOnce sync.Once
)
Expand Down Expand Up @@ -70,7 +69,7 @@ func NewWithAttributes(schemaURL string, attrs ...attribute.KeyValue) *Resource
// of the attrs is known use NewWithAttributes instead.
func NewSchemaless(attrs ...attribute.KeyValue) *Resource {
if len(attrs) == 0 {
return &emptyResource
return &Resource{}
}

// Ensure attributes comply with the specification:
Expand All @@ -81,7 +80,7 @@ func NewSchemaless(attrs ...attribute.KeyValue) *Resource {

// If attrs only contains invalid entries do not allocate a new resource.
if s.Len() == 0 {
return &emptyResource
return &Resource{}
}

return &Resource{attrs: s} //nolint
Expand Down Expand Up @@ -195,7 +194,7 @@ func Merge(a, b *Resource) (*Resource, error) {
// Empty returns an instance of Resource with no attributes. It is
// equivalent to a `nil` Resource.
func Empty() *Resource {
return &emptyResource
return &Resource{}
}

// Default returns an instance of Resource with a default
Expand All @@ -214,7 +213,7 @@ func Default() *Resource {
}
// If Detect did not return a valid resource, fall back to emptyResource.
if defaultResource == nil {
defaultResource = &emptyResource
defaultResource = &Resource{}
}
})
return defaultResource
Expand Down
4 changes: 4 additions & 0 deletions sdk/resource/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ func TestNewWithAttributes(t *testing.T) {
}
for _, c := range cases {
t.Run(fmt.Sprintf("case-%s", c.name), func(t *testing.T) {
// Run ctors in parallel to verify that there is no
// race condition.
t.Parallel()

res := resource.NewSchemaless(c.in...)
if diff := cmp.Diff(
res.Attributes(),
Expand Down

0 comments on commit eb02f96

Please sign in to comment.