telemetry.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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/v2/common"
  15. "github.com/drakkan/sftpgo/v2/logger"
  16. "github.com/drakkan/sftpgo/v2/util"
  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: 0
  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. // Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
  61. MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
  62. }
  63. // ShouldBind returns true if there service must be started
  64. func (c Conf) ShouldBind() bool {
  65. if c.BindPort > 0 {
  66. return true
  67. }
  68. if filepath.IsAbs(c.BindAddress) && runtime.GOOS != "windows" {
  69. return true
  70. }
  71. return false
  72. }
  73. // Initialize configures and starts the telemetry server.
  74. func (c Conf) Initialize(configDir string) error {
  75. var err error
  76. logger.Info(logSender, "", "initializing telemetry server with config %+v", c)
  77. authUserFile := getConfigPath(c.AuthUserFile, configDir)
  78. httpAuth, err = common.NewBasicAuthProvider(authUserFile)
  79. if err != nil {
  80. return err
  81. }
  82. certificateFile := getConfigPath(c.CertificateFile, configDir)
  83. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  84. initializeRouter(c.EnableProfiler)
  85. httpServer := &http.Server{
  86. Handler: router,
  87. ReadHeaderTimeout: 30 * time.Second,
  88. ReadTimeout: 60 * time.Second,
  89. WriteTimeout: 60 * time.Second,
  90. IdleTimeout: 60 * time.Second,
  91. MaxHeaderBytes: 1 << 14, // 16KB
  92. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  93. }
  94. if certificateFile != "" && certificateKeyFile != "" {
  95. certMgr, err = common.NewCertManager(certificateFile, certificateKeyFile, configDir, logSender)
  96. if err != nil {
  97. return err
  98. }
  99. config := &tls.Config{
  100. GetCertificate: certMgr.GetCertificateFunc(),
  101. MinVersion: util.GetTLSVersion(c.MinTLSVersion),
  102. NextProtos: []string{"http/1.1", "h2"},
  103. CipherSuites: util.GetTLSCiphersFromNames(c.TLSCipherSuites),
  104. PreferServerCipherSuites: true,
  105. }
  106. logger.Debug(logSender, "", "configured TLS cipher suites: %v", config.CipherSuites)
  107. httpServer.TLSConfig = config
  108. return util.HTTPListenAndServe(httpServer, c.BindAddress, c.BindPort, true, logSender)
  109. }
  110. return util.HTTPListenAndServe(httpServer, c.BindAddress, c.BindPort, false, logSender)
  111. }
  112. // ReloadCertificateMgr reloads the certificate manager
  113. func ReloadCertificateMgr() error {
  114. if certMgr != nil {
  115. return certMgr.Reload()
  116. }
  117. return nil
  118. }
  119. func getConfigPath(name, configDir string) string {
  120. if !util.IsFileInputValid(name) {
  121. return ""
  122. }
  123. if name != "" && !filepath.IsAbs(name) {
  124. return filepath.Join(configDir, name)
  125. }
  126. return name
  127. }