/
command.go
282 lines (247 loc) · 6.65 KB
/
command.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
package command
import (
"errors"
"fmt"
"net/http"
"sync"
"time"
"golang.org/x/net/context"
"github.com/codegangsta/cli"
"github.com/golang/glog"
"github.com/rs/xhandler"
"tower.pro/renderer/compiler"
"tower.pro/renderer/renderer"
"tower.pro/renderer/storage"
"tower.pro/renderer/watcher"
// Profiler
_ "net/http/pprof"
)
// DefaultWebOptions - Default renderer options.
// You can append options here like renderer.WithMiddleware.
var DefaultWebOptions = []renderer.Option{
// It means we won't spit out component JSON, just HTML
// in case of API routes like one using json.encode they
// will still work as expected with no difference
renderer.WithAlwaysHTML(true),
}
// Commands - List of renderer commands.
var Commands = []cli.Command{
Web,
}
// Web - Web command.
var Web = cli.Command{
Name: "server",
Usage: "renderer server",
Flags: []cli.Flag{
// Compiler options
cli.StringSliceFlag{
Name: "routes",
Usage: "file containing routes in yaml format",
},
cli.StringFlag{
Name: "components",
Usage: "directory containing components",
},
cli.BoolFlag{
Name: "watch",
Usage: "watch for changes in components",
},
cli.BoolFlag{
Name: "compress",
Usage: "removes repeated whitespaces",
},
cli.DurationFlag{
Name: "cache-expiration",
Usage: "cache expiration time",
Value: 15 * time.Minute,
},
cli.DurationFlag{
Name: "cache-cleanup",
Usage: "cache cleanup interval",
Value: 5 * time.Minute,
},
// Web server options
cli.StringFlag{
Name: "listen-addr",
Usage: "renderer interface listening address",
Value: "127.0.0.1:6660",
},
cli.DurationFlag{
Name: "render-timeout",
Usage: "component render timeout",
Value: 5 * time.Second,
},
// HTTP server flags
cli.DurationFlag{
Name: "renderer-read-timeout",
EnvVar: "RENDERER_READ_TIMEOUT",
Usage: "renderer server read timeout",
Value: time.Minute,
},
cli.DurationFlag{
Name: "renderer-write-timeout",
EnvVar: "RENDERER_WRITE_TIMEOUT",
Usage: "renderer server write timeout",
Value: time.Minute,
},
// Tracing and profiling
cli.StringFlag{
Name: "debug-addr",
EnvVar: "DEBUG_ADDR",
Usage: "debug listening address",
},
cli.BoolFlag{
Name: "tracing",
EnvVar: "TRACING",
Usage: "enable tracing (use with --debug-addr)",
},
},
Action: func(c *cli.Context) (err error) {
// Get components directory from --components flag
// Print fatal error if not set
if c.String("components") == "" {
return errors.New("--components flag cannot be empty")
}
// Create a new storage in directory from --components flag
storage, err := storage.New(
storage.WithDir(c.String("components")),
storage.WithCacheExpiration(c.Duration("cache-expiration")),
storage.WithCacheCleanupInterval(c.Duration("cache-cleanup")),
storage.WithWhitespaceRemoval(c.Bool("compress")),
)
if err != nil {
return fmt.Errorf("[storage] %v", err)
}
defer storage.Close()
// Create a compiler from storage
comp := compiler.New(storage)
// Create a context with compiler
ctx := compiler.NewContext(context.Background(), comp)
if c.Bool("tracing") {
DefaultWebOptions = append(DefaultWebOptions, renderer.WithTracing())
}
// Turn routes into HTTP handler
api, err := constructHandler(c.StringSlice("routes"), DefaultWebOptions)
if err != nil {
return fmt.Errorf("[routes] %v", err)
}
// Construct API handler
handler := &atomicHandler{
Context: ctx,
Current: xhandler.New(ctx, api),
Options: DefaultWebOptions,
Watching: c.Bool("watch"),
Routes: c.StringSlice("routes"),
Mutex: new(sync.RWMutex),
}
if c.Bool("watch") {
// Start watching for changes in components directory
var w *watcher.Watcher
w, err = watcher.Start(c.String("components"), storage)
if err != nil {
return
}
defer w.Stop()
// Start watching for changes in routes
for _, filename := range c.StringSlice("routes") {
var watch *watcher.Watcher
watch, err = watcher.Start(filename, handler)
if err != nil {
return
}
defer watch.Stop()
}
}
// Start profiler if enabled
if addr := c.String("pprof-addr"); addr != "" {
go func() {
if err = debugServer(addr); err != nil {
glog.Fatal(err)
}
}()
}
// Construct http server
server := &http.Server{
Addr: c.String("listen-addr"),
Handler: handler,
ReadTimeout: c.Duration("http-read-timeout"),
WriteTimeout: c.Duration("http-write-timeout"),
MaxHeaderBytes: 64 * 1024,
}
glog.Infof("[renderer] starting server on %s", c.String("listen-addr"))
return server.ListenAndServe()
},
}
type atomicHandler struct {
Context context.Context
Current http.Handler
Options []renderer.Option
Mutex *sync.RWMutex
Watching bool
Routes []string
}
// FlushCache - Flushes routes cache. Reads them and constructs handler.
func (handler *atomicHandler) FlushCache() {
// Construct handler from routes
h, err := handler.construct()
if err != nil {
glog.Fatalf("[routes] %v", err)
}
// Lock mutex and exchange handler
handler.Mutex.Lock()
handler.Current = h
handler.Mutex.Unlock()
}
func (handler *atomicHandler) construct() (_ http.Handler, err error) {
h, err := constructHandler(handler.Routes, handler.Options)
if err != nil {
return
}
return xhandler.New(handler.Context, h), nil
}
func (handler *atomicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// If not watching don't use mutexe
if !handler.Watching {
handler.Current.ServeHTTP(w, r)
return
}
// Lock for read and get handler
handler.Mutex.RLock()
h := handler.Current
handler.Mutex.RUnlock()
// Serve request
h.ServeHTTP(w, r)
}
func constructHandler(filenames []string, options []renderer.Option) (_ xhandler.HandlerC, err error) {
if len(filenames) == 0 {
return renderer.New(), nil
}
routes, err := constructRoutes(filenames, options)
if err != nil {
return
}
// Turn routes into HTTP handler
return routes.Construct(options...)
}
// constructRoutes - Constructs routes map from multiple filenames.
func constructRoutes(filenames []string, options []renderer.Option) (res renderer.Routes, err error) {
res = make(renderer.Routes)
for _, filename := range filenames {
var routes renderer.Routes
routes, err = renderer.RoutesFromFile(filename)
if err != nil {
return
}
for route, handler := range routes {
if _, exists := res[route]; exists {
return nil, fmt.Errorf("route %q in %q is not unique", route, filename)
}
res[route] = handler
}
}
return
}
func debugServer(addr string) (err error) {
glog.Infof("[debug] starting server on %s", addr)
return http.ListenAndServe(addr, nil)
}