2015-02-11 02:25:40 +01:00
|
|
|
package handlers
|
2014-11-11 03:57:38 +01:00
|
|
|
|
|
|
|
import (
|
2015-04-02 01:27:24 +02:00
|
|
|
"expvar"
|
2014-12-11 07:33:36 +01:00
|
|
|
"fmt"
|
2015-04-08 00:52:48 +02:00
|
|
|
"math/rand"
|
2015-01-29 00:55:18 +01:00
|
|
|
"net"
|
2014-11-11 03:57:38 +01:00
|
|
|
"net/http"
|
2015-01-29 00:55:18 +01:00
|
|
|
"os"
|
2015-04-02 01:27:24 +02:00
|
|
|
"time"
|
2014-11-11 03:57:38 +01:00
|
|
|
|
2015-02-12 01:49:49 +01:00
|
|
|
"github.com/docker/distribution"
|
2014-12-24 01:01:38 +01:00
|
|
|
"github.com/docker/distribution/configuration"
|
2015-02-07 01:19:19 +01:00
|
|
|
ctxu "github.com/docker/distribution/context"
|
2015-02-12 01:49:49 +01:00
|
|
|
"github.com/docker/distribution/notifications"
|
2015-05-15 03:21:39 +02:00
|
|
|
"github.com/docker/distribution/registry/api/errcode"
|
2015-02-11 03:14:23 +01:00
|
|
|
"github.com/docker/distribution/registry/api/v2"
|
|
|
|
"github.com/docker/distribution/registry/auth"
|
2015-03-06 16:45:16 +01:00
|
|
|
registrymiddleware "github.com/docker/distribution/registry/middleware/registry"
|
|
|
|
repositorymiddleware "github.com/docker/distribution/registry/middleware/repository"
|
2015-02-11 02:41:09 +01:00
|
|
|
"github.com/docker/distribution/registry/storage"
|
2015-05-21 02:12:40 +02:00
|
|
|
memorycache "github.com/docker/distribution/registry/storage/cache/memory"
|
|
|
|
rediscache "github.com/docker/distribution/registry/storage/cache/redis"
|
2015-02-11 03:14:23 +01:00
|
|
|
storagedriver "github.com/docker/distribution/registry/storage/driver"
|
|
|
|
"github.com/docker/distribution/registry/storage/driver/factory"
|
2015-03-03 17:57:52 +01:00
|
|
|
storagemiddleware "github.com/docker/distribution/registry/storage/driver/middleware"
|
2015-04-02 01:27:24 +02:00
|
|
|
"github.com/garyburd/redigo/redis"
|
2014-11-11 03:57:38 +01:00
|
|
|
"github.com/gorilla/mux"
|
2015-02-04 02:59:24 +01:00
|
|
|
"golang.org/x/net/context"
|
2014-11-11 03:57:38 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// App is a global registry application object. Shared resources can be placed
|
|
|
|
// on this object that will be accessible from all requests. Any writable
|
|
|
|
// fields should be protected.
|
|
|
|
type App struct {
|
2015-02-07 01:19:19 +01:00
|
|
|
context.Context
|
2014-11-11 03:57:38 +01:00
|
|
|
|
2015-04-10 03:45:39 +02:00
|
|
|
Config configuration.Configuration
|
2014-11-21 04:57:01 +01:00
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
router *mux.Router // main application router, configured with dispatchers
|
|
|
|
driver storagedriver.StorageDriver // driver maintains the app global storage driver instance.
|
2015-04-10 04:21:33 +02:00
|
|
|
registry distribution.Namespace // registry is the primary registry backend for the app instance.
|
2015-01-29 00:55:18 +01:00
|
|
|
accessController auth.AccessController // main access controller for application
|
2014-11-21 04:57:01 +01:00
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
// events contains notification related configuration.
|
|
|
|
events struct {
|
|
|
|
sink notifications.Sink
|
|
|
|
source notifications.SourceRecord
|
|
|
|
}
|
2015-04-02 01:27:24 +02:00
|
|
|
|
|
|
|
redis *redis.Pool
|
2014-11-11 03:57:38 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewApp takes a configuration and returns a configured app, ready to serve
|
|
|
|
// requests. The app only implements ServeHTTP and can be wrapped in other
|
|
|
|
// handlers accordingly.
|
2015-02-07 01:19:19 +01:00
|
|
|
func NewApp(ctx context.Context, configuration configuration.Configuration) *App {
|
2014-11-11 03:57:38 +01:00
|
|
|
app := &App{
|
2015-04-10 03:45:39 +02:00
|
|
|
Config: configuration,
|
|
|
|
Context: ctx,
|
|
|
|
router: v2.RouterWithPrefix(configuration.HTTP.Prefix),
|
2014-11-11 03:57:38 +01:00
|
|
|
}
|
|
|
|
|
2015-04-10 03:45:39 +02:00
|
|
|
app.Context = ctxu.WithLogger(app.Context, ctxu.GetLogger(app, "instance.id"))
|
2015-02-07 01:19:19 +01:00
|
|
|
|
2014-11-11 03:57:38 +01:00
|
|
|
// Register the handler dispatchers.
|
2014-12-12 07:24:25 +01:00
|
|
|
app.register(v2.RouteNameBase, func(ctx *Context, r *http.Request) http.Handler {
|
2014-12-11 07:33:36 +01:00
|
|
|
return http.HandlerFunc(apiBase)
|
|
|
|
})
|
2014-12-12 07:24:25 +01:00
|
|
|
app.register(v2.RouteNameManifest, imageManifestDispatcher)
|
|
|
|
app.register(v2.RouteNameTags, tagsDispatcher)
|
Refactor Blob Service API
This PR refactors the blob service API to be oriented around blob descriptors.
Identified by digests, blobs become an abstract entity that can be read and
written using a descriptor as a handle. This allows blobs to take many forms,
such as a ReadSeekCloser or a simple byte buffer, allowing blob oriented
operations to better integrate with blob agnostic APIs (such as the `io`
package). The error definitions are now better organized to reflect conditions
that can only be seen when interacting with the blob API.
The main benefit of this is to separate the much smaller metadata from large
file storage. Many benefits also follow from this. Reading and writing has
been separated into discrete services. Backend implementation is also
simplified, by reducing the amount of metadata that needs to be picked up to
simply serve a read. This also improves cacheability.
"Opening" a blob simply consists of an access check (Stat) and a path
calculation. Caching is greatly simplified and we've made the mapping of
provisional to canonical hashes a first-class concept. BlobDescriptorService
and BlobProvider can be combined in different ways to achieve varying effects.
Recommend Review Approach
-------------------------
This is a very large patch. While apologies are in order, we are getting a
considerable amount of refactoring. Most changes follow from the changes to
the root package (distribution), so start there. From there, the main changes
are in storage. Looking at (*repository).Blobs will help to understand the how
the linkedBlobStore is wired. One can explore the internals within and also
branch out into understanding the changes to the caching layer. Following the
descriptions below will also help to guide you.
To reduce the chances for regressions, it was critical that major changes to
unit tests were avoided. Where possible, they are left untouched and where
not, the spirit is hopefully captured. Pay particular attention to where
behavior may have changed.
Storage
-------
The primary changes to the `storage` package, other than the interface
updates, were to merge the layerstore and blobstore. Blob access is now
layered even further. The first layer, blobStore, exposes a global
`BlobStatter` and `BlobProvider`. Operations here provide a fast path for most
read operations that don't take access control into account. The
`linkedBlobStore` layers on top of the `blobStore`, providing repository-
scoped blob link management in the backend. The `linkedBlobStore` implements
the full `BlobStore` suite, providing access-controlled, repository-local blob
writers. The abstraction between the two is slightly broken in that
`linkedBlobStore` is the only channel under which one can write into the global
blob store. The `linkedBlobStore` also provides flexibility in that it can act
over different link sets depending on configuration. This allows us to use the
same code for signature links, manifest links and blob links. Eventually, we
will fully consolidate this storage.
The improved cache flow comes from the `linkedBlobStatter` component
of `linkedBlobStore`. Using a `cachedBlobStatter`, these combine together to
provide a simple cache hierarchy that should streamline access checks on read
and write operations, or at least provide a single path to optimize. The
metrics have been changed in a slightly incompatible way since the former
operations, Fetch and Exists, are no longer relevant.
The fileWriter and fileReader have been slightly modified to support the rest
of the changes. The most interesting is the removal of the `Stat` call from
`newFileReader`. This was the source of unnecessary round trips that were only
present to look up the size of the resulting reader. Now, one must simply pass
in the size, requiring the caller to decide whether or not the `Stat` call is
appropriate. In several cases, it turned out the caller already had the size
already. The `WriterAt` implementation has been removed from `fileWriter`,
since it is no longer required for `BlobWriter`, reducing the number of paths
which writes may take.
Cache
-----
Unfortunately, the `cache` package required a near full rewrite. It was pretty
mechanical in that the cache is oriented around the `BlobDescriptorService`
slightly modified to include the ability to set the values for individual
digests. While the implementation is oriented towards caching, it can act as a
primary store. Provisions are in place to have repository local metadata, in
addition to global metadata. Fallback is implemented as a part of the storage
package to maintain this flexibility.
One unfortunate side-effect is that caching is now repository-scoped, rather
than global. This should have little effect on performance but may increase
memory usage.
Handlers
--------
The `handlers` package has been updated to leverage the new API. For the most
part, the changes are superficial or mechanical based on the API changes. This
did expose a bug in the handling of provisional vs canonical digests that was
fixed in the unit tests.
Configuration
-------------
One user-facing change has been made to the configuration and is updated in
the associated documentation. The `layerinfo` cache parameter has been
deprecated by the `blobdescriptor` cache parameter. Both are equivalent and
configuration files should be backward compatible.
Notifications
-------------
Changes the `notification` package are simply to support the interface
changes.
Context
-------
A small change has been made to the tracing log-level. Traces have been moved
from "info" to "debug" level to reduce output when not needed.
Signed-off-by: Stephen J Day <stephen.day@docker.com>
2015-05-12 09:10:29 +02:00
|
|
|
app.register(v2.RouteNameBlob, blobDispatcher)
|
|
|
|
app.register(v2.RouteNameBlobUpload, blobUploadDispatcher)
|
|
|
|
app.register(v2.RouteNameBlobUploadChunk, blobUploadDispatcher)
|
2014-11-11 03:57:38 +01:00
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
var err error
|
|
|
|
app.driver, err = factory.Create(configuration.Storage.Type(), configuration.Storage.Parameters())
|
2014-11-21 04:57:01 +01:00
|
|
|
if err != nil {
|
|
|
|
// TODO(stevvooe): Move the creation of a service into a protected
|
|
|
|
// method, where this is created lazily. Its status can be queried via
|
|
|
|
// a health check.
|
|
|
|
panic(err)
|
|
|
|
}
|
2015-04-08 00:52:48 +02:00
|
|
|
|
2015-04-17 03:34:29 +02:00
|
|
|
purgeConfig := uploadPurgeDefaultConfig()
|
|
|
|
if mc, ok := configuration.Storage["maintenance"]; ok {
|
|
|
|
for k, v := range mc {
|
|
|
|
switch k {
|
|
|
|
case "uploadpurging":
|
|
|
|
purgeConfig = v.(map[interface{}]interface{})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-04-28 00:58:58 +02:00
|
|
|
startUploadPurger(app, app.driver, ctxu.GetLogger(app), purgeConfig)
|
2015-04-08 00:52:48 +02:00
|
|
|
|
2015-03-09 18:55:52 +01:00
|
|
|
app.driver, err = applyStorageMiddleware(app.driver, configuration.Middleware["storage"])
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2014-11-21 04:57:01 +01:00
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
app.configureEvents(&configuration)
|
2015-04-02 01:27:24 +02:00
|
|
|
app.configureRedis(&configuration)
|
2015-03-06 16:45:16 +01:00
|
|
|
|
2015-04-03 01:38:01 +02:00
|
|
|
// configure storage caches
|
|
|
|
if cc, ok := configuration.Storage["cache"]; ok {
|
Refactor Blob Service API
This PR refactors the blob service API to be oriented around blob descriptors.
Identified by digests, blobs become an abstract entity that can be read and
written using a descriptor as a handle. This allows blobs to take many forms,
such as a ReadSeekCloser or a simple byte buffer, allowing blob oriented
operations to better integrate with blob agnostic APIs (such as the `io`
package). The error definitions are now better organized to reflect conditions
that can only be seen when interacting with the blob API.
The main benefit of this is to separate the much smaller metadata from large
file storage. Many benefits also follow from this. Reading and writing has
been separated into discrete services. Backend implementation is also
simplified, by reducing the amount of metadata that needs to be picked up to
simply serve a read. This also improves cacheability.
"Opening" a blob simply consists of an access check (Stat) and a path
calculation. Caching is greatly simplified and we've made the mapping of
provisional to canonical hashes a first-class concept. BlobDescriptorService
and BlobProvider can be combined in different ways to achieve varying effects.
Recommend Review Approach
-------------------------
This is a very large patch. While apologies are in order, we are getting a
considerable amount of refactoring. Most changes follow from the changes to
the root package (distribution), so start there. From there, the main changes
are in storage. Looking at (*repository).Blobs will help to understand the how
the linkedBlobStore is wired. One can explore the internals within and also
branch out into understanding the changes to the caching layer. Following the
descriptions below will also help to guide you.
To reduce the chances for regressions, it was critical that major changes to
unit tests were avoided. Where possible, they are left untouched and where
not, the spirit is hopefully captured. Pay particular attention to where
behavior may have changed.
Storage
-------
The primary changes to the `storage` package, other than the interface
updates, were to merge the layerstore and blobstore. Blob access is now
layered even further. The first layer, blobStore, exposes a global
`BlobStatter` and `BlobProvider`. Operations here provide a fast path for most
read operations that don't take access control into account. The
`linkedBlobStore` layers on top of the `blobStore`, providing repository-
scoped blob link management in the backend. The `linkedBlobStore` implements
the full `BlobStore` suite, providing access-controlled, repository-local blob
writers. The abstraction between the two is slightly broken in that
`linkedBlobStore` is the only channel under which one can write into the global
blob store. The `linkedBlobStore` also provides flexibility in that it can act
over different link sets depending on configuration. This allows us to use the
same code for signature links, manifest links and blob links. Eventually, we
will fully consolidate this storage.
The improved cache flow comes from the `linkedBlobStatter` component
of `linkedBlobStore`. Using a `cachedBlobStatter`, these combine together to
provide a simple cache hierarchy that should streamline access checks on read
and write operations, or at least provide a single path to optimize. The
metrics have been changed in a slightly incompatible way since the former
operations, Fetch and Exists, are no longer relevant.
The fileWriter and fileReader have been slightly modified to support the rest
of the changes. The most interesting is the removal of the `Stat` call from
`newFileReader`. This was the source of unnecessary round trips that were only
present to look up the size of the resulting reader. Now, one must simply pass
in the size, requiring the caller to decide whether or not the `Stat` call is
appropriate. In several cases, it turned out the caller already had the size
already. The `WriterAt` implementation has been removed from `fileWriter`,
since it is no longer required for `BlobWriter`, reducing the number of paths
which writes may take.
Cache
-----
Unfortunately, the `cache` package required a near full rewrite. It was pretty
mechanical in that the cache is oriented around the `BlobDescriptorService`
slightly modified to include the ability to set the values for individual
digests. While the implementation is oriented towards caching, it can act as a
primary store. Provisions are in place to have repository local metadata, in
addition to global metadata. Fallback is implemented as a part of the storage
package to maintain this flexibility.
One unfortunate side-effect is that caching is now repository-scoped, rather
than global. This should have little effect on performance but may increase
memory usage.
Handlers
--------
The `handlers` package has been updated to leverage the new API. For the most
part, the changes are superficial or mechanical based on the API changes. This
did expose a bug in the handling of provisional vs canonical digests that was
fixed in the unit tests.
Configuration
-------------
One user-facing change has been made to the configuration and is updated in
the associated documentation. The `layerinfo` cache parameter has been
deprecated by the `blobdescriptor` cache parameter. Both are equivalent and
configuration files should be backward compatible.
Notifications
-------------
Changes the `notification` package are simply to support the interface
changes.
Context
-------
A small change has been made to the tracing log-level. Traces have been moved
from "info" to "debug" level to reduce output when not needed.
Signed-off-by: Stephen J Day <stephen.day@docker.com>
2015-05-12 09:10:29 +02:00
|
|
|
v, ok := cc["blobdescriptor"]
|
|
|
|
if !ok {
|
|
|
|
// Backwards compatible: "layerinfo" == "blobdescriptor"
|
|
|
|
v = cc["layerinfo"]
|
|
|
|
}
|
|
|
|
|
|
|
|
switch v {
|
2015-04-03 01:38:01 +02:00
|
|
|
case "redis":
|
|
|
|
if app.redis == nil {
|
|
|
|
panic("redis configuration required to use for layerinfo cache")
|
|
|
|
}
|
2015-05-21 02:12:40 +02:00
|
|
|
app.registry = storage.NewRegistryWithDriver(app, app.driver, rediscache.NewRedisBlobDescriptorCacheProvider(app.redis))
|
Refactor Blob Service API
This PR refactors the blob service API to be oriented around blob descriptors.
Identified by digests, blobs become an abstract entity that can be read and
written using a descriptor as a handle. This allows blobs to take many forms,
such as a ReadSeekCloser or a simple byte buffer, allowing blob oriented
operations to better integrate with blob agnostic APIs (such as the `io`
package). The error definitions are now better organized to reflect conditions
that can only be seen when interacting with the blob API.
The main benefit of this is to separate the much smaller metadata from large
file storage. Many benefits also follow from this. Reading and writing has
been separated into discrete services. Backend implementation is also
simplified, by reducing the amount of metadata that needs to be picked up to
simply serve a read. This also improves cacheability.
"Opening" a blob simply consists of an access check (Stat) and a path
calculation. Caching is greatly simplified and we've made the mapping of
provisional to canonical hashes a first-class concept. BlobDescriptorService
and BlobProvider can be combined in different ways to achieve varying effects.
Recommend Review Approach
-------------------------
This is a very large patch. While apologies are in order, we are getting a
considerable amount of refactoring. Most changes follow from the changes to
the root package (distribution), so start there. From there, the main changes
are in storage. Looking at (*repository).Blobs will help to understand the how
the linkedBlobStore is wired. One can explore the internals within and also
branch out into understanding the changes to the caching layer. Following the
descriptions below will also help to guide you.
To reduce the chances for regressions, it was critical that major changes to
unit tests were avoided. Where possible, they are left untouched and where
not, the spirit is hopefully captured. Pay particular attention to where
behavior may have changed.
Storage
-------
The primary changes to the `storage` package, other than the interface
updates, were to merge the layerstore and blobstore. Blob access is now
layered even further. The first layer, blobStore, exposes a global
`BlobStatter` and `BlobProvider`. Operations here provide a fast path for most
read operations that don't take access control into account. The
`linkedBlobStore` layers on top of the `blobStore`, providing repository-
scoped blob link management in the backend. The `linkedBlobStore` implements
the full `BlobStore` suite, providing access-controlled, repository-local blob
writers. The abstraction between the two is slightly broken in that
`linkedBlobStore` is the only channel under which one can write into the global
blob store. The `linkedBlobStore` also provides flexibility in that it can act
over different link sets depending on configuration. This allows us to use the
same code for signature links, manifest links and blob links. Eventually, we
will fully consolidate this storage.
The improved cache flow comes from the `linkedBlobStatter` component
of `linkedBlobStore`. Using a `cachedBlobStatter`, these combine together to
provide a simple cache hierarchy that should streamline access checks on read
and write operations, or at least provide a single path to optimize. The
metrics have been changed in a slightly incompatible way since the former
operations, Fetch and Exists, are no longer relevant.
The fileWriter and fileReader have been slightly modified to support the rest
of the changes. The most interesting is the removal of the `Stat` call from
`newFileReader`. This was the source of unnecessary round trips that were only
present to look up the size of the resulting reader. Now, one must simply pass
in the size, requiring the caller to decide whether or not the `Stat` call is
appropriate. In several cases, it turned out the caller already had the size
already. The `WriterAt` implementation has been removed from `fileWriter`,
since it is no longer required for `BlobWriter`, reducing the number of paths
which writes may take.
Cache
-----
Unfortunately, the `cache` package required a near full rewrite. It was pretty
mechanical in that the cache is oriented around the `BlobDescriptorService`
slightly modified to include the ability to set the values for individual
digests. While the implementation is oriented towards caching, it can act as a
primary store. Provisions are in place to have repository local metadata, in
addition to global metadata. Fallback is implemented as a part of the storage
package to maintain this flexibility.
One unfortunate side-effect is that caching is now repository-scoped, rather
than global. This should have little effect on performance but may increase
memory usage.
Handlers
--------
The `handlers` package has been updated to leverage the new API. For the most
part, the changes are superficial or mechanical based on the API changes. This
did expose a bug in the handling of provisional vs canonical digests that was
fixed in the unit tests.
Configuration
-------------
One user-facing change has been made to the configuration and is updated in
the associated documentation. The `layerinfo` cache parameter has been
deprecated by the `blobdescriptor` cache parameter. Both are equivalent and
configuration files should be backward compatible.
Notifications
-------------
Changes the `notification` package are simply to support the interface
changes.
Context
-------
A small change has been made to the tracing log-level. Traces have been moved
from "info" to "debug" level to reduce output when not needed.
Signed-off-by: Stephen J Day <stephen.day@docker.com>
2015-05-12 09:10:29 +02:00
|
|
|
ctxu.GetLogger(app).Infof("using redis blob descriptor cache")
|
2015-04-03 01:38:01 +02:00
|
|
|
case "inmemory":
|
2015-05-21 02:12:40 +02:00
|
|
|
app.registry = storage.NewRegistryWithDriver(app, app.driver, memorycache.NewInMemoryBlobDescriptorCacheProvider())
|
Refactor Blob Service API
This PR refactors the blob service API to be oriented around blob descriptors.
Identified by digests, blobs become an abstract entity that can be read and
written using a descriptor as a handle. This allows blobs to take many forms,
such as a ReadSeekCloser or a simple byte buffer, allowing blob oriented
operations to better integrate with blob agnostic APIs (such as the `io`
package). The error definitions are now better organized to reflect conditions
that can only be seen when interacting with the blob API.
The main benefit of this is to separate the much smaller metadata from large
file storage. Many benefits also follow from this. Reading and writing has
been separated into discrete services. Backend implementation is also
simplified, by reducing the amount of metadata that needs to be picked up to
simply serve a read. This also improves cacheability.
"Opening" a blob simply consists of an access check (Stat) and a path
calculation. Caching is greatly simplified and we've made the mapping of
provisional to canonical hashes a first-class concept. BlobDescriptorService
and BlobProvider can be combined in different ways to achieve varying effects.
Recommend Review Approach
-------------------------
This is a very large patch. While apologies are in order, we are getting a
considerable amount of refactoring. Most changes follow from the changes to
the root package (distribution), so start there. From there, the main changes
are in storage. Looking at (*repository).Blobs will help to understand the how
the linkedBlobStore is wired. One can explore the internals within and also
branch out into understanding the changes to the caching layer. Following the
descriptions below will also help to guide you.
To reduce the chances for regressions, it was critical that major changes to
unit tests were avoided. Where possible, they are left untouched and where
not, the spirit is hopefully captured. Pay particular attention to where
behavior may have changed.
Storage
-------
The primary changes to the `storage` package, other than the interface
updates, were to merge the layerstore and blobstore. Blob access is now
layered even further. The first layer, blobStore, exposes a global
`BlobStatter` and `BlobProvider`. Operations here provide a fast path for most
read operations that don't take access control into account. The
`linkedBlobStore` layers on top of the `blobStore`, providing repository-
scoped blob link management in the backend. The `linkedBlobStore` implements
the full `BlobStore` suite, providing access-controlled, repository-local blob
writers. The abstraction between the two is slightly broken in that
`linkedBlobStore` is the only channel under which one can write into the global
blob store. The `linkedBlobStore` also provides flexibility in that it can act
over different link sets depending on configuration. This allows us to use the
same code for signature links, manifest links and blob links. Eventually, we
will fully consolidate this storage.
The improved cache flow comes from the `linkedBlobStatter` component
of `linkedBlobStore`. Using a `cachedBlobStatter`, these combine together to
provide a simple cache hierarchy that should streamline access checks on read
and write operations, or at least provide a single path to optimize. The
metrics have been changed in a slightly incompatible way since the former
operations, Fetch and Exists, are no longer relevant.
The fileWriter and fileReader have been slightly modified to support the rest
of the changes. The most interesting is the removal of the `Stat` call from
`newFileReader`. This was the source of unnecessary round trips that were only
present to look up the size of the resulting reader. Now, one must simply pass
in the size, requiring the caller to decide whether or not the `Stat` call is
appropriate. In several cases, it turned out the caller already had the size
already. The `WriterAt` implementation has been removed from `fileWriter`,
since it is no longer required for `BlobWriter`, reducing the number of paths
which writes may take.
Cache
-----
Unfortunately, the `cache` package required a near full rewrite. It was pretty
mechanical in that the cache is oriented around the `BlobDescriptorService`
slightly modified to include the ability to set the values for individual
digests. While the implementation is oriented towards caching, it can act as a
primary store. Provisions are in place to have repository local metadata, in
addition to global metadata. Fallback is implemented as a part of the storage
package to maintain this flexibility.
One unfortunate side-effect is that caching is now repository-scoped, rather
than global. This should have little effect on performance but may increase
memory usage.
Handlers
--------
The `handlers` package has been updated to leverage the new API. For the most
part, the changes are superficial or mechanical based on the API changes. This
did expose a bug in the handling of provisional vs canonical digests that was
fixed in the unit tests.
Configuration
-------------
One user-facing change has been made to the configuration and is updated in
the associated documentation. The `layerinfo` cache parameter has been
deprecated by the `blobdescriptor` cache parameter. Both are equivalent and
configuration files should be backward compatible.
Notifications
-------------
Changes the `notification` package are simply to support the interface
changes.
Context
-------
A small change has been made to the tracing log-level. Traces have been moved
from "info" to "debug" level to reduce output when not needed.
Signed-off-by: Stephen J Day <stephen.day@docker.com>
2015-05-12 09:10:29 +02:00
|
|
|
ctxu.GetLogger(app).Infof("using inmemory blob descriptor cache")
|
2015-04-03 01:38:01 +02:00
|
|
|
default:
|
Refactor Blob Service API
This PR refactors the blob service API to be oriented around blob descriptors.
Identified by digests, blobs become an abstract entity that can be read and
written using a descriptor as a handle. This allows blobs to take many forms,
such as a ReadSeekCloser or a simple byte buffer, allowing blob oriented
operations to better integrate with blob agnostic APIs (such as the `io`
package). The error definitions are now better organized to reflect conditions
that can only be seen when interacting with the blob API.
The main benefit of this is to separate the much smaller metadata from large
file storage. Many benefits also follow from this. Reading and writing has
been separated into discrete services. Backend implementation is also
simplified, by reducing the amount of metadata that needs to be picked up to
simply serve a read. This also improves cacheability.
"Opening" a blob simply consists of an access check (Stat) and a path
calculation. Caching is greatly simplified and we've made the mapping of
provisional to canonical hashes a first-class concept. BlobDescriptorService
and BlobProvider can be combined in different ways to achieve varying effects.
Recommend Review Approach
-------------------------
This is a very large patch. While apologies are in order, we are getting a
considerable amount of refactoring. Most changes follow from the changes to
the root package (distribution), so start there. From there, the main changes
are in storage. Looking at (*repository).Blobs will help to understand the how
the linkedBlobStore is wired. One can explore the internals within and also
branch out into understanding the changes to the caching layer. Following the
descriptions below will also help to guide you.
To reduce the chances for regressions, it was critical that major changes to
unit tests were avoided. Where possible, they are left untouched and where
not, the spirit is hopefully captured. Pay particular attention to where
behavior may have changed.
Storage
-------
The primary changes to the `storage` package, other than the interface
updates, were to merge the layerstore and blobstore. Blob access is now
layered even further. The first layer, blobStore, exposes a global
`BlobStatter` and `BlobProvider`. Operations here provide a fast path for most
read operations that don't take access control into account. The
`linkedBlobStore` layers on top of the `blobStore`, providing repository-
scoped blob link management in the backend. The `linkedBlobStore` implements
the full `BlobStore` suite, providing access-controlled, repository-local blob
writers. The abstraction between the two is slightly broken in that
`linkedBlobStore` is the only channel under which one can write into the global
blob store. The `linkedBlobStore` also provides flexibility in that it can act
over different link sets depending on configuration. This allows us to use the
same code for signature links, manifest links and blob links. Eventually, we
will fully consolidate this storage.
The improved cache flow comes from the `linkedBlobStatter` component
of `linkedBlobStore`. Using a `cachedBlobStatter`, these combine together to
provide a simple cache hierarchy that should streamline access checks on read
and write operations, or at least provide a single path to optimize. The
metrics have been changed in a slightly incompatible way since the former
operations, Fetch and Exists, are no longer relevant.
The fileWriter and fileReader have been slightly modified to support the rest
of the changes. The most interesting is the removal of the `Stat` call from
`newFileReader`. This was the source of unnecessary round trips that were only
present to look up the size of the resulting reader. Now, one must simply pass
in the size, requiring the caller to decide whether or not the `Stat` call is
appropriate. In several cases, it turned out the caller already had the size
already. The `WriterAt` implementation has been removed from `fileWriter`,
since it is no longer required for `BlobWriter`, reducing the number of paths
which writes may take.
Cache
-----
Unfortunately, the `cache` package required a near full rewrite. It was pretty
mechanical in that the cache is oriented around the `BlobDescriptorService`
slightly modified to include the ability to set the values for individual
digests. While the implementation is oriented towards caching, it can act as a
primary store. Provisions are in place to have repository local metadata, in
addition to global metadata. Fallback is implemented as a part of the storage
package to maintain this flexibility.
One unfortunate side-effect is that caching is now repository-scoped, rather
than global. This should have little effect on performance but may increase
memory usage.
Handlers
--------
The `handlers` package has been updated to leverage the new API. For the most
part, the changes are superficial or mechanical based on the API changes. This
did expose a bug in the handling of provisional vs canonical digests that was
fixed in the unit tests.
Configuration
-------------
One user-facing change has been made to the configuration and is updated in
the associated documentation. The `layerinfo` cache parameter has been
deprecated by the `blobdescriptor` cache parameter. Both are equivalent and
configuration files should be backward compatible.
Notifications
-------------
Changes the `notification` package are simply to support the interface
changes.
Context
-------
A small change has been made to the tracing log-level. Traces have been moved
from "info" to "debug" level to reduce output when not needed.
Signed-off-by: Stephen J Day <stephen.day@docker.com>
2015-05-12 09:10:29 +02:00
|
|
|
if v != "" {
|
2015-04-03 01:38:01 +02:00
|
|
|
ctxu.GetLogger(app).Warnf("unkown cache type %q, caching disabled", configuration.Storage["cache"])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if app.registry == nil {
|
|
|
|
// configure the registry if no cache section is available.
|
2015-04-28 00:58:58 +02:00
|
|
|
app.registry = storage.NewRegistryWithDriver(app.Context, app.driver, nil)
|
2015-04-02 01:41:33 +02:00
|
|
|
}
|
|
|
|
|
2015-03-09 18:55:52 +01:00
|
|
|
app.registry, err = applyRegistryMiddleware(app.registry, configuration.Middleware["registry"])
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
2015-03-06 16:45:16 +01:00
|
|
|
}
|
|
|
|
|
2014-12-18 21:30:19 +01:00
|
|
|
authType := configuration.Auth.Type()
|
|
|
|
|
|
|
|
if authType != "" {
|
|
|
|
accessController, err := auth.GetAccessController(configuration.Auth.Type(), configuration.Auth.Parameters())
|
|
|
|
if err != nil {
|
|
|
|
panic(fmt.Sprintf("unable to configure authorization (%s): %v", authType, err))
|
|
|
|
}
|
|
|
|
app.accessController = accessController
|
|
|
|
}
|
|
|
|
|
2014-11-11 03:57:38 +01:00
|
|
|
return app
|
|
|
|
}
|
|
|
|
|
|
|
|
// register a handler with the application, by route name. The handler will be
|
|
|
|
// passed through the application filters and context will be constructed at
|
|
|
|
// request time.
|
|
|
|
func (app *App) register(routeName string, dispatch dispatchFunc) {
|
|
|
|
|
|
|
|
// TODO(stevvooe): This odd dispatcher/route registration is by-product of
|
|
|
|
// some limitations in the gorilla/mux router. We are using it to keep
|
|
|
|
// routing consistent between the client and server, but we may want to
|
|
|
|
// replace it with manual routing and structure-based dispatch for better
|
|
|
|
// control over the request execution.
|
|
|
|
|
|
|
|
app.router.GetRoute(routeName).Handler(app.dispatcher(dispatch))
|
|
|
|
}
|
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
// configureEvents prepares the event sink for action.
|
|
|
|
func (app *App) configureEvents(configuration *configuration.Configuration) {
|
|
|
|
// Configure all of the endpoint sinks.
|
|
|
|
var sinks []notifications.Sink
|
|
|
|
for _, endpoint := range configuration.Notifications.Endpoints {
|
|
|
|
if endpoint.Disabled {
|
2015-02-07 01:19:19 +01:00
|
|
|
ctxu.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name)
|
2015-01-29 00:55:18 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2015-02-07 01:19:19 +01:00
|
|
|
ctxu.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers)
|
2015-01-29 00:55:18 +01:00
|
|
|
endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{
|
|
|
|
Timeout: endpoint.Timeout,
|
|
|
|
Threshold: endpoint.Threshold,
|
|
|
|
Backoff: endpoint.Backoff,
|
|
|
|
Headers: endpoint.Headers,
|
|
|
|
})
|
|
|
|
|
|
|
|
sinks = append(sinks, endpoint)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NOTE(stevvooe): Moving to a new queueing implementation is as easy as
|
|
|
|
// replacing broadcaster with a rabbitmq implementation. It's recommended
|
|
|
|
// that the registry instances also act as the workers to keep deployment
|
|
|
|
// simple.
|
|
|
|
app.events.sink = notifications.NewBroadcaster(sinks...)
|
|
|
|
|
|
|
|
// Populate registry event source
|
|
|
|
hostname, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
hostname = configuration.HTTP.Addr
|
|
|
|
} else {
|
|
|
|
// try to pick the port off the config
|
|
|
|
_, port, err := net.SplitHostPort(configuration.HTTP.Addr)
|
|
|
|
if err == nil {
|
|
|
|
hostname = net.JoinHostPort(hostname, port)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
app.events.source = notifications.SourceRecord{
|
|
|
|
Addr: hostname,
|
2015-04-10 03:45:39 +02:00
|
|
|
InstanceID: ctxu.GetStringValue(app, "instance.id"),
|
2015-01-29 00:55:18 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-02 01:27:24 +02:00
|
|
|
func (app *App) configureRedis(configuration *configuration.Configuration) {
|
|
|
|
if configuration.Redis.Addr == "" {
|
|
|
|
ctxu.GetLogger(app).Infof("redis not configured")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
pool := &redis.Pool{
|
|
|
|
Dial: func() (redis.Conn, error) {
|
|
|
|
// TODO(stevvooe): Yet another use case for contextual timing.
|
|
|
|
ctx := context.WithValue(app, "redis.connect.startedat", time.Now())
|
|
|
|
|
|
|
|
done := func(err error) {
|
|
|
|
logger := ctxu.GetLoggerWithField(ctx, "redis.connect.duration",
|
|
|
|
ctxu.Since(ctx, "redis.connect.startedat"))
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("redis: error connecting: %v", err)
|
|
|
|
} else {
|
|
|
|
logger.Infof("redis: connect %v", configuration.Redis.Addr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
conn, err := redis.DialTimeout("tcp",
|
|
|
|
configuration.Redis.Addr,
|
|
|
|
configuration.Redis.DialTimeout,
|
|
|
|
configuration.Redis.ReadTimeout,
|
|
|
|
configuration.Redis.WriteTimeout)
|
|
|
|
if err != nil {
|
|
|
|
ctxu.GetLogger(app).Errorf("error connecting to redis instance %s: %v",
|
|
|
|
configuration.Redis.Addr, err)
|
|
|
|
done(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// authorize the connection
|
|
|
|
if configuration.Redis.Password != "" {
|
|
|
|
if _, err = conn.Do("AUTH", configuration.Redis.Password); err != nil {
|
|
|
|
defer conn.Close()
|
|
|
|
done(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// select the database to use
|
|
|
|
if configuration.Redis.DB != 0 {
|
|
|
|
if _, err = conn.Do("SELECT", configuration.Redis.DB); err != nil {
|
|
|
|
defer conn.Close()
|
|
|
|
done(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
done(nil)
|
|
|
|
return conn, nil
|
|
|
|
},
|
|
|
|
MaxIdle: configuration.Redis.Pool.MaxIdle,
|
|
|
|
MaxActive: configuration.Redis.Pool.MaxActive,
|
|
|
|
IdleTimeout: configuration.Redis.Pool.IdleTimeout,
|
|
|
|
TestOnBorrow: func(c redis.Conn, t time.Time) error {
|
|
|
|
// TODO(stevvooe): We can probably do something more interesting
|
|
|
|
// here with the health package.
|
|
|
|
_, err := c.Do("PING")
|
|
|
|
return err
|
|
|
|
},
|
|
|
|
Wait: false, // if a connection is not avialable, proceed without cache.
|
|
|
|
}
|
|
|
|
|
|
|
|
app.redis = pool
|
|
|
|
|
2015-04-03 06:22:11 +02:00
|
|
|
// setup expvar
|
|
|
|
registry := expvar.Get("registry")
|
|
|
|
if registry == nil {
|
|
|
|
registry = expvar.NewMap("registry")
|
|
|
|
}
|
|
|
|
|
|
|
|
registry.(*expvar.Map).Set("redis", expvar.Func(func() interface{} {
|
2015-04-02 01:27:24 +02:00
|
|
|
return map[string]interface{}{
|
|
|
|
"Config": configuration.Redis,
|
|
|
|
"Active": app.redis.ActiveCount(),
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
defer r.Body.Close() // ensure that request body is always closed.
|
|
|
|
|
2015-04-16 04:20:45 +02:00
|
|
|
// Instantiate an http context here so we can track the error codes
|
|
|
|
// returned by the request router.
|
|
|
|
ctx := defaultContextManager.context(app, w, r)
|
|
|
|
defer func() {
|
|
|
|
ctxu.GetResponseLogger(ctx).Infof("response completed")
|
|
|
|
}()
|
|
|
|
defer defaultContextManager.release(ctx)
|
|
|
|
|
|
|
|
// NOTE(stevvooe): Total hack to get instrumented responsewriter from context.
|
|
|
|
var err error
|
|
|
|
w, err = ctxu.GetResponseWriter(ctx)
|
|
|
|
if err != nil {
|
|
|
|
ctxu.GetLogger(ctx).Warnf("response writer not found in context")
|
|
|
|
}
|
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
// Set a header with the Docker Distribution API Version for all responses.
|
|
|
|
w.Header().Add("Docker-Distribution-API-Version", "registry/2.0")
|
|
|
|
app.router.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
2014-11-11 03:57:38 +01:00
|
|
|
// dispatchFunc takes a context and request and returns a constructed handler
|
|
|
|
// for the route. The dispatcher will use this to dynamically create request
|
|
|
|
// specific handlers for each endpoint without creating a new router for each
|
|
|
|
// request.
|
|
|
|
type dispatchFunc func(ctx *Context, r *http.Request) http.Handler
|
|
|
|
|
|
|
|
// TODO(stevvooe): dispatchers should probably have some validation error
|
|
|
|
// chain with proper error reporting.
|
|
|
|
|
|
|
|
// dispatcher returns a handler that constructs a request specific context and
|
|
|
|
// handler, using the dispatch factory function.
|
|
|
|
func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2015-02-07 01:19:19 +01:00
|
|
|
context := app.context(w, r)
|
2014-11-11 03:57:38 +01:00
|
|
|
|
2015-02-07 01:19:19 +01:00
|
|
|
if err := app.authorized(w, r, context); err != nil {
|
2015-02-11 00:19:02 +01:00
|
|
|
ctxu.GetLogger(context).Errorf("error authorizing context: %v", err)
|
2014-12-18 21:30:19 +01:00
|
|
|
return
|
|
|
|
}
|
2014-11-11 03:57:38 +01:00
|
|
|
|
2015-04-15 01:07:23 +02:00
|
|
|
// Add username to request logging
|
|
|
|
context.Context = ctxu.WithLogger(context.Context, ctxu.GetLogger(context.Context, "auth.user.name"))
|
|
|
|
|
2015-02-13 22:59:50 +01:00
|
|
|
if app.nameRequired(r) {
|
|
|
|
repository, err := app.registry.Repository(context, getName(context))
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
ctxu.GetLogger(context).Errorf("error resolving repository: %v", err)
|
|
|
|
|
|
|
|
switch err := err.(type) {
|
|
|
|
case distribution.ErrRepositoryUnknown:
|
2015-05-27 02:18:32 +02:00
|
|
|
context.Errors = append(context.Errors, errcode.NewError(v2.ErrorCodeNameUnknown, err))
|
2015-02-13 22:59:50 +01:00
|
|
|
case distribution.ErrRepositoryNameInvalid:
|
2015-05-27 02:18:32 +02:00
|
|
|
context.Errors = append(context.Errors, errcode.NewError(v2.ErrorCodeNameInvalid, err))
|
2015-02-13 22:59:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
serveJSON(w, context.Errors)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// assign and decorate the authorized repository with an event bridge.
|
|
|
|
context.Repository = notifications.Listen(
|
|
|
|
repository,
|
|
|
|
app.eventBridge(context, r))
|
2015-03-06 16:45:16 +01:00
|
|
|
|
2015-03-09 18:55:52 +01:00
|
|
|
context.Repository, err = applyRepoMiddleware(context.Repository, app.Config.Middleware["repository"])
|
|
|
|
if err != nil {
|
|
|
|
ctxu.GetLogger(context).Errorf("error initializing repository middleware: %v", err)
|
2015-05-27 02:18:32 +02:00
|
|
|
context.Errors = append(context.Errors, errcode.NewError(errcode.ErrorCodeUnknown, err))
|
2015-05-15 03:21:39 +02:00
|
|
|
|
2015-03-09 18:55:52 +01:00
|
|
|
serveJSON(w, context.Errors)
|
|
|
|
return
|
2015-03-06 16:45:16 +01:00
|
|
|
}
|
2015-02-13 22:59:50 +01:00
|
|
|
}
|
|
|
|
|
2015-04-16 04:20:45 +02:00
|
|
|
dispatch(context, r).ServeHTTP(w, r)
|
2014-11-11 03:57:38 +01:00
|
|
|
// Automated error response handling here. Handlers may return their
|
|
|
|
// own errors if they need different behavior (such as range errors
|
|
|
|
// for layer upload).
|
2014-11-21 04:57:01 +01:00
|
|
|
if context.Errors.Len() > 0 {
|
2015-04-21 01:35:09 +02:00
|
|
|
app.logError(context, context.Errors)
|
2015-05-15 03:21:39 +02:00
|
|
|
|
2014-11-11 03:57:38 +01:00
|
|
|
serveJSON(w, context.Errors)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2014-12-11 07:33:36 +01:00
|
|
|
|
2015-05-15 03:21:39 +02:00
|
|
|
func (app *App) logError(context context.Context, errors errcode.Errors) {
|
2015-05-27 02:18:32 +02:00
|
|
|
for _, e := range errors {
|
2015-04-21 01:35:09 +02:00
|
|
|
c := ctxu.WithValue(context, "err.code", e.Code)
|
2015-05-27 02:18:32 +02:00
|
|
|
c = ctxu.WithValue(c, "err.message", e.Code.Message())
|
2015-04-21 01:35:09 +02:00
|
|
|
c = ctxu.WithValue(c, "err.detail", e.Detail)
|
|
|
|
c = ctxu.WithLogger(c, ctxu.GetLogger(c,
|
|
|
|
"err.code",
|
|
|
|
"err.message",
|
|
|
|
"err.detail"))
|
|
|
|
ctxu.GetLogger(c).Errorf("An error occured")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-18 21:30:19 +01:00
|
|
|
// context constructs the context object for the application. This only be
|
|
|
|
// called once per request.
|
2015-02-07 01:19:19 +01:00
|
|
|
func (app *App) context(w http.ResponseWriter, r *http.Request) *Context {
|
2015-04-16 04:20:45 +02:00
|
|
|
ctx := defaultContextManager.context(app, w, r)
|
2015-02-07 01:19:19 +01:00
|
|
|
ctx = ctxu.WithVars(ctx, r)
|
|
|
|
ctx = ctxu.WithLogger(ctx, ctxu.GetLogger(ctx,
|
|
|
|
"vars.name",
|
2015-02-27 00:47:04 +01:00
|
|
|
"vars.reference",
|
2015-02-07 01:19:19 +01:00
|
|
|
"vars.digest",
|
|
|
|
"vars.uuid"))
|
|
|
|
|
2014-12-18 21:30:19 +01:00
|
|
|
context := &Context{
|
|
|
|
App: app,
|
2015-02-07 01:19:19 +01:00
|
|
|
Context: ctx,
|
2014-12-18 21:30:19 +01:00
|
|
|
urlBuilder: v2.NewURLBuilderFromRequest(r),
|
|
|
|
}
|
|
|
|
|
|
|
|
return context
|
|
|
|
}
|
|
|
|
|
2015-01-17 03:32:27 +01:00
|
|
|
// authorized checks if the request can proceed with access to the requested
|
2015-02-11 00:19:02 +01:00
|
|
|
// repository. If it succeeds, the context may access the requested
|
|
|
|
// repository. An error will be returned if access is not available.
|
2015-02-07 01:19:19 +01:00
|
|
|
func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error {
|
|
|
|
ctxu.GetLogger(context).Debug("authorizing request")
|
|
|
|
repo := getName(context)
|
|
|
|
|
2014-12-18 21:30:19 +01:00
|
|
|
if app.accessController == nil {
|
|
|
|
return nil // access controller is not enabled.
|
|
|
|
}
|
|
|
|
|
|
|
|
var accessRecords []auth.Access
|
|
|
|
|
2015-01-17 03:32:27 +01:00
|
|
|
if repo != "" {
|
2015-03-10 00:23:27 +01:00
|
|
|
accessRecords = appendAccessRecords(accessRecords, r.Method, repo)
|
2014-12-19 02:20:35 +01:00
|
|
|
} else {
|
|
|
|
// Only allow the name not to be set on the base route.
|
2015-02-13 22:59:50 +01:00
|
|
|
if app.nameRequired(r) {
|
2015-02-11 00:19:02 +01:00
|
|
|
// For this to be properly secured, repo must always be set for a
|
|
|
|
// resource that may make a modification. The only condition under
|
|
|
|
// which name is not set and we still allow access is when the
|
|
|
|
// base route is accessed. This section prevents us from making
|
|
|
|
// that mistake elsewhere in the code, allowing any operation to
|
|
|
|
// proceed.
|
2014-12-19 02:20:35 +01:00
|
|
|
|
2015-05-15 03:21:39 +02:00
|
|
|
var errs errcode.Errors
|
2015-05-27 02:18:32 +02:00
|
|
|
errs = append(errs, errcode.NewError(v2.ErrorCodeUnauthorized))
|
2015-05-15 03:21:39 +02:00
|
|
|
|
2014-12-19 02:20:35 +01:00
|
|
|
serveJSON(w, errs)
|
2015-02-11 00:19:02 +01:00
|
|
|
return fmt.Errorf("forbidden: no repository name")
|
2014-12-19 02:20:35 +01:00
|
|
|
}
|
2014-12-18 21:30:19 +01:00
|
|
|
}
|
|
|
|
|
2015-02-07 01:19:19 +01:00
|
|
|
ctx, err := app.accessController.Authorized(context.Context, accessRecords...)
|
2015-02-04 02:59:24 +01:00
|
|
|
if err != nil {
|
2014-12-18 21:30:19 +01:00
|
|
|
switch err := err.(type) {
|
|
|
|
case auth.Challenge:
|
2015-05-15 03:21:39 +02:00
|
|
|
// Since err.ServeHTTP will set the HTTP status code for us
|
|
|
|
// we need to set the content-type here. The serveJSON
|
|
|
|
// func will try to do it but it'll be too late at that point.
|
|
|
|
// I would have have preferred to just have the auth.Challenge
|
|
|
|
// ServerHTTP func just add the WWW-Authenticate header and let
|
|
|
|
// serveJSON set the HTTP status code and content-type but I wasn't
|
|
|
|
// sure if that's an ok design change. STEVVOOE ?
|
2014-12-31 05:09:45 +01:00
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
2015-05-15 03:21:39 +02:00
|
|
|
|
2014-12-18 21:30:19 +01:00
|
|
|
err.ServeHTTP(w, r)
|
|
|
|
|
2015-05-15 03:21:39 +02:00
|
|
|
var errs errcode.Errors
|
2015-05-27 02:18:32 +02:00
|
|
|
errs = append(errs, errcode.NewError(v2.ErrorCodeUnauthorized, accessRecords))
|
2014-12-18 21:30:19 +01:00
|
|
|
serveJSON(w, errs)
|
|
|
|
default:
|
|
|
|
// This condition is a potential security problem either in
|
|
|
|
// the configuration or whatever is backing the access
|
|
|
|
// controller. Just return a bad request with no information
|
|
|
|
// to avoid exposure. The request should not proceed.
|
2015-02-07 01:19:19 +01:00
|
|
|
ctxu.GetLogger(context).Errorf("error checking authorization: %v", err)
|
2014-12-18 21:30:19 +01:00
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-02-09 23:44:58 +01:00
|
|
|
// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context
|
|
|
|
// should be replaced by another, rather than replacing the context on a
|
|
|
|
// mutable object.
|
2015-02-07 01:19:19 +01:00
|
|
|
context.Context = ctx
|
2014-12-18 21:30:19 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-01-29 00:55:18 +01:00
|
|
|
// eventBridge returns a bridge for the current request, configured with the
|
|
|
|
// correct actor and source.
|
|
|
|
func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listener {
|
|
|
|
actor := notifications.ActorRecord{
|
2015-02-07 01:19:19 +01:00
|
|
|
Name: getUserName(ctx, r),
|
2015-01-29 00:55:18 +01:00
|
|
|
}
|
2015-02-07 01:19:19 +01:00
|
|
|
request := notifications.NewRequestRecord(ctxu.GetRequestID(ctx), r)
|
2015-01-29 00:55:18 +01:00
|
|
|
|
2015-02-03 22:28:10 +01:00
|
|
|
return notifications.NewBridge(ctx.urlBuilder, app.events.source, actor, request, app.events.sink)
|
2015-01-29 00:55:18 +01:00
|
|
|
}
|
|
|
|
|
2015-02-13 22:59:50 +01:00
|
|
|
// nameRequired returns true if the route requires a name.
|
|
|
|
func (app *App) nameRequired(r *http.Request) bool {
|
|
|
|
route := mux.CurrentRoute(r)
|
|
|
|
return route == nil || route.GetName() != v2.RouteNameBase
|
|
|
|
}
|
|
|
|
|
2014-12-11 07:33:36 +01:00
|
|
|
// apiBase implements a simple yes-man for doing overall checks against the
|
|
|
|
// api. This can support auth roundtrips to support docker login.
|
|
|
|
func apiBase(w http.ResponseWriter, r *http.Request) {
|
|
|
|
const emptyJSON = "{}"
|
|
|
|
// Provide a simple /v2/ 200 OK response with empty json response.
|
2014-12-31 05:09:45 +01:00
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
2014-12-11 07:33:36 +01:00
|
|
|
w.Header().Set("Content-Length", fmt.Sprint(len(emptyJSON)))
|
|
|
|
|
|
|
|
fmt.Fprint(w, emptyJSON)
|
|
|
|
}
|
2015-03-10 00:23:27 +01:00
|
|
|
|
|
|
|
// appendAccessRecords checks the method and adds the appropriate Access records to the records list.
|
|
|
|
func appendAccessRecords(records []auth.Access, method string, repo string) []auth.Access {
|
|
|
|
resource := auth.Resource{
|
|
|
|
Type: "repository",
|
|
|
|
Name: repo,
|
|
|
|
}
|
|
|
|
|
|
|
|
switch method {
|
|
|
|
case "GET", "HEAD":
|
|
|
|
records = append(records,
|
|
|
|
auth.Access{
|
|
|
|
Resource: resource,
|
|
|
|
Action: "pull",
|
|
|
|
})
|
|
|
|
case "POST", "PUT", "PATCH":
|
|
|
|
records = append(records,
|
|
|
|
auth.Access{
|
|
|
|
Resource: resource,
|
|
|
|
Action: "pull",
|
|
|
|
},
|
|
|
|
auth.Access{
|
|
|
|
Resource: resource,
|
|
|
|
Action: "push",
|
|
|
|
})
|
|
|
|
case "DELETE":
|
|
|
|
// DELETE access requires full admin rights, which is represented
|
|
|
|
// as "*". This may not be ideal.
|
|
|
|
records = append(records,
|
|
|
|
auth.Access{
|
|
|
|
Resource: resource,
|
|
|
|
Action: "*",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return records
|
|
|
|
}
|
2015-03-09 18:55:52 +01:00
|
|
|
|
|
|
|
// applyRegistryMiddleware wraps a registry instance with the configured middlewares
|
2015-04-10 04:21:33 +02:00
|
|
|
func applyRegistryMiddleware(registry distribution.Namespace, middlewares []configuration.Middleware) (distribution.Namespace, error) {
|
2015-03-09 18:55:52 +01:00
|
|
|
for _, mw := range middlewares {
|
|
|
|
rmw, err := registrymiddleware.Get(mw.Name, mw.Options, registry)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to configure registry middleware (%s): %s", mw.Name, err)
|
|
|
|
}
|
|
|
|
registry = rmw
|
|
|
|
}
|
|
|
|
return registry, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// applyRepoMiddleware wraps a repository with the configured middlewares
|
|
|
|
func applyRepoMiddleware(repository distribution.Repository, middlewares []configuration.Middleware) (distribution.Repository, error) {
|
|
|
|
for _, mw := range middlewares {
|
|
|
|
rmw, err := repositorymiddleware.Get(mw.Name, mw.Options, repository)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
repository = rmw
|
|
|
|
}
|
|
|
|
return repository, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// applyStorageMiddleware wraps a storage driver with the configured middlewares
|
|
|
|
func applyStorageMiddleware(driver storagedriver.StorageDriver, middlewares []configuration.Middleware) (storagedriver.StorageDriver, error) {
|
|
|
|
for _, mw := range middlewares {
|
|
|
|
smw, err := storagemiddleware.Get(mw.Name, mw.Options, driver)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to configure storage middleware (%s): %v", mw.Name, err)
|
|
|
|
}
|
|
|
|
driver = smw
|
|
|
|
}
|
|
|
|
return driver, nil
|
|
|
|
}
|
2015-04-08 00:52:48 +02:00
|
|
|
|
2015-04-17 03:34:29 +02:00
|
|
|
// uploadPurgeDefaultConfig provides a default configuration for upload
|
|
|
|
// purging to be used in the absence of configuration in the
|
|
|
|
// confifuration file
|
|
|
|
func uploadPurgeDefaultConfig() map[interface{}]interface{} {
|
|
|
|
config := map[interface{}]interface{}{}
|
|
|
|
config["enabled"] = true
|
|
|
|
config["age"] = "168h"
|
|
|
|
config["interval"] = "24h"
|
|
|
|
config["dryrun"] = false
|
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
|
|
|
func badPurgeUploadConfig(reason string) {
|
|
|
|
panic(fmt.Sprintf("Unable to parse upload purge configuration: %s", reason))
|
|
|
|
}
|
|
|
|
|
2015-04-08 00:52:48 +02:00
|
|
|
// startUploadPurger schedules a goroutine which will periodically
|
|
|
|
// check upload directories for old files and delete them
|
2015-04-28 00:58:58 +02:00
|
|
|
func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log ctxu.Logger, config map[interface{}]interface{}) {
|
2015-04-17 03:34:29 +02:00
|
|
|
if config["enabled"] == false {
|
|
|
|
return
|
|
|
|
}
|
2015-04-08 00:52:48 +02:00
|
|
|
|
2015-04-17 03:34:29 +02:00
|
|
|
var purgeAgeDuration time.Duration
|
|
|
|
var err error
|
|
|
|
purgeAge, ok := config["age"]
|
|
|
|
if ok {
|
|
|
|
ageStr, ok := purgeAge.(string)
|
|
|
|
if !ok {
|
|
|
|
badPurgeUploadConfig("age is not a string")
|
|
|
|
}
|
|
|
|
purgeAgeDuration, err = time.ParseDuration(ageStr)
|
|
|
|
if err != nil {
|
|
|
|
badPurgeUploadConfig(fmt.Sprintf("Cannot parse duration: %s", err.Error()))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
badPurgeUploadConfig("age missing")
|
|
|
|
}
|
|
|
|
|
|
|
|
var intervalDuration time.Duration
|
|
|
|
interval, ok := config["interval"]
|
|
|
|
if ok {
|
|
|
|
intervalStr, ok := interval.(string)
|
|
|
|
if !ok {
|
|
|
|
badPurgeUploadConfig("interval is not a string")
|
|
|
|
}
|
|
|
|
|
|
|
|
intervalDuration, err = time.ParseDuration(intervalStr)
|
|
|
|
if err != nil {
|
|
|
|
badPurgeUploadConfig(fmt.Sprintf("Cannot parse interval: %s", err.Error()))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
badPurgeUploadConfig("interval missing")
|
|
|
|
}
|
|
|
|
|
|
|
|
var dryRunBool bool
|
|
|
|
dryRun, ok := config["dryrun"]
|
|
|
|
if ok {
|
|
|
|
dryRunBool, ok = dryRun.(bool)
|
|
|
|
if !ok {
|
|
|
|
badPurgeUploadConfig("cannot parse dryrun")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
badPurgeUploadConfig("dryrun missing")
|
|
|
|
}
|
2015-04-08 00:52:48 +02:00
|
|
|
|
|
|
|
go func() {
|
2015-04-17 03:34:29 +02:00
|
|
|
rand.Seed(time.Now().Unix())
|
|
|
|
jitter := time.Duration(rand.Int()%60) * time.Minute
|
2015-04-08 00:52:48 +02:00
|
|
|
log.Infof("Starting upload purge in %s", jitter)
|
|
|
|
time.Sleep(jitter)
|
|
|
|
|
|
|
|
for {
|
2015-04-28 00:58:58 +02:00
|
|
|
storage.PurgeUploads(ctx, storageDriver, time.Now().Add(-purgeAgeDuration), !dryRunBool)
|
2015-04-17 03:34:29 +02:00
|
|
|
log.Infof("Starting upload purge in %s", intervalDuration)
|
|
|
|
time.Sleep(intervalDuration)
|
2015-04-08 00:52:48 +02:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|