...

Source file src/go.opentelemetry.io/otel/sdk/resource/resource.go

Documentation: go.opentelemetry.io/otel/sdk/resource

     1  // Copyright The OpenTelemetry Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package resource // import "go.opentelemetry.io/otel/sdk/resource"
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"sync"
    21  
    22  	"go.opentelemetry.io/otel"
    23  	"go.opentelemetry.io/otel/attribute"
    24  )
    25  
    26  // Resource describes an entity about which identifying information
    27  // and metadata is exposed.  Resource is an immutable object,
    28  // equivalent to a map from key to unique value.
    29  //
    30  // Resources should be passed and stored as pointers
    31  // (`*resource.Resource`).  The `nil` value is equivalent to an empty
    32  // Resource.
    33  type Resource struct {
    34  	attrs     attribute.Set
    35  	schemaURL string
    36  }
    37  
    38  var (
    39  	defaultResource     *Resource
    40  	defaultResourceOnce sync.Once
    41  )
    42  
    43  var errMergeConflictSchemaURL = errors.New("cannot merge resource due to conflicting Schema URL")
    44  
    45  // New returns a Resource combined from the user-provided detectors.
    46  func New(ctx context.Context, opts ...Option) (*Resource, error) {
    47  	cfg := config{}
    48  	for _, opt := range opts {
    49  		cfg = opt.apply(cfg)
    50  	}
    51  
    52  	r := &Resource{schemaURL: cfg.schemaURL}
    53  	return r, detect(ctx, r, cfg.detectors)
    54  }
    55  
    56  // NewWithAttributes creates a resource from attrs and associates the resource with a
    57  // schema URL. If attrs contains duplicate keys, the last value will be used. If attrs
    58  // contains any invalid items those items will be dropped. The attrs are assumed to be
    59  // in a schema identified by schemaURL.
    60  func NewWithAttributes(schemaURL string, attrs ...attribute.KeyValue) *Resource {
    61  	resource := NewSchemaless(attrs...)
    62  	resource.schemaURL = schemaURL
    63  	return resource
    64  }
    65  
    66  // NewSchemaless creates a resource from attrs. If attrs contains duplicate keys,
    67  // the last value will be used. If attrs contains any invalid items those items will
    68  // be dropped. The resource will not be associated with a schema URL. If the schema
    69  // of the attrs is known use NewWithAttributes instead.
    70  func NewSchemaless(attrs ...attribute.KeyValue) *Resource {
    71  	if len(attrs) == 0 {
    72  		return &Resource{}
    73  	}
    74  
    75  	// Ensure attributes comply with the specification:
    76  	// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/common/README.md#attribute
    77  	s, _ := attribute.NewSetWithFiltered(attrs, func(kv attribute.KeyValue) bool {
    78  		return kv.Valid()
    79  	})
    80  
    81  	// If attrs only contains invalid entries do not allocate a new resource.
    82  	if s.Len() == 0 {
    83  		return &Resource{}
    84  	}
    85  
    86  	return &Resource{attrs: s} //nolint
    87  }
    88  
    89  // String implements the Stringer interface and provides a
    90  // human-readable form of the resource.
    91  //
    92  // Avoid using this representation as the key in a map of resources,
    93  // use Equivalent() as the key instead.
    94  func (r *Resource) String() string {
    95  	if r == nil {
    96  		return ""
    97  	}
    98  	return r.attrs.Encoded(attribute.DefaultEncoder())
    99  }
   100  
   101  // MarshalLog is the marshaling function used by the logging system to represent this exporter.
   102  func (r *Resource) MarshalLog() interface{} {
   103  	return struct {
   104  		Attributes attribute.Set
   105  		SchemaURL  string
   106  	}{
   107  		Attributes: r.attrs,
   108  		SchemaURL:  r.schemaURL,
   109  	}
   110  }
   111  
   112  // Attributes returns a copy of attributes from the resource in a sorted order.
   113  // To avoid allocating a new slice, use an iterator.
   114  func (r *Resource) Attributes() []attribute.KeyValue {
   115  	if r == nil {
   116  		r = Empty()
   117  	}
   118  	return r.attrs.ToSlice()
   119  }
   120  
   121  // SchemaURL returns the schema URL associated with Resource r.
   122  func (r *Resource) SchemaURL() string {
   123  	if r == nil {
   124  		return ""
   125  	}
   126  	return r.schemaURL
   127  }
   128  
   129  // Iter returns an iterator of the Resource attributes.
   130  // This is ideal to use if you do not want a copy of the attributes.
   131  func (r *Resource) Iter() attribute.Iterator {
   132  	if r == nil {
   133  		r = Empty()
   134  	}
   135  	return r.attrs.Iter()
   136  }
   137  
   138  // Equal returns true when a Resource is equivalent to this Resource.
   139  func (r *Resource) Equal(eq *Resource) bool {
   140  	if r == nil {
   141  		r = Empty()
   142  	}
   143  	if eq == nil {
   144  		eq = Empty()
   145  	}
   146  	return r.Equivalent() == eq.Equivalent()
   147  }
   148  
   149  // Merge creates a new resource by combining resource a and b.
   150  //
   151  // If there are common keys between resource a and b, then the value
   152  // from resource b will overwrite the value from resource a, even
   153  // if resource b's value is empty.
   154  //
   155  // The SchemaURL of the resources will be merged according to the spec rules:
   156  // https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/resource/sdk.md#merge
   157  // If the resources have different non-empty schemaURL an empty resource and an error
   158  // will be returned.
   159  func Merge(a, b *Resource) (*Resource, error) {
   160  	if a == nil && b == nil {
   161  		return Empty(), nil
   162  	}
   163  	if a == nil {
   164  		return b, nil
   165  	}
   166  	if b == nil {
   167  		return a, nil
   168  	}
   169  
   170  	// Merge the schema URL.
   171  	var schemaURL string
   172  	switch true {
   173  	case a.schemaURL == "":
   174  		schemaURL = b.schemaURL
   175  	case b.schemaURL == "":
   176  		schemaURL = a.schemaURL
   177  	case a.schemaURL == b.schemaURL:
   178  		schemaURL = a.schemaURL
   179  	default:
   180  		return Empty(), errMergeConflictSchemaURL
   181  	}
   182  
   183  	// Note: 'b' attributes will overwrite 'a' with last-value-wins in attribute.Key()
   184  	// Meaning this is equivalent to: append(a.Attributes(), b.Attributes()...)
   185  	mi := attribute.NewMergeIterator(b.Set(), a.Set())
   186  	combine := make([]attribute.KeyValue, 0, a.Len()+b.Len())
   187  	for mi.Next() {
   188  		combine = append(combine, mi.Attribute())
   189  	}
   190  	merged := NewWithAttributes(schemaURL, combine...)
   191  	return merged, nil
   192  }
   193  
   194  // Empty returns an instance of Resource with no attributes. It is
   195  // equivalent to a `nil` Resource.
   196  func Empty() *Resource {
   197  	return &Resource{}
   198  }
   199  
   200  // Default returns an instance of Resource with a default
   201  // "service.name" and OpenTelemetrySDK attributes.
   202  func Default() *Resource {
   203  	defaultResourceOnce.Do(func() {
   204  		var err error
   205  		defaultResource, err = Detect(
   206  			context.Background(),
   207  			defaultServiceNameDetector{},
   208  			fromEnv{},
   209  			telemetrySDK{},
   210  		)
   211  		if err != nil {
   212  			otel.Handle(err)
   213  		}
   214  		// If Detect did not return a valid resource, fall back to emptyResource.
   215  		if defaultResource == nil {
   216  			defaultResource = &Resource{}
   217  		}
   218  	})
   219  	return defaultResource
   220  }
   221  
   222  // Environment returns an instance of Resource with attributes
   223  // extracted from the OTEL_RESOURCE_ATTRIBUTES environment variable.
   224  func Environment() *Resource {
   225  	detector := &fromEnv{}
   226  	resource, err := detector.Detect(context.Background())
   227  	if err != nil {
   228  		otel.Handle(err)
   229  	}
   230  	return resource
   231  }
   232  
   233  // Equivalent returns an object that can be compared for equality
   234  // between two resources. This value is suitable for use as a key in
   235  // a map.
   236  func (r *Resource) Equivalent() attribute.Distinct {
   237  	return r.Set().Equivalent()
   238  }
   239  
   240  // Set returns the equivalent *attribute.Set of this resource's attributes.
   241  func (r *Resource) Set() *attribute.Set {
   242  	if r == nil {
   243  		r = Empty()
   244  	}
   245  	return &r.attrs
   246  }
   247  
   248  // MarshalJSON encodes the resource attributes as a JSON list of { "Key":
   249  // "...", "Value": ... } pairs in order sorted by key.
   250  func (r *Resource) MarshalJSON() ([]byte, error) {
   251  	if r == nil {
   252  		r = Empty()
   253  	}
   254  	return r.attrs.MarshalJSON()
   255  }
   256  
   257  // Len returns the number of unique key-values in this Resource.
   258  func (r *Resource) Len() int {
   259  	if r == nil {
   260  		return 0
   261  	}
   262  	return r.attrs.Len()
   263  }
   264  
   265  // Encoded returns an encoded representation of the resource.
   266  func (r *Resource) Encoded(enc attribute.Encoder) string {
   267  	if r == nil {
   268  		return ""
   269  	}
   270  	return r.attrs.Encoded(enc)
   271  }
   272  

View as plain text