/
status.go
1981 lines (1801 loc) · 63.5 KB
/
status.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 client
import (
"sort"
"strings"
"time"
"github.com/juju/charm/v12"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/names/v5"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/common/storagecommon"
apiservererrors "github.com/juju/juju/apiserver/errors"
k8sspecs "github.com/juju/juju/caas/kubernetes/provider/specs"
corebase "github.com/juju/juju/core/base"
"github.com/juju/juju/core/cache"
"github.com/juju/juju/core/container"
"github.com/juju/juju/core/crossmodel"
"github.com/juju/juju/core/life"
"github.com/juju/juju/core/lxdprofile"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
"github.com/juju/juju/rpc/params"
"github.com/juju/juju/state"
)
func agentStatusFromStatusInfo(s []status.StatusInfo, kind status.HistoryKind) []params.DetailedStatus {
result := []params.DetailedStatus{}
for _, v := range s {
result = append(result, params.DetailedStatus{
Status: string(v.Status),
Info: v.Message,
Data: v.Data,
Since: v.Since,
Kind: string(kind),
})
}
return result
}
type byTime []params.DetailedStatus
func (s byTime) Len() int {
return len(s)
}
func (s byTime) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byTime) Less(i, j int) bool {
return s[i].Since.Before(*s[j].Since)
}
// applicationStatusHistory returns status history for the given (remote) application.
func (c *Client) applicationStatusHistory(appTag names.ApplicationTag, filter status.StatusHistoryFilter,
kind status.HistoryKind) ([]params.DetailedStatus, error) {
var (
app status.StatusHistoryGetter
err error
)
if kind == status.KindApplication {
app, err = c.api.stateAccessor.Application(appTag.Name)
} else {
app, err = c.api.stateAccessor.RemoteApplication(appTag.Name)
}
if err != nil {
return nil, errors.Trace(err)
}
sInfo, err := app.StatusHistory(filter)
if err != nil {
return nil, errors.Trace(err)
}
return agentStatusFromStatusInfo(sInfo, kind), nil
}
// unitStatusHistory returns a list of status history entries for unit agents or workloads.
func (c *Client) unitStatusHistory(unitTag names.UnitTag, filter status.StatusHistoryFilter,
kind status.HistoryKind) ([]params.DetailedStatus, error) {
unit, err := c.api.stateAccessor.Unit(unitTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
statuses := []params.DetailedStatus{}
if kind == status.KindUnit || kind == status.KindWorkload {
unitStatuses, err := unit.StatusHistory(filter)
if err != nil {
return nil, errors.Trace(err)
}
statuses = agentStatusFromStatusInfo(unitStatuses, status.KindWorkload)
}
if kind == status.KindUnit || kind == status.KindUnitAgent {
agentStatuses, err := unit.AgentHistory().StatusHistory(filter)
if err != nil {
return nil, errors.Trace(err)
}
statuses = append(statuses, agentStatusFromStatusInfo(agentStatuses, status.KindUnitAgent)...)
}
sort.Sort(byTime(statuses))
if kind == status.KindUnit && filter.Size > 0 {
if len(statuses) > filter.Size {
statuses = statuses[len(statuses)-filter.Size:]
}
}
return statuses, nil
}
// machineStatusHistory returns status history for the given machine.
func (c *Client) machineStatusHistory(machineTag names.MachineTag, filter status.StatusHistoryFilter,
kind status.HistoryKind) ([]params.DetailedStatus, error) {
machine, err := c.api.stateAccessor.Machine(machineTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
var sInfo []status.StatusInfo
if kind == status.KindMachineInstance || kind == status.KindContainerInstance {
sInfo, err = machine.InstanceStatusHistory(filter)
} else {
sInfo, err = machine.StatusHistory(filter)
}
if err != nil {
return nil, errors.Trace(err)
}
return agentStatusFromStatusInfo(sInfo, kind), nil
}
// modelStatusHistory returns status history for the current model.
func (c *Client) modelStatusHistory(filter status.StatusHistoryFilter) ([]params.DetailedStatus, error) {
m, err := c.api.stateAccessor.Model()
if err != nil {
return nil, errors.Annotate(err, "cannot get model")
}
sInfo, err := m.StatusHistory(filter)
if err != nil {
return nil, errors.Trace(err)
}
return agentStatusFromStatusInfo(sInfo, status.KindModel), nil
}
// StatusHistory returns a slice of past statuses for several entities.
func (c *Client) StatusHistory(request params.StatusHistoryRequests) params.StatusHistoryResults {
results := params.StatusHistoryResults{}
// TODO(perrito666) the contents of the loop could be split into
// a oneHistory method for clarity.
for _, request := range request.Requests {
filter := status.StatusHistoryFilter{
Size: request.Filter.Size,
FromDate: request.Filter.Date,
Delta: request.Filter.Delta,
Exclude: set.NewStrings(request.Filter.Exclude...),
}
if err := c.checkCanRead(); err != nil {
history := params.StatusHistoryResult{
Error: apiservererrors.ServerError(err),
}
results.Results = append(results.Results, history)
continue
}
if err := filter.Validate(); err != nil {
history := params.StatusHistoryResult{
Error: apiservererrors.ServerError(errors.Annotate(err, "cannot validate status history filter")),
}
results.Results = append(results.Results, history)
continue
}
var (
err error
hist []params.DetailedStatus
)
kind := status.HistoryKind(request.Kind)
switch kind {
case status.KindModel:
hist, err = c.modelStatusHistory(filter)
case status.KindUnit, status.KindWorkload, status.KindUnitAgent:
var u names.UnitTag
if u, err = names.ParseUnitTag(request.Tag); err == nil {
hist, err = c.unitStatusHistory(u, filter, kind)
}
case status.KindApplication, status.KindSAAS:
var app names.ApplicationTag
if app, err = names.ParseApplicationTag(request.Tag); err == nil {
hist, err = c.applicationStatusHistory(app, filter, kind)
}
default:
var m names.MachineTag
if m, err = names.ParseMachineTag(request.Tag); err == nil {
hist, err = c.machineStatusHistory(m, filter, kind)
}
}
if err == nil {
sort.Sort(byTime(hist))
}
results.Results = append(results.Results,
params.StatusHistoryResult{
History: params.History{Statuses: hist},
Error: apiservererrors.ServerError(errors.Annotatef(err, "fetching status history for %q",
request.Tag)),
})
}
return results
}
// FullStatus gives the information needed for juju status over the api
func (c *ClientV6) FullStatus(args params.StatusParams) (params.FullStatus, error) {
args.IncludeStorage = false
return c.Client.FullStatus(args)
}
// FullStatus gives the information needed for juju status over the api
func (c *Client) FullStatus(args params.StatusParams) (params.FullStatus, error) {
if err := c.checkCanRead(); err != nil {
return params.FullStatus{}, err
}
var noStatus params.FullStatus
var context statusContext
context.cachedModel = c.api.modelCache
m, err := c.api.stateAccessor.Model()
if err != nil {
return noStatus, errors.Annotate(err, "cannot get model")
}
context.presence.Presence = c.api.presence.ModelPresence(m.UUID())
cfg, err := m.Config()
if err != nil {
return noStatus, errors.Annotate(err, "cannot obtain current model config")
}
context.providerType = cfg.Type()
if context.spaceInfos, err = c.api.stateAccessor.AllSpaceInfos(); err != nil {
return noStatus, errors.Annotate(err, "cannot obtain space information")
}
if context.model, err = c.api.state().Model(); err != nil {
return noStatus, errors.Annotate(err, "could not fetch model")
}
if context.status, err = context.model.LoadModelStatus(); err != nil {
return noStatus, errors.Annotate(err, "could not load model status values")
}
if context.allAppsUnitsCharmBindings, err =
fetchAllApplicationsAndUnits(c.api.stateAccessor, context.model, context.spaceInfos); err != nil {
return noStatus, errors.Annotate(err, "could not fetch applications and units")
}
if context.consumerRemoteApplications, err =
fetchConsumerRemoteApplications(c.api.stateAccessor); err != nil {
return noStatus, errors.Annotate(err, "could not fetch remote applications")
}
// Only admins can see offer details.
if err := c.checkIsAdmin(); err == nil {
if context.offers, err =
fetchOffers(c.api.stateAccessor, context.allAppsUnitsCharmBindings.applications); err != nil {
return noStatus, errors.Annotate(err, "could not fetch application offers")
}
}
if err = context.fetchMachines(c.api.stateAccessor); err != nil {
return noStatus, errors.Annotate(err, "could not fetch machines")
}
if err = context.fetchOpenPortRangesForAllMachines(c.api.stateAccessor); err != nil {
return noStatus, errors.Annotate(err, "could not fetch open port ranges")
}
if context.controllerNodes, err = fetchControllerNodes(c.api.stateAccessor); err != nil {
return noStatus, errors.Annotate(err, "could not fetch controller nodes")
}
if len(context.controllerNodes) > 1 {
if primaryHAMachine, err := c.api.stateAccessor.HAPrimaryMachine(); err != nil {
// We do not want to return any errors here as they are all
// non-fatal for this call since we can still
// get FullStatus including machine info even if we could not get HA Primary determined.
// Also on some non-HA setups, i.e. where mongo was not run with --replSet,
// this call will return an error.
logger.Warningf("could not determine if there is a primary HA machine: %v", err)
} else {
context.primaryHAMachine = &primaryHAMachine
}
}
// These may be empty when machines have not finished deployment.
if context.ipAddresses, context.spaces, context.linkLayerDevices, err =
fetchNetworkInterfaces(c.api.stateAccessor, context.spaceInfos); err != nil {
return noStatus, errors.Annotate(err, "could not fetch IP addresses and link layer devices")
}
if context.relations, context.relationsById, err = fetchRelations(c.api.stateAccessor); err != nil {
return noStatus, errors.Annotate(err, "could not fetch relations")
}
if len(context.allAppsUnitsCharmBindings.applications) > 0 {
if context.leaders, err = c.api.leadershipReader.Leaders(); err != nil {
// Leader information is additive for status.
// Given that it comes from Dqlite, which may be subject to
// reconfiguration when mutating the control plane, we would
// rather return as much status as possible over an error.
logger.Warningf("could not determine application leaders: %v", err)
context.leaders = make(map[string]string)
}
}
if context.controllerTimestamp, err = c.api.stateAccessor.ControllerTimestamp(); err != nil {
return noStatus, errors.Annotate(err, "could not fetch controller timestamp")
}
context.branches = fetchBranches(c.api.modelCache)
if args.IncludeStorage {
context.storageInstances, err = c.api.storageAccessor.AllStorageInstances()
if err != nil {
return noStatus, errors.Annotate(err, "cannot list all storage instances")
}
context.filesystems, err = c.api.storageAccessor.AllFilesystems()
if err != nil {
return noStatus, errors.Annotate(err, "cannot list all filesystems")
}
context.volumes, err = c.api.storageAccessor.AllVolumes()
if err != nil {
return noStatus, errors.Annotate(err, "cannot list all volumes")
}
}
if logger.IsTraceEnabled() {
logger.Tracef("Applications: %v", context.allAppsUnitsCharmBindings.applications)
logger.Tracef("Remote applications: %v", context.consumerRemoteApplications)
logger.Tracef("Offers: %v", context.offers)
logger.Tracef("Leaders", context.leaders)
logger.Tracef("Relations: %v", context.relations)
logger.Tracef("StorageInstances: %v", context.storageInstances)
logger.Tracef("Filesystems: %v", context.filesystems)
logger.Tracef("Volumes: %v", context.volumes)
}
if len(args.Patterns) > 0 {
patterns := resolveLeaderUnits(args.Patterns, context.leaders)
predicate := BuildPredicateFor(patterns)
// First, attempt to match machines. Any units on those
// machines are implicitly matched.
matchedMachines := make(set.Strings)
for _, machineList := range context.machines {
for _, m := range machineList {
matches, err := predicate(m)
if err != nil {
return noStatus, errors.Annotate(
err, "could not filter machines",
)
}
if matches {
matchedMachines.Add(m.Id())
}
}
}
// Filter units
matchedApps := set.NewStrings()
matchedUnits := set.NewStrings()
unitChainPredicate := UnitChainPredicateFn(predicate, context.unitByName)
// It's possible that we will discover a unit that matches given filter
// half way through units collection. In that case, it may be that the machine
// for that unit has other applications' units on it that have already been examined
// prior. This means that we may miss these other application(s).
// This behavior has been inconsistent since we get units in a map where
// the order is not guaranteed.
// To cater for this scenario, we need to gather all units
// in a temporary collection keyed on machine to allow for the later
// pass. This fixes situations similar to inconsistencies
// observed in lp#1592872.
machineUnits := map[string][]string{}
for _, unitMap := range context.allAppsUnitsCharmBindings.units {
for name, unit := range unitMap {
machineId, err := unit.AssignedMachineId()
if err != nil {
machineId = ""
} else if matchedMachines.Contains(machineId) {
// Unit is on a matching machine.
matchedApps.Add(unit.ApplicationName())
continue
}
if machineId != "" {
machineUnits[machineId] = append(machineUnits[machineId], unit.ApplicationName())
}
// Always start examining at the top-level. This
// prevents a situation where we filter a subordinate
// before we discover its parent is a match.
if !unit.IsPrincipal() {
continue
} else if matches, err := unitChainPredicate(unit); err != nil {
return noStatus, errors.Annotate(err, "could not filter units")
} else if !matches {
delete(unitMap, name)
continue
}
matchedApps.Add(unit.ApplicationName())
matchedUnits.Add(unit.Name())
matchedUnits = matchedUnits.Union(set.NewStrings(unit.SubordinateNames()...))
if machineId != "" {
matchedMachines.Add(machineId)
}
}
}
for _, m := range matchedMachines.SortedValues() {
for _, a := range machineUnits[m] {
if !matchedApps.Contains(a) {
matchedApps.Add(a)
}
}
}
// Filter applications
for appName, app := range context.allAppsUnitsCharmBindings.applications {
matches, err := predicate(app)
if err != nil {
return noStatus, errors.Annotate(err, "could not filter applications")
}
// There are matched units for this application
// or the application matched the given criteria.
deleted := false
if !matchedApps.Contains(appName) && !matches {
delete(context.allAppsUnitsCharmBindings.applications, appName)
deleted = true
}
// Filter relations:
// Remove relations for applications that were deleted and
// for the applications that did not match the
// given criteria.
if deleted || !matches {
// delete relations for this app
if relations, ok := context.relations[appName]; ok {
for _, r := range relations {
delete(context.relationsById, r.Id())
}
delete(context.relations, appName)
}
}
}
// TODO(wallyworld) - filter remote applications
// Filter machines
for aStatus, machineList := range context.machines {
matched := make([]*state.Machine, 0, len(machineList))
for _, m := range machineList {
machineContainers, err := m.Containers()
if err != nil {
return noStatus, err
}
machineContainersSet := set.NewStrings(machineContainers...)
if matchedMachines.Contains(m.Id()) || !matchedMachines.Intersection(machineContainersSet).IsEmpty() {
// The machine is matched directly, or contains a unit
// or container that matches.
logger.Tracef("machine %s is hosting something.", m.Id())
matched = append(matched, m)
continue
}
}
context.machines[aStatus] = matched
}
// Filter branches
context.branches = filterBranches(context.branches, matchedApps,
matchedUnits.Union(set.NewStrings(args.Patterns...)))
// Filter storage
matchedStorageTags := set.NewStrings()
matchedStorageInstances := []state.StorageInstance{}
for _, storageInstance := range context.storageInstances {
owner, ok := storageInstance.Owner()
if !ok {
continue
}
matched := false
switch tag := owner.(type) {
case names.UnitTag:
matched = matchedUnits.Contains(tag.Id())
case names.ApplicationTag:
matched = matchedApps.Contains(tag.Id())
}
if !matched {
continue
}
matchedStorageInstances = append(matchedStorageInstances, storageInstance)
matchedStorageTags.Add(storageInstance.StorageTag().Id())
}
context.storageInstances = matchedStorageInstances
matchedFilesystems := []state.Filesystem{}
for _, filesystem := range context.filesystems {
storageTag, err := filesystem.Storage()
if errors.Is(err, errors.NotAssigned) {
continue
} else if err != nil {
return noStatus, errors.Trace(err)
}
if matchedStorageTags.Contains(storageTag.Id()) {
matchedFilesystems = append(matchedFilesystems, filesystem)
}
}
context.filesystems = matchedFilesystems
matchedVolumes := []state.Volume{}
for _, volume := range context.volumes {
storageTag, err := volume.StorageInstance()
if errors.Is(err, errors.NotAssigned) {
continue
} else if err != nil {
return noStatus, errors.Trace(err)
}
if matchedStorageTags.Contains(storageTag.Id()) {
matchedVolumes = append(matchedVolumes, volume)
}
}
context.volumes = matchedVolumes
}
modelStatus, err := c.modelStatus()
if err != nil {
return noStatus, errors.Annotate(err, "cannot determine model status")
}
var storageDetails []params.StorageDetails
var filesystemDetails []params.FilesystemDetails
var volumeDetails []params.VolumeDetails
if args.IncludeStorage {
storageDetails, err = context.processStorage(c.api.storageAccessor)
if err != nil {
return noStatus, errors.Annotate(err, "cannot process storage instances")
}
filesystemDetails, err = context.processFilesystems(c.api.storageAccessor)
if err != nil {
return noStatus, errors.Annotate(err, "cannot process filesystems")
}
volumeDetails, err = context.processVolumes(c.api.storageAccessor)
if err != nil {
return noStatus, errors.Annotate(err, "cannot process volumes")
}
}
return params.FullStatus{
Model: modelStatus,
Machines: context.processMachines(),
Applications: context.processApplications(),
RemoteApplications: context.processRemoteApplications(),
Offers: context.processOffers(),
Relations: context.processRelations(),
ControllerTimestamp: context.controllerTimestamp,
Branches: context.processBranches(),
Storage: storageDetails,
Filesystems: filesystemDetails,
Volumes: volumeDetails,
}, nil
}
// resolveLeaderUnits resolves the passed in leader pattern to an existing application leader unit
// and then replaces it inplace in the patterns
func resolveLeaderUnits(patterns []string, leaders map[string]string) []string {
for i, v := range patterns {
if strings.Contains(v, "leader") {
application := strings.Split(v, "/")[0]
unit, ok := leaders[application]
if ok {
patterns[i] = unit
continue
}
}
}
return patterns
}
func filterBranches(ctxBranches map[string]cache.Branch,
matchedApps, matchedForBranches set.Strings) map[string]cache.Branch {
// Filter branches based on matchedApps which contains
// the application name if matching on application or unit.
unmatchedBranches := set.NewStrings()
// Need a combination of the pattern strings and all units
// matched above, both principal and subordinate.
for bName, branch := range ctxBranches {
unmatchedBranches.Add(bName)
for appName, units := range branch.AssignedUnits() {
appMatch := matchedForBranches.Contains(appName)
// if the application is in the pattern, and this
// branch,
contains := matchedApps.Contains(appName)
if contains && appMatch {
unmatchedBranches.Remove(bName)
break
}
// if the application is in this branch, but not
// the pattern, check if any assigned units are in
// the pattern
if contains && !appMatch {
for _, u := range units {
if matchedForBranches.Contains(u) {
unmatchedBranches.Remove(bName)
break
}
}
}
}
}
for _, deleteBranch := range unmatchedBranches.Values() {
delete(ctxBranches, deleteBranch)
}
return ctxBranches
}
// newToolsVersionAvailable will return a string representing a tools
// version only if the latest check is newer than current tools.
func (c *Client) modelStatus() (params.ModelStatusInfo, error) {
var info params.ModelStatusInfo
m, err := c.api.stateAccessor.Model()
if err != nil {
return info, errors.Annotate(err, "cannot get model")
}
info.Name = m.Name()
info.Type = string(m.Type())
info.CloudTag = names.NewCloudTag(m.CloudName()).String()
info.CloudRegion = m.CloudRegion()
cfg, err := m.Config()
if err != nil {
return params.ModelStatusInfo{}, errors.Annotate(err, "cannot obtain current model config")
}
latestVersion := m.LatestToolsVersion()
current, ok := cfg.AgentVersion()
if ok {
info.Version = current.String()
if current.Compare(latestVersion) < 0 {
info.AvailableVersion = latestVersion.String()
}
}
aStatus, err := m.Status()
if err != nil {
return params.ModelStatusInfo{}, errors.Annotate(err, "cannot obtain model status info")
}
info.SLA = m.SLALevel()
info.ModelStatus = params.DetailedStatus{
Status: aStatus.Status.String(),
Info: aStatus.Message,
Since: aStatus.Since,
Data: aStatus.Data,
}
if info.SLA != "unsupported" {
ms := m.MeterStatus()
if isColorStatus(ms.Code) {
info.MeterStatus = params.MeterStatus{Color: strings.ToLower(ms.Code.String()), Message: ms.Info}
}
}
return info, nil
}
type applicationStatusInfo struct {
// application: application name -> application
applications map[string]*state.Application
// units: application name -> units name -> units
units map[string]map[string]*state.Unit
// allUnits: unit name -> unit
allUnits map[string]*state.Unit
// latestcharm: charm URL -> charm
latestCharms map[charm.URL]*state.Charm
// endpointpointBindings: application name -> endpoint -> space
endpointBindings map[string]map[string]string
// lxdProfiles: lxd profile name -> lxd profile
lxdProfiles map[string]*charm.LXDProfile
}
type statusContext struct {
providerType string
cachedModel *cache.Model
model *state.Model
status *state.ModelStatus
presence common.ModelPresenceContext
// machines: top-level machine id -> list of machines nested in
// this machine.
machines map[string][]*state.Machine
// allMachines: machine id -> machine
// The machine in this map is the same machine in the machines map.
allMachines map[string]*state.Machine
allInstances *state.ModelInstanceData
allConstraints *state.ModelConstraints
// controllerNodes: node id -> controller node
controllerNodes map[string]state.ControllerNode
// ipAddresses: machine id -> list of ip.addresses
ipAddresses map[string][]*state.Address
// spaces: machine id -> deviceName -> list of spaceNames
spaces map[string]map[string]set.Strings
// linkLayerDevices: machine id -> list of linkLayerDevices
linkLayerDevices map[string][]*state.LinkLayerDevice
// remote applications: application name -> application
consumerRemoteApplications map[string]*state.RemoteApplication
// opened ports by machine.
openPortRangesByMachine map[string]state.MachinePortRanges
// offers: offer name -> offer
offers map[string]offerStatus
// controller current timestamp
controllerTimestamp *time.Time
allAppsUnitsCharmBindings applicationStatusInfo
relations map[string][]*state.Relation
relationsById map[int]*state.Relation
leaders map[string]string
branches map[string]cache.Branch
// Information about all spaces.
spaceInfos network.SpaceInfos
primaryHAMachine *names.MachineTag
// Optional storage info.
storageInstances []state.StorageInstance
volumes []state.Volume
filesystems []state.Filesystem
}
// fetchMachines returns a map from top level machine id to machines, where machines[0] is the host
// machine and machines[1..n] are any containers (including nested ones).
//
// If machineIds is non-nil, only machines whose IDs are in the set are returned.
func (context *statusContext) fetchMachines(st Backend) error {
if context.model.Type() == state.ModelTypeCAAS {
return nil
}
context.machines = make(map[string][]*state.Machine)
context.allMachines = make(map[string]*state.Machine)
machines, err := st.AllMachines()
if err != nil {
return err
}
// AllMachines gives us machines sorted by id.
for _, m := range machines {
context.allMachines[m.Id()] = m
_, ok := m.ParentId()
if !ok {
// Only top level host machines go directly into the machine map.
context.machines[m.Id()] = []*state.Machine{m}
} else {
topParentId := container.TopParentId(m.Id())
machines := context.machines[topParentId]
context.machines[topParentId] = append(machines, m)
}
}
context.allInstances, err = context.model.AllInstanceData()
if err != nil {
return err
}
context.allConstraints, err = context.model.AllConstraints()
if err != nil {
return err
}
return nil
}
func (context *statusContext) fetchOpenPortRangesForAllMachines(st Backend) error {
if context.model.Type() == state.ModelTypeCAAS {
return nil
}
context.openPortRangesByMachine = make(map[string]state.MachinePortRanges)
allMachPortRanges, err := context.model.OpenedPortRangesForAllMachines()
if err != nil {
return err
}
for _, machPortRanges := range allMachPortRanges {
context.openPortRangesByMachine[machPortRanges.MachineID()] = machPortRanges
}
return nil
}
// fetchControllerNodes returns a map from node id to controller node.
func fetchControllerNodes(st Backend) (map[string]state.ControllerNode, error) {
v := make(map[string]state.ControllerNode)
nodes, err := st.ControllerNodes()
if err != nil {
return nil, err
}
for _, n := range nodes {
v[n.Id()] = n
}
return v, nil
}
// fetchNetworkInterfaces returns maps from machine id to ip.addresses, machine
// id to a map of interface names from space names, and machine id to
// linklayerdevices.
//
// All are required to determine a machine's network interfaces configuration,
// so we want all or none.
func fetchNetworkInterfaces(st Backend, spaceInfos network.SpaceInfos) (map[string][]*state.Address,
map[string]map[string]set.Strings, map[string][]*state.LinkLayerDevice, error) {
ipAddresses := make(map[string][]*state.Address)
spacesPerMachine := make(map[string]map[string]set.Strings)
subnets, err := st.AllSubnets()
if err != nil {
return nil, nil, nil, err
}
subnetsByCIDR := make(map[string]*state.Subnet)
for _, subnet := range subnets {
subnetsByCIDR[subnet.CIDR()] = subnet
}
// For every machine, track what devices have addresses so we can filter linklayerdevices later
devicesWithAddresses := make(map[string]set.Strings)
ipAddrs, err := st.AllIPAddresses()
if err != nil {
return nil, nil, nil, err
}
for _, ipAddr := range ipAddrs {
if ipAddr.LoopbackConfigMethod() {
continue
}
machineID := ipAddr.MachineID()
ipAddresses[machineID] = append(ipAddresses[machineID], ipAddr)
if subnet, ok := subnetsByCIDR[ipAddr.SubnetCIDR()]; ok {
spaceName := network.AlphaSpaceName
spaceInfo := spaceInfos.GetByID(subnet.SpaceID())
if spaceInfo != nil {
spaceName = string(spaceInfo.Name)
}
if spaceName != "" {
devices, ok := spacesPerMachine[machineID]
if !ok {
devices = make(map[string]set.Strings)
spacesPerMachine[machineID] = devices
}
deviceName := ipAddr.DeviceName()
spacesSet, ok := devices[deviceName]
if !ok {
spacesSet = make(set.Strings)
devices[deviceName] = spacesSet
}
spacesSet.Add(spaceName)
}
}
deviceSet, ok := devicesWithAddresses[machineID]
if ok {
deviceSet.Add(ipAddr.DeviceName())
} else {
devicesWithAddresses[machineID] = set.NewStrings(ipAddr.DeviceName())
}
}
linkLayerDevices := make(map[string][]*state.LinkLayerDevice)
llDevs, err := st.AllLinkLayerDevices()
if err != nil {
return nil, nil, nil, err
}
for _, llDev := range llDevs {
if llDev.IsLoopbackDevice() {
continue
}
machineID := llDev.MachineID()
machineDevs, ok := devicesWithAddresses[machineID]
if !ok {
// This machine ID doesn't seem to have any devices with IP Addresses
continue
}
if !machineDevs.Contains(llDev.Name()) {
// this device did not have any IP Addresses
continue
}
// This device had an IP Address, so include it in the list of devices for this machine
linkLayerDevices[machineID] = append(linkLayerDevices[machineID], llDev)
}
return ipAddresses, spacesPerMachine, linkLayerDevices, nil
}
// fetchAllApplicationsAndUnits returns a map from application name to application,
// a map from application name to unit name to unit, and a map from base charm URL to latest URL.
func fetchAllApplicationsAndUnits(st Backend, model *state.Model, spaceInfos network.SpaceInfos) (applicationStatusInfo,
error) {
appMap := make(map[string]*state.Application)
unitMap := make(map[string]map[string]*state.Unit)
latestCharms := make(map[charm.URL]*state.Charm)
applications, err := st.AllApplications()
if err != nil {
return applicationStatusInfo{}, err
}
units, err := model.AllUnits()
if err != nil {
return applicationStatusInfo{}, err
}
allUnitsByApp := make(map[string]map[string]*state.Unit)
allUnits := make(map[string]*state.Unit)
for _, unit := range units {
appName := unit.ApplicationName()
if inner, found := allUnitsByApp[appName]; found {
inner[unit.Name()] = unit
} else {
allUnitsByApp[appName] = map[string]*state.Unit{
unit.Name(): unit,
}
}
allUnits[unit.Name()] = unit
}
endpointBindings, err := model.AllEndpointBindings()
if err != nil {
return applicationStatusInfo{}, err
}
allBindingsByApp := make(map[string]map[string]string)
for app, bindings := range endpointBindings {
// If the only binding is the default, and it's set to the
// default space, no need to print.
bindingMap, err := bindings.MapWithSpaceNames(spaceInfos)
if err != nil {
return applicationStatusInfo{}, err
}
if len(bindingMap) == 1 {
if v, ok := bindingMap[""]; ok && v == network.AlphaSpaceName {
continue
}
}
allBindingsByApp[app] = bindingMap
}
lxdProfiles := make(map[string]*charm.LXDProfile)
for _, app := range applications {
appMap[app.Name()] = app
appUnits := allUnitsByApp[app.Name()]
cURL, _ := app.CharmURL()
charmURL, err := charm.ParseURL(*cURL)
if err != nil {
continue
}
if len(appUnits) > 0 {
unitMap[app.Name()] = appUnits
// Record the base URL for the application's charm so that
// the latest store revision can be looked up.
switch {
case charm.CharmHub.Matches(charmURL.Schema):
latestCharms[*charmURL.WithRevision(-1)] = nil
default:
// Don't look up revision for local charms
}
}
ch, _, err := app.Charm()
if err != nil {
continue
}
chName := lxdprofile.Name(model.Name(), app.Name(), ch.Revision())
if profile := ch.LXDProfile(); profile != nil {
lxdProfiles[chName] = &charm.LXDProfile{
Description: profile.Description,
Config: profile.Config,
Devices: profile.Devices,
}
}
}
for baseURL := range latestCharms {
ch, err := st.LatestPlaceholderCharm(&baseURL)
if errors.IsNotFound(err) {
continue
}
if err != nil {
return applicationStatusInfo{}, err
}
latestCharms[baseURL] = ch
}
return applicationStatusInfo{
applications: appMap,
units: unitMap,
allUnits: allUnits,
latestCharms: latestCharms,
endpointBindings: allBindingsByApp,