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.

223 lines
4.2 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  1. package main
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "log"
  8. "math/rand"
  9. "net/http"
  10. "os"
  11. "strings"
  12. "sync"
  13. "text/template"
  14. "time"
  15. "unicode"
  16. "unicode/utf8"
  17. )
  18. var IsDebug *bool
  19. var server *string
  20. var commands = []*Command{
  21. cmdFix,
  22. cmdMaster,
  23. cmdUpload,
  24. cmdShell,
  25. cmdVersion,
  26. cmdVolume,
  27. cmdExport,
  28. }
  29. var exitStatus = 0
  30. var exitMu sync.Mutex
  31. func setExitStatus(n int) {
  32. exitMu.Lock()
  33. if exitStatus < n {
  34. exitStatus = n
  35. }
  36. exitMu.Unlock()
  37. }
  38. func main() {
  39. rand.Seed(time.Now().UnixNano())
  40. flag.Usage = usage
  41. flag.Parse()
  42. args := flag.Args()
  43. if len(args) < 1 {
  44. usage()
  45. }
  46. if args[0] == "help" {
  47. help(args[1:])
  48. for _, cmd := range commands {
  49. if len(args) >= 2 && cmd.Name() == args[1] && cmd.Run != nil {
  50. fmt.Fprintf(os.Stderr, "Default Parameters:\n")
  51. cmd.Flag.PrintDefaults()
  52. }
  53. }
  54. return
  55. }
  56. for _, cmd := range commands {
  57. if cmd.Name() == args[0] && cmd.Run != nil {
  58. cmd.Flag.Usage = func() { cmd.Usage() }
  59. cmd.Flag.Parse(args[1:])
  60. args = cmd.Flag.Args()
  61. IsDebug = cmd.IsDebug
  62. if !cmd.Run(cmd, args) {
  63. fmt.Fprintf(os.Stderr, "\n")
  64. cmd.Flag.Usage()
  65. fmt.Fprintf(os.Stderr, "Default Parameters:\n")
  66. cmd.Flag.PrintDefaults()
  67. }
  68. exit()
  69. return
  70. }
  71. }
  72. fmt.Fprintf(os.Stderr, "weed: unknown subcommand %q\nRun 'weed help' for usage.\n", args[0])
  73. setExitStatus(2)
  74. exit()
  75. }
  76. var usageTemplate = `WeedFS is a software to store billions of files and serve them fast!
  77. Usage:
  78. weed command [arguments]
  79. The commands are:
  80. {{range .}}{{if .Runnable}}
  81. {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
  82. Use "weed help [command]" for more information about a command.
  83. `
  84. var helpTemplate = `{{if .Runnable}}Usage: weed {{.UsageLine}}
  85. {{end}}
  86. {{.Long}}
  87. `
  88. // tmpl executes the given template text on data, writing the result to w.
  89. func tmpl(w io.Writer, text string, data interface{}) {
  90. t := template.New("top")
  91. t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize})
  92. template.Must(t.Parse(text))
  93. if err := t.Execute(w, data); err != nil {
  94. panic(err)
  95. }
  96. }
  97. func capitalize(s string) string {
  98. if s == "" {
  99. return s
  100. }
  101. r, n := utf8.DecodeRuneInString(s)
  102. return string(unicode.ToTitle(r)) + s[n:]
  103. }
  104. func printUsage(w io.Writer) {
  105. tmpl(w, usageTemplate, commands)
  106. }
  107. func usage() {
  108. printUsage(os.Stderr)
  109. os.Exit(2)
  110. }
  111. // help implements the 'help' command.
  112. func help(args []string) {
  113. if len(args) == 0 {
  114. printUsage(os.Stdout)
  115. // not exit 2: succeeded at 'weed help'.
  116. return
  117. }
  118. if len(args) != 1 {
  119. fmt.Fprintf(os.Stderr, "usage: weed help command\n\nToo many arguments given.\n")
  120. os.Exit(2) // failed at 'weed help'
  121. }
  122. arg := args[0]
  123. for _, cmd := range commands {
  124. if cmd.Name() == arg {
  125. tmpl(os.Stdout, helpTemplate, cmd)
  126. // not exit 2: succeeded at 'weed help cmd'.
  127. return
  128. }
  129. }
  130. fmt.Fprintf(os.Stderr, "Unknown help topic %#q. Run 'weed help'.\n", arg)
  131. os.Exit(2) // failed at 'weed help cmd'
  132. }
  133. var atexitFuncs []func()
  134. func atexit(f func()) {
  135. atexitFuncs = append(atexitFuncs, f)
  136. }
  137. func exit() {
  138. for _, f := range atexitFuncs {
  139. f()
  140. }
  141. os.Exit(exitStatus)
  142. }
  143. func exitIfErrors() {
  144. if exitStatus != 0 {
  145. exit()
  146. }
  147. }
  148. func writeJson(w http.ResponseWriter, r *http.Request, obj interface{}) (err error) {
  149. w.Header().Set("Content-Type", "application/javascript")
  150. var bytes []byte
  151. if r.FormValue("pretty") != "" {
  152. bytes, err = json.MarshalIndent(obj, "", " ")
  153. } else {
  154. bytes, err = json.Marshal(obj)
  155. }
  156. if err != nil {
  157. return
  158. }
  159. callback := r.FormValue("callback")
  160. if callback == "" {
  161. _, err = w.Write(bytes)
  162. } else {
  163. if _, err = w.Write([]uint8(callback)); err != nil {
  164. return
  165. }
  166. if _, err = w.Write([]uint8("(")); err != nil {
  167. return
  168. }
  169. fmt.Fprint(w, string(bytes))
  170. if _, err = w.Write([]uint8(")")); err != nil {
  171. return
  172. }
  173. }
  174. return
  175. }
  176. // wrapper for writeJson - just logs errors
  177. func writeJsonQuiet(w http.ResponseWriter, r *http.Request, obj interface{}) {
  178. if err := writeJson(w, r, obj); err != nil {
  179. log.Printf("error writing JSON %s: %s", obj, err)
  180. }
  181. }
  182. func writeJsonError(w http.ResponseWriter, r *http.Request, err error) {
  183. m := make(map[string]interface{})
  184. m["error"] = err.Error()
  185. writeJsonQuiet(w, r, m)
  186. }
  187. func debug(params ...interface{}) {
  188. if *IsDebug {
  189. log.Println(params)
  190. }
  191. }