-
Notifications
You must be signed in to change notification settings - Fork 14
/
query.go
223 lines (197 loc) · 4.91 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package sabakan
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/well"
)
var httpClient = &well.HTTPClient{
Client: &http.Client{},
}
// GraphQLQuery is GraphQL query to retrieve machine information from sabakan.
const GraphQLQuery = `
query ckeSearch($having: MachineParams = null,
$notHaving: MachineParams = {
roles: ["boot"]
states: [RETIRED]
}) {
searchMachines(having: $having, notHaving: $notHaving) {
spec {
serial
labels {
name
value
}
rack
indexInRack
role
ipv4
registerDate
retireDate
}
status {
state
duration
}
}
}
`
// State is the enum type for sabakan states.
type State string
// SabakanState list defined in GraphQL schema.
const (
StateUninitialized = State("UNINITIALIZED")
StateHealthy = State("HEALTHY")
StateUnhealthy = State("UNHEALTHY")
StateUnreachable = State("UNREACHABLE")
StateUpdating = State("UPDATING")
StateRetiring = State("RETIRING")
StateRetired = State("RETIRED")
)
// IsValid returns true if s is vaild.
func (s State) IsValid() bool {
switch s {
case StateUninitialized:
case StateHealthy:
case StateUnhealthy:
case StateUnreachable:
case StateUpdating:
case StateRetiring:
case StateRetired:
default:
return false
}
return true
}
// MachineParams is the query parameter type.
type MachineParams struct {
Labels []struct {
Name string `json:"name"`
Value string `json:"value"`
} `json:"labels"`
Racks []int `json:"racks"`
Roles []string `json:"roles"`
States []State `json:"states"`
MinDaysBeforeRetire int `json:"minDaysBeforeRetire"`
}
// IsValid returns non-nil error if mp is not valid.
func (mp MachineParams) IsValid() error {
for _, state := range mp.States {
if !state.IsValid() {
return errors.New("invalid state: " + string(state))
}
}
return nil
}
// QueryVariables represents the JSON object of the query variables.
type QueryVariables struct {
Having *MachineParams `json:"having"`
NotHaving *MachineParams `json:"notHaving"`
}
// IsValid returns non-nil error if v is not valid.
func (v QueryVariables) IsValid() error {
if v.Having != nil {
if err := v.Having.IsValid(); err != nil {
return err
}
}
if v.NotHaving != nil {
if err := v.NotHaving.IsValid(); err != nil {
return err
}
}
return nil
}
// Machine represents a machine registered with sabakan.
type Machine struct {
Spec struct {
Serial string `json:"serial"`
Labels []struct {
Name string `json:"name"`
Value string `json:"value"`
} `json:"labels"`
Rack int `json:"rack"`
IndexInRack int `json:"indexInRack"`
Role string `json:"role"`
IPv4 []string `json:"ipv4"`
RegisterDate time.Time `json:"registerDate"`
RetireDate time.Time `json:"retireDate"`
} `json:"spec"`
Status struct {
State State `json:"state"`
Duration float64 `json:"duration"`
} `json:"status"`
}
// Query send a GraphQL query to sabakan.
// If sabakan URL is not set, this returns (nil, cke.ErrNotFound).
func Query(ctx context.Context, storage cke.Storage) ([]Machine, error) {
url, err := storage.GetSabakanURL(ctx)
if err != nil {
return nil, err
}
var variables *QueryVariables
varsData, err := storage.GetSabakanQueryVariables(ctx)
switch err {
case cke.ErrNotFound:
case nil:
variables = new(QueryVariables)
err = json.Unmarshal(varsData, variables)
if err != nil {
return nil, err
}
default:
return nil, err
}
return doQuery(ctx, url, variables, httpClient)
}
func doQuery(ctx context.Context, url string, vars *QueryVariables, hc *well.HTTPClient) ([]Machine, error) {
body := struct {
Query string `json:"query"`
Variables *QueryVariables `json:"variables,omitempty"`
}{
GraphQLQuery,
vars,
}
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
// gqlgen 0.9+ requires application/json content-type header.
req.Header.Set("Content-Type", "application/json")
resp, err := hc.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
data, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("sabakan returns %d: %s", resp.StatusCode, string(data))
}
var result struct {
Data struct {
Machines []Machine `json:"searchMachines"`
} `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return nil, err
}
if len(result.Errors) > 0 {
return nil, fmt.Errorf("sabakan returns error: %v", result.Errors)
}
return result.Data.Machines, nil
}