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
48 // ExitChan Channel used for process exit
49 type ExitChan struct {
54 // ConfigInSync Check whether if Syncthing configuration is in sync
55 type configInSync struct {
56 ConfigInSync bool `json:"configInSync"`
59 // FolderStatus Information about the current status of a folder.
60 type FolderStatus struct {
61 GlobalFiles int `json:"globalFiles"`
62 GlobalDirectories int `json:"globalDirectories"`
63 GlobalSymlinks int `json:"globalSymlinks"`
64 GlobalDeleted int `json:"globalDeleted"`
65 GlobalBytes int64 `json:"globalBytes"`
67 LocalFiles int `json:"localFiles"`
68 LocalDirectories int `json:"localDirectories"`
69 LocalSymlinks int `json:"localSymlinks"`
70 LocalDeleted int `json:"localDeleted"`
71 LocalBytes int64 `json:"localBytes"`
73 NeedFiles int `json:"needFiles"`
74 NeedDirectories int `json:"needDirectories"`
75 NeedSymlinks int `json:"needSymlinks"`
76 NeedDeletes int `json:"needDeletes"`
77 NeedBytes int64 `json:"needBytes"`
79 InSyncFiles int `json:"inSyncFiles"`
80 InSyncBytes int64 `json:"inSyncBytes"`
82 State string `json:"state"`
83 StateChanged time.Time `json:"stateChanged"`
85 Sequence int64 `json:"sequence"`
87 IgnorePatterns bool `json:"ignorePatterns"`
90 // NewSyncThing creates a new instance of Syncthing
91 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
92 var url, apiKey, home, binDir string
95 stCfg := conf.FileConf.SThgConf
97 url = stCfg.GuiAddress
98 apiKey = stCfg.GuiAPIKey
100 binDir = stCfg.BinDir
104 url = "http://localhost:8384"
106 if url[0:7] != "http://" {
107 url = "http://" + url
115 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
116 binDir = "/usr/local/bin"
125 logsDir: conf.FileConf.LogsDir,
130 // Create Events monitoring
131 s.Events = s.NewEventListener()
136 // Start Starts syncthing process
137 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
139 // Kill existing process (useful for debug ;-) )
140 if os.Getenv("DEBUG_MODE") != "" {
141 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
144 path, err := exec.LookPath(path.Join(s.binDir, exeName))
146 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
148 cmd := exec.Command(path, args...)
149 cmd.Env = os.Environ()
150 for _, ev := range env {
151 cmd.Env = append(cmd.Env, ev)
156 logFilename := filepath.Join(s.logsDir, exeName+".log")
158 outfile, err := os.Create(logFilename)
160 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
163 cmdOut, err := cmd.StdoutPipe()
165 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
168 go io.Copy(outfile, cmdOut)
176 *eChan = make(chan ExitChan, 1)
177 go func(c *exec.Cmd, oF *os.File) {
179 sts, err := c.Process.Wait()
181 s := sts.Sys().(syscall.WaitStatus)
182 status = s.ExitStatus()
187 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
189 *eChan <- ExitChan{status, err}
195 // Start Starts syncthing process
196 func (s *SyncThing) Start() (*exec.Cmd, error) {
199 s.log.Infof(" ST home=%s", s.Home)
200 s.log.Infof(" ST url=%s", s.BaseURL)
205 "--gui-address=" + s.BaseURL,
209 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
210 s.log.Infof(" ST apikey=%s", s.APIKey)
212 if s.log.Level == logrus.DebugLevel {
213 args = append(args, "-verbose")
217 "STNODEFAULTFOLDER=1",
219 "STNORESTART=1", // FIXME SEB remove ?
222 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
224 // Use autogenerated apikey if not set by config.json
225 if err == nil && s.APIKey == "" {
226 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
228 if b, err := ioutil.ReadAll(fd); err == nil {
229 re := regexp.MustCompile("<apikey>(.*)</apikey>")
230 key := re.FindStringSubmatch(string(b))
241 // StartInotify Starts syncthing-inotify process
242 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
244 exeName := "syncthing-inotify"
246 s.log.Infof(" STI url=%s", s.BaseURL)
249 "-target=" + s.BaseURL,
252 args = append(args, "-api="+s.APIKey)
253 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
255 if s.log.Level == logrus.DebugLevel {
256 args = append(args, "-verbosity=4")
261 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
266 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
267 if err := proc.Signal(os.Interrupt); err != nil {
268 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
272 case <-time.After(time.Second):
273 // A bigger bonk on the head.
274 if err := proc.Signal(os.Kill); err != nil {
275 s.log.Infof("Proc term %s error: %s", pname, err.Error())
280 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
283 // Stop Stops syncthing process
284 func (s *SyncThing) Stop() {
288 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
292 // StopInotify Stops syncthing process
293 func (s *SyncThing) StopInotify() {
297 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
301 // Connect Establish HTTP connection with Syncthing
302 func (s *SyncThing) Connect() error {
304 s.client, err = common.HTTPNewClient(s.BaseURL,
305 common.HTTPClientConfig{
307 HeaderClientKeyName: "X-Syncthing-ID",
310 msg := ": " + err.Error()
311 if strings.Contains(err.Error(), "connection refused") {
312 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
314 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
317 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
320 s.client.SetLogger(s.log)
322 s.MyID, err = s.IDGet()
324 return fmt.Errorf("ERROR: cannot retrieve ID")
327 // Start events monitoring
328 err = s.Events.Start()
333 // IDGet returns the Syncthing ID of Syncthing instance running locally
334 func (s *SyncThing) IDGet() (string, error) {
336 if err := s.client.HTTPGet("system/status", &data); err != nil {
339 status := make(map[string]interface{})
340 json.Unmarshal(data, &status)
341 return status["myID"].(string), nil
344 // ConfigGet returns the current Syncthing configuration
345 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
347 config := config.Configuration{}
348 if err := s.client.HTTPGet("system/config", &data); err != nil {
351 err := json.Unmarshal(data, &config)
355 // ConfigSet set Syncthing configuration
356 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
357 body, err := json.Marshal(cfg)
361 return s.client.HTTPPost("system/config", string(body))
364 // IsConfigInSync Returns true if configuration is in sync
365 func (s *SyncThing) IsConfigInSync() (bool, error) {
368 if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
371 if err := json.Unmarshal(data, &d); err != nil {
374 return d.ConfigInSync, nil