Code

a95dba56125fcdef08a5c0f95ddf5c3c725cecf0
[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"
37         "github.com/sysdb/go/proto"
38         "github.com/sysdb/go/sysdb"
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         res, err := s.query("LIST %s", identifier(req.cmd))
47         if err != nil {
48                 return nil, err
49         }
50         // the template *must* exist
51         return tmpl(s.results[req.cmd], res)
52 }
54 func lookup(req request, s *Server) (*page, error) {
55         if req.r.Method != "POST" {
56                 return nil, errors.New("Method not allowed")
57         }
58         q := req.r.FormValue("query")
59         if q == "''" {
60                 return nil, errors.New("Empty query")
61         }
63         res, err := s.query("LOOKUP hosts MATCHING name =~ %s", q)
64         if err != nil {
65                 return nil, err
66         }
67         return tmpl(s.results["hosts"], res)
68 }
70 func fetch(req request, s *Server) (*page, error) {
71         if len(req.args) == 0 {
72                 return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
73         }
75         var res interface{}
76         var err error
77         switch req.cmd {
78         case "host":
79                 if len(req.args) != 1 {
80                         return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
81                 }
82                 res, err = s.query("FETCH host %s", req.args[0])
83         case "service", "metric":
84                 if len(req.args) != 2 {
85                         return nil, fmt.Errorf("%s not found", strings.Title(req.cmd))
86                 }
87                 res, err = s.query("FETCH %s %s.%s", identifier(req.cmd), req.args[0], req.args[1])
88                 if req.cmd == "metric" {
89                         return metric(req, res, s)
90                 }
91         default:
92                 panic("Unknown request: fetch(" + req.cmd + ")")
93         }
94         if err != nil {
95                 return nil, err
96         }
97         return tmpl(s.results[req.cmd], res)
98 }
100 var datetime = "2006-01-02 15:04:05"
102 func metric(req request, res interface{}, s *Server) (*page, error) {
103         start := time.Now().Add(-24 * time.Hour)
104         end := time.Now()
105         if req.r.Method == "POST" {
106                 var err error
107                 // Parse the values first to verify their format.
108                 if s := req.r.FormValue("start_date"); s != "" {
109                         if start, err = time.Parse(datetime, s); err != nil {
110                                 return nil, fmt.Errorf("Invalid start time %q", s)
111                         }
112                 }
113                 if e := req.r.FormValue("end_date"); e != "" {
114                         if end, err = time.Parse(datetime, e); err != nil {
115                                 return nil, fmt.Errorf("Invalid end time %q", e)
116                         }
117                 }
118         }
120         p := struct {
121                 StartTime string
122                 EndTime   string
123                 URLStart  string
124                 URLEnd    string
125                 Data      interface{}
126         }{
127                 start.Format(datetime),
128                 end.Format(datetime),
129                 start.Format(urldate),
130                 end.Format(urldate),
131                 res,
132         }
133         return tmpl(s.results["metric"], &p)
136 type identifier string
138 func (s *Server) query(cmd string, args ...interface{}) (interface{}, error) {
139         c := <-s.conns
140         defer func() { s.conns <- c }()
142         for i, arg := range args {
143                 switch v := arg.(type) {
144                 case identifier:
145                         // Nothing to do.
146                 case string:
147                         args[i] = proto.EscapeString(v)
148                 case time.Time:
149                         args[i] = v.Format(datetime)
150                 default:
151                         panic(fmt.Sprintf("query: invalid type %T", arg))
152                 }
153         }
155         cmd = fmt.Sprintf(cmd, args...)
156         m := &proto.Message{
157                 Type: proto.ConnectionQuery,
158                 Raw:  []byte(cmd),
159         }
160         if err := c.Send(m); err != nil {
161                 return nil, fmt.Errorf("Query %q: %v", cmd, err)
162         }
164         for {
165                 m, err := c.Receive()
166                 if err != nil {
167                         return nil, fmt.Errorf("Failed to receive server response: %v", err)
168                 }
169                 if m.Type == proto.ConnectionLog {
170                         log.Println(string(m.Raw[4:]))
171                         continue
172                 } else if m.Type == proto.ConnectionError {
173                         return nil, errors.New(string(m.Raw))
174                 }
176                 t, err := m.DataType()
177                 if err != nil {
178                         return nil, fmt.Errorf("Failed to unmarshal response: %v", err)
179                 }
181                 var res interface{}
182                 switch t {
183                 case proto.HostList:
184                         var hosts []sysdb.Host
185                         err = proto.Unmarshal(m, &hosts)
186                         res = hosts
187                 case proto.Host:
188                         var host sysdb.Host
189                         err = proto.Unmarshal(m, &host)
190                         res = host
191                 case proto.Timeseries:
192                         var ts sysdb.Timeseries
193                         err = proto.Unmarshal(m, &ts)
194                         res = ts
195                 default:
196                         return nil, fmt.Errorf("Unsupported data type %d", t)
197                 }
198                 if err != nil {
199                         return nil, fmt.Errorf("Failed to unmarshal response: %v", err)
200                 }
201                 return res, nil
202         }
205 // vim: set tw=78 sw=4 sw=4 noexpandtab :