telemetry.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. // Package telemetry provides telemetry information for SFTPGo, such as:
  2. // - health information (for health checks)
  3. // - metrics
  4. // - profiling information
  5. package telemetry
  6. import (
  7. "crypto/tls"
  8. "log"
  9. "net/http"
  10. "path/filepath"
  11. "runtime"
  12. "time"
  13. "github.com/go-chi/chi/v5"
  14. "github.com/drakkan/sftpgo/common"
  15. "github.com/drakkan/sftpgo/logger"
  16. "github.com/drakkan/sftpgo/utils"
  17. )
  18. const (
  19. logSender = "telemetry"
  20. metricsPath = "/metrics"
  21. pprofBasePath = "/debug"
  22. )
  23. var (
  24. router *chi.Mux
  25. httpAuth common.HTTPAuthProvider
  26. certMgr *common.CertManager
  27. )
  28. // Conf telemetry server configuration.
  29. type Conf struct {
  30. // The port used for serving HTTP requests. 0 disable the HTTP server. Default: 10000
  31. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  32. // The address to listen on. A blank value means listen on all available network interfaces. Default: "127.0.0.1"
  33. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  34. // Enable the built-in profiler.
  35. // The profiler will be accessible via HTTP/HTTPS using the base URL "/debug/pprof/"
  36. EnableProfiler bool `json:"enable_profiler" mapstructure:"enable_profiler"`
  37. // Path to a file used to store usernames and password for basic authentication.
  38. // This can be an absolute path or a path relative to the config dir.
  39. // We support HTTP basic authentication and the file format must conform to the one generated using the Apache
  40. // htpasswd tool. The supported password formats are bcrypt ($2y$ prefix) and md5 crypt ($apr1$ prefix).
  41. // If empty HTTP authentication is disabled
  42. AuthUserFile string `json:"auth_user_file" mapstructure:"auth_user_file"`
  43. // If files containing a certificate and matching private key for the server are provided the server will expect
  44. // HTTPS connections.
  45. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  46. // "paramchange" request to the running service on Windows.
  47. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  48. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  49. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  50. // If CipherSuites is nil/empty, a default list of secure cipher suites
  51. // is used, with a preference order based on hardware performance.
  52. // Note that TLS 1.3 ciphersuites are not configurable.
  53. // The supported ciphersuites names are defined here:
  54. //
  55. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L52
  56. //
  57. // any invalid name will be silently ignored.
  58. // The order matters, the ciphers listed first will be the preferred ones.
  59. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  60. }
  61. // ShouldBind returns true if there service must be started
  62. func (c Conf) ShouldBind() bool {
  63. if c.BindPort > 0 {
  64. return true
  65. }
  66. if filepath.IsAbs(c.BindAddress) && runtime.GOOS != "windows" {
  67. return true
  68. }
  69. return false
  70. }
  71. // Initialize configures and starts the telemetry server.
  72. func (c Conf) Initialize(configDir string) error {
  73. var err error
  74. logger.Debug(logSender, "", "initializing telemetry server with config %+v", c)
  75. authUserFile := getConfigPath(c.AuthUserFile, configDir)
  76. httpAuth, err = common.NewBasicAuthProvider(authUserFile)
  77. if err != nil {
  78. return err
  79. }
  80. certificateFile := getConfigPath(c.CertificateFile, configDir)
  81. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  82. initializeRouter(c.EnableProfiler)
  83. httpServer := &http.Server{
  84. Handler: router,
  85. ReadTimeout: 60 * time.Second,
  86. WriteTimeout: 60 * time.Second,
  87. IdleTimeout: 120 * time.Second,
  88. MaxHeaderBytes: 1 << 14, // 16KB
  89. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  90. }
  91. if certificateFile != "" && certificateKeyFile != "" {
  92. certMgr, err = common.NewCertManager(certificateFile, certificateKeyFile, configDir, logSender)
  93. if err != nil {
  94. return err
  95. }
  96. config := &tls.Config{
  97. GetCertificate: certMgr.GetCertificateFunc(),
  98. MinVersion: tls.VersionTLS12,
  99. CipherSuites: utils.GetTLSCiphersFromNames(c.TLSCipherSuites),
  100. PreferServerCipherSuites: true,
  101. }
  102. logger.Debug(logSender, "", "configured TLS cipher suites: %v", config.CipherSuites)
  103. httpServer.TLSConfig = config
  104. return utils.HTTPListenAndServe(httpServer, c.BindAddress, c.BindPort, true, logSender)
  105. }
  106. return utils.HTTPListenAndServe(httpServer, c.BindAddress, c.BindPort, false, logSender)
  107. }
  108. // ReloadCertificateMgr reloads the certificate manager
  109. func ReloadCertificateMgr() error {
  110. if certMgr != nil {
  111. return certMgr.Reload()
  112. }
  113. return nil
  114. }
  115. func getConfigPath(name, configDir string) string {
  116. if !utils.IsFileInputValid(name) {
  117. return ""
  118. }
  119. if name != "" && !filepath.IsAbs(name) {
  120. return filepath.Join(configDir, name)
  121. }
  122. return name
  123. }