strategy.go 1.87 KB
Newer Older
1 2 3
package strategy

import (
Jeromy's avatar
Jeromy committed
4 5 6 7
	//blocks "github.com/jbenet/go-ipfs/blocks"
	//bstore "github.com/jbenet/go-ipfs/blocks/blockstore"
	//wl "github.com/jbenet/go-ipfs/exchange/bitswap/wantlist"
	//peer "github.com/jbenet/go-ipfs/peer"
8 9 10
	u "github.com/jbenet/go-ipfs/util"
)

11 12
var log = u.Logger("strategy")

Jeromy's avatar
Jeromy committed
13
/*
14 15 16 17 18 19 20 21 22 23
// TODO niceness should be on a per-peer basis. Use-case: Certain peers are
// "trusted" and/or controlled by a single human user. The user may want for
// these peers to exchange data freely
func New(nice bool) Strategy {
	var stratFunc strategyFunc
	if nice {
		stratFunc = yesManStrategy
	} else {
		stratFunc = standardStrategy
	}
24
	return &strategist{
25
		strategyFunc: stratFunc,
26 27 28 29
	}
}

type strategist struct {
30
	strategyFunc
31 32
}

Jeromy's avatar
Jeromy committed
33
func (s *strategist) GetTasks(bandwidth int, ledgers *LedgerManager, bs bstore.Blockstore) ([]*Task, error) {
Jeromy's avatar
Jeromy committed
34 35
	var tasks []*Task

36
	ledgers.lock.RLock()
Jeromy's avatar
Jeromy committed
37
	var partners []peer.Peer
38 39
	for _, ledger := range ledgers.ledgerMap {
		if s.strategyFunc(ledger) {
Jeromy's avatar
Jeromy committed
40 41 42
			partners = append(partners, ledger.Partner)
		}
	}
43
	ledgers.lock.RUnlock()
Jeromy's avatar
Jeromy committed
44 45 46 47 48 49
	if len(partners) == 0 {
		return nil, nil
	}

	bandwidthPerPeer := bandwidth / len(partners)
	for _, p := range partners {
50
		blksForPeer, err := s.getSendableBlocks(ledgers.ledger(p).wantList, bs, bandwidthPerPeer)
Jeromy's avatar
Jeromy committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
		if err != nil {
			return nil, err
		}
		tasks = append(tasks, &Task{
			Peer:   p,
			Blocks: blksForPeer,
		})
	}

	return tasks, nil
}

func (s *strategist) getSendableBlocks(wantlist *wl.Wantlist, bs bstore.Blockstore, bw int) ([]*blocks.Block, error) {
	var outblocks []*blocks.Block
	for _, e := range wantlist.Entries() {
		block, err := bs.Get(e.Value)
67
		if err == bstore.ErrNotFound {
Jeromy's avatar
Jeromy committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81
			continue
		}
		if err != nil {
			return nil, err
		}
		outblocks = append(outblocks, block)
		bw -= len(block.Data)
		if bw <= 0 {
			break
		}
	}
	return outblocks, nil
}

82
func test() {}
83 84 85
func (s *strategist) Seed(int64) {
	// TODO
}
Jeromy's avatar
Jeromy committed
86 87

*/