Code

Added a very simple query language for name or attribute based lookups.
[sysdb/webui.git] / server / query.go
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         "log"
34         "strings"
35         "time"
36         "unicode"
38         "github.com/sysdb/go/proto"
39         "github.com/sysdb/go/sysdb"
40 )
42 func listAll(req request, s *Server) (*page, error) {
43         if len(req.args) != 0 {
44                 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
45         }
47         res, err := s.query("LIST %s", identifier(req.cmd))
48         if err != nil {
49                 return nil, err
50         }
51         // the template *must* exist
52         return tmpl(s.results[req.cmd], res)
53 }
55 func lookup(req request, s *Server) (*page, error) {
56         if req.r.Method != "POST" {
57                 return nil, errors.New("Method not allowed")
58         }
59         tokens, err := tokenize(req.r.PostForm.Get("query"))
60         if err != nil {
61                 return nil, err
62         }
63         if len(tokens) == 0 {
64                 return nil, errors.New("Empty query")
65         }
67         var args string
68         for i, tok := range tokens {
69                 if i != 0 {
70                         args += " AND"
71                 }
73                 if fields := strings.SplitN(tok, ":", 2); len(fields) == 2 {
74                         args += fmt.Sprintf(" attribute[%s] = %s",
75                                 proto.EscapeString(fields[0]), proto.EscapeString(fields[1]))
76                 } else {
77                         args += fmt.Sprintf(" name =~ %s", proto.EscapeString(tok))
78                 }
79         }
81         res, err := s.query("LOOKUP hosts MATCHING" + args)
82         if err != nil {
83                 return nil, err
84         }
85         return tmpl(s.results["hosts"], res)
86 }
88 func fetch(req request, s *Server) (*page, error) {
89         if len(req.args) == 0 {
90                 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
91         }
93         var res interface{}
94         var err error
95         switch req.cmd {
96         case "host":
97                 if len(req.args) != 1 {
98                         return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
99                 }
100                 res, err = s.query("FETCH host %s", req.args[0])
101         case "service", "metric":
102                 if len(req.args) != 2 {
103                         return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
104                 }
105                 res, err = s.query("FETCH %s %s.%s", identifier(req.cmd), req.args[0], req.args[1])
106                 if req.cmd == "metric" {
107                         return metric(req, res, s)
108                 }
109         default:
110                 panic("Unknown request: fetch(" + req.cmd + ")")
111         }
112         if err != nil {
113                 return nil, err
114         }
115         return tmpl(s.results[req.cmd], res)
118 var datetime = "2006-01-02 15:04:05"
120 func metric(req request, res interface{}, s *Server) (*page, error) {
121         start := time.Now().Add(-24 * time.Hour)
122         end := time.Now()
123         if req.r.Method == "POST" {
124                 var err error
125                 // Parse the values first to verify their format.
126                 if s := req.r.PostForm.Get("start_date"); s != "" {
127                         if start, err = time.Parse(datetime, s); err != nil {
128                                 return nil, fmt.Errorf("Invalid start time %q", s)
129                         }
130                 }
131                 if e := req.r.PostForm.Get("end_date"); e != "" {
132                         if end, err = time.Parse(datetime, e); err != nil {
133                                 return nil, fmt.Errorf("Invalid end time %q", e)
134                         }
135                 }
136         }
138         p := struct {
139                 StartTime string
140                 EndTime   string
141                 URLStart  string
142                 URLEnd    string
143                 Data      interface{}
144         }{
145                 start.Format(datetime),
146                 end.Format(datetime),
147                 start.Format(urldate),
148                 end.Format(urldate),
149                 res,
150         }
151         return tmpl(s.results["metric"], &p)
154 // tokenize split the string s into its tokens where a token is either a quoted
155 // string or surrounded by one or more consecutive whitespace characters.
156 func tokenize(s string) ([]string, error) {
157         scan := scanner{}
158         tokens := []string{}
159         start := -1
160         for i, r := range s {
161                 if !scan.inField(r) {
162                         if start == -1 {
163                                 // Skip leading and consecutive whitespace.
164                                 continue
165                         }
166                         tok, err := unescape(s[start:i])
167                         if err != nil {
168                                 return nil, err
169                         }
170                         tokens = append(tokens, tok)
171                         start = -1
172                 } else if start == -1 {
173                         // Found a new field.
174                         start = i
175                 }
176         }
177         if start >= 0 {
178                 // Last (or possibly only) field.
179                 tok, err := unescape(s[start:])
180                 if err != nil {
181                         return nil, err
182                 }
183                 tokens = append(tokens, tok)
184         }
186         if scan.inQuotes {
187                 return nil, errors.New("quoted string not terminated")
188         }
189         if scan.escaped {
190                 return nil, errors.New("illegal character escape at end of string")
191         }
192         return tokens, nil
195 func unescape(s string) (string, error) {
196         var unescaped []byte
197         var i, n int
198         for i = 0; i < len(s); i++ {
199                 if s[i] != '\\' {
200                         n++
201                         continue
202                 }
204                 if i >= len(s) {
205                         return "", errors.New("illegal character escape at end of string")
206                 }
207                 if s[i+1] != ' ' && s[i+1] != '"' && s[i+1] != '\\' {
208                         // Allow simple escapes only for now.
209                         return "", fmt.Errorf("illegal character escape \\%c", s[i+1])
210                 }
211                 if unescaped == nil {
212                         unescaped = []byte(s)
213                 }
214                 copy(unescaped[n:], s[i+1:])
215         }
217         if unescaped != nil {
218                 return string(unescaped[:n]), nil
219         }
220         return s, nil
223 type scanner struct {
224         inQuotes bool
225         escaped  bool
228 func (s *scanner) inField(r rune) bool {
229         if s.escaped {
230                 s.escaped = false
231                 return true
232         }
233         if r == '\\' {
234                 s.escaped = true
235                 return true
236         }
237         if s.inQuotes {
238                 if r == '"' {
239                         s.inQuotes = false
240                         return false
241                 }
242                 return true
243         }
244         if r == '"' {
245                 s.inQuotes = true
246                 return false
247         }
248         return !unicode.IsSpace(r)
251 type identifier string
253 func (s *Server) query(cmd string, args ...interface{}) (interface{}, error) {
254         c := <-s.conns
255         defer func() { s.conns <- c }()
257         for i, arg := range args {
258                 switch v := arg.(type) {
259                 case identifier:
260                         // Nothing to do.
261                 case string:
262                         args[i] = proto.EscapeString(v)
263                 case time.Time:
264                         args[i] = v.Format(datetime)
265                 default:
266                         panic(fmt.Sprintf("query: invalid type %T", arg))
267                 }
268         }
270         cmd = fmt.Sprintf(cmd, args...)
271         m := &proto.Message{
272                 Type: proto.ConnectionQuery,
273                 Raw:  []byte(cmd),
274         }
275         if err := c.Send(m); err != nil {
276                 return nil, fmt.Errorf("Query %q: %v", cmd, err)
277         }
279         for {
280                 m, err := c.Receive()
281                 if err != nil {
282                         return nil, fmt.Errorf("Failed to receive server response: %v", err)
283                 }
284                 if m.Type == proto.ConnectionLog {
285                         log.Println(string(m.Raw[4:]))
286                         continue
287                 } else if m.Type == proto.ConnectionError {
288                         return nil, errors.New(string(m.Raw))
289                 }
291                 t, err := m.DataType()
292                 if err != nil {
293                         return nil, fmt.Errorf("Failed to unmarshal response: %v", err)
294                 }
296                 var res interface{}
297                 switch t {
298                 case proto.HostList:
299                         var hosts []sysdb.Host
300                         err = proto.Unmarshal(m, &hosts)
301                         res = hosts
302                 case proto.Host:
303                         var host sysdb.Host
304                         err = proto.Unmarshal(m, &host)
305                         res = host
306                 case proto.Timeseries:
307                         var ts sysdb.Timeseries
308                         err = proto.Unmarshal(m, &ts)
309                         res = ts
310                 default:
311                         return nil, fmt.Errorf("Unsupported data type %d", t)
312                 }
313                 if err != nil {
314                         return nil, fmt.Errorf("Failed to unmarshal response: %v", err)
315                 }
316                 return res, nil
317         }
320 // vim: set tw=78 sw=4 sw=4 noexpandtab :