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.

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