auto.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. )
  20. var (
  21. // ErrPartialResource is returned by a detector when complete source
  22. // information for a Resource is unavailable or the source information
  23. // contains invalid values that are omitted from the returned Resource.
  24. ErrPartialResource = errors.New("partial resource")
  25. )
  26. // Detector detects OpenTelemetry resource information.
  27. type Detector interface {
  28. // DO NOT CHANGE: any modification will not be backwards compatible and
  29. // must never be done outside of a new major release.
  30. // Detect returns an initialized Resource based on gathered information.
  31. // If the source information to construct a Resource contains invalid
  32. // values, a Resource is returned with the valid parts of the source
  33. // information used for initialization along with an appropriately
  34. // wrapped ErrPartialResource error.
  35. Detect(ctx context.Context) (*Resource, error)
  36. // DO NOT CHANGE: any modification will not be backwards compatible and
  37. // must never be done outside of a new major release.
  38. }
  39. // Detect calls all input detectors sequentially and merges each result with the previous one.
  40. // It returns the merged error too.
  41. func Detect(ctx context.Context, detectors ...Detector) (*Resource, error) {
  42. var autoDetectedRes *Resource
  43. var errInfo []string
  44. for _, detector := range detectors {
  45. if detector == nil {
  46. continue
  47. }
  48. res, err := detector.Detect(ctx)
  49. if err != nil {
  50. errInfo = append(errInfo, err.Error())
  51. if !errors.Is(err, ErrPartialResource) {
  52. continue
  53. }
  54. }
  55. autoDetectedRes, err = Merge(autoDetectedRes, res)
  56. if err != nil {
  57. errInfo = append(errInfo, err.Error())
  58. }
  59. }
  60. var aggregatedError error
  61. if len(errInfo) > 0 {
  62. aggregatedError = fmt.Errorf("detecting resources: %s", errInfo)
  63. }
  64. return autoDetectedRes, aggregatedError
  65. }