summaryrefslogtreecommitdiffstats
path: root/meta-agl-profile-core/recipes-devtools
AgeCommit message (Expand)AuthorFilesLines
2019-04-09Merge remote-tracking branch 'origin/sandbox/sdesneux/thud-upgrade'Jan-Simon Möller34-2002/+11
2019-04-05Bump afb-helpers versionRomain Forlot1-1/+1
2019-04-05Add runtime dependency for the test launcherRomain Forlot1-1/+1
2019-04-05Bump appcontroller versionRomain Forlot1-1/+1
2019-04-04Upgrade to thudScott Murray34-2002/+11
2019-01-02Add afb-helpers & controller librariesRomain Forlot3-0/+41
2018-12-25Revert "Add afb-helpers & app-controller library recipes"Jan-Simon Moeller2-37/+0
2018-12-20Add afb-helpers & app-controller library recipesRomain Forlot2-0/+37
2018-12-20Bump low-level-can-generatorRomain Forlot1-2/+3
2018-12-20Bump cmake-apps-moduleRomain Forlot1-2/+2
2018-11-23Bump cmake-apps-module revision.Romain Forlot1-5/+3
2018-10-29Add CMake Apps module recipeRomain Forlot2-1/+25
2018-09-10Fix do_rootfs eats huge time on docker environmentTadao Tanikawa4-0/+304
2018-08-24Add the afb-test binding in the devel AGL imageRomain Forlot1-0/+1
2018-08-23Port the latest version of valgrindRonan Le Martret25-0/+1651
2018-08-03packagegroup: core: devel: add agl-service-network-tools packageMatt Ranostay1-0/+1
2018-07-25packagegroup-agl-core-devel: add jq and libxslt-bin to parse result filesflounder_5.99.2flounder/5.99.25.99.2Stephane Desneux1-0/+2
2018-07-11Fix cmake build with sdk inside a scriptRonan Le Martret3-0/+56
2018-05-313rd part of the layer/profile rework [1/2]Jan-Simon Möller2-0/+1
2018-04-20Introduce meta-agl-profile-core and meta-agl-profile-graphicsJan-Simon Möller8-0/+158
.mo { color: #ae81ff } /* Literal.Number.Oct */ .highlight .sa { color: #e6db74 } /* Literal.String.Affix */ .highlight .sb { color: #e6db74 } /* Literal.String.Backtick */ .highlight .sc { color: #e6db74 } /* Literal.String.Char */ .highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */ .highlight .sd { color: #e6db74 } /* Literal.String.Doc */ .highlight .s2 { color: #e6db74 } /* Literal.String.Double */ .highlight .se { color: #ae81ff } /* Literal.String.Escape */ .highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */ .highlight .si { color: #e6db74 } /* Literal.String.Interpol */ .highlight .sx { color: #e6db74 } /* Literal.String.Other */ .highlight .sr { color: #e6db74 } /* Literal.String.Regex */ .highlight .s1 { color: #e6db74 } /* Literal.String.Single */ .highlight .ss { color: #e6db74 } /* Literal.String.Symbol */ .highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #a6e22e } /* Name.Function.Magic */ .highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */ .highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */ .highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */ .highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */ .highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */ } @media (prefers-color-scheme: light) { .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
package st

import (
	"encoding/json"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"syscall"
	"time"

	"strings"

	"fmt"

	"io"

	"io/ioutil"

	"regexp"

	"github.com/Sirupsen/logrus"
	common "github.com/iotbzh/xds-common/golib"
	"github.com/iotbzh/xds-server/lib/xdsconfig"
	"github.com/syncthing/syncthing/lib/config"
)

// SyncThing .
type SyncThing struct {
	BaseURL string
	APIKey  string
	Home    string
	STCmd   *exec.Cmd
	STICmd  *exec.Cmd
	MyID    string

	// Private fields
	binDir      string
	logsDir     string
	exitSTChan  chan ExitChan
	exitSTIChan chan ExitChan
	conf        *xdsconfig.Config
	client      *common.HTTPClient
	log         *logrus.Logger
	Events      *Events
}

// ExitChan Channel used for process exit
type ExitChan struct {
	status int
	err    error
}

// ConfigInSync Check whether if Syncthing configuration is in sync
type configInSync struct {
	ConfigInSync bool `json:"configInSync"`
}

// FolderStatus Information about the current status of a folder.
type FolderStatus struct {
	GlobalFiles       int   `json:"globalFiles"`
	GlobalDirectories int   `json:"globalDirectories"`
	GlobalSymlinks    int   `json:"globalSymlinks"`
	GlobalDeleted     int   `json:"globalDeleted"`
	GlobalBytes       int64 `json:"globalBytes"`

	LocalFiles       int   `json:"localFiles"`
	LocalDirectories int   `json:"localDirectories"`
	LocalSymlinks    int   `json:"localSymlinks"`
	LocalDeleted     int   `json:"localDeleted"`
	LocalBytes       int64 `json:"localBytes"`

	NeedFiles       int   `json:"needFiles"`
	NeedDirectories int   `json:"needDirectories"`
	NeedSymlinks    int   `json:"needSymlinks"`
	NeedDeletes     int   `json:"needDeletes"`
	NeedBytes       int64 `json:"needBytes"`

	InSyncFiles int   `json:"inSyncFiles"`
	InSyncBytes int64 `json:"inSyncBytes"`

	State        string    `json:"state"`
	StateChanged time.Time `json:"stateChanged"`

	Sequence int64 `json:"sequence"`

	IgnorePatterns bool `json:"ignorePatterns"`
}

// NewSyncThing creates a new instance of Syncthing
func NewSyncThing(conf *xdsconfig.Config, log *logrus.Logger) *SyncThing {
	var url, apiKey, home, binDir string
	var err error

	stCfg := conf.FileConf.SThgConf
	if stCfg != nil {
		url = stCfg.GuiAddress
		apiKey = stCfg.GuiAPIKey
		home = stCfg.Home
		binDir = stCfg.BinDir
	}

	if url == "" {
		url = "http://localhost:8384"
	}
	if url[0:7] != "http://" {
		url = "http://" + url
	}

	if home == "" {
		home = "/mnt/share"
	}

	if binDir == "" {
		if binDir, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
			binDir = "/usr/local/bin"
		}
	}

	s := SyncThing{
		BaseURL: url,
		APIKey:  apiKey,
		Home:    home,
		binDir:  binDir,
		logsDir: conf.FileConf.LogsDir,
		log:     log,
		conf:    conf,
	}

	// Create Events monitoring
	s.Events = s.NewEventListener()

	return &s
}

// Start Starts syncthing process
func (s *SyncThing) startProc(exeName string, args []string, env []string, eChan *chan ExitChan) (*exec.Cmd, error) {

	// Kill existing process (useful for debug ;-) )
	if os.Getenv("DEBUG_MODE") != "" {
		exec.Command("bash", "-c", "pkill -9 "+exeName).Output()
	}

	path, err := exec.LookPath(path.Join(s.binDir, exeName))
	if err != nil {
		return nil, fmt.Errorf("Cannot find %s executable in %s", exeName, s.binDir)
	}
	cmd := exec.Command(path, args...)
	cmd.Env = os.Environ()
	for _, ev := range env {
		cmd.Env = append(cmd.Env, ev)
	}

	// open log file
	var outfile *os.File
	logFilename := filepath.Join(s.logsDir, exeName+".log")
	if s.logsDir != "" {
		outfile, err := os.Create(logFilename)
		if err != nil {
			return nil, fmt.Errorf("Cannot create log file %s", logFilename)
		}

		cmdOut, err := cmd.StdoutPipe()
		if err != nil {
			return nil, fmt.Errorf("Pipe stdout error for : %s", err)
		}

		go io.Copy(outfile, cmdOut)
	}

	err = cmd.Start()
	if err != nil {
		return nil, err
	}

	*eChan = make(chan ExitChan, 1)
	go func(c *exec.Cmd, oF *os.File) {
		status := 0
		sts, err := c.Process.Wait()
		if !sts.Success() {
			s := sts.Sys().(syscall.WaitStatus)
			status = s.ExitStatus()
		}
		if oF != nil {
			oF.Close()
		}
		s.log.Debugf("%s exited with status %d, err %v", exeName, status, err)

		*eChan <- ExitChan{status, err}
	}(cmd, outfile)

	return cmd, nil
}

// Start Starts syncthing process
func (s *SyncThing) Start() (*exec.Cmd, error) {
	var err error

	s.log.Infof(" ST home=%s", s.Home)
	s.log.Infof(" ST  url=%s", s.BaseURL)

	args := []string{
		"--home=" + s.Home,
		"-no-browser",
		"--gui-address=" + s.BaseURL,
	}

	if s.APIKey != "" {
		args = append(args, "-gui-apikey=\""+s.APIKey+"\"")
		s.log.Infof(" ST apikey=%s", s.APIKey)
	}
	if s.log.Level == logrus.DebugLevel {
		args = append(args, "-verbose")
	}

	env := []string{
		"STNODEFAULTFOLDER=1",
		"STNOUPGRADE=1",
		"STNORESTART=1", // FIXME SEB remove ?
	}

	s.STCmd, err = s.startProc("syncthing", args, env, &s.exitSTChan)

	// Use autogenerated apikey if not set by config.json
	if err == nil && s.APIKey == "" {
		if fd, err := os.Open(filepath.Join(s.Home, "config.xml")); err == nil {
			defer fd.Close()
			if b, err := ioutil.ReadAll(fd); err == nil {
				re := regexp.MustCompile("<apikey>(.*)</apikey>")
				key := re.FindStringSubmatch(string(b))
				if len(key) >= 1 {
					s.APIKey = key[1]
				}
			}
		}
	}

	return s.STCmd, err
}

// StartInotify Starts syncthing-inotify process
func (s *SyncThing) StartInotify() (*exec.Cmd, error) {
	var err error
	exeName := "syncthing-inotify"

	s.log.Infof(" STI  url=%s", s.BaseURL)

	args := []string{
		"-target=" + s.BaseURL,
	}
	if s.APIKey != "" {
		args = append(args, "-api="+s.APIKey)
		s.log.Infof("%s uses apikey=%s", exeName, s.APIKey)
	}
	if s.log.Level == logrus.DebugLevel {
		args = append(args, "-verbosity=4")
	}

	env := []string{}

	s.STICmd, err = s.startProc(exeName, args, env, &s.exitSTIChan)

	return s.STICmd, err
}

func (s *SyncThing) stopProc(pname string, proc *os.Process, exit chan ExitChan) {
	if err := proc.Signal(os.Interrupt); err != nil {
		s.log.Infof("Proc interrupt %s error: %s", pname, err.Error())

		select {
		case <-exit:
		case <-time.After(time.Second):
			// A bigger bonk on the head.
			if err := proc.Signal(os.Kill); err != nil {
				s.log.Infof("Proc term %s error: %s", pname, err.Error())
			}
			<-exit
		}
	}
	s.log.Infof("%s stopped (PID %d)", pname, proc.Pid)
}

// Stop Stops syncthing process
func (s *SyncThing) Stop() {
	if s.STCmd == nil {
		return
	}
	s.stopProc("syncthing", s.STCmd.Process, s.exitSTChan)
	s.STCmd = nil
}

// StopInotify Stops syncthing process
func (s *SyncThing) StopInotify() {
	if s.STICmd == nil {
		return
	}
	s.stopProc("syncthing-inotify", s.STICmd.Process, s.exitSTIChan)
	s.STICmd = nil
}

// Connect Establish HTTP connection with Syncthing
func (s *SyncThing) Connect() error {
	var err error
	s.client, err = common.HTTPNewClient(s.BaseURL,
		common.HTTPClientConfig{
			URLPrefix:           "/rest",
			HeaderClientKeyName: "X-Syncthing-ID",
		})
	if err != nil {
		msg := ": " + err.Error()
		if strings.Contains(err.Error(), "connection refused") {
			msg = fmt.Sprintf("(url: %s)", s.BaseURL)
		}
		return fmt.Errorf("ERROR: cannot connect to Syncthing %s", msg)
	}
	if s.client == nil {
		return fmt.Errorf("ERROR: cannot connect to Syncthing (null client)")
	}

	s.client.SetLogger(s.log)

	s.MyID, err = s.IDGet()
	if err != nil {
		return fmt.Errorf("ERROR: cannot retrieve ID")
	}

	// Start events monitoring
	err = s.Events.Start()

	return err
}

// IDGet returns the Syncthing ID of Syncthing instance running locally
func (s *SyncThing) IDGet() (string, error) {
	var data []byte
	if err := s.client.HTTPGet("system/status", &data); err != nil {
		return "", err
	}
	status := make(map[string]interface{})
	json.Unmarshal(data, &status)
	return status["myID"].(string), nil
}

// ConfigGet returns the current Syncthing configuration
func (s *SyncThing) ConfigGet() (config.Configuration, error) {
	var data []byte
	config := config.Configuration{}
	if err := s.client.HTTPGet("system/config", &data); err != nil {
		return config, err
	}
	err := json.Unmarshal(data, &config)
	return config, err
}

// ConfigSet set Syncthing configuration
func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
	body, err := json.Marshal(cfg)
	if err != nil {
		return err
	}
	return s.client.HTTPPost("system/config", string(body))
}

// IsConfigInSync Returns true if configuration is in sync
func (s *SyncThing) IsConfigInSync() (bool, error) {
	var data []byte
	var d configInSync
	if err := s.client.HTTPGet("system/config/insync", &data); err != nil {
		return false, err
	}
	if err := json.Unmarshal(data, &d); err != nil {
		return false, err
	}
	return d.ConfigInSync, nil
}