1 //
2 // Copyright (C) 2014 Sebastian 'tokkee' Harl <sh@tokkee.org>
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions
7 // are met:
8 // 1. Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // 2. Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 //
14 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15 // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
16 // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
18 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21 // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23 // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
24 // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 package server
28 // Helper functions for handling queries.
30 import (
31 "errors"
32 "fmt"
33 "strings"
34 "time"
35 "unicode"
37 "github.com/sysdb/go/client"
38 "github.com/sysdb/go/proto"
39 )
41 func listAll(req request, s *Server) (*page, error) {
42 if len(req.args) != 0 {
43 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
44 }
46 q, err := client.QueryString("LIST %s", client.Identifier(req.cmd))
47 if err != nil {
48 return nil, err
49 }
50 res, err := s.c.Query(q)
51 if err != nil {
52 return nil, err
53 }
54 // the template *must* exist
55 return tmpl(s.results[req.cmd], res)
56 }
58 func lookup(req request, s *Server) (*page, error) {
59 if req.r.Method != "POST" {
60 return nil, errors.New("Method not allowed")
61 }
62 raw, err := parseQuery(req.r.PostForm.Get("query"))
63 if err != nil {
64 return nil, err
65 }
67 if raw.typ == "" {
68 raw.typ = "hosts"
69 }
70 var args string
71 for name, value := range raw.args {
72 if len(args) > 0 {
73 args += " AND"
74 }
76 if name == "name" {
77 args += fmt.Sprintf(" name =~ %s", value)
78 } else {
79 args += fmt.Sprintf(" %s = %s", name, value)
80 }
81 }
83 q, err := client.QueryString("LOOKUP %s MATCHING"+args, client.Identifier(raw.typ))
84 if err != nil {
85 return nil, err
86 }
87 res, err := s.c.Query(q)
88 if err != nil {
89 return nil, err
90 }
91 if t, ok := s.results[raw.typ]; ok {
92 return tmpl(t, res)
93 }
94 return nil, fmt.Errorf("Unsupported type %s", raw.typ)
95 }
97 func fetch(req request, s *Server) (*page, error) {
98 if len(req.args) == 0 {
99 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
100 }
102 var q string
103 var err error
104 switch req.cmd {
105 case "host":
106 if len(req.args) != 1 {
107 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
108 }
109 q, err = client.QueryString("FETCH host %s", req.args[0])
110 case "service", "metric":
111 if len(req.args) != 2 {
112 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
113 }
114 q, err = client.QueryString("FETCH %s %s.%s", client.Identifier(req.cmd), req.args[0], req.args[1])
115 default:
116 panic("Unknown request: fetch(" + req.cmd + ")")
117 }
118 if err != nil {
119 return nil, err
120 }
122 res, err := s.c.Query(q)
123 if err != nil {
124 return nil, err
125 }
126 if req.cmd == "metric" {
127 return metric(req, res, s)
128 }
129 return tmpl(s.results[req.cmd], res)
130 }
132 func graphs(req request, s *Server) (*page, error) {
133 p := struct {
134 Query, Metrics string
135 QueryOptions string
136 GroupBy []string
137 Attributes map[string]bool
138 }{
139 Query: req.r.PostForm.Get("metrics-query"),
140 GroupBy: req.r.PostForm["group-by"],
141 }
143 if req.r.Method == "POST" {
144 p.Metrics = p.Query
145 if len(p.GroupBy) > 0 {
146 p.QueryOptions += "/g=" + strings.Join(p.GroupBy, ",")
147 }
149 metrics, err := s.queryMetrics(p.Query)
150 if err != nil {
151 return nil, err
152 }
153 p.Attributes = make(map[string]bool)
154 for _, m := range metrics {
155 for a := range m.Attributes {
156 var checked bool
157 for _, g := range p.GroupBy {
158 if a == g {
159 checked = true
160 break
161 }
162 }
163 p.Attributes[a] = checked
164 }
165 }
166 }
167 return tmpl(s.results["graphs"], &p)
168 }
170 var datetime = "2006-01-02 15:04:05"
172 func metric(req request, res interface{}, s *Server) (*page, error) {
173 start := time.Now().Add(-24 * time.Hour)
174 end := time.Now()
175 if req.r.Method == "POST" {
176 var err error
177 // Parse the values first to verify their format.
178 if s := req.r.PostForm.Get("start_date"); s != "" {
179 if start, err = time.Parse(datetime, s); err != nil {
180 return nil, fmt.Errorf("Invalid start time %q", s)
181 }
182 }
183 if e := req.r.PostForm.Get("end_date"); e != "" {
184 if end, err = time.Parse(datetime, e); err != nil {
185 return nil, fmt.Errorf("Invalid end time %q", e)
186 }
187 }
188 }
190 p := struct {
191 StartTime string
192 EndTime string
193 URLStart string
194 URLEnd string
195 Data interface{}
196 }{
197 start.Format(datetime),
198 end.Format(datetime),
199 start.Format(urldate),
200 end.Format(urldate),
201 res,
202 }
203 return tmpl(s.results["metric"], &p)
204 }
206 type query struct {
207 typ string
208 args map[string]string
209 }
211 func (q *query) arg(name, value string) error {
212 if _, ok := q.args[name]; ok {
213 return fmt.Errorf("Duplicate key %q", name)
214 }
215 q.args[name] = proto.EscapeString(value)
216 return nil
217 }
219 func (q *query) attr(parent, name, value string) error {
220 var k string
221 if parent != "" {
222 k = fmt.Sprintf("%s.attribute[%s]", parent, proto.EscapeString(name))
223 } else {
224 k = fmt.Sprintf("attribute[%s]", proto.EscapeString(name))
225 }
227 return q.arg(k, value)
228 }
230 func parseQuery(s string) (*query, error) {
231 tokens, err := tokenize(s)
232 if err != nil {
233 return nil, err
234 }
235 if len(tokens) == 0 {
236 return nil, errors.New("Empty query")
237 }
239 q := &query{args: make(map[string]string)}
240 for i, tok := range tokens {
241 if fields := strings.SplitN(tok, ":", 2); len(fields) == 2 {
242 // Query: [<type>:] [<sibling-type>.]<attribute>:<value> ...
243 if i == 0 && fields[1] == "" {
244 q.typ = fields[0]
245 } else if elems := strings.Split(fields[0], "."); len(elems) > 1 {
246 objs := elems[:len(elems)-1]
247 for _, o := range objs {
248 if o != "host" && o != "service" && o != "metric" {
249 return nil, fmt.Errorf("Invalid object type %q", o)
250 }
251 }
252 if err := q.attr(strings.Join(objs, "."), elems[len(elems)-1], fields[1]); err != nil {
253 return nil, err
254 }
255 } else {
256 if err := q.attr("", fields[0], fields[1]); err != nil {
257 return nil, err
258 }
259 }
260 } else {
261 if err := q.arg("name", tok); err != nil {
262 return nil, err
263 }
264 }
265 }
266 return q, nil
267 }
269 // tokenize split the string s into its tokens where a token is either a quoted
270 // string or surrounded by one or more consecutive whitespace characters.
271 func tokenize(s string) ([]string, error) {
272 scan := scanner{}
273 tokens := []string{}
274 start := -1
275 for i, r := range s {
276 if !scan.inField(r) {
277 if start == -1 {
278 // Skip leading and consecutive whitespace.
279 continue
280 }
281 tok, err := unescape(s[start:i])
282 if err != nil {
283 return nil, err
284 }
285 tokens = append(tokens, tok)
286 start = -1
287 } else if start == -1 {
288 // Found a new field.
289 start = i
290 }
291 }
292 if start >= 0 {
293 // Last (or possibly only) field.
294 tok, err := unescape(s[start:])
295 if err != nil {
296 return nil, err
297 }
298 tokens = append(tokens, tok)
299 }
301 if scan.inQuotes {
302 return nil, errors.New("quoted string not terminated")
303 }
304 if scan.escaped {
305 return nil, errors.New("illegal character escape at end of string")
306 }
307 return tokens, nil
308 }
310 func unescape(s string) (string, error) {
311 var unescaped []byte
312 var i, n int
313 for i = 0; i < len(s); i++ {
314 if s[i] != '\\' {
315 n++
316 continue
317 }
319 if i >= len(s) {
320 return "", errors.New("illegal character escape at end of string")
321 }
322 if s[i+1] != ' ' && s[i+1] != '"' && s[i+1] != '\\' {
323 // Allow simple escapes only for now.
324 return "", fmt.Errorf("illegal character escape \\%c", s[i+1])
325 }
326 if unescaped == nil {
327 unescaped = []byte(s)
328 }
329 copy(unescaped[n:], s[i+1:])
330 }
332 if unescaped != nil {
333 return string(unescaped[:n]), nil
334 }
335 return s, nil
336 }
338 type scanner struct {
339 inQuotes bool
340 escaped bool
341 }
343 func (s *scanner) inField(r rune) bool {
344 if s.escaped {
345 s.escaped = false
346 return true
347 }
348 if r == '\\' {
349 s.escaped = true
350 return true
351 }
352 if s.inQuotes {
353 if r == '"' {
354 s.inQuotes = false
355 return false
356 }
357 return true
358 }
359 if r == '"' {
360 s.inQuotes = true
361 return false
362 }
363 return !unicode.IsSpace(r)
364 }
366 // vim: set tw=78 sw=4 sw=4 noexpandtab :