github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/cmd/jujud/agent/simplestreams.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package agent
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"path"
    12  
    13  	"github.com/juju/juju/environs"
    14  	"github.com/juju/juju/environs/simplestreams"
    15  	envstorage "github.com/juju/juju/environs/storage"
    16  	"github.com/juju/juju/state/storage"
    17  )
    18  
    19  // environmentStorageDataSource is a simplestreams.DataSource that
    20  // retrieves simplestreams metadata from environment storage.
    21  type environmentStorageDataSource struct {
    22  	stor storage.Storage
    23  }
    24  
    25  // NewEnvironmentStorageDataSource returns a new datasource that retrieves
    26  // metadata from environment storage.
    27  func NewEnvironmentStorageDataSource(stor storage.Storage) simplestreams.DataSource {
    28  	return environmentStorageDataSource{stor}
    29  }
    30  
    31  // Description is defined in simplestreams.DataSource.
    32  func (d environmentStorageDataSource) Description() string {
    33  	return "environment storage"
    34  }
    35  
    36  // Fetch is defined in simplestreams.DataSource.
    37  func (d environmentStorageDataSource) Fetch(file string) (io.ReadCloser, string, error) {
    38  	logger.Debugf("fetching %q", file)
    39  
    40  	r, _, err := d.stor.Get(path.Join(envstorage.BaseImagesPath, file))
    41  	if err != nil {
    42  		return nil, "", err
    43  	}
    44  	data, err := ioutil.ReadAll(r)
    45  	if err != nil {
    46  		return nil, "", err
    47  	}
    48  
    49  	url, _ := d.URL(file)
    50  	return ioutil.NopCloser(bytes.NewReader(data)), url, nil
    51  }
    52  
    53  // URL is defined in simplestreams.DataSource.
    54  func (d environmentStorageDataSource) URL(file string) (string, error) {
    55  	path := path.Join(envstorage.BaseImagesPath, file)
    56  	return fmt.Sprintf("environment-storage://%s", path), nil
    57  }
    58  
    59  // Defined in simplestreams.DataSource.
    60  func (d environmentStorageDataSource) SetAllowRetry(allow bool) {
    61  }
    62  
    63  // registerSimplestreamsDataSource registers a environmentStorageDataSource.
    64  func registerSimplestreamsDataSource(stor storage.Storage) {
    65  	ds := NewEnvironmentStorageDataSource(stor)
    66  	environs.RegisterUserImageDataSourceFunc(ds.Description(), func(environs.Environ) (simplestreams.DataSource, error) {
    67  		return ds, nil
    68  	})
    69  }