You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

229 lines
6.1 KiB

10 years ago
  1. /*
  2. * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package main
  17. import (
  18. "fmt"
  19. "os"
  20. "runtime"
  21. "sort"
  22. "strconv"
  23. "github.com/dustin/go-humanize"
  24. "github.com/minio/cli"
  25. "github.com/minio/mc/pkg/console"
  26. "github.com/minio/minio/pkg/probe"
  27. "github.com/olekukonko/ts"
  28. )
  29. var (
  30. // global flags for minio.
  31. minioFlags = []cli.Flag{
  32. cli.BoolFlag{
  33. Name: "help, h",
  34. Usage: "Show help.",
  35. },
  36. }
  37. )
  38. // Help template for minio.
  39. var minioHelpTemplate = `NAME:
  40. {{.Name}} - {{.Usage}}
  41. DESCRIPTION:
  42. {{.Description}}
  43. USAGE:
  44. minio {{if .Flags}}[flags] {{end}}command{{if .Flags}}{{end}} [arguments...]
  45. COMMANDS:
  46. {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
  47. {{end}}{{if .Flags}}
  48. FLAGS:
  49. {{range .Flags}}{{.}}
  50. {{end}}{{end}}
  51. VERSION:
  52. ` + minioVersion +
  53. `{{ "\n"}}{{range $key, $value := ExtraInfo}}
  54. {{$key}}:
  55. {{$value}}
  56. {{end}}`
  57. // init - check the environment before main starts
  58. func init() {
  59. // Check if minio was compiled using a supported version of Golang.
  60. checkGoVersion()
  61. // It is an unsafe practice to run network services as
  62. // root. Containers are an exception.
  63. if !isContainerized() && os.Geteuid() == 0 {
  64. console.Fatalln("Please run ‘minio’ as a non-root user.")
  65. }
  66. }
  67. func migrate() {
  68. // Migrate config file
  69. migrateConfig()
  70. // Migrate other configs here.
  71. }
  72. func enableLoggers() {
  73. // Enable all loggers here.
  74. enableConsoleLogger()
  75. // Add your logger here.
  76. }
  77. // Tries to get os/arch/platform specific information
  78. // Returns a map of current os/arch/platform/memstats
  79. func getSystemData() map[string]string {
  80. host, err := os.Hostname()
  81. if err != nil {
  82. host = ""
  83. }
  84. memstats := &runtime.MemStats{}
  85. runtime.ReadMemStats(memstats)
  86. mem := fmt.Sprintf("Used: %s | Allocated: %s | Used-Heap: %s | Allocated-Heap: %s",
  87. humanize.Bytes(memstats.Alloc),
  88. humanize.Bytes(memstats.TotalAlloc),
  89. humanize.Bytes(memstats.HeapAlloc),
  90. humanize.Bytes(memstats.HeapSys))
  91. platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s",
  92. host,
  93. runtime.GOOS,
  94. runtime.GOARCH)
  95. goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU()))
  96. return map[string]string{
  97. "PLATFORM": platform,
  98. "RUNTIME": goruntime,
  99. "MEM": mem,
  100. }
  101. }
  102. func findClosestCommands(command string) []string {
  103. var closestCommands []string
  104. for _, value := range commandsTree.PrefixMatch(command) {
  105. closestCommands = append(closestCommands, value.(string))
  106. }
  107. sort.Strings(closestCommands)
  108. // Suggest other close commands - allow missed, wrongly added and
  109. // even transposed characters
  110. for _, value := range commandsTree.walk(commandsTree.root) {
  111. if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) {
  112. continue
  113. }
  114. // 2 is arbitrary and represents the max
  115. // allowed number of typed errors
  116. if DamerauLevenshteinDistance(command, value.(string)) < 2 {
  117. closestCommands = append(closestCommands, value.(string))
  118. }
  119. }
  120. return closestCommands
  121. }
  122. func registerApp() *cli.App {
  123. // Register all commands.
  124. registerCommand(serverCmd)
  125. registerCommand(versionCmd)
  126. registerCommand(updateCmd)
  127. // Set up app.
  128. app := cli.NewApp()
  129. app.Name = "Minio"
  130. app.Author = "Minio.io"
  131. app.Usage = "Distributed Object Storage Server for Micro Services."
  132. app.Description = `Micro services environment provisions one Minio server per application instance. Scalability is achieved through large number of smaller personalized instances. This version of the Minio binary is built using Filesystem storage backend for magnetic and solid state disks.`
  133. app.Flags = append(minioFlags, globalFlags...)
  134. app.Commands = commands
  135. app.CustomAppHelpTemplate = minioHelpTemplate
  136. app.CommandNotFound = func(ctx *cli.Context, command string) {
  137. msg := fmt.Sprintf("‘%s’ is not a minio sub-command. See ‘minio --help’.", command)
  138. closestCommands := findClosestCommands(command)
  139. if len(closestCommands) > 0 {
  140. msg += fmt.Sprintf("\n\nDid you mean one of these?\n")
  141. for _, cmd := range closestCommands {
  142. msg += fmt.Sprintf(" ‘%s’\n", cmd)
  143. }
  144. }
  145. console.Fatalln(msg)
  146. }
  147. return app
  148. }
  149. func checkMainSyntax(c *cli.Context) {
  150. configPath, err := getConfigPath()
  151. if err != nil {
  152. console.Fatalf("Unable to obtain user's home directory. \nError: %s\n", err)
  153. }
  154. if configPath == "" {
  155. console.Fatalln("Config folder cannot be empty, please specify --config-dir <foldername>.")
  156. }
  157. }
  158. func main() {
  159. probe.Init() // Set project's root source path.
  160. probe.SetAppInfo("Release-Tag", minioReleaseTag)
  161. probe.SetAppInfo("Commit-ID", minioShortCommitID)
  162. app := registerApp()
  163. app.Before = func(c *cli.Context) error {
  164. // Set global flags.
  165. setGlobalsFromContext(c)
  166. // Sets new config folder.
  167. setGlobalConfigPath(c.GlobalString("config-dir"))
  168. // Valid input arguments to main.
  169. checkMainSyntax(c)
  170. // Migrate any old version of config / state files to newer format.
  171. migrate()
  172. // Initialize config.
  173. err := initConfig()
  174. fatalIf(err.Trace(), "Unable to initialize minio config.", nil)
  175. // Enable all loggers by now.
  176. enableLoggers()
  177. // Do not print update messages, if quiet flag is set.
  178. if !globalQuiet {
  179. // Do not print any errors in release update function.
  180. noError := true
  181. updateMsg := getReleaseUpdate(minioUpdateStableURL, noError)
  182. if updateMsg.Update {
  183. console.Println(updateMsg)
  184. }
  185. }
  186. // Return here.
  187. return nil
  188. }
  189. app.ExtraInfo = func() map[string]string {
  190. if _, e := ts.GetSize(); e != nil {
  191. globalQuiet = true
  192. }
  193. // Enable if debug is enabled.
  194. if globalDebug {
  195. return getSystemData()
  196. }
  197. return make(map[string]string)
  198. }
  199. // Run the app - exit on error.
  200. app.RunAndExitOnError()
  201. }