github.com/technosophos/deis@v1.7.1-0.20150915173815-f9005256004b/deisctl/backend/fleet/list_units.go (about) 1 package fleet 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/coreos/fleet/machine" 8 "github.com/coreos/fleet/schema" 9 "github.com/deis/deis/deisctl/units" 10 ) 11 12 const ( 13 //defaultListUnitFields = "unit,state,load,active,sub,machine" 14 defaultListUnitsFields = "unit,machine,load,active,sub" 15 ) 16 17 type usToField func(c *FleetClient, us *schema.UnitState, full bool) string 18 19 var ( 20 listUnitsFields = map[string]usToField{ 21 "unit": func(c *FleetClient, us *schema.UnitState, full bool) string { 22 if us == nil { 23 return "-" 24 } 25 return us.Name 26 }, 27 "load": func(c *FleetClient, us *schema.UnitState, full bool) string { 28 if us == nil { 29 return "-" 30 } 31 return us.SystemdLoadState 32 }, 33 "active": func(c *FleetClient, us *schema.UnitState, full bool) string { 34 if us == nil { 35 return "-" 36 } 37 return us.SystemdActiveState 38 }, 39 "sub": func(c *FleetClient, us *schema.UnitState, full bool) string { 40 if us == nil { 41 return "-" 42 } 43 return us.SystemdSubState 44 }, 45 "machine": func(c *FleetClient, us *schema.UnitState, full bool) string { 46 if us == nil || us.MachineID == "" { 47 return "-" 48 } 49 ms := c.cachedMachineState(us.MachineID) 50 if ms == nil { 51 ms = &machine.MachineState{ID: us.MachineID} 52 } 53 return machineFullLegend(*ms, full) 54 }, 55 "hash": func(c *FleetClient, us *schema.UnitState, full bool) string { 56 if us == nil || us.Hash == "" { 57 return "-" 58 } 59 if !full { 60 return us.Hash[:7] 61 } 62 return us.Hash 63 }, 64 } 65 ) 66 67 // ListUnits prints all Deis-related units to Stdout 68 func (c *FleetClient) ListUnits() (err error) { 69 var states []*schema.UnitState 70 71 unitStates, err := c.Fleet.UnitStates() 72 if err != nil { 73 return err 74 } 75 76 for _, us := range unitStates { 77 for _, prefix := range units.Names { 78 if strings.HasPrefix(us.Name, prefix) { 79 states = append(states, us) 80 break 81 } 82 } 83 } 84 c.printUnits(states) 85 return 86 } 87 88 // printUnits writes units to stdout using a tabwriter 89 func (c *FleetClient) printUnits(states []*schema.UnitState) { 90 cols := strings.Split(defaultListUnitsFields, ",") 91 fmt.Fprintln(c.out, strings.ToUpper(strings.Join(cols, "\t"))) 92 for _, us := range states { 93 var f []string 94 for _, col := range cols { 95 f = append(f, listUnitsFields[col](c, us, false)) 96 } 97 fmt.Fprintln(c.out, strings.Join(f, "\t")) 98 } 99 c.out.Flush() 100 } 101 102 func machineIDLegend(ms machine.MachineState, full bool) string { 103 legend := ms.ID 104 if !full { 105 legend = fmt.Sprintf("%s...", ms.ShortID()) 106 } 107 return legend 108 } 109 110 func machineFullLegend(ms machine.MachineState, full bool) string { 111 legend := machineIDLegend(ms, full) 112 if len(ms.PublicIP) > 0 { 113 legend = fmt.Sprintf("%s/%s", legend, ms.PublicIP) 114 } 115 return legend 116 }