22 "github.com/Sirupsen/logrus"
23 "github.com/iotbzh/xds-server/lib/common"
24 "github.com/iotbzh/xds-server/lib/xdsconfig"
25 "github.com/syncthing/syncthing/lib/config"
29 type SyncThing struct {
39 exitSTChan chan ExitChan
40 exitSTIChan chan ExitChan
41 client *common.HTTPClient
45 // ExitChan Channel used for process exit
46 type ExitChan struct {
51 // NewSyncThing creates a new instance of Syncthing
52 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
53 var url, apiKey, home, binDir string
56 stCfg := conf.FileConf.SThgConf
58 url = stCfg.GuiAddress
59 apiKey = stCfg.GuiAPIKey
65 url = "http://localhost:8384"
67 if url[0:7] != "http://" {
76 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
77 binDir = "/usr/local/bin"
86 logsDir: conf.FileConf.LogsDir,
93 // Start Starts syncthing process
94 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
96 // Kill existing process (useful for debug ;-) )
97 if os.Getenv("DEBUG_MODE") != "" {
98 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
101 path, err := exec.LookPath(path.Join(s.binDir, exeName))
103 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
105 cmd := exec.Command(path, args...)
106 cmd.Env = os.Environ()
107 for _, ev := range env {
108 cmd.Env = append(cmd.Env, ev)
113 logFilename := filepath.Join(s.logsDir, exeName+".log")
115 outfile, err := os.Create(logFilename)
117 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
120 cmdOut, err := cmd.StdoutPipe()
122 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
125 go io.Copy(outfile, cmdOut)
133 *eChan = make(chan ExitChan, 1)
134 go func(c *exec.Cmd, oF *os.File) {
136 sts, err := c.Process.Wait()
138 s := sts.Sys().(syscall.WaitStatus)
139 status = s.ExitStatus()
144 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
146 *eChan <- ExitChan{status, err}
152 // Start Starts syncthing process
153 func (s *SyncThing) Start() (*exec.Cmd, error) {
156 s.log.Infof(" ST home=%s", s.Home)
157 s.log.Infof(" ST url=%s", s.BaseURL)
162 "--gui-address=" + s.BaseURL,
166 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
167 s.log.Infof(" ST apikey=%s", s.APIKey)
169 if s.log.Level == logrus.DebugLevel {
170 args = append(args, "-verbose")
174 "STNODEFAULTFOLDER=1",
177 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
179 // Use autogenerated apikey if not set by config.json
181 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
183 if b, err := ioutil.ReadAll(fd); err == nil {
184 re := regexp.MustCompile("<apikey>(.*)</apikey>")
185 key := re.FindStringSubmatch(string(b))
196 // StartInotify Starts syncthing-inotify process
197 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
199 exeName := "syncthing-inotify"
201 s.log.Infof(" STI url=%s", s.BaseURL)
204 "-target=" + s.BaseURL,
207 args = append(args, "-api="+s.APIKey)
208 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
210 if s.log.Level == logrus.DebugLevel {
211 args = append(args, "-verbosity=4")
216 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
221 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
222 if err := proc.Signal(os.Interrupt); err != nil {
223 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
227 case <-time.After(time.Second):
228 // A bigger bonk on the head.
229 if err := proc.Signal(os.Kill); err != nil {
230 s.log.Infof("Proc term %s error: %s", pname, err.Error())
235 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
238 // Stop Stops syncthing process
239 func (s *SyncThing) Stop() {
243 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
247 // StopInotify Stops syncthing process
248 func (s *SyncThing) StopInotify() {
252 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
256 // Connect Establish HTTP connection with Syncthing
257 func (s *SyncThing) Connect() error {
259 s.client, err = common.HTTPNewClient(s.BaseURL,
260 common.HTTPClientConfig{
262 HeaderClientKeyName: "X-Syncthing-ID",
265 msg := ": " + err.Error()
266 if strings.Contains(err.Error(), "connection refused") {
267 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
269 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
272 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
275 s.client.SetLogger(s.log)
280 // IDGet returns the Syncthing ID of Syncthing instance running locally
281 func (s *SyncThing) IDGet() (string, error) {
283 if err := s.client.HTTPGet("system/status", &data); err != nil {
286 status := make(map[string]interface{})
287 json.Unmarshal(data, &status)
288 return status["myID"].(string), nil
291 // ConfigGet returns the current Syncthing configuration
292 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
294 config := config.Configuration{}
295 if err := s.client.HTTPGet("system/config", &data); err != nil {
298 err := json.Unmarshal(data, &config)
302 // ConfigSet set Syncthing configuration
303 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
304 body, err := json.Marshal(cfg)
308 return s.client.HTTPPost("system/config", string(body))