blob: d193b1ace7e161dc76973633fb5c46e38cb4a674 [file] [log] [blame]
Mateusz Zalega6a058e72022-11-30 18:03:07 +01001// Package wrapngo wraps packngo methods providing the following usability
2// enhancements:
3// - API call rate limiting
4// - resource-aware call retries
5// - use of a configurable back-off algorithm implementation
6// - context awareness
7//
8// The implementation is provided with the following caveats:
9//
10// There can be only one call in flight. Concurrent calls to API-related
11// methods of the same client will block. Calls returning packngo structs will
12// return nil data when a non-nil error value is returned. An
13// os.ErrDeadlineExceeded will be returned after the underlying API calls time
14// out beyond the chosen back-off algorithm implementation's maximum allowed
15// retry interval. Other errors, excluding context.Canceled and
16// context.DeadlineExceeded, indicate either an error originating at Equinix'
17// API endpoint (which may still stem from invalid call inputs), or a network
18// error.
19//
20// Packngo wrappers included below may return timeout errors even after the
21// wrapped calls succeed in the event server reply could not have been
22// received.
23//
24// This implies that effects of mutating calls can't always be verified
25// atomically, requiring explicit synchronization between API users, regardless
26// of the retry/recovery logic used.
27//
28// Having that in mind, some call wrappers exposed by this package will attempt
29// to recover from this kind of situations by requesting information on any
30// resources created, and retrying the call if needed. This approach assumes
31// any concurrent mutating API users will be synchronized, as it should be in
32// any case.
33//
34// Another way of handling this problem would be to leave it up to the user to
35// retry calls if needed, though this would leak Equinix Metal API, and
36// complicate implementations depending on this package. Due to that, the prior
37// approach was chosen.
38package wrapngo
39
40import (
41 "context"
42 "errors"
43 "flag"
44 "fmt"
45 "net/http"
Serge Bazanskidea7cd02023-04-26 13:58:17 +020046 "sync/atomic"
Mateusz Zalega6a058e72022-11-30 18:03:07 +010047 "time"
48
49 "github.com/cenkalti/backoff/v4"
50 "github.com/google/uuid"
51 "github.com/packethost/packngo"
Serge Bazanskidea7cd02023-04-26 13:58:17 +020052 "github.com/prometheus/client_golang/prometheus"
Mateusz Zalega6a058e72022-11-30 18:03:07 +010053)
54
55// Opts conveys configurable Client parameters.
56type Opts struct {
57 // User and APIKey are the credentials used to authenticate with
58 // Metal API.
59
60 User string
61 APIKey string
62
63 // Optional parameters:
64
65 // BackOff controls the client's behavior in the event of API calls failing
66 // due to IO timeouts by adjusting the lower bound on time taken between
67 // subsequent calls.
68 BackOff func() backoff.BackOff
69
70 // APIRate is the minimum time taken between subsequent API calls.
71 APIRate time.Duration
Serge Bazanski7448f282023-02-20 14:15:51 +010072
73 // Parallelism defines how many calls to the Equinix API will be issued in
74 // parallel. When this limit is reached, subsequent attmepts to call the API will
75 // block. The order of serving of pending calls is currently undefined.
76 //
77 // If not defined (ie. 0), defaults to 1.
78 Parallelism int
Serge Bazanskidea7cd02023-04-26 13:58:17 +020079
80 MetricsRegistry *prometheus.Registry
Mateusz Zalega6a058e72022-11-30 18:03:07 +010081}
82
83func (o *Opts) RegisterFlags() {
84 flag.StringVar(&o.User, "equinix_api_username", "", "Username for Equinix API")
85 flag.StringVar(&o.APIKey, "equinix_api_key", "", "Key/token/password for Equinix API")
Serge Bazanskiafd3cf82023-04-19 17:43:46 +020086 flag.IntVar(&o.Parallelism, "equinix_parallelism", 3, "How many parallel connections to the Equinix API will be allowed")
Mateusz Zalega6a058e72022-11-30 18:03:07 +010087}
88
89// Client is a limited interface of methods that the Shepherd uses on Equinix. It
90// is provided to allow for dependency injection of a fake equinix API for tests.
91type Client interface {
92 // GetDevice wraps packngo's cl.Devices.Get.
Serge Bazanski4969fd72023-04-19 17:43:12 +020093 //
94 // TODO(q3k): remove unused pid parameter.
95 GetDevice(ctx context.Context, pid, did string, opts *packngo.ListOptions) (*packngo.Device, error)
Mateusz Zalega6a058e72022-11-30 18:03:07 +010096 // ListDevices wraps packngo's cl.Device.List.
97 ListDevices(ctx context.Context, pid string) ([]packngo.Device, error)
98 // CreateDevice attempts to create a new device according to the provided
99 // request. The request _must_ configure a HardwareReservationID. This call
100 // attempts to be as idempotent as possible, and will return ErrRaceLost if a
101 // retry was needed but in the meantime the requested hardware reservation from
102 // which this machine was requested got lost.
103 CreateDevice(ctx context.Context, request *packngo.DeviceCreateRequest) (*packngo.Device, error)
Tim Windelschmidt8180de92023-05-11 19:45:37 +0200104 RebootDevice(ctx context.Context, did string) error
105 DeleteDevice(ctx context.Context, id string) error
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100106
107 // ListReservations returns a complete list of hardware reservations associated
108 // with project pid. This is an expensive method that takes a while to execute,
109 // handle with care.
110 ListReservations(ctx context.Context, pid string) ([]packngo.HardwareReservation, error)
Tim Windelschmidt8180de92023-05-11 19:45:37 +0200111 // MoveReservation moves a reserved device to the given project.
112 MoveReservation(ctx context.Context, hardwareReservationDID, projectID string) (*packngo.HardwareReservation, error)
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100113
114 // ListSSHKeys wraps packngo's cl.Keys.List.
115 ListSSHKeys(ctx context.Context) ([]packngo.SSHKey, error)
116 // CreateSSHKey is idempotent - the key label can be used only once. Further
117 // calls referring to the same label and key will not yield errors. See the
118 // package comment for more info on this method's behavior and returned error
119 // values.
120 CreateSSHKey(ctx context.Context, req *packngo.SSHKeyCreateRequest) (*packngo.SSHKey, error)
121 // UpdateSSHKey is idempotent - values included in r can be applied only once,
122 // while subsequent updates using the same data don't produce errors. See the
123 // package comment for information on this method's behavior and returned error
124 // values.
125 UpdateSSHKey(ctx context.Context, kid string, req *packngo.SSHKeyUpdateRequest) (*packngo.SSHKey, error)
126
127 Close()
128}
129
130// client implements the Client interface.
131type client struct {
132 username string
133 token string
134 o *Opts
135 rlt *time.Ticker
136
Serge Bazanskidea7cd02023-04-26 13:58:17 +0200137 serializer *serializer
138 metrics *metricsSet
139}
140
141// serializer is an N-semaphore channel (configured by opts.Parallelism) which is
142// used to limit the number of concurrent calls to the Equinix API.
143//
144// In addition, it implements some simple waiting/usage statistics for
145// metrics/introspection.
146type serializer struct {
147 sem chan struct{}
148 usage int64
149 waiting int64
150}
151
152// up blocks until the serializer has at least one available concurrent call
153// slot. If the given context expires before such a slot is available, the
154// context error is returned.
155func (s *serializer) up(ctx context.Context) error {
156 atomic.AddInt64(&s.waiting, 1)
157 select {
158 case s.sem <- struct{}{}:
159 atomic.AddInt64(&s.waiting, -1)
160 atomic.AddInt64(&s.usage, 1)
161 return nil
162 case <-ctx.Done():
163 atomic.AddInt64(&s.waiting, -1)
164 return ctx.Err()
165 }
166}
167
168// down releases a previously acquire concurrent call slot.
169func (s *serializer) down() {
170 atomic.AddInt64(&s.usage, -1)
171 <-s.sem
172}
173
174// stats returns the number of in-flight and waiting-for-semaphore requests.
175func (s *serializer) stats() (usage, waiting int64) {
176 usage = atomic.LoadInt64(&s.usage)
177 waiting = atomic.LoadInt64(&s.waiting)
178 return
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100179}
180
181// New creates a Client instance based on Opts. PACKNGO_DEBUG environment
182// variable can be set prior to the below call to enable verbose packngo
183// debug logs.
184func New(opts *Opts) Client {
185 return new(opts)
186}
187
188func new(opts *Opts) *client {
189 // Apply the defaults.
190 if opts.APIRate == 0 {
191 opts.APIRate = 2 * time.Second
192 }
193 if opts.BackOff == nil {
194 opts.BackOff = func() backoff.BackOff {
195 return backoff.NewExponentialBackOff()
196 }
197 }
Serge Bazanski7448f282023-02-20 14:15:51 +0100198 if opts.Parallelism == 0 {
199 opts.Parallelism = 1
200 }
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100201
Serge Bazanskidea7cd02023-04-26 13:58:17 +0200202 cl := &client{
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100203 username: opts.User,
204 token: opts.APIKey,
205 o: opts,
206 rlt: time.NewTicker(opts.APIRate),
207
Serge Bazanskidea7cd02023-04-26 13:58:17 +0200208 serializer: &serializer{
209 sem: make(chan struct{}, opts.Parallelism),
210 },
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100211 }
Serge Bazanskidea7cd02023-04-26 13:58:17 +0200212 if opts.MetricsRegistry != nil {
213 ms := newMetricsSet(cl.serializer)
214 opts.MetricsRegistry.MustRegister(ms.inFlight, ms.waiting, ms.requestLatencies)
215 cl.metrics = ms
216 }
217 return cl
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100218}
219
220func (c *client) Close() {
221 c.rlt.Stop()
222}
223
224var (
225 ErrRaceLost = errors.New("race lost with another API user")
226 ErrNoReservationProvided = errors.New("hardware reservation must be set")
227)
228
Tim Windelschmidt8180de92023-05-11 19:45:37 +0200229func (e *client) PowerOffDevice(ctx context.Context, pid string) error {
230 _, err := wrap(ctx, e, func(p *packngo.Client) (*packngo.Response, error) {
231 r, err := p.Devices.PowerOff(pid)
232 if err != nil {
233 return nil, fmt.Errorf("Devices.PowerOff: %w", err)
234 }
235 return r, nil
236 })
237 return err
238}
239
240func (e *client) PowerOnDevice(ctx context.Context, pid string) error {
241 _, err := wrap(ctx, e, func(p *packngo.Client) (*packngo.Response, error) {
242 r, err := p.Devices.PowerOn(pid)
243 if err != nil {
244 return nil, fmt.Errorf("Devices.PowerOn: %w", err)
245 }
246 return r, nil
247 })
248 return err
249}
250
251func (e *client) DeleteDevice(ctx context.Context, id string) error {
252 _, err := wrap(ctx, e, func(p *packngo.Client) (*packngo.Response, error) {
253 r, err := p.Devices.Delete(id, false)
254 if err != nil {
255 return nil, fmt.Errorf("Devices.Delete: %w", err)
256 }
257 return r, nil
258 })
259 return err
260}
261
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100262func (e *client) CreateDevice(ctx context.Context, r *packngo.DeviceCreateRequest) (*packngo.Device, error) {
263 if r.HardwareReservationID == "" {
264 return nil, ErrNoReservationProvided
265 }
266 // Add a tag to the request to detect if someone snatches a hardware reservation
267 // from under us.
268 witnessTag := fmt.Sprintf("wrapngo-idempotency-%s", uuid.New().String())
269 r.Tags = append(r.Tags, witnessTag)
270
271 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.Device, error) {
272 //Does the device already exist?
273 res, _, err := cl.HardwareReservations.Get(r.HardwareReservationID, nil)
274 if err != nil {
275 return nil, fmt.Errorf("couldn't check if device already exists: %w", err)
276 }
277 if res == nil {
278 return nil, fmt.Errorf("unexpected nil response")
279 }
280 if res.Device != nil {
281 // Check if we lost the race for this hardware reservation.
282 tags := make(map[string]bool)
283 for _, tag := range res.Device.Tags {
284 tags[tag] = true
285 }
286 if !tags[witnessTag] {
287 return nil, ErrRaceLost
288 }
289 return res.Device, nil
290 }
291
292 // No device yet. Try to create it.
293 dev, _, err := cl.Devices.Create(r)
294 if err == nil {
295 return dev, nil
296 }
297 // In case of a transient failure (eg. network issue), we retry the whole
298 // operation, which means we first check again if the device already exists. If
299 // it's a permanent error from the API, the backoff logic will fail immediately.
300 return nil, fmt.Errorf("couldn't create device: %w", err)
301 })
302}
303
304func (e *client) ListDevices(ctx context.Context, pid string) ([]packngo.Device, error) {
305 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.Device, error) {
Tim Windelschmidtd1b17472023-04-18 03:49:12 +0200306 // to increase the chances of a stable pagination, we sort the devices by hostname
307 res, _, err := cl.Devices.List(pid, &packngo.GetOptions{SortBy: "hostname"})
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100308 return res, err
309 })
310}
311
Tim Windelschmidt8180de92023-05-11 19:45:37 +0200312func (e *client) UpdateDevice(ctx context.Context, id string, r *packngo.DeviceUpdateRequest) (*packngo.Device, error) {
313 return wrap(ctx, e, func(p *packngo.Client) (*packngo.Device, error) {
314 d, _, err := p.Devices.Update(id, r)
315 if err != nil {
316 return nil, fmt.Errorf("Devices.Update: %w", err)
317 }
318 return d, nil
319 })
320}
321
Serge Bazanski4969fd72023-04-19 17:43:12 +0200322func (e *client) GetDevice(ctx context.Context, pid, did string, opts *packngo.ListOptions) (*packngo.Device, error) {
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100323 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.Device, error) {
Serge Bazanski4969fd72023-04-19 17:43:12 +0200324 d, _, err := cl.Devices.Get(did, opts)
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100325 return d, err
326 })
327}
328
329// Currently unexported, only used in tests.
330func (e *client) deleteDevice(ctx context.Context, did string) error {
331 _, err := wrap(ctx, e, func(cl *packngo.Client) (*struct{}, error) {
332 _, err := cl.Devices.Delete(did, false)
333 if httpStatusCode(err) == http.StatusNotFound {
334 // 404s may pop up as an after effect of running the back-off
335 // algorithm, and as such should not be propagated.
336 return nil, nil
337 }
338 return nil, err
339 })
340 return err
341}
342
343func (e *client) ListReservations(ctx context.Context, pid string) ([]packngo.HardwareReservation, error) {
344 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.HardwareReservation, error) {
Tim Windelschmidt8180de92023-05-11 19:45:37 +0200345 res, _, err := cl.HardwareReservations.List(pid, &packngo.ListOptions{Includes: []string{"facility", "device"}})
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100346 return res, err
347 })
348}
349
Tim Windelschmidt8180de92023-05-11 19:45:37 +0200350func (e *client) MoveReservation(ctx context.Context, hardwareReservationDID, projectID string) (*packngo.HardwareReservation, error) {
351 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.HardwareReservation, error) {
352 hr, _, err := cl.HardwareReservations.Move(hardwareReservationDID, projectID)
353 if err != nil {
354 return nil, fmt.Errorf("HardwareReservations.Move: %w", err)
355 }
356 return hr, err
357 })
358}
359
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100360func (e *client) CreateSSHKey(ctx context.Context, r *packngo.SSHKeyCreateRequest) (*packngo.SSHKey, error) {
361 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
362 // Does the key already exist?
363 ks, _, err := cl.SSHKeys.List()
364 if err != nil {
365 return nil, fmt.Errorf("SSHKeys.List: %w", err)
366 }
367 for _, k := range ks {
368 if k.Label == r.Label {
369 if k.Key != r.Key {
370 return nil, fmt.Errorf("key label already in use for a different key")
371 }
372 return &k, nil
373 }
374 }
375
376 // No key yet. Try to create it.
377 k, _, err := cl.SSHKeys.Create(r)
378 if err != nil {
379 return nil, fmt.Errorf("SSHKeys.Create: %w", err)
380 }
381 return k, nil
382 })
383}
384
385func (e *client) UpdateSSHKey(ctx context.Context, id string, r *packngo.SSHKeyUpdateRequest) (*packngo.SSHKey, error) {
386 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
387 k, _, err := cl.SSHKeys.Update(id, r)
388 if err != nil {
389 return nil, fmt.Errorf("SSHKeys.Update: %w", err)
390 }
391 return k, err
392 })
393}
394
395// Currently unexported, only used in tests.
396func (e *client) deleteSSHKey(ctx context.Context, id string) error {
397 _, err := wrap(ctx, e, func(cl *packngo.Client) (struct{}, error) {
398 _, err := cl.SSHKeys.Delete(id)
399 if err != nil {
400 return struct{}{}, fmt.Errorf("SSHKeys.Delete: %w", err)
401 }
402 return struct{}{}, err
403 })
404 return err
405}
406
407func (e *client) ListSSHKeys(ctx context.Context) ([]packngo.SSHKey, error) {
408 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.SSHKey, error) {
409 ks, _, err := cl.SSHKeys.List()
410 if err != nil {
411 return nil, fmt.Errorf("SSHKeys.List: %w", err)
412 }
413 return ks, nil
414 })
415}
416
417// Currently unexported, only used in tests.
418func (e *client) getSSHKey(ctx context.Context, id string) (*packngo.SSHKey, error) {
419 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
420 k, _, err := cl.SSHKeys.Get(id, nil)
421 if err != nil {
422 return nil, fmt.Errorf("SSHKeys.Get: %w", err)
423 }
424 return k, nil
425 })
426}
Serge Bazanskiae004682023-04-18 13:28:48 +0200427
428func (e *client) RebootDevice(ctx context.Context, did string) error {
429 _, err := wrap(ctx, e, func(cl *packngo.Client) (struct{}, error) {
430 _, err := cl.Devices.Reboot(did)
431 return struct{}{}, err
432 })
433 return err
434}