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"
29 type SyncThing struct {
40 exitSTChan chan ExitChan
41 exitSTIChan chan ExitChan
42 conf *xdsconfig.Config
43 client *common.HTTPClient
47 // ExitChan Channel used for process exit
48 type ExitChan struct {
53 // ConfigInSync Check whether if Syncthing configuration is in sync
54 type configInSync struct {
55 ConfigInSync bool `json:"configInSync"`
58 // FolderStatus Information about the current status of a folder.
59 type FolderStatus struct {
60 GlobalFiles int `json:"globalFiles"`
61 GlobalDirectories int `json:"globalDirectories"`
62 GlobalSymlinks int `json:"globalSymlinks"`
63 GlobalDeleted int `json:"globalDeleted"`
64 GlobalBytes int64 `json:"globalBytes"`
66 LocalFiles int `json:"localFiles"`
67 LocalDirectories int `json:"localDirectories"`
68 LocalSymlinks int `json:"localSymlinks"`
69 LocalDeleted int `json:"localDeleted"`
70 LocalBytes int64 `json:"localBytes"`
72 NeedFiles int `json:"needFiles"`
73 NeedDirectories int `json:"needDirectories"`
74 NeedSymlinks int `json:"needSymlinks"`
75 NeedDeletes int `json:"needDeletes"`
76 NeedBytes int64 `json:"needBytes"`
78 InSyncFiles int `json:"inSyncFiles"`
79 InSyncBytes int64 `json:"inSyncBytes"`
81 State string `json:"state"`
82 StateChanged time.Time `json:"stateChanged"`
84 Sequence int64 `json:"sequence"`
86 IgnorePatterns bool `json:"ignorePatterns"`
89 // NewSyncThing creates a new instance of Syncthing
90 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
91 var url, apiKey, home, binDir string
94 stCfg := conf.FileConf.SThgConf
96 url = stCfg.GuiAddress
97 apiKey = stCfg.GuiAPIKey
103 url = "http://localhost:8384"
105 if url[0:7] != "http://" {
106 url = "http://" + url
114 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
115 binDir = "/usr/local/bin"
124 logsDir: conf.FileConf.LogsDir,
132 // Start Starts syncthing process
133 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
135 // Kill existing process (useful for debug ;-) )
136 if os.Getenv("DEBUG_MODE") != "" {
137 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
140 path, err := exec.LookPath(path.Join(s.binDir, exeName))
142 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
144 cmd := exec.Command(path, args...)
145 cmd.Env = os.Environ()
146 for _, ev := range env {
147 cmd.Env = append(cmd.Env, ev)
152 logFilename := filepath.Join(s.logsDir, exeName+".log")
154 outfile, err := os.Create(logFilename)
156 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
159 cmdOut, err := cmd.StdoutPipe()
161 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
164 go io.Copy(outfile, cmdOut)
172 *eChan = make(chan ExitChan, 1)
173 go func(c *exec.Cmd, oF *os.File) {
175 sts, err := c.Process.Wait()
177 s := sts.Sys().(syscall.WaitStatus)
178 status = s.ExitStatus()
183 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
185 *eChan <- ExitChan{status, err}
191 // Start Starts syncthing process
192 func (s *SyncThing) Start() (*exec.Cmd, error) {
195 s.log.Infof(" ST home=%s", s.Home)
196 s.log.Infof(" ST url=%s", s.BaseURL)
201 "--gui-address=" + s.BaseURL,
205 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
206 s.log.Infof(" ST apikey=%s", s.APIKey)
208 if s.log.Level == logrus.DebugLevel {
209 args = append(args, "-verbose")
213 "STNODEFAULTFOLDER=1",
215 "STNORESTART=1", // FIXME SEB remove ?
218 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
220 // Use autogenerated apikey if not set by config.json
221 if err == nil && s.APIKey == "" {
222 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
224 if b, err := ioutil.ReadAll(fd); err == nil {
225 re := regexp.MustCompile("<apikey>(.*)</apikey>")
226 key := re.FindStringSubmatch(string(b))
237 // StartInotify Starts syncthing-inotify process
238 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
240 exeName := "syncthing-inotify"
242 s.log.Infof(" STI url=%s", s.BaseURL)
245 "-target=" + s.BaseURL,
248 args = append(args, "-api="+s.APIKey)
249 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
251 if s.log.Level == logrus.DebugLevel {
252 args = append(args, "-verbosity=4")
257 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
262 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
263 if err := proc.Signal(os.Interrupt); err != nil {
264 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
268 case <-time.After(time.Second):
269 // A bigger bonk on the head.
270 if err := proc.Signal(os.Kill); err != nil {
271 s.log.Infof("Proc term %s error: %s", pname, err.Error())
276 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
279 // Stop Stops syncthing process
280 func (s *SyncThing) Stop() {
284 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
288 // StopInotify Stops syncthing process
289 func (s *SyncThing) StopInotify() {
293 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
297 // Connect Establish HTTP connection with Syncthing
298 func (s *SyncThing) Connect() error {
300 s.client, err = common.HTTPNewClient(s.BaseURL,
301 common.HTTPClientConfig{
303 HeaderClientKeyName: "X-Syncthing-ID",
306 msg := ": " + err.Error()
307 if strings.Contains(err.Error(), "connection refused") {
308 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
310 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
313 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
316 s.client.SetLogger(s.log)
318 s.MyID, err = s.IDGet()
323 // IDGet returns the Syncthing ID of Syncthing instance running locally
324 func (s *SyncThing) IDGet() (string, error) {
326 if err := s.client.HTTPGet("system/status", &data); err != nil {
329 status := make(map[string]interface{})
330 json.Unmarshal(data, &status)
331 return status["myID"].(string), nil
334 // ConfigGet returns the current Syncthing configuration
335 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
337 config := config.Configuration{}
338 if err := s.client.HTTPGet("system/config", &data); err != nil {
341 err := json.Unmarshal(data, &config)
345 // ConfigSet set Syncthing configuration
346 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
347 body, err := json.Marshal(cfg)
351 return s.client.HTTPPost("system/config", string(body))
354 // IsConfigInSync Returns true if configuration is in sync
355 func (s *SyncThing) IsConfigInSync() (bool, error) {
358 if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
361 if err := json.Unmarshal(data, &d); err != nil {
364 return d.ConfigInSync, nil