forked from juju/juju
/
contextfactory.go
354 lines (320 loc) · 10.8 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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package context
import (
"fmt"
"math/rand"
"time"
"github.com/juju/errors"
"github.com/juju/utils/clock"
"gopkg.in/juju/charm.v6-unstable/hooks"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/api/uniter"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/core/leadership"
"github.com/juju/juju/worker/uniter/hook"
"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
// 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 jujuc.Context.
type StorageContextAccessor interface {
// StorageTags returns the tags of storage instances attached to
// the unit.
StorageTags() ([]names.StorageTag, error)
// Storage returns the jujuc.ContextStorageAttachment with the
// supplied tag if it was found, and whether it was found.
Storage(names.StorageTag) (jujuc.ContextStorageAttachment, 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
tracker leadership.Tracker
// Fields that shouldn't change in a factory's lifetime.
paths Paths
modelUUID string
envName string
machineTag names.MachineTag
storage StorageContextAccessor
clock clock.Clock
zone string
// Callback to get relation state snapshot.
getRelationInfos RelationsFunc
relationCaches map[int]*RelationCache
// For generating "unique" context ids.
rand *rand.Rand
}
// NewContextFactory returns a ContextFactory capable of creating execution contexts backed
// by the supplied unit's supplied API connection.
func NewContextFactory(
state *uniter.State,
unitTag names.UnitTag,
tracker leadership.Tracker,
getRelationInfos RelationsFunc,
storage StorageContextAccessor,
paths Paths,
clock clock.Clock,
) (
ContextFactory, error,
) {
unit, err := state.Unit(unitTag)
if err != nil {
return nil, errors.Trace(err)
}
machineTag, err := unit.AssignedMachine()
if err != nil {
return nil, errors.Trace(err)
}
model, err := state.Model()
if err != nil {
return nil, errors.Trace(err)
}
zone, err := unit.AvailabilityZone()
if err != nil {
return nil, errors.Trace(err)
}
f := &contextFactory{
unit: unit,
state: state,
tracker: tracker,
paths: paths,
modelUUID: model.UUID(),
envName: model.Name(),
machineTag: machineTag,
getRelationInfos: getRelationInfos,
relationCaches: map[int]*RelationCache{},
storage: storage,
rand: rand.New(rand.NewSource(time.Now().Unix())),
clock: clock,
zone: zone,
}
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,
)
ctx := &HookContext{
unit: f.unit,
state: f.state,
LeadershipContext: leadershipContext,
uuid: f.modelUUID,
envName: f.envName,
unitName: f.unit.Name(),
assignedMachineTag: f.machineTag,
relations: f.getContextRelations(),
relationId: -1,
pendingPorts: make(map[PortRange]PortRangeInfo),
storage: f.storage,
clock: f.clock,
componentDir: f.paths.ComponentDir,
componentFuncs: registeredComponentFuncs,
availabilityzone: f.zone,
}
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
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)
}
hookName = fmt.Sprintf("%s-%s", relation.Name(), hookInfo.Kind)
}
if hookInfo.Kind.IsStorage() {
ctx.storageTag = names.NewStorageTag(hookInfo.StorageId)
if _, err := ctx.storage.Storage(ctx.storageTag); err != nil {
return nil, errors.Annotatef(err, "could not retrieve storage for id: %v", hookInfo.StorageId)
}
storageName, err := names.StorageName(hookInfo.StorageId)
if err != nil {
return nil, errors.Trace(err)
}
hookName = fmt.Sprintf("%s-%s", storageName, hookName)
}
ctx.id = f.newId(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)
}
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
}
// 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 errors.Trace(err)
ctx.apiAddrs, err = f.state.APIAddresses()
if err != nil {
return err
}
ctx.machinePorts, err = f.state.AllMachinePorts(f.machineTag)
if err != nil {
return errors.Trace(err)
}
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,
}
// 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.proxySettings = modelConfig.ProxySettings()
// Calling these last, because there's a potential race: they're not guaranteed
// to be set in time to be needed for a hook. If they're not, we just leave them
// unset as we always have; this isn't great but it's about behaviour preservation.
ctx.publicAddress, err = f.unit.PublicAddress()
if err != nil && !params.IsCodeNoAddressSet(err) {
return err
}
ctx.privateAddress, err = f.unit.PrivateAddress()
if err != nil && !params.IsCodeNoAddressSet(err) {
return err
}
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)
}