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 path, err := exec.LookPath(path.Join(s.binDir, exeName))
100 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
102 cmd := exec.Command(path, args...)
103 cmd.Env = os.Environ()
104 for _, ev := range env {
105 cmd.Env = append(cmd.Env, ev)
110 logFilename := filepath.Join(s.logsDir, exeName+".log")
112 outfile, err := os.Create(logFilename)
114 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
117 cmdOut, err := cmd.StdoutPipe()
119 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
122 go io.Copy(outfile, cmdOut)
130 *eChan = make(chan ExitChan, 1)
131 go func(c *exec.Cmd, oF *os.File) {
133 sts, err := c.Process.Wait()
135 s := sts.Sys().(syscall.WaitStatus)
136 status = s.ExitStatus()
141 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
143 *eChan <- ExitChan{status, err}
149 // Start Starts syncthing process
150 func (s *SyncThing) Start() (*exec.Cmd, error) {
153 s.log.Infof(" ST home=%s", s.Home)
154 s.log.Infof(" ST url=%s", s.BaseURL)
159 "--gui-address=" + s.BaseURL,
163 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
164 s.log.Infof(" ST apikey=%s", s.APIKey)
166 if s.log.Level == logrus.DebugLevel {
167 args = append(args, "-verbose")
171 "STNODEFAULTFOLDER=1",
175 // XXX - temporary hack because -gui-apikey seems to correctly handle by
176 // syncthing the early first time
177 stConfigFile := filepath.Join(s.Home, "config.xml")
178 if s.APIKey != "" && !common.Exists(stConfigFile) {
179 s.log.Infof("Stop and restart Syncthing (hack for apikey setting)")
180 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
182 for ; tmo > 0; tmo-- {
183 s.log.Debugf("Waiting Syncthing config.xml creation (%v)\n", tmo)
184 time.Sleep(500 * time.Millisecond)
185 if common.Exists(stConfigFile) {
190 return nil, fmt.Errorf("Cannot start Syncthing for config file creation")
193 read, err := ioutil.ReadFile(stConfigFile)
195 return nil, fmt.Errorf("Cannot read Syncthing config file for apikey setting")
197 re := regexp.MustCompile(`<apikey>.*</apikey>`)
198 newContents := re.ReplaceAllString(string(read), "<apikey>"+s.APIKey+"</apikey>")
199 err = ioutil.WriteFile(stConfigFile, []byte(newContents), 0)
201 return nil, fmt.Errorf("Cannot write Syncthing config file to set apikey")
205 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
207 // Use autogenerated apikey if not set by config.json
209 if fd, err := os.Open(stConfigFile); err == nil {
211 if b, err := ioutil.ReadAll(fd); err == nil {
212 re := regexp.MustCompile("<apikey>(.*)</apikey>")
213 key := re.FindStringSubmatch(string(b))
224 // StartInotify Starts syncthing-inotify process
225 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
227 exeName := "syncthing-inotify"
229 s.log.Infof(" STI url=%s", s.BaseURL)
232 "-target=" + s.BaseURL,
235 args = append(args, "-api="+s.APIKey)
236 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
238 if s.log.Level == logrus.DebugLevel {
239 args = append(args, "-verbosity=4")
244 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
249 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
250 if err := proc.Signal(os.Interrupt); err != nil {
251 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
255 case <-time.After(time.Second):
256 // A bigger bonk on the head.
257 if err := proc.Signal(os.Kill); err != nil {
258 s.log.Infof("Proc term %s error: %s", pname, err.Error())
263 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
266 // Stop Stops syncthing process
267 func (s *SyncThing) Stop() {
271 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
275 // StopInotify Stops syncthing process
276 func (s *SyncThing) StopInotify() {
280 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
284 // Connect Establish HTTP connection with Syncthing
285 func (s *SyncThing) Connect() error {
287 s.client, err = common.HTTPNewClient(s.BaseURL,
288 common.HTTPClientConfig{
290 HeaderClientKeyName: "X-Syncthing-ID",
293 msg := ": " + err.Error()
294 if strings.Contains(err.Error(), "connection refused") {
295 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
297 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
300 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
303 s.client.SetLogger(s.log)
308 // IDGet returns the Syncthing ID of Syncthing instance running locally
309 func (s *SyncThing) IDGet() (string, error) {
311 if err := s.client.HTTPGet("system/status", &data); err != nil {
314 status := make(map[string]interface{})
315 json.Unmarshal(data, &status)
316 return status["myID"].(string), nil
319 // ConfigGet returns the current Syncthing configuration
320 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
322 config := config.Configuration{}
323 if err := s.client.HTTPGet("system/config", &data); err != nil {
326 err := json.Unmarshal(data, &config)
330 // ConfigSet set Syncthing configuration
331 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
332 body, err := json.Marshal(cfg)
336 return s.client.HTTPPost("system/config", string(body))