forked from xiam/luminos
/
command-run.go
325 lines (252 loc) · 7.21 KB
/
command-run.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
Copyright (c) 2012-2013 José Carlos Nieto, http://xiam.menteslibres.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package main
import (
"errors"
"flag"
"fmt"
//"github.com/howeyc/fsnotify"
"log"
"menteslibres.net/gosexy/cli"
"menteslibres.net/gosexy/to"
"menteslibres.net/gosexy/yaml"
"menteslibres.net/luminos/host"
"menteslibres.net/luminos/watcher"
"net"
"net/http"
"net/http/fcgi"
"os"
"strings"
)
// Default values
const DEFAULT_SETTINGS_FILE = "./settings.yaml"
const DEFAULT_SERVER_DOMAIN = "unix"
const DEFAULT_SERVER_PROTOCOL = "tcp"
// Global settings.
var settings *yaml.Yaml
// Host map.
var hosts map[string]*host.Host
// Settings
var flagSettings = flag.String("c", DEFAULT_SETTINGS_FILE, "Path to the settings.yaml file.")
var watch *watcher.Watcher
func init() {
cli.Register("run", cli.Entry{
Name: "run",
Description: "Runs a luminos server.",
Arguments: []string{"c"},
Command: &runCommand{},
})
hosts = make(map[string]*host.Host)
}
type server struct {
}
type runCommand struct {
}
// Dispatches a request and returns the appropriate host.
func route(req *http.Request) *host.Host {
name := req.Host
// Stripping port from request.
if strings.Contains(name, ":") {
name = name[0:strings.Index(name, ":")]
}
path := name + req.URL.Path
// Searching for best match for host.
match := ""
for key, _ := range hosts {
lkey := len(key)
if lkey >= len(match) && lkey <= len(path) {
if path[0:lkey] == key {
match = key
}
}
}
if match == "" {
log.Printf("Could not match any host: %s, falling back to default.\n", req.Host)
match = "default"
}
if _, ok := hosts[match]; ok == true {
return hosts[match]
}
log.Printf("Request for unknown host: %s\n", req.Host)
return nil
}
// Routes a request and lets the host handle it.
func (self server) ServeHTTP(wri http.ResponseWriter, req *http.Request) {
r := route(req)
if r != nil {
r.ServeHTTP(wri, req)
} else {
log.Printf("Failed to serve host %s.\n", req.Host)
}
}
// Loads settings
func loadSettings(file string) (*yaml.Yaml, error) {
var entries map[interface{}]interface{}
var ok bool
// Trying to read settings from file.
y, err := yaml.Open(file)
if err != nil {
return nil, err
}
// Loading and verifying host entries
if entries, ok = y.Get("hosts").(map[interface{}]interface{}); ok == false {
return nil, errors.New("Missing \"hosts\" entry.")
}
h := map[string]*host.Host{}
for key, _ := range entries {
name := to.String(key)
path := to.String(entries[name])
info, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("Failed to validate host %s: %s.", name, err.Error())
}
if info.IsDir() == false {
return nil, fmt.Errorf("Host %s does not point to a directory.", name)
}
h[name], err = host.New(name, path)
if err != nil {
return nil, fmt.Errorf("Failed to initialize host %s: %s.", name, err.Error())
}
}
for name, _ := range hosts {
hosts[name].Close()
}
hosts = h
if _, ok := hosts["default"]; ok == false {
log.Printf("Warning: default host was not provided.")
}
return y, nil
}
func settingsWatcher() error {
var err error
/*
// Watching settings file for changes.
// Was not properly returning events on OSX.
// https://github.com/howeyc/fsnotify/issues/34
watcher, err := fsnotify.NewWatcher()
if err == nil {
defer watcher.Close()
go func() {
for {
select {
case ev := <-watcher.Event:
if ev == nil {
return
}
if ev.IsModify() {
log.Printf("Trying to reload settings file %s...\n", ev.Name)
y, err := loadSettings(ev.Name)
if err != nil {
log.Printf("Error loading settings file %s: %s\n", ev.Name, err.Error())
} else {
settings = y
}
} else if ev.IsDelete() {
watcher.RemoveWatch(ev.Name)
watcher.Watch(ev.Name)
}
case err := <-watcher.Error:
log.Printf("Watcher error: %s\n", err.Error())
}
}
}()
watcher.Watch(settingsFile)
}
*/
// (Stupid) file modification watcher.
watch, err = watcher.New()
if err == nil {
go func() {
defer watch.Close()
for {
select {
case ev := <-watch.Event:
if ev.IsModify() {
y, err := loadSettings(ev.Name)
if err != nil {
log.Printf("Error loading settings file %s: %s\n", ev.Name, err.Error())
} else {
log.Printf("Reloading settings file %s.\n", ev.Name)
settings = y
}
}
}
}
}()
}
return err
}
func (self *runCommand) Execute() error {
// Default settings file.
if *flagSettings == "" {
*flagSettings = DEFAULT_SETTINGS_FILE
}
stat, err := os.Stat(*flagSettings)
if err != nil {
return fmt.Errorf("Error while opening %s: %s", *flagSettings, err.Error())
}
if stat != nil {
if stat.IsDir() == true {
return fmt.Errorf("Could not open %s: it's a directory!", *flagSettings)
} else {
settings, err = loadSettings(*flagSettings)
if err != nil {
return fmt.Errorf("Error while reading settings file %s: %s", *flagSettings, err.Error())
}
err = settingsWatcher()
if err == nil {
watch.Watch(*flagSettings)
}
serverType := to.String(settings.Get("server", "type"))
domain := DEFAULT_SERVER_DOMAIN
address := to.String(settings.Get("server", "socket"))
if address == "" {
domain = DEFAULT_SERVER_PROTOCOL
address = fmt.Sprintf("%s:%d", to.String(settings.Get("server", "bind")), to.Int64(settings.Get("server", "port")))
}
listener, err := net.Listen(domain, address)
if err != nil {
return err
}
defer listener.Close()
switch serverType {
case "fastcgi":
if err == nil {
log.Printf("Starting FastCGI server. Listening at %s.", address)
fcgi.Serve(listener, &server{})
} else {
return fmt.Errorf("Failed to start FastCGI server: %s", err.Error())
}
case "standalone":
if err == nil {
log.Printf("Starting HTTP server. Listening at %s.", address)
http.Serve(listener, &server{})
} else {
return fmt.Errorf("Failed to start HTTP server: %s", err.Error())
}
default:
return fmt.Errorf("Unknown server type: %s", serverType)
}
}
} else {
return fmt.Errorf("Could not load settings file: %s.", *flagSettings)
}
return nil
}