forked from grafana/loki
/
server.go
201 lines (181 loc) · 5.28 KB
/
server.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
package server
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"sort"
"strings"
"text/template"
logutil "github.com/cortexproject/cortex/pkg/util"
"github.com/go-kit/kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/version"
serverww "github.com/weaveworks/common/server"
"github.com/grafana/loki/pkg/promtail/server/ui"
"github.com/grafana/loki/pkg/promtail/targets"
)
var (
readinessProbeFailure = "Not ready: Unable to find any logs to tail. Please verify permissions, volumes, scrape_config, etc."
readinessProbeSuccess = []byte("Ready")
)
// Server embed weaveworks server with static file and templating capability
type Server struct {
*serverww.Server
tms *targets.TargetManagers
externalURL *url.URL
}
// Config extends weaveworks server config
type Config struct {
serverww.Config `yaml:",inline"`
ExternalURL string `yaml:"external_url"`
}
// New makes a new Server
func New(cfg Config, tms *targets.TargetManagers) (*Server, error) {
wws, err := serverww.New(cfg.Config)
if err != nil {
return nil, err
}
externalURL, err := computeExternalURL(cfg.ExternalURL, cfg.HTTPListenPort)
if err != nil {
return nil, errors.Wrapf(err, "parse external URL %q", cfg.ExternalURL)
}
serv := &Server{
Server: wws,
tms: tms,
externalURL: externalURL,
}
serv.HTTP.Path("/").Handler(http.RedirectHandler("/targets", 303))
serv.HTTP.Path("/ready").Handler(http.HandlerFunc(serv.ready))
serv.HTTP.PathPrefix("/static/").Handler(http.FileServer(ui.Assets))
serv.HTTP.Path("/service-discovery").Handler(http.HandlerFunc(serv.serviceDiscovery))
serv.HTTP.Path("/targets").Handler(http.HandlerFunc(serv.targets))
return serv, nil
}
// serviceDiscovery serves the service discovery page.
func (s *Server) serviceDiscovery(rw http.ResponseWriter, _ *http.Request) {
var index []string
allTarget := s.tms.AllTargets()
for job := range allTarget {
index = append(index, job)
}
sort.Strings(index)
scrapeConfigData := struct {
Index []string
Targets map[string][]targets.Target
Active []int
Dropped []int
Total []int
}{
Index: index,
Targets: make(map[string][]targets.Target),
Active: make([]int, len(index)),
Dropped: make([]int, len(index)),
Total: make([]int, len(index)),
}
for i, job := range scrapeConfigData.Index {
scrapeConfigData.Targets[job] = make([]targets.Target, 0, len(allTarget[job]))
scrapeConfigData.Total[i] = len(allTarget[job])
for _, target := range allTarget[job] {
// Do not display more than 100 dropped targets per job to avoid
// returning too much data to the clients.
if targets.IsDropped(target) {
scrapeConfigData.Dropped[i]++
if scrapeConfigData.Dropped[i] > 100 {
continue
}
} else {
scrapeConfigData.Active[i]++
}
scrapeConfigData.Targets[job] = append(scrapeConfigData.Targets[job], target)
}
}
executeTemplate(context.Background(), rw, templateOptions{
Data: scrapeConfigData,
BuildVersion: version.Info(),
Name: "service-discovery.html",
PageTitle: "Service Discovery",
ExternalURL: s.externalURL,
TemplateFuncs: template.FuncMap{
"fileTargetDetails": func(details interface{}) map[string]int64 {
// you can't cast with a text template in go so this is a helper
return details.(map[string]int64)
},
"dropReason": func(details interface{}) string {
if reason, ok := details.(string); ok {
return reason
}
return ""
},
"numReady": func(ts []targets.Target) (readies int) {
for _, t := range ts {
if t.Ready() {
readies++
}
}
return
},
},
})
}
// targets serves the targets page.
func (s *Server) targets(rw http.ResponseWriter, _ *http.Request) {
executeTemplate(context.Background(), rw, templateOptions{
Data: struct {
TargetPools map[string][]targets.Target
}{
TargetPools: s.tms.ActiveTargets(),
},
BuildVersion: version.Info(),
Name: "targets.html",
PageTitle: "Targets",
ExternalURL: s.externalURL,
TemplateFuncs: template.FuncMap{
"fileTargetDetails": func(details interface{}) map[string]int64 {
// you can't cast with a text template in go so this is a helper
return details.(map[string]int64)
},
"numReady": func(ts []targets.Target) (readies int) {
for _, t := range ts {
if t.Ready() {
readies++
}
}
return
},
},
})
}
// ready serves the ready endpoint
func (s *Server) ready(rw http.ResponseWriter, _ *http.Request) {
if !s.tms.Ready() {
http.Error(rw, readinessProbeFailure, http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
if _, err := rw.Write(readinessProbeSuccess); err != nil {
level.Error(logutil.Logger).Log("msg", "error writing success message", "error", err)
}
}
// computeExternalURL computes a sanitized external URL from a raw input. It infers unset
// URL parts from the OS and the given listen address.
func computeExternalURL(u string, port int) (*url.URL, error) {
if u == "" {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
u = fmt.Sprintf("http://%s:%d/", hostname, port)
}
eu, err := url.Parse(u)
if err != nil {
return nil, err
}
ppref := strings.TrimRight(eu.Path, "/")
if ppref != "" && !strings.HasPrefix(ppref, "/") {
ppref = "/" + ppref
}
eu.Path = ppref
return eu, nil
}