rc.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 https://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. sequence map[string]map[string]int64 // Folder ID => Device ID => Sequence
  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. sequence: 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&timeout=10", 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 (p *Process) PauseDevice(dev protocol.DeviceID) error {
  243. _, err := p.Post("/rest/system/pause?device="+dev.String(), nil)
  244. return err
  245. }
  246. func (p *Process) ResumeDevice(dev protocol.DeviceID) error {
  247. _, err := p.Post("/rest/system/resume?device="+dev.String(), nil)
  248. return err
  249. }
  250. func (p *Process) PauseAll() error {
  251. _, err := p.Post("/rest/system/pause", nil)
  252. return err
  253. }
  254. func (p *Process) ResumeAll() error {
  255. _, err := p.Post("/rest/system/resume", nil)
  256. return err
  257. }
  258. func InSync(folder string, ps ...*Process) bool {
  259. for _, p := range ps {
  260. p.eventMut.Lock()
  261. }
  262. defer func() {
  263. for _, p := range ps {
  264. p.eventMut.Unlock()
  265. }
  266. }()
  267. for i := range ps {
  268. // If our latest FolderSummary didn't report 100%, then we are not done.
  269. if !ps[i].done[folder] {
  270. return false
  271. }
  272. // Check Sequence for each device. The local version seen by remote
  273. // devices should be the same as what it has locally, or the index
  274. // hasn't been sent yet.
  275. sourceID := ps[i].id.String()
  276. sourceSeq := ps[i].sequence[folder][sourceID]
  277. l.Debugf("sourceSeq = ps[%d].sequence[%q][%q] = %d", i, folder, sourceID, sourceSeq)
  278. for j := range ps {
  279. if i != j {
  280. remoteSeq := ps[j].sequence[folder][sourceID]
  281. if remoteSeq != sourceSeq {
  282. l.Debugf("remoteSeq = ps[%d].sequence[%q][%q] = %d", j, folder, sourceID, remoteSeq)
  283. return false
  284. }
  285. }
  286. }
  287. }
  288. return true
  289. }
  290. func AwaitSync(folder string, ps ...*Process) {
  291. for {
  292. time.Sleep(250 * time.Millisecond)
  293. if InSync(folder, ps...) {
  294. return
  295. }
  296. }
  297. }
  298. type Model struct {
  299. GlobalBytes int
  300. GlobalDeleted int
  301. GlobalFiles int
  302. InSyncBytes int
  303. InSyncFiles int
  304. Invalid string
  305. LocalBytes int
  306. LocalDeleted int
  307. LocalFiles int
  308. NeedBytes int
  309. NeedFiles int
  310. State string
  311. StateChanged time.Time
  312. Version int
  313. }
  314. func (p *Process) Model(folder string) (Model, error) {
  315. bs, err := p.Get("/rest/db/status?folder=" + url.QueryEscape(folder))
  316. if err != nil {
  317. return Model{}, err
  318. }
  319. var res Model
  320. if err := json.Unmarshal(bs, &res); err != nil {
  321. return Model{}, err
  322. }
  323. l.Debugf("%+v", res)
  324. return res, nil
  325. }
  326. func (p *Process) readResponse(resp *http.Response) ([]byte, error) {
  327. bs, err := ioutil.ReadAll(resp.Body)
  328. resp.Body.Close()
  329. if err != nil {
  330. return bs, err
  331. }
  332. if resp.StatusCode != 200 {
  333. return bs, fmt.Errorf("%s", resp.Status)
  334. }
  335. return bs, nil
  336. }
  337. func (p *Process) checkForProblems(logfd *os.File) error {
  338. fd, err := os.Open(logfd.Name())
  339. if err != nil {
  340. return err
  341. }
  342. defer fd.Close()
  343. raceConditionStart := []byte("WARNING: DATA RACE")
  344. raceConditionSep := []byte("==================")
  345. panicConditionStart := []byte("panic:")
  346. panicConditionSep := []byte(p.id.String()[:5])
  347. sc := bufio.NewScanner(fd)
  348. race := false
  349. _panic := false
  350. for sc.Scan() {
  351. line := sc.Bytes()
  352. if race || _panic {
  353. if bytes.Contains(line, panicConditionSep) {
  354. _panic = false
  355. continue
  356. }
  357. fmt.Printf("%s\n", line)
  358. if bytes.Contains(line, raceConditionSep) {
  359. race = false
  360. }
  361. } else if bytes.Contains(line, raceConditionStart) {
  362. fmt.Printf("%s\n", raceConditionSep)
  363. fmt.Printf("%s\n", raceConditionStart)
  364. race = true
  365. if err == nil {
  366. err = errors.New("Race condition detected")
  367. }
  368. } else if bytes.Contains(line, panicConditionStart) {
  369. _panic = true
  370. if err == nil {
  371. err = errors.New("Panic detected")
  372. }
  373. }
  374. }
  375. return err
  376. }
  377. func (p *Process) eventLoop() {
  378. since := 0
  379. notScanned := make(map[string]struct{})
  380. start := time.Now()
  381. for {
  382. p.eventMut.Lock()
  383. if p.stop {
  384. p.eventMut.Unlock()
  385. return
  386. }
  387. p.eventMut.Unlock()
  388. events, err := p.Events(since)
  389. if err != nil {
  390. if time.Since(start) < 5*time.Second {
  391. // The API has probably not started yet, lets give it some time.
  392. continue
  393. }
  394. // If we're stopping, no need to print the error.
  395. p.eventMut.Lock()
  396. if p.stop {
  397. p.eventMut.Unlock()
  398. return
  399. }
  400. p.eventMut.Unlock()
  401. log.Println("eventLoop: events:", err)
  402. continue
  403. }
  404. for _, ev := range events {
  405. if ev.ID != since+1 {
  406. l.Warnln("Event ID jumped", since, "to", ev.ID)
  407. }
  408. since = ev.ID
  409. switch ev.Type {
  410. case "Starting":
  411. // The Starting event tells us where the configuration is. Load
  412. // it and populate our list of folders.
  413. data := ev.Data.(map[string]interface{})
  414. id, err := protocol.DeviceIDFromString(data["myID"].(string))
  415. if err != nil {
  416. log.Println("eventLoop: DeviceIdFromString:", err)
  417. continue
  418. }
  419. p.id = id
  420. home := data["home"].(string)
  421. w, err := config.Load(filepath.Join(home, "config.xml"), protocol.LocalDeviceID)
  422. if err != nil {
  423. log.Println("eventLoop: Starting:", err)
  424. continue
  425. }
  426. for id := range w.Folders() {
  427. p.eventMut.Lock()
  428. p.folders = append(p.folders, id)
  429. p.eventMut.Unlock()
  430. notScanned[id] = struct{}{}
  431. }
  432. l.Debugln("Started", p.id)
  433. case "StateChanged":
  434. // When a folder changes to idle, we tick it off by removing
  435. // it from p.notScanned.
  436. if len(p.folders) == 0 {
  437. // We haven't parsed the config yet, shouldn't happen
  438. panic("race, or lost startup event")
  439. }
  440. if !p.startComplete {
  441. data := ev.Data.(map[string]interface{})
  442. to := data["to"].(string)
  443. if to == "idle" {
  444. folder := data["folder"].(string)
  445. delete(notScanned, folder)
  446. if len(notScanned) == 0 {
  447. p.eventMut.Lock()
  448. p.startComplete = true
  449. p.startCompleteCond.Broadcast()
  450. p.eventMut.Unlock()
  451. }
  452. }
  453. }
  454. case "LocalIndexUpdated":
  455. data := ev.Data.(map[string]interface{})
  456. folder := data["folder"].(string)
  457. version, _ := data["version"].(json.Number).Int64()
  458. p.eventMut.Lock()
  459. m := p.sequence[folder]
  460. if m == nil {
  461. m = make(map[string]int64)
  462. }
  463. device := p.id.String()
  464. if device == "" {
  465. panic("race, or startup not complete")
  466. }
  467. m[device] = version
  468. p.sequence[folder] = m
  469. p.done[folder] = false
  470. l.Debugf("LocalIndexUpdated %v %v done=false\n\t%+v", p.id, folder, m)
  471. p.eventMut.Unlock()
  472. case "RemoteIndexUpdated":
  473. data := ev.Data.(map[string]interface{})
  474. device := data["device"].(string)
  475. folder := data["folder"].(string)
  476. version, _ := data["version"].(json.Number).Int64()
  477. p.eventMut.Lock()
  478. m := p.sequence[folder]
  479. if m == nil {
  480. m = make(map[string]int64)
  481. }
  482. m[device] = version
  483. p.sequence[folder] = m
  484. p.done[folder] = false
  485. l.Debugf("RemoteIndexUpdated %v %v done=false\n\t%+v", p.id, folder, m)
  486. p.eventMut.Unlock()
  487. case "FolderSummary":
  488. data := ev.Data.(map[string]interface{})
  489. folder := data["folder"].(string)
  490. summary := data["summary"].(map[string]interface{})
  491. need, _ := summary["needBytes"].(json.Number).Int64()
  492. done := need == 0
  493. p.eventMut.Lock()
  494. p.done[folder] = done
  495. l.Debugf("Foldersummary %v %v\n\t%+v", p.id, folder, p.done)
  496. p.eventMut.Unlock()
  497. }
  498. }
  499. }
  500. }
  501. type ConnectionStats struct {
  502. Address string
  503. Type string
  504. Connected bool
  505. Paused bool
  506. ClientVersion string
  507. InBytesTotal int64
  508. OutBytesTotal int64
  509. }
  510. func (p *Process) Connections() (map[string]ConnectionStats, error) {
  511. bs, err := p.Get("/rest/system/connections")
  512. if err != nil {
  513. return nil, err
  514. }
  515. var res map[string]ConnectionStats
  516. if err := json.Unmarshal(bs, &res); err != nil {
  517. return nil, err
  518. }
  519. return res, nil
  520. }
  521. type SystemStatus struct {
  522. Alloc int64
  523. CPUPercent float64
  524. Goroutines int
  525. MyID protocol.DeviceID
  526. PathSeparator string
  527. StartTime time.Time
  528. Sys int64
  529. Themes []string
  530. Tilde string
  531. Uptime int
  532. }
  533. func (p *Process) SystemStatus() (SystemStatus, error) {
  534. bs, err := p.Get("/rest/system/status")
  535. if err != nil {
  536. return SystemStatus{}, err
  537. }
  538. var res SystemStatus
  539. if err := json.Unmarshal(bs, &res); err != nil {
  540. return SystemStatus{}, err
  541. }
  542. return res, nil
  543. }
  544. type SystemVersion struct {
  545. Arch string
  546. Codename string
  547. LongVersion string
  548. OS string
  549. Version string
  550. }
  551. func (p *Process) SystemVersion() (SystemVersion, error) {
  552. bs, err := p.Get("/rest/system/version")
  553. if err != nil {
  554. return SystemVersion{}, err
  555. }
  556. var res SystemVersion
  557. if err := json.Unmarshal(bs, &res); err != nil {
  558. return SystemVersion{}, err
  559. }
  560. return res, nil
  561. }