-
Notifications
You must be signed in to change notification settings - Fork 494
/
unit.go
1040 lines (955 loc) · 31.1 KB
/
unit.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 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package uniter
import (
"github.com/juju/charm/v9"
"github.com/juju/errors"
"github.com/juju/names/v4"
"github.com/juju/juju/api/common"
apiwatcher "github.com/juju/juju/api/watcher"
"github.com/juju/juju/core/life"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
"github.com/juju/juju/core/watcher"
"github.com/juju/juju/rpc/params"
)
// Unit represents a juju unit as seen by a uniter worker.
type Unit struct {
st *State
tag names.UnitTag
life life.Value
resolvedMode params.ResolvedMode
providerID string
}
// Tag returns the unit's tag.
func (u *Unit) Tag() names.UnitTag {
return u.tag
}
// ProviderID returns the provider Id of the unit.
func (u *Unit) ProviderID() string {
return u.providerID
}
// Name returns the name of the unit.
func (u *Unit) Name() string {
return u.tag.Id()
}
// String returns the unit as a string.
func (u *Unit) String() string {
return u.Name()
}
// Life returns the unit's lifecycle value.
func (u *Unit) Life() life.Value {
return u.life
}
// Resolved returns the unit's resolved mode value.
func (u *Unit) Resolved() params.ResolvedMode {
return u.resolvedMode
}
// Refresh updates the cached local copy of the unit's data.
func (u *Unit) Refresh() error {
var results params.UnitRefreshResults
args := params.Entities{
Entities: []params.Entity{
{Tag: u.tag.String()},
},
}
err := u.st.facade.FacadeCall("Refresh", args, &results)
if err != nil {
return errors.Trace(err)
}
if len(results.Results) != 1 {
return errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
// We should be able to use apiserver.common.RestoreError here,
// but because of poor design, it causes import errors.
if params.IsCodeNotFound(result.Error) {
return errors.NewNotFound(result.Error, "")
}
return errors.Trace(result.Error)
}
u.life = result.Life
u.resolvedMode = result.Resolved
u.providerID = result.ProviderID
return nil
}
// SetUnitStatus sets the status of the unit.
func (u *Unit) SetUnitStatus(unitStatus status.Status, info string, data map[string]interface{}) error {
var result params.ErrorResults
args := params.SetStatus{
Entities: []params.EntityStatusArgs{
{Tag: u.tag.String(), Status: unitStatus.String(), Info: info, Data: data},
},
}
err := u.st.facade.FacadeCall("SetUnitStatus", args, &result)
if err != nil {
return errors.Trace(err)
}
return result.OneError()
}
// UnitStatus gets the status details of the unit.
func (u *Unit) UnitStatus() (params.StatusResult, error) {
var results params.StatusResults
args := params.Entities{
Entities: []params.Entity{
{Tag: u.tag.String()},
},
}
err := u.st.facade.FacadeCall("UnitStatus", args, &results)
if err != nil {
return params.StatusResult{}, errors.Trace(err)
}
if len(results.Results) != 1 {
return params.StatusResult{}, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return params.StatusResult{}, result.Error
}
return result, nil
}
// SetAgentStatus sets the status of the unit agent.
func (u *Unit) SetAgentStatus(agentStatus status.Status, info string, data map[string]interface{}) error {
var result params.ErrorResults
args := params.SetStatus{
Entities: []params.EntityStatusArgs{
{Tag: u.tag.String(), Status: agentStatus.String(), Info: info, Data: data},
},
}
err := u.st.facade.FacadeCall("SetAgentStatus", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// AddMetrics adds the metrics for the unit.
func (u *Unit) AddMetrics(metrics []params.Metric) error {
var result params.ErrorResults
args := params.MetricsParams{
Metrics: []params.MetricsParam{{
Tag: u.tag.String(),
Metrics: metrics,
}},
}
err := u.st.facade.FacadeCall("AddMetrics", args, &result)
if err != nil {
return errors.Annotate(err, "unable to add metric")
}
return result.OneError()
}
// AddMetricBatches makes an api call to the uniter requesting it to store metrics batches in state.
func (u *Unit) AddMetricBatches(batches []params.MetricBatch) (map[string]error, error) {
p := params.MetricBatchParams{
Batches: make([]params.MetricBatchParam, len(batches)),
}
batchResults := make(map[string]error, len(batches))
for i, batch := range batches {
p.Batches[i].Tag = u.tag.String()
p.Batches[i].Batch = batch
batchResults[batch.UUID] = nil
}
results := new(params.ErrorResults)
err := u.st.facade.FacadeCall("AddMetricBatches", p, results)
if err != nil {
return nil, errors.Annotate(err, "failed to send metric batches")
}
for i, result := range results.Results {
batchResults[batches[i].UUID] = result.Error
}
return batchResults, nil
}
// EnsureDead sets the unit lifecycle to Dead if it is Alive or
// Dying. It does nothing otherwise.
func (u *Unit) EnsureDead() error {
var result params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("EnsureDead", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// Watch returns a watcher for observing changes to the unit.
func (u *Unit) Watch() (watcher.NotifyWatcher, error) {
return common.Watch(u.st.facade, "Watch", u.tag)
}
// WatchRelations returns a StringsWatcher that notifies of changes to
// the lifecycles of relations involving u.
func (u *Unit) WatchRelations() (watcher.StringsWatcher, error) {
var results params.StringsWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("WatchUnitRelations", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewStringsWatcher(u.st.facade.RawAPICaller(), result)
return w, nil
}
// Application returns the unit's application.
func (u *Unit) Application() (*Application, error) {
application := &Application{
st: u.st,
tag: u.ApplicationTag(),
}
// Call Refresh() immediately to get the up-to-date
// life and other needed locally cached fields.
err := application.Refresh()
if err != nil {
return nil, err
}
return application, nil
}
// ConfigSettings returns the complete set of application charm config settings
// available to the unit. Unset values will be replaced with the default
// value for the associated option, and may thus be nil when no default is
// specified.
func (u *Unit) ConfigSettings() (charm.Settings, error) {
var results params.ConfigSettingsResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("ConfigSettings", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
return charm.Settings(result.Settings), nil
}
// ApplicationName returns the application name.
func (u *Unit) ApplicationName() string {
application, err := names.UnitApplication(u.Name())
if err != nil {
panic(err)
}
return application
}
// ApplicationTag returns the application tag.
func (u *Unit) ApplicationTag() names.ApplicationTag {
return names.NewApplicationTag(u.ApplicationName())
}
// Destroy, when called on a Alive unit, advances its lifecycle as far as
// possible; it otherwise has no effect. In most situations, the unit's
// life is just set to Dying; but if a principal unit that is not assigned
// to a provisioned machine is Destroyed, it will be removed from state
// directly.
func (u *Unit) Destroy() error {
var result params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("Destroy", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// DestroyAllSubordinates destroys all subordinates of the unit.
func (u *Unit) DestroyAllSubordinates() error {
var result params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("DestroyAllSubordinates", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// AssignedMachine returns the unit's assigned machine tag or an error
// satisfying params.IsCodeNotAssigned when the unit has no assigned
// machine..
func (u *Unit) AssignedMachine() (names.MachineTag, error) {
var invalidTag names.MachineTag
var results params.StringResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("AssignedMachine", args, &results)
if err != nil {
return invalidTag, err
}
if len(results.Results) != 1 {
return invalidTag, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return invalidTag, result.Error
}
return names.ParseMachineTag(result.Result)
}
// PrincipalName returns the principal unit name and true for subordinates.
// For principal units the function returns "" and false.
//
// NOTE: This differs from state.Unit.PrincipalName() by returning an
// error as well, because it needs to make an API call.
func (u *Unit) PrincipalName() (string, bool, error) {
var results params.StringBoolResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("GetPrincipal", args, &results)
if err != nil {
return "", false, err
}
if len(results.Results) != 1 {
return "", false, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return "", false, result.Error
}
var unitName string
if result.Ok {
unitTag, err := names.ParseUnitTag(result.Result)
if err != nil {
return "", false, err
}
unitName = unitTag.Id()
}
return unitName, result.Ok, nil
}
// HasSubordinates returns the tags of any subordinate units.
func (u *Unit) HasSubordinates() (bool, error) {
var results params.BoolResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("HasSubordinates", args, &results)
if err != nil {
return false, err
}
if len(results.Results) != 1 {
return false, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return false, result.Error
}
return result.Result, nil
}
// PublicAddress returns the public address of the unit and whether it
// is valid.
//
// NOTE: This differs from state.Unit.PublicAddres() by returning
// an error instead of a bool, because it needs to make an API call.
//
// TODO(dimitern): We might be able to drop this, once we have machine
// addresses implemented fully. See also LP bug 1221798.
func (u *Unit) PublicAddress() (string, error) {
var results params.StringResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("PublicAddress", args, &results)
if err != nil {
return "", err
}
if len(results.Results) != 1 {
return "", errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return "", result.Error
}
return result.Result, nil
}
// PrivateAddress returns the private address of the unit and whether
// it is valid.
//
// NOTE: This differs from state.Unit.PrivateAddress() by returning
// an error instead of a bool, because it needs to make an API call.
//
// TODO(dimitern): We might be able to drop this, once we have machine
// addresses implemented fully. See also LP bug 1221798.
func (u *Unit) PrivateAddress() (string, error) {
var results params.StringResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("PrivateAddress", args, &results)
if err != nil {
return "", err
}
if len(results.Results) != 1 {
return "", errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return "", result.Error
}
return result.Result, nil
}
// AvailabilityZone returns the availability zone of the unit.
func (u *Unit) AvailabilityZone() (string, error) {
var results params.StringResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
if err := u.st.facade.FacadeCall("AvailabilityZone", args, &results); err != nil {
return "", errors.Trace(err)
}
if len(results.Results) != 1 {
return "", errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return "", errors.Trace(result.Error)
}
return result.Result, nil
}
// OpenPorts sets the policy of the port range with protocol to be
// opened.
func (u *Unit) OpenPorts(protocol string, fromPort, toPort int) error {
var result params.ErrorResults
args := params.EntitiesPortRanges{
Entities: []params.EntityPortRange{{
Tag: u.tag.String(),
Protocol: protocol,
FromPort: fromPort,
ToPort: toPort,
}},
}
err := u.st.facade.FacadeCall("OpenPorts", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// ClosePorts sets the policy of the port range with protocol to be
// closed.
func (u *Unit) ClosePorts(protocol string, fromPort, toPort int) error {
var result params.ErrorResults
args := params.EntitiesPortRanges{
Entities: []params.EntityPortRange{{
Tag: u.tag.String(),
Protocol: protocol,
FromPort: fromPort,
ToPort: toPort,
}},
}
err := u.st.facade.FacadeCall("ClosePorts", args, &result)
if err != nil {
return err
}
return result.OneError()
}
var ErrNoCharmURLSet = errors.New("unit has no charm url set")
// CharmURL returns the charm URL this unit is currently using.
func (u *Unit) CharmURL() (*charm.URL, error) {
var results params.StringBoolResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("CharmURL", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
if result.Result != "" {
curl, err := charm.ParseURL(result.Result)
if err != nil {
return nil, err
}
return curl, nil
}
return nil, ErrNoCharmURLSet
}
// SetCharmURL marks the unit as currently using the supplied charm URL.
// An error will be returned if the unit is dead, or the charm URL not known.
func (u *Unit) SetCharmURL(curl *charm.URL) error {
if curl == nil {
return errors.Errorf("charm URL cannot be nil")
}
var result params.ErrorResults
args := params.EntitiesCharmURL{
Entities: []params.EntityCharmURL{
{Tag: u.tag.String(), CharmURL: curl.String()},
},
}
err := u.st.facade.FacadeCall("SetCharmURL", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// ClearResolved removes any resolved setting on the unit.
func (u *Unit) ClearResolved() error {
var result params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("ClearResolved", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// WatchConfigSettingsHash returns a watcher for observing changes to
// the unit's charm configuration settings (with a hash of the
// settings content so we can determine whether it has changed since
// it was last seen by the uniter). The unit must have a charm URL set
// before this method is called, and the returned watcher will be
// valid only while the unit's charm URL is not changed.
func (u *Unit) WatchConfigSettingsHash() (watcher.StringsWatcher, error) {
return getHashWatcher(u, "WatchConfigSettingsHash")
}
// WatchTrustConfigSettingsHash returns a watcher for observing changes to
// the unit's application configuration settings (with a hash of the
// settings content so we can determine whether it has changed since
// it was last seen by the uniter).
func (u *Unit) WatchTrustConfigSettingsHash() (watcher.StringsWatcher, error) {
return getHashWatcher(u, "WatchTrustConfigSettingsHash")
}
func getHashWatcher(u *Unit, methodName string) (watcher.StringsWatcher, error) {
var results params.StringsWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall(methodName, args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewStringsWatcher(u.st.facade.RawAPICaller(), result)
return w, nil
}
// WatchAddressesHash returns a watcher for observing changes to the
// hash of the unit's addresses.
// For IAAS models, the unit must be assigned to a machine before
// this method is called, and the returned watcher will be valid
// only while the unit's assigned machine is not changed.
// For CAAS models, the watcher observes changes to the address
// of the pod associated with the unit.
func (u *Unit) WatchAddressesHash() (watcher.StringsWatcher, error) {
return getHashWatcher(u, "WatchUnitAddressesHash")
}
// WatchActionNotifications returns a StringsWatcher for observing the
// ids of Actions added to the Unit. The initial event will contain the
// ids of any Actions pending at the time the Watcher is made.
func (u *Unit) WatchActionNotifications() (watcher.StringsWatcher, error) {
var results params.StringsWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("WatchActionNotifications", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewStringsWatcher(u.st.facade.RawAPICaller(), result)
return w, nil
}
// WatchUpgradeSeriesNotifications returns a NotifyWatcher for observing the
// state of a series upgrade.
func (u *Unit) WatchUpgradeSeriesNotifications() (watcher.NotifyWatcher, error) {
return u.st.WatchUpgradeSeriesNotifications()
}
// LogActionMessage logs a progress message for the specified action.
func (u *Unit) LogActionMessage(tag names.ActionTag, message string) error {
var result params.ErrorResults
args := params.ActionMessageParams{
Messages: []params.EntityString{{Tag: tag.String(), Value: message}},
}
err := u.st.facade.FacadeCall("LogActionsMessages", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// UpgradeSeriesStatus returns the upgrade series status of a unit from remote state
func (u *Unit) UpgradeSeriesStatus() (model.UpgradeSeriesStatus, string, error) {
return u.st.UpgradeSeriesUnitStatus()
}
// SetUpgradeSeriesStatus sets the upgrade series status of the unit in the remote state
func (u *Unit) SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, reason string) error {
return u.st.SetUpgradeSeriesUnitStatus(status, reason)
}
// RequestReboot sets the reboot flag for its machine agent
func (u *Unit) RequestReboot() error {
machineId, err := u.AssignedMachine()
if err != nil {
return err
}
var result params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: machineId.String()}},
}
err = u.st.facade.FacadeCall("RequestReboot", args, &result)
if err != nil {
return err
}
return result.OneError()
}
// RelationStatus holds information about a relation's scope and status.
type RelationStatus struct {
// Tag is the relation tag.
Tag names.RelationTag
// Suspended is true if the relation is suspended.
Suspended bool
// InScope is true if the relation unit is in scope.
InScope bool
}
// RelationsStatus returns the tags of the relations the unit has joined
// and entered scope, or the relation is suspended.
func (u *Unit) RelationsStatus() ([]RelationStatus, error) {
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
var results params.RelationUnitStatusResults
err := u.st.facade.FacadeCall("RelationsStatus", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
var statusResult []RelationStatus
for _, result := range result.RelationResults {
tag, err := names.ParseRelationTag(result.RelationTag)
if err != nil {
return nil, err
}
statusResult = append(statusResult, RelationStatus{
Tag: tag,
InScope: result.InScope,
Suspended: result.Suspended,
})
}
return statusResult, nil
}
// MeterStatus returns the meter status of the unit.
func (u *Unit) MeterStatus() (statusCode, statusInfo string, rErr error) {
var results params.MeterStatusResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("GetMeterStatus", args, &results)
if err != nil {
return "", "", errors.Trace(err)
}
if len(results.Results) != 1 {
return "", "", errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return "", "", errors.Trace(result.Error)
}
return result.Code, result.Info, nil
}
// WatchMeterStatus returns a watcher for observing changes to the
// unit's meter status.
func (u *Unit) WatchMeterStatus() (watcher.NotifyWatcher, error) {
var results params.NotifyWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("WatchMeterStatus", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewNotifyWatcher(u.st.facade.RawAPICaller(), result)
return w, nil
}
// WatchStorage returns a watcher for observing changes to the
// unit's storage attachments.
func (u *Unit) WatchStorage() (watcher.StringsWatcher, error) {
return u.st.WatchUnitStorageAttachments(u.tag)
}
// WatchInstanceData returns a watcher for observing changes to the
// instanceData of the unit's machine. Primarily used for watching
// LXDProfile changes.
func (u *Unit) WatchInstanceData() (watcher.NotifyWatcher, error) {
var results params.NotifyWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("WatchInstanceData", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewNotifyWatcher(u.st.facade.RawAPICaller(), result)
return w, nil
}
// LXDProfileName returns the name of the lxd profile applied to the unit's
// machine for the current charm version.
func (u *Unit) LXDProfileName() (string, error) {
var results params.StringResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("LXDProfileName", args, &results)
if err != nil {
return "", err
}
if len(results.Results) != 1 {
return "", errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return "", result.Error
}
return result.Result, nil
}
// CanApplyLXDProfile returns true if an lxd profile can be applied to
// this unit, e.g. this is an lxd machine or container and not maunal
func (u *Unit) CanApplyLXDProfile() (bool, error) {
var results params.BoolResults
args := params.Entities{
Entities: []params.Entity{{Tag: u.tag.String()}},
}
err := u.st.facade.FacadeCall("CanApplyLXDProfile", args, &results)
if err != nil {
return false, err
}
if len(results.Results) != 1 {
return false, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return false, result.Error
}
return result.Result, nil
}
// AddStorage adds desired storage instances to a unit.
func (u *Unit) AddStorage(constraints map[string][]params.StorageConstraints) error {
all := make([]params.StorageAddParams, 0, len(constraints))
for storage, cons := range constraints {
for _, one := range cons {
all = append(all, params.StorageAddParams{
UnitTag: u.Tag().String(),
StorageName: storage,
Constraints: one,
})
}
}
args := params.StoragesAddParams{Storages: all}
var results params.ErrorResults
err := u.st.facade.FacadeCall("AddUnitStorage", args, &results)
if err != nil {
return err
}
return results.Combine()
}
// NetworkInfo returns network interfaces/addresses for specified bindings.
func (u *Unit) NetworkInfo(bindings []string, relationId *int) (map[string]params.NetworkInfoResult, error) {
var results params.NetworkInfoResults
args := params.NetworkInfoParams{
Unit: u.tag.String(),
Endpoints: bindings,
RelationId: relationId,
}
err := u.st.facade.FacadeCall("NetworkInfo", args, &results)
if err != nil {
return nil, errors.Trace(err)
}
return results.Results, nil
}
// State returns the state persisted by the charm running in this unit
// and the state internal to the uniter for this unit.
func (u *Unit) State() (params.UnitStateResult, error) {
return u.st.State()
}
// SetState sets the state persisted by the charm running in this unit
// and the state internal to the uniter for this unit.
func (u *Unit) SetState(unitState params.SetUnitStateArg) error {
return u.st.SetState(unitState)
}
// CommitHookChanges batches together all required API calls for applying
// a set of changes after a hook successfully completes and executes them in a
// single transaction.
func (u *Unit) CommitHookChanges(req params.CommitHookChangesArgs) error {
var results params.ErrorResults
err := u.st.facade.FacadeCall("CommitHookChanges", req, &results)
if err != nil {
return err
}
// Make sure we correctly decode quota-related errors.
return maybeRestoreQuotaLimitError(results.OneError())
}
// CommitHookParamsBuilder is a helper type for populating the set of
// parameters used to perform a CommitHookChanges API call.
type CommitHookParamsBuilder struct {
arg params.CommitHookChangesArg
}
// NewCommitHookParamsBuilder returns a new builder for assembling the
// parameters for a CommitHookChanges API call.
func NewCommitHookParamsBuilder(unitTag names.UnitTag) *CommitHookParamsBuilder {
return &CommitHookParamsBuilder{
arg: params.CommitHookChangesArg{
Tag: unitTag.String(),
},
}
}
// OpenPortRange records a request to open a particular port range.
func (b *CommitHookParamsBuilder) OpenPortRange(endpoint string, portRange network.PortRange) {
b.arg.OpenPorts = append(b.arg.OpenPorts, params.EntityPortRange{
// The Tag is optional as the call uses the Tag from the
// CommitHookChangesArg; it is included here for consistency.
Tag: b.arg.Tag,
Endpoint: endpoint,
Protocol: portRange.Protocol,
FromPort: portRange.FromPort,
ToPort: portRange.ToPort,
})
}
// ClosePortRange records a request to close a particular port range.
func (b *CommitHookParamsBuilder) ClosePortRange(endpoint string, portRange network.PortRange) {
b.arg.ClosePorts = append(b.arg.ClosePorts, params.EntityPortRange{
// The Tag is optional as the call uses the Tag from the
// CommitHookChangesArg; it is included here for consistency.
Tag: b.arg.Tag,
Endpoint: endpoint,
Protocol: portRange.Protocol,
FromPort: portRange.FromPort,
ToPort: portRange.ToPort,
})
}
// UpdateRelationUnitSettings records a request to update the unit/application
// settings for a relation.
func (b *CommitHookParamsBuilder) UpdateRelationUnitSettings(relName string, unitSettings, appSettings params.Settings) {
b.arg.RelationUnitSettings = append(b.arg.RelationUnitSettings, params.RelationUnitSettings{
Relation: relName,
Unit: b.arg.Tag,
Settings: unitSettings,
ApplicationSettings: appSettings,
})
}
// UpdateNetworkInfo records a request to update the network information
// settings for each joined relation.
func (b *CommitHookParamsBuilder) UpdateNetworkInfo() {
b.arg.UpdateNetworkInfo = true
}
// UpdateCharmState records a request to update the server-persisted charm state.
func (b *CommitHookParamsBuilder) UpdateCharmState(state map[string]string) {
b.arg.SetUnitState = ¶ms.SetUnitStateArg{
// The Tag is optional as the call uses the Tag from the
// CommitHookChangesArg; it is included here for consistency.
Tag: b.arg.Tag,
CharmState: &state,
}
}
// AddStorage records a request for adding storage.
func (b *CommitHookParamsBuilder) AddStorage(constraints map[string][]params.StorageConstraints) {
storageReqs := make([]params.StorageAddParams, 0, len(constraints))
for storage, cons := range constraints {
for _, one := range cons {
storageReqs = append(storageReqs, params.StorageAddParams{
UnitTag: b.arg.Tag,
StorageName: storage,
Constraints: one,
})
}
}
b.arg.AddStorage = storageReqs
}
// SetPodSpec records a request to update the PodSpec for an application.
func (b *CommitHookParamsBuilder) SetPodSpec(appTag names.ApplicationTag, spec *string) {
b.arg.SetPodSpec = ¶ms.PodSpec{
Tag: appTag.String(),
Spec: spec,
}
}
// SetRawK8sSpec records a request to update the PodSpec for an application.
func (b *CommitHookParamsBuilder) SetRawK8sSpec(appTag names.ApplicationTag, spec *string) {
b.arg.SetRawK8sSpec = ¶ms.PodSpec{
Tag: appTag.String(),
Spec: spec,
}
}
// Build assembles the recorded change requests into a CommitHookChangesArgs
// instance that can be passed as an argument to the CommitHookChanges API
// call.
func (b *CommitHookParamsBuilder) Build() (params.CommitHookChangesArgs, int) {
return params.CommitHookChangesArgs{