scraper.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package filestatsreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/filestatsreceiver"
  4. import (
  5. "context"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. "github.com/bmatcuk/doublestar/v4"
  10. "go.opentelemetry.io/collector/pdata/pcommon"
  11. "go.opentelemetry.io/collector/pdata/pmetric"
  12. "go.opentelemetry.io/collector/receiver"
  13. "go.opentelemetry.io/collector/receiver/scrapererror"
  14. "go.uber.org/multierr"
  15. "go.uber.org/zap"
  16. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/filestatsreceiver/internal/metadata"
  17. )
  18. type scraper struct {
  19. include string
  20. logger *zap.Logger
  21. mb *metadata.MetricsBuilder
  22. }
  23. func (s *scraper) scrape(_ context.Context) (pmetric.Metrics, error) {
  24. matches, err := doublestar.FilepathGlob(s.include)
  25. if err != nil {
  26. return pmetric.NewMetrics(), err
  27. }
  28. var scrapeErrors []error
  29. now := pcommon.NewTimestampFromTime(time.Now())
  30. for _, match := range matches {
  31. fileinfo, err := os.Stat(match)
  32. if err != nil {
  33. scrapeErrors = append(scrapeErrors, err)
  34. continue
  35. }
  36. path, err := filepath.Abs(fileinfo.Name())
  37. if err != nil {
  38. scrapeErrors = append(scrapeErrors, err)
  39. continue
  40. }
  41. s.mb.RecordFileSizeDataPoint(now, fileinfo.Size())
  42. s.mb.RecordFileMtimeDataPoint(now, fileinfo.ModTime().Unix())
  43. collectStats(now, fileinfo, s.mb, s.logger)
  44. rb := s.mb.NewResourceBuilder()
  45. rb.SetFileName(fileinfo.Name())
  46. rb.SetFilePath(path)
  47. s.mb.EmitForResource(metadata.WithResource(rb.Emit()))
  48. }
  49. if len(scrapeErrors) > 0 {
  50. return s.mb.Emit(), scrapererror.NewPartialScrapeError(multierr.Combine(scrapeErrors...), len(scrapeErrors))
  51. }
  52. return s.mb.Emit(), nil
  53. }
  54. func newScraper(cfg *Config, settings receiver.CreateSettings) *scraper {
  55. return &scraper{
  56. include: cfg.Include,
  57. logger: settings.TelemetrySettings.Logger,
  58. mb: metadata.NewMetricsBuilder(cfg.MetricsBuilderConfig, settings),
  59. }
  60. }