summaryrefslogtreecommitdiffstats
path: root/lib/agent
diff options
context:
space:
mode:
authorSebastien Douheret <sebastien.douheret@iot.bzh>2017-05-15 11:12:21 +0200
committerSebastien Douheret <sebastien.douheret@iot.bzh>2017-05-15 19:08:31 +0200
commitbfeab33538d50ee52750de4dd4c0e72b64f674f6 (patch)
treea8ebab2a62f4ca4ccbfbe848106ca53d708c724b /lib/agent
Initial commit.
Signed-off-by: Sebastien Douheret <sebastien.douheret@iot.bzh>
Diffstat (limited to 'lib/agent')
-rw-r--r--lib/agent/agent.go76
1 files changed, 76 insertions, 0 deletions
diff --git a/lib/agent/agent.go b/lib/agent/agent.go
new file mode 100644
index 0000000..80c97f7
--- /dev/null
+++ b/lib/agent/agent.go
@@ -0,0 +1,76 @@
+package agent
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "os/signal"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/codegangsta/cli"
+ "github.com/iotbzh/xds-agent/lib/syncthing"
+ "github.com/iotbzh/xds-agent/lib/xdsconfig"
+ "github.com/iotbzh/xds-agent/lib/xdsserver"
+)
+
+// Context holds the Agent context structure
+type Context struct {
+ ProgName string
+ Config *xdsconfig.Config
+ Log *logrus.Logger
+ SThg *st.SyncThing
+ SThgCmd *exec.Cmd
+ SThgInotCmd *exec.Cmd
+ WWWServer *xdsserver.ServerService
+ Exit chan os.Signal
+}
+
+// NewAgent Create a new instance of Agent
+func NewAgent(cliCtx *cli.Context) *Context {
+ var err error
+
+ // Set logger level and formatter
+ log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
+
+ logLevel := cliCtx.GlobalString("log")
+ if logLevel == "" {
+ logLevel = "error" // FIXME get from Config DefaultLogLevel
+ }
+ if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
+ fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
+ os.Exit(1)
+ }
+ log.Formatter = &logrus.TextFormatter{}
+
+ // Define default configuration
+ ctx := Context{
+ ProgName: cliCtx.App.Name,
+ Log: log,
+ Exit: make(chan os.Signal, 1),
+ }
+
+ // register handler on SIGTERM / exit
+ signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
+ go handlerSigTerm(&ctx)
+
+ return &ctx
+}
+
+// Handle exit and properly stop/close all stuff
+func handlerSigTerm(ctx *Context) {
+ <-ctx.Exit
+ if ctx.SThg != nil {
+ ctx.Log.Infof("Stoping Syncthing... (PID %d)",
+ ctx.SThgCmd.Process.Pid)
+ ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
+ ctx.SThgInotCmd.Process.Pid)
+ ctx.SThg.Stop()
+ ctx.SThg.StopInotify()
+ }
+ if ctx.WWWServer != nil {
+ ctx.Log.Infof("Stoping Web server...")
+ ctx.WWWServer.Stop()
+ }
+ os.Exit(1)
+}