github.com/hhrutter/nomad@v0.6.0-rc2.0.20170723054333-80c4b03f0705/client/fingerprint/storage.go (about)

     1  package fingerprint
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"strconv"
     8  
     9  	"github.com/hashicorp/nomad/client/config"
    10  	"github.com/hashicorp/nomad/nomad/structs"
    11  )
    12  
    13  const bytesPerMegabyte = 1024 * 1024
    14  
    15  // StorageFingerprint is used to measure the amount of storage free for
    16  // applications that the Nomad agent will run on this machine.
    17  type StorageFingerprint struct {
    18  	StaticFingerprinter
    19  	logger *log.Logger
    20  }
    21  
    22  func NewStorageFingerprint(logger *log.Logger) Fingerprint {
    23  	fp := &StorageFingerprint{logger: logger}
    24  	return fp
    25  }
    26  
    27  func (f *StorageFingerprint) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
    28  
    29  	// Initialize these to empty defaults
    30  	node.Attributes["unique.storage.volume"] = ""
    31  	node.Attributes["unique.storage.bytestotal"] = ""
    32  	node.Attributes["unique.storage.bytesfree"] = ""
    33  	if node.Resources == nil {
    34  		node.Resources = &structs.Resources{}
    35  	}
    36  
    37  	// Guard against unset AllocDir
    38  	storageDir := cfg.AllocDir
    39  	if storageDir == "" {
    40  		var err error
    41  		storageDir, err = os.Getwd()
    42  		if err != nil {
    43  			return false, fmt.Errorf("unable to get CWD from filesystem: %s", err)
    44  		}
    45  	}
    46  
    47  	volume, total, free, err := f.diskFree(storageDir)
    48  	if err != nil {
    49  		return false, fmt.Errorf("failed to determine disk space for %s: %v", storageDir, err)
    50  	}
    51  
    52  	node.Attributes["unique.storage.volume"] = volume
    53  	node.Attributes["unique.storage.bytestotal"] = strconv.FormatUint(total, 10)
    54  	node.Attributes["unique.storage.bytesfree"] = strconv.FormatUint(free, 10)
    55  
    56  	node.Resources.DiskMB = int(free / bytesPerMegabyte)
    57  
    58  	return true, nil
    59  }