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