resource.go 7.6 KB

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