github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/resource/resourceadapters/opener.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package resourceadapters
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/names.v2"
     9  
    10  	csclient "github.com/juju/juju/charmstore"
    11  	"github.com/juju/juju/resource"
    12  	"github.com/juju/juju/resource/charmstore"
    13  	corestate "github.com/juju/juju/state"
    14  )
    15  
    16  // resourceOpener is an implementation of server.ResourceOpener.
    17  type resourceOpener struct {
    18  	st     *corestate.State
    19  	res    corestate.Resources
    20  	userID names.Tag
    21  	unit   *corestate.Unit
    22  }
    23  
    24  // OpenResource implements server.ResourceOpener.
    25  func (ro *resourceOpener) OpenResource(name string) (resource.Opened, error) {
    26  	if ro.unit == nil {
    27  		return resource.Opened{}, errors.Errorf("missing unit")
    28  	}
    29  	svc, err := ro.unit.Application()
    30  	if err != nil {
    31  		return resource.Opened{}, errors.Trace(err)
    32  	}
    33  	cURL, _ := ro.unit.CharmURL()
    34  	id := csclient.CharmID{
    35  		URL:     cURL,
    36  		Channel: svc.Channel(),
    37  	}
    38  
    39  	csOpener := newCharmstoreOpener(ro.st)
    40  	client, err := csOpener.NewClient()
    41  	if err != nil {
    42  		return resource.Opened{}, errors.Trace(err)
    43  	}
    44  
    45  	cache := &charmstoreEntityCache{
    46  		st:            ro.res,
    47  		userID:        ro.userID,
    48  		unit:          ro.unit,
    49  		applicationID: ro.unit.ApplicationName(),
    50  	}
    51  
    52  	res, reader, err := charmstore.GetResource(charmstore.GetResourceArgs{
    53  		Client:  client,
    54  		Cache:   cache,
    55  		CharmID: id,
    56  		Name:    name,
    57  	})
    58  	if err != nil {
    59  		return resource.Opened{}, errors.Trace(err)
    60  	}
    61  
    62  	opened := resource.Opened{
    63  		Resource:   res,
    64  		ReadCloser: reader,
    65  	}
    66  	return opened, nil
    67  }