charmhub

package
v0.0.0-...-b0bff92 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2021 License: AGPL-3.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CharmHubServerURL     = "https://api.charmhub.io"
	CharmHubServerVersion = "v2"
	CharmHubServerEntity  = "charms"

	MetadataHeader = "X-Juju-Metadata"

	RefreshTimeout = 10 * time.Second
)

ServerURL holds the default location of the global charm hub. An alternate location can be configured by changing the URL field in the Params struct.

View Source
const (
	// DefaultRetryAttempts defines the number of attempts that a default http
	// transport will retry before giving up.
	// Retries are only performed on certain status codes, nothing in the 200 to
	// 400 range and a select few from the 500 range (deemed retryable):
	//
	// - http.StatusBadGateway
	// - http.StatusGatewayTimeout
	// - http.StatusServiceUnavailable
	// - http.StatusTooManyRequests
	//
	// See: juju/http package.
	DefaultRetryAttempts = 3

	// DefaultRetryDelay holds the amount of time after a try, a new attempt
	// will wait before another attempt.
	DefaultRetryDelay = time.Second * 10

	// DefaultRetryMaxDelay holds the amount of time before a giving up on a
	// request. This values includes any server response from the header
	// Retry-After.
	DefaultRetryMaxDelay = time.Minute * 10
)
View Source
const (
	// NotAvailable is used a placeholder for Name and Channel for a refresh
	// base request, if the Name and Channel is not known.
	NotAvailable = "NA"
)

Variables

This section is empty.

Functions

func APIError

func APIError(err error) (transport.APIError, error)

APIError extracts an API error from the given error or returns an error.

func APIErrors

func APIErrors(err error) (transport.APIErrors, error)

APIErrors extracts a slice of API errors from the given error or returns an error.

func CreateInstanceKey

func CreateInstanceKey(app names.ApplicationTag, model names.ModelTag) string

CreateInstanceKey creates an InstanceKey which can be unique and stable from Refresh action to Refresh action. Required for KPI collection on the charmhub side, see LP:1944582. Rather than saving in state, use the model uuid + the app name, which are unique. Modeled after the applicationDoc DocID and globalKey in state.

func DefaultRetryPolicy

func DefaultRetryPolicy() jujuhttp.RetryPolicy

DefaultRetryPolicy returns a retry policy with sane defaults for most requests.

func ExtractConfigInstanceKey

func ExtractConfigInstanceKey(cfg RefreshConfig) string

ExtractConfigInstanceKey is used to get the instance key from a refresh config.

func IsAPIError

func IsAPIError(err error) bool

IsAPIError checks to see if the error is a valid API error.

func IsAPIErrors

func IsAPIErrors(err error) bool

IsAPIErrors checks to see if the error is a valid series of API errors.

func RequestHTTPTransport

func RequestHTTPTransport(recorder jujuhttp.RequestRecorder, policy jujuhttp.RetryPolicy) func(logger Logger) Transport

RequestHTTPTransport creates a new HTTPTransport that records the requests.

Types

type APIRequestLogger

type APIRequestLogger struct {
	// contains filtered or unexported fields
}

APIRequestLogger creates a wrapper around the transport to allow for better logging.

func NewAPIRequesterLogger

func NewAPIRequesterLogger(transport Transport, logger Logger) *APIRequestLogger

NewAPIRequesterLogger creates a new Transport that allows logging of requests for every request.

func (*APIRequestLogger) Do

func (t *APIRequestLogger) Do(req *http.Request) (*http.Response, error)

Do performs the *http.Request and returns a *http.Response or an error if it fails to construct the transport.

type APIRequester

type APIRequester struct {
	// contains filtered or unexported fields
}

APIRequester creates a wrapper around the transport to allow for better error handling.

func NewAPIRequester

func NewAPIRequester(transport Transport, logger Logger) *APIRequester

NewAPIRequester creates a new http.Client for making requests to a server.

func (*APIRequester) Do

func (t *APIRequester) Do(req *http.Request) (*http.Response, error)

Do performs the *http.Request and returns a *http.Response or an error if it fails to construct the transport.

type Action

type Action string

Action represents the type of refresh is performed.

const (
	// InstallAction defines a install action.
	InstallAction Action = "install"

	// DownloadAction defines a download action.
	DownloadAction Action = "download"

	// RefreshAction defines a refresh action.
	RefreshAction Action = "refresh"
)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents the client side of a charm store.

func NewClient

func NewClient(config Config) (*Client, error)

NewClient creates a new charmHub client from the supplied configuration.

func NewClientWithFileSystem

func NewClientWithFileSystem(config Config, fileSystem FileSystem) (*Client, error)

NewClientWithFileSystem creates a new charmHub client from the supplied configuration and a file system.

func (*Client) Download

func (c *Client) Download(ctx context.Context, resourceURL *url.URL, archivePath string, options ...DownloadOption) error

Download defines a client for downloading charms directly.

func (*Client) DownloadAndRead

func (c *Client) DownloadAndRead(ctx context.Context, resourceURL *url.URL, archivePath string, options ...DownloadOption) (*charm.CharmArchive, error)

DownloadAndRead defines a client for downloading charms directly.

func (*Client) DownloadAndReadBundle

func (c *Client) DownloadAndReadBundle(ctx context.Context, resourceURL *url.URL, archivePath string, options ...DownloadOption) (charm.Bundle, error)

DownloadAndReadBundle defines a client for downloading bundles directly.

func (*Client) DownloadResource

func (c *Client) DownloadResource(ctx context.Context, resourceURL *url.URL) (r io.ReadCloser, err error)

DownloadResource returns an io.ReadCloser to read the Resource from.

func (*Client) Find

func (c *Client) Find(ctx context.Context, name string, options ...FindOption) ([]transport.FindResponse, error)

Find searches for a given charm for a given name from CharmHub API.

func (*Client) Info

func (c *Client) Info(ctx context.Context, name string, options ...InfoOption) (transport.InfoResponse, error)

Info returns charm info on the provided charm name from CharmHub API.

func (*Client) ListResourceRevisions

func (c *Client) ListResourceRevisions(ctx context.Context, charm, resource string) ([]transport.ResourceRevision, error)

ListResourceRevisions returns resource revisions for the provided charm and resource.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context, config RefreshConfig) ([]transport.RefreshResponse, error)

Refresh defines a client for making refresh API calls with different actions.

func (*Client) RefreshWithMetricsOnly

func (c *Client) RefreshWithMetricsOnly(ctx context.Context, metrics map[charmmetrics.MetricKey]map[charmmetrics.MetricKey]string) error

RefreshWithMetricsOnly defines a client making a refresh API call with no action, whose purpose is to send metrics data for models without current units. E.G. the controller model.

func (*Client) RefreshWithRequestMetrics

func (c *Client) RefreshWithRequestMetrics(ctx context.Context, config RefreshConfig, metrics map[charmmetrics.MetricKey]map[charmmetrics.MetricKey]string) ([]transport.RefreshResponse, error)

RefreshWithRequestMetrics defines a client for making refresh API calls. Specifically to use the refresh action and provide metrics. Intended for use in the charm revision updater facade only. Otherwise use Refresh.

func (*Client) URL

func (c *Client) URL() string

URL returns the underlying store URL.

type Config

type Config struct {
	// URL holds the base endpoint URL of the charmHub,
	// with no trailing slash, not including the version.
	// For example https://api.charmhub.io/v2/charms/
	URL string

	// Version holds the version attribute of the charmHub we're requesting.
	Version string

	// Entity holds the entity to target when querying the API (charm or snaps).
	Entity string

	// Headers allow the defining of a set of default headers when sending the
	// requests. These headers augment the headers required for sending requests
	// and allow overriding existing headers.
	Headers http.Header

	// Transport represents the default http transport to use for all API
	// requests.
	Transport Transport

	// Logger to use during the API requests.
	Logger Logger
}

Config holds configuration for creating a new charm hub client.

func CharmHubConfig

func CharmHubConfig(logger Logger, options ...Option) (Config, error)

CharmHubConfig defines a charmHub client configuration for targeting the charmhub API.

func CharmHubConfigFromURL

func CharmHubConfigFromURL(url string, logger Logger, options ...Option) (Config, error)

CharmHubConfigFromURL defines a charmHub client configuration with a given URL for targeting the API.

func (Config) BasePath

func (c Config) BasePath() (charmhubpath.Path, error)

BasePath returns the base configuration path for speaking to the server API.

type DownloadClient

type DownloadClient struct {
	// contains filtered or unexported fields
}

DownloadClient represents a client for downloading charm resources directly.

func NewDownloadClient

func NewDownloadClient(transport Transport, fileSystem FileSystem, logger Logger) *DownloadClient

NewDownloadClient creates a DownloadClient for requesting

func (*DownloadClient) Download

func (c *DownloadClient) Download(ctx context.Context, resourceURL *url.URL, archivePath string, options ...DownloadOption) error

Download returns the raw charm zip file, which is retrieved from the given URL. It is expected that the archive path doesn't already exist and if it does, it will error out. It is expected that the callee handles the clean up of the archivePath. TODO (stickupkid): We should either create and remove, or take a file and let the callee remove. The fact that the operations are asymmetrical can lead to unexpected expectations; namely leaking of files.

func (*DownloadClient) DownloadAndRead

func (c *DownloadClient) DownloadAndRead(ctx context.Context, resourceURL *url.URL, archivePath string, options ...DownloadOption) (*charm.CharmArchive, error)

DownloadAndRead returns a charm archive retrieved from the given URL.

func (*DownloadClient) DownloadAndReadBundle

func (c *DownloadClient) DownloadAndReadBundle(ctx context.Context, resourceURL *url.URL, archivePath string, options ...DownloadOption) (*charm.BundleArchive, error)

DownloadAndReadBundle returns a bundle archive retrieved from the given URL.

func (*DownloadClient) DownloadResource

func (c *DownloadClient) DownloadResource(ctx context.Context, resourceURL *url.URL) (r io.ReadCloser, err error)

DownloadResource returns an io.ReadCloser to read the Resource from.

type DownloadKey

type DownloadKey string

DownloadKey represents a key for accessing the context value.

const (
	// DownloadNameKey defines a name of a download, so the progress bar can
	// show it.
	DownloadNameKey DownloadKey = "download-name-key"
)

type DownloadOption

type DownloadOption func(*downloadOptions)

DownloadOption to be passed to Info to customize the resulting request.

func WithProgressBar

func WithProgressBar(pb ProgressBar) DownloadOption

WithProgressBar sets the channel on the option.

type FileSystem

type FileSystem interface {
	// Create creates or truncates the named file. If the file already exists,
	// it is truncated.
	Create(string) (*os.File, error)
}

FileSystem defines a file system for modifying files on a users system.

func DefaultFileSystem

func DefaultFileSystem() FileSystem

DefaultFileSystem is the file system used for most download requests.

type FindClient

type FindClient struct {
	// contains filtered or unexported fields
}

FindClient defines a client for querying information about a given charm or bundle for a given CharmHub store.

func NewFindClient

func NewFindClient(path path.Path, client RESTClient, logger Logger) *FindClient

NewFindClient creates a FindClient for querying charm or bundle information.

func (*FindClient) Find

func (c *FindClient) Find(ctx context.Context, query string, options ...FindOption) ([]transport.FindResponse, error)

Find searches Charm Hub and provides results matching a string.

type FindOption

type FindOption func(*findOptions)

FindOption to be passed to Find to customize the resulting request.

func WithFindCategory

func WithFindCategory(category string) FindOption

WithFindCategory sets the category on the option.

func WithFindChannel

func WithFindChannel(channel string) FindOption

WithFindChannel sets the channel on the option.

func WithFindPlatforms

func WithFindPlatforms(platforms string) FindOption

WithFindPlatforms sets the charmPlatforms on the option.

func WithFindPublisher

func WithFindPublisher(publisher string) FindOption

WithFindPublisher sets the publisher on the option.

func WithFindRelationProvides

func WithFindRelationProvides(relationProvides string) FindOption

WithFindRelationProvides sets the relationProvides on the option.

func WithFindRelationRequires

func WithFindRelationRequires(relationRequires string) FindOption

WithFindRelationRequires sets the relationRequires on the option.

func WithFindType

func WithFindType(charmType string) FindOption

WithFindType sets the charmType on the option.

type HTTPRESTClient

type HTTPRESTClient struct {
	// contains filtered or unexported fields
}

HTTPRESTClient represents a RESTClient that expects to interact with a HTTP transport.

func NewHTTPRESTClient

func NewHTTPRESTClient(transport Transport, headers http.Header) *HTTPRESTClient

NewHTTPRESTClient creates a new HTTPRESTClient

func (*HTTPRESTClient) Get

func (c *HTTPRESTClient) Get(ctx context.Context, path path.Path, result interface{}) (RESTResponse, error)

Get makes a GET request to the given path in the CharmHub (not including the host name or version prefix but including a leading /), parsing the result as JSON into the given result value, which should be a pointer to the expected data, but may be nil if no result is desired.

func (*HTTPRESTClient) Post

func (c *HTTPRESTClient) Post(ctx context.Context, path path.Path, headers http.Header, body, result interface{}) (RESTResponse, error)

Post makes a POST request to the given path in the CharmHub (not including the host name or version prefix but including a leading /), parsing the result as JSON into the given result value, which should be a pointer to the expected data, but may be nil if no result is desired.

type Headers

type Headers = map[string][]string

Headers represents a series of headers that we would like to pass to the REST API.

type InfoClient

type InfoClient struct {
	// contains filtered or unexported fields
}

InfoClient defines a client for info requests.

func NewInfoClient

func NewInfoClient(path path.Path, client RESTClient, logger Logger) *InfoClient

NewInfoClient creates a InfoClient for requesting

func (*InfoClient) Info

func (c *InfoClient) Info(ctx context.Context, name string, options ...InfoOption) (transport.InfoResponse, error)

Info requests the information of a given charm. If that charm doesn't exist an error stating that fact will be returned.

type InfoOption

type InfoOption func(*infoOptions)

InfoOption to be passed to Info to customize the resulting request.

func WithInfoChannel

func WithInfoChannel(ch string) InfoOption

WithInfoChannel sets the channel on the option.

type Logger

type Logger interface {
	IsTraceEnabled() bool

	Errorf(string, ...interface{})
	Debugf(string, ...interface{})
	Tracef(string, ...interface{})

	ChildWithLabels(string, ...string) loggo.Logger
}

Logger is a in place interface to represent a logger for consuming.

type MIME

type MIME = string

MIME represents a MIME type for identifying requests and response bodies.

const (
	// JSON represents the MIME type for JSON request and response types.
	JSON MIME = "application/json"
)

type Option

type Option func(*options)

Option to be passed into charmhub construction to customize the client.

func WithHTTPTransport

func WithHTTPTransport(transportFn func(Logger) Transport) Option

WithHTTPTransport sets the default http transport to use on the option.

func WithMetadataHeaders

func WithMetadataHeaders(h map[string]string) Option

WithMetadataHeaders sets the headers on the option.

func WithURL

func WithURL(u string) Option

WithURL sets the url on the option.

type ProgressBar

type ProgressBar interface {
	io.Writer

	// Start progress with max "total" steps.
	Start(label string, total float64)
	// Finished the progress display
	Finished()
}

ProgressBar defines a progress bar type for giving feedback to the user about the state of the download.

type RESTClient

type RESTClient interface {
	// Get performs GET requests to a given Path.
	Get(context.Context, path.Path, interface{}) (RESTResponse, error)
	// Post performs POST requests to a given Path.
	Post(context.Context, path.Path, http.Header, interface{}, interface{}) (RESTResponse, error)
}

RESTClient defines a type for making requests to a server.

type RESTResponse

type RESTResponse struct {
	StatusCode int
}

RESTResponse abstracts away the underlying response from the implementation.

type RefreshBase

type RefreshBase struct {
	Architecture string
	Name         string
	Channel      string
}

RefreshBase defines a base for selecting a specific charm. Continues to exist to allow for incoming bases to be converted to bases inside this package.

func (RefreshBase) String

func (p RefreshBase) String() string

type RefreshClient

type RefreshClient struct {
	// contains filtered or unexported fields
}

RefreshClient defines a client for refresh requests.

func NewRefreshClient

func NewRefreshClient(path path.Path, client RESTClient, logger Logger) *RefreshClient

NewRefreshClient creates a RefreshClient for requesting

func (*RefreshClient) Refresh

Refresh is used to refresh installed charms to a more suitable revision.

func (*RefreshClient) RefreshWithMetricsOnly

func (c *RefreshClient) RefreshWithMetricsOnly(ctx context.Context, metrics map[charmmetrics.MetricKey]map[charmmetrics.MetricKey]string) error

RefreshWithMetricsOnly is to provide metrics without context or actions. Used as part of the charm revision updater facade.

func (*RefreshClient) RefreshWithRequestMetrics

func (c *RefreshClient) RefreshWithRequestMetrics(ctx context.Context, config RefreshConfig, metrics map[charmmetrics.MetricKey]map[charmmetrics.MetricKey]string) ([]transport.RefreshResponse, error)

RefreshWithRequestMetrics is to get refreshed charm data and provide metrics at the same time. Used as part of the charm revision updater facade.

type RefreshConfig

type RefreshConfig interface {
	// Build a refresh request for sending to the API.
	Build() (transport.RefreshRequest, error)

	// Ensure that the request back contains the information we requested.
	Ensure([]transport.RefreshResponse) error

	// String describes the underlying refresh config.
	String() string
}

RefreshConfig defines a type for building refresh requests.

func AddConfigMetrics

func AddConfigMetrics(config RefreshConfig, metrics map[charmmetrics.MetricKey]string) (RefreshConfig, error)

AddConfigMetrics adds metrics to a refreshOne config. All values are applied at once, subsequent calls, replace all values.

func AddResource

func AddResource(config RefreshConfig, name string, revision int) (RefreshConfig, bool)

AddResource adds resource revision data to a executeOne config. Used for install by revision.

func DownloadOneFromChannel

func DownloadOneFromChannel(id string, channel string, base RefreshBase) (RefreshConfig, error)

DownloadOneFromChannel creates a request config using the channel and not the revision for requesting only one charm.

func DownloadOneFromChannelByName

func DownloadOneFromChannelByName(name string, channel string, base RefreshBase) (RefreshConfig, error)

DownloadOneFromChannelByName creates a request config using the channel and not the revision for requesting only one charm.

func DownloadOneFromRevision

func DownloadOneFromRevision(id string, revision int) (RefreshConfig, error)

DownloadOneFromRevision creates a request config using the revision and not the channel for requesting only one charm.

func DownloadOneFromRevisionByName

func DownloadOneFromRevisionByName(name string, revision int) (RefreshConfig, error)

DownloadOneFromRevisionByName creates a request config using the revision and not the channel for requesting only one charm.

func InstallOneFromChannel

func InstallOneFromChannel(name string, channel string, base RefreshBase) (RefreshConfig, error)

InstallOneFromChannel creates a request config using the channel and not the revision for requesting only one charm.

func InstallOneFromRevision

func InstallOneFromRevision(name string, revision int) (RefreshConfig, error)

InstallOneFromRevision creates a request config using the revision and not the channel for requesting only one charm.

func RefreshMany

func RefreshMany(configs ...RefreshConfig) RefreshConfig

RefreshMany will compose many refresh configs.

func RefreshOne

func RefreshOne(key, id string, revision int, channel string, base RefreshBase) (RefreshConfig, error)

RefreshOne creates a request config for requesting only one charm.

type ResourcesClient

type ResourcesClient struct {
	// contains filtered or unexported fields
}

ResourcesClient defines a client for resources requests.

func NewResourcesClient

func NewResourcesClient(path path.Path, client RESTClient, logger Logger) *ResourcesClient

NewResourcesClient creates a ResourcesClient for requesting

func (*ResourcesClient) ListResourceRevisions

func (c *ResourcesClient) ListResourceRevisions(ctx context.Context, charm, resource string) ([]transport.ResourceRevision, error)

ListResourceRevisions returns a slice of resource revisions for the provided resource of the given charm.

type Transport

type Transport interface {
	// Do performs the *http.Request and returns a *http.Response or an error
	// if it fails to construct the transport.
	Do(*http.Request) (*http.Response, error)
}

Transport defines a type for making the actual request.

func DefaultHTTPTransport

func DefaultHTTPTransport(logger Logger) Transport

DefaultHTTPTransport creates a new HTTPTransport.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL