2021-08-23 13:14:53 +00:00
|
|
|
//go:build !windows
|
2015-07-16 21:14:58 +00:00
|
|
|
|
2018-02-05 21:05:59 +00:00
|
|
|
package daemon // import "github.com/docker/docker/daemon"
|
2015-07-16 21:14:58 +00:00
|
|
|
|
|
|
|
import (
|
2018-03-22 21:11:03 +00:00
|
|
|
"context"
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 15:53:35 +00:00
|
|
|
"fmt"
|
2015-07-16 21:14:58 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
2023-09-13 15:41:45 +00:00
|
|
|
"github.com/containerd/log"
|
2016-09-06 18:18:12 +00:00
|
|
|
containertypes "github.com/docker/docker/api/types/container"
|
Add new `HostConfig` field, `Mounts`.
`Mounts` allows users to specify in a much safer way the volumes they
want to use in the container.
This replaces `Binds` and `Volumes`, which both still exist, but
`Mounts` and `Binds`/`Volumes` are exclussive.
The CLI will continue to use `Binds` and `Volumes` due to concerns with
parsing the volume specs on the client side and cross-platform support
(for now).
The new API follows exactly the services mount API.
Example usage of `Mounts`:
```
$ curl -XPOST localhost:2375/containers/create -d '{
"Image": "alpine:latest",
"HostConfig": {
"Mounts": [{
"Type": "Volume",
"Target": "/foo"
},{
"Type": "bind",
"Source": "/var/run/docker.sock",
"Target": "/var/run/docker.sock",
},{
"Type": "volume",
"Name": "important_data",
"Target": "/var/data",
"ReadOnly": true,
"VolumeOptions": {
"DriverConfig": {
Name: "awesomeStorage",
Options: {"size": "10m"},
Labels: {"some":"label"}
}
}]
}
}'
```
There are currently 2 types of mounts:
- **bind**: Paths on the host that get mounted into the
container. Paths must exist prior to creating the container.
- **volume**: Volumes that persist after the
container is removed.
Not all fields are available in each type, and validation is done to
ensure these fields aren't mixed up between types.
Signed-off-by: Brian Goff <cpuguy83@gmail.com>
2016-04-26 18:25:35 +00:00
|
|
|
mounttypes "github.com/docker/docker/api/types/mount"
|
2015-11-12 19:55:17 +00:00
|
|
|
"github.com/docker/docker/container"
|
2023-06-09 18:19:34 +00:00
|
|
|
"github.com/docker/docker/errdefs"
|
2023-07-27 12:56:28 +00:00
|
|
|
"github.com/docker/docker/internal/compatcontext"
|
2018-03-20 17:29:18 +00:00
|
|
|
"github.com/docker/docker/oci"
|
2023-06-09 18:19:34 +00:00
|
|
|
volumemounts "github.com/docker/docker/volume/mounts"
|
2018-03-22 21:11:03 +00:00
|
|
|
volumeopts "github.com/docker/docker/volume/service/opts"
|
2017-04-18 13:26:36 +00:00
|
|
|
"github.com/opencontainers/selinux/go-selinux/label"
|
2023-06-09 18:19:34 +00:00
|
|
|
"github.com/pkg/errors"
|
2015-07-16 21:14:58 +00:00
|
|
|
)
|
|
|
|
|
2017-08-08 19:43:48 +00:00
|
|
|
// createContainerOSSpecificSettings performs host-OS specific container create functionality
|
2023-07-27 12:56:28 +00:00
|
|
|
func (daemon *Daemon) createContainerOSSpecificSettings(ctx context.Context, container *container.Container, config *containertypes.Config, hostConfig *containertypes.HostConfig) error {
|
2015-11-04 00:57:16 +00:00
|
|
|
if err := daemon.Mount(container); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer daemon.Unmount(container)
|
|
|
|
|
2017-11-16 06:20:33 +00:00
|
|
|
rootIDs := daemon.idMapping.RootPair()
|
2017-05-19 22:06:46 +00:00
|
|
|
if err := container.SetupWorkingDirectory(rootIDs); err != nil {
|
2016-01-08 04:11:21 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-03-20 17:29:18 +00:00
|
|
|
// Set the default masked and readonly paths with regard to the host config options if they are not set.
|
|
|
|
if hostConfig.MaskedPaths == nil && !hostConfig.Privileged {
|
|
|
|
hostConfig.MaskedPaths = oci.DefaultSpec().Linux.MaskedPaths // Set it to the default if nil
|
|
|
|
container.HostConfig.MaskedPaths = hostConfig.MaskedPaths
|
|
|
|
}
|
|
|
|
if hostConfig.ReadonlyPaths == nil && !hostConfig.Privileged {
|
|
|
|
hostConfig.ReadonlyPaths = oci.DefaultSpec().Linux.ReadonlyPaths // Set it to the default if nil
|
|
|
|
container.HostConfig.ReadonlyPaths = hostConfig.ReadonlyPaths
|
|
|
|
}
|
|
|
|
|
2015-07-16 21:14:58 +00:00
|
|
|
for spec := range config.Volumes {
|
2015-11-04 01:03:40 +00:00
|
|
|
destination := filepath.Clean(spec)
|
2015-09-29 14:01:57 +00:00
|
|
|
|
2015-07-16 21:14:58 +00:00
|
|
|
// Skip volumes for which we already have something mounted on that
|
|
|
|
// destination because of a --volume-from.
|
2020-02-03 20:28:19 +00:00
|
|
|
if container.HasMountFor(destination) {
|
2023-07-27 12:56:28 +00:00
|
|
|
log.G(ctx).WithField("container", container.ID).WithField("destination", spec).Debug("mountpoint already exists, skipping anonymous volume")
|
2020-02-03 20:28:19 +00:00
|
|
|
// Not an error, this could easily have come from the image config.
|
2015-07-16 21:14:58 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
path, err := container.GetResourcePath(destination)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
stat, err := os.Stat(path)
|
|
|
|
if err == nil && !stat.IsDir() {
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 15:53:35 +00:00
|
|
|
return fmt.Errorf("cannot mount volume over existing file, file exists %s", path)
|
2015-07-16 21:14:58 +00:00
|
|
|
}
|
|
|
|
|
2023-03-11 22:34:21 +00:00
|
|
|
v, err := daemon.volumes.Create(context.TODO(), "", hostConfig.VolumeDriver, volumeopts.WithCreateReference(container.ID))
|
2015-07-16 21:14:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-06-12 13:25:32 +00:00
|
|
|
|
2018-03-22 21:11:03 +00:00
|
|
|
if err := label.Relabel(v.Mountpoint, container.MountLabel, true); err != nil {
|
2015-07-16 21:14:58 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-03-22 21:11:03 +00:00
|
|
|
container.AddMountPointWithVolume(destination, &volumeWrapper{v: v, s: daemon.volumes}, true)
|
2016-01-08 02:38:38 +00:00
|
|
|
}
|
2023-07-27 12:56:28 +00:00
|
|
|
return daemon.populateVolumes(ctx, container)
|
2016-01-08 02:38:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// populateVolumes copies data from the container's rootfs into the volume for non-binds.
|
|
|
|
// this is only called when the container is created.
|
2023-07-27 12:56:28 +00:00
|
|
|
func (daemon *Daemon) populateVolumes(ctx context.Context, c *container.Container) error {
|
2016-01-08 02:38:38 +00:00
|
|
|
for _, mnt := range c.MountPoints {
|
Add new `HostConfig` field, `Mounts`.
`Mounts` allows users to specify in a much safer way the volumes they
want to use in the container.
This replaces `Binds` and `Volumes`, which both still exist, but
`Mounts` and `Binds`/`Volumes` are exclussive.
The CLI will continue to use `Binds` and `Volumes` due to concerns with
parsing the volume specs on the client side and cross-platform support
(for now).
The new API follows exactly the services mount API.
Example usage of `Mounts`:
```
$ curl -XPOST localhost:2375/containers/create -d '{
"Image": "alpine:latest",
"HostConfig": {
"Mounts": [{
"Type": "Volume",
"Target": "/foo"
},{
"Type": "bind",
"Source": "/var/run/docker.sock",
"Target": "/var/run/docker.sock",
},{
"Type": "volume",
"Name": "important_data",
"Target": "/var/data",
"ReadOnly": true,
"VolumeOptions": {
"DriverConfig": {
Name: "awesomeStorage",
Options: {"size": "10m"},
Labels: {"some":"label"}
}
}]
}
}'
```
There are currently 2 types of mounts:
- **bind**: Paths on the host that get mounted into the
container. Paths must exist prior to creating the container.
- **volume**: Volumes that persist after the
container is removed.
Not all fields are available in each type, and validation is done to
ensure these fields aren't mixed up between types.
Signed-off-by: Brian Goff <cpuguy83@gmail.com>
2016-04-26 18:25:35 +00:00
|
|
|
if mnt.Volume == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if mnt.Type != mounttypes.TypeVolume || !mnt.CopyData {
|
2016-01-08 02:38:38 +00:00
|
|
|
continue
|
2015-07-16 21:14:58 +00:00
|
|
|
}
|
|
|
|
|
2023-07-27 12:56:28 +00:00
|
|
|
if err := daemon.populateVolume(ctx, c, mnt); err != nil {
|
2016-01-08 02:38:38 +00:00
|
|
|
return err
|
|
|
|
}
|
2015-07-16 21:14:58 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2023-06-09 18:19:34 +00:00
|
|
|
|
2023-07-27 12:56:28 +00:00
|
|
|
func (daemon *Daemon) populateVolume(ctx context.Context, c *container.Container, mnt *volumemounts.MountPoint) error {
|
2023-06-09 18:19:34 +00:00
|
|
|
ctrDestPath, err := c.GetResourcePath(mnt.Destination)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := os.Stat(ctrDestPath); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-07-27 12:56:28 +00:00
|
|
|
volumePath, cleanup, err := mnt.Setup(ctx, c.MountLabel, daemon.idMapping.RootPair(), nil)
|
2023-06-09 18:19:34 +00:00
|
|
|
if err != nil {
|
|
|
|
if errdefs.IsNotFound(err) {
|
|
|
|
return nil
|
|
|
|
}
|
2023-07-27 12:56:28 +00:00
|
|
|
log.G(ctx).WithError(err).Debugf("can't copy data from %s:%s, to %s", c.ID, mnt.Destination, volumePath)
|
2023-06-09 18:19:34 +00:00
|
|
|
return errors.Wrapf(err, "failed to populate volume")
|
|
|
|
}
|
2023-07-27 12:56:28 +00:00
|
|
|
defer mnt.Cleanup(compatcontext.WithoutCancel(ctx))
|
|
|
|
defer cleanup(compatcontext.WithoutCancel(ctx))
|
2023-06-09 18:19:34 +00:00
|
|
|
|
2023-07-27 12:56:28 +00:00
|
|
|
log.G(ctx).Debugf("copying image data from %s:%s, to %s", c.ID, mnt.Destination, volumePath)
|
2023-06-09 18:19:34 +00:00
|
|
|
if err := c.CopyImagePathContent(volumePath, ctrDestPath); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|