-
Notifications
You must be signed in to change notification settings - Fork 20
/
remotes.go
315 lines (249 loc) · 8.17 KB
/
remotes.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package trust
import (
"crypto/x509"
"errors"
"fmt"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/logger"
"github.com/google/renameio"
"gopkg.in/yaml.v2"
"github.com/canonical/microcluster/client"
internalClient "github.com/canonical/microcluster/internal/rest/client"
internalTypes "github.com/canonical/microcluster/internal/rest/types"
"github.com/canonical/microcluster/rest/types"
)
// Remotes is a convenient alias as we will often deal with groups of yaml files.
type Remotes struct {
data map[string]Remote
updateMu sync.RWMutex
}
// Remote represents a yaml file with credentials to be read by the daemon.
type Remote struct {
Location `yaml:",inline"`
Certificate types.X509Certificate `yaml:"certificate"`
}
// Location represents configurable identifying information about a remote.
type Location struct {
Name string `yaml:"name"`
Address types.AddrPort `yaml:"address"`
}
// Load reads any yaml files in the given directory and parses them into a set of Remotes.
func (r *Remotes) Load(dir string) error {
r.updateMu.Lock()
defer r.updateMu.Unlock()
files, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("Unable to read trust directory: %q: %w", dir, err)
}
remoteData := map[string]Remote{}
for _, file := range files {
fileName := file.Name()
if file.IsDir() || !strings.HasSuffix(fileName, ".yaml") {
continue
}
content, err := os.ReadFile(filepath.Join(dir, fileName))
if err != nil {
return fmt.Errorf("Unable to read file %q: %w", fileName, err)
}
remote := &Remote{}
err = yaml.Unmarshal(content, remote)
if err != nil {
return fmt.Errorf("Unable to parse yaml for %q: %w", fileName, err)
}
if remote.Certificate.Certificate == nil {
return fmt.Errorf("Failed to parse local record %q. Found empty certificate", remote.Name)
}
remoteData[remote.Name] = *remote
}
// If the refreshed truststore data is empty, and we already had data in the truststore,
// abort the refresh because an initialized system should always have truststore entries.
if len(remoteData) == 0 && len(r.data) != 0 {
logger.Warn("Failed to parse new remotes from truststore")
return nil
}
r.data = remoteData
return nil
}
// Add adds a new local cluster member record for the remotes.
func (r *Remotes) Add(dir string, remotes ...Remote) error {
r.updateMu.Lock()
defer r.updateMu.Unlock()
for _, remote := range remotes {
if remote.Certificate.Certificate == nil {
return fmt.Errorf("Failed to parse local record %q. Found empty certificate", remote.Name)
}
_, ok := r.data[remote.Name]
if ok {
return fmt.Errorf("A remote with name %q already exists", remote.Name)
}
bytes, err := yaml.Marshal(remote)
if err != nil {
return fmt.Errorf("Failed to parse remote %q to yaml: %w", remote.Name, err)
}
path := filepath.Join(dir, fmt.Sprintf("%s.yaml", remote.Name))
_, err = os.Stat(path)
if err == nil {
return fmt.Errorf("Remote at %q already exists", path)
}
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("Failed to check remote path %q: %w", path, err)
}
err = renameio.WriteFile(path, bytes, 0644)
if err != nil {
return fmt.Errorf("Failed to write %q: %w", path, err)
}
// Add the remote manually so we can use it right away without waiting for inotify.
r.data[remote.Name] = remote
}
return nil
}
// Replace replaces the in-memory and locally stored remotes with the given list from the database.
func (r *Remotes) Replace(dir string, newRemotes ...internalTypes.ClusterMember) error {
r.updateMu.Lock()
defer r.updateMu.Unlock()
if len(newRemotes) == 0 {
return fmt.Errorf("Received empty remotes")
}
remoteData := map[string]Remote{}
for _, remote := range newRemotes {
newRemote := Remote{
Location: Location{Name: remote.Name, Address: remote.Address},
Certificate: remote.Certificate,
}
if remote.Certificate.Certificate == nil {
return fmt.Errorf("Failed to parse local record %q. Found empty certificate", remote.Name)
}
bytes, err := yaml.Marshal(newRemote)
if err != nil {
return fmt.Errorf("Failed to parse remote %q to yaml: %w", remote.Name, err)
}
remotePath := filepath.Join(dir, fmt.Sprintf("%s.yaml", remote.Name))
err = renameio.WriteFile(remotePath, bytes, 0644)
if err != nil {
return fmt.Errorf("Failed to write %q: %w", remotePath, err)
}
remoteData[remote.Name] = newRemote
}
allEntries, err := os.ReadDir(dir)
if err != nil {
return err
}
// Remove any outdated entries.
for _, entry := range allEntries {
name, _, _ := strings.Cut(entry.Name(), ".yaml")
_, ok := remoteData[name]
if !ok {
remotePath := filepath.Join(dir, fmt.Sprintf("%s.yaml", name))
err = os.Remove(remotePath)
if err != nil {
return err
}
}
}
if len(remoteData) == 0 {
return fmt.Errorf("Failed to parse new remotes")
}
r.data = remoteData
return nil
}
// SelectRandom returns a random remote.
func (r *Remotes) SelectRandom() *Remote {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
allRemotes := make([]Remote, 0, len(r.data))
for _, r := range r.data {
allRemotes = append(allRemotes, r)
}
return &allRemotes[rand.Intn(len(allRemotes))]
}
// Addresses returns just the host:port addresses of the remotes.
func (r *Remotes) Addresses() map[string]types.AddrPort {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
addrs := map[string]types.AddrPort{}
for _, remote := range r.data {
addrs[remote.Name] = remote.Address
}
return addrs
}
// Cluster returns a set of clients for every remote, which can be concurrently queried.
func (r *Remotes) Cluster(isNotification bool, serverCert *shared.CertInfo, publicKey *x509.Certificate) (client.Cluster, error) {
cluster := make(client.Cluster, 0, r.Count()-1)
for _, addr := range r.Addresses() {
url := api.NewURL().Scheme("https").Host(addr.String())
c, err := internalClient.New(*url, serverCert, publicKey, isNotification)
if err != nil {
return nil, err
}
cluster = append(cluster, client.Client{Client: *c})
}
return cluster, nil
}
// RemoteByAddress returns a Remote matching the given host address (or nil if none are found).
func (r *Remotes) RemoteByAddress(addrPort types.AddrPort) *Remote {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
for _, remote := range r.data {
if remote.Address.String() == addrPort.String() {
return &remote
}
}
return nil
}
// RemoteByCertificateFingerprint returns a remote whose certificate fingerprint matches the provided fingerprint.
func (r *Remotes) RemoteByCertificateFingerprint(fingerprint string) *Remote {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
for _, remote := range r.data {
if fingerprint == shared.CertFingerprint(remote.Certificate.Certificate) {
return &remote
}
}
return nil
}
// Certificates returns a map of remotes certificates by fingerprint.
func (r *Remotes) Certificates() map[string]types.X509Certificate {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
certMap := map[string]types.X509Certificate{}
for _, remote := range r.data {
certMap[shared.CertFingerprint(remote.Certificate.Certificate)] = remote.Certificate
}
return certMap
}
// CertificatesNative returns the Certificates map with values as native x509.Certificate type.
func (r *Remotes) CertificatesNative() map[string]x509.Certificate {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
certMap := map[string]x509.Certificate{}
for _, remote := range r.data {
certMap[shared.CertFingerprint(remote.Certificate.Certificate)] = *remote.Certificate.Certificate
}
return certMap
}
// Count returns the number of remotes.
func (r *Remotes) Count() int {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
return len(r.data)
}
// RemotesByName returns a copy of the list of peers, keyed by each system's name.
func (r *Remotes) RemotesByName() map[string]Remote {
r.updateMu.RLock()
defer r.updateMu.RUnlock()
remoteData := make(map[string]Remote, len(r.data))
for name, data := range r.data {
remoteData[name] = data
}
return remoteData
}
// URL returns the parsed URL of the Remote.
func (r *Remote) URL() api.URL {
return *api.NewURL().Scheme("https").Host(r.Address.String())
}