forked from juju/juju
/
output_tabular.go
350 lines (315 loc) · 9.16 KB
/
output_tabular.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package status
import (
"fmt"
"io"
"regexp"
"sort"
"strings"
"github.com/juju/ansiterm"
"github.com/juju/errors"
"github.com/juju/utils"
"github.com/juju/utils/set"
"gopkg.in/juju/charm.v6-unstable/hooks"
"github.com/juju/juju/cmd/output"
"github.com/juju/juju/core/crossmodel"
"github.com/juju/juju/instance"
"github.com/juju/juju/status"
)
type statusRelation struct {
application1 string
application2 string
relation string
subordinate bool
}
func (s *statusRelation) relationType() string {
if s.subordinate {
return "subordinate"
} else if s.application1 == s.application2 {
return "peer"
}
return "regular"
}
type relationFormatter struct {
relationIndex set.Strings
relations map[string]*statusRelation
}
func newRelationFormatter() *relationFormatter {
return &relationFormatter{
relationIndex: set.NewStrings(),
relations: make(map[string]*statusRelation),
}
}
func (r *relationFormatter) len() int {
return r.relationIndex.Size()
}
func (r *relationFormatter) add(rel1, rel2, relation string, is2SubOf1 bool) {
rel := []string{rel1, rel2}
if !is2SubOf1 {
sort.Sort(sort.StringSlice(rel))
}
k := strings.Join(rel, "\t")
r.relations[k] = &statusRelation{
application1: rel[0],
application2: rel[1],
relation: relation,
subordinate: is2SubOf1,
}
r.relationIndex.Add(k)
}
func (r *relationFormatter) sorted() []string {
return r.relationIndex.SortedValues()
}
func (r *relationFormatter) get(k string) *statusRelation {
return r.relations[k]
}
// FormatTabular writes a tabular summary of machines, applications, and
// units. Any subordinate items are indented by two spaces beneath
// their superior.
func FormatTabular(writer io.Writer, forceColor bool, value interface{}) error {
const maxVersionWidth = 15
const ellipsis = "..."
const truncatedWidth = maxVersionWidth - len(ellipsis)
fs, valueConverted := value.(formattedStatus)
if !valueConverted {
return errors.Errorf("expected value of type %T, got %T", fs, value)
}
// To format things into columns.
tw := output.TabWriter(writer)
if forceColor {
tw.SetColorCapable(forceColor)
}
w := output.Wrapper{tw}
p := w.Println
outputHeaders := func(values ...interface{}) {
p()
p(values...)
}
cloudRegion := fs.Model.Cloud
if fs.Model.CloudRegion != "" {
cloudRegion += "/" + fs.Model.CloudRegion
}
header := []interface{}{"Model", "Controller", "Cloud/Region", "Version"}
values := []interface{}{fs.Model.Name, fs.Model.Controller, cloudRegion, fs.Model.Version}
message := getModelMessage(fs.Model)
if message != "" {
header = append(header, "Notes")
values = append(values, message)
}
// The first set of headers don't use outputHeaders because it adds the blank line.
p(header...)
p(values...)
if len(fs.RemoteApplications) > 0 {
outputHeaders("SAAS name", "Status", "Store", "URL")
for _, appName := range utils.SortStringsNaturally(stringKeysFromMap(fs.RemoteApplications)) {
app := fs.RemoteApplications[appName]
var store, urlPath string
url, err := crossmodel.ParseApplicationURL(app.ApplicationURL)
if err == nil {
store = url.Source
urlPath = url.Path()
if store == "" {
store = "local"
}
} else {
// This is not expected.
logger.Errorf("invalid application URL %q: %v", app.ApplicationURL, err)
store = "unknown"
urlPath = app.ApplicationURL
}
p(appName, app.StatusInfo.Current, store, urlPath)
}
tw.Flush()
}
units := make(map[string]unitStatus)
metering := false
relations := newRelationFormatter()
outputHeaders("App", "Version", "Status", "Scale", "Charm", "Store", "Rev", "OS", "Notes")
tw.SetColumnAlignRight(3)
tw.SetColumnAlignRight(6)
for _, appName := range utils.SortStringsNaturally(stringKeysFromMap(fs.Applications)) {
app := fs.Applications[appName]
version := app.Version
// Don't let a long version push out the version column.
if len(version) > maxVersionWidth {
version = version[:truncatedWidth] + ellipsis
}
// Notes may well contain other things later.
notes := ""
if app.Exposed {
notes = "exposed"
}
w.Print(appName, version)
w.PrintStatus(app.StatusInfo.Current)
scale, warn := fs.applicationScale(appName)
if warn {
w.PrintColor(output.WarningHighlight, scale)
} else {
w.Print(scale)
}
p(app.CharmName,
app.CharmOrigin,
app.CharmRev,
app.OS,
notes)
for un, u := range app.Units {
units[un] = u
if u.MeterStatus != nil {
metering = true
}
}
// Ensure that we pick a consistent name for peer relations.
sortedRelTypes := make([]string, 0, len(app.Relations))
for relType := range app.Relations {
sortedRelTypes = append(sortedRelTypes, relType)
}
sort.Strings(sortedRelTypes)
subs := set.NewStrings(app.SubordinateTo...)
for _, relType := range sortedRelTypes {
for _, related := range app.Relations[relType] {
relations.add(related, appName, relType, subs.Contains(related))
}
}
}
pUnit := func(name string, u unitStatus, level int) {
message := u.WorkloadStatusInfo.Message
agentDoing := agentDoing(u.JujuStatusInfo)
if agentDoing != "" {
message = fmt.Sprintf("(%s) %s", agentDoing, message)
}
if u.Leader {
name += "*"
}
w.Print(indent("", level*2, name))
w.PrintStatus(u.WorkloadStatusInfo.Current)
w.PrintStatus(u.JujuStatusInfo.Current)
p(
u.Machine,
u.PublicAddress,
strings.Join(u.OpenedPorts, ","),
message,
)
}
outputHeaders("Unit", "Workload", "Agent", "Machine", "Public address", "Ports", "Message")
for _, name := range utils.SortStringsNaturally(stringKeysFromMap(units)) {
u := units[name]
pUnit(name, u, 0)
const indentationLevel = 1
recurseUnits(u, indentationLevel, pUnit)
}
if metering {
outputHeaders("Meter", "Status", "Message")
for _, name := range utils.SortStringsNaturally(stringKeysFromMap(units)) {
u := units[name]
if u.MeterStatus != nil {
w.Print(name)
outputColor := fromMeterStatusColor(u.MeterStatus.Color)
w.PrintColor(outputColor, u.MeterStatus.Color)
w.PrintColor(outputColor, u.MeterStatus.Message)
w.Println()
}
}
}
p()
printMachines(tw, fs.Machines)
if relations.len() > 0 {
outputHeaders("Relation", "Provides", "Consumes", "Type")
for _, k := range relations.sorted() {
r := relations.get(k)
if r != nil {
p(r.relation, r.application1, r.application2, r.relationType())
}
}
}
tw.Flush()
return nil
}
func fromMeterStatusColor(msColor string) *ansiterm.Context {
switch msColor {
case "green":
return output.GoodHighlight
case "amber":
return output.WarningHighlight
case "red":
return output.ErrorHighlight
}
return nil
}
func getModelMessage(model modelStatus) string {
// Select the most important message about the model (if any).
switch {
case model.Status.Message != "":
return model.Status.Message
case model.AvailableVersion != "":
return "upgrade available: " + model.AvailableVersion
default:
return ""
}
}
func printMachines(tw *ansiterm.TabWriter, machines map[string]machineStatus) {
w := output.Wrapper{tw}
w.Println("Machine", "State", "DNS", "Inst id", "Series", "AZ", "Message")
for _, name := range utils.SortStringsNaturally(stringKeysFromMap(machines)) {
printMachine(w, machines[name])
}
}
func printMachine(w output.Wrapper, m machineStatus) {
// We want to display availability zone so extract from hardware info".
hw, err := instance.ParseHardware(m.Hardware)
if err != nil {
logger.Warningf("invalid hardware info %s for machine %v", m.Hardware, m)
}
az := ""
if hw.AvailabilityZone != nil {
az = *hw.AvailabilityZone
}
w.Print(m.Id)
w.PrintStatus(m.JujuStatus.Current)
w.Println(m.DNSName, m.InstanceId, m.Series, az, m.MachineStatus.Message)
for _, name := range utils.SortStringsNaturally(stringKeysFromMap(m.Containers)) {
printMachine(w, m.Containers[name])
}
}
// FormatMachineTabular writes a tabular summary of machine
func FormatMachineTabular(writer io.Writer, forceColor bool, value interface{}) error {
fs, valueConverted := value.(formattedMachineStatus)
if !valueConverted {
return errors.Errorf("expected value of type %T, got %T", fs, value)
}
tw := output.TabWriter(writer)
if forceColor {
tw.SetColorCapable(forceColor)
}
printMachines(tw, fs.Machines)
tw.Flush()
return nil
}
// agentDoing returns what hook or action, if any,
// the agent is currently executing.
// The hook name or action is extracted from the agent message.
func agentDoing(agentStatus statusInfoContents) string {
if agentStatus.Current != status.Executing {
return ""
}
// First see if we can determine a hook name.
var hookNames []string
for _, h := range hooks.UnitHooks() {
hookNames = append(hookNames, string(h))
}
for _, h := range hooks.RelationHooks() {
hookNames = append(hookNames, string(h))
}
hookExp := regexp.MustCompile(fmt.Sprintf(`running (?P<hook>%s?) hook`, strings.Join(hookNames, "|")))
match := hookExp.FindStringSubmatch(agentStatus.Message)
if len(match) > 0 {
return match[1]
}
// Now try for an action name.
actionExp := regexp.MustCompile(`running action (?P<action>.*)`)
match = actionExp.FindStringSubmatch(agentStatus.Message)
if len(match) > 0 {
return match[1]
}
return ""
}