~nskaggs/+junk/xenial-test

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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package provisioner

import (
	"fmt"
	"sort"
	"strings"

	"github.com/juju/errors"
	"github.com/juju/utils/series"
	"github.com/juju/utils/set"
	"gopkg.in/juju/names.v2"

	"github.com/juju/juju/apiserver/common"
	"github.com/juju/juju/apiserver/common/storagecommon"
	"github.com/juju/juju/apiserver/params"
	"github.com/juju/juju/cloudconfig/instancecfg"
	"github.com/juju/juju/environs"
	"github.com/juju/juju/environs/imagemetadata"
	"github.com/juju/juju/environs/simplestreams"
	"github.com/juju/juju/environs/tags"
	"github.com/juju/juju/state"
	"github.com/juju/juju/state/cloudimagemetadata"
	"github.com/juju/juju/state/multiwatcher"
	"github.com/juju/juju/storage"
)

// ProvisioningInfo returns the provisioning information for each given machine entity.
func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) {
	result := params.ProvisioningInfoResults{
		Results: make([]params.ProvisioningInfoResult, len(args.Entities)),
	}
	canAccess, err := p.getAuthFunc()
	if err != nil {
		return result, err
	}
	for i, entity := range args.Entities {
		tag, err := names.ParseMachineTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		machine, err := p.getMachine(canAccess, tag)
		if err == nil {
			result.Results[i].Result, err = p.getProvisioningInfo(machine)
		}
		result.Results[i].Error = common.ServerError(err)
	}
	return result, nil
}

func (p *ProvisionerAPI) getProvisioningInfo(m *state.Machine) (*params.ProvisioningInfo, error) {
	cons, err := m.Constraints()
	if err != nil {
		return nil, err
	}

	volumes, err := p.machineVolumeParams(m)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var jobs []multiwatcher.MachineJob
	for _, job := range m.Jobs() {
		jobs = append(jobs, job.ToParams())
	}

	tags, err := p.machineTags(m, jobs)
	if err != nil {
		return nil, errors.Trace(err)
	}

	subnetsToZones, err := p.machineSubnetsAndZones(m)
	if err != nil {
		return nil, errors.Annotate(err, "cannot match subnets to zones")
	}

	endpointBindings, err := p.machineEndpointBindings(m)
	if err != nil {
		return nil, errors.Annotate(err, "cannot determine machine endpoint bindings")
	}
	imageMetadata, err := p.availableImageMetadata(m)
	if err != nil {
		return nil, errors.Annotate(err, "cannot get available image metadata")
	}
	controllerCfg, err := p.st.ControllerConfig()
	if err != nil {
		return nil, errors.Annotate(err, "cannot get controller configuration")
	}

	return &params.ProvisioningInfo{
		Constraints:      cons,
		Series:           m.Series(),
		Placement:        m.Placement(),
		Jobs:             jobs,
		Volumes:          volumes,
		Tags:             tags,
		SubnetsToZones:   subnetsToZones,
		EndpointBindings: endpointBindings,
		ImageMetadata:    imageMetadata,
		ControllerConfig: controllerCfg,
	}, nil
}

// machineVolumeParams retrieves VolumeParams for the volumes that should be
// provisioned with, and attached to, the machine. The client should ignore
// parameters that it does not know how to handle.
func (p *ProvisionerAPI) machineVolumeParams(m *state.Machine) ([]params.VolumeParams, error) {
	volumeAttachments, err := m.VolumeAttachments()
	if err != nil {
		return nil, err
	}
	if len(volumeAttachments) == 0 {
		return nil, nil
	}
	modelConfig, err := p.st.ModelConfig()
	if err != nil {
		return nil, err
	}
	controllerCfg, err := p.st.ControllerConfig()
	if err != nil {
		return nil, err
	}
	allVolumeParams := make([]params.VolumeParams, 0, len(volumeAttachments))
	for _, volumeAttachment := range volumeAttachments {
		volumeTag := volumeAttachment.Volume()
		volume, err := p.st.Volume(volumeTag)
		if err != nil {
			return nil, errors.Annotatef(err, "getting volume %q", volumeTag.Id())
		}
		storageInstance, err := storagecommon.MaybeAssignedStorageInstance(
			volume.StorageInstance, p.st.StorageInstance,
		)
		if err != nil {
			return nil, errors.Annotatef(err, "getting volume %q storage instance", volumeTag.Id())
		}
		volumeParams, err := storagecommon.VolumeParams(
			volume, storageInstance, modelConfig.UUID(), controllerCfg.ControllerUUID(),
			modelConfig, p.storagePoolManager, p.storageProviderRegistry,
		)
		if err != nil {
			return nil, errors.Annotatef(err, "getting volume %q parameters", volumeTag.Id())
		}
		provider, err := p.storageProviderRegistry.StorageProvider(storage.ProviderType(volumeParams.Provider))
		if err != nil {
			return nil, errors.Annotate(err, "getting storage provider")
		}
		if provider.Dynamic() {
			// Leave dynamic storage to the storage provisioner.
			continue
		}
		volumeAttachmentParams, ok := volumeAttachment.Params()
		if !ok {
			// Attachment is already provisioned; this is an insane
			// state, so we should not proceed with the volume.
			return nil, errors.Errorf(
				"volume %s already attached to machine %s",
				volumeTag.Id(), m.Id(),
			)
		}
		// Not provisioned yet, so ask the cloud provisioner do it.
		volumeParams.Attachment = &params.VolumeAttachmentParams{
			volumeTag.String(),
			m.Tag().String(),
			"", // we're creating the volume, so it has no volume ID.
			"", // we're creating the machine, so it has no instance ID.
			volumeParams.Provider,
			volumeAttachmentParams.ReadOnly,
		}
		allVolumeParams = append(allVolumeParams, volumeParams)
	}
	return allVolumeParams, nil
}

// machineTags returns machine-specific tags to set on the instance.
func (p *ProvisionerAPI) machineTags(m *state.Machine, jobs []multiwatcher.MachineJob) (map[string]string, error) {
	// Names of all units deployed to the machine.
	//
	// TODO(axw) 2015-06-02 #1461358
	// We need a worker that periodically updates
	// instance tags with current deployment info.
	units, err := m.Units()
	if err != nil {
		return nil, errors.Trace(err)
	}
	unitNames := make([]string, 0, len(units))
	for _, unit := range units {
		if !unit.IsPrincipal() {
			continue
		}
		unitNames = append(unitNames, unit.Name())
	}
	sort.Strings(unitNames)

	cfg, err := p.st.ModelConfig()
	if err != nil {
		return nil, errors.Trace(err)
	}
	controllerCfg, err := p.st.ControllerConfig()
	if err != nil {
		return nil, errors.Trace(err)
	}
	machineTags := instancecfg.InstanceTags(cfg.UUID(), controllerCfg.ControllerUUID(), cfg, jobs)
	if len(unitNames) > 0 {
		machineTags[tags.JujuUnitsDeployed] = strings.Join(unitNames, " ")
	}
	return machineTags, nil
}

// machineSubnetsAndZones returns a map of subnet provider-specific id
// to list of availability zone names for that subnet. The result can
// be empty if there are no spaces constraints specified for the
// machine, or there's an error fetching them.
func (p *ProvisionerAPI) machineSubnetsAndZones(m *state.Machine) (map[string][]string, error) {
	mcons, err := m.Constraints()
	if err != nil {
		return nil, errors.Annotate(err, "cannot get machine constraints")
	}
	includeSpaces := mcons.IncludeSpaces()
	if len(includeSpaces) < 1 {
		// Nothing to do.
		return nil, nil
	}
	// TODO(dimitern): For the network model MVP we only use the first
	// included space and ignore the rest.
	//
	// LKK Card: https://canonical.leankit.com/Boards/View/101652562/117352306
	// LP Bug: http://pad.lv/1498232
	spaceName := includeSpaces[0]
	if len(includeSpaces) > 1 {
		logger.Debugf(
			"using space %q from constraints for machine %q (ignoring remaining: %v)",
			spaceName, m.Id(), includeSpaces[1:],
		)
	}
	space, err := p.st.Space(spaceName)
	if err != nil {
		return nil, errors.Trace(err)
	}
	subnets, err := space.Subnets()
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(subnets) == 0 {
		return nil, errors.Errorf("cannot use space %q as deployment target: no subnets", spaceName)
	}
	subnetsToZones := make(map[string][]string, len(subnets))
	for _, subnet := range subnets {
		warningPrefix := fmt.Sprintf(
			"not using subnet %q in space %q for machine %q provisioning: ",
			subnet.CIDR(), spaceName, m.Id(),
		)
		providerId := subnet.ProviderId()
		if providerId == "" {
			logger.Warningf(warningPrefix + "no ProviderId set")
			continue
		}
		// TODO(dimitern): Once state.Subnet supports multiple zones,
		// use all of them below.
		//
		// LKK Card: https://canonical.leankit.com/Boards/View/101652562/119979611
		zone := subnet.AvailabilityZone()
		if zone == "" {
			logger.Warningf(warningPrefix + "no availability zone(s) set")
			continue
		}
		subnetsToZones[string(providerId)] = []string{zone}
	}
	return subnetsToZones, nil
}

func (p *ProvisionerAPI) machineEndpointBindings(m *state.Machine) (map[string]string, error) {
	units, err := m.Units()
	if err != nil {
		return nil, errors.Trace(err)
	}

	spacesNamesToProviderIds, err := p.allSpaceNamesToProviderIds()
	if err != nil {
		return nil, errors.Trace(err)
	}

	var combinedBindings map[string]string
	processedServicesSet := set.NewStrings()
	for _, unit := range units {
		if !unit.IsPrincipal() {
			continue
		}
		service, err := unit.Application()
		if err != nil {
			return nil, err
		}
		if processedServicesSet.Contains(service.Name()) {
			// Already processed, skip it.
			continue
		}
		bindings, err := service.EndpointBindings()
		if err != nil {
			return nil, err
		}
		processedServicesSet.Add(service.Name())

		if len(bindings) == 0 {
			continue
		}
		if combinedBindings == nil {
			combinedBindings = make(map[string]string)
		}

		for endpoint, spaceName := range bindings {
			if spaceName == "" {
				// Skip unspecified bindings, as they won't affect the instance
				// selected for provisioning.
				continue
			}

			spaceProviderId, nameKnown := spacesNamesToProviderIds[spaceName]
			if nameKnown {
				combinedBindings[endpoint] = spaceProviderId
			} else {
				// Technically, this can't happen in practice, as we're
				// validating the bindings during service deployment.
				return nil, errors.Errorf("unknown space %q with no provider ID specified for endpoint %q", spaceName, endpoint)
			}
		}
	}
	return combinedBindings, nil
}

func (p *ProvisionerAPI) allSpaceNamesToProviderIds() (map[string]string, error) {
	allSpaces, err := p.st.AllSpaces()
	if err != nil {
		return nil, errors.Annotate(err, "getting all spaces")
	}

	namesToProviderIds := make(map[string]string, len(allSpaces))
	for _, space := range allSpaces {
		name := space.Name()

		// For providers without native support for spaces, use the name instead
		// as provider ID.
		providerId := string(space.ProviderId())
		if len(providerId) == 0 {
			providerId = name
		}

		namesToProviderIds[name] = providerId
	}

	return namesToProviderIds, nil
}

// availableImageMetadata returns all image metadata available to this machine
// or an error fetching them.
func (p *ProvisionerAPI) availableImageMetadata(m *state.Machine) ([]params.CloudImageMetadata, error) {
	imageConstraint, env, err := p.constructImageConstraint(m)
	if err != nil {
		return nil, errors.Annotate(err, "could not construct image constraint")
	}

	// Look for image metadata in state.
	data, err := p.findImageMetadata(imageConstraint, env)
	if err != nil {
		return nil, err
	}
	sort.Sort(metadataList(data))
	logger.Debugf("available image metadata for provisioning: %v", data)
	return data, nil
}

// constructImageConstraint returns model-specific criteria used to look for image metadata.
func (p *ProvisionerAPI) constructImageConstraint(m *state.Machine) (*imagemetadata.ImageConstraint, environs.Environ, error) {
	// If we can determine current region,
	// we want only metadata specific to this region.
	cloud, env, err := p.obtainEnvCloudConfig()
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	lookup := simplestreams.LookupParams{
		Series: []string{m.Series()},
		Stream: env.Config().ImageStream(),
	}

	mcons, err := m.Constraints()
	if err != nil {
		return nil, nil, errors.Annotatef(err, "cannot get machine constraints for machine %v", m.MachineTag().Id())
	}

	if mcons.Arch != nil {
		lookup.Arches = []string{*mcons.Arch}
	}
	if cloud != nil {
		lookup.CloudSpec = *cloud
	}

	return imagemetadata.NewImageConstraint(lookup), env, nil
}

// obtainEnvCloudConfig returns environment specific cloud information
// to be used in search for compatible images and their metadata.
func (p *ProvisionerAPI) obtainEnvCloudConfig() (*simplestreams.CloudSpec, environs.Environ, error) {
	env, err := environs.GetEnviron(p.configGetter, environs.New)
	if err != nil {
		return nil, nil, errors.Annotate(err, "could not get model")
	}

	if inst, ok := env.(simplestreams.HasRegion); ok {
		cloud, err := inst.Region()
		if err != nil {
			// can't really find images if we cannot determine cloud region
			// TODO (anastasiamac 2015-12-03) or can we?
			return nil, nil, errors.Annotate(err, "getting provider region information (cloud spec)")
		}
		return &cloud, env, nil
	}
	return nil, env, nil
}

// findImageMetadata returns all image metadata or an error fetching them.
// It looks for image metadata in state.
// If none are found, we fall back on original image search in simple streams.
func (p *ProvisionerAPI) findImageMetadata(imageConstraint *imagemetadata.ImageConstraint, env environs.Environ) ([]params.CloudImageMetadata, error) {
	// Look for image metadata in state.
	stateMetadata, err := p.imageMetadataFromState(imageConstraint)
	if err != nil && !errors.IsNotFound(err) {
		// look into simple stream if for some reason can't get from controller,
		// so do not exit on error.
		logger.Infof("could not get image metadata from controller: %v", err)
	}
	logger.Debugf("got from controller %d metadata", len(stateMetadata))
	// No need to look in data sources if found in state.
	if len(stateMetadata) != 0 {
		return stateMetadata, nil
	}

	// If no metadata is found in state, fall back to original simple stream search.
	// Currently, an image metadata worker picks up this metadata periodically (daily),
	// and stores it in state. So potentially, this collection could be different
	// to what is in state.
	dsMetadata, err := p.imageMetadataFromDataSources(env, imageConstraint)
	if err != nil {
		if !errors.IsNotFound(err) {
			return nil, errors.Trace(err)
		}
	}
	logger.Debugf("got from data sources %d metadata", len(dsMetadata))

	return dsMetadata, nil
}

// imageMetadataFromState returns image metadata stored in state
// that matches given criteria.
func (p *ProvisionerAPI) imageMetadataFromState(constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
	filter := cloudimagemetadata.MetadataFilter{
		Series: constraint.Series,
		Arches: constraint.Arches,
		Region: constraint.Region,
		Stream: constraint.Stream,
	}
	stored, err := p.st.CloudImageMetadataStorage.FindMetadata(filter)
	if err != nil {
		return nil, errors.Trace(err)
	}

	toParams := func(m cloudimagemetadata.Metadata) params.CloudImageMetadata {
		return params.CloudImageMetadata{
			ImageId:         m.ImageId,
			Stream:          m.Stream,
			Region:          m.Region,
			Version:         m.Version,
			Series:          m.Series,
			Arch:            m.Arch,
			VirtType:        m.VirtType,
			RootStorageType: m.RootStorageType,
			RootStorageSize: m.RootStorageSize,
			Source:          m.Source,
			Priority:        m.Priority,
		}
	}

	var all []params.CloudImageMetadata
	for _, ms := range stored {
		for _, m := range ms {
			all = append(all, toParams(m))
		}
	}
	return all, nil
}

// imageMetadataFromDataSources finds image metadata that match specified criteria in existing data sources.
func (p *ProvisionerAPI) imageMetadataFromDataSources(env environs.Environ, constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
	sources, err := environs.ImageMetadataSources(env)
	if err != nil {
		return nil, err
	}

	getStream := func(current string) string {
		if current == "" {
			if constraint.Stream != "" {
				return constraint.Stream
			}
			return env.Config().ImageStream()
		}
		return current
	}

	toModel := func(m *imagemetadata.ImageMetadata, mStream string, mSeries string, source string, priority int) cloudimagemetadata.Metadata {

		return cloudimagemetadata.Metadata{
			cloudimagemetadata.MetadataAttributes{
				Region:          m.RegionName,
				Arch:            m.Arch,
				VirtType:        m.VirtType,
				RootStorageType: m.Storage,
				Source:          source,
				Series:          mSeries,
				Stream:          mStream,
			},
			priority,
			m.Id,
		}
	}

	var metadataState []cloudimagemetadata.Metadata
	for _, source := range sources {
		logger.Debugf("looking in data source %v", source.Description())
		found, info, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, constraint)
		if err != nil {
			// Do not stop looking in other data sources if there is an issue here.
			logger.Warningf("encountered %v while getting published images metadata from %v", err, source.Description())
			continue
		}
		for _, m := range found {
			mSeries, err := series.VersionSeries(m.Version)
			if err != nil {
				logger.Warningf("could not determine series for image id %s: %v", m.Id, err)
				continue
			}
			mStream := getStream(m.Stream)
			metadataState = append(metadataState, toModel(m, mStream, mSeries, info.Source, source.Priority()))
		}
	}
	if len(metadataState) > 0 {
		if err := p.st.CloudImageMetadataStorage.SaveMetadata(metadataState); err != nil {
			// No need to react here, just take note
			logger.Warningf("failed to save published image metadata: %v", err)
		}
	}

	// Since we've fallen through to data sources search and have saved all needed images into controller,
	// let's try to get them from controller to avoid duplication of conversion logic here.
	all, err := p.imageMetadataFromState(constraint)
	if err != nil {
		return nil, errors.Annotate(err, "could not read metadata from controller after saving it there from data sources")
	}

	if len(all) == 0 {
		return nil, errors.NotFoundf("image metadata for series %v, arch %v", constraint.Series, constraint.Arches)
	}

	return all, nil
}

// metadataList is a convenience type enabling to sort
// a collection of CloudImageMetadata in order of priority.
type metadataList []params.CloudImageMetadata

// Implements sort.Interface
func (m metadataList) Len() int {
	return len(m)
}

// Implements sort.Interface and sorts image metadata by priority.
func (m metadataList) Less(i, j int) bool {
	return m[i].Priority < m[j].Priority
}

// Implements sort.Interface
func (m metadataList) Swap(i, j int) {
	m[i], m[j] = m[j], m[i]
}