/
contextfactory.go
506 lines (459 loc) · 15.9 KB
/
contextfactory.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
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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package context
import (
"fmt"
"math/rand"
"time"
"github.com/juju/charm/v12/hooks"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v5"
"github.com/juju/juju/api/agent/uniter"
"github.com/juju/juju/core/leadership"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/secrets"
"github.com/juju/juju/rpc/params"
jujusecrets "github.com/juju/juju/secrets"
"github.com/juju/juju/worker/uniter/hook"
"github.com/juju/juju/worker/uniter/runner/context/payloads"
"github.com/juju/juju/worker/uniter/runner/context/resources"
"github.com/juju/juju/worker/uniter/runner/jujuc"
)
// CommandInfo specifies the information necessary to run a command.
type CommandInfo struct {
// RelationId is the relation context to execute the commands in.
RelationId int
// RemoteUnitName is the remote unit for the relation context.
RemoteUnitName string
// TODO(jam): 2019-10-23 Add RemoteApplicationName
// ForceRemoteUnit skips unit inference and existence validation.
ForceRemoteUnit bool
}
// ContextFactory represents a long-lived object that can create execution contexts
// relevant to a specific unit.
type ContextFactory interface {
// CommandContext creates a new context for running a juju command.
CommandContext(commandInfo CommandInfo) (*HookContext, error)
// HookContext creates a new context for running a juju hook.
HookContext(hookInfo hook.Info) (*HookContext, error)
// ActionContext creates a new context for running a juju action.
ActionContext(actionData *ActionData) (*HookContext, error)
}
// StorageContextAccessor is an interface providing access to StorageContexts
// for a hooks.Context.
type StorageContextAccessor interface {
// StorageTags returns the tags of storage instances attached to
// the unit.
StorageTags() ([]names.StorageTag, error)
// Storage returns the hooks.ContextStorageAttachment with the
// supplied tag if it was found, and whether it was found.
Storage(names.StorageTag) (jujuc.ContextStorageAttachment, error)
}
// SecretsAccessor is used by the hook context to access the secrets backend.
type SecretsAccessor interface {
// CreateSecretURIs is used by secret-add to get URIs
// for added secrets.
CreateSecretURIs(int) ([]*secrets.URI, error)
// SecretMetadata is used by secrets-get to fetch
// metadata for secrets.
SecretMetadata() ([]secrets.SecretOwnerMetadata, error)
// SecretRotated records the outcome of rotating a secret.
SecretRotated(uri string, oldRevision int) error
}
// SecretsBackendGetter creates a secrets backend client.
type SecretsBackendGetter func() (jujusecrets.BackendsClient, error)
// RelationsFunc is used to get snapshots of relation membership at context
// creation time.
type RelationsFunc func() map[int]*RelationInfo
type contextFactory struct {
// API connection fields; unit should be deprecated, but isn't yet.
unit *uniter.Unit
state *uniter.State
resources *uniter.ResourcesFacadeClient
payloads *uniter.PayloadFacadeClient
secretsClient SecretsAccessor
secretsBackendGetter SecretsBackendGetter
tracker leadership.Tracker
logger loggo.Logger
// Fields that shouldn't change in a factory's lifetime.
paths Paths
modelUUID string
modelName string
modelType model.ModelType
machineTag names.MachineTag
clock Clock
zone string
principal string
// Callback to get relation state snapshot.
getRelationInfos RelationsFunc
relationCaches map[int]*RelationCache
// For generating "unique" context ids.
rand *rand.Rand
}
// FactoryConfig contains configuration values
// for the context factory.
type FactoryConfig struct {
State *uniter.State
SecretsClient SecretsAccessor
SecretsBackendGetter SecretsBackendGetter
Unit *uniter.Unit
Resources *uniter.ResourcesFacadeClient
Payloads *uniter.PayloadFacadeClient
Tracker leadership.Tracker
GetRelationInfos RelationsFunc
Paths Paths
Clock Clock
Logger loggo.Logger
}
// NewContextFactory returns a ContextFactory capable of creating execution contexts backed
// by the supplied unit's supplied API connection.
func NewContextFactory(config FactoryConfig) (ContextFactory, error) {
m, err := config.State.Model()
if err != nil {
return nil, errors.Trace(err)
}
var (
machineTag names.MachineTag
zone string
)
if m.ModelType == model.IAAS {
machineTag, err = config.Unit.AssignedMachine()
if err != nil {
return nil, errors.Trace(err)
}
zone, err = config.Unit.AvailabilityZone()
if err != nil {
return nil, errors.Trace(err)
}
}
principal, ok, err := config.Unit.PrincipalName()
if err != nil {
return nil, errors.Trace(err)
} else if !ok {
principal = ""
}
f := &contextFactory{
unit: config.Unit,
state: config.State,
resources: config.Resources,
payloads: config.Payloads,
secretsClient: config.SecretsClient,
secretsBackendGetter: config.SecretsBackendGetter,
tracker: config.Tracker,
logger: config.Logger,
paths: config.Paths,
modelUUID: m.UUID,
modelName: m.Name,
machineTag: machineTag,
getRelationInfos: config.GetRelationInfos,
relationCaches: map[int]*RelationCache{},
rand: rand.New(rand.NewSource(time.Now().Unix())),
clock: config.Clock,
zone: zone,
principal: principal,
modelType: m.ModelType,
}
return f, nil
}
// newId returns a probably-unique identifier for a new context, containing the
// supplied string.
func (f *contextFactory) newId(name string) string {
return fmt.Sprintf("%s-%s-%d", f.unit.Name(), name, f.rand.Int63())
}
// coreContext creates a new context with all unspecialised fields filled in.
func (f *contextFactory) coreContext() (*HookContext, error) {
leadershipContext := newLeadershipContext(
f.state.LeadershipSettings,
f.tracker,
f.unit.Name(),
)
ctx := &HookContext{
unit: f.unit,
state: f.state,
secretsClient: f.secretsClient,
secretsBackendGetter: f.secretsBackendGetter,
LeadershipContext: leadershipContext,
uuid: f.modelUUID,
modelName: f.modelName,
modelType: f.modelType,
unitName: f.unit.Name(),
assignedMachineTag: f.machineTag,
relations: f.getContextRelations(),
relationId: -1,
clock: f.clock,
logger: f.logger,
availabilityZone: f.zone,
principal: f.principal,
ResourcesHookContext: &resources.ResourcesHookContext{
Client: f.resources,
ResourcesDir: f.paths.GetResourcesDir(),
Logger: f.logger,
},
storageAttachmentCache: make(map[names.StorageTag]jujuc.ContextStorageAttachment),
}
payloadCtx, err := payloads.NewContext(f.payloads)
if err != nil {
return nil, err
}
ctx.PayloadsHookContext = payloadCtx
if err := f.updateContext(ctx); err != nil {
return nil, err
}
return ctx, nil
}
// ActionContext is part of the ContextFactory interface.
func (f *contextFactory) ActionContext(actionData *ActionData) (*HookContext, error) {
if actionData == nil {
return nil, errors.New("nil actionData specified")
}
ctx, err := f.coreContext()
if err != nil {
return nil, errors.Trace(err)
}
ctx.actionData = actionData
ctx.id = f.newId(actionData.Name)
return ctx, nil
}
// HookContext is part of the ContextFactory interface.
func (f *contextFactory) HookContext(hookInfo hook.Info) (*HookContext, error) {
ctx, err := f.coreContext()
if err != nil {
return nil, errors.Trace(err)
}
hookName := string(hookInfo.Kind)
if hookInfo.Kind.IsRelation() {
ctx.relationId = hookInfo.RelationId
ctx.remoteUnitName = hookInfo.RemoteUnit
ctx.remoteApplicationName = hookInfo.RemoteApplication
ctx.departingUnitName = hookInfo.DepartingUnit
relation, found := ctx.relations[hookInfo.RelationId]
if !found {
return nil, errors.Errorf("unknown relation id: %v", hookInfo.RelationId)
}
if hookInfo.Kind == hooks.RelationDeparted {
relation.cache.RemoveMember(hookInfo.RemoteUnit)
} else if hookInfo.RemoteUnit != "" {
// Clear remote settings cache for changing remote unit.
relation.cache.InvalidateMember(hookInfo.RemoteUnit)
} else if hookInfo.RemoteApplication != "" {
// relation.cache.InvalidateApplication(hookInfo.RemoteApplication)
}
hookName = fmt.Sprintf("%s-%s", relation.Name(), hookInfo.Kind)
}
if hookInfo.Kind.IsStorage() {
ctx.storageTag = names.NewStorageTag(hookInfo.StorageId)
storageName, err := names.StorageName(hookInfo.StorageId)
if err != nil {
return nil, errors.Trace(err)
}
hookName = fmt.Sprintf("%s-%s", storageName, hookName)
// Cache the storage this hook context is for.
_, err = ctx.Storage(ctx.storageTag)
if err != nil && !errors.Is(err, errors.NotProvisioned) {
return nil, errors.Annotatef(err, "could not retrieve storage for id: %v", hookInfo.StorageId)
}
}
if hookInfo.Kind.IsWorkload() {
ctx.workloadName = hookInfo.WorkloadName
hookName = fmt.Sprintf("%s-%s", hookInfo.WorkloadName, hookName)
switch hookInfo.Kind {
case hooks.PebbleCustomNotice:
ctx.noticeID = hookInfo.NoticeID
ctx.noticeType = hookInfo.NoticeType
ctx.noticeKey = hookInfo.NoticeKey
}
}
if hookInfo.Kind == hooks.PreSeriesUpgrade {
ctx.baseUpgradeTarget = hookInfo.MachineUpgradeTarget
}
if hookInfo.Kind.IsSecret() {
ctx.secretURI = hookInfo.SecretURI
ctx.secretLabel = hookInfo.SecretLabel
if hook.SecretHookRequiresRevision(hookInfo.Kind) {
ctx.secretRevision = hookInfo.SecretRevision
}
if ctx.secretLabel == "" {
info, err := ctx.SecretMetadata()
if err != nil {
return nil, errors.Trace(err)
}
uri, err := secrets.ParseURI(ctx.secretURI)
if err != nil {
return nil, errors.Trace(err)
}
md := info[uri.ID]
ctx.secretLabel = md.Label
}
}
ctx.id = f.newId(hookName)
ctx.hookName = hookName
return ctx, nil
}
// CommandContext is part of the ContextFactory interface.
func (f *contextFactory) CommandContext(commandInfo CommandInfo) (*HookContext, error) {
ctx, err := f.coreContext()
if err != nil {
return nil, errors.Trace(err)
}
// TODO(jam): 2019-10-24 Include remoteAppName
relationId, remoteUnitName, err := inferRemoteUnit(ctx.relations, commandInfo)
if err != nil {
return nil, errors.Trace(err)
}
ctx.relationId = relationId
ctx.remoteUnitName = remoteUnitName
ctx.id = f.newId("run-commands")
return ctx, nil
}
// ModelType is part of the ContextFactory interface.
func (f *contextFactory) ModelType() model.ModelType {
return f.modelType
}
// getContextRelations updates the factory's relation caches, and uses them
// to construct ContextRelations for a fresh context.
func (f *contextFactory) getContextRelations() map[int]*ContextRelation {
contextRelations := map[int]*ContextRelation{}
relationInfos := f.getRelationInfos()
relationCaches := map[int]*RelationCache{}
for id, info := range relationInfos {
relationUnit := info.RelationUnit
memberNames := info.MemberNames
cache, found := f.relationCaches[id]
if found {
cache.Prune(memberNames)
} else {
cache = NewRelationCache(relationUnit.ReadSettings, memberNames)
}
relationCaches[id] = cache
contextRelations[id] = NewContextRelation(relationUnit, cache)
}
f.relationCaches = relationCaches
return contextRelations
}
// updateContext fills in all unspecialized fields that require an API call to
// discover.
//
// Approximately *every* line of code in this function represents a bug: ie, some
// piece of information we expose to the charm but which we fail to report changes
// to via hooks. Furthermore, the fact that we make multiple API calls at this
// time, rather than grabbing everything we need in one go, is unforgivably yucky.
func (f *contextFactory) updateContext(ctx *HookContext) (err error) {
defer func() { err = errors.Trace(err) }()
ctx.apiAddrs, err = f.state.APIAddresses()
if err != nil {
return err
}
sla, err := f.state.SLALevel()
if err != nil {
return errors.Annotate(err, "could not retrieve the SLA level")
}
ctx.slaLevel = sla
apiVersion, err := f.state.CloudAPIVersion()
if err != nil {
f.logger.Warningf("could not retrieve the cloud API version: %v", err)
}
ctx.cloudAPIVersion = apiVersion
// TODO(fwereade) 23-10-2014 bug 1384572
// Nothing here should ever be getting the environ config directly.
modelConfig, err := f.state.ModelConfig()
if err != nil {
return err
}
ctx.legacyProxySettings = modelConfig.LegacyProxySettings()
ctx.jujuProxySettings = modelConfig.JujuProxySettings()
statusCode, statusInfo, err := f.unit.MeterStatus()
if err != nil {
return errors.Annotate(err, "could not retrieve meter status for unit")
}
ctx.meterStatus = &meterStatus{
code: statusCode,
info: statusInfo,
}
var machPortRanges map[names.UnitTag]network.GroupedPortRanges
var appPortRanges map[names.UnitTag]network.GroupedPortRanges
switch f.modelType {
case model.IAAS:
if machPortRanges, err = f.state.OpenedMachinePortRangesByEndpoint(f.machineTag); err != nil {
return errors.Trace(err)
}
ctx.privateAddress, err = f.unit.PrivateAddress()
if err != nil && !params.IsCodeNoAddressSet(err) {
f.logger.Warningf("cannot get legacy private address for %v: %v", f.unit.Name(), err)
}
case model.CAAS:
if appPortRanges, err = f.state.OpenedPortRangesByEndpoint(); err != nil && !errors.Is(err, errors.NotSupported) {
return errors.Trace(err)
}
}
ctx.portRangeChanges = newPortRangeChangeRecorder(ctx.logger, f.unit.Tag(), f.modelType, machPortRanges, appPortRanges)
ctx.secretChanges = newSecretsChangeRecorder(ctx.logger)
info, err := ctx.secretsClient.SecretMetadata()
if err != nil {
return err
}
ctx.secretMetadata = make(map[string]jujuc.SecretMetadata)
for _, v := range info {
md := v.Metadata
ownerTag, err := names.ParseTag(md.OwnerTag)
if err != nil {
return err
}
ctx.secretMetadata[md.URI.ID] = jujuc.SecretMetadata{
Description: md.Description,
Label: md.Label,
Owner: ownerTag,
RotatePolicy: md.RotatePolicy,
LatestRevision: md.LatestRevision,
LatestExpireTime: md.LatestExpireTime,
NextRotateTime: md.NextRotateTime,
Revisions: v.Revisions,
Access: md.Access,
}
}
return nil
}
func inferRemoteUnit(rctxs map[int]*ContextRelation, info CommandInfo) (int, string, error) {
relationId := info.RelationId
hasRelation := relationId != -1
remoteUnit := info.RemoteUnitName
hasRemoteUnit := remoteUnit != ""
// Check baseline sanity of remote unit, if supplied.
if hasRemoteUnit {
if !names.IsValidUnit(remoteUnit) {
return -1, "", errors.Errorf(`invalid remote unit: %s`, remoteUnit)
} else if !hasRelation {
return -1, "", errors.Errorf("remote unit provided without a relation: %s", remoteUnit)
}
}
// Check sanity of relation, if supplied, otherwise easy early return.
if !hasRelation {
return relationId, remoteUnit, nil
}
rctx, found := rctxs[relationId]
if !found {
return -1, "", errors.Errorf("unknown relation id: %d", relationId)
}
// Past basic sanity checks; if forced, accept what we're given.
if info.ForceRemoteUnit {
return relationId, remoteUnit, nil
}
// Infer an appropriate remote unit if we can.
possibles := rctx.UnitNames()
if remoteUnit == "" {
switch len(possibles) {
case 0:
return -1, "", errors.Errorf("cannot infer remote unit in empty relation %d", relationId)
case 1:
return relationId, possibles[0], nil
}
return -1, "", errors.Errorf("ambiguous remote unit; possibilities are %+v", possibles)
}
for _, possible := range possibles {
if remoteUnit == possible {
return relationId, remoteUnit, nil
}
}
return -1, "", errors.Errorf("unknown remote unit %s; possibilities are %+v", remoteUnit, possibles)
}