github.com/bigcommerce/nomad@v0.9.3-bc/command/node_status.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"sort"
     7  	"strconv"
     8  	"strings"
     9  	"time"
    10  
    11  	humanize "github.com/dustin/go-humanize"
    12  	"github.com/hashicorp/nomad/api"
    13  	"github.com/hashicorp/nomad/api/contexts"
    14  	"github.com/hashicorp/nomad/helper"
    15  	"github.com/posener/complete"
    16  )
    17  
    18  const (
    19  	// floatFormat is a format string for formatting floats.
    20  	floatFormat = "#,###.##"
    21  
    22  	// bytesPerMegabyte is the number of bytes per MB
    23  	bytesPerMegabyte = 1024 * 1024
    24  )
    25  
    26  type NodeStatusCommand struct {
    27  	Meta
    28  	length      int
    29  	short       bool
    30  	verbose     bool
    31  	list_allocs bool
    32  	self        bool
    33  	stats       bool
    34  	json        bool
    35  	tmpl        string
    36  }
    37  
    38  func (c *NodeStatusCommand) Help() string {
    39  	helpText := `
    40  Usage: nomad node status [options] <node>
    41  
    42    Display status information about a given node. The list of nodes
    43    returned includes only nodes which jobs may be scheduled to, and
    44    includes status and other high-level information.
    45  
    46    If a node ID is passed, information for that specific node will be displayed,
    47    including resource usage statistics. If no node ID's are passed, then a
    48    short-hand list of all nodes will be displayed. The -self flag is useful to
    49    quickly access the status of the local node.
    50  
    51  General Options:
    52  
    53    ` + generalOptionsUsage() + `
    54  
    55  Node Status Options:
    56  
    57    -self
    58      Query the status of the local node.
    59  
    60    -stats
    61      Display detailed resource usage statistics.
    62  
    63    -allocs
    64      Display a count of running allocations for each node.
    65  
    66    -short
    67      Display short output. Used only when a single node is being
    68      queried, and drops verbose output about node allocations.
    69  
    70    -verbose
    71      Display full information.
    72  
    73    -json
    74      Output the node in its JSON format.
    75  
    76    -t
    77      Format and display node using a Go template.
    78  `
    79  	return strings.TrimSpace(helpText)
    80  }
    81  
    82  func (c *NodeStatusCommand) Synopsis() string {
    83  	return "Display status information about nodes"
    84  }
    85  
    86  func (c *NodeStatusCommand) AutocompleteFlags() complete.Flags {
    87  	return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient),
    88  		complete.Flags{
    89  			"-allocs":  complete.PredictNothing,
    90  			"-json":    complete.PredictNothing,
    91  			"-self":    complete.PredictNothing,
    92  			"-short":   complete.PredictNothing,
    93  			"-stats":   complete.PredictNothing,
    94  			"-t":       complete.PredictAnything,
    95  			"-verbose": complete.PredictNothing,
    96  		})
    97  }
    98  
    99  func (c *NodeStatusCommand) AutocompleteArgs() complete.Predictor {
   100  	return complete.PredictFunc(func(a complete.Args) []string {
   101  		client, err := c.Meta.Client()
   102  		if err != nil {
   103  			return nil
   104  		}
   105  
   106  		resp, _, err := client.Search().PrefixSearch(a.Last, contexts.Nodes, nil)
   107  		if err != nil {
   108  			return []string{}
   109  		}
   110  		return resp.Matches[contexts.Nodes]
   111  	})
   112  }
   113  
   114  func (c *NodeStatusCommand) Name() string { return "node-status" }
   115  
   116  func (c *NodeStatusCommand) Run(args []string) int {
   117  
   118  	flags := c.Meta.FlagSet(c.Name(), FlagSetClient)
   119  	flags.Usage = func() { c.Ui.Output(c.Help()) }
   120  	flags.BoolVar(&c.short, "short", false, "")
   121  	flags.BoolVar(&c.verbose, "verbose", false, "")
   122  	flags.BoolVar(&c.list_allocs, "allocs", false, "")
   123  	flags.BoolVar(&c.self, "self", false, "")
   124  	flags.BoolVar(&c.stats, "stats", false, "")
   125  	flags.BoolVar(&c.json, "json", false, "")
   126  	flags.StringVar(&c.tmpl, "t", "", "")
   127  
   128  	if err := flags.Parse(args); err != nil {
   129  		return 1
   130  	}
   131  
   132  	// Check that we got either a single node or none
   133  	args = flags.Args()
   134  	if len(args) > 1 {
   135  		c.Ui.Error("This command takes either one or no arguments")
   136  		c.Ui.Error(commandErrorText(c))
   137  		return 1
   138  	}
   139  
   140  	// Truncate the id unless full length is requested
   141  	c.length = shortId
   142  	if c.verbose {
   143  		c.length = fullId
   144  	}
   145  
   146  	// Get the HTTP client
   147  	client, err := c.Meta.Client()
   148  	if err != nil {
   149  		c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
   150  		return 1
   151  	}
   152  
   153  	// Use list mode if no node name was provided
   154  	if len(args) == 0 && !c.self {
   155  
   156  		// Query the node info
   157  		nodes, _, err := client.Nodes().List(nil)
   158  		if err != nil {
   159  			c.Ui.Error(fmt.Sprintf("Error querying node status: %s", err))
   160  			return 1
   161  		}
   162  
   163  		// If output format is specified, format and output the node data list
   164  		if c.json || len(c.tmpl) > 0 {
   165  			out, err := Format(c.json, c.tmpl, nodes)
   166  			if err != nil {
   167  				c.Ui.Error(err.Error())
   168  				return 1
   169  			}
   170  
   171  			c.Ui.Output(out)
   172  			return 0
   173  		}
   174  
   175  		// Return nothing if no nodes found
   176  		if len(nodes) == 0 {
   177  			return 0
   178  		}
   179  
   180  		// Format the nodes list
   181  		out := make([]string, len(nodes)+1)
   182  
   183  		out[0] = "ID|DC|Name|Class|"
   184  
   185  		if c.verbose {
   186  			out[0] += "Address|Version|"
   187  		}
   188  
   189  		out[0] += "Drain|Eligibility|Status"
   190  
   191  		if c.list_allocs {
   192  			out[0] += "|Running Allocs"
   193  		}
   194  
   195  		for i, node := range nodes {
   196  			out[i+1] = fmt.Sprintf("%s|%s|%s|%s",
   197  				limit(node.ID, c.length),
   198  				node.Datacenter,
   199  				node.Name,
   200  				node.NodeClass)
   201  			if c.verbose {
   202  				out[i+1] += fmt.Sprintf("|%s|%s",
   203  					node.Address, node.Version)
   204  			}
   205  			out[i+1] += fmt.Sprintf("|%v|%s|%s",
   206  				node.Drain,
   207  				node.SchedulingEligibility,
   208  				node.Status)
   209  
   210  			if c.list_allocs {
   211  				numAllocs, err := getRunningAllocs(client, node.ID)
   212  				if err != nil {
   213  					c.Ui.Error(fmt.Sprintf("Error querying node allocations: %s", err))
   214  					return 1
   215  				}
   216  				out[i+1] += fmt.Sprintf("|%v",
   217  					len(numAllocs))
   218  			}
   219  		}
   220  
   221  		// Dump the output
   222  		c.Ui.Output(formatList(out))
   223  		return 0
   224  	}
   225  
   226  	// Query the specific node
   227  	var nodeID string
   228  	if !c.self {
   229  		nodeID = args[0]
   230  	} else {
   231  		var err error
   232  		if nodeID, err = getLocalNodeID(client); err != nil {
   233  			c.Ui.Error(err.Error())
   234  			return 1
   235  		}
   236  	}
   237  	if len(nodeID) == 1 {
   238  		c.Ui.Error(fmt.Sprintf("Identifier must contain at least two characters."))
   239  		return 1
   240  	}
   241  
   242  	nodeID = sanitizeUUIDPrefix(nodeID)
   243  	nodes, _, err := client.Nodes().PrefixList(nodeID)
   244  	if err != nil {
   245  		c.Ui.Error(fmt.Sprintf("Error querying node info: %s", err))
   246  		return 1
   247  	}
   248  	// Return error if no nodes are found
   249  	if len(nodes) == 0 {
   250  		c.Ui.Error(fmt.Sprintf("No node(s) with prefix %q found", nodeID))
   251  		return 1
   252  	}
   253  	if len(nodes) > 1 {
   254  		// Dump the output
   255  		c.Ui.Error(fmt.Sprintf("Prefix matched multiple nodes\n\n%s",
   256  			formatNodeStubList(nodes, c.verbose)))
   257  		return 1
   258  	}
   259  
   260  	// Prefix lookup matched a single node
   261  	node, _, err := client.Nodes().Info(nodes[0].ID, nil)
   262  	if err != nil {
   263  		c.Ui.Error(fmt.Sprintf("Error querying node info: %s", err))
   264  		return 1
   265  	}
   266  
   267  	// If output format is specified, format and output the data
   268  	if c.json || len(c.tmpl) > 0 {
   269  		out, err := Format(c.json, c.tmpl, node)
   270  		if err != nil {
   271  			c.Ui.Error(err.Error())
   272  			return 1
   273  		}
   274  
   275  		c.Ui.Output(out)
   276  		return 0
   277  	}
   278  
   279  	return c.formatNode(client, node)
   280  }
   281  
   282  func nodeDrivers(n *api.Node) []string {
   283  	var drivers []string
   284  	for k, v := range n.Attributes {
   285  		// driver.docker = 1
   286  		parts := strings.Split(k, ".")
   287  		if len(parts) != 2 {
   288  			continue
   289  		} else if parts[0] != "driver" {
   290  			continue
   291  		} else if v != "1" {
   292  			continue
   293  		}
   294  
   295  		drivers = append(drivers, parts[1])
   296  	}
   297  
   298  	sort.Strings(drivers)
   299  	return drivers
   300  }
   301  
   302  func formatDrain(n *api.Node) string {
   303  	if n.DrainStrategy != nil {
   304  		b := new(strings.Builder)
   305  		b.WriteString("true")
   306  		if n.DrainStrategy.DrainSpec.Deadline.Nanoseconds() < 0 {
   307  			b.WriteString("; force drain")
   308  		} else if n.DrainStrategy.ForceDeadline.IsZero() {
   309  			b.WriteString("; no deadline")
   310  		} else {
   311  			fmt.Fprintf(b, "; %s deadline", formatTime(n.DrainStrategy.ForceDeadline))
   312  		}
   313  
   314  		if n.DrainStrategy.IgnoreSystemJobs {
   315  			b.WriteString("; ignoring system jobs")
   316  		}
   317  		return b.String()
   318  	}
   319  
   320  	return strconv.FormatBool(n.Drain)
   321  }
   322  
   323  func (c *NodeStatusCommand) formatNode(client *api.Client, node *api.Node) int {
   324  	// Format the header output
   325  	basic := []string{
   326  		fmt.Sprintf("ID|%s", limit(node.ID, c.length)),
   327  		fmt.Sprintf("Name|%s", node.Name),
   328  		fmt.Sprintf("Class|%s", node.NodeClass),
   329  		fmt.Sprintf("DC|%s", node.Datacenter),
   330  		fmt.Sprintf("Drain|%v", formatDrain(node)),
   331  		fmt.Sprintf("Eligibility|%s", node.SchedulingEligibility),
   332  		fmt.Sprintf("Status|%s", node.Status),
   333  	}
   334  
   335  	if c.short {
   336  		basic = append(basic, fmt.Sprintf("Drivers|%s", strings.Join(nodeDrivers(node), ",")))
   337  		c.Ui.Output(c.Colorize().Color(formatKV(basic)))
   338  	} else {
   339  		// Get the host stats
   340  		hostStats, nodeStatsErr := client.Nodes().Stats(node.ID, nil)
   341  		if nodeStatsErr != nil {
   342  			c.Ui.Output("")
   343  			c.Ui.Error(fmt.Sprintf("error fetching node stats: %v", nodeStatsErr))
   344  		}
   345  		if hostStats != nil {
   346  			uptime := time.Duration(hostStats.Uptime * uint64(time.Second))
   347  			basic = append(basic, fmt.Sprintf("Uptime|%s", uptime.String()))
   348  		}
   349  
   350  		// Emit the driver info
   351  		if !c.verbose {
   352  			driverStatus := fmt.Sprintf("Driver Status| %s", c.outputTruncatedNodeDriverInfo(node))
   353  			basic = append(basic, driverStatus)
   354  		}
   355  
   356  		c.Ui.Output(c.Colorize().Color(formatKV(basic)))
   357  
   358  		if c.verbose {
   359  			c.outputNodeDriverInfo(node)
   360  		}
   361  
   362  		// Emit node events
   363  		c.outputNodeStatusEvents(node)
   364  
   365  		// Get list of running allocations on the node
   366  		runningAllocs, err := getRunningAllocs(client, node.ID)
   367  		if err != nil {
   368  			c.Ui.Error(fmt.Sprintf("Error querying node for running allocations: %s", err))
   369  			return 1
   370  		}
   371  
   372  		allocatedResources := getAllocatedResources(client, runningAllocs, node)
   373  		c.Ui.Output(c.Colorize().Color("\n[bold]Allocated Resources[reset]"))
   374  		c.Ui.Output(formatList(allocatedResources))
   375  
   376  		actualResources, err := getActualResources(client, runningAllocs, node)
   377  		if err == nil {
   378  			c.Ui.Output(c.Colorize().Color("\n[bold]Allocation Resource Utilization[reset]"))
   379  			c.Ui.Output(formatList(actualResources))
   380  		}
   381  
   382  		hostResources, err := getHostResources(hostStats, node)
   383  		if err != nil {
   384  			c.Ui.Output("")
   385  			c.Ui.Error(fmt.Sprintf("error fetching node stats: %v", err))
   386  		}
   387  		if err == nil {
   388  			c.Ui.Output(c.Colorize().Color("\n[bold]Host Resource Utilization[reset]"))
   389  			c.Ui.Output(formatList(hostResources))
   390  		}
   391  
   392  		if err == nil && node.NodeResources != nil && len(node.NodeResources.Devices) > 0 {
   393  			c.Ui.Output(c.Colorize().Color("\n[bold]Device Resource Utilization[reset]"))
   394  			c.Ui.Output(formatList(getDeviceResourcesForNode(hostStats.DeviceStats, node)))
   395  		}
   396  		if hostStats != nil && c.stats {
   397  			c.Ui.Output(c.Colorize().Color("\n[bold]CPU Stats[reset]"))
   398  			c.printCpuStats(hostStats)
   399  			c.Ui.Output(c.Colorize().Color("\n[bold]Memory Stats[reset]"))
   400  			c.printMemoryStats(hostStats)
   401  			c.Ui.Output(c.Colorize().Color("\n[bold]Disk Stats[reset]"))
   402  			c.printDiskStats(hostStats)
   403  			if len(hostStats.DeviceStats) > 0 {
   404  				c.Ui.Output(c.Colorize().Color("\n[bold]Device Stats[reset]"))
   405  				printDeviceStats(c.Ui, hostStats.DeviceStats)
   406  			}
   407  		}
   408  	}
   409  
   410  	nodeAllocs, _, err := client.Nodes().Allocations(node.ID, nil)
   411  	if err != nil {
   412  		c.Ui.Error(fmt.Sprintf("Error querying node allocations: %s", err))
   413  		return 1
   414  	}
   415  
   416  	c.Ui.Output(c.Colorize().Color("\n[bold]Allocations[reset]"))
   417  	c.Ui.Output(formatAllocList(nodeAllocs, c.verbose, c.length))
   418  
   419  	if c.verbose {
   420  		c.formatAttributes(node)
   421  		c.formatDeviceAttributes(node)
   422  		c.formatMeta(node)
   423  	}
   424  	return 0
   425  
   426  }
   427  
   428  func (c *NodeStatusCommand) outputTruncatedNodeDriverInfo(node *api.Node) string {
   429  	drivers := make([]string, 0, len(node.Drivers))
   430  
   431  	for driverName, driverInfo := range node.Drivers {
   432  		if !driverInfo.Detected {
   433  			continue
   434  		}
   435  
   436  		if !driverInfo.Healthy {
   437  			drivers = append(drivers, fmt.Sprintf("%s (unhealthy)", driverName))
   438  		} else {
   439  			drivers = append(drivers, driverName)
   440  		}
   441  	}
   442  	sort.Strings(drivers)
   443  	return strings.Trim(strings.Join(drivers, ","), ", ")
   444  }
   445  
   446  func (c *NodeStatusCommand) outputNodeDriverInfo(node *api.Node) {
   447  	c.Ui.Output(c.Colorize().Color("\n[bold]Drivers"))
   448  
   449  	size := len(node.Drivers)
   450  	nodeDrivers := make([]string, 0, size+1)
   451  
   452  	nodeDrivers = append(nodeDrivers, "Driver|Detected|Healthy|Message|Time")
   453  
   454  	drivers := make([]string, 0, len(node.Drivers))
   455  	for driver := range node.Drivers {
   456  		drivers = append(drivers, driver)
   457  	}
   458  	sort.Strings(drivers)
   459  
   460  	for _, driver := range drivers {
   461  		info := node.Drivers[driver]
   462  		timestamp := formatTime(info.UpdateTime)
   463  		nodeDrivers = append(nodeDrivers, fmt.Sprintf("%s|%v|%v|%s|%s", driver, info.Detected, info.Healthy, info.HealthDescription, timestamp))
   464  	}
   465  	c.Ui.Output(formatList(nodeDrivers))
   466  }
   467  
   468  func (c *NodeStatusCommand) outputNodeStatusEvents(node *api.Node) {
   469  	c.Ui.Output(c.Colorize().Color("\n[bold]Node Events"))
   470  	c.outputNodeEvent(node.Events)
   471  }
   472  
   473  func (c *NodeStatusCommand) outputNodeEvent(events []*api.NodeEvent) {
   474  	size := len(events)
   475  	nodeEvents := make([]string, size+1)
   476  	if c.verbose {
   477  		nodeEvents[0] = "Time|Subsystem|Message|Details"
   478  	} else {
   479  		nodeEvents[0] = "Time|Subsystem|Message"
   480  	}
   481  
   482  	for i, event := range events {
   483  		timestamp := formatTime(event.Timestamp)
   484  		subsystem := formatEventSubsystem(event.Subsystem, event.Details["driver"])
   485  		msg := event.Message
   486  		if c.verbose {
   487  			details := formatEventDetails(event.Details)
   488  			nodeEvents[size-i] = fmt.Sprintf("%s|%s|%s|%s", timestamp, subsystem, msg, details)
   489  		} else {
   490  			nodeEvents[size-i] = fmt.Sprintf("%s|%s|%s", timestamp, subsystem, msg)
   491  		}
   492  	}
   493  	c.Ui.Output(formatList(nodeEvents))
   494  }
   495  
   496  func formatEventSubsystem(subsystem, driverName string) string {
   497  	if driverName == "" {
   498  		return subsystem
   499  	}
   500  
   501  	// If this event is for a driver, append the driver name to make the message
   502  	// clearer
   503  	return fmt.Sprintf("Driver: %s", driverName)
   504  }
   505  
   506  func formatEventDetails(details map[string]string) string {
   507  	output := make([]string, 0, len(details))
   508  	for k, v := range details {
   509  		output = append(output, fmt.Sprintf("%s: %s ", k, v))
   510  	}
   511  	return strings.Join(output, ", ")
   512  }
   513  
   514  func (c *NodeStatusCommand) formatAttributes(node *api.Node) {
   515  	// Print the attributes
   516  	keys := make([]string, len(node.Attributes))
   517  	for k := range node.Attributes {
   518  		keys = append(keys, k)
   519  	}
   520  	sort.Strings(keys)
   521  
   522  	var attributes []string
   523  	for _, k := range keys {
   524  		if k != "" {
   525  			attributes = append(attributes, fmt.Sprintf("%s|%s", k, node.Attributes[k]))
   526  		}
   527  	}
   528  	c.Ui.Output(c.Colorize().Color("\n[bold]Attributes[reset]"))
   529  	c.Ui.Output(formatKV(attributes))
   530  }
   531  
   532  func (c *NodeStatusCommand) formatDeviceAttributes(node *api.Node) {
   533  	if node.NodeResources == nil {
   534  		return
   535  	}
   536  	devices := node.NodeResources.Devices
   537  	if len(devices) == 0 {
   538  		return
   539  	}
   540  
   541  	sort.Slice(devices, func(i, j int) bool {
   542  		return devices[i].ID() < devices[j].ID()
   543  	})
   544  
   545  	first := true
   546  	for _, d := range devices {
   547  		if len(d.Attributes) == 0 {
   548  			continue
   549  		}
   550  
   551  		if first {
   552  			c.Ui.Output("\nDevice Group Attributes")
   553  			first = false
   554  		} else {
   555  			c.Ui.Output("")
   556  		}
   557  		c.Ui.Output(formatKV(getDeviceAttributes(d)))
   558  	}
   559  }
   560  
   561  func (c *NodeStatusCommand) formatMeta(node *api.Node) {
   562  	// Print the meta
   563  	keys := make([]string, 0, len(node.Meta))
   564  	for k := range node.Meta {
   565  		keys = append(keys, k)
   566  	}
   567  	sort.Strings(keys)
   568  
   569  	var meta []string
   570  	for _, k := range keys {
   571  		if k != "" {
   572  			meta = append(meta, fmt.Sprintf("%s|%s", k, node.Meta[k]))
   573  		}
   574  	}
   575  	c.Ui.Output(c.Colorize().Color("\n[bold]Meta[reset]"))
   576  	c.Ui.Output(formatKV(meta))
   577  }
   578  
   579  func (c *NodeStatusCommand) printCpuStats(hostStats *api.HostStats) {
   580  	l := len(hostStats.CPU)
   581  	for i, cpuStat := range hostStats.CPU {
   582  		cpuStatsAttr := make([]string, 4)
   583  		cpuStatsAttr[0] = fmt.Sprintf("CPU|%v", cpuStat.CPU)
   584  		cpuStatsAttr[1] = fmt.Sprintf("User|%v%%", humanize.FormatFloat(floatFormat, cpuStat.User))
   585  		cpuStatsAttr[2] = fmt.Sprintf("System|%v%%", humanize.FormatFloat(floatFormat, cpuStat.System))
   586  		cpuStatsAttr[3] = fmt.Sprintf("Idle|%v%%", humanize.FormatFloat(floatFormat, cpuStat.Idle))
   587  		c.Ui.Output(formatKV(cpuStatsAttr))
   588  		if i+1 < l {
   589  			c.Ui.Output("")
   590  		}
   591  	}
   592  }
   593  
   594  func (c *NodeStatusCommand) printMemoryStats(hostStats *api.HostStats) {
   595  	memoryStat := hostStats.Memory
   596  	memStatsAttr := make([]string, 4)
   597  	memStatsAttr[0] = fmt.Sprintf("Total|%v", humanize.IBytes(memoryStat.Total))
   598  	memStatsAttr[1] = fmt.Sprintf("Available|%v", humanize.IBytes(memoryStat.Available))
   599  	memStatsAttr[2] = fmt.Sprintf("Used|%v", humanize.IBytes(memoryStat.Used))
   600  	memStatsAttr[3] = fmt.Sprintf("Free|%v", humanize.IBytes(memoryStat.Free))
   601  	c.Ui.Output(formatKV(memStatsAttr))
   602  }
   603  
   604  func (c *NodeStatusCommand) printDiskStats(hostStats *api.HostStats) {
   605  	l := len(hostStats.DiskStats)
   606  	for i, diskStat := range hostStats.DiskStats {
   607  		diskStatsAttr := make([]string, 7)
   608  		diskStatsAttr[0] = fmt.Sprintf("Device|%s", diskStat.Device)
   609  		diskStatsAttr[1] = fmt.Sprintf("MountPoint|%s", diskStat.Mountpoint)
   610  		diskStatsAttr[2] = fmt.Sprintf("Size|%s", humanize.IBytes(diskStat.Size))
   611  		diskStatsAttr[3] = fmt.Sprintf("Used|%s", humanize.IBytes(diskStat.Used))
   612  		diskStatsAttr[4] = fmt.Sprintf("Available|%s", humanize.IBytes(diskStat.Available))
   613  		diskStatsAttr[5] = fmt.Sprintf("Used Percent|%v%%", humanize.FormatFloat(floatFormat, diskStat.UsedPercent))
   614  		diskStatsAttr[6] = fmt.Sprintf("Inodes Percent|%v%%", humanize.FormatFloat(floatFormat, diskStat.InodesUsedPercent))
   615  		c.Ui.Output(formatKV(diskStatsAttr))
   616  		if i+1 < l {
   617  			c.Ui.Output("")
   618  		}
   619  	}
   620  }
   621  
   622  // getRunningAllocs returns a slice of allocation id's running on the node
   623  func getRunningAllocs(client *api.Client, nodeID string) ([]*api.Allocation, error) {
   624  	var allocs []*api.Allocation
   625  
   626  	// Query the node allocations
   627  	nodeAllocs, _, err := client.Nodes().Allocations(nodeID, nil)
   628  	// Filter list to only running allocations
   629  	for _, alloc := range nodeAllocs {
   630  		if alloc.ClientStatus == "running" {
   631  			allocs = append(allocs, alloc)
   632  		}
   633  	}
   634  	return allocs, err
   635  }
   636  
   637  // getAllocatedResources returns the resource usage of the node.
   638  func getAllocatedResources(client *api.Client, runningAllocs []*api.Allocation, node *api.Node) []string {
   639  	// Compute the total
   640  	total := computeNodeTotalResources(node)
   641  
   642  	// Get Resources
   643  	var cpu, mem, disk int
   644  	for _, alloc := range runningAllocs {
   645  		cpu += *alloc.Resources.CPU
   646  		mem += *alloc.Resources.MemoryMB
   647  		disk += *alloc.Resources.DiskMB
   648  	}
   649  
   650  	resources := make([]string, 2)
   651  	resources[0] = "CPU|Memory|Disk"
   652  	resources[1] = fmt.Sprintf("%d/%d MHz|%s/%s|%s/%s",
   653  		cpu,
   654  		*total.CPU,
   655  		humanize.IBytes(uint64(mem*bytesPerMegabyte)),
   656  		humanize.IBytes(uint64(*total.MemoryMB*bytesPerMegabyte)),
   657  		humanize.IBytes(uint64(disk*bytesPerMegabyte)),
   658  		humanize.IBytes(uint64(*total.DiskMB*bytesPerMegabyte)))
   659  
   660  	return resources
   661  }
   662  
   663  // computeNodeTotalResources returns the total allocatable resources (resources
   664  // minus reserved)
   665  func computeNodeTotalResources(node *api.Node) api.Resources {
   666  	total := api.Resources{}
   667  
   668  	r := node.Resources
   669  	res := node.Reserved
   670  	if res == nil {
   671  		res = &api.Resources{}
   672  	}
   673  	total.CPU = helper.IntToPtr(*r.CPU - *res.CPU)
   674  	total.MemoryMB = helper.IntToPtr(*r.MemoryMB - *res.MemoryMB)
   675  	total.DiskMB = helper.IntToPtr(*r.DiskMB - *res.DiskMB)
   676  	return total
   677  }
   678  
   679  // getActualResources returns the actual resource usage of the allocations.
   680  func getActualResources(client *api.Client, runningAllocs []*api.Allocation, node *api.Node) ([]string, error) {
   681  	// Compute the total
   682  	total := computeNodeTotalResources(node)
   683  
   684  	// Get Resources
   685  	var cpu float64
   686  	var mem uint64
   687  	for _, alloc := range runningAllocs {
   688  		// Make the call to the client to get the actual usage.
   689  		stats, err := client.Allocations().Stats(alloc, nil)
   690  		if err != nil {
   691  			return nil, err
   692  		}
   693  
   694  		cpu += stats.ResourceUsage.CpuStats.TotalTicks
   695  		mem += stats.ResourceUsage.MemoryStats.RSS
   696  	}
   697  
   698  	resources := make([]string, 2)
   699  	resources[0] = "CPU|Memory"
   700  	resources[1] = fmt.Sprintf("%v/%d MHz|%v/%v",
   701  		math.Floor(cpu),
   702  		*total.CPU,
   703  		humanize.IBytes(mem),
   704  		humanize.IBytes(uint64(*total.MemoryMB*bytesPerMegabyte)))
   705  
   706  	return resources, nil
   707  }
   708  
   709  // getHostResources returns the actual resource usage of the node.
   710  func getHostResources(hostStats *api.HostStats, node *api.Node) ([]string, error) {
   711  	if hostStats == nil {
   712  		return nil, fmt.Errorf("actual resource usage not present")
   713  	}
   714  	var resources []string
   715  
   716  	// calculate disk usage
   717  	storageDevice := node.Attributes["unique.storage.volume"]
   718  	var diskUsed, diskSize uint64
   719  	var physical bool
   720  	for _, disk := range hostStats.DiskStats {
   721  		if disk.Device == storageDevice {
   722  			diskUsed = disk.Used
   723  			diskSize = disk.Size
   724  			physical = true
   725  		}
   726  	}
   727  
   728  	resources = make([]string, 2)
   729  	resources[0] = "CPU|Memory|Disk"
   730  	if physical {
   731  		resources[1] = fmt.Sprintf("%v/%d MHz|%s/%s|%s/%s",
   732  			math.Floor(hostStats.CPUTicksConsumed),
   733  			*node.Resources.CPU,
   734  			humanize.IBytes(hostStats.Memory.Used),
   735  			humanize.IBytes(hostStats.Memory.Total),
   736  			humanize.IBytes(diskUsed),
   737  			humanize.IBytes(diskSize),
   738  		)
   739  	} else {
   740  		// If non-physical device are used, output device name only,
   741  		// since nomad doesn't collect the stats data.
   742  		resources[1] = fmt.Sprintf("%v/%d MHz|%s/%s|(%s)",
   743  			math.Floor(hostStats.CPUTicksConsumed),
   744  			*node.Resources.CPU,
   745  			humanize.IBytes(hostStats.Memory.Used),
   746  			humanize.IBytes(hostStats.Memory.Total),
   747  			storageDevice,
   748  		)
   749  	}
   750  	return resources, nil
   751  }
   752  
   753  // formatNodeStubList is used to return a table format of a list of node stubs.
   754  func formatNodeStubList(nodes []*api.NodeListStub, verbose bool) string {
   755  	// Return error if no nodes are found
   756  	if len(nodes) == 0 {
   757  		return ""
   758  	}
   759  	// Truncate the id unless full length is requested
   760  	length := shortId
   761  	if verbose {
   762  		length = fullId
   763  	}
   764  
   765  	// Format the nodes list that matches the prefix so that the user
   766  	// can create a more specific request
   767  	out := make([]string, len(nodes)+1)
   768  	out[0] = "ID|DC|Name|Class|Drain|Eligibility|Status"
   769  	for i, node := range nodes {
   770  		out[i+1] = fmt.Sprintf("%s|%s|%s|%s|%v|%s|%s",
   771  			limit(node.ID, length),
   772  			node.Datacenter,
   773  			node.Name,
   774  			node.NodeClass,
   775  			node.Drain,
   776  			node.SchedulingEligibility,
   777  			node.Status)
   778  	}
   779  
   780  	return formatList(out)
   781  }