forked from juju/juju
/
context.go
1459 lines (1273 loc) · 46.8 KB
/
context.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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Package context contains the ContextFactory and Context definitions. Context implements
// runner.Context and is used together with uniter.Runner to run hooks, commands and actions.
package context
import (
"fmt"
"path"
"strings"
"sync"
"time"
"github.com/juju/charm/v9"
"github.com/juju/charm/v9/hooks"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/juju/proxy"
"github.com/DavinZhang/juju/api/base"
"github.com/DavinZhang/juju/api/secretsmanager"
"github.com/DavinZhang/juju/api/uniter"
"github.com/DavinZhang/juju/apiserver/params"
"github.com/DavinZhang/juju/caas"
k8sspecs "github.com/DavinZhang/juju/caas/kubernetes/provider/specs"
"github.com/DavinZhang/juju/core/application"
"github.com/DavinZhang/juju/core/model"
"github.com/DavinZhang/juju/core/network"
"github.com/DavinZhang/juju/core/quota"
coresecrets "github.com/DavinZhang/juju/core/secrets"
"github.com/DavinZhang/juju/core/status"
"github.com/DavinZhang/juju/juju/sockets"
"github.com/DavinZhang/juju/version"
"github.com/DavinZhang/juju/worker/common/charmrunner"
"github.com/DavinZhang/juju/worker/uniter/runner/jujuc"
)
// Logger is here to stop the desire of creating a package level Logger.
// Don't do this, instead use xxx.
type logger interface{}
var _ logger = struct{}{}
// Context exposes hooks.Context, and additional methods needed by Runner.
type Context interface {
jujuc.Context
Id() string
HookVars(
paths Paths,
remote bool,
env Environmenter) ([]string, error)
ActionData() (*ActionData, error)
SetProcess(process HookProcess)
HasExecutionSetUnitStatus() bool
ResetExecutionSetUnitStatus()
ModelType() model.ModelType
Prepare() error
Flush(badge string, failure error) error
GetLogger(module string) loggo.Logger
}
// Paths exposes the paths needed by Context.
type Paths interface {
// GetToolsDir returns the filesystem path to the dirctory containing
// the hook tool symlinks.
GetToolsDir() string
// GetBaseDir returns the filesystem path to the directory in which
// the charm is installed.
GetBaseDir() string
// GetCharmDir returns the filesystem path to the directory in which
// the charm is installed.
GetCharmDir() string
// GetJujucServerSocket returns the path to the socket used by the hook tools
// to communicate back to the executing uniter process. It might be a
// filesystem path, or it might be abstract.
GetJujucServerSocket(remote bool) sockets.Socket
// GetJujucClientSocket returns the path to the socket used by the hook tools
// to communicate back to the executing uniter process. It might be a
// filesystem path, or it might be abstract.
GetJujucClientSocket(remote bool) sockets.Socket
// GetMetricsSpoolDir returns the path to a metrics spool dir, used
// to store metrics recorded during a single hook run.
GetMetricsSpoolDir() string
// ComponentDir returns the filesystem path to the directory
// containing all data files for a component.
ComponentDir(name string) string
}
// Clock defines the methods of the full clock.Clock that are needed here.
type Clock interface {
// After waits for the duration to elapse and then sends the
// current time on the returned channel.
After(time.Duration) <-chan time.Time
}
var ErrIsNotLeader = errors.Errorf("this unit is not the leader")
// ComponentConfig holds all the information related to a hook context
// needed by components.
type ComponentConfig struct {
// UnitName is the name of the unit.
UnitName string
// DataDir is the component's data directory.
DataDir string
// APICaller is the API caller the component may use.
APICaller base.APICaller
}
// ComponentFunc is a factory function for Context components.
type ComponentFunc func(ComponentConfig) (jujuc.ContextComponent, error)
var registeredComponentFuncs = map[string]ComponentFunc{}
// Add the named component factory func to the registry.
func RegisterComponentFunc(name string, f ComponentFunc) error {
if _, ok := registeredComponentFuncs[name]; ok {
return errors.AlreadyExistsf("%s", name)
}
registeredComponentFuncs[name] = f
return nil
}
// meterStatus describes the unit's meter status.
type meterStatus struct {
code string
info string
}
// HookProcess is an interface representing a process running a hook.
type HookProcess interface {
Pid() int
Kill() error
}
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination mocks/hookunit_mock.go github.com/DavinZhang/juju/worker/uniter/runner/context HookUnit
// HookUnit represents the functions needed by a unit in a hook context to
// call into state.
type HookUnit interface {
Application() (*uniter.Application, error)
ApplicationName() string
ConfigSettings() (charm.Settings, error)
LogActionMessage(names.ActionTag, string) error
Name() string
NetworkInfo(bindings []string, relationId *int) (map[string]params.NetworkInfoResult, error)
RequestReboot() error
SetUnitStatus(unitStatus status.Status, info string, data map[string]interface{}) error
SetAgentStatus(agentStatus status.Status, info string, data map[string]interface{}) error
State() (params.UnitStateResult, error)
Tag() names.UnitTag
UnitStatus() (params.StatusResult, error)
UpdateNetworkInfo() error
CommitHookChanges(params.CommitHookChangesArgs) error
}
// HookContext is the implementation of runner.Context.
type HookContext struct {
unit HookUnit
// state is the handle to the uniter State so that HookContext can make
// API calls on the state.
// NOTE: We would like to be rid of the fake-remote-Unit and switch
// over fully to API calls on State. This adds that ability, but we're
// not fully there yet.
state *uniter.State
// secretFacade allows the context to access the secrets backend.
secretFacade *secretsmanager.Client
// LeadershipContext supplies several hooks.Context methods.
LeadershipContext
// principal is the unitName of the principal charm.
principal string
// privateAddress is the cached value of the unit's private
// address.
privateAddress string
// publicAddress is the cached value of the unit's public
// address.
publicAddress string
// availabilityZone is the cached value of the unit's
// availability zone name.
availabilityZone string
// configSettings holds the application configuration.
configSettings charm.Settings
// goalState holds the goal state struct
goalState application.GoalState
// id identifies the context.
id string
hookName string
// actionData contains the values relevant to the run of an Action:
// its tag, its parameters, and its results.
actionData *ActionData
// actionDataMu protects against concurrent access to actionData.
actionDataMu sync.Mutex
// uuid is the universally unique identifier of the environment.
uuid string
// modelName is the human friendly name of the environment.
modelName string
// modelType
modelType model.ModelType
// unitName is the human friendly name of the local unit.
unitName string
// status is the status of the local unit.
status *jujuc.StatusInfo
// relationId identifies the relation for which a relation hook is
// executing. If it is -1, the context is not running a relation hook;
// otherwise, its value must be a valid key into the relations map.
relationId int
// remoteUnitName identifies the changing unit of the executing relation
// hook. It will be empty if the context is not running a relation hook,
// or if it is running a relation-broken hook.
remoteUnitName string
// remoteApplicationName identifies the application name in response to
// relation-set --app.
remoteApplicationName string
// relations contains the context for every relation the unit is a member
// of, keyed on relation id.
relations map[int]*ContextRelation
// departingUnitName identifies the unit that goes away from the relation.
// It is only populated when running a RelationDeparted hook.
departingUnitName string
// apiAddrs contains the API server addresses.
apiAddrs []string
// legacyProxySettings are the current legacy proxy settings
// that the uniter knows about.
legacyProxySettings proxy.Settings
// jujuProxySettings are the current juju proxy settings
// that the uniter knows about.
jujuProxySettings proxy.Settings
// meterStatus is the status of the unit's metering.
meterStatus *meterStatus
// a helper for recording requests to open/close port ranges for this unit.
portRangeChanges *portRangeChangeRecorder
// assignedMachineTag contains the tag of the unit's assigned
// machine.
assignedMachineTag names.MachineTag
// process is the process of the command that is being run in the local context,
// like a juju-exec command or a hook
process HookProcess
// rebootPriority tells us when the hook wants to reboot. If rebootPriority
// is hooks.RebootNow the hook will be killed and requeued.
rebootPriority jujuc.RebootPriority
// storage provides access to the information about storage
// attached to the unit.
storage StorageContextAccessor
// storageId is the tag of the storage instance associated
// with the running hook.
storageTag names.StorageTag
// hasRunSetStatus is true if a call to the status-set was made during the
// invocation of a hook.
// This attribute is persisted to local uniter state at the end of the hook
// execution so that the uniter can ultimately decide if it needs to update
// a charm's workload status, or if the charm has already taken care of it.
hasRunStatusSet bool
// storageAddConstraints is a collection of storage constraints
// keyed on storage name as specified in the charm.
// This collection will be added to the unit on successful
// hook run, so the actual add will happen in a flush.
storageAddConstraints map[string][]params.StorageConstraints
// clock is used for any time operations.
clock Clock
logger loggo.Logger
componentDir func(string) string
componentFuncs map[string]ComponentFunc
// slaLevel contains the current SLA level.
slaLevel string
// The cloud specification
cloudSpec *params.CloudSpec
// The cloud API version, if available.
cloudAPIVersion string
// podSpecYaml is the pending pod spec to be committed.
podSpecYaml *string
// k8sRawSpecYaml is the pending raw k8s spec to be committed.
k8sRawSpecYaml *string
// A cached view of the unit's charm state that gets persisted by juju
// once the context is flushed.
cachedCharmState map[string]string
// A flag that keeps track of whether the unit's state has been mutated.
charmStateCacheDirty bool
// workloadName is the name of the container which the hook is in relation to.
workloadName string
// seriesUpgradeTarget is the series that the unit's machine is to be
// updated to when Juju is issued the `upgrade-series` command.
seriesUpgradeTarget string
// secretURL is the reference to the secret relevant to the hook.
secretURL string
mu sync.Mutex
}
// GetLogger returns a Logger for the specified module.
func (ctx *HookContext) GetLogger(module string) loggo.Logger {
return ctx.logger.Root().Child(module)
}
// GetCharmState returns a copy of the cached charm state.
// Implements jujuc.HookContext.unitCharmStateContext, part of runner.Context.
func (ctx *HookContext) GetCharmState() (map[string]string, error) {
ctx.mu.Lock()
defer ctx.mu.Unlock()
if err := ctx.ensureCharmStateLoaded(); err != nil {
return nil, err
}
if len(ctx.cachedCharmState) == 0 {
return nil, nil
}
retVal := make(map[string]string, len(ctx.cachedCharmState))
for k, v := range ctx.cachedCharmState {
retVal[k] = v
}
return retVal, nil
}
// GetCharmStateValue returns the value of the given key.
// Implements jujuc.HookContext.unitCharmStateContext, part of runner.Context.
func (ctx *HookContext) GetCharmStateValue(key string) (string, error) {
ctx.mu.Lock()
defer ctx.mu.Unlock()
if err := ctx.ensureCharmStateLoaded(); err != nil {
return "", err
}
value, ok := ctx.cachedCharmState[key]
if !ok {
return "", errors.NotFoundf("%q", key)
}
return value, nil
}
// SetCharmStateValue sets the key/value pair provided in the cache.
// Implements jujuc.HookContext.unitCharmStateContext, part of runner.Context.
func (ctx *HookContext) SetCharmStateValue(key, value string) error {
ctx.mu.Lock()
defer ctx.mu.Unlock()
if err := ctx.ensureCharmStateLoaded(); err != nil {
return err
}
// Enforce fixed quota limit for key/value sizes. Performing this check
// as early as possible allows us to provide feedback to charm authors
// who might be tempted to exploit this feature for storing CLOBs/BLOBs.
if err := quota.CheckTupleSize(key, value, quota.MaxCharmStateKeySize, quota.MaxCharmStateValueSize); err != nil {
return errors.Trace(err)
}
curValue, exists := ctx.cachedCharmState[key]
if exists && curValue == value {
return nil // no-op
}
ctx.cachedCharmState[key] = value
ctx.charmStateCacheDirty = true
return nil
}
// DeleteCharmStateValue deletes the key/value pair for the given key from
// the cache.
// Implements jujuc.HookContext.unitCharmStateContext, part of runner.Context.
func (ctx *HookContext) DeleteCharmStateValue(key string) error {
ctx.mu.Lock()
defer ctx.mu.Unlock()
if err := ctx.ensureCharmStateLoaded(); err != nil {
return err
}
if _, exists := ctx.cachedCharmState[key]; !exists {
return nil // no-op
}
delete(ctx.cachedCharmState, key)
ctx.charmStateCacheDirty = true
return nil
}
// ensureCharmStateLoaded retrieves and caches the unit's charm state from the
// controller. The caller of this method must be holding the ctx mutex.
func (ctx *HookContext) ensureCharmStateLoaded() error {
// NOTE: Assuming lock to be held!
if ctx.cachedCharmState != nil {
return nil
}
// Load from controller
var charmState map[string]string
unitState, err := ctx.unit.State()
if err != nil {
return errors.Annotate(err, "loading unit state from database")
}
if unitState.CharmState == nil {
charmState = make(map[string]string)
} else {
charmState = unitState.CharmState
}
ctx.cachedCharmState = charmState
ctx.charmStateCacheDirty = false
return nil
}
// Component returns the ContextComponent with the supplied name if
// it was found.
// Implements jujuc.HookContext.ContextComponents, part of runner.Context.
func (ctx *HookContext) Component(name string) (jujuc.ContextComponent, error) {
compCtxFunc, ok := ctx.componentFuncs[name]
if !ok {
return nil, errors.NotFoundf("context component %q", name)
}
facade := ctx.state.Facade()
config := ComponentConfig{
UnitName: ctx.unit.Name(),
DataDir: ctx.componentDir(name),
APICaller: facade.RawAPICaller(),
}
compCtx, err := compCtxFunc(config)
if err != nil {
return nil, errors.Trace(err)
}
return compCtx, nil
}
// RequestReboot will set the reboot flag to true on the machine agent
// Implements jujuc.HookContext.ContextInstance, part of runner.Context.
func (ctx *HookContext) RequestReboot(priority jujuc.RebootPriority) error {
// Must set reboot priority first, because killing the hook
// process will trigger the completion of the hook. If killing
// the hook fails, then we can reset the priority.
ctx.setRebootPriority(priority)
var err error
if priority == jujuc.RebootNow {
// At this point, the hook should be running
err = ctx.killCharmHook()
}
switch err {
case nil, charmrunner.ErrNoProcess:
// ErrNoProcess almost certainly means we are running in debug hooks
default:
ctx.setRebootPriority(jujuc.RebootSkip)
}
return err
}
func (ctx *HookContext) GetRebootPriority() jujuc.RebootPriority {
ctx.mu.Lock()
defer ctx.mu.Unlock()
return ctx.rebootPriority
}
func (ctx *HookContext) setRebootPriority(priority jujuc.RebootPriority) {
ctx.mu.Lock()
defer ctx.mu.Unlock()
ctx.rebootPriority = priority
}
func (ctx *HookContext) GetProcess() HookProcess {
ctx.mu.Lock()
defer ctx.mu.Unlock()
return ctx.process
}
// SetProcess implements runner.Context.
func (ctx *HookContext) SetProcess(process HookProcess) {
ctx.mu.Lock()
defer ctx.mu.Unlock()
ctx.process = process
}
// Id returns an integer which uniquely identifies the relation.
// Implements jujuc.HookContext.ContextRelation, part of runner.Context.
func (ctx *HookContext) Id() string {
return ctx.id
}
// UnitName returns the executing unit's name.
// UnitName implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) UnitName() string {
return ctx.unitName
}
// ModelType of the context we are running in.
// SetProcess implements runner.Context.
func (ctx *HookContext) ModelType() model.ModelType {
return ctx.modelType
}
// UnitStatus will return the status for the current Unit.
// Implements jujuc.HookContext.ContextStatus, part of runner.Context.
func (ctx *HookContext) UnitStatus() (*jujuc.StatusInfo, error) {
if ctx.status == nil {
var err error
unitStatus, err := ctx.unit.UnitStatus()
if err != nil {
return nil, err
}
ctx.status = &jujuc.StatusInfo{
Status: unitStatus.Status,
Info: unitStatus.Info,
Data: unitStatus.Data,
}
}
return ctx.status, nil
}
// ApplicationStatus returns the status for the application and all the units on
// the application to which this context unit belongs, only if this unit is
// the leader.
// Implements jujuc.HookContext.ContextStatus, part of runner.Context.
func (ctx *HookContext) ApplicationStatus() (jujuc.ApplicationStatusInfo, error) {
var err error
isLeader, err := ctx.IsLeader()
if err != nil {
return jujuc.ApplicationStatusInfo{}, errors.Annotatef(err, "cannot determine leadership")
}
if !isLeader {
return jujuc.ApplicationStatusInfo{}, ErrIsNotLeader
}
app, err := ctx.unit.Application()
if err != nil {
return jujuc.ApplicationStatusInfo{}, errors.Trace(err)
}
appStatus, err := app.Status(ctx.unit.Name())
if err != nil {
return jujuc.ApplicationStatusInfo{}, errors.Trace(err)
}
us := make([]jujuc.StatusInfo, len(appStatus.Units))
i := 0
for t, s := range appStatus.Units {
us[i] = jujuc.StatusInfo{
Tag: t,
Status: s.Status,
Info: s.Info,
Data: s.Data,
}
i++
}
return jujuc.ApplicationStatusInfo{
Application: jujuc.StatusInfo{
Tag: app.Tag().String(),
Status: appStatus.Application.Status,
Info: appStatus.Application.Info,
Data: appStatus.Application.Data,
},
Units: us,
}, nil
}
// SetUnitStatus will set the given status for this unit.
// Implements jujuc.HookContext.ContextStatus, part of runner.Context.
func (ctx *HookContext) SetUnitStatus(unitStatus jujuc.StatusInfo) error {
ctx.hasRunStatusSet = true
ctx.logger.Tracef("[WORKLOAD-STATUS] %s: %s", unitStatus.Status, unitStatus.Info)
return ctx.unit.SetUnitStatus(
status.Status(unitStatus.Status),
unitStatus.Info,
unitStatus.Data,
)
}
// SetAgentStatus will set the given status for this unit's agent.
// Implements jujuc.HookContext.ContextStatus, part of runner.Context.
func (ctx *HookContext) SetAgentStatus(agentStatus jujuc.StatusInfo) error {
ctx.logger.Tracef("[AGENT-STATUS] %s: %s", agentStatus.Status, agentStatus.Info)
return ctx.unit.SetAgentStatus(
status.Status(agentStatus.Status),
agentStatus.Info,
agentStatus.Data,
)
}
// SetApplicationStatus will set the given status to the application to which this
// unit's belong, only if this unit is the leader.
// Implements jujuc.HookContext.ContextStatus, part of runner.Context.
func (ctx *HookContext) SetApplicationStatus(applicationStatus jujuc.StatusInfo) error {
ctx.logger.Tracef("[APPLICATION-STATUS] %s: %s", applicationStatus.Status, applicationStatus.Info)
isLeader, err := ctx.IsLeader()
if err != nil {
return errors.Annotatef(err, "cannot determine leadership")
}
if !isLeader {
return ErrIsNotLeader
}
app, err := ctx.unit.Application()
if err != nil {
return errors.Trace(err)
}
return app.SetStatus(
ctx.unit.Name(),
status.Status(applicationStatus.Status),
applicationStatus.Info,
applicationStatus.Data,
)
}
// HasExecutionSetUnitStatus implements runner.Context.
func (ctx *HookContext) HasExecutionSetUnitStatus() bool {
return ctx.hasRunStatusSet
}
// ResetExecutionSetUnitStatus implements runner.Context.
func (ctx *HookContext) ResetExecutionSetUnitStatus() {
ctx.hasRunStatusSet = false
}
// PublicAddress returns the executing unit's public address or an
// error if it is not available.
// Implements jujuc.HookContext.ContextNetworking, part of runner.Context.
func (ctx *HookContext) PublicAddress() (string, error) {
if ctx.publicAddress == "" {
return "", errors.NotFoundf("public address")
}
return ctx.publicAddress, nil
}
// PrivateAddress returns the executing unit's private address or an
// error if it is not available.
// Implements jujuc.HookContext.ContextNetworking, part of runner.Context.
func (ctx *HookContext) PrivateAddress() (string, error) {
if ctx.privateAddress == "" {
return "", errors.NotFoundf("private address")
}
return ctx.privateAddress, nil
}
// AvailabilityZone returns the executing unit's availability zone or an error
// if it was not found (or is not available).
// Implements jujuc.HookContext.ContextInstance, part of runner.Context.
func (ctx *HookContext) AvailabilityZone() (string, error) {
if ctx.availabilityZone == "" {
return "", errors.NotFoundf("availability zone")
}
return ctx.availabilityZone, nil
}
// StorageTags returns a list of tags for storage instances
// attached to the unit or an error if they are not available.
// Implements jujuc.HookContext.ContextStorage, part of runner.Context.
func (ctx *HookContext) StorageTags() ([]names.StorageTag, error) {
return ctx.storage.StorageTags()
}
// HookStorage returns the storage attachment associated
// the executing hook if it was found, and an error if it
// was not found or is not available.
// Implements jujuc.HookContext.ContextStorage, part of runner.Context.
func (ctx *HookContext) HookStorage() (jujuc.ContextStorageAttachment, error) {
return ctx.Storage(ctx.storageTag)
}
// Storage returns the ContextStorageAttachment with the supplied
// tag if it was found, and an error if it was not found or is not
// available to the context.
// Implements jujuc.HookContext.ContextStorage, part of runner.Context.
func (ctx *HookContext) Storage(tag names.StorageTag) (jujuc.ContextStorageAttachment, error) {
if ctx.storage == nil {
return nil, errors.NotFoundf("storage %s", tag)
}
return ctx.storage.Storage(tag)
}
// AddUnitStorage saves storage constraints in the context.
// Implements jujuc.HookContext.ContextStorage, part of runner.Context.
func (ctx *HookContext) AddUnitStorage(cons map[string]params.StorageConstraints) error {
// All storage constraints are accumulated before context is flushed.
if ctx.storageAddConstraints == nil {
ctx.storageAddConstraints = make(
map[string][]params.StorageConstraints,
len(cons))
}
for storage, newConstraints := range cons {
// Multiple calls for the same storage are accumulated as well.
ctx.storageAddConstraints[storage] = append(
ctx.storageAddConstraints[storage],
newConstraints)
}
return nil
}
// OpenPortRange marks the supplied port range for opening.
// Implements jujuc.HookContext.ContextNetworking, part of runner.Context.
func (ctx *HookContext) OpenPortRange(endpointName string, portRange network.PortRange) error {
return ctx.portRangeChanges.OpenPortRange(endpointName, portRange)
}
// ClosePortRange ensures the supplied port range is closed even when
// the executing unit's application is exposed (unless it is opened
// separately by a co- located unit).
// Implements jujuc.HookContext.ContextNetworking, part of runner.Context.
func (ctx *HookContext) ClosePortRange(endpointName string, portRange network.PortRange) error {
return ctx.portRangeChanges.ClosePortRange(endpointName, portRange)
}
// OpenedPortRanges returns all port ranges currently opened by this
// unit on its assigned machine grouped by endpoint.
// Implements jujuc.HookContext.ContextNetworking, part of runner.Context.
func (ctx *HookContext) OpenedPortRanges() network.GroupedPortRanges {
return ctx.portRangeChanges.OpenedUnitPortRanges()
}
// ConfigSettings returns the current application configuration of the executing unit.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) ConfigSettings() (charm.Settings, error) {
if ctx.configSettings == nil {
var err error
ctx.configSettings, err = ctx.unit.ConfigSettings()
if err != nil {
return nil, err
}
}
result := charm.Settings{}
for name, value := range ctx.configSettings {
result[name] = value
}
return result, nil
}
// GetSecret returns the value of the specified secret.
func (ctx *HookContext) GetSecret(name string) (coresecrets.SecretValue, error) {
v, err := ctx.secretFacade.GetValue(name)
if err != nil {
return nil, err
}
return v, nil
}
// CreateSecret creates a secret with the specified data.
func (ctx *HookContext) CreateSecret(name string, args *jujuc.SecretUpsertArgs) (string, error) {
app, _ := names.UnitApplication(ctx.UnitName())
cfg := coresecrets.NewSecretConfig(coresecrets.AppSnippet, app, name)
cfg.RotateInterval = args.RotateInterval
cfg.Status = args.Status
cfg.Description = args.Description
cfg.Tags = args.Tags
return ctx.secretFacade.Create(cfg, args.Type, args.Value)
}
// UpdateSecret creates a secret with the specified data.
func (ctx *HookContext) UpdateSecret(name string, args *jujuc.SecretUpsertArgs) (string, error) {
app, _ := names.UnitApplication(ctx.UnitName())
cfg := coresecrets.NewSecretConfig(coresecrets.AppSnippet, app, name)
cfg.RotateInterval = args.RotateInterval
cfg.Status = args.Status
cfg.Description = args.Description
cfg.Tags = args.Tags
URL := coresecrets.NewSimpleURL(cfg.Path)
return ctx.secretFacade.Update(URL.ID(), cfg, args.Value)
}
// GrantSecret grants access to a specified secret.
func (ctx *HookContext) GrantSecret(name string, args *jujuc.SecretGrantRevokeArgs) error {
app, _ := names.UnitApplication(ctx.UnitName())
cfg := coresecrets.NewSecretConfig(coresecrets.AppSnippet, app, name)
URL := coresecrets.NewSimpleURL(cfg.Path)
return ctx.secretFacade.Grant(URL.ID(), &secretsmanager.SecretRevokeGrantArgs{
ApplicationName: args.ApplicationName,
UnitName: args.UnitName,
RelationId: args.RelationId,
Role: coresecrets.RoleView,
})
}
// RevokeSecret revokes access to a specified secret.
func (ctx *HookContext) RevokeSecret(name string, args *jujuc.SecretGrantRevokeArgs) error {
app, _ := names.UnitApplication(ctx.UnitName())
cfg := coresecrets.NewSecretConfig(coresecrets.AppSnippet, app, name)
URL := coresecrets.NewSimpleURL(cfg.Path)
return ctx.secretFacade.Revoke(URL.ID(), &secretsmanager.SecretRevokeGrantArgs{
ApplicationName: args.ApplicationName,
UnitName: args.UnitName,
})
}
// GoalState returns the goal state for the current unit.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) GoalState() (*application.GoalState, error) {
var err error
ctx.goalState, err = ctx.state.GoalState()
if err != nil {
return nil, err
}
return &ctx.goalState, nil
}
// SetPodSpec sets the podspec for the unit's application.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) SetPodSpec(specYaml string) error {
isLeader, err := ctx.IsLeader()
if err != nil {
return errors.Annotatef(err, "cannot determine leadership")
}
if !isLeader {
ctx.logger.Errorf("%q is not the leader but is setting application k8s spec", ctx.unitName)
return ErrIsNotLeader
}
_, err = k8sspecs.ParsePodSpec(specYaml)
if err != nil {
return errors.Trace(err)
}
ctx.podSpecYaml = &specYaml
return nil
}
// SetRawK8sSpec sets the raw k8s spec for the unit's application.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) SetRawK8sSpec(specYaml string) error {
isLeader, err := ctx.IsLeader()
if err != nil {
return errors.Annotatef(err, "cannot determine leadership")
}
if !isLeader {
ctx.logger.Errorf("%q is not the leader but is setting application raw k8s spec", ctx.unitName)
return ErrIsNotLeader
}
_, err = k8sspecs.ParseRawK8sSpec(specYaml)
if err != nil {
return errors.Trace(err)
}
ctx.k8sRawSpecYaml = &specYaml
return nil
}
// GetPodSpec returns the k8s spec for the unit's application.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) GetPodSpec() (string, error) {
appName := ctx.unit.ApplicationName()
return ctx.state.GetPodSpec(appName)
}
// GetRawK8sSpec returns the raw k8s spec for the unit's application.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) GetRawK8sSpec() (string, error) {
appName := ctx.unit.ApplicationName()
return ctx.state.GetRawK8sSpec(appName)
}
// CloudSpec return the cloud specification for the running unit's model.
// Implements jujuc.HookContext.ContextUnit, part of runner.Context.
func (ctx *HookContext) CloudSpec() (*params.CloudSpec, error) {
if ctx.modelType == model.CAAS {
return nil, errors.NotSupportedf("credential-get on a %q model", model.CAAS)
}
var err error
ctx.cloudSpec, err = ctx.state.CloudSpec()
if err != nil {
return nil, err
}
return ctx.cloudSpec, nil
}
// ActionParams simply returns the arguments to the Action.
// Implements jujuc.ActionHookContext.actionHookContext, part of runner.Context.
func (ctx *HookContext) ActionParams() (map[string]interface{}, error) {
ctx.actionDataMu.Lock()
defer ctx.actionDataMu.Unlock()
if ctx.actionData == nil {
return nil, errors.New("not running an action")
}
return ctx.actionData.Params, nil
}
// LogActionMessage logs a progress message for the Action.
// Implements jujuc.ActionHookContext.actionHookContext, part of runner.Context.
func (ctx *HookContext) LogActionMessage(message string) error {
ctx.actionDataMu.Lock()
defer ctx.actionDataMu.Unlock()
if ctx.actionData == nil {
return errors.New("not running an action")
}
return ctx.unit.LogActionMessage(ctx.actionData.Tag, message)
}
// SetActionMessage sets a message for the Action, usually an error message.
// Implements jujuc.ActionHookContext.actionHookContext, part of runner.Context.
func (ctx *HookContext) SetActionMessage(message string) error {
ctx.actionDataMu.Lock()
defer ctx.actionDataMu.Unlock()
if ctx.actionData == nil {
return errors.New("not running an action")
}
ctx.actionData.ResultsMessage = message
return nil
}
// SetActionFailed sets the fail state of the action.
// Implements jujuc.ActionHookContext.actionHookContext, part of runner.Context.
func (ctx *HookContext) SetActionFailed() error {
ctx.actionDataMu.Lock()
defer ctx.actionDataMu.Unlock()
if ctx.actionData == nil {
return errors.New("not running an action")
}
ctx.actionData.Failed = true
return nil
}
// UpdateActionResults inserts new values for use with action-set and
// action-fail. The results struct will be delivered to the controller
// upon completion of the Action. It returns an error if not called on an
// Action-containing HookContext.
// Implements jujuc.ActionHookContext.actionHookContext, part of runner.Context.
func (ctx *HookContext) UpdateActionResults(keys []string, value interface{}) error {
ctx.actionDataMu.Lock()
defer ctx.actionDataMu.Unlock()
if ctx.actionData == nil {
return errors.New("not running an action")
}
addValueToMap(keys, value, ctx.actionData.ResultsMap)
return nil
}
// HookRelation returns the ContextRelation associated with the executing
// hook if it was found, or an error if it was not found (or is not available).
// Implements jujuc.RelationHookContext.relationHookContext, part of runner.Context.
func (ctx *HookContext) HookRelation() (jujuc.ContextRelation, error) {
return ctx.Relation(ctx.relationId)
}
// RemoteUnitName returns the name of the remote unit the hook execution
// is associated with if it was found, and an error if it was not found or is not
// available.
// Implements jujuc.RelationHookContext.relationHookContext, part of runner.Context.
func (ctx *HookContext) RemoteUnitName() (string, error) {
if ctx.remoteUnitName == "" {
return "", errors.NotFoundf("remote unit")
}
return ctx.remoteUnitName, nil
}
// RemoteApplicationName returns the name of the remote application the hook execution
// is associated with if it was found, and an error if it was not found or is not
// available.
// Implements jujuc.RelationHookContext.relationHookContext, part of runner.Context.
func (ctx *HookContext) RemoteApplicationName() (string, error) {
if ctx.remoteApplicationName == "" {
return "", errors.NotFoundf("saas application")
}
return ctx.remoteApplicationName, nil
}
// Relation returns the relation with the supplied id if it was found, and
// an error if it was not found or is not available.