github.com/thanos-io/thanos@v0.32.5/pkg/block/metadata/hash.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package metadata
     5  
     6  import (
     7  	"encoding/hex"
     8  	"fmt"
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  
    13  	"github.com/go-kit/log"
    14  	"github.com/minio/sha256-simd"
    15  	"github.com/pkg/errors"
    16  
    17  	"github.com/thanos-io/thanos/pkg/runutil"
    18  )
    19  
    20  // HashFunc indicates what type of hash it is.
    21  type HashFunc string
    22  
    23  const (
    24  	// SHA256Func shows that SHA256 has been used to generate the hash.
    25  	SHA256Func HashFunc = "SHA256"
    26  	// NoneFunc shows that hashes should not be added. Used internally.
    27  	NoneFunc HashFunc = ""
    28  )
    29  
    30  // ObjectHash stores the hash of an object in the object storage.
    31  type ObjectHash struct {
    32  	Func  HashFunc `json:"hashFunc"`
    33  	Value string   `json:"value"`
    34  }
    35  
    36  // Equal returns true if two hashes are equal.
    37  func (oh *ObjectHash) Equal(other *ObjectHash) bool {
    38  	return oh.Value == other.Value
    39  }
    40  
    41  // CalculateHash calculates the hash of the given type.
    42  func CalculateHash(p string, hf HashFunc, logger log.Logger) (ObjectHash, error) {
    43  	switch hf {
    44  	case SHA256Func:
    45  		f, err := os.Open(filepath.Clean(p))
    46  		if err != nil {
    47  			return ObjectHash{}, errors.Wrap(err, "opening file")
    48  		}
    49  		defer runutil.CloseWithLogOnErr(logger, f, "closing %s", p)
    50  
    51  		h := sha256.New()
    52  
    53  		if _, err := io.Copy(h, f); err != nil {
    54  			return ObjectHash{}, errors.Wrap(err, "copying")
    55  		}
    56  
    57  		return ObjectHash{
    58  			Func:  SHA256Func,
    59  			Value: hex.EncodeToString(h.Sum(nil)),
    60  		}, nil
    61  	}
    62  	return ObjectHash{}, fmt.Errorf("hash function %v is not supported", hf)
    63  
    64  }