Fix syncthing logger
[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         }
231
232         s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
233
234         // Use autogenerated apikey if not set by config.json
235         if err == nil && s.APIKey == "" {
236                 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
237                         defer fd.Close()
238                         if b, err := ioutil.ReadAll(fd); err == nil {
239                                 re := regexp.MustCompile("<apikey>(.*)</apikey>")
240                                 key := re.FindStringSubmatch(string(b))
241                                 if len(key) >= 1 {
242                                         s.APIKey = key[1]
243                                 }
244                         }
245                 }
246         }
247
248         return s.STCmd, err
249 }
250
251 // StartInotify Starts syncthing-inotify process
252 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
253         var err error
254         exeName := "syncthing-inotify"
255
256         s.log.Infof(" STI  url=%s", s.BaseURL)
257
258         args := []string{
259                 "-target=" + s.BaseURL,
260         }
261         if s.APIKey != "" {
262                 args = append(args, "-api="+s.APIKey)
263                 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
264         }
265         if s.log.Level == logrus.DebugLevel {
266                 args = append(args, "-verbosity=4")
267         }
268
269         env := []string{}
270
271         s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
272
273         return s.STICmd, err
274 }
275
276 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
277         if err := proc.Signal(os.Interrupt); err != nil {
278                 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
279
280                 select {
281                 case <-exit:
282                 case <-time.After(time.Second):
283                         // A bigger bonk on the head.
284                         if err := proc.Signal(os.Kill); err != nil {
285                                 s.log.Infof("Proc term %s error: %s", pname, err.Error())
286                         }
287                         <-exit
288                 }
289         }
290         s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
291 }
292
293 // Stop Stops syncthing process
294 func (s *SyncThing) Stop() {
295         if s.STCmd == nil {
296                 return
297         }
298         s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
299         s.STCmd = nil
300 }
301
302 // StopInotify Stops syncthing process
303 func (s *SyncThing) StopInotify() {
304         if s.STICmd == nil {
305                 return
306         }
307         s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
308         s.STICmd = nil
309 }
310
311 // Connect Establish HTTP connection with Syncthing
312 func (s *SyncThing) Connect() error {
313         var err error
314         s.Connected = false
315         s.client, err = common.HTTPNewClient(s.BaseURL,
316                 common.HTTPClientConfig{
317                         URLPrefix:           "/rest",
318                         HeaderClientKeyName: "X-Syncthing-ID",
319                         LogOut:              s.conf.LogVerboseOut,
320                         LogPrefix:           "SYNCTHING: ",
321                         LogLevel:            common.HTTPLogLevelWarning,
322                 })
323         s.client.SetLogLevel(s.log.Level.String())
324
325         if err != nil {
326                 msg := ": " + err.Error()
327                 if strings.Contains(err.Error(), "connection refused") {
328                         msg = fmt.Sprintf("(url: %s)", s.BaseURL)
329                 }
330                 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
331         }
332         if s.client == nil {
333                 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
334         }
335
336         s.MyID, err = s.IDGet()
337         if err != nil {
338                 return fmt.Errorf("ERROR: cannot retrieve ID")
339         }
340
341         s.Connected = true
342
343         // Start events monitoring
344         err = s.Events.Start()
345
346         return err
347 }
348
349 // IDGet returns the Syncthing ID of Syncthing instance running locally
350 func (s *SyncThing) IDGet() (string, error) {
351         var data []byte
352         if err := s.client.HTTPGet("system/status", &data); err != nil {
353                 return "", err
354         }
355         status := make(map[string]interface{})
356         json.Unmarshal(data, &status)
357         return status["myID"].(string), nil
358 }
359
360 // ConfigGet returns the current Syncthing configuration
361 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
362         var data []byte
363         config := config.Configuration{}
364         if err := s.client.HTTPGet("system/config", &data); err != nil {
365                 return config, err
366         }
367         err := json.Unmarshal(data, &config)
368         return config, err
369 }
370
371 // ConfigSet set Syncthing configuration
372 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
373         body, err := json.Marshal(cfg)
374         if err != nil {
375                 return err
376         }
377         return s.client.HTTPPost("system/config", string(body))
378 }
379
380 // IsConfigInSync Returns true if configuration is in sync
381 func (s *SyncThing) IsConfigInSync() (bool, error) {
382         var data []byte
383         var d configInSync
384         if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
385                 return false, err
386         }
387         if err := json.Unmarshal(data, &d); err != nil {
388                 return false, err
389         }
390         return d.ConfigInSync, nil
391 }