resource.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // SchemaURL returns the schema URL associated with Resource r.
  114. func (r *Resource) SchemaURL() string {
  115. if r == nil {
  116. return ""
  117. }
  118. return r.schemaURL
  119. }
  120. // Iter returns an iterator of the Resource attributes.
  121. // This is ideal to use if you do not want a copy of the attributes.
  122. func (r *Resource) Iter() attribute.Iterator {
  123. if r == nil {
  124. r = Empty()
  125. }
  126. return r.attrs.Iter()
  127. }
  128. // Equal returns true when a Resource is equivalent to this Resource.
  129. func (r *Resource) Equal(eq *Resource) bool {
  130. if r == nil {
  131. r = Empty()
  132. }
  133. if eq == nil {
  134. eq = Empty()
  135. }
  136. return r.Equivalent() == eq.Equivalent()
  137. }
  138. // Merge creates a new resource by combining resource a and b.
  139. //
  140. // If there are common keys between resource a and b, then the value
  141. // from resource b will overwrite the value from resource a, even
  142. // if resource b's value is empty.
  143. //
  144. // The SchemaURL of the resources will be merged according to the spec rules:
  145. // https://github.com/open-telemetry/opentelemetry-specification/blob/bad49c714a62da5493f2d1d9bafd7ebe8c8ce7eb/specification/resource/sdk.md#merge
  146. // If the resources have different non-empty schemaURL an empty resource and an error
  147. // will be returned.
  148. func Merge(a, b *Resource) (*Resource, error) {
  149. if a == nil && b == nil {
  150. return Empty(), nil
  151. }
  152. if a == nil {
  153. return b, nil
  154. }
  155. if b == nil {
  156. return a, nil
  157. }
  158. // Merge the schema URL.
  159. var schemaURL string
  160. switch true {
  161. case a.schemaURL == "":
  162. schemaURL = b.schemaURL
  163. case b.schemaURL == "":
  164. schemaURL = a.schemaURL
  165. case a.schemaURL == b.schemaURL:
  166. schemaURL = a.schemaURL
  167. default:
  168. return Empty(), errMergeConflictSchemaURL
  169. }
  170. // Note: 'b' attributes will overwrite 'a' with last-value-wins in attribute.Key()
  171. // Meaning this is equivalent to: append(a.Attributes(), b.Attributes()...)
  172. mi := attribute.NewMergeIterator(b.Set(), a.Set())
  173. combine := make([]attribute.KeyValue, 0, a.Len()+b.Len())
  174. for mi.Next() {
  175. combine = append(combine, mi.Attribute())
  176. }
  177. merged := NewWithAttributes(schemaURL, combine...)
  178. return merged, nil
  179. }
  180. // Empty returns an instance of Resource with no attributes. It is
  181. // equivalent to a `nil` Resource.
  182. func Empty() *Resource {
  183. return &emptyResource
  184. }
  185. // Default returns an instance of Resource with a default
  186. // "service.name" and OpenTelemetrySDK attributes.
  187. func Default() *Resource {
  188. defaultResourceOnce.Do(func() {
  189. var err error
  190. defaultResource, err = Detect(
  191. context.Background(),
  192. defaultServiceNameDetector{},
  193. fromEnv{},
  194. telemetrySDK{},
  195. )
  196. if err != nil {
  197. otel.Handle(err)
  198. }
  199. // If Detect did not return a valid resource, fall back to emptyResource.
  200. if defaultResource == nil {
  201. defaultResource = &emptyResource
  202. }
  203. })
  204. return defaultResource
  205. }
  206. // Environment returns an instance of Resource with attributes
  207. // extracted from the OTEL_RESOURCE_ATTRIBUTES environment variable.
  208. func Environment() *Resource {
  209. detector := &fromEnv{}
  210. resource, err := detector.Detect(context.Background())
  211. if err != nil {
  212. otel.Handle(err)
  213. }
  214. return resource
  215. }
  216. // Equivalent returns an object that can be compared for equality
  217. // between two resources. This value is suitable for use as a key in
  218. // a map.
  219. func (r *Resource) Equivalent() attribute.Distinct {
  220. return r.Set().Equivalent()
  221. }
  222. // Set returns the equivalent *attribute.Set of this resource's attributes.
  223. func (r *Resource) Set() *attribute.Set {
  224. if r == nil {
  225. r = Empty()
  226. }
  227. return &r.attrs
  228. }
  229. // MarshalJSON encodes the resource attributes as a JSON list of { "Key":
  230. // "...", "Value": ... } pairs in order sorted by key.
  231. func (r *Resource) MarshalJSON() ([]byte, error) {
  232. if r == nil {
  233. r = Empty()
  234. }
  235. return r.attrs.MarshalJSON()
  236. }
  237. // Len returns the number of unique key-values in this Resource.
  238. func (r *Resource) Len() int {
  239. if r == nil {
  240. return 0
  241. }
  242. return r.attrs.Len()
  243. }
  244. // Encoded returns an encoded representation of the resource.
  245. func (r *Resource) Encoded(enc attribute.Encoder) string {
  246. if r == nil {
  247. return ""
  248. }
  249. return r.attrs.Encoded(enc)
  250. }