-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigration.go
322 lines (281 loc) · 9.6 KB
/
migration.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
316
317
318
319
320
321
322
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package migration
import (
"io"
"net/url"
"os"
"time"
"github.com/juju/charm/v11"
"github.com/juju/description/v4"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/naturalsort"
"github.com/juju/version/v2"
"github.com/juju/juju/core/leadership"
"github.com/juju/juju/core/migration"
"github.com/juju/juju/core/resources"
"github.com/juju/juju/state"
"github.com/juju/juju/tools"
)
var logger = loggo.GetLogger("juju.migration")
// StateExporter describes interface on state required to export a
// model.
type StateExporter interface {
// Export generates an abstract representation of a model.
Export(leaders map[string]string) (description.Model, error)
}
// StateImporter describes the method needed to import a model
// into the database.
type StateImporter interface {
Import(model description.Model) (*state.Model, *state.State, error)
}
// ClaimerFunc is a function that returns a leadership claimer for the
// model UUID passed.
type ClaimerFunc func(string) (leadership.Claimer, error)
// ImportModel deserializes a model description from the bytes, transforms
// the model config based on information from the controller model, and then
// imports that as a new database model.
func ImportModel(importer StateImporter, getClaimer ClaimerFunc, bytes []byte) (*state.Model, *state.State, error) {
model, err := description.Deserialize(bytes)
if err != nil {
return nil, nil, errors.Trace(err)
}
dbModel, dbState, err := importer.Import(model)
if err != nil {
return nil, nil, errors.Trace(err)
}
claimer, err := getClaimer(dbModel.UUID())
if err != nil {
return nil, nil, errors.Annotate(err, "getting leadership claimer")
}
logger.Debugf("importing leadership")
for _, application := range model.Applications() {
if application.Leader() == "" {
continue
}
// When we import a new model, we need to give the leaders
// some time to settle. We don't want to have leader switches
// just because we migrated a model, so this time needs to be
// long enough to make sure we cover the time taken to migrate
// a reasonable sized model. We don't yet know how long this
// is going to be, but we need something.
// TODO(babbageclunk): Handle this better - maybe a way to
// suppress leadership expirations for a model until it is
// finished importing?
logger.Debugf("%q is the leader for %q", application.Leader(), application.Name())
err := claimer.ClaimLeadership(
application.Name(),
application.Leader(),
time.Minute,
)
if err != nil {
return nil, nil, errors.Annotatef(
err,
"claiming leadership for %q",
application.Leader(),
)
}
}
return dbModel, dbState, nil
}
// CharmDownloader defines a single method that is used to download a
// charm from the source controller in a migration.
type CharmDownloader interface {
OpenCharm(*charm.URL) (io.ReadCloser, error)
}
// CharmUploader defines a single method that is used to upload a
// charm to the target controller in a migration.
type CharmUploader interface {
UploadCharm(*charm.URL, io.ReadSeeker) (*charm.URL, error)
}
// ToolsDownloader defines a single method that is used to download
// tools from the source controller in a migration.
type ToolsDownloader interface {
OpenURI(string, url.Values) (io.ReadCloser, error)
}
// ToolsUploader defines a single method that is used to upload tools
// to the target controller in a migration.
type ToolsUploader interface {
UploadTools(io.ReadSeeker, version.Binary) (tools.List, error)
}
// ResourceDownloader defines the interface for downloading resources
// from the source controller during a migration.
type ResourceDownloader interface {
OpenResource(string, string) (io.ReadCloser, error)
}
// ResourceUploader defines the interface for uploading resources into
// the target controller during a migration.
type ResourceUploader interface {
UploadResource(resources.Resource, io.ReadSeeker) error
SetPlaceholderResource(resources.Resource) error
SetUnitResource(string, resources.Resource) error
}
// UploadBinariesConfig provides all the configuration that the
// UploadBinaries function needs to operate. To construct the config
// with the default helper functions, use `NewUploadBinariesConfig`.
type UploadBinariesConfig struct {
Charms []string
CharmDownloader CharmDownloader
CharmUploader CharmUploader
Tools map[version.Binary]string
ToolsDownloader ToolsDownloader
ToolsUploader ToolsUploader
Resources []migration.SerializedModelResource
ResourceDownloader ResourceDownloader
ResourceUploader ResourceUploader
}
// Validate makes sure that all the config values are non-nil.
func (c *UploadBinariesConfig) Validate() error {
if c.CharmDownloader == nil {
return errors.NotValidf("missing CharmDownloader")
}
if c.CharmUploader == nil {
return errors.NotValidf("missing CharmUploader")
}
if c.ToolsDownloader == nil {
return errors.NotValidf("missing ToolsDownloader")
}
if c.ToolsUploader == nil {
return errors.NotValidf("missing ToolsUploader")
}
if c.ResourceDownloader == nil {
return errors.NotValidf("missing ResourceDownloader")
}
if c.ResourceUploader == nil {
return errors.NotValidf("missing ResourceUploader")
}
return nil
}
// UploadBinaries will send binaries stored in the source blobstore to
// the target controller.
func UploadBinaries(config UploadBinariesConfig) error {
if err := config.Validate(); err != nil {
return errors.Trace(err)
}
if err := uploadCharms(config); err != nil {
return errors.Annotatef(err, "cannot upload charms")
}
if err := uploadTools(config); err != nil {
return errors.Annotatef(err, "cannot upload agent binaries")
}
if err := uploadResources(config); err != nil {
return errors.Annotatef(err, "cannot upload resources")
}
return nil
}
func streamThroughTempFile(r io.Reader) (_ io.ReadSeeker, cleanup func(), err error) {
tempFile, err := os.CreateTemp("", "juju-migrate-binary")
if err != nil {
return nil, nil, errors.Trace(err)
}
defer func() {
if err != nil {
_ = os.Remove(tempFile.Name())
}
}()
_, err = io.Copy(tempFile, r)
if err != nil {
return nil, nil, errors.Trace(err)
}
_, err = tempFile.Seek(0, 0)
if err != nil {
return nil, nil, errors.Annotatef(err, "potentially corrupt binary")
}
rmTempFile := func() {
filename := tempFile.Name()
_ = tempFile.Close()
_ = os.Remove(filename)
}
return tempFile, rmTempFile, nil
}
func uploadCharms(config UploadBinariesConfig) error {
// It is critical that charms are uploaded in ascending charm URL
// order so that charm revisions end up the same in the target as
// they were in the source.
naturalsort.Sort(config.Charms)
for _, charmURL := range config.Charms {
logger.Debugf("sending charm %s to target", charmURL)
curl, err := charm.ParseURL(charmURL)
if err != nil {
return errors.Annotate(err, "bad charm URL")
}
reader, err := config.CharmDownloader.OpenCharm(curl)
if err != nil {
return errors.Annotate(err, "cannot open charm")
}
defer func() { _ = reader.Close() }()
content, cleanup, err := streamThroughTempFile(reader)
if err != nil {
return errors.Trace(err)
}
defer cleanup()
if usedCurl, err := config.CharmUploader.UploadCharm(curl, content); err != nil {
return errors.Annotate(err, "cannot upload charm")
} else if usedCurl.String() != curl.String() {
// The target controller shouldn't assign a different charm URL.
return errors.Errorf("charm %s unexpectedly assigned %s", curl, usedCurl)
}
}
return nil
}
func uploadTools(config UploadBinariesConfig) error {
for v, uri := range config.Tools {
logger.Debugf("sending agent binaries to target: %s", v)
reader, err := config.ToolsDownloader.OpenURI(uri, nil)
if err != nil {
return errors.Annotate(err, "cannot open charm")
}
defer func() { _ = reader.Close() }()
content, cleanup, err := streamThroughTempFile(reader)
if err != nil {
return errors.Trace(err)
}
defer cleanup()
if _, err := config.ToolsUploader.UploadTools(content, v); err != nil {
return errors.Annotate(err, "cannot upload agent binaries")
}
}
return nil
}
func uploadResources(config UploadBinariesConfig) error {
for _, res := range config.Resources {
if res.ApplicationRevision.IsPlaceholder() {
// Resource placeholders created in the migration import rather
// than attempting to post empty resources.
} else {
err := uploadAppResource(config, res.ApplicationRevision)
if err != nil {
return errors.Trace(err)
}
}
for unitName, unitRev := range res.UnitRevisions {
if err := config.ResourceUploader.SetUnitResource(unitName, unitRev); err != nil {
return errors.Annotate(err, "cannot set unit resource")
}
}
// Each config.Resources element also contains a
// CharmStoreRevision field. This isn't especially important
// to migrate so is skipped for now.
}
return nil
}
func uploadAppResource(config UploadBinariesConfig, rev resources.Resource) error {
logger.Debugf("opening application resource for %s: %s", rev.ApplicationID, rev.Name)
reader, err := config.ResourceDownloader.OpenResource(rev.ApplicationID, rev.Name)
if err != nil {
return errors.Annotate(err, "cannot open resource")
}
defer func() { _ = reader.Close() }()
// TODO(menn0) - validate that the downloaded revision matches
// the expected metadata. Check revision and fingerprint.
content, cleanup, err := streamThroughTempFile(reader)
if err != nil {
return errors.Trace(err)
}
defer cleanup()
if err := config.ResourceUploader.UploadResource(rev, content); err != nil {
return errors.Annotate(err, "cannot upload resource")
}
return nil
}