github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/volume/store/db.go (about)

     1  package store
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/boltdb/bolt"
     7  	"github.com/pkg/errors"
     8  	"github.com/sirupsen/logrus"
     9  )
    10  
    11  var volumeBucketName = []byte("volumes")
    12  
    13  type volumeMetadata struct {
    14  	Name    string
    15  	Driver  string
    16  	Labels  map[string]string
    17  	Options map[string]string
    18  }
    19  
    20  func (s *VolumeStore) setMeta(name string, meta volumeMetadata) error {
    21  	return s.db.Update(func(tx *bolt.Tx) error {
    22  		return setMeta(tx, name, meta)
    23  	})
    24  }
    25  
    26  func setMeta(tx *bolt.Tx, name string, meta volumeMetadata) error {
    27  	metaJSON, err := json.Marshal(meta)
    28  	if err != nil {
    29  		return err
    30  	}
    31  	b := tx.Bucket(volumeBucketName)
    32  	return errors.Wrap(b.Put([]byte(name), metaJSON), "error setting volume metadata")
    33  }
    34  
    35  func (s *VolumeStore) getMeta(name string) (volumeMetadata, error) {
    36  	var meta volumeMetadata
    37  	err := s.db.View(func(tx *bolt.Tx) error {
    38  		return getMeta(tx, name, &meta)
    39  	})
    40  	return meta, err
    41  }
    42  
    43  func getMeta(tx *bolt.Tx, name string, meta *volumeMetadata) error {
    44  	b := tx.Bucket(volumeBucketName)
    45  	val := b.Get([]byte(name))
    46  	if string(val) == "" {
    47  		return nil
    48  	}
    49  	if err := json.Unmarshal(val, meta); err != nil {
    50  		return errors.Wrap(err, "error unmarshaling volume metadata")
    51  	}
    52  	return nil
    53  }
    54  
    55  func (s *VolumeStore) removeMeta(name string) error {
    56  	return s.db.Update(func(tx *bolt.Tx) error {
    57  		return removeMeta(tx, name)
    58  	})
    59  }
    60  
    61  func removeMeta(tx *bolt.Tx, name string) error {
    62  	b := tx.Bucket(volumeBucketName)
    63  	return errors.Wrap(b.Delete([]byte(name)), "error removing volume metadata")
    64  }
    65  
    66  // listMeta is used during restore to get the list of volume metadata
    67  // from the on-disk database.
    68  // Any errors that occur are only logged.
    69  func listMeta(tx *bolt.Tx) []volumeMetadata {
    70  	var ls []volumeMetadata
    71  	b := tx.Bucket(volumeBucketName)
    72  	b.ForEach(func(k, v []byte) error {
    73  		if len(v) == 0 {
    74  			// don't try to unmarshal an empty value
    75  			return nil
    76  		}
    77  
    78  		var m volumeMetadata
    79  		if err := json.Unmarshal(v, &m); err != nil {
    80  			// Just log the error
    81  			logrus.Errorf("Error while reading volume metadata for volume %q: %v", string(k), err)
    82  			return nil
    83  		}
    84  		ls = append(ls, m)
    85  		return nil
    86  	})
    87  	return ls
    88  }