-
Notifications
You must be signed in to change notification settings - Fork 37
/
store.go
1656 lines (1542 loc) · 48.7 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
49
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package charmstore // import "gopkg.in/juju/charmstore.v5/internal/charmstore"
import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"sync"
"time"
"github.com/juju/loggo"
"github.com/juju/utils/parallel"
"gopkg.in/errgo.v1"
"gopkg.in/juju/charm.v6"
"gopkg.in/juju/charmrepo.v3/csclient/params"
"gopkg.in/macaroon-bakery.v2-unstable/bakery"
"gopkg.in/macaroon-bakery.v2-unstable/bakery/mgostorage"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/juju/charmstore.v5/audit"
"gopkg.in/juju/charmstore.v5/internal/blobstore"
"gopkg.in/juju/charmstore.v5/internal/cache"
"gopkg.in/juju/charmstore.v5/internal/mongodoc"
"gopkg.in/juju/charmstore.v5/internal/monitoring"
"gopkg.in/juju/charmstore.v5/internal/router"
)
var logger = loggo.GetLogger("charmstore.internal.charmstore")
var (
errClosed = errgo.New("charm store has been closed")
ErrTooManySessions = errgo.New("too many mongo sessions in use")
)
// Pool holds a connection to the underlying charm and blob
// data stores. Calling its Store method returns a new Store
// from the pool that can be used to process short-lived requests
// to access and modify the store.
type Pool struct {
db StoreDatabase
es *SearchIndex
bakery *bakery.Service
stats stats
run *parallel.Run
// statsCache holds a cache of AggregatedCounts
// values, keyed by entity id. When the id has no
// revision, the counts apply to all revisions of the
// entity.
statsCache *cache.Cache
config ServerParams
// auditEncoder encodes messages to auditLogger.
auditEncoder *json.Encoder
auditLogger *lumberjack.Logger
// reqStoreC is a buffered channel that contains allocated
// stores that are not currently in use.
reqStoreC chan *Store
// mu guards the fields following it.
mu sync.Mutex
// storeCount holds the number of stores currently allocated.
storeCount int
// closed holds whether the handler has been closed.
closed bool
// rootKeys holds the cache of macaroon root keys.
rootKeys *mgostorage.RootKeys
}
// reqStoreCacheSize holds the maximum number of store
// instances to keep around cached when there is no
// limit specified by config.MaxMgoSessions.
const reqStoreCacheSize = 50
// maxAsyncGoroutines holds the maximum number
// of goroutines that will be started by Store.Go.
const maxAsyncGoroutines = 50
// NewPool returns a Pool that uses the given database
// and search index. If bakeryParams is not nil,
// the Bakery field in the resulting Store will be set
// to a new Service that stores macaroons in mongo.
//
// The pool must be closed (with the Close method)
// after use.
func NewPool(db *mgo.Database, si *SearchIndex, bakeryParams *bakery.NewServiceParams, config ServerParams) (*Pool, error) {
if config.StatsCacheMaxAge == 0 {
config.StatsCacheMaxAge = time.Hour
}
if config.NewBlobBackend == nil {
config.NewBlobBackend = func(db *mgo.Database) blobstore.Backend {
return blobstore.NewMongoBackend(db, "entitystore")
}
}
p := &Pool{
db: StoreDatabase{db}.copy(),
es: si,
statsCache: cache.New(config.StatsCacheMaxAge),
config: config,
run: parallel.NewRun(maxAsyncGoroutines),
auditLogger: config.AuditLogger,
rootKeys: mgostorage.NewRootKeys(100),
}
if config.MaxMgoSessions > 0 {
p.reqStoreC = make(chan *Store, config.MaxMgoSessions)
} else {
p.reqStoreC = make(chan *Store, reqStoreCacheSize)
}
if bakeryParams != nil {
bakerySvc, err := bakery.NewService(*bakeryParams)
if err != nil {
return nil, errgo.Notef(err, "cannot create bakery service")
}
p.bakery = bakerySvc
}
if config.AuditLogger != nil {
p.auditLogger = config.AuditLogger
p.auditEncoder = json.NewEncoder(p.auditLogger)
}
store := p.Store()
defer store.Close()
if !config.NoIndexes {
if err := store.ensureIndexes(); err != nil {
return nil, errgo.Notef(err, "cannot ensure indexes")
}
if err := store.ES.ensureIndexes(false); err != nil {
return nil, errgo.Notef(err, "cannot ensure elasticsearch indexes")
}
}
return p, nil
}
// Close closes the pool. This must be called when the pool
// is finished with.
func (p *Pool) Close() {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return
}
p.closed = true
p.mu.Unlock()
p.run.Wait()
p.db.Close()
// Close all cached stores. Any used by
// outstanding requests will be closed when the
// requests complete.
loop:
for {
select {
case s := <-p.reqStoreC:
s.DB.Close()
default:
break loop
}
}
if p.auditLogger != nil {
p.auditLogger.Close()
}
}
// RequestStore returns a store for a client request. It returns
// an error with a ErrTooManySessions cause
// if too many mongo sessions are in use.
func (p *Pool) RequestStore() (*Store, error) {
store, err := p.requestStoreNB(false)
if store != nil {
return store, nil
}
if errgo.Cause(err) != ErrTooManySessions {
return nil, errgo.Mask(err)
}
// No handlers currently available - we've exceeded our concurrency limit
// so wait for a handler to become available.
select {
case store := <-p.reqStoreC:
return store, nil
case <-time.After(p.config.HTTPRequestWaitDuration):
return nil, errgo.Mask(err, errgo.Is(ErrTooManySessions))
}
}
func (p *Pool) newBlobStore(db StoreDatabase) *blobstore.Store {
backend := p.config.NewBlobBackend(db.Database)
bs := blobstore.New(db.Database, "entitystore", backend)
if p.config.MinUploadPartSize != 0 {
bs.MinPartSize = p.config.MinUploadPartSize
}
if p.config.MaxUploadPartSize != 0 {
bs.MaxPartSize = p.config.MaxUploadPartSize
}
if p.config.MaxUploadParts != 0 {
bs.MaxParts = p.config.MaxUploadParts
}
return bs
}
// Store returns a Store that can be used to access the database.
//
// It must be closed (with the Close method) after use.
func (p *Pool) Store() *Store {
store, _ := p.requestStoreNB(true)
return store
}
// requestStoreNB is like RequestStore except that it
// does not block when a Store is not immediately
// available, in which case it returns an error with
// a ErrTooManySessions cause.
//
// If always is true, it will never return an error.
func (p *Pool) requestStoreNB(always bool) (*Store, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed && !always {
return nil, errClosed
}
select {
case store := <-p.reqStoreC:
return store, nil
default:
}
if !always && p.config.MaxMgoSessions > 0 && p.storeCount >= p.config.MaxMgoSessions {
return nil, ErrTooManySessions
}
p.storeCount++
db := p.db.copy()
store := &Store{
DB: db,
BlobStore: p.newBlobStore(db),
ES: p.es,
stats: &p.stats,
pool: p,
}
store.Bakery = store.BakeryWithPolicy(p.config.RootKeyPolicy)
return store, nil
}
// BakeryWithPolicy returns a copy of the Store's Bakery with a macaroon
// storage that returns root keys conforming to the given policy.
//
// If there is no configured bakery, it returns nil.
func (s *Store) BakeryWithPolicy(policy mgostorage.Policy) *bakery.Service {
if s.pool.bakery == nil {
return nil
}
return s.pool.bakery.WithStore(s.pool.rootKeys.NewStorage(s.DB.Macaroons(), policy))
}
// Store holds a connection to the underlying charm and blob
// data stores that is appropriate for short term use.
type Store struct {
DB StoreDatabase
BlobStore *blobstore.Store
ES *SearchIndex
Bakery *bakery.Service
stats *stats
pool *Pool
}
// Copy returns a new store with a lifetime
// independent of s. Use this method if you
// need to use a store in an independent goroutine.
//
// It must be closed (with the Close method) after use.
func (s *Store) Copy() *Store {
s1 := *s
s1.DB = s.DB.clone()
s1.BlobStore = s.pool.newBlobStore(s1.DB)
s1.Bakery = s1.BakeryWithPolicy(s.pool.config.RootKeyPolicy)
s.pool.mu.Lock()
s.pool.storeCount++
s.pool.mu.Unlock()
return &s1
}
// Close closes the store instance.
func (s *Store) Close() {
// Refresh the mongodb session so that the
// next time the Store is used, it will acquire
// a new connection from the pool as if the
// session had been copied.
s.DB.Session.Refresh()
s.pool.mu.Lock()
defer s.pool.mu.Unlock()
if !s.pool.closed && (s.pool.config.MaxMgoSessions == 0 || s.pool.storeCount <= s.pool.config.MaxMgoSessions) {
// The pool isn't overloaded, so put the store
// back. Note that the default case should
// never happen when MaxMgoSessions > 0.
select {
case s.pool.reqStoreC <- s:
return
default:
// No space for handler - this may happen when
// the number of actual sessions has exceeded
// the requested maximum (for example when
// a request already at the limit uses another session,
// or when we are imposing no limit).
}
}
s.DB.Close()
s.pool.storeCount--
}
// SetReconnectTimeout sets the length of time that
// mongo requests will block waiting to reconnect
// to a disconnected mongo server. If it is zero,
// requests may block forever.
func (s *Store) SetReconnectTimeout(d time.Duration) {
s.DB.Session.SetSyncTimeout(d)
}
// Go runs the given function in a new goroutine,
// passing it a copy of s, which will be closed
// after the function returns.
func (s *Store) Go(f func(*Store)) {
s = s.Copy()
s.pool.run.Do(func() error {
defer s.Close()
f(s)
return nil
})
}
// Pool returns the pool that the store originally
// came from.
func (s *Store) Pool() *Pool {
return s.pool
}
func (s *Store) ensureIndexes() error {
indexes := []struct {
c *mgo.Collection
i mgo.Index
}{{
s.DB.StatCounters(),
mgo.Index{Key: []string{"k", "t"}, Unique: true},
}, {
s.DB.StatTokens(),
mgo.Index{Key: []string{"t"}, Unique: true},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"baseurl"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"uploadtime"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"promulgated-url"}, Unique: true, Sparse: true},
}, {
s.DB.Logs(),
mgo.Index{Key: []string{"urls"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"user"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"user", "name"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"user", "name", "series"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"series"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"blobhash256"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"_id", "name"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"charmrequiredinterfaces"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"charmprovidedinterfaces"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"bundlecharms"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"name", "published", "-promulgated-revision", "-supportedseries"}},
}, {
s.DB.Entities(),
mgo.Index{Key: []string{"name", "published", "user", "-revision", "-supportedseries"}},
}, {
s.DB.BaseEntities(),
mgo.Index{Key: []string{"name"}},
}, {
s.DB.Resources(),
mgo.Index{Key: []string{"baseurl", "name"}},
}, {
s.DB.Resources(),
mgo.Index{Key: []string{"baseurl", "name", "revision"}, Unique: true},
}, {
// TODO this index should be created by the mgo gridfs code.
s.DB.C("entitystore.files"),
mgo.Index{Key: []string{"filename"}},
}, {
s.DB.Revisions(),
mgo.Index{Key: []string{"baseurl"}},
}}
for _, idx := range indexes {
err := idx.c.EnsureIndex(idx.i)
if err != nil {
return errgo.Notef(err, "cannot ensure index with keys %v on collection %s", idx.i, idx.c.Name)
}
}
if err := s.pool.rootKeys.EnsureIndex(s.DB.Macaroons()); err != nil {
return errgo.Notef(err, "cannot ensure root keys index")
}
return nil
}
// BlobStoreGC runs the blobstore garbage collector,
// deleting all blobs that have not been referenced since
// the given time.
func (s *Store) BlobStoreGC(before time.Time) error {
// BEWARE: if this code does not add all the relevant blob
// hashes, they will be removed by the garbage collector!
// Get entity counts so we can make an approximate
// measure of hash count.
entityCount, err := s.DB.Entities().Count()
if err != nil {
return errgo.Mask(err)
}
resourceCount, err := s.DB.Resources().Count()
if err != nil {
return errgo.Mask(err)
}
// Assume non-multipart resources, v5 entities that need conversion,
// and a 20% duplication rate,
estimatedRefCount := (entityCount*2 + resourceCount) * 4 / 5
refs := blobstore.NewRefs(estimatedRefCount)
iter := s.DB.Entities().Find(nil).Select(FieldSelector(
"prev5blobextrahash",
"blobhash",
"size",
)).Iter()
var entity mongodoc.Entity
for iter.Next(&entity) {
if entity.PreV5BlobExtraHash != "" {
refs.Add(entity.PreV5BlobExtraHash)
}
refs.Add(entity.BlobHash)
}
if err := iter.Err(); err != nil {
return errgo.Mask(err)
}
iter = s.DB.Resources().Find(nil).Select(FieldSelector(
"blobhash",
"blobindex",
)).Iter()
var resource mongodoc.Resource
for iter.Next(&resource) {
if resource.BlobIndex == nil {
refs.Add(resource.BlobHash)
continue
}
for _, hash := range resource.BlobIndex.Hashes {
refs.Add(hash)
}
}
if err := iter.Err(); err != nil {
return errgo.Mask(err)
}
stats, err := s.BlobStore.GC(refs, before)
if err != nil {
return errgo.Notef(err, "blobstore GC failed")
}
monitoring.SetBlobStoreStats(stats)
return nil
}
// AddAudit adds the given entry to the audit log.
func (s *Store) AddAudit(entry audit.Entry) {
s.addAuditAtTime(entry, time.Now())
}
func (s *Store) addAuditAtTime(entry audit.Entry, t time.Time) {
if s.pool.auditEncoder == nil {
return
}
entry.Time = t
err := s.pool.auditEncoder.Encode(entry)
if err != nil {
logger.Errorf("Cannot write audit log entry: %v", err)
}
}
// NewRevision returns a new revision number for the
// given entity URL.
func (s *Store) NewRevision(id *charm.URL) (int, error) {
id = id.WithRevision(-1)
col := s.DB.Revisions()
change := mgo.Change{
Update: bson.D{{"$inc", bson.D{{"revision", 1}}}},
ReturnNew: true,
}
var doc mongodoc.LatestRevision
_, err := col.FindId(id).Apply(change, &doc)
if err == nil {
return doc.Revision, nil
}
if err != mgo.ErrNotFound {
return 0, errgo.Notef(err, "cannot obtain new revision")
}
// This is the first revision of a given name.
firstRev := 0
if id.Series == "" {
// It's multi-series. Choose a revision that's greater
// than any existing single-series variant.
err := col.Find(bson.D{{"baseurl", mongodoc.BaseURL(id)}}).Sort("-revision").One(&doc)
if err == nil {
firstRev = doc.Revision + 1
} else if err != mgo.ErrNotFound {
return 0, errgo.Notef(err, "cannot find latest single-series revision")
}
}
err = col.Insert(mongodoc.LatestRevision{
URL: id,
BaseURL: mongodoc.BaseURL(id),
Revision: firstRev,
})
if mgo.IsDup(err) {
// We were in a race and they won. Recur to
// use the usual increment method to find the id.
return s.NewRevision(id)
}
return firstRev, nil
}
// AddRevision records a new revision of the given id,
// meaning that any subsequent NewRevision call
// for the id will return a higher revision number.
func (s *Store) AddRevision(id *router.ResolvedURL) error {
if err := s.addRevision(&id.URL); err != nil {
return errgo.Mask(err)
}
if purl := id.PromulgatedURL(); purl != nil {
if err := s.addRevision(purl); err != nil {
return errgo.Mask(err)
}
}
return nil
}
// addRevision is the internal version of AddRevision
// which acts on a single non-resolved URL.
func (s *Store) addRevision(id *charm.URL) error {
rev := id.Revision
id = id.WithRevision(-1)
_, err := s.DB.Revisions().Upsert(bson.D{
{"_id", id},
{"revision", bson.D{{"$lt", rev}}},
}, mongodoc.LatestRevision{
URL: id,
BaseURL: mongodoc.BaseURL(id),
Revision: rev,
})
if err == nil {
return nil
}
if mgo.IsDup(err) {
// We didn't find any documents to update
// but still failed to insert a new document,
// which implies that there is an existing
// document with a higher id.
return nil
}
return errgo.Notef(err, "cannot add revision")
}
// FindEntity finds the entity in the store with the given URL, which
// must be fully qualified. If the given URL has no user then it is
// assumed to be a promulgated entity. If fields is not nil, only its
// fields will be populated in the returned entities.
func (s *Store) FindEntity(url *router.ResolvedURL, fields map[string]int) (*mongodoc.Entity, error) {
q := s.DB.Entities().Find(bson.D{{"_id", &url.URL}})
if fields != nil {
q = q.Select(fields)
}
var entity mongodoc.Entity
err := q.One(&entity)
if err != nil {
if err == mgo.ErrNotFound {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "entity not found")
}
return nil, errgo.Mask(err)
}
return &entity, nil
}
// FindEntities finds all entities in the store matching the given URL.
// If the given URL has no user then only promulgated entities will be
// queried. If the given URL channel does not represent an entity under
// development then only published entities will be queried. If fields
// is not nil, only its fields will be populated in the returned
// entities.
func (s *Store) FindEntities(url *charm.URL, fields map[string]int) ([]*mongodoc.Entity, error) {
query := s.EntitiesQuery(url)
if fields != nil {
query = query.Select(fields)
}
var docs []*mongodoc.Entity
err := query.All(&docs)
if err != nil {
return nil, errgo.Notef(err, "cannot find entities matching %s", url)
}
return docs, nil
}
// FindBestEntity finds the entity that provides the preferred match to
// the given URL, on the given channel. If the given URL has no user
// then only promulgated entities will be queried. If fields is not nil,
// only those fields will be populated in the returned entities.
//
// If the URL contains a revision then it is assumed to be fully formed
// and refer to a single entity; the channel is ignored.
//
// If the URL does not contain a revision then the channel is searched
// for the best match, here NoChannel will be treated as
// params.StableChannel.
func (s *Store) FindBestEntity(url *charm.URL, channel params.Channel, fields map[string]int) (*mongodoc.Entity, error) {
if fields != nil {
// Make sure we have all the fields we need to make a decision.
// TODO this would be more efficient if we used bitmasks for field selection.
nfields := map[string]int{
"_id": 1,
"promulgated-url": 1,
"promulgated-revision": 1,
"series": 1,
"revision": 1,
"published": 1,
}
for f := range fields {
nfields[f] = 1
}
fields = nfields
}
if url.Revision != -1 {
// If the URL contains a revision, then it refers to a single entity.
entity, err := s.findSingleEntity(url, fields)
if errgo.Cause(err) == params.ErrNotFound {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "no matching charm or bundle for %s", url)
} else if err != nil {
return nil, errgo.Mask(err)
}
// If a channel was specified make sure the entity is in that channel.
// This is crucial because if we don't do this, then the user could choose
// to use any chosen set of ACLs against any entity.
if params.ValidChannels[channel] && channel != params.UnpublishedChannel && !entity.Published[channel] {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "%s not found in %s channel", url, channel)
}
return entity, nil
}
switch channel {
case params.UnpublishedChannel:
return s.findUnpublishedEntity(url, fields)
case params.NoChannel:
channel = params.StableChannel
fallthrough
default:
return s.findEntityInChannel(url, channel, fields)
}
}
// findSingleEntity returns the entity referred to by URL. It is expected
// that the URL refers to only one entity and is fully formed. The url may
// refer to either a user-owned or promulgated charm name.
func (s *Store) findSingleEntity(url *charm.URL, fields map[string]int) (*mongodoc.Entity, error) {
query := s.EntitiesQuery(url)
if fields != nil {
query = query.Select(fields)
}
var entity mongodoc.Entity
err := query.One(&entity)
if err == nil {
return &entity, nil
}
if err == mgo.ErrNotFound {
return nil, errgo.WithCausef(err, params.ErrNotFound, "no matching charm or bundle for %s", url)
}
return nil, errgo.Notef(err, "cannot find entities matching %s", url)
}
// findEntityInChannel attempts to find an entity on the given channel. The
// base entity for URL is retrieved and the series with the best match to
// URL.Series is used as the resolved entity.
func (s *Store) findEntityInChannel(url *charm.URL, ch params.Channel, fields map[string]int) (*mongodoc.Entity, error) {
baseEntity, err := s.FindBaseEntity(url, map[string]int{
"_id": 1,
"channelentities": 1,
})
if errgo.Cause(err) == params.ErrNotFound {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "no matching charm or bundle for %s", url)
} else if err != nil {
return nil, errgo.Mask(err)
}
var entityURL *charm.URL
if url.Series == "" {
var entitySeries string
for s, u := range baseEntity.ChannelEntities[ch] {
// Determine the preferred URL from the available series.
//
// Note that because each of the series has a different
// score the only situation where the score in the URL is
// where there is more than one series supported by a
// multi-series charm. In this case the tie is broken by
// looking for the preferred series from the ones
// supported by the charm. To save fetching every charm
// to look at the supported series the key is used,
// because when a charm is listed as the published
// version for a series it must support that series.
if entityURL == nil ||
seriesScore[u.Series] > seriesScore[entityURL.Series] ||
// Note that if the two series are the same, they must both be
// multi-series URLs.
seriesScore[u.Series] == seriesScore[entityURL.Series] && seriesScore[s] > seriesScore[entitySeries] {
entityURL = u
entitySeries = s
}
}
} else {
entityURL = baseEntity.ChannelEntities[ch][url.Series]
}
if entityURL == nil {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "no matching charm or bundle for %s", url)
}
return s.findSingleEntity(entityURL, fields)
}
// findUnpublishedEntity attempts to find an entity on the unpublished
// channel. This searches all entities in the store for the best match to
// the URL.
func (s *Store) findUnpublishedEntity(url *charm.URL, fields map[string]int) (*mongodoc.Entity, error) {
entities, err := s.FindEntities(url, fields)
if err != nil {
return nil, errgo.Mask(err)
}
if len(entities) == 0 {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "no matching charm or bundle for %s", url)
}
best := entities[0]
for _, e := range entities {
if seriesScore[e.Series] > seriesScore[best.Series] {
best = e
continue
}
if seriesScore[e.Series] < seriesScore[best.Series] {
continue
}
if url.User == "" {
if e.PromulgatedRevision > best.PromulgatedRevision {
best = e
continue
}
} else {
if e.Revision > best.Revision {
best = e
continue
}
}
}
return best, nil
}
var seriesScore = map[string]int{
"bundle": -1,
"lucid": 1000,
"precise": 1001,
"trusty": 1002,
"xenial": 1003,
"bionic": 1004,
"quantal": 1,
"raring": 2,
"saucy": 3,
"utopic": 4,
"vivid": 5,
"wily": 6,
"yakkety": 7,
"zesty": 8,
"artful": 9,
"cosmic": 0, // TODO: make this higher when cosmic is released
// When we find a multi-series charm (no series) we
// will always choose it in preference to a series-specific
// charm
"": 5000,
}
var seriesBundleOrEmpty = bson.D{{"$or", []bson.D{{{"series", "bundle"}}, {{"series", ""}}}}}
// EntitiesQuery creates a mgo.Query object that can be used to find entities
// matching the given URL. If the given URL has no user then the produced query
// will only match promulgated entities.
func (s *Store) EntitiesQuery(url *charm.URL) *mgo.Query {
entities := s.DB.Entities()
query := make(bson.D, 1, 5)
query[0] = bson.DocElem{"name", url.Name}
if url.User == "" {
if url.Revision > -1 {
query = append(query, bson.DocElem{"promulgated-revision", url.Revision})
} else {
query = append(query, bson.DocElem{"promulgated-revision", bson.D{{"$gt", -1}}})
}
} else {
query = append(query, bson.DocElem{"user", url.User})
if url.Revision > -1 {
query = append(query, bson.DocElem{"revision", url.Revision})
}
}
if url.Series == "" {
if url.Revision > -1 {
// If we're specifying a revision we must be searching
// for a canonical URL, so search for a multi-series
// charm or a bundle.
query = append(query, seriesBundleOrEmpty...)
}
} else if url.Series == "bundle" {
query = append(query, bson.DocElem{"series", "bundle"})
} else {
query = append(query, bson.DocElem{"supportedseries", url.Series})
}
return entities.Find(query)
}
// FindBaseEntity finds the base entity in the store using the given URL,
// which can either represent a fully qualified entity or a base id.
// If fields is not nil, only those fields will be populated in the
// returned base entity.
func (s *Store) FindBaseEntity(url *charm.URL, fields map[string]int) (*mongodoc.BaseEntity, error) {
var query *mgo.Query
if url.User == "" {
query = s.DB.BaseEntities().Find(bson.D{{"name", url.Name}, {"promulgated", 1}})
} else {
query = s.DB.BaseEntities().FindId(mongodoc.BaseURL(url))
}
if fields != nil {
query = query.Select(fields)
}
var baseEntity mongodoc.BaseEntity
if err := query.One(&baseEntity); err != nil {
if err == mgo.ErrNotFound {
return nil, errgo.WithCausef(nil, params.ErrNotFound, "base entity not found")
}
return nil, errgo.Notef(err, "cannot find base entity %v", url)
}
return &baseEntity, nil
}
// FieldSelector returns a field selector that will select
// the given fields, or all fields if none are specified.
func FieldSelector(fields ...string) map[string]int {
if len(fields) == 0 {
return nil
}
sel := make(map[string]int, len(fields))
for _, field := range fields {
sel[field] = 1
}
return sel
}
// UpdateEntity applies the provided update to the entity described by
// url. If there are no entries in update then no update is performed,
// and no error is returned.
func (s *Store) UpdateEntity(url *router.ResolvedURL, update bson.D) error {
if len(update) == 0 {
return nil
}
if err := s.DB.Entities().Update(bson.D{{"_id", &url.URL}}, update); err != nil {
if err == mgo.ErrNotFound {
return errgo.WithCausef(err, params.ErrNotFound, "cannot update %q", url)
}
return errgo.Notef(err, "cannot update %q", url)
}
return nil
}
// UpdateBaseEntity applies the provided update to the base entity of
// url. If there are no entries in update then no update is performed,
// and no error is returned.
func (s *Store) UpdateBaseEntity(url *router.ResolvedURL, update bson.D) error {
if len(update) == 0 {
return nil
}
if err := s.DB.BaseEntities().Update(bson.D{{"_id", mongodoc.BaseURL(&url.URL)}}, update); err != nil {
if err == mgo.ErrNotFound {
return errgo.WithCausef(err, params.ErrNotFound, "cannot update base entity for %q", url)
}
return errgo.Notef(err, "cannot update base entity for %q", url)
}
return nil
}
var ErrPublishResourceMismatch = errgo.Newf("charm published with incorrect resources")
// Publish assigns channels to the entity corresponding to the given URL.
// An error is returned if no channels are provided. See params.ValidChannels
// for the list of supported channels. The unpublished channel cannot
// be provided.
//
// If the given resources do not match those expected or they're not
// found, an error with a ErrPublichResourceMismatch cause will be returned.
func (s *Store) Publish(url *router.ResolvedURL, resources map[string]int, channels ...params.Channel) error {
var updateSearch bool
// Throw away any channels that we don't like.
actualChannels := make([]params.Channel, 0, len(channels))
for _, c := range channels {
if !params.ValidChannels[c] || c == params.UnpublishedChannel {
continue
}
actualChannels = append(actualChannels, c)
if c == params.StableChannel {
updateSearch = true
}
}
channels = actualChannels
if len(channels) == 0 {
return errgo.Newf("cannot update %q: no valid channels provided", url)
}
entity, err := s.FindEntity(url, FieldSelector("series", "supportedseries", "charmmeta", "baseurl"))
if err != nil {
return errgo.Mask(err, errgo.Is(params.ErrNotFound))
}
resourceDocs := make([]mongodoc.ResourceRevision, 0, len(resources))
if err = s.checkPublishedResources(entity, resources); err != nil {
return errgo.WithCausef(err, ErrPublishResourceMismatch, "")
}
for name, rev := range resources {
resourceDocs = append(resourceDocs, mongodoc.ResourceRevision{
Name: name,
Revision: rev,
})
}
series := entity.SupportedSeries
if len(series) == 0 {
series = []string{entity.Series}
}
// Update the entity's published channels.
update := make(bson.D, 0, len(channels)*(len(series)+1)) // ...ish.
for _, c := range channels {
update = append(update, bson.DocElem{"published." + string(c), true})
}
if err := s.UpdateEntity(url, bson.D{{"$set", update}}); err != nil {
return errgo.Mask(err, errgo.Is(params.ErrNotFound))
}
// Update the base entity.
update = update[:0]
for _, c := range channels {
for _, s := range series {
update = append(update, bson.DocElem{fmt.Sprintf("channelentities.%s.%s", c, s), entity.URL})
}
update = append(update, bson.DocElem{fmt.Sprintf("channelresources.%s", c), resourceDocs})
}
if err := s.UpdateBaseEntity(url, bson.D{{"$set", update}}); err != nil {
return errgo.Mask(err)
}
if !updateSearch {
return nil
}
// Add entity to ElasticSearch.
if err := s.UpdateSearch(url); err != nil {
return errgo.Notef(err, "cannot index %s to ElasticSearch", url)
}
return nil
}
func (s *Store) checkPublishedResources(entity *mongodoc.Entity, resources map[string]int) error {
knownResources, _, err := s.charmResources(entity.BaseURL)
if err != nil {
return errgo.Mask(err)
}
for name, rev := range resources {
if !charmHasResource(entity.CharmMeta, name) {