gui.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "mime"
  8. "net/http"
  9. "path/filepath"
  10. "runtime"
  11. "sync"
  12. "bitbucket.org/tebeka/nrsc"
  13. "github.com/calmh/syncthing/model"
  14. "github.com/codegangsta/martini"
  15. )
  16. func startGUI(addr string, m *model.Model) {
  17. router := martini.NewRouter()
  18. router.Get("/", getRoot)
  19. router.Get("/rest/version", restGetVersion)
  20. router.Get("/rest/model", restGetModel)
  21. router.Get("/rest/connections", restGetConnections)
  22. router.Get("/rest/config", restGetConfig)
  23. router.Get("/rest/need", restGetNeed)
  24. router.Get("/rest/system", restGetSystem)
  25. go func() {
  26. mr := martini.New()
  27. mr.Use(nrscStatic("gui"))
  28. mr.Use(martini.Recovery())
  29. mr.Action(router.Handle)
  30. mr.Map(m)
  31. err := http.ListenAndServe(addr, mr)
  32. if err != nil {
  33. warnln("GUI not possible:", err)
  34. }
  35. }()
  36. }
  37. func getRoot(w http.ResponseWriter, r *http.Request) {
  38. http.Redirect(w, r, "/index.html", 302)
  39. }
  40. func restGetVersion() string {
  41. return Version
  42. }
  43. func restGetModel(m *model.Model, w http.ResponseWriter) {
  44. var res = make(map[string]interface{})
  45. globalFiles, globalDeleted, globalBytes := m.GlobalSize()
  46. res["globalFiles"], res["globalDeleted"], res["globalBytes"] = globalFiles, globalDeleted, globalBytes
  47. localFiles, localDeleted, localBytes := m.LocalSize()
  48. res["localFiles"], res["localDeleted"], res["localBytes"] = localFiles, localDeleted, localBytes
  49. inSyncFiles, inSyncBytes := m.InSyncSize()
  50. res["inSyncFiles"], res["inSyncBytes"] = inSyncFiles, inSyncBytes
  51. files, total := m.NeedFiles()
  52. res["needFiles"], res["needBytes"] = len(files), total
  53. w.Header().Set("Content-Type", "application/json")
  54. json.NewEncoder(w).Encode(res)
  55. }
  56. func restGetConnections(m *model.Model, w http.ResponseWriter) {
  57. var res = m.ConnectionStats()
  58. w.Header().Set("Content-Type", "application/json")
  59. json.NewEncoder(w).Encode(res)
  60. }
  61. func restGetConfig(w http.ResponseWriter) {
  62. var res = make(map[string]interface{})
  63. res["repository"] = config.OptionMap("repository")
  64. res["nodes"] = config.OptionMap("nodes")
  65. w.Header().Set("Content-Type", "application/json")
  66. json.NewEncoder(w).Encode(res)
  67. }
  68. type guiFile model.File
  69. func (f guiFile) MarshalJSON() ([]byte, error) {
  70. type t struct {
  71. Name string
  72. Size int
  73. }
  74. return json.Marshal(t{
  75. Name: f.Name,
  76. Size: model.File(f).Size(),
  77. })
  78. }
  79. func restGetNeed(m *model.Model, w http.ResponseWriter) {
  80. files, _ := m.NeedFiles()
  81. gfs := make([]guiFile, len(files))
  82. for i, f := range files {
  83. gfs[i] = guiFile(f)
  84. }
  85. w.Header().Set("Content-Type", "application/json")
  86. json.NewEncoder(w).Encode(gfs)
  87. }
  88. var cpuUsagePercent float64
  89. var cpuUsageLock sync.RWMutex
  90. func restGetSystem(w http.ResponseWriter) {
  91. var m runtime.MemStats
  92. runtime.ReadMemStats(&m)
  93. res := make(map[string]interface{})
  94. res["goroutines"] = runtime.NumGoroutine()
  95. res["alloc"] = m.Alloc
  96. res["sys"] = m.Sys
  97. cpuUsageLock.RLock()
  98. res["cpuPercent"] = cpuUsagePercent
  99. cpuUsageLock.RUnlock()
  100. w.Header().Set("Content-Type", "application/json")
  101. json.NewEncoder(w).Encode(res)
  102. }
  103. func nrscStatic(path string) interface{} {
  104. if err := nrsc.Initialize(); err != nil {
  105. panic("Unable to initialize nrsc: " + err.Error())
  106. }
  107. return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
  108. file := req.URL.Path
  109. // nrsc expects there not to be a leading slash
  110. if file[0] == '/' {
  111. file = file[1:]
  112. }
  113. f := nrsc.Get(file)
  114. if f == nil {
  115. return
  116. }
  117. rdr, err := f.Open()
  118. if err != nil {
  119. http.Error(res, "Internal Server Error", http.StatusInternalServerError)
  120. }
  121. defer rdr.Close()
  122. mtype := mime.TypeByExtension(filepath.Ext(req.URL.Path))
  123. if len(mtype) != 0 {
  124. res.Header().Set("Content-Type", mtype)
  125. }
  126. res.Header().Set("Content-Size", fmt.Sprintf("%d", f.Size()))
  127. res.Header().Set("Last-Modified", f.ModTime().UTC().Format(http.TimeFormat))
  128. io.Copy(res, rdr)
  129. }
  130. }