Initial commit.
[src/xds/xds-agent.git] / lib / agent / agent.go
1 package agent
2
3 import (
4         "fmt"
5         "os"
6         "os/exec"
7         "os/signal"
8         "syscall"
9
10         "github.com/Sirupsen/logrus"
11         "github.com/codegangsta/cli"
12         "github.com/iotbzh/xds-agent/lib/syncthing"
13         "github.com/iotbzh/xds-agent/lib/xdsconfig"
14         "github.com/iotbzh/xds-agent/lib/xdsserver"
15 )
16
17 // Context holds the Agent context structure
18 type Context struct {
19         ProgName    string
20         Config      *xdsconfig.Config
21         Log         *logrus.Logger
22         SThg        *st.SyncThing
23         SThgCmd     *exec.Cmd
24         SThgInotCmd *exec.Cmd
25         WWWServer   *xdsserver.ServerService
26         Exit        chan os.Signal
27 }
28
29 // NewAgent Create a new instance of Agent
30 func NewAgent(cliCtx *cli.Context) *Context {
31         var err error
32
33         // Set logger level and formatter
34         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
35
36         logLevel := cliCtx.GlobalString("log")
37         if logLevel == "" {
38                 logLevel = "error" // FIXME get from Config DefaultLogLevel
39         }
40         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
41                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
42                 os.Exit(1)
43         }
44         log.Formatter = &logrus.TextFormatter{}
45
46         // Define default configuration
47         ctx := Context{
48                 ProgName: cliCtx.App.Name,
49                 Log:      log,
50                 Exit:     make(chan os.Signal, 1),
51         }
52
53         // register handler on SIGTERM / exit
54         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
55         go handlerSigTerm(&ctx)
56
57         return &ctx
58 }
59
60 // Handle exit and properly stop/close all stuff
61 func handlerSigTerm(ctx *Context) {
62         <-ctx.Exit
63         if ctx.SThg != nil {
64                 ctx.Log.Infof("Stoping Syncthing... (PID %d)",
65                         ctx.SThgCmd.Process.Pid)
66                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
67                         ctx.SThgInotCmd.Process.Pid)
68                 ctx.SThg.Stop()
69                 ctx.SThg.StopInotify()
70         }
71         if ctx.WWWServer != nil {
72                 ctx.Log.Infof("Stoping Web server...")
73                 ctx.WWWServer.Stop()
74         }
75         os.Exit(1)
76 }