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 {
39 exitSTChan chan ExitChan
40 exitSTIChan chan ExitChan
41 client *common.HTTPClient
43 conf *xdsconfig.Config
46 // ExitChan Channel used for process exit
47 type ExitChan struct {
52 // ConfigInSync Check whether if Syncthing configuration is in sync
53 type configInSync struct {
54 ConfigInSync bool `json:"configInSync"`
57 // FolderStatus Information about the current status of a folder.
58 type FolderStatus struct {
59 GlobalFiles int `json:"globalFiles"`
60 GlobalDirectories int `json:"globalDirectories"`
61 GlobalSymlinks int `json:"globalSymlinks"`
62 GlobalDeleted int `json:"globalDeleted"`
63 GlobalBytes int64 `json:"globalBytes"`
65 LocalFiles int `json:"localFiles"`
66 LocalDirectories int `json:"localDirectories"`
67 LocalSymlinks int `json:"localSymlinks"`
68 LocalDeleted int `json:"localDeleted"`
69 LocalBytes int64 `json:"localBytes"`
71 NeedFiles int `json:"needFiles"`
72 NeedDirectories int `json:"needDirectories"`
73 NeedSymlinks int `json:"needSymlinks"`
74 NeedDeletes int `json:"needDeletes"`
75 NeedBytes int64 `json:"needBytes"`
77 InSyncFiles int `json:"inSyncFiles"`
78 InSyncBytes int64 `json:"inSyncBytes"`
80 State string `json:"state"`
81 StateChanged time.Time `json:"stateChanged"`
83 Sequence int64 `json:"sequence"`
85 IgnorePatterns bool `json:"ignorePatterns"`
88 // NewSyncThing creates a new instance of Syncthing
89 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
90 var url, apiKey, home, binDir string
92 stCfg := conf.FileConf.SThgConf
94 url = stCfg.GuiAddress
95 apiKey = stCfg.GuiAPIKey
101 url = "http://localhost:8386"
103 if url[0:7] != "http://" {
104 url = "http://" + url
108 panic("home parameter must be set")
116 logsDir: conf.FileConf.LogsDir,
121 // Create Events monitoring
122 s.Events = s.NewEventListener()
127 // Start Starts syncthing process
128 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
132 // Kill existing process (useful for debug ;-) )
133 if _, dbg := os.LookupEnv("XDS_DEBUG_MODE"); dbg {
134 fmt.Printf("\n!!! DEBUG_MODE set: KILL existing %s process(es) !!!\n", exeName)
135 exec.Command("bash", "-c", "ps -ax |grep "+exeName+" |grep "+s.BaseURL+" |cut -d' ' -f 1|xargs -I{} kill -9 {}").Output()
138 // When not set (or set to '.') set bin to path of xds-agent executable
140 if bdir == "" || bdir == "." {
141 exe, _ := os.Executable()
142 if exeAbsPath, err := filepath.Abs(exe); err == nil {
143 if exePath, err := filepath.EvalSymlinks(exeAbsPath); err == nil {
144 bdir = filepath.Dir(exePath)
149 exePath, err = exec.LookPath(path.Join(bdir, exeName))
151 // Let's try in /opt/AGL/bin
152 exePath, err = exec.LookPath(path.Join("opt", "AGL", "bin", exeName))
154 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, bdir)
157 cmd := exec.Command(exePath, args...)
158 cmd.Env = os.Environ()
159 for _, ev := range env {
160 cmd.Env = append(cmd.Env, ev)
165 logFilename := filepath.Join(s.logsDir, exeName+".log")
167 outfile, err := os.Create(logFilename)
169 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
172 cmdOut, err := cmd.StdoutPipe()
174 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
177 go io.Copy(outfile, cmdOut)
185 *eChan = make(chan ExitChan, 1)
186 go func(c *exec.Cmd, oF *os.File) {
188 sts, err := c.Process.Wait()
190 s := sts.Sys().(syscall.WaitStatus)
191 status = s.ExitStatus()
196 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
198 *eChan <- ExitChan{status, err}
204 // Start Starts syncthing process
205 func (s *SyncThing) Start() (*exec.Cmd, error) {
208 s.log.Infof(" ST home=%s", s.Home)
209 s.log.Infof(" ST url=%s", s.BaseURL)
214 "--gui-address=" + s.BaseURL,
218 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
219 s.log.Infof(" ST apikey=%s", s.APIKey)
221 if s.log.Level == logrus.DebugLevel {
222 args = append(args, "-verbose")
226 "STNODEFAULTFOLDER=1",
230 /* FIXME - STILL NEEDED ?, if not SUP code
232 // XXX - temporary hack because -gui-apikey seems to correctly handle by
233 // syncthing the early first time
234 stConfigFile := filepath.Join(s.Home, "config.xml")
235 if s.APIKey != "" && !common.Exists(stConfigFile) {
236 s.log.Infof("Stop and restart Syncthing (hack for apikey setting)")
237 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
239 for ; tmo > 0; tmo-- {
240 s.log.Debugf("Waiting Syncthing config.xml creation (%v)\n", tmo)
241 time.Sleep(500 * time.Millisecond)
242 if common.Exists(stConfigFile) {
247 return nil, fmt.Errorf("Cannot start Syncthing for config file creation")
250 read, err := ioutil.ReadFile(stConfigFile)
252 return nil, fmt.Errorf("Cannot read Syncthing config file for apikey setting")
254 re := regexp.MustCompile(`<apikey>.*</apikey>`)
255 newContents := re.ReplaceAllString(string(read), "<apikey>"+s.APIKey+"</apikey>")
256 err = ioutil.WriteFile(stConfigFile, []byte(newContents), 0)
258 return nil, fmt.Errorf("Cannot write Syncthing config file to set apikey")
262 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
264 // Use autogenerated apikey if not set by config.json
265 if err == nil && s.APIKey == "" {
266 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
268 if b, err := ioutil.ReadAll(fd); err == nil {
269 re := regexp.MustCompile("<apikey>(.*)</apikey>")
270 key := re.FindStringSubmatch(string(b))
281 // StartInotify Starts syncthing-inotify process
282 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
284 exeName := "syncthing-inotify"
286 s.log.Infof(" STI url=%s", s.BaseURL)
289 "-target=" + s.BaseURL,
292 args = append(args, "-api="+s.APIKey)
293 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
295 if s.log.Level == logrus.DebugLevel {
296 args = append(args, "-verbosity=4")
301 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
306 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
307 if err := proc.Signal(os.Interrupt); err != nil {
308 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
312 case <-time.After(time.Second):
313 // A bigger bonk on the head.
314 if err := proc.Signal(os.Kill); err != nil {
315 s.log.Infof("Proc term %s error: %s", pname, err.Error())
320 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
323 // Stop Stops syncthing process
324 func (s *SyncThing) Stop() {
328 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
332 // StopInotify Stops syncthing process
333 func (s *SyncThing) StopInotify() {
337 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
341 // Connect Establish HTTP connection with Syncthing
342 func (s *SyncThing) Connect() error {
345 s.client, err = common.HTTPNewClient(s.BaseURL,
346 common.HTTPClientConfig{
348 HeaderClientKeyName: "X-Syncthing-ID",
349 LogOut: s.conf.LogVerboseOut,
350 LogPrefix: "SYNCTHING: ",
351 LogLevel: common.HTTPLogLevelWarning,
353 s.client.SetLogLevel(s.log.Level.String())
356 msg := ": " + err.Error()
357 if strings.Contains(err.Error(), "connection refused") {
358 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
360 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
363 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
366 s.MyID, err = s.IDGet()
368 return fmt.Errorf("ERROR: cannot retrieve ID")
373 // Start events monitoring
374 err = s.Events.Start()
379 // IDGet returns the Syncthing ID of Syncthing instance running locally
380 func (s *SyncThing) IDGet() (string, error) {
382 if err := s.client.HTTPGet("system/status", &data); err != nil {
385 status := make(map[string]interface{})
386 json.Unmarshal(data, &status)
387 return status["myID"].(string), nil
390 // ConfigGet returns the current Syncthing configuration
391 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
393 config := config.Configuration{}
394 if err := s.client.HTTPGet("system/config", &data); err != nil {
397 err := json.Unmarshal(data, &config)
401 // ConfigSet set Syncthing configuration
402 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
403 body, err := json.Marshal(cfg)
407 return s.client.HTTPPost("system/config", string(body))
410 // IsConfigInSync Returns true if configuration is in sync
411 func (s *SyncThing) IsConfigInSync() (bool, error) {
414 if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
417 if err := json.Unmarshal(data, &d); err != nil {
420 return d.ConfigInSync, nil