19 "github.com/Sirupsen/logrus"
20 "github.com/iotbzh/xds-agent/lib/xdsconfig"
21 common "github.com/iotbzh/xds-common/golib"
22 "github.com/syncthing/syncthing/lib/config"
26 type SyncThing struct {
36 exitSTChan chan ExitChan
37 exitSTIChan chan ExitChan
38 client *common.HTTPClient
42 // ExitChan Channel used for process exit
43 type ExitChan struct {
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
53 stCfg := conf.FileConf.SThgConf
55 url = stCfg.GuiAddress
56 apiKey = stCfg.GuiAPIKey
62 url = "http://localhost:8384"
64 if url[0:7] != "http://" {
73 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
74 binDir = "/usr/local/bin"
83 logsDir: conf.FileConf.LogsDir,
90 // Start Starts syncthing process
91 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
93 // Kill existing process (useful for debug ;-) )
94 if os.Getenv("DEBUG_MODE") != "" {
95 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
98 // When not set (or set to '.') set bin to path of xds-agent executable
100 if bdir == "" || bdir == "." {
101 if dir, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
106 path, err := exec.LookPath(path.Join(bdir, exeName))
108 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, bdir)
110 cmd := exec.Command(path, args...)
111 cmd.Env = os.Environ()
112 for _, ev := range env {
113 cmd.Env = append(cmd.Env, ev)
118 logFilename := filepath.Join(s.logsDir, exeName+".log")
120 outfile, err := os.Create(logFilename)
122 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
125 cmdOut, err := cmd.StdoutPipe()
127 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
130 go io.Copy(outfile, cmdOut)
138 *eChan = make(chan ExitChan, 1)
139 go func(c *exec.Cmd, oF *os.File) {
141 sts, err := c.Process.Wait()
143 s := sts.Sys().(syscall.WaitStatus)
144 status = s.ExitStatus()
149 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
151 *eChan <- ExitChan{status, err}
157 // Start Starts syncthing process
158 func (s *SyncThing) Start() (*exec.Cmd, error) {
161 s.log.Infof(" ST home=%s", s.Home)
162 s.log.Infof(" ST url=%s", s.BaseURL)
167 "--gui-address=" + s.BaseURL,
171 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
172 s.log.Infof(" ST apikey=%s", s.APIKey)
174 if s.log.Level == logrus.DebugLevel {
175 args = append(args, "-verbose")
179 "STNODEFAULTFOLDER=1",
183 // XXX - temporary hack because -gui-apikey seems to correctly handle by
184 // syncthing the early first time
185 stConfigFile := filepath.Join(s.Home, "config.xml")
186 if s.APIKey != "" && !common.Exists(stConfigFile) {
187 s.log.Infof("Stop and restart Syncthing (hack for apikey setting)")
188 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
190 for ; tmo > 0; tmo-- {
191 s.log.Debugf("Waiting Syncthing config.xml creation (%v)\n", tmo)
192 time.Sleep(500 * time.Millisecond)
193 if common.Exists(stConfigFile) {
198 return nil, fmt.Errorf("Cannot start Syncthing for config file creation")
201 read, err := ioutil.ReadFile(stConfigFile)
203 return nil, fmt.Errorf("Cannot read Syncthing config file for apikey setting")
205 re := regexp.MustCompile(`<apikey>.*</apikey>`)
206 newContents := re.ReplaceAllString(string(read), "<apikey>"+s.APIKey+"</apikey>")
207 err = ioutil.WriteFile(stConfigFile, []byte(newContents), 0)
209 return nil, fmt.Errorf("Cannot write Syncthing config file to set apikey")
213 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
215 // Use autogenerated apikey if not set by config.json
217 if fd, err := os.Open(stConfigFile); err == nil {
219 if b, err := ioutil.ReadAll(fd); err == nil {
220 re := regexp.MustCompile("<apikey>(.*)</apikey>")
221 key := re.FindStringSubmatch(string(b))
232 // StartInotify Starts syncthing-inotify process
233 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
235 exeName := "syncthing-inotify"
237 s.log.Infof(" STI url=%s", s.BaseURL)
240 "-target=" + s.BaseURL,
243 args = append(args, "-api="+s.APIKey)
244 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
246 if s.log.Level == logrus.DebugLevel {
247 args = append(args, "-verbosity=4")
252 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
257 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
258 if err := proc.Signal(os.Interrupt); err != nil {
259 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
263 case <-time.After(time.Second):
264 // A bigger bonk on the head.
265 if err := proc.Signal(os.Kill); err != nil {
266 s.log.Infof("Proc term %s error: %s", pname, err.Error())
271 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
274 // Stop Stops syncthing process
275 func (s *SyncThing) Stop() {
279 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
283 // StopInotify Stops syncthing process
284 func (s *SyncThing) StopInotify() {
288 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
292 // Connect Establish HTTP connection with Syncthing
293 func (s *SyncThing) Connect() error {
295 s.client, err = common.HTTPNewClient(s.BaseURL,
296 common.HTTPClientConfig{
298 HeaderClientKeyName: "X-Syncthing-ID",
301 msg := ": " + err.Error()
302 if strings.Contains(err.Error(), "connection refused") {
303 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
305 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
308 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
311 s.client.SetLogLevel(s.log.Level.String())
312 s.client.LoggerPrefix = "SYNCTHING: "
313 s.client.LoggerOut = s.log.Out
318 // IDGet returns the Syncthing ID of Syncthing instance running locally
319 func (s *SyncThing) IDGet() (string, error) {
321 if err := s.client.HTTPGet("system/status", &data); err != nil {
324 status := make(map[string]interface{})
325 json.Unmarshal(data, &status)
326 return status["myID"].(string), nil
329 // ConfigGet returns the current Syncthing configuration
330 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
332 config := config.Configuration{}
333 if err := s.client.HTTPGet("system/config", &data); err != nil {
336 err := json.Unmarshal(data, &config)
340 // ConfigSet set Syncthing configuration
341 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
342 body, err := json.Marshal(cfg)
346 return s.client.HTTPPost("system/config", string(body))