This repository has been archived by the owner on Sep 8, 2018. It is now read-only.
/
query.go
165 lines (146 loc) · 4.38 KB
/
query.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
package main
import (
"bufio"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/oklog/oklog/pkg/store"
"github.com/oklog/ulid"
)
func runQuery(args []string) error {
flagset := flag.NewFlagSet("query", flag.ExitOnError)
var (
storeAddr = flagset.String("store", "localhost:7650", "address of store instance to query")
from = flagset.String("from", "1h", "from, as RFC3339 timestamp or duration ago")
to = flagset.String("to", "now", "to, as RFC3339 timestamp or duration ago")
q = flagset.String("q", "", "query expression")
regex = flagset.Bool("regex", false, "parse -q as regular expression")
stats = flagset.Bool("stats", false, "statistics only, no records (implies -v)")
nocopy = flagset.Bool("nocopy", false, "don't read the response body")
withulid = flagset.Bool("ulid", false, "include ULID prefix with each record")
verbose = flagset.Bool("v", false, "verbose output to stderr")
)
flagset.Usage = usageFor(flagset, "oklog query [flags]")
if err := flagset.Parse(args); err != nil {
return err
}
begin := time.Now()
verbosePrintf := func(string, ...interface{}) {}
if *verbose || *stats {
verbosePrintf = func(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
}
}
_, hostport, _, _, err := parseAddr(*storeAddr, defaultAPIPort)
if err != nil {
return errors.Wrap(err, "couldn't parse -store")
}
fromDuration, durationErr := time.ParseDuration(*from)
fromTime, timeErr := time.Parse(time.RFC3339Nano, *from)
fromNow := strings.ToLower(*from) == "now"
var fromStr string
switch {
case fromNow:
fromStr = time.Now().Format(time.RFC3339)
case durationErr == nil && timeErr != nil:
fromStr = time.Now().Add(neg(fromDuration)).Format(time.RFC3339)
case durationErr != nil && timeErr == nil:
fromStr = fromTime.Format(time.RFC3339)
default:
return fmt.Errorf("couldn't parse -from (%q) as either duration or time", *from)
}
toDuration, durationErr := time.ParseDuration(*to)
toTime, timeErr := time.Parse(time.RFC3339, *to)
toNow := strings.ToLower(*to) == "now"
var toStr string
switch {
case toNow:
toStr = time.Now().Format(time.RFC3339)
case durationErr == nil && timeErr != nil:
toStr = time.Now().Add(neg(toDuration)).Format(time.RFC3339)
case durationErr != nil && timeErr == nil:
toStr = toTime.Format(time.RFC3339)
default:
return fmt.Errorf("couldn't parse -to (%q) as either duration or time", *to)
}
method := "GET"
if *stats {
method = "HEAD"
}
var asRegex string
if *regex {
asRegex = "®ex=true"
}
req, err := http.NewRequest(method, fmt.Sprintf(
"http://%s/store%s?from=%s&to=%s&q=%s%s",
hostport,
store.APIPathUserQuery,
url.QueryEscape(fromStr),
url.QueryEscape(toStr),
url.QueryEscape(*q),
asRegex,
), nil)
if err != nil {
return err
}
verbosePrintf("GET %s\n", req.URL.String())
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
req.URL.RawQuery = "" // for pretty print
return errors.Errorf("%s %s: %s", req.Method, req.URL.String(), resp.Status)
}
var result store.QueryResult
if err := result.DecodeFrom(resp); err != nil {
return errors.Wrap(err, "decoding query result")
}
qtype := "normal string"
if result.Params.Regex {
qtype = "regular expression"
}
verbosePrintf("Response in %s\n", time.Since(begin))
verbosePrintf("Queried from %s\n", result.Params.From)
verbosePrintf("Queried to %s\n", result.Params.To)
verbosePrintf("Queried %s %q\n", qtype, result.Params.Q)
verbosePrintf("%d node(s) queried\n", result.NodesQueried)
verbosePrintf("%d segment(s) queried\n", result.SegmentsQueried)
verbosePrintf("%dB (%dMiB) maximum data set size\n", result.MaxDataSetSize, result.MaxDataSetSize/(1024*1024))
verbosePrintf("%d error(s)\n", result.ErrorCount)
verbosePrintf("%s server-reported duration\n", result.Duration)
switch {
case *nocopy:
break
case *withulid:
io.Copy(os.Stdout, result.Records)
default:
io.Copy(os.Stdout, strip(result.Records))
}
result.Records.Close()
return nil
}
func neg(d time.Duration) time.Duration {
if d > 0 {
d = -d
}
return d
}
func strip(r io.Reader) io.Reader {
pr, pw := io.Pipe()
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
pw.Write(s.Bytes()[ulid.EncodedSize+1:])
pw.Write([]byte{'\n'})
}
pw.CloseWithError(s.Err())
}()
return pr
}