Add workaround for Syncthing apikey setting.
[src/xds/xds-agent.git] / lib / syncthing / st.go
1 package st
2
3 import (
4         "encoding/json"
5         "io"
6         "io/ioutil"
7         "os"
8         "path"
9         "path/filepath"
10         "regexp"
11         "strings"
12         "syscall"
13         "time"
14
15         "fmt"
16
17         "os/exec"
18
19         "github.com/Sirupsen/logrus"
20         "github.com/iotbzh/xds-agent/lib/common"
21         "github.com/iotbzh/xds-agent/lib/xdsconfig"
22         "github.com/syncthing/syncthing/lib/config"
23 )
24
25 // SyncThing .
26 type SyncThing struct {
27         BaseURL string
28         APIKey  string
29         Home    string
30         STCmd   *exec.Cmd
31         STICmd  *exec.Cmd
32
33         // Private fields
34         binDir      string
35         logsDir     string
36         exitSTChan  chan ExitChan
37         exitSTIChan chan ExitChan
38         client      *common.HTTPClient
39         log         *logrus.Logger
40 }
41
42 // ExitChan Channel used for process exit
43 type ExitChan struct {
44         status int
45         err    error
46 }
47
48 // NewSyncThing creates a new instance of Syncthing
49 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
50         var url, apiKey, home, binDir string
51         var err error
52
53         stCfg := conf.FileConf.SThgConf
54         if stCfg != nil {
55                 url = stCfg.GuiAddress
56                 apiKey = stCfg.GuiAPIKey
57                 home = stCfg.Home
58                 binDir = stCfg.BinDir
59         }
60
61         if url == "" {
62                 url = "http://localhost:8384"
63         }
64         if url[0:7] != "http://" {
65                 url = "http://" + url
66         }
67
68         if home == "" {
69                 home = "/mnt/share"
70         }
71
72         if binDir == "" {
73                 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
74                         binDir = "/usr/local/bin"
75                 }
76         }
77
78         s := SyncThing{
79                 BaseURL: url,
80                 APIKey:  apiKey,
81                 Home:    home,
82                 binDir:  binDir,
83                 logsDir: conf.FileConf.LogsDir,
84                 log:     log,
85         }
86
87         return &s
88 }
89
90 // Start Starts syncthing process
91 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
92
93         // Kill existing process (useful for debug ;-) )
94         if os.Getenv("DEBUG_MODE") != "" {
95                 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
96         }
97
98         path, err := exec.LookPath(path.Join(s.binDir, exeName))
99         if err != nil {
100                 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
101         }
102         cmd := exec.Command(path, args...)
103         cmd.Env = os.Environ()
104         for _, ev := range env {
105                 cmd.Env = append(cmd.Env, ev)
106         }
107
108         // open log file
109         var outfile *os.File
110         logFilename := filepath.Join(s.logsDir, exeName+".log")
111         if s.logsDir != "" {
112                 outfile, err := os.Create(logFilename)
113                 if err != nil {
114                         return nil, fmt.Errorf("Cannot create log file %s", logFilename)
115                 }
116
117                 cmdOut, err := cmd.StdoutPipe()
118                 if err != nil {
119                         return nil, fmt.Errorf("Pipe stdout error for : %s", err)
120                 }
121
122                 go io.Copy(outfile, cmdOut)
123         }
124
125         err = cmd.Start()
126         if err != nil {
127                 return nil, err
128         }
129
130         *eChan = make(chan ExitChan, 1)
131         go func(c *exec.Cmd, oF *os.File) {
132                 status := 0
133                 sts, err := c.Process.Wait()
134                 if !sts.Success() {
135                         s := sts.Sys().(syscall.WaitStatus)
136                         status = s.ExitStatus()
137                 }
138                 if oF != nil {
139                         oF.Close()
140                 }
141                 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
142
143                 *eChan <- ExitChan{status, err}
144         }(cmd, outfile)
145
146         return cmd, nil
147 }
148
149 // Start Starts syncthing process
150 func (s *SyncThing) Start() (*exec.Cmd, error) {
151         var err error
152
153         s.log.Infof(" ST home=%s", s.Home)
154         s.log.Infof(" ST  url=%s", s.BaseURL)
155
156         args := []string{
157                 "--home=" + s.Home,
158                 "-no-browser",
159                 "--gui-address=" + s.BaseURL,
160         }
161
162         if s.APIKey != "" {
163                 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
164                 s.log.Infof(" ST apikey=%s", s.APIKey)
165         }
166         if s.log.Level == logrus.DebugLevel {
167                 args = append(args, "-verbose")
168         }
169
170         env := []string{
171                 "STNODEFAULTFOLDER=1",
172                 "STNOUPGRADE=1",
173                 "STNORESTART=1",
174         }
175
176         // XXX - temporary hack because -gui-apikey seems to correctly handle by
177         // syncthing the early first time
178         stConfigFile := filepath.Join(s.Home, "config.xml")
179         if s.APIKey != "" && !common.Exists(stConfigFile) {
180                 s.log.Infof("Stop and restart Syncthing (hack for apikey setting)")
181                 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
182                 tmo := 20
183                 for ; tmo > 0; tmo-- {
184                         s.log.Debugf("Waiting Syncthing config.xml creation (%v)\n", tmo)
185                         time.Sleep(500 * time.Millisecond)
186                         if common.Exists(stConfigFile) {
187                                 break
188         }
189                 }
190                 if tmo <= 0 {
191                         return nil, fmt.Errorf("Cannot start Syncthing for config file creation")
192                 }
193                 s.Stop()
194                 read, err := ioutil.ReadFile(stConfigFile)
195                 if err != nil {
196                         return nil, fmt.Errorf("Cannot read Syncthing config file for apikey setting")
197                 }
198                 re := regexp.MustCompile(`<apikey>.*</apikey>`)
199                 newContents := re.ReplaceAllString(string(read), "<apikey>"+s.APIKey+"</apikey>")
200                 err = ioutil.WriteFile(stConfigFile, []byte(newContents), 0)
201                 if err != nil {
202                         return nil, fmt.Errorf("Cannot write Syncthing config file to set apikey")
203                 }
204         }
205
206         s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
207
208         // Use autogenerated apikey if not set by config.json
209         if s.APIKey == "" {
210                 if fd, err := os.Open(stConfigFile); err == nil {
211                         defer fd.Close()
212                         if b, err := ioutil.ReadAll(fd); err == nil {
213                                 re := regexp.MustCompile("<apikey>(.*)</apikey>")
214                                 key := re.FindStringSubmatch(string(b))
215                                 if len(key) >= 1 {
216                                         s.APIKey = key[1]
217                                 }
218                         }
219                 }
220         }
221
222         return s.STCmd, err
223 }
224
225 // StartInotify Starts syncthing-inotify process
226 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
227         var err error
228         exeName := "syncthing-inotify"
229
230         s.log.Infof(" STI  url=%s", s.BaseURL)
231
232         args := []string{
233                 "-target=" + s.BaseURL,
234         }
235         if s.APIKey != "" {
236                 args = append(args, "-api="+s.APIKey)
237                 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
238         }
239         if s.log.Level == logrus.DebugLevel {
240                 args = append(args, "-verbosity=4")
241         }
242
243         env := []string{}
244
245         s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
246
247         return s.STICmd, err
248 }
249
250 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
251         if err := proc.Signal(os.Interrupt); err != nil {
252                 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
253
254                 select {
255                 case <-exit:
256                 case <-time.After(time.Second):
257                         // A bigger bonk on the head.
258                         if err := proc.Signal(os.Kill); err != nil {
259                                 s.log.Infof("Proc term %s error: %s", pname, err.Error())
260                         }
261                         <-exit
262                 }
263         }
264         s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
265 }
266
267 // Stop Stops syncthing process
268 func (s *SyncThing) Stop() {
269         if s.STCmd == nil {
270                 return
271         }
272         s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
273         s.STCmd = nil
274 }
275
276 // StopInotify Stops syncthing process
277 func (s *SyncThing) StopInotify() {
278         if s.STICmd == nil {
279                 return
280         }
281         s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
282         s.STICmd = nil
283 }
284
285 // Connect Establish HTTP connection with Syncthing
286 func (s *SyncThing) Connect() error {
287         var err error
288         s.client, err = common.HTTPNewClient(s.BaseURL,
289                 common.HTTPClientConfig{
290                         URLPrefix:           "/rest",
291                         HeaderClientKeyName: "X-Syncthing-ID",
292                 })
293         if err != nil {
294                 msg := ": " + err.Error()
295                 if strings.Contains(err.Error(), "connection refused") {
296                         msg = fmt.Sprintf("(url: %s)", s.BaseURL)
297                 }
298                 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
299         }
300         if s.client == nil {
301                 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
302         }
303
304         s.client.SetLogger(s.log)
305
306         return nil
307 }
308
309 // IDGet returns the Syncthing ID of Syncthing instance running locally
310 func (s *SyncThing) IDGet() (string, error) {
311         var data []byte
312         if err := s.client.HTTPGet("system/status", &data); err != nil {
313                 return "", err
314         }
315         status := make(map[string]interface{})
316         json.Unmarshal(data, &status)
317         return status["myID"].(string), nil
318 }
319
320 // ConfigGet returns the current Syncthing configuration
321 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
322         var data []byte
323         config := config.Configuration{}
324         if err := s.client.HTTPGet("system/config", &data); err != nil {
325                 return config, err
326         }
327         err := json.Unmarshal(data, &config)
328         return config, err
329 }
330
331 // ConfigSet set Syncthing configuration
332 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
333         body, err := json.Marshal(cfg)
334         if err != nil {
335                 return err
336         }
337         return s.client.HTTPPost("system/config", string(body))
338 }