docker

package
v0.13.8 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2024 License: Apache-2.0 Imports: 30 Imported by: 2

Documentation

Index

Constants

View Source
const LegacyConfigMediaType = "application/octet-stream"

LegacyConfigMediaType should be replaced by OCI image spec.

More detail: docker/distribution#1622

Variables

View Source
var (
	// ErrorCodeUnknown is a generic error that can be used as a last
	// resort if there is no situation-specific error message that can be used
	ErrorCodeUnknown = Register("errcode", ErrorDescriptor{
		Value:   "UNKNOWN",
		Message: "unknown error",
		Description: `Generic error returned when the error does not have an
			                                            API classification.`,
		HTTPStatusCode: http.StatusInternalServerError,
	})

	// ErrorCodeUnsupported is returned when an operation is not supported.
	ErrorCodeUnsupported = Register("errcode", ErrorDescriptor{
		Value:   "UNSUPPORTED",
		Message: "The operation is unsupported.",
		Description: `The operation was unsupported due to a missing
		implementation or invalid set of parameters.`,
		HTTPStatusCode: http.StatusMethodNotAllowed,
	})

	// ErrorCodeUnauthorized is returned if a request requires
	// authentication.
	ErrorCodeUnauthorized = Register("errcode", ErrorDescriptor{
		Value:   "UNAUTHORIZED",
		Message: "authentication required",
		Description: `The access controller was unable to authenticate
		the client. Often this will be accompanied by a
		Www-Authenticate HTTP response header indicating how to
		authenticate.`,
		HTTPStatusCode: http.StatusUnauthorized,
	})

	// ErrorCodeDenied is returned if a client does not have sufficient
	// permission to perform an action.
	ErrorCodeDenied = Register("errcode", ErrorDescriptor{
		Value:   "DENIED",
		Message: "requested access to the resource is denied",
		Description: `The access controller denied access for the
		operation on a resource.`,
		HTTPStatusCode: http.StatusForbidden,
	})

	// ErrorCodeUnavailable provides a common error to report unavailability
	// of a service or endpoint.
	ErrorCodeUnavailable = Register("errcode", ErrorDescriptor{
		Value:          "UNAVAILABLE",
		Message:        "service unavailable",
		Description:    "Returned when a service is not available",
		HTTPStatusCode: http.StatusServiceUnavailable,
	})

	// ErrorCodeTooManyRequests is returned if a client attempts too many
	// times to contact a service endpoint.
	ErrorCodeTooManyRequests = Register("errcode", ErrorDescriptor{
		Value:   "TOOMANYREQUESTS",
		Message: "too many requests",
		Description: `Returned when a client attempts to contact a
		service too many times`,
		HTTPStatusCode: http.StatusTooManyRequests,
	})
)
View Source
var (
	// ErrInvalidAuthorization is used when credentials are passed to a server but
	// those credentials are rejected.
	ErrInvalidAuthorization = errors.New("authorization failed")

	// MaxManifestSize represents the largest size accepted from a registry
	// during resolution. Larger manifests may be accepted using a
	// resolution method other than the registry.
	//
	// NOTE: The max supported layers by some runtimes is 128 and individual
	// layers will not contribute more than 256 bytes, making a
	// reasonable limit for a large image manifests of 32K bytes.
	// 4M bytes represents a much larger upper bound for images which may
	// contain large annotations or be non-images. A proper manifest
	// design puts large metadata in subobjects, as is consistent the
	// intent of the manifest design.
	MaxManifestSize int64 = 4 * 1048 * 1048
)

Functions

func AppendDistributionSourceLabel

func AppendDistributionSourceLabel(manager content.Manager, ref string) (images.HandlerFunc, error)

AppendDistributionSourceLabel updates the label of blob with distribution source.

func ContextWithAppendPullRepositoryScope

func ContextWithAppendPullRepositoryScope(ctx context.Context, repo string) context.Context

ContextWithAppendPullRepositoryScope is used to append repository pull scope into existing scopes indexed by the tokenScopesKey{}.

func ContextWithRepositoryScope

func ContextWithRepositoryScope(ctx context.Context, refspec reference.Spec, push bool) (context.Context, error)

ContextWithRepositoryScope returns a context with tokenScopesKey{} and the repository scope value.

func ConvertManifest

func ConvertManifest(ctx context.Context, store content.Store, desc ocispec.Descriptor) (ocispec.Descriptor, error)

ConvertManifest changes application/octet-stream to schema2 config media type if need.

NOTE: 1. original manifest will be deleted by next gc round. 2. don't cover manifest list.

func DefaultHost

func DefaultHost(ns string) (string, error)

DefaultHost is the default host function.

func GetGroupNames

func GetGroupNames() []string

GetGroupNames returns the list of Error group names that are registered

func GetTokenScopes

func GetTokenScopes(ctx context.Context, common []string) []string

GetTokenScopes returns deduplicated and sorted scopes from ctx.Value(tokenScopesKey{}) and common scopes.

func IsLocalhost

func IsLocalhost(host string) bool

IsLocalhost checks if the registry host is local.

func MatchAllHosts

func MatchAllHosts(string) (bool, error)

MatchAllHosts is a host match function which is always true.

func MatchLocalhost

func MatchLocalhost(host string) (bool, error)

MatchLocalhost is a host match function which returns true for localhost.

Note: this does not handle matching of ip addresses in octal, decimal or hex form.

func NewResolver

func NewResolver(options ResolverOptions) remotes.Resolver

NewResolver returns a new resolver to a Docker registry

func RepositoryScope

func RepositoryScope(refspec reference.Spec, push bool) (string, error)

RepositoryScope returns a repository scope string such as "repository:foo/bar:pull" for "host/foo/bar:baz". When push is true, both pull and push are added to the scope.

func WithScope

func WithScope(ctx context.Context, scope string) context.Context

WithScope appends a custom registry auth scope to the context.

Types

type Authorizer

type Authorizer interface {
	// Authorize sets the appropriate `Authorization` header on the given
	// request.
	//
	// If no authorization is found for the request, the request remains
	// unmodified. It may also add an `Authorization` header as
	//  "bearer <some bearer token>"
	//  "basic <base64 encoded credentials>"
	//
	// It may return remotes/errors.ErrUnexpectedStatus, which for example,
	// can be used by the caller to find out the status code returned by the registry.
	Authorize(context.Context, *http.Request) error

	// AddResponses adds a 401 response for the authorizer to consider when
	// authorizing requests. The last response should be unauthorized and
	// the previous requests are used to consider redirects and retries
	// that may have led to the 401.
	//
	// If response is not handled, returns `ErrNotImplemented`
	AddResponses(context.Context, []*http.Response) error
}

Authorizer is used to authorize HTTP requests based on 401 HTTP responses. An Authorizer is responsible for caching tokens or credentials used by requests.

func NewDockerAuthorizer

func NewDockerAuthorizer(opts ...AuthorizerOpt) Authorizer

NewDockerAuthorizer creates an authorizer using Docker's registry authentication spec. See https://docs.docker.com/registry/spec/auth/

type AuthorizerOpt

type AuthorizerOpt func(*authorizerConfig)

AuthorizerOpt configures an authorizer

func WithAuthClient

func WithAuthClient(client *http.Client) AuthorizerOpt

WithAuthClient provides the HTTP client for the authorizer

func WithAuthCreds

func WithAuthCreds(creds func(string) (string, string, error)) AuthorizerOpt

WithAuthCreds provides a credential function to the authorizer

func WithAuthHeader

func WithAuthHeader(hdr http.Header) AuthorizerOpt

WithAuthHeader provides HTTP headers for authorization

func WithFetchRefreshToken

func WithFetchRefreshToken(f OnFetchRefreshToken) AuthorizerOpt

WithFetchRefreshToken enables fetching "refresh token" (aka "identity token", "offline token").

type Error

type Error struct {
	Code    ErrorCode   `json:"code"`
	Message string      `json:"message"`
	Detail  interface{} `json:"detail,omitempty"`
}

Error provides a wrapper around ErrorCode with extra Details provided.

func (Error) Error

func (e Error) Error() string

Error returns a human readable representation of the error.

func (Error) ErrorCode

func (e Error) ErrorCode() ErrorCode

ErrorCode returns the ID/Value of this Error

func (Error) WithArgs

func (e Error) WithArgs(args ...interface{}) Error

WithArgs uses the passed-in list of interface{} as the substitution variables in the Error's Message string, but returns a new Error

func (Error) WithDetail

func (e Error) WithDetail(detail interface{}) Error

WithDetail will return a new Error, based on the current one, but with some Detail info added

type ErrorCode

type ErrorCode int

ErrorCode represents the error type. The errors are serialized via strings and the integer format may change and should *never* be exported.

func ParseErrorCode

func ParseErrorCode(value string) ErrorCode

ParseErrorCode returns the value by the string error code. `ErrorCodeUnknown` will be returned if the error is not known.

func Register

func Register(group string, descriptor ErrorDescriptor) ErrorCode

Register will make the passed-in error known to the environment and return a new ErrorCode

func (ErrorCode) Descriptor

func (ec ErrorCode) Descriptor() ErrorDescriptor

Descriptor returns the descriptor for the error code.

func (ErrorCode) Error

func (ec ErrorCode) Error() string

Error returns the ID/Value

func (ErrorCode) ErrorCode

func (ec ErrorCode) ErrorCode() ErrorCode

ErrorCode just returns itself

func (ErrorCode) MarshalText

func (ec ErrorCode) MarshalText() (text []byte, err error)

MarshalText encodes the receiver into UTF-8-encoded text and returns the result.

func (ErrorCode) Message

func (ec ErrorCode) Message() string

Message returned the human-readable error message for this error code.

func (ErrorCode) String

func (ec ErrorCode) String() string

String returns the canonical identifier for this error code.

func (*ErrorCode) UnmarshalText

func (ec *ErrorCode) UnmarshalText(text []byte) error

UnmarshalText decodes the form generated by MarshalText.

func (ErrorCode) WithArgs

func (ec ErrorCode) WithArgs(args ...interface{}) Error

WithArgs creates a new Error struct and sets the Args slice

func (ErrorCode) WithDetail

func (ec ErrorCode) WithDetail(detail interface{}) Error

WithDetail creates a new Error struct based on the passed-in info and set the Detail property appropriately

func (ErrorCode) WithMessage

func (ec ErrorCode) WithMessage(message string) Error

WithMessage creates a new Error struct based on the passed-in info and overrides the Message property.

type ErrorCoder

type ErrorCoder interface {
	ErrorCode() ErrorCode
}

ErrorCoder is the base interface for ErrorCode and Error allowing users of each to just call ErrorCode to get the real ID of each

type ErrorDescriptor

type ErrorDescriptor struct {
	// Code is the error code that this descriptor describes.
	Code ErrorCode

	// Value provides a unique, string key, often captilized with
	// underscores, to identify the error code. This value is used as the
	// keyed value when serializing api errors.
	Value string

	// Message is a short, human readable description of the error condition
	// included in API responses.
	Message string

	// Description provides a complete account of the errors purpose, suitable
	// for use in documentation.
	Description string

	// HTTPStatusCode provides the http status code that is associated with
	// this error condition.
	HTTPStatusCode int
}

ErrorDescriptor provides relevant information about a given error code.

func GetErrorAllDescriptors

func GetErrorAllDescriptors() []ErrorDescriptor

GetErrorAllDescriptors returns a slice of all ErrorDescriptors that are registered, irrespective of what group they're in

func GetErrorCodeGroup

func GetErrorCodeGroup(name string) []ErrorDescriptor

GetErrorCodeGroup returns the named group of error descriptors

type Errors

type Errors []error

Errors provides the envelope for multiple errors and a few sugar methods for use within the application.

func (Errors) Error

func (errs Errors) Error() string

func (Errors) Len

func (errs Errors) Len() int

Len returns the current number of errors.

func (Errors) MarshalJSON

func (errs Errors) MarshalJSON() ([]byte, error)

MarshalJSON converts slice of error, ErrorCode or Error into a slice of Error - then serializes

func (*Errors) UnmarshalJSON

func (errs *Errors) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes []Error and then converts it into slice of Error or ErrorCode

type HostCapabilities

type HostCapabilities uint8

HostCapabilities represent the capabilities of the registry host. This also represents the set of operations for which the registry host may be trusted to perform.

For example pushing is a capability which should only be performed on an upstream source, not a mirror. Resolving (the process of converting a name into a digest) must be considered a trusted operation and only done by a host which is trusted (or more preferably by secure process which can prove the provenance of the mapping). A public mirror should never be trusted to do a resolve action.

| Registry Type | Pull | Resolve | Push | |------------------|------|---------|------| | Public Registry | yes | yes | yes | | Private Registry | yes | yes | yes | | Public Mirror | yes | no | no | | Private Mirror | yes | yes | no |

const (
	// HostCapabilityPull represents the capability to fetch manifests
	// and blobs by digest
	HostCapabilityPull HostCapabilities = 1 << iota

	// HostCapabilityResolve represents the capability to fetch manifests
	// by name
	HostCapabilityResolve

	// HostCapabilityPush represents the capability to push blobs and
	// manifests
	HostCapabilityPush

	// HostCapabilityReferrers represents the capability to generate a
	// list of referrers using the OCI Distribution referrers endpoint.
	HostCapabilityReferrers
)

func (HostCapabilities) Has

Has checks whether the capabilities list has the provide capability

type OnFetchRefreshToken

type OnFetchRefreshToken func(ctx context.Context, refreshToken string, req *http.Request)

OnFetchRefreshToken is called on fetching request token.

type RegistryHost

type RegistryHost struct {
	Client       *http.Client
	Authorizer   Authorizer
	Host         string
	Scheme       string
	Path         string
	Capabilities HostCapabilities
	Header       http.Header
}

RegistryHost represents a complete configuration for a registry host, representing the capabilities, authorizations, connection configuration, and location.

type RegistryHosts

type RegistryHosts func(string) ([]RegistryHost, error)

RegistryHosts fetches the registry hosts for a given namespace, provided by the host component of an distribution image reference.

func ConfigureDefaultRegistries

func ConfigureDefaultRegistries(ropts ...RegistryOpt) RegistryHosts

ConfigureDefaultRegistries is used to create a default configuration for registries. For more advanced configurations or per-domain setups, the RegistryHosts interface should be used directly. NOTE: This function will always return a non-empty value or error

func Registries

func Registries(registries ...RegistryHosts) RegistryHosts

Registries joins multiple registry configuration functions, using the same order as provided within the arguments. When an empty registry configuration is returned with a nil error, the next function will be called. NOTE: This function will not join configurations, as soon as a non-empty configuration is returned from a configuration function, it will be returned to the caller.

type RegistryOpt

type RegistryOpt func(*registryOpts)

RegistryOpt defines a registry default option

func WithAuthorizer

func WithAuthorizer(a Authorizer) RegistryOpt

WithAuthorizer configures the default authorizer for a registry

func WithClient

func WithClient(c *http.Client) RegistryOpt

WithClient configures the default http client for a registry

func WithHostTranslator

func WithHostTranslator(h func(string) (string, error)) RegistryOpt

WithHostTranslator defines the default translator to use for registry hosts

func WithPlainHTTP

func WithPlainHTTP(f func(string) (bool, error)) RegistryOpt

WithPlainHTTP configures registries to use plaintext http scheme for the provided host match function.

type ResolverOptions

type ResolverOptions struct {
	// Hosts returns registry host configurations for a namespace.
	Hosts RegistryHosts

	// Headers are the HTTP request header fields sent by the resolver
	Headers http.Header

	// Tracker is used to track uploads to the registry. This is used
	// since the registry does not have upload tracking and the existing
	// mechanism for getting blob upload status is expensive.
	Tracker StatusTracker

	// Authorizer is used to authorize registry requests
	// Deprecated: use Hosts
	Authorizer Authorizer

	// Credentials provides username and secret given a host.
	// If username is empty but a secret is given, that secret
	// is interpreted as a long lived token.
	// Deprecated: use Hosts
	Credentials func(string) (string, string, error)

	// Host provides the hostname given a namespace.
	// Deprecated: use Hosts
	Host func(string) (string, error)

	// PlainHTTP specifies to use plain http and not https
	// Deprecated: use Hosts
	PlainHTTP bool

	// Client is the http client to used when making registry requests
	// Deprecated: use Hosts
	Client *http.Client
}

ResolverOptions are used to configured a new Docker register resolver

type Status

type Status struct {
	content.Status

	Committed bool

	// ErrClosed contains error encountered on close.
	ErrClosed error

	// UploadUUID is used by the Docker registry to reference blob uploads
	UploadUUID string
}

Status of a content operation

type StatusTrackLocker

type StatusTrackLocker interface {
	StatusTracker
	Lock(string)
	Unlock(string)
}

StatusTrackLocker to track status of operations with lock

func NewInMemoryTracker

func NewInMemoryTracker() StatusTrackLocker

NewInMemoryTracker returns a StatusTracker that tracks content status in-memory

type StatusTracker

type StatusTracker interface {
	GetStatus(string) (Status, error)
	SetStatus(string, Status)
}

StatusTracker to track status of operations

Directories

Path Synopsis
Package config contains utilities for helping configure the Docker resolver
Package config contains utilities for helping configure the Docker resolver
Package schema1 provides a converter to fetch an image formatted in Docker Image Manifest v2, Schema 1.
Package schema1 provides a converter to fetch an image formatted in Docker Image Manifest v2, Schema 1.

Jump to

Keyboard shortcuts

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