2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
39 "github.com/Sirupsen/logrus"
40 common "github.com/iotbzh/xds-common/golib"
41 "github.com/iotbzh/xds-server/lib/xdsconfig"
42 "github.com/syncthing/syncthing/lib/config"
46 type SyncThing struct {
59 exitSTChan chan ExitChan
60 exitSTIChan chan ExitChan
61 client *common.HTTPClient
63 conf *xdsconfig.Config
66 // ExitChan Channel used for process exit
67 type ExitChan struct {
72 // ConfigInSync Check whether if Syncthing configuration is in sync
73 type configInSync struct {
74 ConfigInSync bool `json:"configInSync"`
77 // FolderStatus Information about the current status of a folder.
78 type FolderStatus struct {
79 GlobalFiles int `json:"globalFiles"`
80 GlobalDirectories int `json:"globalDirectories"`
81 GlobalSymlinks int `json:"globalSymlinks"`
82 GlobalDeleted int `json:"globalDeleted"`
83 GlobalBytes int64 `json:"globalBytes"`
85 LocalFiles int `json:"localFiles"`
86 LocalDirectories int `json:"localDirectories"`
87 LocalSymlinks int `json:"localSymlinks"`
88 LocalDeleted int `json:"localDeleted"`
89 LocalBytes int64 `json:"localBytes"`
91 NeedFiles int `json:"needFiles"`
92 NeedDirectories int `json:"needDirectories"`
93 NeedSymlinks int `json:"needSymlinks"`
94 NeedDeletes int `json:"needDeletes"`
95 NeedBytes int64 `json:"needBytes"`
97 InSyncFiles int `json:"inSyncFiles"`
98 InSyncBytes int64 `json:"inSyncBytes"`
100 State string `json:"state"`
101 StateChanged time.Time `json:"stateChanged"`
103 Sequence int64 `json:"sequence"`
105 IgnorePatterns bool `json:"ignorePatterns"`
108 // NewSyncThing creates a new instance of Syncthing
109 func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
110 var url, apiKey, home, binDir string
112 stCfg := conf.FileConf.SThgConf
114 url = stCfg.GuiAddress
115 apiKey = stCfg.GuiAPIKey
117 binDir = stCfg.BinDir
121 url = "http://localhost:8385"
123 if url[0:7] != "http://" {
124 url = "http://" + url
128 panic("home parameter must be set")
136 logsDir: conf.FileConf.LogsDir,
141 // Create Events monitoring
142 s.Events = s.NewEventListener()
147 // Start Starts syncthing process
148 func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {
152 // Kill existing process (useful for debug ;-) )
153 if os.Getenv("DEBUG_MODE") != "" {
154 fmt.Printf("\n!!! DEBUG_MODE set: KILL existing %s process(es) !!!\n", exeName)
155 exec.Command("bash", "-c", "ps -ax |grep "+exeName+" |grep "+s.BaseURL+" |cut -d' ' -f 1|xargs -I{} kill -9 {}").Output()
158 // When not set (or set to '.') set bin to path of xds-agent executable
160 if bdir == "" || bdir == "." {
161 exe, _ := os.Executable()
162 if exeAbsPath, err := filepath.Abs(exe); err == nil {
163 if exePath, err := filepath.EvalSymlinks(exeAbsPath); err == nil {
164 bdir = filepath.Dir(exePath)
169 exePath, err = exec.LookPath(path.Join(bdir, exeName))
171 // Let's try in /opt/AGL/bin
172 exePath, err = exec.LookPath(path.Join("opt", "AGL", "bin", exeName))
174 return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, bdir)
177 cmd := exec.Command(exePath, args...)
178 cmd.Env = os.Environ()
179 for _, ev := range env {
180 cmd.Env = append(cmd.Env, ev)
185 logFilename := filepath.Join(s.logsDir, exeName+".log")
187 outfile, err := os.Create(logFilename)
189 return nil, fmt.Errorf("Cannot create log file %s", logFilename)
192 cmdOut, err := cmd.StdoutPipe()
194 return nil, fmt.Errorf("Pipe stdout error for : %s", err)
197 go io.Copy(outfile, cmdOut)
205 *eChan = make(chan ExitChan, 1)
206 go func(c *exec.Cmd, oF *os.File) {
208 sts, err := c.Process.Wait()
210 s := sts.Sys().(syscall.WaitStatus)
211 status = s.ExitStatus()
216 s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)
218 *eChan <- ExitChan{status, err}
224 // Start Starts syncthing process
225 func (s *SyncThing) Start() (*exec.Cmd, error) {
228 s.log.Infof(" ST home=%s", s.Home)
229 s.log.Infof(" ST url=%s", s.BaseURL)
234 "--gui-address=" + s.BaseURL,
238 args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
239 s.log.Infof(" ST apikey=%s", s.APIKey)
241 if s.log.Level == logrus.DebugLevel {
242 args = append(args, "-verbose")
246 "STNODEFAULTFOLDER=1",
250 s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)
252 // Use autogenerated apikey if not set by config.json
253 if err == nil && s.APIKey == "" {
254 if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
256 if b, err := ioutil.ReadAll(fd); err == nil {
257 re := regexp.MustCompile("<apikey>(.*)</apikey>")
258 key := re.FindStringSubmatch(string(b))
269 // StartInotify Starts syncthing-inotify process
270 func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
272 exeName := "syncthing-inotify"
274 s.log.Infof(" STI url=%s", s.BaseURL)
277 "-target=" + s.BaseURL,
280 args = append(args, "-api="+s.APIKey)
281 s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
283 if s.log.Level == logrus.DebugLevel {
284 args = append(args, "-verbosity=4")
289 s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)
294 func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
295 if err := proc.Signal(os.Interrupt); err != nil {
296 s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())
300 case <-time.After(time.Second):
301 // A bigger bonk on the head.
302 if err := proc.Signal(os.Kill); err != nil {
303 s.log.Infof("Proc term %s error: %s", pname, err.Error())
308 s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
311 // Stop Stops syncthing process
312 func (s *SyncThing) Stop() {
316 s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
320 // StopInotify Stops syncthing process
321 func (s *SyncThing) StopInotify() {
325 s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
329 // Connect Establish HTTP connection with Syncthing
330 func (s *SyncThing) Connect() error {
333 s.client, err = common.HTTPNewClient(s.BaseURL,
334 common.HTTPClientConfig{
336 HeaderClientKeyName: "X-Syncthing-ID",
337 LogOut: s.conf.LogVerboseOut,
338 LogPrefix: "SYNCTHING: ",
339 LogLevel: common.HTTPLogLevelWarning,
341 s.client.SetLogLevel(s.log.Level.String())
344 msg := ": " + err.Error()
345 if strings.Contains(err.Error(), "connection refused") {
346 msg = fmt.Sprintf("(url: %s)", s.BaseURL)
348 return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
351 return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
354 s.MyID, err = s.IDGet()
356 return fmt.Errorf("ERROR: cannot retrieve ID")
361 // Start events monitoring
362 err = s.Events.Start()
367 // IDGet returns the Syncthing ID of Syncthing instance running locally
368 func (s *SyncThing) IDGet() (string, error) {
370 if err := s.client.HTTPGet("system/status", &data); err != nil {
373 status := make(map[string]interface{})
374 json.Unmarshal(data, &status)
375 return status["myID"].(string), nil
378 // ConfigGet returns the current Syncthing configuration
379 func (s *SyncThing) ConfigGet() (config.Configuration, error) {
381 config := config.Configuration{}
382 if err := s.client.HTTPGet("system/config", &data); err != nil {
385 err := json.Unmarshal(data, &config)
389 // ConfigSet set Syncthing configuration
390 func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
391 body, err := json.Marshal(cfg)
395 return s.client.HTTPPost("system/config", string(body))
398 // IsConfigInSync Returns true if configuration is in sync
399 func (s *SyncThing) IsConfigInSync() (bool, error) {
402 if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
405 if err := json.Unmarshal(data, &d); err != nil {
408 return d.ConfigInSync, nil