-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
static_handler.go
243 lines (210 loc) · 7.31 KB
/
static_handler.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
// Copyright (c) 2019 The Jaeger Authors.
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"regexp"
"strings"
"sync/atomic"
"github.com/fsnotify/fsnotify"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/jaegertracing/jaeger/cmd/query/app/ui"
)
var (
favoriteIcon = "favicon.ico"
staticRootFiles = []string{favoriteIcon}
configPattern = regexp.MustCompile("JAEGER_CONFIG *= *DEFAULT_CONFIG;")
basePathPattern = regexp.MustCompile(`<base href="/"`)
basePathReplace = `<base href="%s/"`
errBadBasePath = "Invalid base path '%s'. Must start but not end with a slash '/', e.g. '/jaeger/ui'"
)
// RegisterStaticHandler adds handler for static assets to the router.
func RegisterStaticHandler(r *mux.Router, logger *zap.Logger, qOpts *QueryOptions) {
staticHandler, err := NewStaticAssetsHandler(qOpts.StaticAssets, StaticAssetsHandlerOptions{
BasePath: qOpts.BasePath,
UIConfigPath: qOpts.UIConfig,
Logger: logger,
})
if err != nil {
logger.Panic("Could not create static assets handler", zap.Error(err))
}
staticHandler.RegisterRoutes(r)
}
// StaticAssetsHandler handles static assets
type StaticAssetsHandler struct {
options StaticAssetsHandlerOptions
indexHTML atomic.Value // stores []byte
assetsFS http.FileSystem
}
// StaticAssetsHandlerOptions defines options for NewStaticAssetsHandler
type StaticAssetsHandlerOptions struct {
BasePath string
UIConfigPath string
Logger *zap.Logger
}
// NewStaticAssetsHandler returns a StaticAssetsHandler
func NewStaticAssetsHandler(staticAssetsRoot string, options StaticAssetsHandlerOptions) (*StaticAssetsHandler, error) {
assetsFS := ui.StaticFiles
if staticAssetsRoot != "" {
assetsFS = http.Dir(staticAssetsRoot)
}
if options.Logger == nil {
options.Logger = zap.NewNop()
}
indexHTML, err := loadIndexBytes(assetsFS.Open, options)
if err != nil {
return nil, err
}
h := &StaticAssetsHandler{
options: options,
assetsFS: assetsFS,
}
h.indexHTML.Store(indexHTML)
h.watch()
return h, nil
}
func loadIndexBytes(open func(string) (http.File, error), options StaticAssetsHandlerOptions) ([]byte, error) {
indexBytes, err := loadIndexHTML(open)
if err != nil {
return nil, errors.Wrap(err, "cannot load index.html")
}
configString := "JAEGER_CONFIG = DEFAULT_CONFIG"
if config, err := loadUIConfig(options.UIConfigPath); err != nil {
return nil, err
} else if config != nil {
// TODO if we want to support other config formats like YAML, we need to normalize `config` to be
// suitable for json.Marshal(). For example, YAML parser may return a map that has keys of type
// interface{}, and json.Marshal() is unable to serialize it.
bytes, _ := json.Marshal(config)
configString = fmt.Sprintf("JAEGER_CONFIG = %v", string(bytes))
}
indexBytes = configPattern.ReplaceAll(indexBytes, []byte(configString+";"))
if options.BasePath == "" {
options.BasePath = "/"
}
if options.BasePath != "/" {
if !strings.HasPrefix(options.BasePath, "/") || strings.HasSuffix(options.BasePath, "/") {
return nil, fmt.Errorf(errBadBasePath, options.BasePath)
}
indexBytes = basePathPattern.ReplaceAll(indexBytes, []byte(fmt.Sprintf(basePathReplace, options.BasePath)))
}
return indexBytes, nil
}
func (sH *StaticAssetsHandler) watch() {
if sH.options.UIConfigPath == "" {
return
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
sH.options.Logger.Error("failed to create a new watcher for the UI config", zap.Error(err))
return
}
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Remove == fsnotify.Remove {
// this might be related to a file inside the dir, so, just log a warn if this is about the file we care about
// otherwise, just ignore the event
if event.Name == sH.options.UIConfigPath {
sH.options.Logger.Warn("the UI config file has been removed, using the last known version")
}
continue
}
// this will catch events for all files inside the same directory, which is OK if we don't have many changes
sH.options.Logger.Info("reloading UI config", zap.String("filename", sH.options.UIConfigPath))
content, err := loadIndexBytes(sH.assetsFS.Open, sH.options)
if err != nil {
sH.options.Logger.Error("error while reloading the UI config", zap.Error(err))
}
sH.indexHTML.Store(content)
case err, ok := <-watcher.Errors:
if !ok {
return
}
sH.options.Logger.Error("event", zap.Error(err))
}
}
}()
err = watcher.Add(sH.options.UIConfigPath)
if err != nil {
sH.options.Logger.Error("error adding watcher to file", zap.String("file", sH.options.UIConfigPath), zap.Error(err))
} else {
sH.options.Logger.Info("watching", zap.String("file", sH.options.UIConfigPath))
}
dir := filepath.Dir(sH.options.UIConfigPath)
err = watcher.Add(dir)
if err != nil {
sH.options.Logger.Error("error adding watcher to dir", zap.String("dir", dir), zap.Error(err))
} else {
sH.options.Logger.Info("watching", zap.String("dir", dir))
}
}
func loadIndexHTML(open func(string) (http.File, error)) ([]byte, error) {
indexFile, err := open("/index.html")
if err != nil {
return nil, errors.Wrap(err, "cannot open index.html")
}
defer indexFile.Close()
indexBytes, err := ioutil.ReadAll(indexFile)
if err != nil {
return nil, errors.Wrap(err, "cannot read from index.html")
}
return indexBytes, nil
}
func loadUIConfig(uiConfig string) (map[string]interface{}, error) {
if uiConfig == "" {
return nil, nil
}
ext := filepath.Ext(uiConfig)
bytes, err := ioutil.ReadFile(uiConfig) /* nolint #nosec , this comes from an admin, not user */
if err != nil {
return nil, errors.Wrapf(err, "cannot read UI config file %v", uiConfig)
}
var c map[string]interface{}
var unmarshal func([]byte, interface{}) error
switch strings.ToLower(ext) {
case ".json":
unmarshal = json.Unmarshal
default:
return nil, fmt.Errorf("unrecognized UI config file format %v", uiConfig)
}
if err := unmarshal(bytes, &c); err != nil {
return nil, errors.Wrapf(err, "cannot parse UI config file %v", uiConfig)
}
return c, nil
}
// RegisterRoutes registers routes for this handler on the given router
func (sH *StaticAssetsHandler) RegisterRoutes(router *mux.Router) {
fileServer := http.FileServer(sH.assetsFS)
if sH.options.BasePath != "/" {
fileServer = http.StripPrefix(sH.options.BasePath+"/", fileServer)
}
router.PathPrefix("/static/").Handler(fileServer)
for _, file := range staticRootFiles {
router.Path("/" + file).Handler(fileServer)
}
router.NotFoundHandler = http.HandlerFunc(sH.notFound)
}
func (sH *StaticAssetsHandler) notFound(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(sH.indexHTML.Load().([]byte))
}