lxd/db/node.go
func (c *ClusterTx) NodeWithLeastContainers() (string, error) {
	threshold, err := c.NodeOfflineThreshold()
	if err != nil {
		return "", errors.Wrap(err, "failed to get offline threshold")
	}
	nodes, err := c.Nodes()
	if err != nil {
		return "", errors.Wrap(err, "failed to get current nodes")
	}

	name := ""
	containers := -1
	for _, node := range nodes {
		if node.IsOffline(threshold) {
			continue
		}

		// Fetch the number of containers already created on this node.
		created, err := query.Count(c.tx, "containers", "node_id=?", node.ID)
		if err != nil {
			return "", errors.Wrap(err, "Failed to get containers count")
		}

		// Fetch the number of containers currently being created on this node.
		pending, err := query.Count(
			c.tx, "operations", "node_id=? AND type=?", node.ID, OperationContainerCreate)
		if err != nil {
			return "", errors.Wrap(err, "Failed to get pending containers count")
		}

		count := created + pending
		if containers == -1 || count < containers {
			containers = count
			name = node.Name
		}
	}
	return name, nil
}
func (c *ClusterTx) NodeWithLeastContainers() (string, error) {
	threshold, err := c.NodeOfflineThreshold()
	if err != nil {
		return "", errors.Wrap(err, "failed to get offline threshold")
	}
	nodes, err := c.Nodes()
	if err != nil {
		return "", errors.Wrap(err, "failed to get current nodes")
	}

	name := ""
	containers := -1
	for _, node := range nodes {
		if node.IsOffline(threshold) {
			continue
		}

		// Fetch the number of containers already created on this node.
		created, err := query.Count(c.tx, "containers", "node_id=?", node.ID)
		if err != nil {
			return "", errors.Wrap(err, "Failed to get containers count")
		}

		// Fetch the number of containers currently being created on this node.
		pending, err := query.Count(
			c.tx, "operations", "node_id=? AND type=?", node.ID, OperationContainerCreate)
		if err != nil {
			return "", errors.Wrap(err, "Failed to get pending containers count")
		}

		count := created + pending
		if containers == -1 || count < containers {
			containers = count
			name = node.Name
		}
	}
	return name, nil
}
// NodeWithLeastContainers returns the name of the non-offline node with with
// the least number of containers (either already created or being created with
// an operation).