providers.go 7.44 KB
Newer Older
1 2 3
package providers

import (
Jeromy's avatar
Jeromy committed
4
	"context"
5 6 7 8 9
	"encoding/binary"
	"fmt"
	"strings"
	"time"

10
	lru "github.com/hashicorp/golang-lru"
11
	cid "github.com/ipfs/go-cid"
12
	ds "github.com/ipfs/go-datastore"
Hector Sanjuan's avatar
Hector Sanjuan committed
13
	autobatch "github.com/ipfs/go-datastore/autobatch"
14 15 16 17
	dsq "github.com/ipfs/go-datastore/query"
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
18
	peer "github.com/libp2p/go-libp2p-peer"
19
	base32 "github.com/whyrusleeping/base32"
20 21
)

22 23
var batchBufferSize = 256

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
var log = logging.Logger("providers")

var lruCacheSize = 256
var ProvideValidity = time.Hour * 24
var defaultCleanupInterval = time.Hour

type ProviderManager struct {
	// all non channel fields are meant to be accessed only within
	// the run method
	providers *lru.Cache
	dstore    ds.Datastore

	newprovs chan *addProv
	getprovs chan *getProv
	proc     goprocess.Process

	cleanupInterval time.Duration
}

type providerSet struct {
	providers []peer.ID
	set       map[peer.ID]time.Time
}

type addProv struct {
49
	k   cid.Cid
50 51 52 53
	val peer.ID
}

type getProv struct {
54
	k    cid.Cid
55 56 57
	resp chan []peer.ID
}

58
func NewProviderManager(ctx context.Context, local peer.ID, dstore ds.Batching) *ProviderManager {
59 60 61
	pm := new(ProviderManager)
	pm.getprovs = make(chan *getProv)
	pm.newprovs = make(chan *addProv)
62
	pm.dstore = autobatch.NewAutoBatching(dstore, batchBufferSize)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	cache, err := lru.New(lruCacheSize)
	if err != nil {
		panic(err) //only happens if negative value is passed to lru constructor
	}
	pm.providers = cache

	pm.proc = goprocessctx.WithContext(ctx)
	pm.cleanupInterval = defaultCleanupInterval
	pm.proc.Go(func(p goprocess.Process) { pm.run() })

	return pm
}

const providersKeyPrefix = "/providers/"

78
func mkProvKey(k cid.Cid) string {
79
	return providersKeyPrefix + base32.RawStdEncoding.EncodeToString(k.Bytes())
80 81 82 83 84 85
}

func (pm *ProviderManager) Process() goprocess.Process {
	return pm.proc
}

86
func (pm *ProviderManager) providersForKey(k cid.Cid) ([]peer.ID, error) {
87 88 89 90 91 92 93
	pset, err := pm.getProvSet(k)
	if err != nil {
		return nil, err
	}
	return pset.providers, nil
}

94
func (pm *ProviderManager) getProvSet(k cid.Cid) (*providerSet, error) {
95
	cached, ok := pm.providers.Get(k.KeyString())
96 97 98 99 100 101 102 103 104 105
	if ok {
		return cached.(*providerSet), nil
	}

	pset, err := loadProvSet(pm.dstore, k)
	if err != nil {
		return nil, err
	}

	if len(pset.providers) > 0 {
106
		pm.providers.Add(k.KeyString(), pset)
107 108 109 110 111
	}

	return pset, nil
}

112
func loadProvSet(dstore ds.Datastore, k cid.Cid) (*providerSet, error) {
113
	res, err := dstore.Query(dsq.Query{Prefix: mkProvKey(k)})
114 115 116 117 118
	if err != nil {
		return nil, err
	}

	out := newProviderSet()
119 120 121 122 123
	for {
		e, ok := res.NextSync()
		if !ok {
			break
		}
124
		if e.Error != nil {
125
			log.Error("got an error: ", e.Error)
126 127 128
			continue
		}

129 130 131
		lix := strings.LastIndex(e.Key, "/")

		decstr, err := base32.RawStdEncoding.DecodeString(e.Key[lix+1:])
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		if err != nil {
			log.Error("base32 decoding error: ", err)
			continue
		}

		pid := peer.ID(decstr)

		t, err := readTimeValue(e.Value)
		if err != nil {
			log.Warning("parsing providers record from disk: ", err)
			continue
		}

		out.setVal(pid, t)
	}

	return out, nil
}

func readTimeValue(i interface{}) (time.Time, error) {
	data, ok := i.([]byte)
	if !ok {
		return time.Time{}, fmt.Errorf("data was not a []byte")
	}

	nsec, _ := binary.Varint(data)

	return time.Unix(0, nsec), nil
}

162
func (pm *ProviderManager) addProv(k cid.Cid, p peer.ID) error {
163
	iprovs, ok := pm.providers.Get(k.KeyString())
164
	if !ok {
165 166 167 168 169
		stored, err := loadProvSet(pm.dstore, k)
		if err != nil {
			return err
		}
		iprovs = stored
170
		pm.providers.Add(k.KeyString(), iprovs)
171 172 173 174 175 176 177 178
	}
	provs := iprovs.(*providerSet)
	now := time.Now()
	provs.setVal(p, now)

	return writeProviderEntry(pm.dstore, k, p, now)
}

179
func writeProviderEntry(dstore ds.Datastore, k cid.Cid, p peer.ID, t time.Time) error {
180
	dsk := mkProvKey(k) + "/" + base32.RawStdEncoding.EncodeToString([]byte(p))
181 182 183 184

	buf := make([]byte, 16)
	n := binary.PutVarint(buf, t.UnixNano())

185
	return dstore.Put(ds.NewKey(dsk), buf[:n])
186 187
}

188
func (pm *ProviderManager) deleteProvSet(k cid.Cid) error {
189
	pm.providers.Remove(k.KeyString())
190 191 192

	res, err := pm.dstore.Query(dsq.Query{
		KeysOnly: true,
193
		Prefix:   mkProvKey(k),
194
	})
195 196 197
	if err != nil {
		return err
	}
198 199 200 201 202 203 204

	entries, err := res.Rest()
	if err != nil {
		return err
	}

	for _, e := range entries {
205
		err := pm.dstore.Delete(ds.NewKey(e.Key))
206 207 208 209 210 211 212
		if err != nil {
			log.Error("deleting provider set: ", err)
		}
	}
	return nil
}

213
func (pm *ProviderManager) getProvKeys() (func() (cid.Cid, bool), error) {
214
	res, err := pm.dstore.Query(dsq.Query{
215
		KeysOnly: true,
216 217 218 219 220 221
		Prefix:   providersKeyPrefix,
	})
	if err != nil {
		return nil, err
	}

222
	iter := func() (cid.Cid, bool) {
223 224 225
		for e := range res.Next() {
			parts := strings.Split(e.Key, "/")
			if len(parts) != 4 {
226
				log.Warningf("incorrectly formatted provider entry in datastore: %s", e.Key)
227 228 229 230
				continue
			}
			decoded, err := base32.RawStdEncoding.DecodeString(parts[2])
			if err != nil {
231
				log.Warning("error decoding base32 provider key: %s: %s", parts[2], err)
232 233
				continue
			}
234

235 236
			c, err := cid.Cast(decoded)
			if err != nil {
237
				log.Warning("error casting key to cid from datastore key: %s", err)
238 239
				continue
			}
240

241
			return c, true
242
		}
243
		return cid.Cid{}, false
244 245
	}

246
	return iter, nil
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
}

func (pm *ProviderManager) run() {
	tick := time.NewTicker(pm.cleanupInterval)
	for {
		select {
		case np := <-pm.newprovs:
			err := pm.addProv(np.k, np.val)
			if err != nil {
				log.Error("error adding new providers: ", err)
			}
		case gp := <-pm.getprovs:
			provs, err := pm.providersForKey(gp.k)
			if err != nil && err != ds.ErrNotFound {
				log.Error("error reading providers: ", err)
			}

			gp.resp <- provs
		case <-tick.C:
266
			keys, err := pm.getProvKeys()
267 268 269 270
			if err != nil {
				log.Error("Error loading provider keys: ", err)
				continue
			}
Steven Allen's avatar
Steven Allen committed
271
			now := time.Now()
272 273 274 275 276 277
			for {
				k, ok := keys()
				if !ok {
					break
				}

278 279 280 281 282 283
				provs, err := pm.getProvSet(k)
				if err != nil {
					log.Error("error loading known provset: ", err)
					continue
				}
				for p, t := range provs.set {
Steven Allen's avatar
Steven Allen committed
284
					if now.Sub(t) > ProvideValidity {
285 286 287
						delete(provs.set, p)
					}
				}
Steven Allen's avatar
Steven Allen committed
288 289 290
				// have we run out of providers?
				if len(provs.set) == 0 {
					provs.providers = nil
291 292 293 294
					err := pm.deleteProvSet(k)
					if err != nil {
						log.Error("error deleting provider set: ", err)
					}
Steven Allen's avatar
Steven Allen committed
295 296
				} else if len(provs.set) < len(provs.providers) {
					// We must have modified the providers set, recompute.
Steven Allen's avatar
Steven Allen committed
297 298 299 300
					provs.providers = make([]peer.ID, 0, len(provs.set))
					for p := range provs.set {
						provs.providers = append(provs.providers, p)
					}
301 302 303
				}
			}
		case <-pm.proc.Closing():
304
			tick.Stop()
305 306 307 308 309
			return
		}
	}
}

310
func (pm *ProviderManager) AddProvider(ctx context.Context, k cid.Cid, val peer.ID) {
311 312 313 314 315 316 317 318 319 320
	prov := &addProv{
		k:   k,
		val: val,
	}
	select {
	case pm.newprovs <- prov:
	case <-ctx.Done():
	}
}

321
func (pm *ProviderManager) GetProviders(ctx context.Context, k cid.Cid) []peer.ID {
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	gp := &getProv{
		k:    k,
		resp: make(chan []peer.ID, 1), // buffered to prevent sender from blocking
	}
	select {
	case <-ctx.Done():
		return nil
	case pm.getprovs <- gp:
	}
	select {
	case <-ctx.Done():
		return nil
	case peers := <-gp.resp:
		return peers
	}
}

func newProviderSet() *providerSet {
	return &providerSet{
		set: make(map[peer.ID]time.Time),
	}
}

func (ps *providerSet) Add(p peer.ID) {
	ps.setVal(p, time.Now())
}

func (ps *providerSet) setVal(p peer.ID, t time.Time) {
	_, found := ps.set[p]
	if !found {
		ps.providers = append(ps.providers, p)
	}

	ps.set[p] = t
}