init.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // init_once.go contains global initialization/teardown functions that should be called exactly once
  2. // per process.
  3. package imgproxy
  4. import (
  5. "sync"
  6. "sync/atomic"
  7. "github.com/DataDog/datadog-agent/pkg/trace/log"
  8. "github.com/imgproxy/imgproxy/v3/config"
  9. "github.com/imgproxy/imgproxy/v3/config/loadenv"
  10. "github.com/imgproxy/imgproxy/v3/errorreport"
  11. "github.com/imgproxy/imgproxy/v3/gliblog"
  12. "github.com/imgproxy/imgproxy/v3/logger"
  13. "github.com/imgproxy/imgproxy/v3/monitoring"
  14. "github.com/imgproxy/imgproxy/v3/vips"
  15. "go.uber.org/automaxprocs/maxprocs"
  16. )
  17. var (
  18. done atomic.Bool // done indicates that initialization has been performed
  19. once sync.Once // once is used to ensure initialization is performed only once
  20. )
  21. // Init performs the global resources initialization. This should be done once per process.
  22. func Init() error {
  23. var err error
  24. once.Do(func() {
  25. err = initialize()
  26. done.Store(true)
  27. })
  28. return err
  29. }
  30. // Shutdown performs global cleanup
  31. func Shutdown() {
  32. if !done.Load() {
  33. return
  34. }
  35. vips.Shutdown()
  36. monitoring.Stop()
  37. errorreport.Close()
  38. }
  39. // initialize contains the actual initialization logic
  40. func initialize() error {
  41. if err := logger.Init(); err != nil {
  42. return err
  43. }
  44. gliblog.Init()
  45. maxprocs.Set(maxprocs.Logger(log.Debugf))
  46. if err := monitoring.Init(); err != nil {
  47. return err
  48. }
  49. if err := vips.Init(); err != nil {
  50. return err
  51. }
  52. errorreport.Init()
  53. // NOTE: This is temporary workaround. We have to load env vars in config.go before
  54. // actually configuring ImgProxy instance because for now we use it as a source of truth.
  55. // Will be removed once we move env var loading to imgproxy.go
  56. if err := loadenv.Load(); err != nil {
  57. return err
  58. }
  59. if err := config.Configure(); err != nil {
  60. return err
  61. }
  62. // NOTE: End of temporary workaround.
  63. return nil
  64. }