2015-05-19 16:05:25 -04:00
|
|
|
package volume
|
|
|
|
|
2015-09-09 22:23:06 -04:00
|
|
|
import (
|
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 10:53:35 -05:00
|
|
|
"fmt"
|
2015-09-09 22:23:06 -04:00
|
|
|
"os"
|
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 14:25:35 -04:00
|
|
|
"path/filepath"
|
2015-09-09 22:23:06 -04:00
|
|
|
"strings"
|
2016-05-26 14:39:46 -04:00
|
|
|
"syscall"
|
2016-03-07 21:41:44 -05:00
|
|
|
|
2016-09-06 14:18:12 -04:00
|
|
|
mounttypes "github.com/docker/docker/api/types/mount"
|
2016-08-23 04:33:38 -04:00
|
|
|
"github.com/docker/docker/pkg/idtools"
|
2016-03-07 21:41:44 -05:00
|
|
|
"github.com/docker/docker/pkg/stringid"
|
2016-05-26 14:39:46 -04:00
|
|
|
"github.com/opencontainers/runc/libcontainer/label"
|
2016-09-23 10:38:19 -04:00
|
|
|
"github.com/pkg/errors"
|
2015-09-09 22:23:06 -04:00
|
|
|
)
|
|
|
|
|
2015-07-21 13:50:10 -04:00
|
|
|
// DefaultDriverName is the driver name used for the driver
|
|
|
|
// implemented in the local package.
|
2016-04-11 11:17:52 -04:00
|
|
|
const DefaultDriverName = "local"
|
|
|
|
|
|
|
|
// Scopes define if a volume has is cluster-wide (global) or local only.
|
|
|
|
// Scopes are returned by the volume driver when it is queried for capabilities and then set on a volume
|
|
|
|
const (
|
|
|
|
LocalScope = "local"
|
|
|
|
GlobalScope = "global"
|
|
|
|
)
|
2015-05-19 16:05:25 -04:00
|
|
|
|
2015-07-21 13:50:10 -04:00
|
|
|
// Driver is for creating and removing volumes.
|
2015-05-19 16:05:25 -04:00
|
|
|
type Driver interface {
|
|
|
|
// Name returns the name of the volume driver.
|
|
|
|
Name() string
|
|
|
|
// Create makes a new volume with the given id.
|
2015-06-12 09:25:32 -04:00
|
|
|
Create(name string, opts map[string]string) (Volume, error)
|
2015-05-19 16:05:25 -04:00
|
|
|
// Remove deletes the volume.
|
2015-09-23 16:29:14 -04:00
|
|
|
Remove(vol Volume) (err error)
|
|
|
|
// List lists all the volumes the driver has
|
|
|
|
List() ([]Volume, error)
|
2016-02-11 18:21:52 -05:00
|
|
|
// Get retrieves the volume with the requested name
|
2015-09-23 16:29:14 -04:00
|
|
|
Get(name string) (Volume, error)
|
2016-07-01 17:29:08 -04:00
|
|
|
// Scope returns the scope of the driver (e.g. `global` or `local`).
|
2016-04-11 11:17:52 -04:00
|
|
|
// Scope determines how the driver is handled at a cluster level
|
|
|
|
Scope() string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Capability defines a set of capabilities that a driver is able to handle.
|
|
|
|
type Capability struct {
|
|
|
|
// Scope is the scope of the driver, `global` or `local`
|
|
|
|
// A `global` scope indicates that the driver manages volumes across the cluster
|
|
|
|
// A `local` scope indicates that the driver only manages volumes resources local to the host
|
|
|
|
// Scope is declared by the driver
|
|
|
|
Scope string
|
2015-05-19 16:05:25 -04:00
|
|
|
}
|
|
|
|
|
2015-07-21 13:50:10 -04:00
|
|
|
// Volume is a place to store data. It is backed by a specific driver, and can be mounted.
|
2015-05-19 16:05:25 -04:00
|
|
|
type Volume interface {
|
|
|
|
// Name returns the name of the volume
|
|
|
|
Name() string
|
|
|
|
// DriverName returns the name of the driver which owns this volume.
|
|
|
|
DriverName() string
|
|
|
|
// Path returns the absolute path to the volume.
|
|
|
|
Path() string
|
|
|
|
// Mount mounts the volume and returns the absolute path to
|
|
|
|
// where it can be consumed.
|
2016-03-07 21:41:44 -05:00
|
|
|
Mount(id string) (string, error)
|
2015-05-19 16:05:25 -04:00
|
|
|
// Unmount unmounts the volume when it is no longer in use.
|
2016-03-07 21:41:44 -05:00
|
|
|
Unmount(id string) error
|
2016-03-07 15:44:43 -05:00
|
|
|
// Status returns low-level status information about a volume
|
|
|
|
Status() map[string]interface{}
|
2015-05-19 16:05:25 -04:00
|
|
|
}
|
2015-07-12 04:33:30 -04:00
|
|
|
|
2016-09-17 15:32:31 -04:00
|
|
|
// DetailedVolume wraps a Volume with user-defined labels, options, and cluster scope (e.g., `local` or `global`)
|
|
|
|
type DetailedVolume interface {
|
2016-04-11 11:17:52 -04:00
|
|
|
Labels() map[string]string
|
2016-09-17 15:32:31 -04:00
|
|
|
Options() map[string]string
|
2016-04-11 11:17:52 -04:00
|
|
|
Scope() string
|
|
|
|
Volume
|
|
|
|
}
|
|
|
|
|
2015-09-09 22:23:06 -04:00
|
|
|
// MountPoint is the intersection point between a volume and a container. It
|
|
|
|
// specifies which volume is to be used and where inside a container it should
|
|
|
|
// be mounted.
|
|
|
|
type MountPoint struct {
|
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 14:25:35 -04:00
|
|
|
Source string // Container host directory
|
|
|
|
Destination string // Inside the container
|
|
|
|
RW bool // True if writable
|
|
|
|
Name string // Name set by user
|
|
|
|
Driver string // Volume driver to use
|
|
|
|
Type mounttypes.Type `json:",omitempty"` // Type of mount to use, see `Type<foo>` definitions
|
|
|
|
Volume Volume `json:"-"`
|
2015-09-09 22:23:06 -04:00
|
|
|
|
|
|
|
// Note Mode is not used on Windows
|
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 14:25:35 -04:00
|
|
|
Mode string `json:"Relabel,omitempty"` // Originally field was `Relabel`"
|
2015-10-23 16:57:57 -04:00
|
|
|
|
|
|
|
// Note Propagation is not used on Windows
|
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 14:25:35 -04:00
|
|
|
Propagation mounttypes.Propagation `json:",omitempty"` // Mount propagation string
|
2016-03-14 23:31:42 -04:00
|
|
|
|
|
|
|
// Specifies if data should be copied from the container before the first mount
|
|
|
|
// Use a pointer here so we can tell if the user set this value explicitly
|
|
|
|
// This allows us to error out when the user explicitly enabled copy but we can't copy due to the volume being populated
|
|
|
|
CopyData bool `json:"-"`
|
2016-03-07 21:41:44 -05:00
|
|
|
// ID is the opaque ID used to pass to the volume driver.
|
|
|
|
// This should be set by calls to `Mount` and unset by calls to `Unmount`
|
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 14:25:35 -04:00
|
|
|
ID string `json:",omitempty"`
|
|
|
|
Spec mounttypes.Mount
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Setup sets up a mount point by either mounting the volume if it is
|
|
|
|
// configured, or creating the source directory if supplied.
|
2016-08-23 04:33:38 -04:00
|
|
|
func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (string, error) {
|
2015-09-09 22:23:06 -04:00
|
|
|
if m.Volume != nil {
|
2016-03-07 21:41:44 -05:00
|
|
|
if m.ID == "" {
|
|
|
|
m.ID = stringid.GenerateNonCryptoID()
|
|
|
|
}
|
2016-09-23 10:38:19 -04:00
|
|
|
path, err := m.Volume.Mount(m.ID)
|
|
|
|
return path, errors.Wrapf(err, "error while mounting volume '%s'", m.Source)
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
2016-04-16 11:21:17 -04:00
|
|
|
if len(m.Source) == 0 {
|
|
|
|
return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined")
|
|
|
|
}
|
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 14:25:35 -04:00
|
|
|
// system.MkdirAll() produces an error if m.Source exists and is a file (not a directory),
|
|
|
|
if m.Type == mounttypes.TypeBind {
|
|
|
|
// idtools.MkdirAllNewAs() produces an error if m.Source exists and is a file (not a directory)
|
|
|
|
// also, makes sure that if the directory is created, the correct remapped rootUID/rootGID will own it
|
|
|
|
if err := idtools.MkdirAllNewAs(m.Source, 0755, rootUID, rootGID); err != nil {
|
|
|
|
if perr, ok := err.(*os.PathError); ok {
|
|
|
|
if perr.Err != syscall.ENOTDIR {
|
2016-09-23 10:38:19 -04:00
|
|
|
return "", errors.Wrapf(err, "error while creating mount source path '%s'", m.Source)
|
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 14:25:35 -04:00
|
|
|
}
|
2016-05-26 14:39:46 -04:00
|
|
|
}
|
2016-04-16 11:21:17 -04:00
|
|
|
}
|
2016-05-26 14:39:46 -04:00
|
|
|
}
|
|
|
|
if label.RelabelNeeded(m.Mode) {
|
|
|
|
if err := label.Relabel(m.Source, mountLabel, label.IsShared(m.Mode)); err != nil {
|
2016-09-23 10:38:19 -04:00
|
|
|
return "", errors.Wrapf(err, "error setting label on mount source '%s'", m.Source)
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
|
|
|
}
|
2016-04-16 11:21:17 -04:00
|
|
|
return m.Source, nil
|
2015-07-12 04:33:30 -04:00
|
|
|
}
|
|
|
|
|
2015-09-09 22:23:06 -04:00
|
|
|
// Path returns the path of a volume in a mount point.
|
|
|
|
func (m *MountPoint) Path() string {
|
|
|
|
if m.Volume != nil {
|
|
|
|
return m.Volume.Path()
|
|
|
|
}
|
|
|
|
return m.Source
|
2015-07-12 04:33:30 -04:00
|
|
|
}
|
|
|
|
|
2016-03-09 11:17:57 -05:00
|
|
|
// ParseVolumesFrom ensures that the supplied volumes-from is valid.
|
2015-09-09 22:23:06 -04:00
|
|
|
func ParseVolumesFrom(spec string) (string, string, error) {
|
|
|
|
if len(spec) == 0 {
|
2016-07-28 06:31:16 -04:00
|
|
|
return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
specParts := strings.SplitN(spec, ":", 2)
|
|
|
|
id := specParts[0]
|
|
|
|
mode := "rw"
|
|
|
|
|
|
|
|
if len(specParts) == 2 {
|
|
|
|
mode = specParts[1]
|
|
|
|
if !ValidMountMode(mode) {
|
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 10:53:35 -05:00
|
|
|
return "", "", errInvalidMode(mode)
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
2015-10-23 16:57:57 -04:00
|
|
|
// For now don't allow propagation properties while importing
|
|
|
|
// volumes from data container. These volumes will inherit
|
|
|
|
// the same propagation property as of the original volume
|
|
|
|
// in data container. This probably can be relaxed in future.
|
|
|
|
if HasPropagation(mode) {
|
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 10:53:35 -05:00
|
|
|
return "", "", errInvalidMode(mode)
|
2015-10-23 16:57:57 -04:00
|
|
|
}
|
2016-03-14 23:31:42 -04:00
|
|
|
// Do not allow copy modes on volumes-from
|
|
|
|
if _, isSet := getCopyMode(mode); isSet {
|
|
|
|
return "", "", errInvalidMode(mode)
|
|
|
|
}
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
|
|
|
return id, mode, nil
|
|
|
|
}
|
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 10:53:35 -05:00
|
|
|
|
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 14:25:35 -04:00
|
|
|
// ParseMountRaw parses a raw volume spec (e.g. `-v /foo:/bar:shared`) into a
|
|
|
|
// structured spec. Once the raw spec is parsed it relies on `ParseMountSpec` to
|
|
|
|
// validate the spec and create a MountPoint
|
|
|
|
func ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
|
|
|
|
arr, err := splitRawSpec(convertSlash(raw))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var spec mounttypes.Mount
|
|
|
|
var mode string
|
|
|
|
switch len(arr) {
|
|
|
|
case 1:
|
|
|
|
// Just a destination path in the container
|
|
|
|
spec.Target = arr[0]
|
|
|
|
case 2:
|
|
|
|
if ValidMountMode(arr[1]) {
|
|
|
|
// Destination + Mode is not a valid volume - volumes
|
|
|
|
// cannot include a mode. eg /foo:rw
|
|
|
|
return nil, errInvalidSpec(raw)
|
|
|
|
}
|
|
|
|
// Host Source Path or Name + Destination
|
|
|
|
spec.Source = arr[0]
|
|
|
|
spec.Target = arr[1]
|
|
|
|
case 3:
|
|
|
|
// HostSourcePath+DestinationPath+Mode
|
|
|
|
spec.Source = arr[0]
|
|
|
|
spec.Target = arr[1]
|
|
|
|
mode = arr[2]
|
|
|
|
default:
|
|
|
|
return nil, errInvalidSpec(raw)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !ValidMountMode(mode) {
|
|
|
|
return nil, errInvalidMode(mode)
|
|
|
|
}
|
|
|
|
|
|
|
|
if filepath.IsAbs(spec.Source) {
|
|
|
|
spec.Type = mounttypes.TypeBind
|
|
|
|
} else {
|
|
|
|
spec.Type = mounttypes.TypeVolume
|
|
|
|
}
|
|
|
|
|
|
|
|
spec.ReadOnly = !ReadWrite(mode)
|
|
|
|
|
|
|
|
// cannot assume that if a volume driver is passed in that we should set it
|
|
|
|
if volumeDriver != "" && spec.Type == mounttypes.TypeVolume {
|
|
|
|
spec.VolumeOptions = &mounttypes.VolumeOptions{
|
|
|
|
DriverConfig: &mounttypes.Driver{Name: volumeDriver},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if copyData, isSet := getCopyMode(mode); isSet {
|
|
|
|
if spec.VolumeOptions == nil {
|
|
|
|
spec.VolumeOptions = &mounttypes.VolumeOptions{}
|
|
|
|
}
|
|
|
|
spec.VolumeOptions.NoCopy = !copyData
|
|
|
|
}
|
|
|
|
if HasPropagation(mode) {
|
|
|
|
spec.BindOptions = &mounttypes.BindOptions{
|
|
|
|
Propagation: GetPropagation(mode),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
mp, err := ParseMountSpec(spec, platformRawValidationOpts...)
|
|
|
|
if mp != nil {
|
|
|
|
mp.Mode = mode
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
|
|
|
|
}
|
|
|
|
return mp, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseMountSpec reads a mount config, validates it, and configures a mountpoint from it.
|
|
|
|
func ParseMountSpec(cfg mounttypes.Mount, options ...func(*validateOpts)) (*MountPoint, error) {
|
|
|
|
if err := validateMountConfig(&cfg, options...); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
mp := &MountPoint{
|
|
|
|
RW: !cfg.ReadOnly,
|
|
|
|
Destination: clean(convertSlash(cfg.Target)),
|
|
|
|
Type: cfg.Type,
|
|
|
|
Spec: cfg,
|
|
|
|
}
|
|
|
|
|
|
|
|
switch cfg.Type {
|
|
|
|
case mounttypes.TypeVolume:
|
|
|
|
if cfg.Source == "" {
|
|
|
|
mp.Name = stringid.GenerateNonCryptoID()
|
|
|
|
} else {
|
|
|
|
mp.Name = cfg.Source
|
|
|
|
}
|
|
|
|
mp.CopyData = DefaultCopyMode
|
|
|
|
|
|
|
|
mp.Driver = DefaultDriverName
|
|
|
|
if cfg.VolumeOptions != nil {
|
|
|
|
if cfg.VolumeOptions.DriverConfig != nil {
|
|
|
|
mp.Driver = cfg.VolumeOptions.DriverConfig.Name
|
|
|
|
}
|
|
|
|
if cfg.VolumeOptions.NoCopy {
|
|
|
|
mp.CopyData = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case mounttypes.TypeBind:
|
|
|
|
mp.Source = clean(convertSlash(cfg.Source))
|
|
|
|
if cfg.BindOptions != nil {
|
|
|
|
if len(cfg.BindOptions.Propagation) > 0 {
|
|
|
|
mp.Propagation = cfg.BindOptions.Propagation
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return mp, nil
|
|
|
|
}
|
|
|
|
|
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 10:53:35 -05:00
|
|
|
func errInvalidMode(mode string) error {
|
|
|
|
return fmt.Errorf("invalid mode: %v", mode)
|
|
|
|
}
|
|
|
|
|
|
|
|
func errInvalidSpec(spec string) error {
|
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 14:25:35 -04:00
|
|
|
return fmt.Errorf("invalid volume specification: '%s'", spec)
|
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 10:53:35 -05:00
|
|
|
}
|