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 conf *xdsconfig.Config
42 client *common.HTTPClient
46 // ExitChan Channel used for process exit
47 type ExitChan struct {
52 // NewSyncThing creates a new instance of Syncthing
53 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
54 var url, apiKey, home, binDir string
57 stCfg := conf.FileConf.SThgConf
59 url = stCfg.GuiAddress
60 apiKey = stCfg.GuiAPIKey
66 url = "http://localhost:8384"
68 if url[0:7] != "http://" {
77 if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
78 binDir = "/usr/local/bin"
87 logsDir: conf.FileConf.LogsDir,
95 // Start Starts syncthing process
96 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
98 // Kill existing process (useful for debug ;-) )
99 if os.Getenv("DEBUG_MODE") != "" {
100 exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
103 path, err := exec.LookPath(path.Join(s.binDir, exeName))
105 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
107 cmd := exec.Command(path, args...)
108 cmd.Env = os.Environ()
109 for _, ev := range env {
110 cmd.Env = append(cmd.Env, ev)
115 logFilename := filepath.Join(s.logsDir, exeName+".log")
117 outfile, err := os.Create(logFilename)
119 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
122 cmdOut, err := cmd.StdoutPipe()
124 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
127 go io.Copy(outfile, cmdOut)
135 *eChan = make(chan ExitChan, 1)
136 go func(c *exec.Cmd, oF *os.File) {
138 sts, err := c.Process.Wait()
140 s := sts.Sys().(syscall.WaitStatus)
141 status = s.ExitStatus()
146 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
148 *eChan <- ExitChan{status, err}
154 // Start Starts syncthing process
155 func (s *SyncThing) Start() (*exec.Cmd, error) {
158 s.log.Infof(" ST home=%s", s.Home)
159 s.log.Infof(" ST url=%s", s.BaseURL)
164 "--gui-address=" + s.BaseURL,
168 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
169 s.log.Infof(" ST apikey=%s", s.APIKey)
171 if s.log.Level == logrus.DebugLevel {
172 args = append(args, "-verbose")
176 "STNODEFAULTFOLDER=1",
179 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
181 // Use autogenerated apikey if not set by config.json
183 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
185 if b, err := ioutil.ReadAll(fd); err == nil {
186 re := regexp.MustCompile("<apikey>(.*)</apikey>")
187 key := re.FindStringSubmatch(string(b))
198 // StartInotify Starts syncthing-inotify process
199 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
201 exeName := "syncthing-inotify"
203 s.log.Infof(" STI url=%s", s.BaseURL)
206 "-target=" + s.BaseURL,
209 args = append(args, "-api="+s.APIKey)
210 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
212 if s.log.Level == logrus.DebugLevel {
213 args = append(args, "-verbosity=4")
218 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
223 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
224 if err := proc.Signal(os.Interrupt); err != nil {
225 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
229 case <-time.After(time.Second):
230 // A bigger bonk on the head.
231 if err := proc.Signal(os.Kill); err != nil {
232 s.log.Infof("Proc term %s error: %s", pname, err.Error())
237 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
240 // Stop Stops syncthing process
241 func (s *SyncThing) Stop() {
245 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
249 // StopInotify Stops syncthing process
250 func (s *SyncThing) StopInotify() {
254 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
258 // Connect Establish HTTP connection with Syncthing
259 func (s *SyncThing) Connect() error {
261 s.client, err = common.HTTPNewClient(s.BaseURL,
262 common.HTTPClientConfig{
264 HeaderClientKeyName: "X-Syncthing-ID",
267 msg := ": " + err.Error()
268 if strings.Contains(err.Error(), "connection refused") {
269 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
271 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
274 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
277 s.client.SetLogger(s.log)
282 // IDGet returns the Syncthing ID of Syncthing instance running locally
283 func (s *SyncThing) IDGet() (string, error) {
285 if err := s.client.HTTPGet("system/status", &data); err != nil {
288 status := make(map[string]interface{})
289 json.Unmarshal(data, &status)
290 return status["myID"].(string), nil
293 // ConfigGet returns the current Syncthing configuration
294 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
296 config := config.Configuration{}
297 if err := s.client.HTTPGet("system/config", &data); err != nil {
300 err := json.Unmarshal(data, &config)
304 // ConfigSet set Syncthing configuration
305 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
306 body, err := json.Marshal(cfg)
310 return s.client.HTTPPost("system/config", string(body))