Wait folder insync before sending exit event.
[src/xds/xds-server.git] / lib / syncthing / st.go
1 package st
2
3 import (
4         "encoding/json"
5         "os"
6         "os/exec"
7         "path"
8         "path/filepath"
9         "syscall"
10         "time"
11
12         "strings"
13
14         "fmt"
15
16         "io"
17
18         "io/ioutil"
19
20         "regexp"
21
22         "github.com/Sirupsen/logrus"
23         "github.com/iotbzh/xds-server/lib/common"
24         "github.com/iotbzh/xds-server/lib/xdsconfig"
25         "github.com/syncthing/syncthing/lib/config"
26 )
27
28 // SyncThing .
29 type SyncThing struct {
30         BaseURL string
31         APIKey  string
32         Home    string
33         STCmd   *exec.Cmd
34         STICmd  *exec.Cmd
35
36         // Private fields
37         binDir      string
38         logsDir     string
39         exitSTChan  chan ExitChan
40         exitSTIChan chan ExitChan
41         conf        *xdsconfig.Config
42         client      *common.HTTPClient
43         log         *logrus.Logger
44 }
45
46 // ExitChan Channel used for process exit
47 type ExitChan struct {
48         status int
49         err    error
50 }
51
52 // ConfigInSync Check whether if Syncthing configuration is in sync
53 type configInSync struct {
54         ConfigInSync bool `json:"configInSync"`
55 }
56
57 // FolderStatus Information about the current status of a folder.
58 type FolderStatus struct {
59         GlobalFiles       int   `json:"globalFiles"`
60         GlobalDirectories int   `json:"globalDirectories"`
61         GlobalSymlinks    int   `json:"globalSymlinks"`
62         GlobalDeleted     int   `json:"globalDeleted"`
63         GlobalBytes       int64 `json:"globalBytes"`
64
65         LocalFiles       int   `json:"localFiles"`
66         LocalDirectories int   `json:"localDirectories"`
67         LocalSymlinks    int   `json:"localSymlinks"`
68         LocalDeleted     int   `json:"localDeleted"`
69         LocalBytes       int64 `json:"localBytes"`
70
71         NeedFiles       int   `json:"needFiles"`
72         NeedDirectories int   `json:"needDirectories"`
73         NeedSymlinks    int   `json:"needSymlinks"`
74         NeedDeletes     int   `json:"needDeletes"`
75         NeedBytes       int64 `json:"needBytes"`
76
77         InSyncFiles int   `json:"inSyncFiles"`
78         InSyncBytes int64 `json:"inSyncBytes"`
79
80         State        string    `json:"state"`
81         StateChanged time.Time `json:"stateChanged"`
82
83         Sequence int64 `json:"sequence"`
84
85         IgnorePatterns bool `json:"ignorePatterns"`
86 }
87
88 // NewSyncThing creates a new instance of Syncthing
89 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
90         var url, apiKey, home, binDir string
91         var err error
92
93         stCfg := conf.FileConf.SThgConf
94         if stCfg != nil {
95                 url = stCfg.GuiAddress
96                 apiKey = stCfg.GuiAPIKey
97                 home = stCfg.Home
98                 binDir = stCfg.BinDir
99         }
100
101         if url == "" {
102                 url = "http://localhost:8384"
103         }
104         if url[0:7] != "http://" {
105                 url = "http://" + url
106         }
107
108         if home == "" {
109                 home = "/mnt/share"
110         }
111
112         if binDir == "" {
113                 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
114                         binDir = "/usr/local/bin"
115                 }
116         }
117
118         s := SyncThing{
119                 BaseURL: url,
120                 APIKey:  apiKey,
121                 Home:    home,
122                 binDir:  binDir,
123                 logsDir: conf.FileConf.LogsDir,
124                 log:     log,
125                 conf:    conf,
126         }
127
128         return &s
129 }
130
131 // Start Starts syncthing process
132 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
133
134         // Kill existing process (useful for debug ;-) )
135         if os.Getenv("DEBUG_MODE") != "" {
136                 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
137         }
138
139         path, err := exec.LookPath(path.Join(s.binDir, exeName))
140         if err != nil {
141                 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
142         }
143         cmd := exec.Command(path, args...)
144         cmd.Env = os.Environ()
145         for _, ev := range env {
146                 cmd.Env = append(cmd.Env, ev)
147         }
148
149         // open log file
150         var outfile *os.File
151         logFilename := filepath.Join(s.logsDir, exeName+".log")
152         if s.logsDir != "" {
153                 outfile, err := os.Create(logFilename)
154                 if err != nil {
155                         return nil, fmt.Errorf("Cannot create log file %s", logFilename)
156                 }
157
158                 cmdOut, err := cmd.StdoutPipe()
159                 if err != nil {
160                         return nil, fmt.Errorf("Pipe stdout error for : %s", err)
161                 }
162
163                 go io.Copy(outfile, cmdOut)
164         }
165
166         err = cmd.Start()
167         if err != nil {
168                 return nil, err
169         }
170
171         *eChan = make(chan ExitChan, 1)
172         go func(c *exec.Cmd, oF *os.File) {
173                 status := 0
174                 sts, err := c.Process.Wait()
175                 if !sts.Success() {
176                         s := sts.Sys().(syscall.WaitStatus)
177                         status = s.ExitStatus()
178                 }
179                 if oF != nil {
180                         oF.Close()
181                 }
182                 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
183
184                 *eChan <- ExitChan{status, err}
185         }(cmd, outfile)
186
187         return cmd, nil
188 }
189
190 // Start Starts syncthing process
191 func (s *SyncThing) Start() (*exec.Cmd, error) {
192         var err error
193
194         s.log.Infof(" ST home=%s", s.Home)
195         s.log.Infof(" ST  url=%s", s.BaseURL)
196
197         args := []string{
198                 "--home=" + s.Home,
199                 "-no-browser",
200                 "--gui-address=" + s.BaseURL,
201         }
202
203         if s.APIKey != "" {
204                 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
205                 s.log.Infof(" ST apikey=%s", s.APIKey)
206         }
207         if s.log.Level == logrus.DebugLevel {
208                 args = append(args, "-verbose")
209         }
210
211         env := []string{
212                 "STNODEFAULTFOLDER=1",
213         }
214
215         s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
216
217         // Use autogenerated apikey if not set by config.json
218         if s.APIKey == "" {
219                 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
220                         defer fd.Close()
221                         if b, err := ioutil.ReadAll(fd); err == nil {
222                                 re := regexp.MustCompile("<apikey>(.*)</apikey>")
223                                 key := re.FindStringSubmatch(string(b))
224                                 if len(key) >= 1 {
225                                         s.APIKey = key[1]
226                                 }
227                         }
228                 }
229         }
230
231         return s.STCmd, err
232 }
233
234 // StartInotify Starts syncthing-inotify process
235 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
236         var err error
237         exeName := "syncthing-inotify"
238
239         s.log.Infof(" STI  url=%s", s.BaseURL)
240
241         args := []string{
242                 "-target=" + s.BaseURL,
243         }
244         if s.APIKey != "" {
245                 args = append(args, "-api="+s.APIKey)
246                 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
247         }
248         if s.log.Level == logrus.DebugLevel {
249                 args = append(args, "-verbosity=4")
250         }
251
252         env := []string{}
253
254         s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
255
256         return s.STICmd, err
257 }
258
259 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
260         if err := proc.Signal(os.Interrupt); err != nil {
261                 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
262
263                 select {
264                 case <-exit:
265                 case <-time.After(time.Second):
266                         // A bigger bonk on the head.
267                         if err := proc.Signal(os.Kill); err != nil {
268                                 s.log.Infof("Proc term %s error: %s", pname, err.Error())
269                         }
270                         <-exit
271                 }
272         }
273         s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
274 }
275
276 // Stop Stops syncthing process
277 func (s *SyncThing) Stop() {
278         if s.STCmd == nil {
279                 return
280         }
281         s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
282         s.STCmd = nil
283 }
284
285 // StopInotify Stops syncthing process
286 func (s *SyncThing) StopInotify() {
287         if s.STICmd == nil {
288                 return
289         }
290         s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
291         s.STICmd = nil
292 }
293
294 // Connect Establish HTTP connection with Syncthing
295 func (s *SyncThing) Connect() error {
296         var err error
297         s.client, err = common.HTTPNewClient(s.BaseURL,
298                 common.HTTPClientConfig{
299                         URLPrefix:           "/rest",
300                         HeaderClientKeyName: "X-Syncthing-ID",
301                 })
302         if err != nil {
303                 msg := ": " + err.Error()
304                 if strings.Contains(err.Error(), "connection refused") {
305                         msg = fmt.Sprintf("(url: %s)", s.BaseURL)
306                 }
307                 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
308         }
309         if s.client == nil {
310                 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
311         }
312
313         s.client.SetLogger(s.log)
314
315         return nil
316 }
317
318 // IDGet returns the Syncthing ID of Syncthing instance running locally
319 func (s *SyncThing) IDGet() (string, error) {
320         var data []byte
321         if err := s.client.HTTPGet("system/status", &data); err != nil {
322                 return "", err
323         }
324         status := make(map[string]interface{})
325         json.Unmarshal(data, &status)
326         return status["myID"].(string), nil
327 }
328
329 // ConfigGet returns the current Syncthing configuration
330 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
331         var data []byte
332         config := config.Configuration{}
333         if err := s.client.HTTPGet("system/config", &data); err != nil {
334                 return config, err
335         }
336         err := json.Unmarshal(data, &config)
337         return config, err
338 }
339
340 // ConfigSet set Syncthing configuration
341 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
342         body, err := json.Marshal(cfg)
343         if err != nil {
344                 return err
345         }
346         return s.client.HTTPPost("system/config", string(body))
347 }
348
349 // IsConfigInSync Returns true if configuration is in sync
350 func (s *SyncThing) IsConfigInSync() (bool, error) {
351         var data []byte
352         var d configInSync
353         if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
354                 return false, err
355         }
356         if err := json.Unmarshal(data, &d); err != nil {
357                 return false, err
358         }
359         return d.ConfigInSync, nil
360 }
361
362 // FolderStatus Returns all information about the current
363 func (s *SyncThing) FolderStatus(folderID string) (*FolderStatus, error) {
364         var data []byte
365         var res FolderStatus
366         if folderID == "" {
367                 return nil, fmt.Errorf("folderID not set")
368         }
369         if err := s.client.HTTPGet("db/status?folder="+folderID, &data); err != nil {
370                 return nil, err
371         }
372         if err := json.Unmarshal(data, &res); err != nil {
373                 return nil, err
374         }
375         return &res, nil
376 }
377
378 // IsFolderInSync Returns true when folder is in sync
379 func (s *SyncThing) IsFolderInSync(folderID string) (bool, error) {
380         // FIXME better to detected FolderCompletion event (/rest/events)
381         // See https://docs.syncthing.net/dev/events.html
382         sts, err := s.FolderStatus(folderID)
383         if err != nil {
384                 return false, err
385         }
386         return sts.NeedBytes == 0, nil
387 }
388
389 // FolderScan Request immediate folder scan.
390 // Scan all folders if folderID param is empty
391 func (s *SyncThing) FolderScan(folderID string, subpath string) error {
392         url := "db/scan"
393         if folderID != "" {
394                 url += "?folder=" + folderID
395
396                 if subpath != "" {
397                         url += "&sub=" + subpath
398                 }
399         }
400         return s.client.HTTPPost(url, "")
401 }