github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/state/autocertcache.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package state 5 6 import ( 7 "github.com/juju/errors" 8 "golang.org/x/crypto/acme/autocert" 9 "golang.org/x/net/context" 10 "gopkg.in/mgo.v2" 11 12 "github.com/juju/juju/mongo" 13 ) 14 15 // AutocertCache returns an implementation 16 // of autocert.Cache backed by the state. 17 func (st *State) AutocertCache() autocert.Cache { 18 return autocertCache{st} 19 } 20 21 type autocertCache struct { 22 st *State 23 } 24 25 type autocertCacheDoc struct { 26 Name string `bson:"_id"` 27 Data []byte `bson:"data"` 28 } 29 30 // Put implements autocert.Cache.Put. 31 func (cache autocertCache) Put(ctx context.Context, name string, data []byte) error { 32 coll, closeColl := cache.coll() 33 defer closeColl() 34 _, err := coll.UpsertId(name, autocertCacheDoc{ 35 Name: name, 36 Data: data, 37 }) 38 if err != nil { 39 return errors.Annotatef(err, "cannot store autocert key %q", name) 40 } 41 return nil 42 } 43 44 // Get implements autocert.Cache.Get. 45 func (cache autocertCache) Get(ctx context.Context, name string) ([]byte, error) { 46 coll, closeColl := cache.coll() 47 defer closeColl() 48 var doc autocertCacheDoc 49 err := coll.FindId(name).One(&doc) 50 if err == nil { 51 return doc.Data, nil 52 } 53 if errors.Cause(err) == mgo.ErrNotFound { 54 return nil, autocert.ErrCacheMiss 55 } 56 return nil, errors.Annotatef(err, "cannot get autocert key %q", name) 57 } 58 59 // Delete implements autocert.Cache.Delete. 60 func (cache autocertCache) Delete(ctx context.Context, name string) error { 61 coll, closeColl := cache.coll() 62 defer closeColl() 63 err := coll.RemoveId(name) 64 if err == nil || errors.Cause(err) == mgo.ErrNotFound { 65 return nil 66 } 67 return errors.Annotatef(err, "cannot delete autocert key %q", name) 68 } 69 70 func (cache autocertCache) coll() (mongo.WriteCollection, func()) { 71 coll, closer := cache.st.getCollection(autocertCacheC) 72 return coll.Writeable(), closer 73 }