Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

128 linhas
4.9 KiB

  1. package main
  2. import (
  3. "context"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "time"
  8. "github.com/golang/gddo/database"
  9. "github.com/golang/gddo/log"
  10. "github.com/spf13/pflag"
  11. "github.com/spf13/viper"
  12. )
  13. const (
  14. gaeProjectEnvVar = "GAE_LONG_APP_ID"
  15. )
  16. const (
  17. ConfigMaxAge = "max_age"
  18. ConfigGetTimeout = "get_timeout"
  19. ConfigRobotThreshold = "robot"
  20. ConfigAssetsDir = "assets"
  21. ConfigFirstGetTimeout = "first_get_timeout"
  22. ConfigBindAddress = "http"
  23. ConfigProject = "project"
  24. ConfigTrustProxyHeaders = "trust_proxy_headers"
  25. ConfigSidebar = "sidebar"
  26. ConfigDefaultGOOS = "default_goos"
  27. ConfigSourcegraphURL = "sourcegraph_url"
  28. ConfigGithubInterval = "github_interval"
  29. ConfigCrawlInterval = "crawl_interval"
  30. ConfigDialTimeout = "dial_timeout"
  31. ConfigRequestTimeout = "request_timeout"
  32. )
  33. // Initialize configuration
  34. func init() {
  35. ctx := context.Background()
  36. // Automatically detect if we are on App Engine.
  37. if os.Getenv(gaeProjectEnvVar) != "" {
  38. viper.Set("on_appengine", true)
  39. } else {
  40. viper.Set("on_appengine", false)
  41. }
  42. // Setup command line flags
  43. flags := buildFlags()
  44. flags.Parse(os.Args)
  45. if err := viper.BindPFlags(flags); err != nil {
  46. panic(err)
  47. }
  48. // Also fetch from enviorment
  49. viper.SetEnvPrefix("gddo")
  50. viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
  51. viper.AutomaticEnv()
  52. // Automatically get project ID from env on Google App Engine
  53. viper.BindEnv(ConfigProject, gaeProjectEnvVar)
  54. // Read from config.
  55. readViperConfig(ctx)
  56. log.Info(ctx, "config values loaded", "values", viper.AllSettings())
  57. }
  58. func buildFlags() *pflag.FlagSet {
  59. flags := pflag.NewFlagSet("default", pflag.ExitOnError)
  60. flags.StringP("config", "c", "", "path to motd config file")
  61. flags.String("project", "", "Google Cloud Platform project used for Google services")
  62. // TODO(stephenmw): flags.Bool("enable-admin-pages", false, "When true, enables /admin pages")
  63. flags.Float64(ConfigRobotThreshold, 100, "Request counter threshold for robots.")
  64. flags.String(ConfigAssetsDir, filepath.Join(defaultBase("github.com/golang/gddo/gddo-server"), "assets"), "Base directory for templates and static files.")
  65. flags.Duration(ConfigGetTimeout, 8*time.Second, "Time to wait for package update from the VCS.")
  66. flags.Duration(ConfigFirstGetTimeout, 5*time.Second, "Time to wait for first fetch of package from the VCS.")
  67. flags.Duration(ConfigMaxAge, 24*time.Hour, "Update package documents older than this age.")
  68. flags.String(ConfigBindAddress, ":8080", "Listen for HTTP connections on this address.")
  69. flags.Bool(ConfigSidebar, false, "Enable package page sidebar.")
  70. flags.String(ConfigDefaultGOOS, "", "Default GOOS to use when building package documents.")
  71. flags.Bool(ConfigTrustProxyHeaders, false, "If enabled, identify the remote address of the request using X-Real-Ip in header.")
  72. flags.String(ConfigSourcegraphURL, "https://sourcegraph.com", "Link to global uses on Sourcegraph based at this URL (no need for trailing slash).")
  73. flags.Duration(ConfigGithubInterval, 0, "Github updates crawler sleeps for this duration between fetches. Zero disables the crawler.")
  74. flags.Duration(ConfigCrawlInterval, 0, "Package updater sleeps for this duration between package updates. Zero disables updates.")
  75. flags.Duration(ConfigDialTimeout, 5*time.Second, "Timeout for dialing an HTTP connection.")
  76. flags.Duration(ConfigRequestTimeout, 20*time.Second, "Time out for roundtripping an HTTP request.")
  77. // TODO(stephenmw): pass these variables at database creation time.
  78. flags.StringVar(&database.RedisServer, "db-server", database.RedisServer, "URI of Redis server.")
  79. flags.DurationVar(&database.RedisIdleTimeout, "db-idle-timeout", database.RedisIdleTimeout, "Close Redis connections after remaining idle for this duration.")
  80. flags.BoolVar(&database.RedisLog, "db-log", database.RedisLog, "Log database commands")
  81. return flags
  82. }
  83. // readViperConfig finds and then parses a config file. It will log.Fatal if the
  84. // config file was specified or could not parse. Otherwise it will only warn
  85. // that it failed to load the config.
  86. func readViperConfig(ctx context.Context) {
  87. viper.AddConfigPath(".")
  88. viper.AddConfigPath("/etc")
  89. viper.SetConfigName("gddo")
  90. if viper.GetString("config") != "" {
  91. viper.SetConfigFile(viper.GetString("config"))
  92. }
  93. if err := viper.ReadInConfig(); err != nil {
  94. // If a config exists but could not be parsed, we should bail.
  95. if _, ok := err.(viper.ConfigParseError); ok {
  96. log.Fatal(ctx, "failed to parse config", "error", err)
  97. }
  98. // If the user specified a config file location in flags or env and
  99. // we failed to load it, we should bail. If not, it is just a warning.
  100. if viper.GetString("config") != "" {
  101. log.Fatal(ctx, "failed to load configuration file", "error", err)
  102. } else {
  103. log.Warn(ctx, "failed to load configuration file", "error", err)
  104. }
  105. } else {
  106. log.Info(ctx, "loaded configuration file successfully", "path", viper.ConfigFileUsed())
  107. }
  108. }