-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.go
244 lines (214 loc) · 6.31 KB
/
main.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"fmt"
"github.com/MG-RAST/Shock/shock-server/auth"
"github.com/MG-RAST/Shock/shock-server/conf"
ncon "github.com/MG-RAST/Shock/shock-server/controller/node"
acon "github.com/MG-RAST/Shock/shock-server/controller/node/acl"
icon "github.com/MG-RAST/Shock/shock-server/controller/node/index"
pcon "github.com/MG-RAST/Shock/shock-server/controller/preauth"
"github.com/MG-RAST/Shock/shock-server/db"
"github.com/MG-RAST/Shock/shock-server/logger"
"github.com/MG-RAST/Shock/shock-server/node"
"github.com/MG-RAST/Shock/shock-server/preauth"
"github.com/MG-RAST/Shock/shock-server/responder"
"github.com/MG-RAST/Shock/shock-server/user"
"github.com/MG-RAST/Shock/shock-server/util"
"github.com/stretchr/goweb"
"github.com/stretchr/goweb/context"
"net"
"net/http"
"os"
"os/signal"
"runtime"
"strconv"
)
type resource struct {
R []string `json:"resources"`
U string `json:"url"`
D string `json:"documentation"`
C string `json:"contact"`
I string `json:"id"`
T string `json:"type"`
}
func mapRoutes() {
goweb.MapBefore(func(ctx context.Context) error {
req := ctx.HttpRequest()
host, _, _ := net.SplitHostPort(req.RemoteAddr)
if host == "::1" {
host = "localhost"
}
suffix := ""
if _, ok := req.Header["Authorization"]; ok {
suffix += " AUTH"
}
if l, has := req.Header["Content-Length"]; has {
suffix += " Content-Length: " + l[0]
}
logger.Info("access", fmt.Sprintf("%s REQ RECEIVED \"%s %s%s\"", host, ctx.MethodString(), req.RequestURI, suffix))
return nil
})
goweb.MapAfter(func(ctx context.Context) error {
req := ctx.HttpRequest()
host, _, _ := net.SplitHostPort(req.RemoteAddr)
if host == "::1" {
host = "localhost"
}
suffix := ""
if _, ok := req.Header["Authorization"]; ok {
suffix += " AUTH"
}
if l, has := req.Header["Content-Length"]; has {
suffix += " Content-Length: " + l[0]
}
logger.Info("access", fmt.Sprintf("RESPONDED TO %s \"%s %s%s\"", host, ctx.MethodString(), req.RequestURI, suffix))
return nil
})
goweb.Map("/preauth/{id}", func(ctx context.Context) error {
pcon.PreAuthRequest(ctx)
return nil
})
goweb.Map("/node/{nid}/acl/{type}", func(ctx context.Context) error {
acon.AclTypedRequest(ctx)
return nil
})
goweb.Map("/node/{nid}/acl/", func(ctx context.Context) error {
acon.AclRequest(ctx)
return nil
})
goweb.Map("/node/{nid}/index/{idxType}", func(ctx context.Context) error {
icon.IndexTypedRequest(ctx)
return nil
})
goweb.Map("/", func(ctx context.Context) error {
host := util.ApiUrl(ctx)
r := resource{
R: []string{"node"},
U: host + "/",
D: host + "/documentation.html",
C: conf.Conf["admin-email"],
I: "Shock",
T: "Shock",
}
return responder.WriteResponseObject(ctx, http.StatusOK, r)
})
nodeController := new(ncon.NodeController)
goweb.MapController(nodeController)
goweb.MapStatic("/assets", conf.Conf["site-path"]+"/assets")
goweb.MapStaticFile("/documentation.html", conf.Conf["site-path"]+"/pages/main.html")
// Map the favicon
//goweb.MapStaticFile("/favicon.ico", "static-files/favicon.ico")
// Catch-all handler for everything that we don't understand
goweb.Map(func(ctx context.Context) error {
return responder.RespondWithError(ctx, http.StatusBadRequest, "Parameters do not match a valid Shock request type.")
})
}
func main() {
// init(s)
conf.Initialize()
logger.Initialize()
if err := db.Initialize(); err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
logger.Error("ERROR: " + err.Error())
os.Exit(1)
}
user.Initialize()
node.Initialize()
preauth.Initialize()
auth.Initialize()
// print conf
printLogo()
conf.Print()
// check if necessary directories exist or created
for _, path := range []string{conf.Conf["site-path"], conf.Conf["data-path"], conf.Conf["logs-path"], conf.Conf["data-path"] + "/temp"} {
if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
if err := os.Mkdir(path, 0777); err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
logger.Error("ERROR: " + err.Error())
os.Exit(1)
}
}
}
// reload
if conf.RELOAD != "" {
fmt.Println("####### Reloading #######")
err := reload(conf.RELOAD)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
logger.Error("ERROR: " + err.Error())
os.Exit(1)
}
fmt.Println("Done")
}
// setting GOMAXPROCS
var procs int
avail := runtime.NumCPU()
if avail <= 2 {
procs = 1
} else if avail == 3 {
procs = 2
} else {
procs = avail - 2
}
fmt.Println("##### Procs #####")
fmt.Printf("Number of available CPUs = %d\n", avail)
if conf.Conf["GOMAXPROCS"] != "" {
if setting, err := strconv.Atoi(conf.Conf["GOMAXPROCS"]); err != nil {
err_msg := "ERROR: could not interpret configured GOMAXPROCS value as integer.\n"
fmt.Fprintf(os.Stderr, err_msg)
logger.Error("ERROR: " + err_msg)
os.Exit(1)
} else {
procs = setting
}
}
if procs <= avail {
fmt.Printf("Running Shock server with GOMAXPROCS = %d\n\n", procs)
runtime.GOMAXPROCS(procs)
} else {
fmt.Println("GOMAXPROCS config value is greater than available number of CPUs.")
fmt.Printf("Running Shock server with GOMAXPROCS = %d\n\n", avail)
runtime.GOMAXPROCS(avail)
}
if conf.Conf["pidfile"] != "" {
f, err := os.Create(conf.Conf["pidfile"])
if err != nil {
err_msg := "Could not create pid file: " + conf.Conf["pidfile"] + "\n"
fmt.Fprintf(os.Stderr, err_msg)
logger.Error("ERROR: " + err_msg)
os.Exit(1)
}
defer f.Close()
pid := os.Getpid()
fmt.Fprintln(f, pid)
fmt.Println("##### pidfile #####")
fmt.Printf("pid: %d saved to file: %s\n\n", pid, conf.Conf["pidfile"])
}
Address := conf.Conf["api-ip"] + ":" + conf.Conf["api-port"]
mapRoutes()
s := &http.Server{
Addr: ":" + Address,
Handler: goweb.DefaultHttpHandler(),
ReadTimeout: 0,
WriteTimeout: 0,
MaxHeaderBytes: 1 << 20,
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
listener, listenErr := net.Listen("tcp", Address)
if listenErr != nil {
err_msg := "Could not listen - " + listenErr.Error() + "\n"
fmt.Fprintf(os.Stderr, err_msg)
logger.Error("ERROR: " + err_msg)
os.Exit(1)
}
go func() {
for _ = range c {
// sig is a ^C, handle it
// stop the HTTP server
fmt.Fprintln(os.Stderr, "Stopping the server...")
listener.Close()
}
}()
fmt.Fprintf(os.Stderr, "Error in Serve: %s\n", s.Serve(listener))
}