-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest2command.go
196 lines (157 loc) · 3.92 KB
/
rest2command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package main
import (
"context"
"encoding/json"
"io"
"net/http"
"os"
"os/signal"
"time"
"fmt"
"io/ioutil"
"regexp"
"os/exec"
"log/syslog"
log "github.com/Sirupsen/logrus"
logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
)
var (
Port = ":9999"
ConfigurationFile = "/etc/rest2command/configuration.json"
Version = "1.0.0"
BuildTime = time.Now().String()
GitHash = "undefined"
API_Version = ""
CredentialsFile = "./credentials.json"
)
type Configuration struct {
Url string `json:"url"`
Command string `json:"command"`
Args string `json:"args"`
}
type Command struct {
Command string
Args string
}
func main() {
setUpLog()
setUp()
// subscribe to SIGINT signals
stopChan := make(chan os.Signal)
signal.Notify(stopChan, os.Interrupt)
mux := buildHandlers()
srv := &http.Server{
Addr: Port,
Handler: mux,
}
go func() {
err := srv.ListenAndServe()
if err != nil {
log.Info("listen: %s\n", err.Error())
}
}()
<-stopChan // wait for SIGINT
log.Info("Shutting down server...")
// shut down gracefully, but wait no longer than 5 seconds before halting
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
srv.Shutdown(ctx)
log.Info("Server gracefully stopped")
}
func getConfigurations(configuration string) []Configuration {
log.Debug("Loading file ", configuration)
raw, err := ioutil.ReadFile(configuration)
if err != nil {
log.Fatal(err.Error())
os.Exit(1)
}
var c []Configuration
json.Unmarshal(raw, &c)
return c
}
func buildCommands(configurations []Configuration) map[string]Command {
commands := make(map[string]Command)
for _, configuration := range configurations {
log.Debug(API_Version+configuration.Url, " -> ", configuration.Command)
commands[API_Version+configuration.Url] = Command{
Command: configuration.Command,
Args: configuration.Args,
}
}
return commands
}
func buildHandlers() *http.ServeMux {
mux := http.NewServeMux()
log.Info("Setting handlers")
commands := buildCommands(getConfigurations(ConfigurationFile))
for key := range commands {
//TODO wrap handlerfunc to check credentials and log information
// https://medium.com/@matryer/the-http-handlerfunc-wrapper-technique-in-golang-c60bf76e6124
mux.Handle(key, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
out := runCommand(commands[r.RequestURI])
io.WriteString(w, out)
}))
}
return mux
}
func runCommand(cmd Command) string {
log.Debug("Cmd: ", cmd.Command, " Args ", cmd.Args)
out, err := exec.Command(cmd.Command, cmd.Args).Output()
if err != nil {
log.Error(err)
out = []byte("error")
}
log.Debug("Out: ", fmt.Sprintf("%s", out))
return fmt.Sprintf("%s", out)
}
func setUp() {
if os.Getenv("PORT") != "" {
Port = ":" + os.Getenv("PORT")
}
if os.Getenv("FILE_CONFIGURATION") != "" {
ConfigurationFile = os.Getenv("FILE_CONFIGURATION")
}
if os.Getenv("FILE_CREDENTIALS") != "" {
CredentialsFile = os.Getenv("FILE_CREDENTIALS")
}
API_Version = fmt.Sprintf("/v%s", getAPIVersion(Version))
log.Info("Context: ", API_Version)
}
func getAPIVersion(version string) string {
versionRegExp := regexp.MustCompile(`(\d+).(\d+).(\d+)`)
if versionRegExp.MatchString(version) {
versions := versionRegExp.FindStringSubmatch(version)
return versions[1]
}
return "0"
}
func setUpLog() {
switch os.Getenv("LOG_LEVEL") {
case "debug":
log.SetLevel(log.DebugLevel)
break
case "info":
log.SetLevel(log.InfoLevel)
break
case "warn":
log.SetLevel(log.WarnLevel)
break
case "error":
log.SetLevel(log.ErrorLevel)
break
case "fatal":
log.SetLevel(log.FatalLevel)
break
case "panic":
log.SetLevel(log.PanicLevel)
break
default:
log.SetLevel(log.InfoLevel)
break
}
log := log.New()
hook, err := logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO|syslog.LOG_ERR|syslog.LOG_DEBUG, "")
if err == nil {
log.Hooks.Add(hook)
}
log.Warning("asfas")
}