github.com/emate/nomad@v0.8.2-wo-binpacking/command/node_status.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"sort"
     7  	"strings"
     8  	"time"
     9  
    10  	humanize "github.com/dustin/go-humanize"
    11  	"github.com/posener/complete"
    12  
    13  	"github.com/hashicorp/nomad/api"
    14  	"github.com/hashicorp/nomad/api/contexts"
    15  	"github.com/hashicorp/nomad/helper"
    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 (c *NodeStatusCommand) formatNode(client *api.Client, node *api.Node) int {
   303  	// Format the header output
   304  	basic := []string{
   305  		fmt.Sprintf("ID|%s", limit(node.ID, c.length)),
   306  		fmt.Sprintf("Name|%s", node.Name),
   307  		fmt.Sprintf("Class|%s", node.NodeClass),
   308  		fmt.Sprintf("DC|%s", node.Datacenter),
   309  		fmt.Sprintf("Drain|%v", node.Drain),
   310  		fmt.Sprintf("Eligibility|%s", node.SchedulingEligibility),
   311  		fmt.Sprintf("Status|%s", node.Status),
   312  	}
   313  
   314  	if c.short {
   315  		basic = append(basic, fmt.Sprintf("Drivers|%s", strings.Join(nodeDrivers(node), ",")))
   316  		c.Ui.Output(c.Colorize().Color(formatKV(basic)))
   317  	} else {
   318  		// Get the host stats
   319  		hostStats, nodeStatsErr := client.Nodes().Stats(node.ID, nil)
   320  		if nodeStatsErr != nil {
   321  			c.Ui.Output("")
   322  			c.Ui.Error(fmt.Sprintf("error fetching node stats: %v", nodeStatsErr))
   323  		}
   324  		if hostStats != nil {
   325  			uptime := time.Duration(hostStats.Uptime * uint64(time.Second))
   326  			basic = append(basic, fmt.Sprintf("Uptime|%s", uptime.String()))
   327  		}
   328  
   329  		// Emit the driver info
   330  		if !c.verbose {
   331  			driverStatus := fmt.Sprintf("Driver Status| %s", c.outputTruncatedNodeDriverInfo(node))
   332  			basic = append(basic, driverStatus)
   333  		}
   334  
   335  		c.Ui.Output(c.Colorize().Color(formatKV(basic)))
   336  
   337  		if c.verbose {
   338  			c.outputNodeDriverInfo(node)
   339  		}
   340  
   341  		// Emit node events
   342  		c.outputNodeStatusEvents(node)
   343  
   344  		// Get list of running allocations on the node
   345  		runningAllocs, err := getRunningAllocs(client, node.ID)
   346  		if err != nil {
   347  			c.Ui.Error(fmt.Sprintf("Error querying node for running allocations: %s", err))
   348  			return 1
   349  		}
   350  
   351  		allocatedResources := getAllocatedResources(client, runningAllocs, node)
   352  		c.Ui.Output(c.Colorize().Color("\n[bold]Allocated Resources[reset]"))
   353  		c.Ui.Output(formatList(allocatedResources))
   354  
   355  		actualResources, err := getActualResources(client, runningAllocs, node)
   356  		if err == nil {
   357  			c.Ui.Output(c.Colorize().Color("\n[bold]Allocation Resource Utilization[reset]"))
   358  			c.Ui.Output(formatList(actualResources))
   359  		}
   360  
   361  		hostResources, err := getHostResources(hostStats, node)
   362  		if err != nil {
   363  			c.Ui.Output("")
   364  			c.Ui.Error(fmt.Sprintf("error fetching node stats: %v", err))
   365  		}
   366  		if err == nil {
   367  			c.Ui.Output(c.Colorize().Color("\n[bold]Host Resource Utilization[reset]"))
   368  			c.Ui.Output(formatList(hostResources))
   369  		}
   370  
   371  		if hostStats != nil && c.stats {
   372  			c.Ui.Output(c.Colorize().Color("\n[bold]CPU Stats[reset]"))
   373  			c.printCpuStats(hostStats)
   374  			c.Ui.Output(c.Colorize().Color("\n[bold]Memory Stats[reset]"))
   375  			c.printMemoryStats(hostStats)
   376  			c.Ui.Output(c.Colorize().Color("\n[bold]Disk Stats[reset]"))
   377  			c.printDiskStats(hostStats)
   378  		}
   379  	}
   380  
   381  	nodeAllocs, _, err := client.Nodes().Allocations(node.ID, nil)
   382  	if err != nil {
   383  		c.Ui.Error(fmt.Sprintf("Error querying node allocations: %s", err))
   384  		return 1
   385  	}
   386  
   387  	c.Ui.Output(c.Colorize().Color("\n[bold]Allocations[reset]"))
   388  	c.Ui.Output(formatAllocList(nodeAllocs, c.verbose, c.length))
   389  
   390  	if c.verbose {
   391  		c.formatAttributes(node)
   392  		c.formatMeta(node)
   393  	}
   394  	return 0
   395  
   396  }
   397  
   398  func (c *NodeStatusCommand) outputTruncatedNodeDriverInfo(node *api.Node) string {
   399  	drivers := make([]string, 0, len(node.Drivers))
   400  
   401  	for driverName, driverInfo := range node.Drivers {
   402  		if !driverInfo.Detected {
   403  			continue
   404  		}
   405  
   406  		if !driverInfo.Healthy {
   407  			drivers = append(drivers, fmt.Sprintf("%s (unhealthy)", driverName))
   408  		} else {
   409  			drivers = append(drivers, driverName)
   410  		}
   411  	}
   412  	sort.Strings(drivers)
   413  	return strings.Trim(strings.Join(drivers, ","), ", ")
   414  }
   415  
   416  func (c *NodeStatusCommand) outputNodeDriverInfo(node *api.Node) {
   417  	c.Ui.Output(c.Colorize().Color("\n[bold]Drivers"))
   418  
   419  	size := len(node.Drivers)
   420  	nodeDrivers := make([]string, 0, size+1)
   421  
   422  	nodeDrivers = append(nodeDrivers, "Driver|Detected|Healthy|Message|Time")
   423  
   424  	drivers := make([]string, 0, len(node.Drivers))
   425  	for driver := range node.Drivers {
   426  		drivers = append(drivers, driver)
   427  	}
   428  	sort.Strings(drivers)
   429  
   430  	for _, driver := range drivers {
   431  		info := node.Drivers[driver]
   432  		timestamp := formatTime(info.UpdateTime)
   433  		nodeDrivers = append(nodeDrivers, fmt.Sprintf("%s|%v|%v|%s|%s", driver, info.Detected, info.Healthy, info.HealthDescription, timestamp))
   434  	}
   435  	c.Ui.Output(formatList(nodeDrivers))
   436  }
   437  
   438  func (c *NodeStatusCommand) outputNodeStatusEvents(node *api.Node) {
   439  	c.Ui.Output(c.Colorize().Color("\n[bold]Node Events"))
   440  	c.outputNodeEvent(node.Events)
   441  }
   442  
   443  func (c *NodeStatusCommand) outputNodeEvent(events []*api.NodeEvent) {
   444  	size := len(events)
   445  	nodeEvents := make([]string, size+1)
   446  	if c.verbose {
   447  		nodeEvents[0] = "Time|Subsystem|Message|Details"
   448  	} else {
   449  		nodeEvents[0] = "Time|Subsystem|Message"
   450  	}
   451  
   452  	for i, event := range events {
   453  		timestamp := formatTime(event.Timestamp)
   454  		subsystem := formatEventSubsystem(event.Subsystem, event.Details["driver"])
   455  		msg := event.Message
   456  		if c.verbose {
   457  			details := formatEventDetails(event.Details)
   458  			nodeEvents[size-i] = fmt.Sprintf("%s|%s|%s|%s", timestamp, subsystem, msg, details)
   459  		} else {
   460  			nodeEvents[size-i] = fmt.Sprintf("%s|%s|%s", timestamp, subsystem, msg)
   461  		}
   462  	}
   463  	c.Ui.Output(formatList(nodeEvents))
   464  }
   465  
   466  func formatEventSubsystem(subsystem, driverName string) string {
   467  	if driverName == "" {
   468  		return subsystem
   469  	}
   470  
   471  	// If this event is for a driver, append the driver name to make the message
   472  	// clearer
   473  	return fmt.Sprintf("Driver: %s", driverName)
   474  }
   475  
   476  func formatEventDetails(details map[string]string) string {
   477  	output := make([]string, 0, len(details))
   478  	for k, v := range details {
   479  		output = append(output, fmt.Sprintf("%s: %s ", k, v))
   480  	}
   481  	return strings.Join(output, ", ")
   482  }
   483  
   484  func (c *NodeStatusCommand) formatAttributes(node *api.Node) {
   485  	// Print the attributes
   486  	keys := make([]string, len(node.Attributes))
   487  	for k := range node.Attributes {
   488  		keys = append(keys, k)
   489  	}
   490  	sort.Strings(keys)
   491  
   492  	var attributes []string
   493  	for _, k := range keys {
   494  		if k != "" {
   495  			attributes = append(attributes, fmt.Sprintf("%s|%s", k, node.Attributes[k]))
   496  		}
   497  	}
   498  	c.Ui.Output(c.Colorize().Color("\n[bold]Attributes[reset]"))
   499  	c.Ui.Output(formatKV(attributes))
   500  }
   501  
   502  func (c *NodeStatusCommand) formatMeta(node *api.Node) {
   503  	// Print the meta
   504  	keys := make([]string, 0, len(node.Meta))
   505  	for k := range node.Meta {
   506  		keys = append(keys, k)
   507  	}
   508  	sort.Strings(keys)
   509  
   510  	var meta []string
   511  	for _, k := range keys {
   512  		if k != "" {
   513  			meta = append(meta, fmt.Sprintf("%s|%s", k, node.Meta[k]))
   514  		}
   515  	}
   516  	c.Ui.Output(c.Colorize().Color("\n[bold]Meta[reset]"))
   517  	c.Ui.Output(formatKV(meta))
   518  }
   519  
   520  func (c *NodeStatusCommand) printCpuStats(hostStats *api.HostStats) {
   521  	l := len(hostStats.CPU)
   522  	for i, cpuStat := range hostStats.CPU {
   523  		cpuStatsAttr := make([]string, 4)
   524  		cpuStatsAttr[0] = fmt.Sprintf("CPU|%v", cpuStat.CPU)
   525  		cpuStatsAttr[1] = fmt.Sprintf("User|%v%%", humanize.FormatFloat(floatFormat, cpuStat.User))
   526  		cpuStatsAttr[2] = fmt.Sprintf("System|%v%%", humanize.FormatFloat(floatFormat, cpuStat.System))
   527  		cpuStatsAttr[3] = fmt.Sprintf("Idle|%v%%", humanize.FormatFloat(floatFormat, cpuStat.Idle))
   528  		c.Ui.Output(formatKV(cpuStatsAttr))
   529  		if i+1 < l {
   530  			c.Ui.Output("")
   531  		}
   532  	}
   533  }
   534  
   535  func (c *NodeStatusCommand) printMemoryStats(hostStats *api.HostStats) {
   536  	memoryStat := hostStats.Memory
   537  	memStatsAttr := make([]string, 4)
   538  	memStatsAttr[0] = fmt.Sprintf("Total|%v", humanize.IBytes(memoryStat.Total))
   539  	memStatsAttr[1] = fmt.Sprintf("Available|%v", humanize.IBytes(memoryStat.Available))
   540  	memStatsAttr[2] = fmt.Sprintf("Used|%v", humanize.IBytes(memoryStat.Used))
   541  	memStatsAttr[3] = fmt.Sprintf("Free|%v", humanize.IBytes(memoryStat.Free))
   542  	c.Ui.Output(formatKV(memStatsAttr))
   543  }
   544  
   545  func (c *NodeStatusCommand) printDiskStats(hostStats *api.HostStats) {
   546  	l := len(hostStats.DiskStats)
   547  	for i, diskStat := range hostStats.DiskStats {
   548  		diskStatsAttr := make([]string, 7)
   549  		diskStatsAttr[0] = fmt.Sprintf("Device|%s", diskStat.Device)
   550  		diskStatsAttr[1] = fmt.Sprintf("MountPoint|%s", diskStat.Mountpoint)
   551  		diskStatsAttr[2] = fmt.Sprintf("Size|%s", humanize.IBytes(diskStat.Size))
   552  		diskStatsAttr[3] = fmt.Sprintf("Used|%s", humanize.IBytes(diskStat.Used))
   553  		diskStatsAttr[4] = fmt.Sprintf("Available|%s", humanize.IBytes(diskStat.Available))
   554  		diskStatsAttr[5] = fmt.Sprintf("Used Percent|%v%%", humanize.FormatFloat(floatFormat, diskStat.UsedPercent))
   555  		diskStatsAttr[6] = fmt.Sprintf("Inodes Percent|%v%%", humanize.FormatFloat(floatFormat, diskStat.InodesUsedPercent))
   556  		c.Ui.Output(formatKV(diskStatsAttr))
   557  		if i+1 < l {
   558  			c.Ui.Output("")
   559  		}
   560  	}
   561  }
   562  
   563  // getRunningAllocs returns a slice of allocation id's running on the node
   564  func getRunningAllocs(client *api.Client, nodeID string) ([]*api.Allocation, error) {
   565  	var allocs []*api.Allocation
   566  
   567  	// Query the node allocations
   568  	nodeAllocs, _, err := client.Nodes().Allocations(nodeID, nil)
   569  	// Filter list to only running allocations
   570  	for _, alloc := range nodeAllocs {
   571  		if alloc.ClientStatus == "running" {
   572  			allocs = append(allocs, alloc)
   573  		}
   574  	}
   575  	return allocs, err
   576  }
   577  
   578  // getAllocatedResources returns the resource usage of the node.
   579  func getAllocatedResources(client *api.Client, runningAllocs []*api.Allocation, node *api.Node) []string {
   580  	// Compute the total
   581  	total := computeNodeTotalResources(node)
   582  
   583  	// Get Resources
   584  	var cpu, mem, disk, iops int
   585  	for _, alloc := range runningAllocs {
   586  		cpu += *alloc.Resources.CPU
   587  		mem += *alloc.Resources.MemoryMB
   588  		disk += *alloc.Resources.DiskMB
   589  		iops += *alloc.Resources.IOPS
   590  	}
   591  
   592  	resources := make([]string, 2)
   593  	resources[0] = "CPU|Memory|Disk|IOPS"
   594  	resources[1] = fmt.Sprintf("%d/%d MHz|%s/%s|%s/%s|%d/%d",
   595  		cpu,
   596  		*total.CPU,
   597  		humanize.IBytes(uint64(mem*bytesPerMegabyte)),
   598  		humanize.IBytes(uint64(*total.MemoryMB*bytesPerMegabyte)),
   599  		humanize.IBytes(uint64(disk*bytesPerMegabyte)),
   600  		humanize.IBytes(uint64(*total.DiskMB*bytesPerMegabyte)),
   601  		iops,
   602  		*total.IOPS)
   603  
   604  	return resources
   605  }
   606  
   607  // computeNodeTotalResources returns the total allocatable resources (resources
   608  // minus reserved)
   609  func computeNodeTotalResources(node *api.Node) api.Resources {
   610  	total := api.Resources{}
   611  
   612  	r := node.Resources
   613  	res := node.Reserved
   614  	if res == nil {
   615  		res = &api.Resources{}
   616  	}
   617  	total.CPU = helper.IntToPtr(*r.CPU - *res.CPU)
   618  	total.MemoryMB = helper.IntToPtr(*r.MemoryMB - *res.MemoryMB)
   619  	total.DiskMB = helper.IntToPtr(*r.DiskMB - *res.DiskMB)
   620  	total.IOPS = helper.IntToPtr(*r.IOPS - *res.IOPS)
   621  	return total
   622  }
   623  
   624  // getActualResources returns the actual resource usage of the allocations.
   625  func getActualResources(client *api.Client, runningAllocs []*api.Allocation, node *api.Node) ([]string, error) {
   626  	// Compute the total
   627  	total := computeNodeTotalResources(node)
   628  
   629  	// Get Resources
   630  	var cpu float64
   631  	var mem uint64
   632  	for _, alloc := range runningAllocs {
   633  		// Make the call to the client to get the actual usage.
   634  		stats, err := client.Allocations().Stats(alloc, nil)
   635  		if err != nil {
   636  			return nil, err
   637  		}
   638  
   639  		cpu += stats.ResourceUsage.CpuStats.TotalTicks
   640  		mem += stats.ResourceUsage.MemoryStats.RSS
   641  	}
   642  
   643  	resources := make([]string, 2)
   644  	resources[0] = "CPU|Memory"
   645  	resources[1] = fmt.Sprintf("%v/%d MHz|%v/%v",
   646  		math.Floor(cpu),
   647  		*total.CPU,
   648  		humanize.IBytes(mem),
   649  		humanize.IBytes(uint64(*total.MemoryMB*bytesPerMegabyte)))
   650  
   651  	return resources, nil
   652  }
   653  
   654  // getHostResources returns the actual resource usage of the node.
   655  func getHostResources(hostStats *api.HostStats, node *api.Node) ([]string, error) {
   656  	if hostStats == nil {
   657  		return nil, fmt.Errorf("actual resource usage not present")
   658  	}
   659  	var resources []string
   660  
   661  	// calculate disk usage
   662  	storageDevice := node.Attributes["unique.storage.volume"]
   663  	var diskUsed, diskSize uint64
   664  	var physical bool
   665  	for _, disk := range hostStats.DiskStats {
   666  		if disk.Device == storageDevice {
   667  			diskUsed = disk.Used
   668  			diskSize = disk.Size
   669  			physical = true
   670  		}
   671  	}
   672  
   673  	resources = make([]string, 2)
   674  	resources[0] = "CPU|Memory|Disk"
   675  	if physical {
   676  		resources[1] = fmt.Sprintf("%v/%d MHz|%s/%s|%s/%s",
   677  			math.Floor(hostStats.CPUTicksConsumed),
   678  			*node.Resources.CPU,
   679  			humanize.IBytes(hostStats.Memory.Used),
   680  			humanize.IBytes(hostStats.Memory.Total),
   681  			humanize.IBytes(diskUsed),
   682  			humanize.IBytes(diskSize),
   683  		)
   684  	} else {
   685  		// If non-physical device are used, output device name only,
   686  		// since nomad doesn't collect the stats data.
   687  		resources[1] = fmt.Sprintf("%v/%d MHz|%s/%s|(%s)",
   688  			math.Floor(hostStats.CPUTicksConsumed),
   689  			*node.Resources.CPU,
   690  			humanize.IBytes(hostStats.Memory.Used),
   691  			humanize.IBytes(hostStats.Memory.Total),
   692  			storageDevice,
   693  		)
   694  	}
   695  	return resources, nil
   696  }
   697  
   698  // formatNodeStubList is used to return a table format of a list of node stubs.
   699  func formatNodeStubList(nodes []*api.NodeListStub, verbose bool) string {
   700  	// Return error if no nodes are found
   701  	if len(nodes) == 0 {
   702  		return ""
   703  	}
   704  	// Truncate the id unless full length is requested
   705  	length := shortId
   706  	if verbose {
   707  		length = fullId
   708  	}
   709  
   710  	// Format the nodes list that matches the prefix so that the user
   711  	// can create a more specific request
   712  	out := make([]string, len(nodes)+1)
   713  	out[0] = "ID|DC|Name|Class|Drain|Eligibility|Status"
   714  	for i, node := range nodes {
   715  		out[i+1] = fmt.Sprintf("%s|%s|%s|%s|%v|%s|%s",
   716  			limit(node.ID, length),
   717  			node.Datacenter,
   718  			node.Name,
   719  			node.NodeClass,
   720  			node.Drain,
   721  			node.SchedulingEligibility,
   722  			node.Status)
   723  	}
   724  
   725  	return formatList(out)
   726  }