mount.go 6.18 KB
Newer Older
Tommi Virtanen's avatar
Tommi Virtanen committed
1 2 3 4 5 6
// Package mount provides a Datastore that has other Datastores
// mounted at various key prefixes.
package mount

import (
	"errors"
7
	"fmt"
Jeromy's avatar
Jeromy committed
8
	"io"
9
	"sort"
Tommi Virtanen's avatar
Tommi Virtanen committed
10 11
	"strings"

Jeromy's avatar
Jeromy committed
12 13
	"github.com/ipfs/go-datastore"
	"github.com/ipfs/go-datastore/query"
Tommi Virtanen's avatar
Tommi Virtanen committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
)

var (
	ErrNoMount = errors.New("no datastore mounted for this key")
)

type Mount struct {
	Prefix    datastore.Key
	Datastore datastore.Datastore
}

func New(mounts []Mount) *Datastore {
	// make a copy so we're sure it doesn't mutate
	m := make([]Mount, len(mounts))
	for i, v := range mounts {
		m[i] = v
	}
31
	sort.Slice(m, func(i, j int) bool { return m[i].Prefix.String() > m[j].Prefix.String() })
Tommi Virtanen's avatar
Tommi Virtanen committed
32 33 34 35 36 37 38 39 40
	return &Datastore{mounts: m}
}

type Datastore struct {
	mounts []Mount
}

var _ datastore.Datastore = (*Datastore)(nil)

41
func (d *Datastore) lookup(key datastore.Key) (ds datastore.Datastore, mountpoint, rest datastore.Key) {
Tommi Virtanen's avatar
Tommi Virtanen committed
42
	for _, m := range d.mounts {
43
		if m.Prefix.Equal(key) || m.Prefix.IsAncestorOf(key) {
Tommi Virtanen's avatar
Tommi Virtanen committed
44 45
			s := strings.TrimPrefix(key.String(), m.Prefix.String())
			k := datastore.NewKey(s)
46
			return m.Datastore, m.Prefix, k
Tommi Virtanen's avatar
Tommi Virtanen committed
47 48
		}
	}
49
	return nil, datastore.NewKey("/"), key
Tommi Virtanen's avatar
Tommi Virtanen committed
50 51
}

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// lookupAll returns all mounts that might contain keys that are descendant of <key>
//
// Matching: /ao/e
//
// /          B /ao/e
// /a/        not matching
// /ao/       B /e
// /ao/e/     A /
// /ao/e/uh/  A /
// /aoe/      not matching
func (d *Datastore) lookupAll(key datastore.Key) (ds []datastore.Datastore, mountpoint, rest []datastore.Key) {
	for _, m := range d.mounts {
		p := m.Prefix.String()
		if len(p) > 1 {
			p = p + "/"
		}

		if strings.HasPrefix(p, key.String()) {
			ds = append(ds, m.Datastore)
			mountpoint = append(mountpoint, m.Prefix)
			rest = append(rest, datastore.NewKey("/"))
		} else if strings.HasPrefix(key.String(), p) {
			r := strings.TrimPrefix(key.String(), m.Prefix.String())

			ds = append(ds, m.Datastore)
			mountpoint = append(mountpoint, m.Prefix)
			rest = append(rest, datastore.NewKey(r))
		}
	}
	return ds, mountpoint, rest
}

Tommi Virtanen's avatar
Tommi Virtanen committed
84
func (d *Datastore) Put(key datastore.Key, value interface{}) error {
85
	ds, _, k := d.lookup(key)
Tommi Virtanen's avatar
Tommi Virtanen committed
86 87 88 89 90 91 92
	if ds == nil {
		return ErrNoMount
	}
	return ds.Put(k, value)
}

func (d *Datastore) Get(key datastore.Key) (value interface{}, err error) {
93
	ds, _, k := d.lookup(key)
Tommi Virtanen's avatar
Tommi Virtanen committed
94 95 96 97 98 99 100
	if ds == nil {
		return nil, datastore.ErrNotFound
	}
	return ds.Get(k)
}

func (d *Datastore) Has(key datastore.Key) (exists bool, err error) {
101
	ds, _, k := d.lookup(key)
Tommi Virtanen's avatar
Tommi Virtanen committed
102 103 104 105
	if ds == nil {
		return false, nil
	}
	return ds.Has(k)
Tommi Virtanen's avatar
Tommi Virtanen committed
106 107 108
}

func (d *Datastore) Delete(key datastore.Key) error {
109
	ds, _, k := d.lookup(key)
Tommi Virtanen's avatar
Tommi Virtanen committed
110 111 112 113
	if ds == nil {
		return datastore.ErrNotFound
	}
	return ds.Delete(k)
Tommi Virtanen's avatar
Tommi Virtanen committed
114 115 116
}

func (d *Datastore) Query(q query.Query) (query.Results, error) {
117 118 119 120
	if len(q.Filters) > 0 ||
		len(q.Orders) > 0 ||
		q.Limit > 0 ||
		q.Offset > 0 {
121 122
		// TODO this is still overly simplistic, but the only callers are
		// `ipfs refs local` and ipfs-ds-convert.
123 124
		return nil, errors.New("mount only supports listing all prefixed keys in random order")
	}
125 126 127 128 129 130 131 132 133 134 135 136 137 138
	prefix := datastore.NewKey(q.Prefix)
	dses, mounts, rests := d.lookupAll(prefix)

	// current itorator state
	var res query.Results
	var mount datastore.Key
	i := 0

	return query.ResultsFromIterator(q, query.Iterator{
		Next: func() (query.Result, bool) {
			var r query.Result
			var more bool

			for try := true; try; try = len(dses) > i {
139
				if res == nil {
140 141 142 143 144
					if len(dses) <= i {
						//This should not happen normally
						return query.Result{}, false
					}

145
					dst := dses[i]
146
					mount = mounts[i]
147
					rest := rests[i]
148 149 150

					q2 := q
					q2.Prefix = rest.String()
151
					r, err := dst.Query(q2)
152 153 154 155 156 157 158 159
					if err != nil {
						return query.Result{Error: err}, false
					}
					res = r
				}

				r, more = res.NextSync()
				if !more {
160 161 162 163 164 165
					err := res.Close()
					if err != nil {
						return query.Result{Error: err}, false
					}
					res = nil

166 167 168 169 170 171 172 173 174
					i++
					more = len(dses) > i
				} else {
					break
				}
			}

			r.Key = mount.Child(datastore.RawKey(r.Key)).String()
			return r, more
175
		},
176
		Close: func() error {
177
			if len(mounts) > i && res != nil {
178 179 180
				return res.Close()
			}
			return nil
181
		},
182
	}), nil
Tommi Virtanen's avatar
Tommi Virtanen committed
183
}
Jeromy's avatar
Jeromy committed
184

Jeromy's avatar
Jeromy committed
185 186 187 188 189 190 191 192 193 194 195 196
func (d *Datastore) Close() error {
	for _, d := range d.mounts {
		if c, ok := d.Datastore.(io.Closer); ok {
			err := c.Close()
			if err != nil {
				return err
			}
		}
	}
	return nil
}

Jeromy's avatar
Jeromy committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
type mountBatch struct {
	mounts map[string]datastore.Batch

	d *Datastore
}

func (d *Datastore) Batch() (datastore.Batch, error) {
	return &mountBatch{
		mounts: make(map[string]datastore.Batch),
		d:      d,
	}, nil
}

func (mt *mountBatch) lookupBatch(key datastore.Key) (datastore.Batch, datastore.Key, error) {
	child, loc, rest := mt.d.lookup(key)
	t, ok := mt.mounts[loc.String()]
	if !ok {
Jeromy's avatar
Jeromy committed
214
		bds, ok := child.(datastore.Batching)
Jeromy's avatar
Jeromy committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
		if !ok {
			return nil, datastore.NewKey(""), datastore.ErrBatchUnsupported
		}
		var err error
		t, err = bds.Batch()
		if err != nil {
			return nil, datastore.NewKey(""), err
		}
		mt.mounts[loc.String()] = t
	}
	return t, rest, nil
}

func (mt *mountBatch) Put(key datastore.Key, val interface{}) error {
	t, rest, err := mt.lookupBatch(key)
	if err != nil {
		return err
	}

	return t.Put(rest, val)
}

func (mt *mountBatch) Delete(key datastore.Key) error {
	t, rest, err := mt.lookupBatch(key)
	if err != nil {
		return err
	}

	return t.Delete(rest)
}

func (mt *mountBatch) Commit() error {
	for _, t := range mt.mounts {
		err := t.Commit()
		if err != nil {
			return err
		}
	}
	return nil
}
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

func (d *Datastore) Check() error {
	for _, m := range d.mounts {
		if c, ok := m.Datastore.(datastore.CheckedDatastore); ok {
			if err := c.Check(); err != nil {
				return fmt.Errorf("checking datastore at %s: %s", m.Prefix.String(), err.Error())
			}
		}
	}
	return nil
}

func (d *Datastore) Scrub() error {
	for _, m := range d.mounts {
		if c, ok := m.Datastore.(datastore.ScrubbedDatastore); ok {
			if err := c.Scrub(); err != nil {
				return fmt.Errorf("scrubbing datastore at %s: %s", m.Prefix.String(), err.Error())
			}
		}
	}
	return nil
}

func (d *Datastore) CollectGarbage() error {
	for _, m := range d.mounts {
		if c, ok := m.Datastore.(datastore.GCDatastore); ok {
			if err := c.CollectGarbage(); err != nil {
				return fmt.Errorf("gc on datastore at %s: %s", m.Prefix.String(), err.Error())
			}
		}
	}
	return nil
}