blob: dc54340fdb3fee377c3da2b4a2d75dc944f7ce5a [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"
46 "time"
47
48 "github.com/cenkalti/backoff/v4"
49 "github.com/google/uuid"
50 "github.com/packethost/packngo"
51)
52
53// Opts conveys configurable Client parameters.
54type Opts struct {
55 // User and APIKey are the credentials used to authenticate with
56 // Metal API.
57
58 User string
59 APIKey string
60
61 // Optional parameters:
62
63 // BackOff controls the client's behavior in the event of API calls failing
64 // due to IO timeouts by adjusting the lower bound on time taken between
65 // subsequent calls.
66 BackOff func() backoff.BackOff
67
68 // APIRate is the minimum time taken between subsequent API calls.
69 APIRate time.Duration
Serge Bazanski7448f282023-02-20 14:15:51 +010070
71 // Parallelism defines how many calls to the Equinix API will be issued in
72 // parallel. When this limit is reached, subsequent attmepts to call the API will
73 // block. The order of serving of pending calls is currently undefined.
74 //
75 // If not defined (ie. 0), defaults to 1.
76 Parallelism int
Mateusz Zalega6a058e72022-11-30 18:03:07 +010077}
78
79func (o *Opts) RegisterFlags() {
80 flag.StringVar(&o.User, "equinix_api_username", "", "Username for Equinix API")
81 flag.StringVar(&o.APIKey, "equinix_api_key", "", "Key/token/password for Equinix API")
Serge Bazanski7448f282023-02-20 14:15:51 +010082 flag.IntVar(&o.Parallelism, "equinix_parallelism", 1, "How many parallel connections to the Equinix API will be allowed")
Mateusz Zalega6a058e72022-11-30 18:03:07 +010083}
84
85// Client is a limited interface of methods that the Shepherd uses on Equinix. It
86// is provided to allow for dependency injection of a fake equinix API for tests.
87type Client interface {
88 // GetDevice wraps packngo's cl.Devices.Get.
89 GetDevice(ctx context.Context, pid, did string) (*packngo.Device, error)
90 // ListDevices wraps packngo's cl.Device.List.
91 ListDevices(ctx context.Context, pid string) ([]packngo.Device, error)
92 // CreateDevice attempts to create a new device according to the provided
93 // request. The request _must_ configure a HardwareReservationID. This call
94 // attempts to be as idempotent as possible, and will return ErrRaceLost if a
95 // retry was needed but in the meantime the requested hardware reservation from
96 // which this machine was requested got lost.
97 CreateDevice(ctx context.Context, request *packngo.DeviceCreateRequest) (*packngo.Device, error)
98
99 // ListReservations returns a complete list of hardware reservations associated
100 // with project pid. This is an expensive method that takes a while to execute,
101 // handle with care.
102 ListReservations(ctx context.Context, pid string) ([]packngo.HardwareReservation, error)
103
104 // ListSSHKeys wraps packngo's cl.Keys.List.
105 ListSSHKeys(ctx context.Context) ([]packngo.SSHKey, error)
106 // CreateSSHKey is idempotent - the key label can be used only once. Further
107 // calls referring to the same label and key will not yield errors. See the
108 // package comment for more info on this method's behavior and returned error
109 // values.
110 CreateSSHKey(ctx context.Context, req *packngo.SSHKeyCreateRequest) (*packngo.SSHKey, error)
111 // UpdateSSHKey is idempotent - values included in r can be applied only once,
112 // while subsequent updates using the same data don't produce errors. See the
113 // package comment for information on this method's behavior and returned error
114 // values.
115 UpdateSSHKey(ctx context.Context, kid string, req *packngo.SSHKeyUpdateRequest) (*packngo.SSHKey, error)
Serge Bazanskiae004682023-04-18 13:28:48 +0200116 RebootDevice(ctx context.Context, did string) error
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100117
118 Close()
119}
120
121// client implements the Client interface.
122type client struct {
123 username string
124 token string
125 o *Opts
126 rlt *time.Ticker
127
Serge Bazanski7448f282023-02-20 14:15:51 +0100128 // serializer is a N-semaphore channel (configured by opts.Parallelism) which is
129 // used to limit the number of concurrent calls to the Equinix API.
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100130 serializer chan (struct{})
131}
132
133// New creates a Client instance based on Opts. PACKNGO_DEBUG environment
134// variable can be set prior to the below call to enable verbose packngo
135// debug logs.
136func New(opts *Opts) Client {
137 return new(opts)
138}
139
140func new(opts *Opts) *client {
141 // Apply the defaults.
142 if opts.APIRate == 0 {
143 opts.APIRate = 2 * time.Second
144 }
145 if opts.BackOff == nil {
146 opts.BackOff = func() backoff.BackOff {
147 return backoff.NewExponentialBackOff()
148 }
149 }
Serge Bazanski7448f282023-02-20 14:15:51 +0100150 if opts.Parallelism == 0 {
151 opts.Parallelism = 1
152 }
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100153
154 return &client{
155 username: opts.User,
156 token: opts.APIKey,
157 o: opts,
158 rlt: time.NewTicker(opts.APIRate),
159
Serge Bazanski7448f282023-02-20 14:15:51 +0100160 serializer: make(chan struct{}, opts.Parallelism),
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100161 }
162}
163
164func (c *client) Close() {
165 c.rlt.Stop()
166}
167
168var (
169 ErrRaceLost = errors.New("race lost with another API user")
170 ErrNoReservationProvided = errors.New("hardware reservation must be set")
171)
172
173func (e *client) CreateDevice(ctx context.Context, r *packngo.DeviceCreateRequest) (*packngo.Device, error) {
174 if r.HardwareReservationID == "" {
175 return nil, ErrNoReservationProvided
176 }
177 // Add a tag to the request to detect if someone snatches a hardware reservation
178 // from under us.
179 witnessTag := fmt.Sprintf("wrapngo-idempotency-%s", uuid.New().String())
180 r.Tags = append(r.Tags, witnessTag)
181
182 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.Device, error) {
183 //Does the device already exist?
184 res, _, err := cl.HardwareReservations.Get(r.HardwareReservationID, nil)
185 if err != nil {
186 return nil, fmt.Errorf("couldn't check if device already exists: %w", err)
187 }
188 if res == nil {
189 return nil, fmt.Errorf("unexpected nil response")
190 }
191 if res.Device != nil {
192 // Check if we lost the race for this hardware reservation.
193 tags := make(map[string]bool)
194 for _, tag := range res.Device.Tags {
195 tags[tag] = true
196 }
197 if !tags[witnessTag] {
198 return nil, ErrRaceLost
199 }
200 return res.Device, nil
201 }
202
203 // No device yet. Try to create it.
204 dev, _, err := cl.Devices.Create(r)
205 if err == nil {
206 return dev, nil
207 }
208 // In case of a transient failure (eg. network issue), we retry the whole
209 // operation, which means we first check again if the device already exists. If
210 // it's a permanent error from the API, the backoff logic will fail immediately.
211 return nil, fmt.Errorf("couldn't create device: %w", err)
212 })
213}
214
215func (e *client) ListDevices(ctx context.Context, pid string) ([]packngo.Device, error) {
216 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.Device, error) {
Tim Windelschmidtd1b17472023-04-18 03:49:12 +0200217 // to increase the chances of a stable pagination, we sort the devices by hostname
218 res, _, err := cl.Devices.List(pid, &packngo.GetOptions{SortBy: "hostname"})
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100219 return res, err
220 })
221}
222
223func (e *client) GetDevice(ctx context.Context, pid, did string) (*packngo.Device, error) {
224 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.Device, error) {
225 d, _, err := cl.Devices.Get(did, nil)
226 return d, err
227 })
228}
229
230// Currently unexported, only used in tests.
231func (e *client) deleteDevice(ctx context.Context, did string) error {
232 _, err := wrap(ctx, e, func(cl *packngo.Client) (*struct{}, error) {
233 _, err := cl.Devices.Delete(did, false)
234 if httpStatusCode(err) == http.StatusNotFound {
235 // 404s may pop up as an after effect of running the back-off
236 // algorithm, and as such should not be propagated.
237 return nil, nil
238 }
239 return nil, err
240 })
241 return err
242}
243
244func (e *client) ListReservations(ctx context.Context, pid string) ([]packngo.HardwareReservation, error) {
245 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.HardwareReservation, error) {
246 res, _, err := cl.HardwareReservations.List(pid, nil)
247 return res, err
248 })
249}
250
251func (e *client) CreateSSHKey(ctx context.Context, r *packngo.SSHKeyCreateRequest) (*packngo.SSHKey, error) {
252 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
253 // Does the key already exist?
254 ks, _, err := cl.SSHKeys.List()
255 if err != nil {
256 return nil, fmt.Errorf("SSHKeys.List: %w", err)
257 }
258 for _, k := range ks {
259 if k.Label == r.Label {
260 if k.Key != r.Key {
261 return nil, fmt.Errorf("key label already in use for a different key")
262 }
263 return &k, nil
264 }
265 }
266
267 // No key yet. Try to create it.
268 k, _, err := cl.SSHKeys.Create(r)
269 if err != nil {
270 return nil, fmt.Errorf("SSHKeys.Create: %w", err)
271 }
272 return k, nil
273 })
274}
275
276func (e *client) UpdateSSHKey(ctx context.Context, id string, r *packngo.SSHKeyUpdateRequest) (*packngo.SSHKey, error) {
277 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
278 k, _, err := cl.SSHKeys.Update(id, r)
279 if err != nil {
280 return nil, fmt.Errorf("SSHKeys.Update: %w", err)
281 }
282 return k, err
283 })
284}
285
286// Currently unexported, only used in tests.
287func (e *client) deleteSSHKey(ctx context.Context, id string) error {
288 _, err := wrap(ctx, e, func(cl *packngo.Client) (struct{}, error) {
289 _, err := cl.SSHKeys.Delete(id)
290 if err != nil {
291 return struct{}{}, fmt.Errorf("SSHKeys.Delete: %w", err)
292 }
293 return struct{}{}, err
294 })
295 return err
296}
297
298func (e *client) ListSSHKeys(ctx context.Context) ([]packngo.SSHKey, error) {
299 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.SSHKey, error) {
300 ks, _, err := cl.SSHKeys.List()
301 if err != nil {
302 return nil, fmt.Errorf("SSHKeys.List: %w", err)
303 }
304 return ks, nil
305 })
306}
307
308// Currently unexported, only used in tests.
309func (e *client) getSSHKey(ctx context.Context, id string) (*packngo.SSHKey, error) {
310 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
311 k, _, err := cl.SSHKeys.Get(id, nil)
312 if err != nil {
313 return nil, fmt.Errorf("SSHKeys.Get: %w", err)
314 }
315 return k, nil
316 })
317}
Serge Bazanskiae004682023-04-18 13:28:48 +0200318
319func (e *client) RebootDevice(ctx context.Context, did string) error {
320 _, err := wrap(ctx, e, func(cl *packngo.Client) (struct{}, error) {
321 _, err := cl.Devices.Reboot(did)
322 return struct{}{}, err
323 })
324 return err
325}