resource.go 7.8 KB

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