github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/client/cli/store/snapshot.go (about)

     1  package cli
     2  
     3  import (
     4  	"net/url"
     5  
     6  	snap "github.com/tickoalcantara12/micro/v3/client/cli/store/snapshot"
     7  	"github.com/tickoalcantara12/micro/v3/service/logger"
     8  	"github.com/pkg/errors"
     9  	"github.com/urfave/cli/v2"
    10  )
    11  
    12  // snapshot in the entrypoint for micro store snapshot
    13  func snapshot(ctx *cli.Context) error {
    14  	s, err := makeStore(ctx)
    15  	if err != nil {
    16  		return errors.Wrap(err, "couldn't construct a store")
    17  	}
    18  	log := logger.DefaultLogger
    19  	dest := ctx.String("destination")
    20  	var sn snap.Snapshot
    21  
    22  	if len(dest) == 0 {
    23  		return errors.New("destination flag must be set")
    24  	}
    25  	u, err := url.Parse(dest)
    26  	if err != nil {
    27  		return errors.Wrap(err, "destination is invalid")
    28  	}
    29  	switch u.Scheme {
    30  	case "file":
    31  		sn = snap.NewFileSnapshot(snap.Destination(dest))
    32  	default:
    33  		return errors.Errorf("unsupported destination scheme: %s", u.Scheme)
    34  	}
    35  	err = sn.Init()
    36  	if err != nil {
    37  		return errors.Wrap(err, "failed to initialise the snapshotter")
    38  	}
    39  
    40  	log.Logf(logger.InfoLevel, "Snapshotting store %s", s.String())
    41  	recordChan, err := sn.Start()
    42  	if err != nil {
    43  		return errors.Wrap(err, "couldn't start the snapshotter")
    44  	}
    45  	keys, err := s.List()
    46  	if err != nil {
    47  		return errors.Wrap(err, "couldn't List() from store "+s.String())
    48  	}
    49  	log.Logf(logger.DebugLevel, "Snapshotting %d keys", len(keys))
    50  
    51  	for _, key := range keys {
    52  		r, err := s.Read(key)
    53  		if err != nil {
    54  			return errors.Wrapf(err, "couldn't read key %s", key)
    55  		}
    56  		if len(r) != 1 {
    57  			return errors.Errorf("reading %s from %s returned 0 records", key, s.String())
    58  		}
    59  		recordChan <- r[0]
    60  	}
    61  	close(recordChan)
    62  	sn.Wait()
    63  	return nil
    64  }