/
connect.go
283 lines (241 loc) · 10.4 KB
/
connect.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package cluster
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/lxc/lxd/client"
clusterRequest "github.com/lxc/lxd/lxd/cluster/request"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/request"
"github.com/lxc/lxd/lxd/state"
storagePools "github.com/lxc/lxd/lxd/storage"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/version"
)
// Connect is a convenience around lxd.ConnectLXD that configures the client
// with the correct parameters for node-to-node communication.
//
// If 'notify' switch is true, then the user agent will be set to the special
// to the UserAgentNotifier value, which can be used in some cases to distinguish
// between a regular client request and an internal cluster request.
func Connect(address string, networkCert *shared.CertInfo, serverCert *shared.CertInfo, r *http.Request, notify bool) (lxd.InstanceServer, error) {
// Wait for a connection to the events API first for non-notify connections.
if !notify {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
defer cancel()
err := EventListenerWait(ctx, address)
if err != nil {
return nil, fmt.Errorf("Missing event connection with target cluster member")
}
}
args := &lxd.ConnectionArgs{
TLSServerCert: string(networkCert.PublicKey()),
TLSClientCert: string(serverCert.PublicKey()),
TLSClientKey: string(serverCert.PrivateKey()),
SkipGetServer: true,
UserAgent: version.UserAgent,
}
if notify {
args.UserAgent = clusterRequest.UserAgentNotifier
}
if r != nil {
proxy := func(req *http.Request) (*url.URL, error) {
ctx := r.Context()
val, ok := ctx.Value(request.CtxUsername).(string)
if ok {
req.Header.Add(request.HeaderForwardedUsername, val)
}
val, ok = ctx.Value(request.CtxProtocol).(string)
if ok {
req.Header.Add(request.HeaderForwardedProtocol, val)
}
req.Header.Add(request.HeaderForwardedAddress, r.RemoteAddr)
return shared.ProxyFromEnvironment(req)
}
args.Proxy = proxy
}
url := fmt.Sprintf("https://%s", address)
return lxd.ConnectLXD(url, args)
}
// ConnectIfInstanceIsRemote figures out the address of the cluster member which is running the instance with the
// given name in the specified project. If it's not the local member will connect to it and return the connected
// client (configured with the specified project), otherwise it will just return nil.
func ConnectIfInstanceIsRemote(cluster *db.Cluster, projectName string, instName string, networkCert *shared.CertInfo, serverCert *shared.CertInfo, r *http.Request, instanceType instancetype.Type) (lxd.InstanceServer, error) {
var address string // Cluster member address.
err := cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
address, err = tx.GetNodeAddressOfInstance(ctx, projectName, instName, instanceType)
return err
})
if err != nil {
return nil, err
}
if address == "" {
return nil, nil // The instance is running on this local member, no need to connect.
}
client, err := Connect(address, networkCert, serverCert, r, false)
if err != nil {
return nil, err
}
client = client.UseProject(projectName)
return client, nil
}
// ConnectIfVolumeIsRemote figures out the address of the cluster member on which the volume with the given name is
// defined. If it's not the local cluster member it will connect to it and return the connected client, otherwise
// it just returns nil. If there is more than one cluster member with a matching volume name, an error is returned.
func ConnectIfVolumeIsRemote(s *state.State, poolName string, projectName string, volumeName string, volumeType int, networkCert *shared.CertInfo, serverCert *shared.CertInfo, r *http.Request) (lxd.InstanceServer, error) {
localNodeID := s.DB.Cluster.GetNodeID()
var err error
var nodes []db.NodeInfo
var poolID int64
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
poolID, err = tx.GetStoragePoolID(ctx, poolName)
if err != nil {
return err
}
nodes, err = tx.GetStorageVolumeNodes(ctx, poolID, projectName, volumeName, volumeType)
if err != nil {
return err
}
return nil
})
if err != nil && err != db.ErrNoClusterMember {
return nil, err
}
// If volume uses a remote storage driver and so has no explicit cluster member, then we need to check
// whether it is exclusively attached to remote instance, and if so then we need to forward the request to
// the node whereit is currently used. This avoids conflicting with another member when using it locally.
if err == db.ErrNoClusterMember {
// GetStoragePoolVolume returns a volume with an empty Location field for remote drivers.
var dbVolume *db.StorageVolume
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
dbVolume, err = tx.GetStoragePoolVolume(ctx, poolID, projectName, volumeType, volumeName, true)
return err
})
if err != nil {
return nil, err
}
remoteInstance, err := storagePools.VolumeUsedByExclusiveRemoteInstancesWithProfiles(s, poolName, projectName, &dbVolume.StorageVolume)
if err != nil {
return nil, fmt.Errorf("Failed checking if volume %q is available: %w", volumeName, err)
}
if remoteInstance != nil {
var instNode db.NodeInfo
err := s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
instNode, err = tx.GetNodeByName(ctx, remoteInstance.Node)
return err
})
if err != nil {
return nil, fmt.Errorf("Failed getting cluster member info for %q: %w", remoteInstance.Node, err)
}
// Replace node list with instance's cluster member node (which might be local member).
nodes = []db.NodeInfo{instNode}
} else {
// Volume isn't exclusively attached to an instance. Use local cluster member.
return nil, nil
}
}
nodeCount := len(nodes)
if nodeCount > 1 {
return nil, fmt.Errorf("More than one cluster member has a volume named %q. Please target a specific member", volumeName)
} else if nodeCount < 1 {
// Should never get here.
return nil, fmt.Errorf("Volume %q has empty cluster member list", volumeName)
}
node := nodes[0]
if node.ID == localNodeID {
// Use local cluster member if volume belongs to this local member.
return nil, nil
}
// Connect to remote cluster member.
return Connect(node.Address, networkCert, serverCert, r, false)
}
// SetupTrust is a convenience around InstanceServer.CreateCertificate that adds the given server certificate to
// the trusted pool of the cluster at the given address, using the given password. The certificate is added as
// type CertificateTypeServer to allow intra-member communication. If a certificate with the same fingerprint
// already exists with a different name or type, then no error is returned.
func SetupTrust(serverCert *shared.CertInfo, serverName string, targetAddress string, targetCert string, targetPassword string) error {
// Connect to the target cluster node.
args := &lxd.ConnectionArgs{
TLSServerCert: targetCert,
UserAgent: version.UserAgent,
}
target, err := lxd.ConnectLXD(fmt.Sprintf("https://%s", targetAddress), args)
if err != nil {
return fmt.Errorf("Failed to connect to target cluster node %q: %w", targetAddress, err)
}
cert, err := shared.GenerateTrustCertificate(serverCert, serverName)
if err != nil {
return fmt.Errorf("Failed generating trust certificate: %w", err)
}
post := api.CertificatesPost{
CertificatePut: cert.CertificatePut,
Password: targetPassword,
}
err = target.CreateCertificate(post)
if err != nil && !api.StatusErrorCheck(err, http.StatusConflict) {
return fmt.Errorf("Failed to add server cert to cluster: %w", err)
}
return nil
}
// UpdateTrust ensures that the supplied certificate is stored in the target trust store with the correct name
// and type to ensure correct cluster operation. Should be called after SetupTrust. If a certificate with the same
// fingerprint is already in the trust store, but is of the wrong type or name then the existing certificate is
// updated to the correct type and name. If the existing certificate is the correct type but the wrong name then an
// error is returned. And if the existing certificate is the correct type and name then nothing more is done.
func UpdateTrust(serverCert *shared.CertInfo, serverName string, targetAddress string, targetCert string) error {
// Connect to the target cluster node.
args := &lxd.ConnectionArgs{
TLSClientCert: string(serverCert.PublicKey()),
TLSClientKey: string(serverCert.PrivateKey()),
TLSServerCert: targetCert,
UserAgent: version.UserAgent,
}
target, err := lxd.ConnectLXD(fmt.Sprintf("https://%s", targetAddress), args)
if err != nil {
return fmt.Errorf("Failed to connect to target cluster node %q: %w", targetAddress, err)
}
cert, err := shared.GenerateTrustCertificate(serverCert, serverName)
if err != nil {
return fmt.Errorf("Failed generating trust certificate: %w", err)
}
existingCert, _, err := target.GetCertificate(cert.Fingerprint)
if err != nil {
return fmt.Errorf("Failed getting existing certificate: %w", err)
}
if existingCert.Name != serverName && existingCert.Type == api.CertificateTypeServer {
// Don't alter an existing server certificate that has our fingerprint but not our name.
// Something is wrong as this shouldn't happen.
return fmt.Errorf("Existing server certificate with different name %q already in trust store", existingCert.Name)
} else if existingCert.Name != serverName && existingCert.Type != api.CertificateTypeServer {
// Ensure that if a client certificate already exists that matches our fingerprint, that it
// has the correct name and type for cluster operation, to allow us to associate member
// server names to certificate names.
err = target.UpdateCertificate(cert.Fingerprint, cert.CertificatePut, "")
if err != nil {
return fmt.Errorf("Failed updating certificate name and type in trust store: %w", err)
}
}
return nil
}
// HasConnectivity probes the member with the given address for connectivity.
func HasConnectivity(networkCert *shared.CertInfo, serverCert *shared.CertInfo, address string) bool {
config, err := tlsClientConfig(networkCert, serverCert)
if err != nil {
return false
}
var conn net.Conn
dialer := &net.Dialer{Timeout: time.Second}
conn, err = tls.DialWithDialer(dialer, "tcp", address, config)
if err == nil {
_ = conn.Close()
return true
}
return false
}