|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "os/exec" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/pkg/errors" |
| 12 | + log "github.com/sirupsen/logrus" |
| 13 | + |
| 14 | + "github.com/brocaar/lora-gateway-bridge/internal/config" |
| 15 | + "github.com/brocaar/lora-gateway-bridge/internal/integration" |
| 16 | + "github.com/brocaar/loraserver/api/gw" |
| 17 | + "github.com/brocaar/lorawan" |
| 18 | +) |
| 19 | + |
| 20 | +type command struct { |
| 21 | + Command string |
| 22 | + MaxExecutionDuration time.Duration |
| 23 | +} |
| 24 | + |
| 25 | +var ( |
| 26 | + mux sync.RWMutex |
| 27 | + |
| 28 | + commands map[string]command |
| 29 | +) |
| 30 | + |
| 31 | +// Setup configures the gateway commands. |
| 32 | +func Setup(conf config.Config) error { |
| 33 | + mux.Lock() |
| 34 | + defer mux.Unlock() |
| 35 | + |
| 36 | + commands = make(map[string]command) |
| 37 | + |
| 38 | + for k, v := range conf.Commands.Commands { |
| 39 | + commands[k] = command{ |
| 40 | + Command: v.Command, |
| 41 | + MaxExecutionDuration: v.MaxExecutionDuration, |
| 42 | + } |
| 43 | + |
| 44 | + log.WithFields(log.Fields{ |
| 45 | + "command": k, |
| 46 | + "command_exec": v.Command, |
| 47 | + "max_execution_duration": v.MaxExecutionDuration, |
| 48 | + }).Info("commands: configuring command") |
| 49 | + } |
| 50 | + |
| 51 | + go executeLoop() |
| 52 | + |
| 53 | + return nil |
| 54 | +} |
| 55 | + |
| 56 | +func executeLoop() { |
| 57 | + for cmd := range integration.GetIntegration().GetGatewayCommandExecRequestChan() { |
| 58 | + go func(cmd gw.GatewayCommandExecRequest) { |
| 59 | + executeCommand(cmd) |
| 60 | + }(cmd) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +func executeCommand(cmd gw.GatewayCommandExecRequest) { |
| 65 | + var gatewayID lorawan.EUI64 |
| 66 | + copy(gatewayID[:], cmd.GatewayId) |
| 67 | + |
| 68 | + stdout, stderr, err := execute(cmd.Command, cmd.Stdin, cmd.Environment) |
| 69 | + resp := gw.GatewayCommandExecResponse{ |
| 70 | + GatewayId: cmd.GatewayId, |
| 71 | + Token: cmd.Token, |
| 72 | + Stdout: stdout, |
| 73 | + Stderr: stderr, |
| 74 | + } |
| 75 | + if err != nil { |
| 76 | + resp.Error = err.Error() |
| 77 | + } |
| 78 | + |
| 79 | + if err := integration.GetIntegration().PublishEvent(gatewayID, "exec", &resp); err != nil { |
| 80 | + log.WithError(err).Error("commands: publish command execution event error") |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +func execute(command string, stdin []byte, environment map[string]string) ([]byte, []byte, error) { |
| 85 | + mux.RLock() |
| 86 | + defer mux.RUnlock() |
| 87 | + |
| 88 | + cmd, ok := commands[command] |
| 89 | + if !ok { |
| 90 | + return nil, nil, errors.New("command does not exist") |
| 91 | + } |
| 92 | + |
| 93 | + cmdArgs, err := ParseCommandLine(cmd.Command) |
| 94 | + if err != nil { |
| 95 | + return nil, nil, errors.Wrap(err, "parse command error") |
| 96 | + } |
| 97 | + if len(cmdArgs) == 0 { |
| 98 | + return nil, nil, errors.New("no command is given") |
| 99 | + } |
| 100 | + |
| 101 | + log.WithFields(log.Fields{ |
| 102 | + "command": command, |
| 103 | + "exec": cmdArgs[0], |
| 104 | + "args": cmdArgs[1:], |
| 105 | + "max_execution_duration": cmd.MaxExecutionDuration, |
| 106 | + }).Info("commands: executing command") |
| 107 | + |
| 108 | + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(cmd.MaxExecutionDuration)) |
| 109 | + defer cancel() |
| 110 | + |
| 111 | + cmdCtx := exec.CommandContext(ctx, cmdArgs[0], cmdArgs[1:]...) |
| 112 | + for k, v := range environment { |
| 113 | + cmdCtx.Env = append(cmdCtx.Env, fmt.Sprintf("%s=%s", k, v)) |
| 114 | + } |
| 115 | + |
| 116 | + stdinPipe, err := cmdCtx.StdinPipe() |
| 117 | + if err != nil { |
| 118 | + return nil, nil, errors.Wrap(err, "get stdin pipe error") |
| 119 | + } |
| 120 | + |
| 121 | + stdoutPipe, err := cmdCtx.StdoutPipe() |
| 122 | + if err != nil { |
| 123 | + return nil, nil, errors.Wrap(err, "get stdout pipe error") |
| 124 | + } |
| 125 | + |
| 126 | + stderrPipe, err := cmdCtx.StderrPipe() |
| 127 | + if err != nil { |
| 128 | + return nil, nil, errors.Wrap(err, "get stderr pipe error") |
| 129 | + } |
| 130 | + |
| 131 | + go func() { |
| 132 | + defer stdinPipe.Close() |
| 133 | + if _, err := stdinPipe.Write(stdin); err != nil { |
| 134 | + log.WithError(err).Error("commands: write to stdin error") |
| 135 | + } |
| 136 | + }() |
| 137 | + |
| 138 | + if err := cmdCtx.Start(); err != nil { |
| 139 | + return nil, nil, errors.Wrap(err, "starting command error") |
| 140 | + } |
| 141 | + |
| 142 | + stdoutB, _ := ioutil.ReadAll(stdoutPipe) |
| 143 | + stderrB, _ := ioutil.ReadAll(stderrPipe) |
| 144 | + |
| 145 | + if err := cmdCtx.Wait(); err != nil { |
| 146 | + return nil, nil, errors.Wrap(err, "waiting for command to finish error") |
| 147 | + } |
| 148 | + |
| 149 | + return stdoutB, stderrB, nil |
| 150 | +} |
| 151 | + |
| 152 | +// source: https://stackoverflow.com/questions/34118732/parse-a-command-line-string-into-flags-and-arguments-in-golang |
| 153 | +func ParseCommandLine(command string) ([]string, error) { |
| 154 | + var args []string |
| 155 | + state := "start" |
| 156 | + current := "" |
| 157 | + quote := "\"" |
| 158 | + escapeNext := true |
| 159 | + for i := 0; i < len(command); i++ { |
| 160 | + c := command[i] |
| 161 | + |
| 162 | + if state == "quotes" { |
| 163 | + if string(c) != quote { |
| 164 | + current += string(c) |
| 165 | + } else { |
| 166 | + args = append(args, current) |
| 167 | + current = "" |
| 168 | + state = "start" |
| 169 | + } |
| 170 | + continue |
| 171 | + } |
| 172 | + |
| 173 | + if escapeNext { |
| 174 | + current += string(c) |
| 175 | + escapeNext = false |
| 176 | + continue |
| 177 | + } |
| 178 | + |
| 179 | + if c == '\\' { |
| 180 | + escapeNext = true |
| 181 | + continue |
| 182 | + } |
| 183 | + |
| 184 | + if c == '"' || c == '\'' { |
| 185 | + state = "quotes" |
| 186 | + quote = string(c) |
| 187 | + continue |
| 188 | + } |
| 189 | + |
| 190 | + if state == "arg" { |
| 191 | + if c == ' ' || c == '\t' { |
| 192 | + args = append(args, current) |
| 193 | + current = "" |
| 194 | + state = "start" |
| 195 | + } else { |
| 196 | + current += string(c) |
| 197 | + } |
| 198 | + continue |
| 199 | + } |
| 200 | + |
| 201 | + if c != ' ' && c != '\t' { |
| 202 | + state = "arg" |
| 203 | + current += string(c) |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + if state == "quotes" { |
| 208 | + return []string{}, errors.New(fmt.Sprintf("Unclosed quote in command line: %s", command)) |
| 209 | + } |
| 210 | + |
| 211 | + if current != "" { |
| 212 | + args = append(args, current) |
| 213 | + } |
| 214 | + |
| 215 | + return args, nil |
| 216 | +} |
0 commit comments