22385bf07de13e576e03007b179ede5fd6e97000
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 }{
138 Query: req.r.PostForm.Get("metrics-query"),
139 GroupBy: req.r.PostForm.Get("group-by"),
140 }
142 if req.r.Method == "POST" {
143 p.Metrics = p.Query
144 if p.GroupBy != "" {
145 p.QueryOptions += "/g=" + strings.Join(strings.Fields(p.GroupBy), ",")
146 }
147 }
148 return tmpl(s.results["graphs"], &p)
149 }
151 var datetime = "2006-01-02 15:04:05"
153 func metric(req request, res interface{}, s *Server) (*page, error) {
154 start := time.Now().Add(-24 * time.Hour)
155 end := time.Now()
156 if req.r.Method == "POST" {
157 var err error
158 // Parse the values first to verify their format.
159 if s := req.r.PostForm.Get("start_date"); s != "" {
160 if start, err = time.Parse(datetime, s); err != nil {
161 return nil, fmt.Errorf("Invalid start time %q", s)
162 }
163 }
164 if e := req.r.PostForm.Get("end_date"); e != "" {
165 if end, err = time.Parse(datetime, e); err != nil {
166 return nil, fmt.Errorf("Invalid end time %q", e)
167 }
168 }
169 }
171 p := struct {
172 StartTime string
173 EndTime string
174 URLStart string
175 URLEnd string
176 Data interface{}
177 }{
178 start.Format(datetime),
179 end.Format(datetime),
180 start.Format(urldate),
181 end.Format(urldate),
182 res,
183 }
184 return tmpl(s.results["metric"], &p)
185 }
187 type query struct {
188 typ string
189 args map[string]string
190 }
192 func (q *query) arg(name, value string) error {
193 if _, ok := q.args[name]; ok {
194 return fmt.Errorf("Duplicate key %q", name)
195 }
196 q.args[name] = proto.EscapeString(value)
197 return nil
198 }
200 func (q *query) attr(parent, name, value string) error {
201 var k string
202 if parent != "" {
203 k = fmt.Sprintf("%s.attribute[%s]", parent, proto.EscapeString(name))
204 } else {
205 k = fmt.Sprintf("attribute[%s]", proto.EscapeString(name))
206 }
208 return q.arg(k, value)
209 }
211 func parseQuery(s string) (*query, error) {
212 tokens, err := tokenize(s)
213 if err != nil {
214 return nil, err
215 }
216 if len(tokens) == 0 {
217 return nil, errors.New("Empty query")
218 }
220 q := &query{args: make(map[string]string)}
221 for i, tok := range tokens {
222 if fields := strings.SplitN(tok, ":", 2); len(fields) == 2 {
223 // Query: [<type>:] [<sibling-type>.]<attribute>:<value> ...
224 if i == 0 && fields[1] == "" {
225 q.typ = fields[0]
226 } else if elems := strings.Split(fields[0], "."); len(elems) > 1 {
227 objs := elems[:len(elems)-1]
228 for _, o := range objs {
229 if o != "host" && o != "service" && o != "metric" {
230 return nil, fmt.Errorf("Invalid object type %q", o)
231 }
232 }
233 if err := q.attr(strings.Join(objs, "."), elems[len(elems)-1], fields[1]); err != nil {
234 return nil, err
235 }
236 } else {
237 if err := q.attr("", fields[0], fields[1]); err != nil {
238 return nil, err
239 }
240 }
241 } else {
242 if err := q.arg("name", tok); err != nil {
243 return nil, err
244 }
245 }
246 }
247 return q, nil
248 }
250 // tokenize split the string s into its tokens where a token is either a quoted
251 // string or surrounded by one or more consecutive whitespace characters.
252 func tokenize(s string) ([]string, error) {
253 scan := scanner{}
254 tokens := []string{}
255 start := -1
256 for i, r := range s {
257 if !scan.inField(r) {
258 if start == -1 {
259 // Skip leading and consecutive whitespace.
260 continue
261 }
262 tok, err := unescape(s[start:i])
263 if err != nil {
264 return nil, err
265 }
266 tokens = append(tokens, tok)
267 start = -1
268 } else if start == -1 {
269 // Found a new field.
270 start = i
271 }
272 }
273 if start >= 0 {
274 // Last (or possibly only) field.
275 tok, err := unescape(s[start:])
276 if err != nil {
277 return nil, err
278 }
279 tokens = append(tokens, tok)
280 }
282 if scan.inQuotes {
283 return nil, errors.New("quoted string not terminated")
284 }
285 if scan.escaped {
286 return nil, errors.New("illegal character escape at end of string")
287 }
288 return tokens, nil
289 }
291 func unescape(s string) (string, error) {
292 var unescaped []byte
293 var i, n int
294 for i = 0; i < len(s); i++ {
295 if s[i] != '\\' {
296 n++
297 continue
298 }
300 if i >= len(s) {
301 return "", errors.New("illegal character escape at end of string")
302 }
303 if s[i+1] != ' ' && s[i+1] != '"' && s[i+1] != '\\' {
304 // Allow simple escapes only for now.
305 return "", fmt.Errorf("illegal character escape \\%c", s[i+1])
306 }
307 if unescaped == nil {
308 unescaped = []byte(s)
309 }
310 copy(unescaped[n:], s[i+1:])
311 }
313 if unescaped != nil {
314 return string(unescaped[:n]), nil
315 }
316 return s, nil
317 }
319 type scanner struct {
320 inQuotes bool
321 escaped bool
322 }
324 func (s *scanner) inField(r rune) bool {
325 if s.escaped {
326 s.escaped = false
327 return true
328 }
329 if r == '\\' {
330 s.escaped = true
331 return true
332 }
333 if s.inQuotes {
334 if r == '"' {
335 s.inQuotes = false
336 return false
337 }
338 return true
339 }
340 if r == '"' {
341 s.inQuotes = true
342 return false
343 }
344 return !unicode.IsSpace(r)
345 }
347 // vim: set tw=78 sw=4 sw=4 noexpandtab :