20755: Allow cloud drivers to register their own metrics.
[arvados.git] / lib / cloud / interfaces.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package cloud
6
7 import (
8         "encoding/json"
9         "errors"
10         "io"
11         "time"
12
13         "git.arvados.org/arvados.git/sdk/go/arvados"
14         "github.com/prometheus/client_golang/prometheus"
15         "github.com/sirupsen/logrus"
16         "golang.org/x/crypto/ssh"
17 )
18
19 // A RateLimitError should be returned by an InstanceSet when the
20 // cloud service indicates it is rejecting all API calls for some time
21 // interval.
22 type RateLimitError interface {
23         // Time before which the caller should expect requests to
24         // fail.
25         EarliestRetry() time.Time
26         error
27 }
28
29 // A QuotaError should be returned by an InstanceSet when the cloud
30 // service indicates the account cannot create more VMs than already
31 // exist.
32 type QuotaError interface {
33         // If true, don't create more instances until some existing
34         // instances are destroyed. If false, don't handle the error
35         // as a quota error.
36         IsQuotaError() bool
37         error
38 }
39
40 type SharedResourceTags map[string]string
41 type InstanceSetID string
42 type InstanceTags map[string]string
43 type InstanceID string
44 type ImageID string
45
46 // An Executor executes commands on an ExecutorTarget.
47 type Executor interface {
48         // Update the set of private keys used to authenticate to
49         // targets.
50         SetSigners(...ssh.Signer)
51
52         // Set the target used for subsequent command executions.
53         SetTarget(ExecutorTarget)
54
55         // Return the current target.
56         Target() ExecutorTarget
57
58         // Execute a shell command and return the resulting stdout and
59         // stderr. stdin can be nil.
60         Execute(cmd string, stdin io.Reader) (stdout, stderr []byte, err error)
61 }
62
63 var ErrNotImplemented = errors.New("not implemented")
64
65 // An ExecutorTarget is a remote command execution service.
66 type ExecutorTarget interface {
67         // SSH server hostname or IP address, or empty string if
68         // unknown while instance is booting.
69         Address() string
70
71         // Remote username to send during SSH authentication.
72         RemoteUser() string
73
74         // Return nil if the given public key matches the instance's
75         // SSH server key. If the provided Dialer is not nil,
76         // VerifyHostKey can use it to make outgoing network
77         // connections from the instance -- e.g., to use the cloud's
78         // "this instance's metadata" API.
79         //
80         // Return ErrNotImplemented if no verification mechanism is
81         // available.
82         VerifyHostKey(ssh.PublicKey, *ssh.Client) error
83 }
84
85 // Instance is implemented by the provider-specific instance types.
86 type Instance interface {
87         ExecutorTarget
88
89         // ID returns the provider's instance ID. It must be stable
90         // for the life of the instance.
91         ID() InstanceID
92
93         // String typically returns the cloud-provided instance ID.
94         String() string
95
96         // Cloud provider's "instance type" ID. Matches a ProviderType
97         // in the cluster's InstanceTypes configuration.
98         ProviderType() string
99
100         // Get current tags
101         Tags() InstanceTags
102
103         // Replace tags with the given tags
104         SetTags(InstanceTags) error
105
106         // Get recent price history, if available. The InstanceType is
107         // supplied as an argument so the driver implementation can
108         // account for AddedScratch cost without requesting the volume
109         // attachment information from the provider's API.
110         PriceHistory(arvados.InstanceType) []InstancePrice
111
112         // Shut down the node
113         Destroy() error
114 }
115
116 // An InstanceSet manages a set of VM instances created by an elastic
117 // cloud provider like AWS, GCE, or Azure.
118 //
119 // All public methods of an InstanceSet, and all public methods of the
120 // instances it returns, are goroutine safe.
121 type InstanceSet interface {
122         // Create a new instance with the given type, image, and
123         // initial set of tags. If supported by the driver, add the
124         // provided public key to /root/.ssh/authorized_keys.
125         //
126         // The given InitCommand should be executed on the newly
127         // created instance. This is optional for a driver whose
128         // instances' VerifyHostKey() method never returns
129         // ErrNotImplemented. InitCommand will be under 1 KiB.
130         //
131         // The returned error should implement RateLimitError and
132         // QuotaError where applicable.
133         Create(arvados.InstanceType, ImageID, InstanceTags, InitCommand, ssh.PublicKey) (Instance, error)
134
135         // Return all instances, including ones that are booting or
136         // shutting down. Optionally, filter out nodes that don't have
137         // all of the given InstanceTags (the caller will ignore these
138         // anyway).
139         //
140         // An instance returned by successive calls to Instances() may
141         // -- but does not need to -- be represented by the same
142         // Instance object each time. Thus, the caller is responsible
143         // for de-duplicating the returned instances by comparing the
144         // InstanceIDs returned by the instances' ID() methods.
145         Instances(InstanceTags) ([]Instance, error)
146
147         // Stop any background tasks and release other resources.
148         Stop()
149 }
150
151 type InstancePrice struct {
152         StartTime time.Time
153         Price     float64
154 }
155
156 type InitCommand string
157
158 // A Driver returns an InstanceSet that uses the given InstanceSetID
159 // and driver-dependent configuration parameters.
160 //
161 // If the driver creates cloud resources that aren't attached to a
162 // single VM instance (like SSH key pairs on AWS) and support tagging,
163 // they should be tagged with the provided SharedResourceTags.
164 //
165 // The supplied id will be of the form "zzzzz-zzzzz-zzzzzzzzzzzzzzz"
166 // where each z can be any alphanum. The returned InstanceSet must use
167 // this id to tag long-lived cloud resources that it creates, and must
168 // assume control of any existing resources that are tagged with the
169 // same id. Tagging can be accomplished by including the ID in
170 // resource names, using the cloud provider's tagging feature, or any
171 // other mechanism. The tags must be visible to another instance of
172 // the same driver running on a different host.
173 //
174 // The returned InstanceSet must not modify or delete cloud resources
175 // unless they are tagged with the given InstanceSetID or the caller
176 // (dispatcher) calls Destroy() on them. It may log a summary of
177 // untagged resources once at startup, though. Thus, two identically
178 // configured InstanceSets running on different hosts with different
179 // ids should log about the existence of each other's resources at
180 // startup, but will not interfere with each other.
181 //
182 // The dispatcher always passes the InstanceSetID as a tag when
183 // calling Create() and Instances(), so the driver does not need to
184 // tag/filter VMs by InstanceSetID itself.
185 //
186 // Example:
187 //
188 //      type exampleInstanceSet struct {
189 //              ownID     string
190 //              AccessKey string
191 //      }
192 //
193 //      type exampleDriver struct {}
194 //
195 //      func (*exampleDriver) InstanceSet(config json.RawMessage, id cloud.InstanceSetID, tags cloud.SharedResourceTags, logger logrus.FieldLogger, reg *prometheus.Registry) (cloud.InstanceSet, error) {
196 //              var is exampleInstanceSet
197 //              if err := json.Unmarshal(config, &is); err != nil {
198 //                      return nil, err
199 //              }
200 //              is.ownID = id
201 //              return &is, nil
202 //      }
203 type Driver interface {
204         InstanceSet(config json.RawMessage, id InstanceSetID, tags SharedResourceTags, logger logrus.FieldLogger, reg *prometheus.Registry) (InstanceSet, error)
205 }
206
207 // DriverFunc makes a Driver using the provided function as its
208 // InstanceSet method. This is similar to http.HandlerFunc.
209 func DriverFunc(fn func(config json.RawMessage, id InstanceSetID, tags SharedResourceTags, logger logrus.FieldLogger, reg *prometheus.Registry) (InstanceSet, error)) Driver {
210         return driverFunc(fn)
211 }
212
213 type driverFunc func(config json.RawMessage, id InstanceSetID, tags SharedResourceTags, logger logrus.FieldLogger, reg *prometheus.Registry) (InstanceSet, error)
214
215 func (df driverFunc) InstanceSet(config json.RawMessage, id InstanceSetID, tags SharedResourceTags, logger logrus.FieldLogger, reg *prometheus.Registry) (InstanceSet, error) {
216         return df(config, id, tags, logger, reg)
217 }