rc.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package rc provides remote control of a Syncthing process via the REST API.
  7. package rc
  8. import (
  9. "bufio"
  10. "bytes"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "log"
  17. "net/http"
  18. "net/url"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "strconv"
  23. stdsync "sync"
  24. "time"
  25. "github.com/syncthing/syncthing/lib/config"
  26. "github.com/syncthing/syncthing/lib/dialer"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. "github.com/syncthing/syncthing/lib/sync"
  29. )
  30. // APIKey is set via the STGUIAPIKEY variable when we launch the binary, to
  31. // ensure that we have API access regardless of authentication settings.
  32. const APIKey = "592A47BC-A7DF-4C2F-89E0-A80B3E5094EE"
  33. type Process struct {
  34. // Set at initialization
  35. addr string
  36. // Set by eventLoop()
  37. eventMut sync.Mutex
  38. id protocol.DeviceID
  39. folders []string
  40. startComplete bool
  41. startCompleteCond *stdsync.Cond
  42. stop bool
  43. localVersion map[string]map[string]int64 // Folder ID => Device ID => LocalVersion
  44. done map[string]bool // Folder ID => 100%
  45. cmd *exec.Cmd
  46. logfd *os.File
  47. }
  48. // NewProcess returns a new Process talking to Syncthing at the specified address.
  49. // Example: NewProcess("127.0.0.1:8082")
  50. func NewProcess(addr string) *Process {
  51. p := &Process{
  52. addr: addr,
  53. localVersion: make(map[string]map[string]int64),
  54. done: make(map[string]bool),
  55. eventMut: sync.NewMutex(),
  56. }
  57. p.startCompleteCond = stdsync.NewCond(p.eventMut)
  58. return p
  59. }
  60. func (p *Process) ID() protocol.DeviceID {
  61. return p.id
  62. }
  63. // LogTo creates the specified log file and ensures that stdout and stderr
  64. // from the Start()ed process is redirected there. Must be called before
  65. // Start().
  66. func (p *Process) LogTo(filename string) error {
  67. if p.cmd != nil {
  68. panic("logfd cannot be set with an existing cmd")
  69. }
  70. if p.logfd != nil {
  71. p.logfd.Close()
  72. }
  73. fd, err := os.Create(filename)
  74. if err != nil {
  75. return err
  76. }
  77. p.logfd = fd
  78. return nil
  79. }
  80. // Start runs the specified Syncthing binary with the given arguments.
  81. // Syncthing should be configured to provide an API on the address given to
  82. // NewProcess. Event processing is started.
  83. func (p *Process) Start(bin string, args ...string) error {
  84. cmd := exec.Command(bin, args...)
  85. if p.logfd != nil {
  86. cmd.Stdout = p.logfd
  87. cmd.Stderr = p.logfd
  88. }
  89. cmd.Env = append(os.Environ(), "STNORESTART=1", "STGUIAPIKEY="+APIKey)
  90. err := cmd.Start()
  91. if err != nil {
  92. return err
  93. }
  94. p.cmd = cmd
  95. go p.eventLoop()
  96. return nil
  97. }
  98. // AwaitStartup waits for the Syncthing process to start and perform initial
  99. // scans of all folders.
  100. func (p *Process) AwaitStartup() {
  101. p.eventMut.Lock()
  102. for !p.startComplete {
  103. p.startCompleteCond.Wait()
  104. }
  105. p.eventMut.Unlock()
  106. return
  107. }
  108. // Stop stops the running Syncthing process. If the process was logging to a
  109. // local file (set by LogTo), the log file will be opened and checked for
  110. // panics and data races. The presence of either will be signalled in the form
  111. // of a returned error.
  112. func (p *Process) Stop() (*os.ProcessState, error) {
  113. p.eventMut.Lock()
  114. if p.stop {
  115. p.eventMut.Unlock()
  116. return p.cmd.ProcessState, nil
  117. }
  118. p.stop = true
  119. p.eventMut.Unlock()
  120. if _, err := p.Post("/rest/system/shutdown", nil); err != nil && err != io.ErrUnexpectedEOF {
  121. // Unexpected EOF is somewhat expected here, as we may exit before
  122. // returning something sensible.
  123. return nil, err
  124. }
  125. p.cmd.Wait()
  126. var err error
  127. if p.logfd != nil {
  128. err = p.checkForProblems(p.logfd)
  129. }
  130. return p.cmd.ProcessState, err
  131. }
  132. // Get performs an HTTP GET and returns the bytes and/or an error. Any non-200
  133. // return code is returned as an error.
  134. func (p *Process) Get(path string) ([]byte, error) {
  135. client := &http.Client{
  136. Timeout: 30 * time.Second,
  137. Transport: &http.Transport{
  138. Dial: dialer.Dial,
  139. Proxy: http.ProxyFromEnvironment,
  140. DisableKeepAlives: true,
  141. },
  142. }
  143. url := fmt.Sprintf("http://%s%s", p.addr, path)
  144. req, err := http.NewRequest("GET", url, nil)
  145. if err != nil {
  146. return nil, err
  147. }
  148. req.Header.Add("X-API-Key", APIKey)
  149. resp, err := client.Do(req)
  150. if err != nil {
  151. return nil, err
  152. }
  153. return p.readResponse(resp)
  154. }
  155. // Post performs an HTTP POST and returns the bytes and/or an error. Any
  156. // non-200 return code is returned as an error.
  157. func (p *Process) Post(path string, data io.Reader) ([]byte, error) {
  158. client := &http.Client{
  159. Timeout: 600 * time.Second,
  160. Transport: &http.Transport{
  161. DisableKeepAlives: true,
  162. },
  163. }
  164. url := fmt.Sprintf("http://%s%s", p.addr, path)
  165. req, err := http.NewRequest("POST", url, data)
  166. if err != nil {
  167. return nil, err
  168. }
  169. req.Header.Add("X-API-Key", APIKey)
  170. req.Header.Add("Content-Type", "application/json")
  171. resp, err := client.Do(req)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return p.readResponse(resp)
  176. }
  177. type Event struct {
  178. ID int
  179. Time time.Time
  180. Type string
  181. Data interface{}
  182. }
  183. func (p *Process) Events(since int) ([]Event, error) {
  184. bs, err := p.Get(fmt.Sprintf("/rest/events?since=%d", since))
  185. if err != nil {
  186. return nil, err
  187. }
  188. var evs []Event
  189. dec := json.NewDecoder(bytes.NewReader(bs))
  190. dec.UseNumber()
  191. err = dec.Decode(&evs)
  192. if err != nil {
  193. return nil, fmt.Errorf("Events: %s in %q", err, bs)
  194. }
  195. return evs, err
  196. }
  197. func (p *Process) Rescan(folder string) error {
  198. _, err := p.Post("/rest/db/scan?folder="+url.QueryEscape(folder), nil)
  199. return err
  200. }
  201. func (p *Process) RescanDelay(folder string, delaySeconds int) error {
  202. _, err := p.Post(fmt.Sprintf("/rest/db/scan?folder=%s&next=%d", url.QueryEscape(folder), delaySeconds), nil)
  203. return err
  204. }
  205. func (p *Process) RescanSub(folder string, sub string, delaySeconds int) error {
  206. return p.RescanSubs(folder, []string{sub}, delaySeconds)
  207. }
  208. func (p *Process) RescanSubs(folder string, subs []string, delaySeconds int) error {
  209. data := url.Values{}
  210. data.Set("folder", folder)
  211. for _, sub := range subs {
  212. data.Add("sub", sub)
  213. }
  214. data.Set("next", strconv.Itoa(delaySeconds))
  215. _, err := p.Post("/rest/db/scan?"+data.Encode(), nil)
  216. return err
  217. }
  218. func (p *Process) ConfigInSync() (bool, error) {
  219. bs, err := p.Get("/rest/system/config/insync")
  220. if err != nil {
  221. return false, err
  222. }
  223. return bytes.Contains(bs, []byte("true")), nil
  224. }
  225. func (p *Process) GetConfig() (config.Configuration, error) {
  226. var cfg config.Configuration
  227. bs, err := p.Get("/rest/system/config")
  228. if err != nil {
  229. return cfg, err
  230. }
  231. err = json.Unmarshal(bs, &cfg)
  232. return cfg, err
  233. }
  234. func (p *Process) PostConfig(cfg config.Configuration) error {
  235. buf := new(bytes.Buffer)
  236. if err := json.NewEncoder(buf).Encode(cfg); err != nil {
  237. return err
  238. }
  239. _, err := p.Post("/rest/system/config", buf)
  240. return err
  241. }
  242. func InSync(folder string, ps ...*Process) bool {
  243. for _, p := range ps {
  244. p.eventMut.Lock()
  245. }
  246. defer func() {
  247. for _, p := range ps {
  248. p.eventMut.Unlock()
  249. }
  250. }()
  251. for i := range ps {
  252. // If our latest FolderSummary didn't report 100%, then we are not done.
  253. if !ps[i].done[folder] {
  254. return false
  255. }
  256. // Check LocalVersion for each device. The local version seen by remote
  257. // devices should be the same as what it has locally, or the index
  258. // hasn't been sent yet.
  259. sourceID := ps[i].id.String()
  260. sourceVersion := ps[i].localVersion[folder][sourceID]
  261. for j := range ps {
  262. if i != j {
  263. remoteVersion := ps[j].localVersion[folder][sourceID]
  264. if remoteVersion != sourceVersion {
  265. return false
  266. }
  267. }
  268. }
  269. }
  270. return true
  271. }
  272. func AwaitSync(folder string, ps ...*Process) {
  273. for {
  274. time.Sleep(250 * time.Millisecond)
  275. if InSync(folder, ps...) {
  276. return
  277. }
  278. }
  279. }
  280. type Model struct {
  281. GlobalBytes int
  282. GlobalDeleted int
  283. GlobalFiles int
  284. InSyncBytes int
  285. InSyncFiles int
  286. Invalid string
  287. LocalBytes int
  288. LocalDeleted int
  289. LocalFiles int
  290. NeedBytes int
  291. NeedFiles int
  292. State string
  293. StateChanged time.Time
  294. Version int
  295. }
  296. func (p *Process) Model(folder string) (Model, error) {
  297. bs, err := p.Get("/rest/db/status?folder=" + url.QueryEscape(folder))
  298. if err != nil {
  299. return Model{}, err
  300. }
  301. var res Model
  302. if err := json.Unmarshal(bs, &res); err != nil {
  303. return Model{}, err
  304. }
  305. l.Debugf("%+v", res)
  306. return res, nil
  307. }
  308. func (p *Process) readResponse(resp *http.Response) ([]byte, error) {
  309. bs, err := ioutil.ReadAll(resp.Body)
  310. resp.Body.Close()
  311. if err != nil {
  312. return bs, err
  313. }
  314. if resp.StatusCode != 200 {
  315. return bs, fmt.Errorf("%s", resp.Status)
  316. }
  317. return bs, nil
  318. }
  319. func (p *Process) checkForProblems(logfd *os.File) error {
  320. fd, err := os.Open(logfd.Name())
  321. if err != nil {
  322. return err
  323. }
  324. defer fd.Close()
  325. raceConditionStart := []byte("WARNING: DATA RACE")
  326. raceConditionSep := []byte("==================")
  327. panicConditionStart := []byte("panic:")
  328. panicConditionSep := []byte(p.id.String()[:5])
  329. sc := bufio.NewScanner(fd)
  330. race := false
  331. _panic := false
  332. for sc.Scan() {
  333. line := sc.Bytes()
  334. if race || _panic {
  335. if bytes.Contains(line, panicConditionSep) {
  336. _panic = false
  337. continue
  338. }
  339. fmt.Printf("%s\n", line)
  340. if bytes.Contains(line, raceConditionSep) {
  341. race = false
  342. }
  343. } else if bytes.Contains(line, raceConditionStart) {
  344. fmt.Printf("%s\n", raceConditionSep)
  345. fmt.Printf("%s\n", raceConditionStart)
  346. race = true
  347. if err == nil {
  348. err = errors.New("Race condition detected")
  349. }
  350. } else if bytes.Contains(line, panicConditionStart) {
  351. _panic = true
  352. if err == nil {
  353. err = errors.New("Panic detected")
  354. }
  355. }
  356. }
  357. return err
  358. }
  359. func (p *Process) eventLoop() {
  360. since := 0
  361. notScanned := make(map[string]struct{})
  362. start := time.Now()
  363. for {
  364. p.eventMut.Lock()
  365. if p.stop {
  366. p.eventMut.Unlock()
  367. return
  368. }
  369. p.eventMut.Unlock()
  370. time.Sleep(250 * time.Millisecond)
  371. events, err := p.Events(since)
  372. if err != nil {
  373. if time.Since(start) < 5*time.Second {
  374. // The API has probably not started yet, lets give it some time.
  375. continue
  376. }
  377. // If we're stopping, no need to print the error.
  378. p.eventMut.Lock()
  379. if p.stop {
  380. p.eventMut.Unlock()
  381. return
  382. }
  383. p.eventMut.Unlock()
  384. log.Println("eventLoop: events:", err)
  385. continue
  386. }
  387. since = events[len(events)-1].ID
  388. for _, ev := range events {
  389. switch ev.Type {
  390. case "Starting":
  391. // The Starting event tells us where the configuration is. Load
  392. // it and populate our list of folders.
  393. data := ev.Data.(map[string]interface{})
  394. id, err := protocol.DeviceIDFromString(data["myID"].(string))
  395. if err != nil {
  396. log.Println("eventLoop: DeviceIdFromString:", err)
  397. continue
  398. }
  399. p.id = id
  400. home := data["home"].(string)
  401. w, err := config.Load(filepath.Join(home, "config.xml"), protocol.LocalDeviceID)
  402. if err != nil {
  403. log.Println("eventLoop: Starting:", err)
  404. continue
  405. }
  406. for id := range w.Folders() {
  407. p.eventMut.Lock()
  408. p.folders = append(p.folders, id)
  409. p.eventMut.Unlock()
  410. notScanned[id] = struct{}{}
  411. }
  412. case "StateChanged":
  413. // When a folder changes to idle, we tick it off by removing
  414. // it from p.notScanned.
  415. if !p.startComplete {
  416. data := ev.Data.(map[string]interface{})
  417. to := data["to"].(string)
  418. if to == "idle" {
  419. folder := data["folder"].(string)
  420. delete(notScanned, folder)
  421. if len(notScanned) == 0 {
  422. p.eventMut.Lock()
  423. p.startComplete = true
  424. p.startCompleteCond.Broadcast()
  425. p.eventMut.Unlock()
  426. }
  427. }
  428. }
  429. case "LocalIndexUpdated":
  430. data := ev.Data.(map[string]interface{})
  431. folder := data["folder"].(string)
  432. version, _ := data["version"].(json.Number).Int64()
  433. p.eventMut.Lock()
  434. m := p.localVersion[folder]
  435. if m == nil {
  436. m = make(map[string]int64)
  437. }
  438. m[p.id.String()] = version
  439. p.localVersion[folder] = m
  440. p.done[folder] = false
  441. l.Debugf("LocalIndexUpdated %v %v done=false\n\t%+v", p.id, folder, m)
  442. p.eventMut.Unlock()
  443. case "RemoteIndexUpdated":
  444. data := ev.Data.(map[string]interface{})
  445. device := data["device"].(string)
  446. folder := data["folder"].(string)
  447. version, _ := data["version"].(json.Number).Int64()
  448. p.eventMut.Lock()
  449. m := p.localVersion[folder]
  450. if m == nil {
  451. m = make(map[string]int64)
  452. }
  453. m[device] = version
  454. p.localVersion[folder] = m
  455. p.done[folder] = false
  456. l.Debugf("RemoteIndexUpdated %v %v done=false\n\t%+v", p.id, folder, m)
  457. p.eventMut.Unlock()
  458. case "FolderSummary":
  459. data := ev.Data.(map[string]interface{})
  460. folder := data["folder"].(string)
  461. summary := data["summary"].(map[string]interface{})
  462. need, _ := summary["needBytes"].(json.Number).Int64()
  463. done := need == 0
  464. p.eventMut.Lock()
  465. p.done[folder] = done
  466. l.Debugf("Foldersummary %v %v\n\t%+v", p.id, folder, p.done)
  467. p.eventMut.Unlock()
  468. }
  469. }
  470. }
  471. }