storj/pkg/storage/segments/store.go

227 lines
5.9 KiB
Go
Raw Normal View History

// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package segment
import (
"context"
"io"
"time"
monkit "gopkg.in/spacemonkeygo/monkit.v2"
"storj.io/storj/pkg/eestream"
"storj.io/storj/pkg/kademlia"
"storj.io/storj/pkg/overlay"
"storj.io/storj/pkg/paths"
"storj.io/storj/pkg/piecestore/rpc/client"
"storj.io/storj/pkg/pointerdb"
"storj.io/storj/pkg/ranger"
"storj.io/storj/pkg/storage"
"storj.io/storj/pkg/storage/ec"
opb "storj.io/storj/protos/overlay"
ppb "storj.io/storj/protos/pointerdb"
)
var (
mon = monkit.Package()
)
// Meta will contain encryption and stream information
type Meta struct {
Data []byte
}
// Store for segments
type Store interface {
Meta(ctx context.Context, path paths.Path) (meta Meta, err error)
Get(ctx context.Context, path paths.Path) (rr ranger.RangeCloser,
meta Meta, err error)
Put(ctx context.Context, path paths.Path, data io.Reader, metadata []byte,
expiration time.Time) (meta Meta, err error)
Delete(ctx context.Context, path paths.Path) (err error)
List(ctx context.Context, prefix, startAfter, endBefore paths.Path,
recursive bool, limit int, metaFlags uint64) (items []storage.ListItem,
more bool, err error)
}
type segmentStore struct {
oc overlay.Client
ec ecclient.Client
pdb pointerdb.Client
rs eestream.RedundancyStrategy
}
// NewSegmentStore creates a new instance of segmentStore
func NewSegmentStore(oc overlay.Client, ec ecclient.Client,
pdb pointerdb.Client, rs eestream.RedundancyStrategy) Store {
return &segmentStore{oc: oc, ec: ec, pdb: pdb, rs: rs}
}
// Meta retrieves the metadata of the segment
func (s *segmentStore) Meta(ctx context.Context, path paths.Path) (meta Meta,
err error) {
defer mon.Task()(&ctx)(&err)
pr, err := s.pdb.Get(ctx, path, nil)
if err != nil {
return Meta{}, Error.Wrap(err)
}
return Meta{Data: pr.GetMetadata()}, nil
}
// Put uploads a segment to an erasure code client
func (s *segmentStore) Put(ctx context.Context, path paths.Path, data io.Reader,
metadata []byte, expiration time.Time) (meta Meta, err error) {
defer mon.Task()(&ctx)(&err)
// uses overlay client to request a list of nodes
nodes, err := s.oc.Choose(ctx, s.rs.TotalCount(), 0)
if err != nil {
return Meta{}, Error.Wrap(err)
}
pieceID := client.NewPieceID()
// puts file to ecclient
err = s.ec.Put(ctx, nodes, s.rs, pieceID, data, expiration)
if err != nil {
return Meta{}, Error.Wrap(err)
}
var remotePieces []*ppb.RemotePiece
for i := range nodes {
remotePieces = append(remotePieces, &ppb.RemotePiece{
PieceNum: int64(i),
NodeId: nodes[i].Id,
})
}
// creates pointer
pr := &ppb.Pointer{
Type: ppb.Pointer_REMOTE,
Remote: &ppb.RemoteSegment{
Redundancy: &ppb.RedundancyScheme{
Type: ppb.RedundancyScheme_RS,
MinReq: int64(s.rs.RequiredCount()),
Total: int64(s.rs.TotalCount()),
RepairThreshold: int64(s.rs.Min),
SuccessThreshold: int64(s.rs.Opt),
},
PieceId: string(pieceID),
RemotePieces: remotePieces,
},
Metadata: metadata,
}
// puts pointer to pointerDB
err = s.pdb.Put(ctx, path, pr, nil)
if err != nil {
return Meta{}, Error.Wrap(err)
}
// get the metadata for the newly uploaded segment
m, err := s.Meta(ctx, path)
if err != nil {
return Meta{}, Error.Wrap(err)
}
return m, nil
}
// Get retrieves a segment using erasure code, overlay, and pointerdb clients
func (s *segmentStore) Get(ctx context.Context, path paths.Path) (
rr ranger.RangeCloser, meta Meta, err error) {
defer mon.Task()(&ctx)(&err)
pr, err := s.pdb.Get(ctx, path, nil)
if err != nil {
return nil, Meta{}, Error.Wrap(err)
}
if pr.GetType() != ppb.Pointer_REMOTE {
return nil, Meta{}, Error.New("TODO: only getting remote pointers supported")
}
seg := pr.GetRemote()
pid := client.PieceID(seg.PieceId)
nodes, err := s.lookupNodes(ctx, seg)
if err != nil {
return nil, Meta{}, Error.Wrap(err)
}
rr, err = s.ec.Get(ctx, nodes, s.rs, pid, pr.GetSize())
if err != nil {
return nil, Meta{}, Error.Wrap(err)
}
return rr, Meta{Data: pr.GetMetadata()}, nil
}
// Delete tells piece stores to delete a segment and deletes pointer from pointerdb
func (s *segmentStore) Delete(ctx context.Context, path paths.Path) (err error) {
defer mon.Task()(&ctx)(&err)
pr, err := s.pdb.Get(ctx, path, nil)
if err != nil {
return Error.Wrap(err)
}
if pr.GetType() != ppb.Pointer_REMOTE {
return Error.New("TODO: only getting remote pointers supported")
}
seg := pr.GetRemote()
pid := client.PieceID(seg.PieceId)
nodes, err := s.lookupNodes(ctx, seg)
if err != nil {
return Error.Wrap(err)
}
// ecclient sends delete request
err = s.ec.Delete(ctx, nodes, pid)
if err != nil {
return Error.Wrap(err)
}
// deletes pointer from pointerdb
return s.pdb.Delete(ctx, path, nil)
}
// lookupNodes calls Lookup to get node addresses from the overlay
func (s *segmentStore) lookupNodes(ctx context.Context, seg *ppb.RemoteSegment) (
nodes []*opb.Node, err error) {
nodes = make([]*opb.Node, len(seg.GetRemotePieces()))
for i, p := range seg.GetRemotePieces() {
node, err := s.oc.Lookup(ctx, kademlia.StringToNodeID(p.GetNodeId()))
if err != nil {
// TODO better error handling: failing to lookup a few nodes should
// not fail the request
return nil, Error.Wrap(err)
}
nodes[i] = node
}
return nodes, nil
}
// List retrieves paths to segments and their metadata stored in the pointerdb
func (s *segmentStore) List(ctx context.Context, prefix, startAfter,
endBefore paths.Path, recursive bool, limit int, metaFlags uint64) (
items []storage.ListItem, more bool, err error) {
defer mon.Task()(&ctx)(&err)
captplanet (#159) * captplanet I kind of went overboard this weekend. The major goal of this changeset is to provide an environment for local development where all of the various services can be easily run together. Developing on Storj v3 should be as easy as running a setup command and a run command! To do this, this changeset introduces a new tool called captplanet, which combines the powers of the Overlay Cache, the PointerDB, the PieceStore, Kademlia, the Minio Gateway, etc. Running 40 farmers and a heavy client inside the same process forced a rethinking of the "services" that we had. To avoid confusion by reusing prior terms, this changeset introduces two new types: Providers and Responsibilities. I wanted to avoid as many merge conflicts as possible, so I left the existing Services and code for now, but if people like this route we can clean up the duplication. A Responsibility is a collection of gRPC methods and corresponding state. The following systems are examples of Responsibilities: * Kademlia * OverlayCache * PointerDB * StatDB * PieceStore * etc. A Provider is a collection of Responsibilities that share an Identity, such as: * The heavy client * The farmer * The gateway An Identity is a public/private key pair, a node id, etc. Farmers all need different Identities, so captplanet needs to support running multiple concurrent Providers with different Identities. Each Responsibility and Provider should allow for configuration of multiple copies on its own so creating Responsibilities and Providers use a new workflow. To make a Responsibility, one should create a "config" struct, such as: ``` type Config struct { RepairThreshold int `help:"If redundancy falls below this number of pieces, repair is triggered" default:"30"` SuccessThreshold int `help:"If redundancy is above this number then no additional uploads are needed" default:"40"` } ``` To use "config" structs, this changeset introduces another new library called 'cfgstruct', which allows for the configuration of arbitrary structs through flagsets, and thus through cobra and viper. cfgstruct relies on Go's "struct tags" feature to document help information and default values. Config structs can be configured via cfgstruct.Bind for binding the struct to a flagset. Because this configuration system makes setup and configuration easier *in general*, additional commands are provided that allow for easy standup of separate Providers. Please make sure to check out: * cmd/captplanet/farmer/main.go (a new farmer binary) * cmd/captplanet/hc/main.go (a new heavy client binary) * cmd/captplanet/gw/main.go (a new minio gateway binary) Usage: ``` $ go install -v storj.io/storj/cmd/captplanet $ captplanet setup $ captplanet run ``` Configuration is placed by default in `~/.storj/capt/` Other changes: * introduces new config structs for currently existing Responsibilities that conform to the new Responsibility interface. Please see the `pkg/*/config.go` files for examples. * integrates the PointerDB API key with other global configuration via flags, instead of through environment variables through viper like it's been doing. (ultimately this should also change to use the PointerDB config struct but this is an okay shortterm solution). * changes the Overlay cache to use a URL for database configuration instead of separate redis and bolt config settings. * stubs out some peer identity skeleton code (but not the meat). * Fixes the SegmentStore to use the overlay client and pointerdb clients instead of gRPC client code directly * Leaves a very clear spot where we need to tie the object to stream to segment store together. There's sort of a "golden spike" opportunity to connect all the train tracks together at the bottom of pkg/miniogw/config.go, labeled with a bunch of TODOs. Future stuff: * I now prefer this design over the original pkg/process.Service thing I had been pushing before (sorry!) * The experience of trying to have multiple farmers configurable concurrently led me to prefer config structs over global flags (I finally came around) or using viper directly. I think global flags are okay sometimes but in general going forward we should try and get all relevant config into config structs. * If you all like this direction, I think we can go delete my old Service interfaces and a bunch of flags and clean up a bunch of stuff. * If you don't like this direction, it's no sweat at all, and despite how much code there is here I'm not very tied to any of this! Considering a lot of this was written between midnight and 6 am, it might not be any good! * bind tests
2018-07-24 17:08:28 +01:00
res, more, err := s.pdb.List(ctx, startAfter, int64(limit), nil)
if err != nil {
return nil, false, Error.Wrap(err)
}
items = make([]storage.ListItem, len(res))
for i, path := range res {
items[i].Path = paths.New(string(path))
// TODO items[i].Meta =
}
return items, more, nil
}