blob: 400556bb16efd27eee614190ad10a97ae9b91ea4 [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)
116
117 Close()
118}
119
120// client implements the Client interface.
121type client struct {
122 username string
123 token string
124 o *Opts
125 rlt *time.Ticker
126
Serge Bazanski7448f282023-02-20 14:15:51 +0100127 // serializer is a N-semaphore channel (configured by opts.Parallelism) which is
128 // used to limit the number of concurrent calls to the Equinix API.
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100129 serializer chan (struct{})
130}
131
132// New creates a Client instance based on Opts. PACKNGO_DEBUG environment
133// variable can be set prior to the below call to enable verbose packngo
134// debug logs.
135func New(opts *Opts) Client {
136 return new(opts)
137}
138
139func new(opts *Opts) *client {
140 // Apply the defaults.
141 if opts.APIRate == 0 {
142 opts.APIRate = 2 * time.Second
143 }
144 if opts.BackOff == nil {
145 opts.BackOff = func() backoff.BackOff {
146 return backoff.NewExponentialBackOff()
147 }
148 }
Serge Bazanski7448f282023-02-20 14:15:51 +0100149 if opts.Parallelism == 0 {
150 opts.Parallelism = 1
151 }
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100152
153 return &client{
154 username: opts.User,
155 token: opts.APIKey,
156 o: opts,
157 rlt: time.NewTicker(opts.APIRate),
158
Serge Bazanski7448f282023-02-20 14:15:51 +0100159 serializer: make(chan struct{}, opts.Parallelism),
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100160 }
161}
162
163func (c *client) Close() {
164 c.rlt.Stop()
165}
166
167var (
168 ErrRaceLost = errors.New("race lost with another API user")
169 ErrNoReservationProvided = errors.New("hardware reservation must be set")
170)
171
172func (e *client) CreateDevice(ctx context.Context, r *packngo.DeviceCreateRequest) (*packngo.Device, error) {
173 if r.HardwareReservationID == "" {
174 return nil, ErrNoReservationProvided
175 }
176 // Add a tag to the request to detect if someone snatches a hardware reservation
177 // from under us.
178 witnessTag := fmt.Sprintf("wrapngo-idempotency-%s", uuid.New().String())
179 r.Tags = append(r.Tags, witnessTag)
180
181 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.Device, error) {
182 //Does the device already exist?
183 res, _, err := cl.HardwareReservations.Get(r.HardwareReservationID, nil)
184 if err != nil {
185 return nil, fmt.Errorf("couldn't check if device already exists: %w", err)
186 }
187 if res == nil {
188 return nil, fmt.Errorf("unexpected nil response")
189 }
190 if res.Device != nil {
191 // Check if we lost the race for this hardware reservation.
192 tags := make(map[string]bool)
193 for _, tag := range res.Device.Tags {
194 tags[tag] = true
195 }
196 if !tags[witnessTag] {
197 return nil, ErrRaceLost
198 }
199 return res.Device, nil
200 }
201
202 // No device yet. Try to create it.
203 dev, _, err := cl.Devices.Create(r)
204 if err == nil {
205 return dev, nil
206 }
207 // In case of a transient failure (eg. network issue), we retry the whole
208 // operation, which means we first check again if the device already exists. If
209 // it's a permanent error from the API, the backoff logic will fail immediately.
210 return nil, fmt.Errorf("couldn't create device: %w", err)
211 })
212}
213
214func (e *client) ListDevices(ctx context.Context, pid string) ([]packngo.Device, error) {
215 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.Device, error) {
Tim Windelschmidtd1b17472023-04-18 03:49:12 +0200216 // to increase the chances of a stable pagination, we sort the devices by hostname
217 res, _, err := cl.Devices.List(pid, &packngo.GetOptions{SortBy: "hostname"})
Mateusz Zalega6a058e72022-11-30 18:03:07 +0100218 return res, err
219 })
220}
221
222func (e *client) GetDevice(ctx context.Context, pid, did string) (*packngo.Device, error) {
223 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.Device, error) {
224 d, _, err := cl.Devices.Get(did, nil)
225 return d, err
226 })
227}
228
229// Currently unexported, only used in tests.
230func (e *client) deleteDevice(ctx context.Context, did string) error {
231 _, err := wrap(ctx, e, func(cl *packngo.Client) (*struct{}, error) {
232 _, err := cl.Devices.Delete(did, false)
233 if httpStatusCode(err) == http.StatusNotFound {
234 // 404s may pop up as an after effect of running the back-off
235 // algorithm, and as such should not be propagated.
236 return nil, nil
237 }
238 return nil, err
239 })
240 return err
241}
242
243func (e *client) ListReservations(ctx context.Context, pid string) ([]packngo.HardwareReservation, error) {
244 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.HardwareReservation, error) {
245 res, _, err := cl.HardwareReservations.List(pid, nil)
246 return res, err
247 })
248}
249
250func (e *client) CreateSSHKey(ctx context.Context, r *packngo.SSHKeyCreateRequest) (*packngo.SSHKey, error) {
251 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
252 // Does the key already exist?
253 ks, _, err := cl.SSHKeys.List()
254 if err != nil {
255 return nil, fmt.Errorf("SSHKeys.List: %w", err)
256 }
257 for _, k := range ks {
258 if k.Label == r.Label {
259 if k.Key != r.Key {
260 return nil, fmt.Errorf("key label already in use for a different key")
261 }
262 return &k, nil
263 }
264 }
265
266 // No key yet. Try to create it.
267 k, _, err := cl.SSHKeys.Create(r)
268 if err != nil {
269 return nil, fmt.Errorf("SSHKeys.Create: %w", err)
270 }
271 return k, nil
272 })
273}
274
275func (e *client) UpdateSSHKey(ctx context.Context, id string, r *packngo.SSHKeyUpdateRequest) (*packngo.SSHKey, error) {
276 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
277 k, _, err := cl.SSHKeys.Update(id, r)
278 if err != nil {
279 return nil, fmt.Errorf("SSHKeys.Update: %w", err)
280 }
281 return k, err
282 })
283}
284
285// Currently unexported, only used in tests.
286func (e *client) deleteSSHKey(ctx context.Context, id string) error {
287 _, err := wrap(ctx, e, func(cl *packngo.Client) (struct{}, error) {
288 _, err := cl.SSHKeys.Delete(id)
289 if err != nil {
290 return struct{}{}, fmt.Errorf("SSHKeys.Delete: %w", err)
291 }
292 return struct{}{}, err
293 })
294 return err
295}
296
297func (e *client) ListSSHKeys(ctx context.Context) ([]packngo.SSHKey, error) {
298 return wrap(ctx, e, func(cl *packngo.Client) ([]packngo.SSHKey, error) {
299 ks, _, err := cl.SSHKeys.List()
300 if err != nil {
301 return nil, fmt.Errorf("SSHKeys.List: %w", err)
302 }
303 return ks, nil
304 })
305}
306
307// Currently unexported, only used in tests.
308func (e *client) getSSHKey(ctx context.Context, id string) (*packngo.SSHKey, error) {
309 return wrap(ctx, e, func(cl *packngo.Client) (*packngo.SSHKey, error) {
310 k, _, err := cl.SSHKeys.Get(id, nil)
311 if err != nil {
312 return nil, fmt.Errorf("SSHKeys.Get: %w", err)
313 }
314 return k, nil
315 })
316}