|
| 1 | +package fleet |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sort" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/coreos/fleet/machine" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + defaultListMachinesFields = "machine,ip,metadata" |
| 13 | +) |
| 14 | + |
| 15 | +var ( |
| 16 | + listMachinesFields = map[string]machineToField{ |
| 17 | + "machine": func(ms *machine.MachineState, full bool) string { |
| 18 | + return machineIDLegend(*ms, full) |
| 19 | + }, |
| 20 | + "ip": func(ms *machine.MachineState, full bool) string { |
| 21 | + if len(ms.PublicIP) == 0 { |
| 22 | + return "-" |
| 23 | + } |
| 24 | + return ms.PublicIP |
| 25 | + }, |
| 26 | + "metadata": func(ms *machine.MachineState, full bool) string { |
| 27 | + if len(ms.Metadata) == 0 { |
| 28 | + return "-" |
| 29 | + } |
| 30 | + return formatMetadata(ms.Metadata) |
| 31 | + }, |
| 32 | + } |
| 33 | +) |
| 34 | + |
| 35 | +type machineToField func(ms *machine.MachineState, full bool) string |
| 36 | + |
| 37 | +// ListMachines prints all nodes to Stdout |
| 38 | +func (c *FleetClient) ListMachines() (err error) { |
| 39 | + machines, err := c.Fleet.Machines() |
| 40 | + if err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + |
| 44 | + c.printMachines(machines) |
| 45 | + return |
| 46 | +} |
| 47 | + |
| 48 | +// printUnits writes units to stdout using a tabwriter |
| 49 | +func (c *FleetClient) printMachines(states []machine.MachineState) { |
| 50 | + cols := strings.Split(defaultListMachinesFields, ",") |
| 51 | + fmt.Fprintln(c.out, strings.ToUpper(strings.Join(cols, "\t"))) |
| 52 | + for _, ms := range states { |
| 53 | + var f []string |
| 54 | + for _, c := range cols { |
| 55 | + f = append(f, listMachinesFields[c](&ms, false)) |
| 56 | + } |
| 57 | + fmt.Fprintln(c.out, strings.Join(f, "\t")) |
| 58 | + } |
| 59 | + c.out.Flush() |
| 60 | +} |
| 61 | + |
| 62 | +func formatMetadata(metadata map[string]string) string { |
| 63 | + pairs := make([]string, len(metadata)) |
| 64 | + idx := 0 |
| 65 | + var sorted sort.StringSlice |
| 66 | + for k := range metadata { |
| 67 | + sorted = append(sorted, k) |
| 68 | + } |
| 69 | + sorted.Sort() |
| 70 | + for _, key := range sorted { |
| 71 | + value := metadata[key] |
| 72 | + pairs[idx] = fmt.Sprintf("%s=%s", key, value) |
| 73 | + idx++ |
| 74 | + } |
| 75 | + return strings.Join(pairs, ",") |
| 76 | +} |
0 commit comments